xref: /freebsd/sys/dev/bhnd/bhndb/bhndb.c (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
1 /*-
2  * Copyright (c) 2015-2016 Landon Fuller <landon@landonf.org>
3  * Copyright (c) 2017 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Landon Fuller
7  * under sponsorship from the FreeBSD Foundation.
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  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
17  *    redistribution must be conditioned upon including a substantially
18  *    similar Disclaimer requirement for further binary redistribution.
19  *
20  * NO WARRANTY
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
24  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
25  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
26  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
29  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31  * THE POSSIBILITY OF SUCH DAMAGES.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 /*
38  * Abstract BHND Bridge Device Driver
39  *
40  * Provides generic support for bridging from a parent bus (such as PCI) to
41  * a BHND-compatible bus (e.g. bcma or siba).
42  */
43 
44 #include <sys/param.h>
45 #include <sys/kernel.h>
46 #include <sys/bus.h>
47 #include <sys/module.h>
48 #include <sys/sbuf.h>
49 #include <sys/systm.h>
50 
51 #include <machine/bus.h>
52 #include <sys/rman.h>
53 #include <machine/resource.h>
54 
55 #include <dev/bhnd/bhndvar.h>
56 #include <dev/bhnd/bhndreg.h>
57 
58 #include <dev/bhnd/bhnd_erom.h>
59 
60 #include <dev/bhnd/cores/chipc/chipcreg.h>
61 #include <dev/bhnd/nvram/bhnd_nvram.h>
62 
63 #include "bhnd_chipc_if.h"
64 #include "bhnd_nvram_if.h"
65 
66 #include "bhndbvar.h"
67 #include "bhndb_bus_if.h"
68 #include "bhndb_hwdata.h"
69 #include "bhndb_private.h"
70 
71 /* Debugging flags */
72 static u_long bhndb_debug = 0;
73 TUNABLE_ULONG("hw.bhndb.debug", &bhndb_debug);
74 
75 enum {
76 	BHNDB_DEBUG_PRIO = 1 << 0,
77 };
78 
79 #define	BHNDB_DEBUG(_type)	(BHNDB_DEBUG_ ## _type & bhndb_debug)
80 
81 static bool			 bhndb_hw_matches(struct bhndb_softc *sc,
82 				     struct bhnd_core_info *cores, u_int ncores,
83 				     const struct bhndb_hw *hw);
84 
85 static int			 bhndb_init_region_cfg(struct bhndb_softc *sc,
86 				     bhnd_erom_t *erom,
87 				     struct bhndb_resources *r,
88 				     struct bhnd_core_info *cores, u_int ncores,
89 				     const struct bhndb_hw_priority *table);
90 
91 static int			 bhndb_find_hwspec(struct bhndb_softc *sc,
92 				     struct bhnd_core_info *cores, u_int ncores,
93 				     const struct bhndb_hw **hw);
94 
95 bhndb_addrspace			 bhndb_get_addrspace(struct bhndb_softc *sc,
96 				     device_t child);
97 
98 static struct rman		*bhndb_get_rman(struct bhndb_softc *sc,
99 				     device_t child, int type);
100 
101 static int			 bhndb_init_child_resource(struct resource *r,
102 				     struct resource *parent,
103 				     bhnd_size_t offset,
104 				     bhnd_size_t size);
105 
106 static int			 bhndb_activate_static_region(
107 				     struct bhndb_softc *sc,
108 				     struct bhndb_region *region,
109 				     device_t child, int type, int rid,
110 				     struct resource *r);
111 
112 static int			 bhndb_try_activate_resource(
113 				     struct bhndb_softc *sc, device_t child,
114 				     int type, int rid, struct resource *r,
115 				     bool *indirect);
116 
117 static inline struct bhndb_dw_alloc *bhndb_io_resource(struct bhndb_softc *sc,
118 					bus_addr_t addr, bus_size_t size,
119 					bus_size_t *offset, bool *stolen,
120 					bus_addr_t *restore);
121 
122 /**
123  * Default bhndb(4) implementation of DEVICE_PROBE().
124  *
125  * This function provides the default bhndb implementation of DEVICE_PROBE(),
126  * and is compatible with bhndb(4) bridges attached via bhndb_attach_bridge().
127  */
128 int
129 bhndb_generic_probe(device_t dev)
130 {
131 	return (BUS_PROBE_NOWILDCARD);
132 }
133 
134 static void
135 bhndb_probe_nomatch(device_t dev, device_t child)
136 {
137 	const char *name;
138 
139 	name = device_get_name(child);
140 	if (name == NULL)
141 		name = "unknown device";
142 
143 	device_printf(dev, "<%s> (no driver attached)\n", name);
144 }
145 
146 static int
147 bhndb_print_child(device_t dev, device_t child)
148 {
149 	struct bhndb_softc	*sc;
150 	struct resource_list	*rl;
151 	int			 retval = 0;
152 
153 	sc = device_get_softc(dev);
154 
155 	retval += bus_print_child_header(dev, child);
156 
157 	rl = BUS_GET_RESOURCE_LIST(dev, child);
158 	if (rl != NULL) {
159 		retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY,
160 		    "%#jx");
161 		retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ,
162 		    "%jd");
163 	}
164 
165 	retval += bus_print_child_domain(dev, child);
166 	retval += bus_print_child_footer(dev, child);
167 
168 	return (retval);
169 }
170 
171 static int
172 bhndb_child_location(device_t dev, device_t child, struct sbuf *sb)
173 {
174 	struct bhndb_softc *sc;
175 
176 	sc = device_get_softc(dev);
177 
178 	sbuf_printf(sb, "base=0x%llx",
179 	    (unsigned long long) sc->chipid.enum_addr);
180 	return (0);
181 }
182 
183 /**
184  * Return true if @p cores matches the @p hw specification.
185  *
186  * @param sc BHNDB device state.
187  * @param cores A device table to match against.
188  * @param ncores The number of cores in @p cores.
189  * @param hw The hardware description to be matched against.
190  */
191 static bool
192 bhndb_hw_matches(struct bhndb_softc *sc, struct bhnd_core_info *cores,
193     u_int ncores, const struct bhndb_hw *hw)
194 {
195 	for (u_int i = 0; i < hw->num_hw_reqs; i++) {
196 		const struct bhnd_core_match	*match;
197 		bool				 found;
198 
199 		match =  &hw->hw_reqs[i];
200 		found = false;
201 
202 		for (u_int d = 0; d < ncores; d++) {
203 			struct bhnd_core_info *core = &cores[d];
204 
205 			if (BHNDB_IS_CORE_DISABLED(sc->dev, sc->bus_dev, core))
206 				continue;
207 
208 			if (!bhnd_core_matches(core, match))
209 				continue;
210 
211 			found = true;
212 			break;
213 		}
214 
215 		if (!found)
216 			return (false);
217 	}
218 
219 	return (true);
220 }
221 
222 /**
223  * Initialize the region maps and priority configuration in @p br using
224  * the priority @p table and the set of cores enumerated by @p erom.
225  *
226  * @param sc The bhndb device state.
227  * @param br The resource state to be configured.
228  * @param erom EROM parser used to enumerate @p cores.
229  * @param cores All cores enumerated on the bridged bhnd bus.
230  * @param ncores The length of @p cores.
231  * @param table Hardware priority table to be used to determine the relative
232  * priorities of per-core port resources.
233  */
234 static int
235 bhndb_init_region_cfg(struct bhndb_softc *sc, bhnd_erom_t *erom,
236     struct bhndb_resources *br, struct bhnd_core_info *cores, u_int ncores,
237     const struct bhndb_hw_priority *table)
238 {
239 	const struct bhndb_hw_priority	*hp;
240 	bhnd_addr_t			 addr;
241 	bhnd_size_t			 size;
242 	size_t				 prio_low, prio_default, prio_high;
243 	int				 error;
244 
245 	/* The number of port regions per priority band that must be accessible
246 	 * via dynamic register windows */
247 	prio_low = 0;
248 	prio_default = 0;
249 	prio_high = 0;
250 
251 	/*
252 	 * Register bridge regions covering all statically mapped ports.
253 	 */
254 	for (u_int i = 0; i < ncores; i++) {
255 		const struct bhndb_regwin	*regw;
256 		struct bhnd_core_info		*core;
257 		struct bhnd_core_match		 md;
258 
259 		core = &cores[i];
260 		md = bhnd_core_get_match_desc(core);
261 
262 		for (regw = br->cfg->register_windows;
263 		    regw->win_type != BHNDB_REGWIN_T_INVALID; regw++)
264 		{
265 			const struct bhndb_port_priority	*pp;
266 			uint32_t				 alloc_flags;
267 
268 			/* Only core windows are supported */
269 			if (regw->win_type != BHNDB_REGWIN_T_CORE)
270 				continue;
271 
272 			/* Skip non-matching cores. */
273 			if (!bhndb_regwin_match_core(regw, core))
274 				continue;
275 
276 			/* Fetch the base address of the mapped port */
277 			error = bhnd_erom_lookup_core_addr(erom, &md,
278 			    regw->d.core.port_type,
279 			    regw->d.core.port,
280 			    regw->d.core.region,
281 			    NULL,
282 			    &addr,
283 			    &size);
284 			if (error) {
285 				/* Skip non-applicable register windows */
286 				if (error == ENOENT)
287 					continue;
288 
289 				return (error);
290 			}
291 
292 			/*
293 			 * Apply the register window's region offset, if any.
294 			 */
295 			if (regw->d.core.offset > size) {
296 				device_printf(sc->dev, "invalid register "
297 				    "window offset %#jx for region %#jx+%#jx\n",
298 				    regw->d.core.offset, addr, size);
299 				return (EINVAL);
300 			}
301 
302 			addr += regw->d.core.offset;
303 
304 			/*
305 			 * Always defer to the register window's size.
306 			 *
307 			 * If the port size is smaller than the window size,
308 			 * this ensures that we fully utilize register windows
309 			 * larger than the referenced port.
310 			 *
311 			 * If the port size is larger than the window size, this
312 			 * ensures that we do not directly map the allocations
313 			 * within the region to a too-small window.
314 			 */
315 			size = regw->win_size;
316 
317 			/* Fetch allocation flags from the corresponding port
318 			 * priority entry, if any */
319 			pp = bhndb_hw_priorty_find_port(table, core,
320 			    regw->d.core.port_type, regw->d.core.port,
321 			    regw->d.core.region);
322 			if (pp != NULL) {
323 				alloc_flags = pp->alloc_flags;
324 			} else {
325 				alloc_flags = 0;
326 			}
327 
328 			/*
329 			 * Add to the bus region list.
330 			 *
331 			 * The window priority for a statically mapped region is
332 			 * always HIGH.
333 			 */
334 			error = bhndb_add_resource_region(br, addr, size,
335 			    BHNDB_PRIORITY_HIGH, alloc_flags, regw);
336 			if (error)
337 				return (error);
338 		}
339 	}
340 
341 	/*
342 	 * Perform priority accounting and register bridge regions for all
343 	 * ports defined in the priority table
344 	 */
345 	for (u_int i = 0; i < ncores; i++) {
346 		struct bhnd_core_info	*core;
347 		struct bhnd_core_match	 md;
348 
349 		core = &cores[i];
350 		md = bhnd_core_get_match_desc(core);
351 
352 		/*
353 		 * Skip priority accounting for cores that ...
354 		 */
355 
356 		/* ... do not require bridge resources */
357 		if (BHNDB_IS_CORE_DISABLED(sc->dev, sc->bus_dev, core))
358 			continue;
359 
360 		/* ... do not have a priority table entry */
361 		hp = bhndb_hw_priority_find_core(table, core);
362 		if (hp == NULL)
363 			continue;
364 
365 		/* ... are explicitly disabled in the priority table. */
366 		if (hp->priority == BHNDB_PRIORITY_NONE)
367 			continue;
368 
369 		/* Determine the number of dynamic windows required and
370 		 * register their bus_region entries. */
371 		for (u_int i = 0; i < hp->num_ports; i++) {
372 			const struct bhndb_port_priority *pp;
373 
374 			pp = &hp->ports[i];
375 
376 			/* Fetch the address+size of the mapped port. */
377 			error = bhnd_erom_lookup_core_addr(erom, &md,
378 			    pp->type, pp->port, pp->region,
379 			    NULL, &addr, &size);
380 			if (error) {
381 				/* Skip ports not defined on this device */
382 				if (error == ENOENT)
383 					continue;
384 
385 				return (error);
386 			}
387 
388 			/* Skip ports with an existing static mapping */
389 			if (bhndb_has_static_region_mapping(br, addr, size))
390 				continue;
391 
392 			/* Define a dynamic region for this port */
393 			error = bhndb_add_resource_region(br, addr, size,
394 			    pp->priority, pp->alloc_flags, NULL);
395 			if (error)
396 				return (error);
397 
398 			/* Update port mapping counts */
399 			switch (pp->priority) {
400 			case BHNDB_PRIORITY_NONE:
401 				break;
402 			case BHNDB_PRIORITY_LOW:
403 				prio_low++;
404 				break;
405 			case BHNDB_PRIORITY_DEFAULT:
406 				prio_default++;
407 				break;
408 			case BHNDB_PRIORITY_HIGH:
409 				prio_high++;
410 				break;
411 			}
412 		}
413 	}
414 
415 	/* Determine the minimum priority at which we'll allocate direct
416 	 * register windows from our dynamic pool */
417 	size_t prio_total = prio_low + prio_default + prio_high;
418 	if (prio_total <= br->dwa_count) {
419 		/* low+default+high priority regions get windows */
420 		br->min_prio = BHNDB_PRIORITY_LOW;
421 
422 	} else if (prio_default + prio_high <= br->dwa_count) {
423 		/* default+high priority regions get windows */
424 		br->min_prio = BHNDB_PRIORITY_DEFAULT;
425 
426 	} else {
427 		/* high priority regions get windows */
428 		br->min_prio = BHNDB_PRIORITY_HIGH;
429 	}
430 
431 	if (BHNDB_DEBUG(PRIO)) {
432 		struct bhndb_region	*region;
433 		const char		*direct_msg, *type_msg;
434 		bhndb_priority_t	 prio, prio_min;
435 		uint32_t		 flags;
436 
437 		prio_min = br->min_prio;
438 		device_printf(sc->dev, "min_prio: %d\n", prio_min);
439 
440 		STAILQ_FOREACH(region, &br->bus_regions, link) {
441 			prio = region->priority;
442 			flags = region->alloc_flags;
443 
444 			direct_msg = prio >= prio_min ? "direct" : "indirect";
445 			type_msg = region->static_regwin ? "static" : "dynamic";
446 
447 			device_printf(sc->dev, "region 0x%llx+0x%llx priority "
448 			    "%u %s/%s",
449 			    (unsigned long long) region->addr,
450 			    (unsigned long long) region->size,
451 			    region->priority,
452 			    direct_msg, type_msg);
453 
454 			if (flags & BHNDB_ALLOC_FULFILL_ON_OVERCOMMIT)
455 				printf(" [overcommit]\n");
456 			else
457 				printf("\n");
458 		}
459 	}
460 
461 	return (0);
462 }
463 
464 /**
465  * Find a hardware specification for @p dev.
466  *
467  * @param sc The bhndb device state.
468  * @param cores All cores enumerated on the bridged bhnd bus.
469  * @param ncores The length of @p cores.
470  * @param[out] hw On success, the matched hardware specification.
471  * with @p dev.
472  *
473  * @retval 0 success
474  * @retval non-zero if an error occurs fetching device info for comparison.
475  */
476 static int
477 bhndb_find_hwspec(struct bhndb_softc *sc, struct bhnd_core_info *cores,
478     u_int ncores, const struct bhndb_hw **hw)
479 {
480 	const struct bhndb_hw	*next, *hw_table;
481 
482 	/* Search for the first matching hardware config. */
483 	hw_table = BHNDB_BUS_GET_HARDWARE_TABLE(sc->parent_dev, sc->dev);
484 	for (next = hw_table; next->hw_reqs != NULL; next++) {
485 		if (!bhndb_hw_matches(sc, cores, ncores, next))
486 			continue;
487 
488 		/* Found */
489 		*hw = next;
490 		return (0);
491 	}
492 
493 	return (ENOENT);
494 }
495 
496 /**
497  * Helper function that must be called by subclass bhndb(4) drivers
498  * when implementing DEVICE_ATTACH() before calling any bhnd(4) or bhndb(4)
499  * APIs on the bridge device.
500  *
501  * This function will add a bridged bhnd(4) child device with a device order of
502  * BHND_PROBE_BUS. Any subclass bhndb(4) driver may use the BHND_PROBE_*
503  * priority bands to add additional devices that will be attached in
504  * their preferred order relative to the bridged bhnd(4) bus.
505  *
506  * @param dev		The bridge device to attach.
507  * @param cid		The bridged device's chip identification.
508  * @param cores		The bridged device's core table.
509  * @param ncores	The number of cores in @p cores.
510  * @param bridge_core	Core info for the bhnd(4) core serving as the host
511  *			bridge.
512  * @param erom_class	An erom parser class that may be used to parse
513  *			the bridged device's device enumeration table.
514  */
515 int
516 bhndb_attach(device_t dev, struct bhnd_chipid *cid,
517     struct bhnd_core_info *cores, u_int ncores,
518     struct bhnd_core_info *bridge_core, bhnd_erom_class_t *erom_class)
519 {
520 	struct bhndb_devinfo		*dinfo;
521 	struct bhndb_softc		*sc;
522 	const struct bhndb_hw		*hw;
523 	const struct bhndb_hwcfg	*hwcfg;
524 	const struct bhndb_hw_priority	*hwprio;
525 	struct bhnd_erom_io		*eio;
526 	bhnd_erom_t			*erom;
527 	int				 error;
528 
529 	sc = device_get_softc(dev);
530 	sc->dev = dev;
531 	sc->parent_dev = device_get_parent(dev);
532 	sc->bridge_core = *bridge_core;
533 	sc->chipid = *cid;
534 
535 	if ((error = bhnd_service_registry_init(&sc->services)))
536 		return (error);
537 
538 	BHNDB_LOCK_INIT(sc);
539 
540 	erom = NULL;
541 
542 	/* Find a matching bridge hardware configuration */
543 	if ((error = bhndb_find_hwspec(sc, cores, ncores, &hw))) {
544 		device_printf(sc->dev, "unable to identify device, "
545 		    " using generic bridge resource definitions\n");
546 
547 		hwcfg = BHNDB_BUS_GET_GENERIC_HWCFG(sc->parent_dev, dev);
548 		hw = NULL;
549 	} else {
550 		hwcfg = hw->cfg;
551 	}
552 
553 	if (hw != NULL && (bootverbose || BHNDB_DEBUG(PRIO))) {
554 		device_printf(sc->dev, "%s resource configuration\n", hw->name);
555 	}
556 
557 	/* Allocate bridge resource state using the discovered hardware
558 	 * configuration */
559 	sc->bus_res = bhndb_alloc_resources(sc->dev, sc->parent_dev, hwcfg);
560 	if (sc->bus_res == NULL) {
561 		device_printf(sc->dev, "failed to allocate bridge resource "
562 		    "state\n");
563 		error = ENOMEM;
564 		goto failed;
565 	}
566 
567 	/* Add our bridged bus device */
568 	sc->bus_dev = BUS_ADD_CHILD(dev, BHND_PROBE_BUS, "bhnd", -1);
569 	if (sc->bus_dev == NULL) {
570 		error = ENXIO;
571 		goto failed;
572 	}
573 
574 	dinfo = device_get_ivars(sc->bus_dev);
575 	dinfo->addrspace = BHNDB_ADDRSPACE_BRIDGED;
576 
577 	/* We can now use bhndb to perform bridging of SYS_RES_MEMORY resources;
578 	 * we use this to instantiate an erom parser instance */
579 	eio = bhnd_erom_iores_new(sc->bus_dev, 0);
580 	if ((erom = bhnd_erom_alloc(erom_class, cid, eio)) == NULL) {
581 		bhnd_erom_io_fini(eio);
582 		error = ENXIO;
583 		goto failed;
584 	}
585 
586 	/* Populate our resource priority configuration */
587 	hwprio = BHNDB_BUS_GET_HARDWARE_PRIO(sc->parent_dev, sc->dev);
588 	error = bhndb_init_region_cfg(sc, erom, sc->bus_res, cores, ncores,
589 	    hwprio);
590 	if (error) {
591 		device_printf(sc->dev, "failed to initialize resource "
592 		    "priority configuration: %d\n", error);
593 		goto failed;
594 	}
595 
596 	/* Free our erom instance */
597 	bhnd_erom_free(erom);
598 	erom = NULL;
599 
600 	return (0);
601 
602 failed:
603 	BHNDB_LOCK_DESTROY(sc);
604 
605 	if (sc->bus_res != NULL)
606 		bhndb_free_resources(sc->bus_res);
607 
608 	if (erom != NULL)
609 		bhnd_erom_free(erom);
610 
611 	bhnd_service_registry_fini(&sc->services);
612 
613 	return (error);
614 }
615 
616 /**
617  * Default bhndb(4) implementation of DEVICE_DETACH().
618  *
619  * This function detaches any child devices, and if successful, releases all
620  * resources held by the bridge device.
621  */
622 int
623 bhndb_generic_detach(device_t dev)
624 {
625 	struct bhndb_softc	*sc;
626 	int			 error;
627 
628 	sc = device_get_softc(dev);
629 
630 	/* Detach children */
631 	if ((error = bus_generic_detach(dev)))
632 		return (error);
633 
634 	/* Delete children */
635 	if ((error = device_delete_children(dev)))
636 		return (error);
637 
638 	/* Clean up our service registry */
639 	if ((error = bhnd_service_registry_fini(&sc->services)))
640 		return (error);
641 
642 	/* Clean up our driver state. */
643 	bhndb_free_resources(sc->bus_res);
644 
645 	BHNDB_LOCK_DESTROY(sc);
646 
647 	return (0);
648 }
649 
650 /**
651  * Default bhndb(4) implementation of DEVICE_SUSPEND().
652  *
653  * This function calls bus_generic_suspend() (or implements equivalent
654  * behavior).
655  */
656 int
657 bhndb_generic_suspend(device_t dev)
658 {
659 	return (bus_generic_suspend(dev));
660 }
661 
662 /**
663  * Default bhndb(4) implementation of DEVICE_RESUME().
664  *
665  * This function calls bus_generic_resume() (or implements equivalent
666  * behavior).
667  */
668 int
669 bhndb_generic_resume(device_t dev)
670 {
671 	struct bhndb_softc	*sc;
672 	struct bhndb_resources	*bus_res;
673 	struct bhndb_dw_alloc	*dwa;
674 	int			 error;
675 
676 	sc = device_get_softc(dev);
677 	bus_res = sc->bus_res;
678 
679 	/* Guarantee that all in-use dynamic register windows are mapped to
680 	 * their previously configured target address. */
681 	BHNDB_LOCK(sc);
682 	error = 0;
683 	for (size_t i = 0; i < bus_res->dwa_count; i++) {
684 		dwa = &bus_res->dw_alloc[i];
685 
686 		/* Skip regions that were not previously used */
687 		if (bhndb_dw_is_free(bus_res, dwa) && dwa->target == 0x0)
688 			continue;
689 
690 		/* Otherwise, ensure the register window is correct before
691 		 * any children attempt MMIO */
692 		error = BHNDB_SET_WINDOW_ADDR(dev, dwa->win, dwa->target);
693 		if (error)
694 			break;
695 	}
696 	BHNDB_UNLOCK(sc);
697 
698 	/* Error restoring hardware state; children cannot be safely resumed */
699 	if (error) {
700 		device_printf(dev, "Unable to restore hardware configuration; "
701 		    "cannot resume: %d\n", error);
702 		return (error);
703 	}
704 
705 	return (bus_generic_resume(dev));
706 }
707 
708 /**
709  * Default implementation of BHNDB_SUSPEND_RESOURCE.
710  */
711 static void
712 bhndb_suspend_resource(device_t dev, device_t child, int type,
713     struct resource *r)
714 {
715 	struct bhndb_softc	*sc;
716 	struct bhndb_dw_alloc	*dwa;
717 
718 	sc = device_get_softc(dev);
719 
720 	/* Non-MMIO resources (e.g. IRQs) are handled solely by our parent */
721 	if (type != SYS_RES_MEMORY)
722 		return;
723 
724 	BHNDB_LOCK(sc);
725 	dwa = bhndb_dw_find_resource(sc->bus_res, r);
726 	if (dwa == NULL) {
727 		BHNDB_UNLOCK(sc);
728 		return;
729 	}
730 
731 	if (BHNDB_DEBUG(PRIO))
732 		device_printf(child, "suspend resource type=%d 0x%jx+0x%jx\n",
733 		    type, rman_get_start(r), rman_get_size(r));
734 
735 	/* Release the resource's window reference */
736 	bhndb_dw_release(sc->bus_res, dwa, r);
737 	BHNDB_UNLOCK(sc);
738 }
739 
740 /**
741  * Default implementation of BHNDB_RESUME_RESOURCE.
742  */
743 static int
744 bhndb_resume_resource(device_t dev, device_t child, int type,
745     struct resource *r)
746 {
747 	struct bhndb_softc	*sc;
748 
749 	sc = device_get_softc(dev);
750 
751 	/* Non-MMIO resources (e.g. IRQs) are handled solely by our parent */
752 	if (type != SYS_RES_MEMORY)
753 		return (0);
754 
755 	/* Inactive resources don't require reallocation of bridge resources */
756 	if (!(rman_get_flags(r) & RF_ACTIVE))
757 		return (0);
758 
759 	if (BHNDB_DEBUG(PRIO))
760 		device_printf(child, "resume resource type=%d 0x%jx+0x%jx\n",
761 		    type, rman_get_start(r), rman_get_size(r));
762 
763 	return (bhndb_try_activate_resource(sc, rman_get_device(r), type,
764 	    rman_get_rid(r), r, NULL));
765 }
766 
767 /**
768  * Default bhndb(4) implementation of BUS_READ_IVAR().
769  */
770 static int
771 bhndb_read_ivar(device_t dev, device_t child, int index,
772     uintptr_t *result)
773 {
774 	return (ENOENT);
775 }
776 
777 /**
778  * Default bhndb(4) implementation of BUS_WRITE_IVAR().
779  */
780 static int
781 bhndb_write_ivar(device_t dev, device_t child, int index,
782     uintptr_t value)
783 {
784 	return (ENOENT);
785 }
786 
787 /**
788  * Return the address space for the given @p child device.
789  */
790 bhndb_addrspace
791 bhndb_get_addrspace(struct bhndb_softc *sc, device_t child)
792 {
793 	struct bhndb_devinfo	*dinfo;
794 	device_t		 imd_dev;
795 
796 	/* Find the directly attached parent of the requesting device */
797 	imd_dev = child;
798 	while (imd_dev != NULL && device_get_parent(imd_dev) != sc->dev)
799 		imd_dev = device_get_parent(imd_dev);
800 
801 	if (imd_dev == NULL)
802 		panic("bhndb address space request for non-child device %s\n",
803 		     device_get_nameunit(child));
804 
805 	dinfo = device_get_ivars(imd_dev);
806 	return (dinfo->addrspace);
807 }
808 
809 /**
810  * Return the rman instance for a given resource @p type, if any.
811  *
812  * @param sc The bhndb device state.
813  * @param child The requesting child.
814  * @param type The resource type (e.g. SYS_RES_MEMORY, SYS_RES_IRQ, ...)
815  */
816 static struct rman *
817 bhndb_get_rman(struct bhndb_softc *sc, device_t child, int type)
818 {
819 	switch (bhndb_get_addrspace(sc, child)) {
820 	case BHNDB_ADDRSPACE_NATIVE:
821 		switch (type) {
822 		case SYS_RES_MEMORY:
823 			return (&sc->bus_res->ht_mem_rman);
824 		case SYS_RES_IRQ:
825 			return (NULL);
826 		default:
827 			return (NULL);
828 		}
829 
830 	case BHNDB_ADDRSPACE_BRIDGED:
831 		switch (type) {
832 		case SYS_RES_MEMORY:
833 			return (&sc->bus_res->br_mem_rman);
834 		case SYS_RES_IRQ:
835 			return (&sc->bus_res->br_irq_rman);
836 		default:
837 			return (NULL);
838 		}
839 	}
840 
841 	/* Quieten gcc */
842 	return (NULL);
843 }
844 
845 /**
846  * Default implementation of BUS_ADD_CHILD()
847  */
848 static device_t
849 bhndb_add_child(device_t dev, u_int order, const char *name, int unit)
850 {
851 	struct bhndb_devinfo	*dinfo;
852 	device_t		 child;
853 
854 	child = device_add_child_ordered(dev, order, name, unit);
855 	if (child == NULL)
856 		return (NULL);
857 
858 	dinfo = malloc(sizeof(struct bhndb_devinfo), M_BHND, M_NOWAIT);
859 	if (dinfo == NULL) {
860 		device_delete_child(dev, child);
861 		return (NULL);
862 	}
863 
864 	dinfo->addrspace = BHNDB_ADDRSPACE_NATIVE;
865 	resource_list_init(&dinfo->resources);
866 
867 	device_set_ivars(child, dinfo);
868 
869 	return (child);
870 }
871 
872 /**
873  * Default implementation of BUS_CHILD_DELETED().
874  */
875 static void
876 bhndb_child_deleted(device_t dev, device_t child)
877 {
878 	struct bhndb_devinfo *dinfo = device_get_ivars(child);
879 	if (dinfo != NULL) {
880 		resource_list_free(&dinfo->resources);
881 		free(dinfo, M_BHND);
882 	}
883 
884 	device_set_ivars(child, NULL);
885 }
886 
887 /**
888  * Default implementation of BHNDB_GET_CHIPID().
889  */
890 static const struct bhnd_chipid *
891 bhndb_get_chipid(device_t dev, device_t child)
892 {
893 	struct bhndb_softc *sc = device_get_softc(dev);
894 	return (&sc->chipid);
895 }
896 
897 /**
898  * Default implementation of BHNDB_IS_CORE_DISABLED().
899  */
900 static bool
901 bhndb_is_core_disabled(device_t dev, device_t child,
902     struct bhnd_core_info *core)
903 {
904 	struct bhndb_softc	*sc;
905 
906 	sc = device_get_softc(dev);
907 
908 	/* Try to defer to the bhndb bus parent */
909 	if (BHNDB_BUS_IS_CORE_DISABLED(sc->parent_dev, dev, core))
910 		return (true);
911 
912 	/* Otherwise, we treat bridge-capable cores as unpopulated if they're
913 	 * not the configured host bridge */
914 	if (BHND_DEVCLASS_SUPPORTS_HOSTB(bhnd_core_class(core)))
915 		return (!bhnd_cores_equal(core, &sc->bridge_core));
916 
917 	/* Assume the core is populated */
918 	return (false);
919 }
920 
921 /**
922  * Default bhndb(4) implementation of BHNDB_GET_HOSTB_CORE().
923  *
924  * This function uses a heuristic valid on all known PCI/PCIe/PCMCIA-bridged
925  * bhnd(4) devices.
926  */
927 static int
928 bhndb_get_hostb_core(device_t dev, device_t child, struct bhnd_core_info *core)
929 {
930 	struct bhndb_softc *sc = device_get_softc(dev);
931 
932 	*core = sc->bridge_core;
933 	return (0);
934 }
935 
936 /**
937  * Default bhndb(4) implementation of BHND_BUS_GET_SERVICE_REGISTRY().
938  */
939 static struct bhnd_service_registry *
940 bhndb_get_service_registry(device_t dev, device_t child)
941 {
942 	struct bhndb_softc *sc = device_get_softc(dev);
943 
944 	return (&sc->services);
945 }
946 
947 /**
948  * Default bhndb(4) implementation of BUS_ALLOC_RESOURCE().
949  */
950 static struct resource *
951 bhndb_alloc_resource(device_t dev, device_t child, int type,
952     int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
953 {
954 	struct bhndb_softc		*sc;
955 	struct resource_list_entry	*rle;
956 	struct resource			*rv;
957 	struct rman			*rm;
958 	int				 error;
959 	bool				 passthrough, isdefault;
960 
961 	sc = device_get_softc(dev);
962 	passthrough = (device_get_parent(child) != dev);
963 	isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
964 	rle = NULL;
965 
966 	/* Fetch the resource manager */
967 	rm = bhndb_get_rman(sc, child, type);
968 	if (rm == NULL) {
969 		/* Delegate to our parent device's bus; the requested
970 		 * resource type isn't handled locally. */
971 		return (BUS_ALLOC_RESOURCE(device_get_parent(sc->parent_dev),
972 		    child, type, rid,  start, end, count, flags));
973 	}
974 
975 	/* Populate defaults */
976 	if (!passthrough && isdefault) {
977 		/* Fetch the resource list entry. */
978 		rle = resource_list_find(BUS_GET_RESOURCE_LIST(dev, child),
979 		    type, *rid);
980 		if (rle == NULL) {
981 			device_printf(dev,
982 			    "default resource %#x type %d for child %s "
983 			    "not found\n", *rid, type,
984 			    device_get_nameunit(child));
985 
986 			return (NULL);
987 		}
988 
989 		if (rle->res != NULL) {
990 			device_printf(dev,
991 			    "resource entry %#x type %d for child %s is busy\n",
992 			    *rid, type, device_get_nameunit(child));
993 
994 			return (NULL);
995 		}
996 
997 		start = rle->start;
998 		end = rle->end;
999 		count = ulmax(count, rle->count);
1000 	}
1001 
1002 	/* Validate resource addresses */
1003 	if (start > end || count > ((end - start) + 1))
1004 		return (NULL);
1005 
1006 	/* Make our reservation */
1007 	rv = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1008 	    child);
1009 	if (rv == NULL)
1010 		return (NULL);
1011 
1012 	rman_set_rid(rv, *rid);
1013 
1014 	/* Activate */
1015 	if (flags & RF_ACTIVE) {
1016 		error = bus_activate_resource(child, type, *rid, rv);
1017 		if (error) {
1018 			device_printf(dev,
1019 			    "failed to activate entry %#x type %d for "
1020 				"child %s: %d\n",
1021 			     *rid, type, device_get_nameunit(child), error);
1022 
1023 			rman_release_resource(rv);
1024 
1025 			return (NULL);
1026 		}
1027 	}
1028 
1029 	/* Update child's resource list entry */
1030 	if (rle != NULL) {
1031 		rle->res = rv;
1032 		rle->start = rman_get_start(rv);
1033 		rle->end = rman_get_end(rv);
1034 		rle->count = rman_get_size(rv);
1035 	}
1036 
1037 	return (rv);
1038 }
1039 
1040 /**
1041  * Default bhndb(4) implementation of BUS_RELEASE_RESOURCE().
1042  */
1043 static int
1044 bhndb_release_resource(device_t dev, device_t child, int type, int rid,
1045     struct resource *r)
1046 {
1047 	struct bhndb_softc		*sc;
1048 	struct resource_list_entry	*rle;
1049 	bool				 passthrough;
1050 	int				 error;
1051 
1052 	sc = device_get_softc(dev);
1053 	passthrough = (device_get_parent(child) != dev);
1054 
1055 	/* Delegate to our parent device's bus if the requested resource type
1056 	 * isn't handled locally. */
1057 	if (bhndb_get_rman(sc, child, type) == NULL) {
1058 		return (BUS_RELEASE_RESOURCE(device_get_parent(sc->parent_dev),
1059 		    child, type, rid, r));
1060 	}
1061 
1062 	/* Deactivate resources */
1063 	if (rman_get_flags(r) & RF_ACTIVE) {
1064 		error = BUS_DEACTIVATE_RESOURCE(dev, child, type, rid, r);
1065 		if (error)
1066 			return (error);
1067 	}
1068 
1069 	if ((error = rman_release_resource(r)))
1070 		return (error);
1071 
1072 	if (!passthrough) {
1073 		/* Clean resource list entry */
1074 		rle = resource_list_find(BUS_GET_RESOURCE_LIST(dev, child),
1075 		    type, rid);
1076 		if (rle != NULL)
1077 			rle->res = NULL;
1078 	}
1079 
1080 	return (0);
1081 }
1082 
1083 /**
1084  * Default bhndb(4) implementation of BUS_ADJUST_RESOURCE().
1085  */
1086 static int
1087 bhndb_adjust_resource(device_t dev, device_t child, int type,
1088     struct resource *r, rman_res_t start, rman_res_t end)
1089 {
1090 	struct bhndb_softc		*sc;
1091 	struct rman			*rm;
1092 	rman_res_t			 mstart, mend;
1093 	int				 error;
1094 
1095 	sc = device_get_softc(dev);
1096 	error = 0;
1097 
1098 	/* Delegate to our parent device's bus if the requested resource type
1099 	 * isn't handled locally. */
1100 	rm = bhndb_get_rman(sc, child, type);
1101 	if (rm == NULL) {
1102 		return (BUS_ADJUST_RESOURCE(device_get_parent(sc->parent_dev),
1103 		    child, type, r, start, end));
1104 	}
1105 
1106 	/* Verify basic constraints */
1107 	if (end <= start)
1108 		return (EINVAL);
1109 
1110 	if (!rman_is_region_manager(r, rm))
1111 		return (ENXIO);
1112 
1113 	BHNDB_LOCK(sc);
1114 
1115 	/* If not active, allow any range permitted by the resource manager */
1116 	if (!(rman_get_flags(r) & RF_ACTIVE))
1117 		goto done;
1118 
1119 	/* Otherwise, the range is limited by the bridged resource mapping */
1120 	error = bhndb_find_resource_limits(sc->bus_res, type, r, &mstart,
1121 	    &mend);
1122 	if (error)
1123 		goto done;
1124 
1125 	if (start < mstart || end > mend) {
1126 		error = EINVAL;
1127 		goto done;
1128 	}
1129 
1130 	/* Fall through */
1131 done:
1132 	if (!error)
1133 		error = rman_adjust_resource(r, start, end);
1134 
1135 	BHNDB_UNLOCK(sc);
1136 	return (error);
1137 }
1138 
1139 /**
1140  * Initialize child resource @p r with a virtual address, tag, and handle
1141  * copied from @p parent, adjusted to contain only the range defined by
1142  * @p offsize and @p size.
1143  *
1144  * @param r The register to be initialized.
1145  * @param parent The parent bus resource that fully contains the subregion.
1146  * @param offset The subregion offset within @p parent.
1147  * @param size The subregion size.
1148  * @p r.
1149  */
1150 static int
1151 bhndb_init_child_resource(struct resource *r,
1152     struct resource *parent, bhnd_size_t offset, bhnd_size_t size)
1153 {
1154 	bus_space_handle_t	bh, child_bh;
1155 	bus_space_tag_t		bt;
1156 	uintptr_t		vaddr;
1157 	int			error;
1158 
1159 	/* Fetch the parent resource's real bus values */
1160 	vaddr = (uintptr_t) rman_get_virtual(parent);
1161 	bt = rman_get_bustag(parent);
1162 	bh = rman_get_bushandle(parent);
1163 
1164 	/* Configure child resource with window-adjusted real bus values */
1165 	vaddr += offset;
1166 	error = bus_space_subregion(bt, bh, offset, size, &child_bh);
1167 	if (error)
1168 		return (error);
1169 
1170 	rman_set_virtual(r, (void *) vaddr);
1171 	rman_set_bustag(r, bt);
1172 	rman_set_bushandle(r, child_bh);
1173 
1174 	return (0);
1175 }
1176 
1177 /**
1178  * Attempt activation of a fixed register window mapping for @p child.
1179  *
1180  * @param sc BHNDB device state.
1181  * @param region The static region definition capable of mapping @p r.
1182  * @param child A child requesting resource activation.
1183  * @param type Resource type.
1184  * @param rid Resource identifier.
1185  * @param r Resource to be activated.
1186  *
1187  * @retval 0 if @p r was activated successfully
1188  * @retval ENOENT if no fixed register window was found.
1189  * @retval non-zero if @p r could not be activated.
1190  */
1191 static int
1192 bhndb_activate_static_region(struct bhndb_softc *sc,
1193     struct bhndb_region *region, device_t child, int type, int rid,
1194     struct resource *r)
1195 {
1196 	struct resource			*bridge_res;
1197 	const struct bhndb_regwin	*win;
1198 	bhnd_size_t			 parent_offset;
1199 	rman_res_t			 r_start, r_size;
1200 	int				 error;
1201 
1202 	win = region->static_regwin;
1203 
1204 	KASSERT(win != NULL && BHNDB_REGWIN_T_IS_STATIC(win->win_type),
1205 	    ("can't activate non-static region"));
1206 
1207 	r_start = rman_get_start(r);
1208 	r_size = rman_get_size(r);
1209 
1210 	/* Find the corresponding bridge resource */
1211 	bridge_res = bhndb_host_resource_for_regwin(sc->bus_res->res, win);
1212 	if (bridge_res == NULL)
1213 		return (ENXIO);
1214 
1215 	/* Calculate subregion offset within the parent resource */
1216 	parent_offset = r_start - region->addr;
1217 	parent_offset += win->win_offset;
1218 
1219 	/* Configure resource with its real bus values. */
1220 	error = bhndb_init_child_resource(r, bridge_res, parent_offset, r_size);
1221 	if (error)
1222 		return (error);
1223 
1224 	/* Mark active */
1225 	if ((error = rman_activate_resource(r)))
1226 		return (error);
1227 
1228 	return (0);
1229 }
1230 
1231 /**
1232  * Attempt to allocate/retain a dynamic register window for @p r, returning
1233  * the retained window.
1234  *
1235  * @param sc The bhndb driver state.
1236  * @param r The resource for which a window will be retained.
1237  */
1238 static struct bhndb_dw_alloc *
1239 bhndb_retain_dynamic_window(struct bhndb_softc *sc, struct resource *r)
1240 {
1241 	struct bhndb_dw_alloc	*dwa;
1242 	rman_res_t		 r_start, r_size;
1243 	int			 error;
1244 
1245 	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1246 
1247 	r_start = rman_get_start(r);
1248 	r_size = rman_get_size(r);
1249 
1250 	/* Look for an existing dynamic window we can reference */
1251 	dwa = bhndb_dw_find_mapping(sc->bus_res, r_start, r_size);
1252 	if (dwa != NULL) {
1253 		if (bhndb_dw_retain(sc->bus_res, dwa, r) == 0)
1254 			return (dwa);
1255 
1256 		return (NULL);
1257 	}
1258 
1259 	/* Otherwise, try to reserve a free window */
1260 	dwa = bhndb_dw_next_free(sc->bus_res);
1261 	if (dwa == NULL) {
1262 		/* No free windows */
1263 		return (NULL);
1264 	}
1265 
1266 	/* Window must be large enough to map the entire resource */
1267 	if (dwa->win->win_size < rman_get_size(r))
1268 		return (NULL);
1269 
1270 	/* Set the window target */
1271 	error = bhndb_dw_set_addr(sc->dev, sc->bus_res, dwa, rman_get_start(r),
1272 	    rman_get_size(r));
1273 	if (error) {
1274 		device_printf(sc->dev, "dynamic window initialization "
1275 			"for 0x%llx-0x%llx failed: %d\n",
1276 			(unsigned long long) r_start,
1277 			(unsigned long long) r_start + r_size - 1,
1278 			error);
1279 		return (NULL);
1280 	}
1281 
1282 	/* Add our reservation */
1283 	if (bhndb_dw_retain(sc->bus_res, dwa, r))
1284 		return (NULL);
1285 
1286 	return (dwa);
1287 }
1288 
1289 /**
1290  * Activate a resource using any viable static or dynamic register window.
1291  *
1292  * @param sc The bhndb driver state.
1293  * @param child The child holding ownership of @p r.
1294  * @param type The type of the resource to be activated.
1295  * @param rid The resource ID of @p r.
1296  * @param r The resource to be activated
1297  * @param[out] indirect On error and if not NULL, will be set to 'true' if
1298  * the caller should instead use an indirect resource mapping.
1299  *
1300  * @retval 0 success
1301  * @retval non-zero activation failed.
1302  */
1303 static int
1304 bhndb_try_activate_resource(struct bhndb_softc *sc, device_t child, int type,
1305     int rid, struct resource *r, bool *indirect)
1306 {
1307 	struct bhndb_region	*region;
1308 	struct bhndb_dw_alloc	*dwa;
1309 	bhndb_priority_t	 dw_priority;
1310 	rman_res_t		 r_start, r_size;
1311 	rman_res_t		 parent_offset;
1312 	int			 error;
1313 
1314 	BHNDB_LOCK_ASSERT(sc, MA_NOTOWNED);
1315 
1316 	if (indirect != NULL)
1317 		*indirect = false;
1318 
1319 	switch (type) {
1320 	case SYS_RES_IRQ:
1321 		/* IRQ resources are always directly mapped */
1322 		return (rman_activate_resource(r));
1323 
1324 	case SYS_RES_MEMORY:
1325 		/* Handled below */
1326 		break;
1327 
1328 	default:
1329 		device_printf(sc->dev, "unsupported resource type %d\n", type);
1330 		return (ENXIO);
1331 	}
1332 
1333 	/* Only MMIO resources can be mapped via register windows */
1334 	KASSERT(type == SYS_RES_MEMORY, ("invalid type: %d", type));
1335 
1336 	r_start = rman_get_start(r);
1337 	r_size = rman_get_size(r);
1338 
1339 	/* Activate native addrspace resources using the host address space */
1340 	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_NATIVE) {
1341 		struct resource *parent;
1342 
1343 		/* Find the bridge resource referenced by the child */
1344 		parent = bhndb_host_resource_for_range(sc->bus_res->res,
1345 		    type, r_start, r_size);
1346 		if (parent == NULL) {
1347 			device_printf(sc->dev, "host resource not found "
1348 			     "for 0x%llx-0x%llx\n",
1349 			     (unsigned long long) r_start,
1350 			     (unsigned long long) r_start + r_size - 1);
1351 			return (ENOENT);
1352 		}
1353 
1354 		/* Initialize child resource with the real bus values */
1355 		error = bhndb_init_child_resource(r, parent,
1356 		    r_start - rman_get_start(parent), r_size);
1357 		if (error)
1358 			return (error);
1359 
1360 		/* Try to activate child resource */
1361 		return (rman_activate_resource(r));
1362 	}
1363 
1364 	/* Default to low priority */
1365 	dw_priority = BHNDB_PRIORITY_LOW;
1366 
1367 	/* Look for a bus region matching the resource's address range */
1368 	region = bhndb_find_resource_region(sc->bus_res, r_start, r_size);
1369 	if (region != NULL)
1370 		dw_priority = region->priority;
1371 
1372 	/* Prefer static mappings over consuming a dynamic windows. */
1373 	if (region && region->static_regwin) {
1374 		error = bhndb_activate_static_region(sc, region, child, type,
1375 		    rid, r);
1376 		if (error)
1377 			device_printf(sc->dev, "static window allocation "
1378 			     "for 0x%llx-0x%llx failed\n",
1379 			     (unsigned long long) r_start,
1380 			     (unsigned long long) r_start + r_size - 1);
1381 		return (error);
1382 	}
1383 
1384 	/* A dynamic window will be required; is this resource high enough
1385 	 * priority to be reserved a dynamic window? */
1386 	if (dw_priority < sc->bus_res->min_prio) {
1387 		if (indirect)
1388 			*indirect = true;
1389 
1390 		return (ENOMEM);
1391 	}
1392 
1393 	/* Find and retain a usable window */
1394 	BHNDB_LOCK(sc); {
1395 		dwa = bhndb_retain_dynamic_window(sc, r);
1396 	} BHNDB_UNLOCK(sc);
1397 
1398 	if (dwa == NULL) {
1399 		if (indirect)
1400 			*indirect = true;
1401 		return (ENOMEM);
1402 	}
1403 
1404 	/* Configure resource with its real bus values. */
1405 	parent_offset = dwa->win->win_offset;
1406 	parent_offset += r_start - dwa->target;
1407 
1408 	error = bhndb_init_child_resource(r, dwa->parent_res, parent_offset,
1409 	    dwa->win->win_size);
1410 	if (error)
1411 		goto failed;
1412 
1413 	/* Mark active */
1414 	if ((error = rman_activate_resource(r)))
1415 		goto failed;
1416 
1417 	return (0);
1418 
1419 failed:
1420 	/* Release our region allocation. */
1421 	BHNDB_LOCK(sc);
1422 	bhndb_dw_release(sc->bus_res, dwa, r);
1423 	BHNDB_UNLOCK(sc);
1424 
1425 	return (error);
1426 }
1427 
1428 /**
1429  * Default bhndb(4) implementation of BUS_ACTIVATE_RESOURCE().
1430  */
1431 static int
1432 bhndb_activate_resource(device_t dev, device_t child, int type, int rid,
1433     struct resource *r)
1434 {
1435 	struct bhndb_softc *sc = device_get_softc(dev);
1436 
1437 	/* Delegate directly to our parent device's bus if the requested
1438 	 * resource type isn't handled locally. */
1439 	if (bhndb_get_rman(sc, child, type) == NULL) {
1440 		return (BUS_ACTIVATE_RESOURCE(device_get_parent(sc->parent_dev),
1441 		    child, type, rid, r));
1442 	}
1443 
1444 	return (bhndb_try_activate_resource(sc, child, type, rid, r, NULL));
1445 }
1446 
1447 /**
1448  * Default bhndb(4) implementation of BUS_DEACTIVATE_RESOURCE().
1449  */
1450 static int
1451 bhndb_deactivate_resource(device_t dev, device_t child, int type,
1452     int rid, struct resource *r)
1453 {
1454 	struct bhndb_dw_alloc	*dwa;
1455 	struct bhndb_softc	*sc;
1456 	struct rman		*rm;
1457 	int			 error;
1458 
1459 	sc = device_get_softc(dev);
1460 
1461 	/* Delegate directly to our parent device's bus if the requested
1462 	 * resource type isn't handled locally. */
1463 	rm = bhndb_get_rman(sc, child, type);
1464 	if (rm == NULL) {
1465 		return (BUS_DEACTIVATE_RESOURCE(
1466 		    device_get_parent(sc->parent_dev), child, type, rid, r));
1467 	}
1468 
1469 	/* Mark inactive */
1470 	if ((error = rman_deactivate_resource(r)))
1471 		return (error);
1472 
1473 	switch (type) {
1474 	case SYS_RES_IRQ:
1475 		/* No bridge-level state to be freed */
1476 		return (0);
1477 
1478 	case SYS_RES_MEMORY:
1479 		/* Free any dynamic window allocation. */
1480 		if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED) {
1481 			BHNDB_LOCK(sc);
1482 			dwa = bhndb_dw_find_resource(sc->bus_res, r);
1483 			if (dwa != NULL)
1484 				bhndb_dw_release(sc->bus_res, dwa, r);
1485 			BHNDB_UNLOCK(sc);
1486 		}
1487 
1488 		return (0);
1489 
1490 	default:
1491 		device_printf(dev, "unsupported resource type %d\n", type);
1492 		return (ENXIO);
1493 	}
1494 }
1495 
1496 /**
1497  * Default bhndb(4) implementation of BUS_GET_RESOURCE_LIST().
1498  */
1499 static struct resource_list *
1500 bhndb_get_resource_list(device_t dev, device_t child)
1501 {
1502 	struct bhndb_devinfo *dinfo = device_get_ivars(child);
1503 	return (&dinfo->resources);
1504 }
1505 
1506 /**
1507  * Default bhndb(4) implementation of BHND_BUS_ACTIVATE_RESOURCE().
1508  *
1509  * For BHNDB_ADDRSPACE_NATIVE children, all resources are activated as direct
1510  * resources via BUS_ACTIVATE_RESOURCE().
1511  *
1512  * For BHNDB_ADDRSPACE_BRIDGED children, the resource priority is determined,
1513  * and if possible, the resource is activated as a direct resource. For example,
1514  * depending on resource priority and bridge resource availability, this
1515  * function will attempt to activate SYS_RES_MEMORY resources using either a
1516  * static register window, a dynamic register window, or it will configure @p r
1517  * as an indirect resource -- in that order.
1518  */
1519 static int
1520 bhndb_activate_bhnd_resource(device_t dev, device_t child,
1521     int type, int rid, struct bhnd_resource *r)
1522 {
1523 	struct bhndb_softc	*sc;
1524 	struct bhndb_region	*region;
1525 	bhndb_priority_t	 r_prio;
1526 	rman_res_t		 r_start, r_size;
1527 	int 			 error;
1528 	bool			 indirect;
1529 
1530 	KASSERT(!r->direct,
1531 	    ("direct flag set on inactive resource"));
1532 
1533 	KASSERT(!(rman_get_flags(r->res) & RF_ACTIVE),
1534 	    ("RF_ACTIVE set on inactive resource"));
1535 
1536 	sc = device_get_softc(dev);
1537 
1538 	/* Delegate directly to BUS_ACTIVATE_RESOURCE() if the requested
1539 	 * resource type isn't handled locally. */
1540 	if (bhndb_get_rman(sc, child, type) == NULL) {
1541 		error = BUS_ACTIVATE_RESOURCE(dev, child, type, rid, r->res);
1542 		if (error == 0)
1543 			r->direct = true;
1544 		return (error);
1545 	}
1546 
1547 	r_start = rman_get_start(r->res);
1548 	r_size = rman_get_size(r->res);
1549 
1550 	/* Determine the resource priority of bridged resources, and skip direct
1551 	 * allocation if the priority is too low. */
1552 	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED) {
1553 		switch (type) {
1554 		case SYS_RES_IRQ:
1555 			/* IRQ resources are always direct */
1556 			break;
1557 
1558 		case SYS_RES_MEMORY:
1559 			region = bhndb_find_resource_region(sc->bus_res,
1560 				r_start, r_size);
1561 			if (region != NULL)
1562 				r_prio = region->priority;
1563 			else
1564 				r_prio = BHNDB_PRIORITY_NONE;
1565 
1566 			/* If less than the minimum dynamic window priority,
1567 			 * this resource should always be indirect. */
1568 			if (r_prio < sc->bus_res->min_prio)
1569 				return (0);
1570 
1571 			break;
1572 
1573 		default:
1574 			device_printf(dev, "unsupported resource type %d\n",
1575 			    type);
1576 			return (ENXIO);
1577 		}
1578 	}
1579 
1580 	/* Attempt direct activation */
1581 	error = bhndb_try_activate_resource(sc, child, type, rid, r->res,
1582 	    &indirect);
1583 	if (!error) {
1584 		r->direct = true;
1585 	} else if (indirect) {
1586 		/* The request was valid, but no viable register window is
1587 		 * available; indirection must be employed. */
1588 		error = 0;
1589 		r->direct = false;
1590 	}
1591 
1592 	if (BHNDB_DEBUG(PRIO) &&
1593 	    bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED)
1594 	{
1595 		device_printf(child, "activated 0x%llx-0x%llx as %s "
1596 		    "resource\n",
1597 		    (unsigned long long) r_start,
1598 		    (unsigned long long) r_start + r_size - 1,
1599 		    r->direct ? "direct" : "indirect");
1600 	}
1601 
1602 	return (error);
1603 }
1604 
1605 /**
1606  * Default bhndb(4) implementation of BHND_BUS_DEACTIVATE_RESOURCE().
1607  */
1608 static int
1609 bhndb_deactivate_bhnd_resource(device_t dev, device_t child,
1610     int type, int rid, struct bhnd_resource *r)
1611 {
1612 	int error;
1613 
1614 	/* Indirect resources don't require activation */
1615 	if (!r->direct)
1616 		return (0);
1617 
1618 	KASSERT(rman_get_flags(r->res) & RF_ACTIVE,
1619 	    ("RF_ACTIVE not set on direct resource"));
1620 
1621 	/* Perform deactivation */
1622 	error = BUS_DEACTIVATE_RESOURCE(dev, child, type, rid, r->res);
1623 	if (!error)
1624 		r->direct = false;
1625 
1626 	return (error);
1627 }
1628 
1629 /**
1630  * Find the best available bridge resource allocation record capable of handling
1631  * bus I/O requests of @p size at @p addr.
1632  *
1633  * In order of preference, this function will either:
1634  *
1635  * - Configure and return a free allocation record
1636  * - Return an existing allocation record mapping the requested space, or
1637  * - Steal, configure, and return an in-use allocation record.
1638  *
1639  * Will panic if a usable record cannot be found.
1640  *
1641  * @param sc Bridge driver state.
1642  * @param addr The I/O target address.
1643  * @param size The size of the I/O operation to be performed at @p addr.
1644  * @param[out] borrowed Set to true if the allocation record was borrowed to
1645  * fulfill this request; the borrowed record maps the target address range,
1646  * and must not be modified.
1647  * @param[out] stolen Set to true if the allocation record was stolen to fulfill
1648  * this request. If a stolen allocation record is returned,
1649  * bhndb_io_resource_restore() must be called upon completion of the bus I/O
1650  * request.
1651  * @param[out] restore If the allocation record was stolen, this will be set
1652  * to the target that must be restored.
1653  */
1654 static struct bhndb_dw_alloc *
1655 bhndb_io_resource_get_window(struct bhndb_softc *sc, bus_addr_t addr,
1656     bus_size_t size, bool *borrowed, bool *stolen, bus_addr_t *restore)
1657 {
1658 	struct bhndb_resources	*br;
1659 	struct bhndb_dw_alloc	*dwa;
1660 	struct bhndb_region	*region;
1661 
1662 	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1663 
1664 	br = sc->bus_res;
1665 	*borrowed = false;
1666 	*stolen = false;
1667 
1668 	/* Try to fetch a free window */
1669 	if ((dwa = bhndb_dw_next_free(br)) != NULL)
1670 		return (dwa);
1671 
1672 	/* Search for an existing dynamic mapping of this address range.
1673 	 * Static regions are not searched, as a statically mapped
1674 	 * region would never be allocated as an indirect resource. */
1675 	for (size_t i = 0; i < br->dwa_count; i++) {
1676 		const struct bhndb_regwin *win;
1677 
1678 		dwa = &br->dw_alloc[i];
1679 		win = dwa->win;
1680 
1681 		KASSERT(win->win_type == BHNDB_REGWIN_T_DYN,
1682 			("invalid register window type"));
1683 
1684 		/* Verify the range */
1685 		if (addr < dwa->target)
1686 			continue;
1687 
1688 		if (addr + size > dwa->target + win->win_size)
1689 			continue;
1690 
1691 		/* Found */
1692 		*borrowed = true;
1693 		return (dwa);
1694 	}
1695 
1696 	/* Try to steal a window; this should only be required on very early
1697 	 * PCI_V0 (BCM4318, etc) Wi-Fi chipsets */
1698 	region = bhndb_find_resource_region(br, addr, size);
1699 	if (region == NULL)
1700 		return (NULL);
1701 
1702 	if ((region->alloc_flags & BHNDB_ALLOC_FULFILL_ON_OVERCOMMIT) == 0)
1703 		return (NULL);
1704 
1705 	/* Steal a window. This acquires our backing spinlock, disabling
1706 	 * interrupts; the spinlock will be released by
1707 	 * bhndb_dw_return_stolen() */
1708 	if ((dwa = bhndb_dw_steal(br, restore)) != NULL) {
1709 		*stolen = true;
1710 		return (dwa);
1711 	}
1712 
1713 	panic("register windows exhausted attempting to map 0x%llx-0x%llx\n",
1714 	    (unsigned long long) addr, (unsigned long long) addr+size-1);
1715 }
1716 
1717 /**
1718  * Return a borrowed reference to a bridge resource allocation record capable
1719  * of handling bus I/O requests of @p size at @p addr.
1720  *
1721  * This will either return a reference to an existing allocation record mapping
1722  * the requested space, or will configure and return a free allocation record.
1723  *
1724  * Will panic if a usable record cannot be found.
1725  *
1726  * @param sc Bridge driver state.
1727  * @param addr The I/O target address.
1728  * @param size The size of the I/O operation to be performed at @p addr.
1729  * @param[out] offset The offset within the returned resource at which
1730  * to perform the I/O request.
1731  * @param[out] stolen Set to true if the allocation record was stolen to fulfill
1732  * this request. If a stolen allocation record is returned,
1733  * bhndb_io_resource_restore() must be called upon completion of the bus I/O
1734  * request.
1735  * @param[out] restore If the allocation record was stolen, this will be set
1736  * to the target that must be restored.
1737  */
1738 static inline struct bhndb_dw_alloc *
1739 bhndb_io_resource(struct bhndb_softc *sc, bus_addr_t addr, bus_size_t size,
1740     bus_size_t *offset, bool *stolen, bus_addr_t *restore)
1741 {
1742 	struct bhndb_dw_alloc	*dwa;
1743 	bool			 borrowed;
1744 	int			 error;
1745 
1746 	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1747 
1748 	dwa = bhndb_io_resource_get_window(sc, addr, size, &borrowed, stolen,
1749 	    restore);
1750 
1751 	/* Adjust the window if the I/O request won't fit in the current
1752 	 * target range. */
1753 	if (addr < dwa->target ||
1754 	    addr > dwa->target + dwa->win->win_size ||
1755 	    (dwa->target + dwa->win->win_size) - addr < size)
1756 	{
1757 		/* Cannot modify target of borrowed windows */
1758 		if (borrowed) {
1759 			panic("borrowed register window does not map expected "
1760 			    "range 0x%llx-0x%llx\n",
1761 			    (unsigned long long) addr,
1762 			    (unsigned long long) addr+size-1);
1763 		}
1764 
1765 		error = bhndb_dw_set_addr(sc->dev, sc->bus_res, dwa, addr,
1766 		    size);
1767 		if (error) {
1768 		    panic("failed to set register window target mapping "
1769 			    "0x%llx-0x%llx\n",
1770 			    (unsigned long long) addr,
1771 			    (unsigned long long) addr+size-1);
1772 		}
1773 	}
1774 
1775 	/* Calculate the offset and return */
1776 	*offset = (addr - dwa->target) + dwa->win->win_offset;
1777 	return (dwa);
1778 }
1779 
1780 /*
1781  * BHND_BUS_(READ|WRITE_* implementations
1782  */
1783 
1784 /* bhndb_bus_(read|write) common implementation */
1785 #define	BHNDB_IO_COMMON_SETUP(_io_size)				\
1786 	struct bhndb_softc	*sc;				\
1787 	struct bhndb_dw_alloc	*dwa;				\
1788 	struct resource		*io_res;			\
1789 	bus_size_t		 io_offset;			\
1790 	bus_addr_t		 restore;		\
1791 	bool			 stolen;			\
1792 								\
1793 	sc = device_get_softc(dev);				\
1794 								\
1795 	BHNDB_LOCK(sc);						\
1796 	dwa = bhndb_io_resource(sc, rman_get_start(r->res) +	\
1797 	    offset, _io_size, &io_offset, &stolen, &restore);	\
1798 	io_res = dwa->parent_res;				\
1799 								\
1800 	KASSERT(!r->direct,					\
1801 	    ("bhnd_bus slow path used for direct resource"));	\
1802 								\
1803 	KASSERT(rman_get_flags(io_res) & RF_ACTIVE,		\
1804 	    ("i/o resource is not active"));
1805 
1806 #define	BHNDB_IO_COMMON_TEARDOWN()				\
1807 	if (stolen) {						\
1808 		bhndb_dw_return_stolen(sc->dev, sc->bus_res,	\
1809 		    dwa, restore);				\
1810 	}							\
1811 	BHNDB_UNLOCK(sc);
1812 
1813 /* Defines a bhndb_bus_read_* method implementation */
1814 #define	BHNDB_IO_READ(_type, _name)				\
1815 static _type							\
1816 bhndb_bus_read_ ## _name (device_t dev, device_t child,		\
1817     struct bhnd_resource *r, bus_size_t offset)			\
1818 {								\
1819 	_type v;						\
1820 	BHNDB_IO_COMMON_SETUP(sizeof(_type));			\
1821 	v = bus_read_ ## _name (io_res, io_offset);		\
1822 	BHNDB_IO_COMMON_TEARDOWN();				\
1823 								\
1824 	return (v);						\
1825 }
1826 
1827 /* Defines a bhndb_bus_write_* method implementation */
1828 #define	BHNDB_IO_WRITE(_type, _name)				\
1829 static void							\
1830 bhndb_bus_write_ ## _name (device_t dev, device_t child,	\
1831     struct bhnd_resource *r, bus_size_t offset, _type value)	\
1832 {								\
1833 	BHNDB_IO_COMMON_SETUP(sizeof(_type));			\
1834 	bus_write_ ## _name (io_res, io_offset, value);		\
1835 	BHNDB_IO_COMMON_TEARDOWN();				\
1836 }
1837 
1838 /* Defines a bhndb_bus_(read|write|set)_(multi|region)_* method */
1839 #define	BHNDB_IO_MISC(_type, _ptr, _op, _size)			\
1840 static void							\
1841 bhndb_bus_ ## _op ## _ ## _size (device_t dev,			\
1842     device_t child, struct bhnd_resource *r, bus_size_t offset,	\
1843     _type _ptr datap, bus_size_t count)				\
1844 {								\
1845 	BHNDB_IO_COMMON_SETUP(sizeof(_type) * count);		\
1846 	bus_ ## _op ## _ ## _size (io_res, io_offset,		\
1847 	    datap, count);					\
1848 	BHNDB_IO_COMMON_TEARDOWN();				\
1849 }
1850 
1851 /* Defines a complete set of read/write methods */
1852 #define	BHNDB_IO_METHODS(_type, _size)				\
1853 	BHNDB_IO_READ(_type, _size)				\
1854 	BHNDB_IO_WRITE(_type, _size)				\
1855 								\
1856 	BHNDB_IO_READ(_type, stream_ ## _size)			\
1857 	BHNDB_IO_WRITE(_type, stream_ ## _size)			\
1858 								\
1859 	BHNDB_IO_MISC(_type, *, read_multi, _size)		\
1860 	BHNDB_IO_MISC(_type, *, write_multi, _size)		\
1861 								\
1862 	BHNDB_IO_MISC(_type, *, read_multi_stream, _size)	\
1863 	BHNDB_IO_MISC(_type, *, write_multi_stream, _size)	\
1864 								\
1865 	BHNDB_IO_MISC(_type,  , set_multi, _size)		\
1866 	BHNDB_IO_MISC(_type,  , set_region, _size)		\
1867 	BHNDB_IO_MISC(_type, *, read_region, _size)		\
1868 	BHNDB_IO_MISC(_type, *, write_region, _size)		\
1869 								\
1870 	BHNDB_IO_MISC(_type, *, read_region_stream, _size)	\
1871 	BHNDB_IO_MISC(_type, *, write_region_stream, _size)
1872 
1873 BHNDB_IO_METHODS(uint8_t, 1);
1874 BHNDB_IO_METHODS(uint16_t, 2);
1875 BHNDB_IO_METHODS(uint32_t, 4);
1876 
1877 /**
1878  * Default bhndb(4) implementation of BHND_BUS_BARRIER().
1879  */
1880 static void
1881 bhndb_bus_barrier(device_t dev, device_t child, struct bhnd_resource *r,
1882     bus_size_t offset, bus_size_t length, int flags)
1883 {
1884 	BHNDB_IO_COMMON_SETUP(length);
1885 
1886 	bus_barrier(io_res, io_offset + offset, length, flags);
1887 
1888 	BHNDB_IO_COMMON_TEARDOWN();
1889 }
1890 
1891 /**
1892  * Default bhndb(4) implementation of BHND_MAP_INTR().
1893  */
1894 static int
1895 bhndb_bhnd_map_intr(device_t dev, device_t child, u_int intr, rman_res_t *irq)
1896 {
1897 	struct bhndb_softc	*sc;
1898 	u_int			 ivec;
1899 	int			 error;
1900 
1901 	sc = device_get_softc(dev);
1902 
1903 	/* Is the intr valid? */
1904 	if (intr >= bhnd_get_intr_count(child))
1905 		return (EINVAL);
1906 
1907 	/* Fetch the interrupt vector */
1908 	if ((error = bhnd_get_intr_ivec(child, intr, &ivec)))
1909 		return (error);
1910 
1911 	/* Map directly to the actual backplane interrupt vector */
1912 	*irq = ivec;
1913 
1914 	return (0);
1915 }
1916 
1917 /**
1918  * Default bhndb(4) implementation of BHND_UNMAP_INTR().
1919  */
1920 static void
1921 bhndb_bhnd_unmap_intr(device_t dev, device_t child, rman_res_t irq)
1922 {
1923 	/* No state to clean up */
1924 }
1925 
1926 /**
1927  * Default bhndb(4) implementation of BUS_SETUP_INTR().
1928  */
1929 static int
1930 bhndb_setup_intr(device_t dev, device_t child, struct resource *r,
1931     int flags, driver_filter_t filter, driver_intr_t handler, void *arg,
1932     void **cookiep)
1933 {
1934 	struct bhndb_softc		*sc;
1935 	struct bhndb_intr_isrc		*isrc;
1936 	struct bhndb_intr_handler	*ih;
1937 	int				 error;
1938 
1939 	sc = device_get_softc(dev);
1940 
1941 	/* Fetch the isrc */
1942 	if ((error = BHNDB_MAP_INTR_ISRC(dev, r, &isrc))) {
1943 		device_printf(dev, "failed to fetch isrc: %d\n", error);
1944 		return (error);
1945 	}
1946 
1947 	/* Allocate new ihandler entry  */
1948 	ih = bhndb_alloc_intr_handler(child, r, isrc);
1949 	if (ih == NULL)
1950 		return (ENOMEM);
1951 
1952 	/* Perform actual interrupt setup via the host isrc */
1953 	error = bus_setup_intr(isrc->is_owner, isrc->is_res, flags, filter,
1954 	    handler, arg, &ih->ih_cookiep);
1955 	if (error) {
1956 		bhndb_free_intr_handler(ih);
1957 		return (error);
1958 	}
1959 
1960 	/* Add to our interrupt handler list */
1961 	BHNDB_LOCK(sc);
1962 	bhndb_register_intr_handler(sc->bus_res, ih);
1963 	BHNDB_UNLOCK(sc);
1964 
1965 	/* Provide the interrupt handler entry as our cookiep value */
1966 	*cookiep = ih;
1967 	return (0);
1968 }
1969 
1970 /**
1971  * Default bhndb(4) implementation of BUS_TEARDOWN_INTR().
1972  */
1973 static int
1974 bhndb_teardown_intr(device_t dev, device_t child, struct resource *r,
1975     void *cookiep)
1976 {
1977 	struct bhndb_softc		*sc;
1978 	struct bhndb_intr_handler	*ih;
1979 	struct bhndb_intr_isrc		*isrc;
1980 	int				 error;
1981 
1982 	sc = device_get_softc(dev);
1983 
1984 	/* Locate and claim ownership of the interrupt handler entry */
1985 	BHNDB_LOCK(sc);
1986 
1987 	ih = bhndb_find_intr_handler(sc->bus_res, cookiep);
1988 	if (ih == NULL) {
1989 		panic("%s requested teardown of invalid cookiep %p",
1990 		    device_get_nameunit(child), cookiep);
1991 	}
1992 
1993 	bhndb_deregister_intr_handler(sc->bus_res, ih);
1994 
1995 	BHNDB_UNLOCK(sc);
1996 
1997 	/* Perform actual interrupt teardown via the host isrc */
1998 	isrc = ih->ih_isrc;
1999 	error = bus_teardown_intr(isrc->is_owner, isrc->is_res, ih->ih_cookiep);
2000 	if (error) {
2001 		/* If teardown fails, we need to reinsert the handler entry
2002 		 * to allow later teardown */
2003 		BHNDB_LOCK(sc);
2004 		bhndb_register_intr_handler(sc->bus_res, ih);
2005 		BHNDB_UNLOCK(sc);
2006 
2007 		return (error);
2008 	}
2009 
2010 	/* Free the entry */
2011 	bhndb_free_intr_handler(ih);
2012 	return (0);
2013 }
2014 
2015 /**
2016  * Default bhndb(4) implementation of BUS_BIND_INTR().
2017  */
2018 static int
2019 bhndb_bind_intr(device_t dev, device_t child, struct resource *irq, int cpu)
2020 {
2021 	struct bhndb_softc		*sc;
2022 	struct bhndb_intr_handler	*ih;
2023 	struct bhndb_intr_isrc		*isrc;
2024 
2025 	sc = device_get_softc(dev);
2026 	isrc = NULL;
2027 
2028 	/* Fetch the isrc corresponding to the child IRQ resource */
2029 	BHNDB_LOCK(sc);
2030 	STAILQ_FOREACH(ih, &sc->bus_res->bus_intrs, ih_link) {
2031 		if (ih->ih_res == irq) {
2032 			isrc = ih->ih_isrc;
2033 			break;
2034 		}
2035 	}
2036 	BHNDB_UNLOCK(sc);
2037 
2038 	if (isrc == NULL) {
2039 		panic("%s requested bind of invalid irq %#jx-%#jx",
2040 		    device_get_nameunit(child), rman_get_start(irq),
2041 		    rman_get_end(irq));
2042 	}
2043 
2044 	/* Perform actual bind via the host isrc */
2045 	return (bus_bind_intr(isrc->is_owner, isrc->is_res, cpu));
2046 }
2047 
2048 /**
2049  * Default bhndb(4) implementation of BUS_DESCRIBE_INTR().
2050  */
2051 static int
2052 bhndb_describe_intr(device_t dev, device_t child, struct resource *irq,
2053     void *cookie, const char *descr)
2054 {
2055 	struct bhndb_softc		*sc;
2056 	struct bhndb_intr_handler	*ih;
2057 	struct bhndb_intr_isrc		*isrc;
2058 
2059 	sc = device_get_softc(dev);
2060 
2061 	/* Locate the interrupt handler entry; the caller owns the handler
2062 	 * reference, and thus our entry is guaranteed to remain valid after
2063 	 * we drop out lock below. */
2064 	BHNDB_LOCK(sc);
2065 
2066 	ih = bhndb_find_intr_handler(sc->bus_res, cookie);
2067 	if (ih == NULL) {
2068 		panic("%s requested invalid cookiep %p",
2069 		    device_get_nameunit(child), cookie);
2070 	}
2071 
2072 	isrc = ih->ih_isrc;
2073 
2074 	BHNDB_UNLOCK(sc);
2075 
2076 	/* Perform the actual request via the host isrc */
2077 	return (BUS_DESCRIBE_INTR(device_get_parent(isrc->is_owner),
2078 	    isrc->is_owner, isrc->is_res, ih->ih_cookiep, descr));
2079 }
2080 
2081 /**
2082  * Default bhndb(4) implementation of BUS_CONFIG_INTR().
2083  */
2084 static int
2085 bhndb_config_intr(device_t dev, int irq, enum intr_trigger trig,
2086     enum intr_polarity pol)
2087 {
2088 	/* Unsupported */
2089 	return (ENXIO);
2090 }
2091 
2092 /**
2093  * Default bhndb(4) implementation of BUS_REMAP_INTR().
2094  */
2095 static int
2096 bhndb_remap_intr(device_t dev, device_t child, u_int irq)
2097 {
2098 	/* Unsupported */
2099 	return (ENXIO);
2100 }
2101 
2102 /**
2103  * Default bhndb(4) implementation of BHND_BUS_GET_DMA_TRANSLATION().
2104  */
2105 static inline int
2106 bhndb_get_dma_translation(device_t dev, device_t child, u_int width,
2107     uint32_t flags, bus_dma_tag_t *dmat,
2108     struct bhnd_dma_translation *translation)
2109 {
2110 	struct bhndb_softc			*sc;
2111 	const struct bhndb_hwcfg		*hwcfg;
2112 	const struct bhnd_dma_translation	*match;
2113 	bus_dma_tag_t				 match_dmat;
2114 	bhnd_addr_t				 addr_mask, match_addr_mask;
2115 
2116 	sc = device_get_softc(dev);
2117 	hwcfg = sc->bus_res->cfg;
2118 
2119 	/* Is DMA supported? */
2120 	if (sc->bus_res->res->dma_tags == NULL)
2121 		return (ENODEV);
2122 
2123 	/* Is the requested width supported? */
2124 	if (width > BHND_DMA_ADDR_32BIT) {
2125 		/* Backplane must support 64-bit addressing */
2126 		if (!(sc->chipid.chip_caps & BHND_CAP_BP64))
2127 			width = BHND_DMA_ADDR_32BIT;
2128 	}
2129 
2130 	/* Find the best matching descriptor for the requested width */
2131 	addr_mask = BHND_DMA_ADDR_BITMASK(width);
2132 
2133 	match = NULL;
2134 	match_addr_mask = 0x0;
2135 	match_dmat = NULL;
2136 
2137 	for (size_t i = 0; i < sc->bus_res->res->num_dma_tags; i++) {
2138 		const struct bhnd_dma_translation	*dwin;
2139 		bhnd_addr_t				 masked;
2140 
2141 		dwin = &hwcfg->dma_translations[i];
2142 
2143 		/* The base address must be device addressable */
2144 		if ((dwin->base_addr & addr_mask) != dwin->base_addr)
2145 			continue;
2146 
2147 		/* The flags must match */
2148 		if ((dwin->flags & flags) != flags)
2149 			continue;
2150 
2151 		/* The window must cover at least part of our addressable
2152 		 * range */
2153 		masked = (dwin->addr_mask | dwin->addrext_mask) & addr_mask;
2154 		if (masked == 0)
2155 			continue;
2156 
2157 		/* Is this a better match? */
2158 		if (match == NULL || masked > match_addr_mask) {
2159 			match = dwin;
2160 			match_addr_mask = masked;
2161 			match_dmat = sc->bus_res->res->dma_tags[i];
2162 		}
2163 	}
2164 
2165 	if (match == NULL || match_addr_mask == 0)
2166 		return (ENOENT);
2167 
2168 	if (dmat != NULL)
2169 		*dmat = match_dmat;
2170 
2171 	if (translation != NULL)
2172 		*translation = *match;
2173 
2174 	return (0);
2175 }
2176 
2177 /**
2178  * Default bhndb(4) implementation of BUS_GET_DMA_TAG().
2179  */
2180 static bus_dma_tag_t
2181 bhndb_get_dma_tag(device_t dev, device_t child)
2182 {
2183 	struct bhndb_softc *sc = device_get_softc(dev);
2184 
2185 	/*
2186 	 * A bridge may have multiple DMA translation descriptors, each with
2187 	 * their own incompatible restrictions; drivers should in general call
2188 	 * BHND_BUS_GET_DMA_TRANSLATION() to fetch both the best available DMA
2189 	 * translation, and its corresponding DMA tag.
2190 	 *
2191 	 * Child drivers that do not use BHND_BUS_GET_DMA_TRANSLATION() are
2192 	 * responsible for creating their own restricted DMA tag; since we
2193 	 * cannot do this for them in BUS_GET_DMA_TAG(), we simply return the
2194 	 * bridge parent's DMA tag directly;
2195 	 */
2196 	return (bus_get_dma_tag(sc->parent_dev));
2197 }
2198 
2199 static device_method_t bhndb_methods[] = {
2200 	/* Device interface */ \
2201 	DEVMETHOD(device_probe,			bhndb_generic_probe),
2202 	DEVMETHOD(device_detach,		bhndb_generic_detach),
2203 	DEVMETHOD(device_shutdown,		bus_generic_shutdown),
2204 	DEVMETHOD(device_suspend,		bhndb_generic_suspend),
2205 	DEVMETHOD(device_resume,		bhndb_generic_resume),
2206 
2207 	/* Bus interface */
2208 	DEVMETHOD(bus_probe_nomatch,		bhndb_probe_nomatch),
2209 	DEVMETHOD(bus_print_child,		bhndb_print_child),
2210 	DEVMETHOD(bus_child_location,		bhndb_child_location),
2211 	DEVMETHOD(bus_add_child,		bhndb_add_child),
2212 	DEVMETHOD(bus_child_deleted,		bhndb_child_deleted),
2213 
2214 	DEVMETHOD(bus_alloc_resource,		bhndb_alloc_resource),
2215 	DEVMETHOD(bus_release_resource,		bhndb_release_resource),
2216 	DEVMETHOD(bus_activate_resource,	bhndb_activate_resource),
2217 	DEVMETHOD(bus_deactivate_resource,	bhndb_deactivate_resource),
2218 
2219 	DEVMETHOD(bus_setup_intr,		bhndb_setup_intr),
2220 	DEVMETHOD(bus_teardown_intr,		bhndb_teardown_intr),
2221 	DEVMETHOD(bus_config_intr,		bhndb_config_intr),
2222 	DEVMETHOD(bus_bind_intr,		bhndb_bind_intr),
2223 	DEVMETHOD(bus_describe_intr,		bhndb_describe_intr),
2224 	DEVMETHOD(bus_remap_intr,		bhndb_remap_intr),
2225 
2226 	DEVMETHOD(bus_get_dma_tag,		bhndb_get_dma_tag),
2227 
2228 	DEVMETHOD(bus_adjust_resource,		bhndb_adjust_resource),
2229 	DEVMETHOD(bus_set_resource,		bus_generic_rl_set_resource),
2230 	DEVMETHOD(bus_get_resource,		bus_generic_rl_get_resource),
2231 	DEVMETHOD(bus_delete_resource,		bus_generic_rl_delete_resource),
2232 	DEVMETHOD(bus_get_resource_list,	bhndb_get_resource_list),
2233 
2234 	DEVMETHOD(bus_read_ivar,		bhndb_read_ivar),
2235 	DEVMETHOD(bus_write_ivar,		bhndb_write_ivar),
2236 
2237 	/* BHNDB interface */
2238 	DEVMETHOD(bhndb_get_chipid,		bhndb_get_chipid),
2239 	DEVMETHOD(bhndb_is_core_disabled,	bhndb_is_core_disabled),
2240 	DEVMETHOD(bhndb_get_hostb_core,		bhndb_get_hostb_core),
2241 	DEVMETHOD(bhndb_suspend_resource,	bhndb_suspend_resource),
2242 	DEVMETHOD(bhndb_resume_resource,	bhndb_resume_resource),
2243 
2244 	/* BHND interface */
2245 	DEVMETHOD(bhnd_bus_get_chipid,		bhndb_get_chipid),
2246 	DEVMETHOD(bhnd_bus_activate_resource,	bhndb_activate_bhnd_resource),
2247 	DEVMETHOD(bhnd_bus_deactivate_resource,	bhndb_deactivate_bhnd_resource),
2248 	DEVMETHOD(bhnd_bus_get_nvram_var,	bhnd_bus_generic_get_nvram_var),
2249 	DEVMETHOD(bhnd_bus_map_intr,		bhndb_bhnd_map_intr),
2250 	DEVMETHOD(bhnd_bus_unmap_intr,		bhndb_bhnd_unmap_intr),
2251 	DEVMETHOD(bhnd_bus_get_dma_translation,	bhndb_get_dma_translation),
2252 
2253 	DEVMETHOD(bhnd_bus_get_service_registry,bhndb_get_service_registry),
2254 	DEVMETHOD(bhnd_bus_register_provider,	bhnd_bus_generic_sr_register_provider),
2255 	DEVMETHOD(bhnd_bus_deregister_provider,	bhnd_bus_generic_sr_deregister_provider),
2256 	DEVMETHOD(bhnd_bus_retain_provider,	bhnd_bus_generic_sr_retain_provider),
2257 	DEVMETHOD(bhnd_bus_release_provider,	bhnd_bus_generic_sr_release_provider),
2258 
2259 	DEVMETHOD(bhnd_bus_read_1,		bhndb_bus_read_1),
2260 	DEVMETHOD(bhnd_bus_read_2,		bhndb_bus_read_2),
2261 	DEVMETHOD(bhnd_bus_read_4,		bhndb_bus_read_4),
2262 	DEVMETHOD(bhnd_bus_write_1,		bhndb_bus_write_1),
2263 	DEVMETHOD(bhnd_bus_write_2,		bhndb_bus_write_2),
2264 	DEVMETHOD(bhnd_bus_write_4,		bhndb_bus_write_4),
2265 
2266 	DEVMETHOD(bhnd_bus_read_stream_1,	bhndb_bus_read_stream_1),
2267 	DEVMETHOD(bhnd_bus_read_stream_2,	bhndb_bus_read_stream_2),
2268 	DEVMETHOD(bhnd_bus_read_stream_4,	bhndb_bus_read_stream_4),
2269 	DEVMETHOD(bhnd_bus_write_stream_1,	bhndb_bus_write_stream_1),
2270 	DEVMETHOD(bhnd_bus_write_stream_2,	bhndb_bus_write_stream_2),
2271 	DEVMETHOD(bhnd_bus_write_stream_4,	bhndb_bus_write_stream_4),
2272 
2273 	DEVMETHOD(bhnd_bus_read_multi_1,	bhndb_bus_read_multi_1),
2274 	DEVMETHOD(bhnd_bus_read_multi_2,	bhndb_bus_read_multi_2),
2275 	DEVMETHOD(bhnd_bus_read_multi_4,	bhndb_bus_read_multi_4),
2276 	DEVMETHOD(bhnd_bus_write_multi_1,	bhndb_bus_write_multi_1),
2277 	DEVMETHOD(bhnd_bus_write_multi_2,	bhndb_bus_write_multi_2),
2278 	DEVMETHOD(bhnd_bus_write_multi_4,	bhndb_bus_write_multi_4),
2279 
2280 	DEVMETHOD(bhnd_bus_read_multi_stream_1,	bhndb_bus_read_multi_stream_1),
2281 	DEVMETHOD(bhnd_bus_read_multi_stream_2,	bhndb_bus_read_multi_stream_2),
2282 	DEVMETHOD(bhnd_bus_read_multi_stream_4,	bhndb_bus_read_multi_stream_4),
2283 	DEVMETHOD(bhnd_bus_write_multi_stream_1,bhndb_bus_write_multi_stream_1),
2284 	DEVMETHOD(bhnd_bus_write_multi_stream_2,bhndb_bus_write_multi_stream_2),
2285 	DEVMETHOD(bhnd_bus_write_multi_stream_4,bhndb_bus_write_multi_stream_4),
2286 
2287 	DEVMETHOD(bhnd_bus_set_multi_1,		bhndb_bus_set_multi_1),
2288 	DEVMETHOD(bhnd_bus_set_multi_2,		bhndb_bus_set_multi_2),
2289 	DEVMETHOD(bhnd_bus_set_multi_4,		bhndb_bus_set_multi_4),
2290 	DEVMETHOD(bhnd_bus_set_region_1,	bhndb_bus_set_region_1),
2291 	DEVMETHOD(bhnd_bus_set_region_2,	bhndb_bus_set_region_2),
2292 	DEVMETHOD(bhnd_bus_set_region_4,	bhndb_bus_set_region_4),
2293 
2294 	DEVMETHOD(bhnd_bus_read_region_1,	bhndb_bus_read_region_1),
2295 	DEVMETHOD(bhnd_bus_read_region_2,	bhndb_bus_read_region_2),
2296 	DEVMETHOD(bhnd_bus_read_region_4,	bhndb_bus_read_region_4),
2297 	DEVMETHOD(bhnd_bus_write_region_1,	bhndb_bus_write_region_1),
2298 	DEVMETHOD(bhnd_bus_write_region_2,	bhndb_bus_write_region_2),
2299 	DEVMETHOD(bhnd_bus_write_region_4,	bhndb_bus_write_region_4),
2300 
2301 	DEVMETHOD(bhnd_bus_read_region_stream_1,bhndb_bus_read_region_stream_1),
2302 	DEVMETHOD(bhnd_bus_read_region_stream_2,bhndb_bus_read_region_stream_2),
2303 	DEVMETHOD(bhnd_bus_read_region_stream_4,bhndb_bus_read_region_stream_4),
2304 	DEVMETHOD(bhnd_bus_write_region_stream_1,bhndb_bus_write_region_stream_1),
2305 	DEVMETHOD(bhnd_bus_write_region_stream_2,bhndb_bus_write_region_stream_2),
2306 	DEVMETHOD(bhnd_bus_write_region_stream_4,bhndb_bus_write_region_stream_4),
2307 
2308 	DEVMETHOD(bhnd_bus_barrier,		bhndb_bus_barrier),
2309 
2310 	DEVMETHOD_END
2311 };
2312 
2313 devclass_t bhndb_devclass;
2314 
2315 DEFINE_CLASS_0(bhndb, bhndb_driver, bhndb_methods, sizeof(struct bhndb_softc));
2316 
2317 MODULE_VERSION(bhndb, 1);
2318 MODULE_DEPEND(bhndb, bhnd, 1, 1, 1);
2319