bhndb.c revision 298480
1/*-
2 * Copyright (c) 2015 Landon Fuller <landon@landonf.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer,
10 *    without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13 *    redistribution must be conditioned upon including a substantially
14 *    similar Disclaimer requirement for further binary redistribution.
15 *
16 * NO WARRANTY
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27 * THE POSSIBILITY OF SUCH DAMAGES.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/dev/bhnd/bhndb/bhndb.c 298480 2016-04-22 16:27:35Z adrian $");
32
33/*
34 * Abstract BHND Bridge Device Driver
35 *
36 * Provides generic support for bridging from a parent bus (such as PCI) to
37 * a BHND-compatible bus (e.g. bcma or siba).
38 */
39
40#include <sys/param.h>
41#include <sys/kernel.h>
42#include <sys/bus.h>
43#include <sys/module.h>
44#include <sys/systm.h>
45
46#include <machine/bus.h>
47#include <sys/rman.h>
48#include <machine/resource.h>
49
50#include <dev/bhnd/bhndvar.h>
51#include <dev/bhnd/bhndreg.h>
52
53#include <dev/bhnd/cores/chipc/chipcreg.h>
54
55#include "bhndbvar.h"
56#include "bhndb_bus_if.h"
57#include "bhndb_hwdata.h"
58#include "bhndb_private.h"
59
60/* Debugging flags */
61static u_long bhndb_debug = 0;
62TUNABLE_ULONG("hw.bhndb.debug", &bhndb_debug);
63
64enum {
65	BHNDB_DEBUG_PRIO = 1 << 0,
66};
67
68#define	BHNDB_DEBUG(_type)	(BHNDB_DEBUG_ ## _type & bhndb_debug)
69
70static bool			 bhndb_hw_matches(device_t *devlist,
71				     int num_devs,
72				     const struct bhndb_hw *hw);
73
74static int			 bhndb_initialize_region_cfg(
75				     struct bhndb_softc *sc, device_t *devs,
76				     int ndevs,
77				     const struct bhndb_hw_priority *table,
78				     struct bhndb_resources *r);
79
80static int			 bhndb_find_hwspec(struct bhndb_softc *sc,
81				     device_t *devs, int ndevs,
82				     const struct bhndb_hw **hw);
83
84static int			 bhndb_read_chipid(struct bhndb_softc *sc,
85				     const struct bhndb_hwcfg *cfg,
86				     struct bhnd_chipid *result);
87
88bhndb_addrspace			 bhndb_get_addrspace(struct bhndb_softc *sc,
89				     device_t child);
90
91static struct rman		*bhndb_get_rman(struct bhndb_softc *sc,
92				     device_t child, int type);
93
94static int			 bhndb_init_child_resource(struct resource *r,
95				     struct resource *parent,
96				     bhnd_size_t offset,
97				     bhnd_size_t size);
98
99static int			 bhndb_activate_static_region(
100				     struct bhndb_softc *sc,
101				     struct bhndb_region *region,
102				     device_t child, int type, int rid,
103				     struct resource *r);
104
105static int			 bhndb_try_activate_resource(
106				     struct bhndb_softc *sc, device_t child,
107				     int type, int rid, struct resource *r,
108				     bool *indirect);
109
110
111/**
112 * Default bhndb(4) implementation of DEVICE_PROBE().
113 *
114 * This function provides the default bhndb implementation of DEVICE_PROBE(),
115 * and is compatible with bhndb(4) bridges attached via bhndb_attach_bridge().
116 */
117int
118bhndb_generic_probe(device_t dev)
119{
120	return (BUS_PROBE_NOWILDCARD);
121}
122
123static void
124bhndb_probe_nomatch(device_t dev, device_t child)
125{
126	const char *name;
127
128	name = device_get_name(child);
129	if (name == NULL)
130		name = "unknown device";
131
132	device_printf(dev, "<%s> (no driver attached)\n", name);
133}
134
135static int
136bhndb_print_child(device_t dev, device_t child)
137{
138	struct bhndb_softc	*sc;
139	struct resource_list	*rl;
140	int			 retval = 0;
141
142	sc = device_get_softc(dev);
143
144	retval += bus_print_child_header(dev, child);
145
146	rl = BUS_GET_RESOURCE_LIST(dev, child);
147	if (rl != NULL) {
148		retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY,
149		    "%#jx");
150		retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ,
151		    "%jd");
152	}
153
154	retval += bus_print_child_domain(dev, child);
155	retval += bus_print_child_footer(dev, child);
156
157	return (retval);
158}
159
160static int
161bhndb_child_pnpinfo_str(device_t bus, device_t child, char *buf,
162    size_t buflen)
163{
164	*buf = '\0';
165	return (0);
166}
167
168static int
169bhndb_child_location_str(device_t dev, device_t child, char *buf,
170    size_t buflen)
171{
172	struct bhndb_softc *sc;
173
174	sc = device_get_softc(dev);
175
176	snprintf(buf, buflen, "base=0x%llx",
177	    (unsigned long long) sc->chipid.enum_addr);
178	return (0);
179}
180
181/**
182 * Return true if @p devlist matches the @p hw specification.
183 *
184 * @param devlist A device table to match against.
185 * @param num_devs The number of devices in @p devlist.
186 * @param hw The hardware description to be matched against.
187 */
188static bool
189bhndb_hw_matches(device_t *devlist, int num_devs, const struct bhndb_hw *hw)
190{
191	for (u_int i = 0; i < hw->num_hw_reqs; i++) {
192		const struct bhnd_core_match	*match;
193		bool				 found;
194
195		match =  &hw->hw_reqs[i];
196		found = false;
197
198		for (int d = 0; d < num_devs; d++) {
199			if (!bhnd_device_matches(devlist[d], match))
200				continue;
201
202			found = true;
203			break;
204		}
205
206		if (!found)
207			return (false);
208	}
209
210	return (true);
211}
212
213/**
214 * Initialize the region maps and priority configuration in @p r using
215 * the provided priority @p table and the set of devices attached to
216 * the bridged @p bus_dev .
217 *
218 * @param sc The bhndb device state.
219 * @param devs All devices enumerated on the bridged bhnd bus.
220 * @param ndevs The length of @p devs.
221 * @param table Hardware priority table to be used to determine the relative
222 * priorities of per-core port resources.
223 * @param r The resource state to be configured.
224 */
225static int
226bhndb_initialize_region_cfg(struct bhndb_softc *sc, device_t *devs, int ndevs,
227    const struct bhndb_hw_priority *table, struct bhndb_resources *r)
228{
229	const struct bhndb_hw_priority	*hp;
230	bhnd_addr_t			 addr;
231	bhnd_size_t			 size;
232	size_t				 prio_low, prio_default, prio_high;
233	int				 error;
234
235	/* The number of port regions per priority band that must be accessible
236	 * via dynamic register windows */
237	prio_low = 0;
238	prio_default = 0;
239	prio_high = 0;
240
241	/*
242	 * Register bridge regions covering all statically mapped ports.
243	 */
244	for (int i = 0; i < ndevs; i++) {
245		const struct bhndb_regwin	*regw;
246		device_t			 child;
247
248		child = devs[i];
249
250		for (regw = r->cfg->register_windows;
251		    regw->win_type != BHNDB_REGWIN_T_INVALID; regw++)
252		{
253			/* Only core windows are supported */
254			if (regw->win_type != BHNDB_REGWIN_T_CORE)
255				continue;
256
257			/* Skip non-applicable register windows. */
258			if (!bhndb_regwin_matches_device(regw, child))
259				continue;
260
261			/* Fetch the base address of the mapped port. */
262			error = bhnd_get_region_addr(child,
263			    regw->core.port_type, regw->core.port,
264			    regw->core.region, &addr, &size);
265			if (error)
266			    return (error);
267
268			/*
269			 * Always defer to the register window's size.
270			 *
271			 * If the port size is smaller than the window size,
272			 * this ensures that we fully utilize register windows
273			 * larger than the referenced port.
274			 *
275			 * If the port size is larger than the window size, this
276			 * ensures that we do not directly map the allocations
277			 * within the region to a too-small window.
278			 */
279			size = regw->win_size;
280
281			/*
282			 * Add to the bus region list.
283			 *
284			 * The window priority for a statically mapped
285			 * region is always HIGH.
286			 */
287			error = bhndb_add_resource_region(r, addr, size,
288			    BHNDB_PRIORITY_HIGH, regw);
289			if (error)
290				return (error);
291		}
292	}
293
294	/*
295	 * Perform priority accounting and register bridge regions for all
296	 * ports defined in the priority table
297	 */
298	for (int i = 0; i < ndevs; i++) {
299		struct bhndb_region	*region;
300		device_t		 child;
301
302		child = devs[i];
303
304		/*
305		 * Skip priority accounting for cores that ...
306		 */
307
308		/* ... do not require bridge resources */
309		if (bhnd_is_hw_disabled(child) || !device_is_enabled(child))
310			continue;
311
312		/* ... do not have a priority table entry */
313		hp = bhndb_hw_priority_find_device(table, child);
314		if (hp == NULL)
315			continue;
316
317		/* ... are explicitly disabled in the priority table. */
318		if (hp->priority == BHNDB_PRIORITY_NONE)
319			continue;
320
321		/* Determine the number of dynamic windows required and
322		 * register their bus_region entries. */
323		for (u_int i = 0; i < hp->num_ports; i++) {
324			const struct bhndb_port_priority *pp;
325
326			pp = &hp->ports[i];
327
328			/* Skip ports not defined on this device */
329			if (!bhnd_is_region_valid(child, pp->type, pp->port,
330			    pp->region))
331			{
332				continue;
333			}
334
335			/* Fetch the address+size of the mapped port. */
336			error = bhnd_get_region_addr(child, pp->type, pp->port,
337			    pp->region, &addr, &size);
338			if (error)
339			    return (error);
340
341			/* Skip ports with an existing static mapping */
342			region = bhndb_find_resource_region(r, addr, size);
343			if (region != NULL && region->static_regwin != NULL)
344				continue;
345
346			/* Define a dynamic region for this port */
347			error = bhndb_add_resource_region(r, addr, size,
348			    pp->priority, NULL);
349			if (error)
350				return (error);
351
352			/* Update port mapping counts */
353			switch (pp->priority) {
354			case BHNDB_PRIORITY_NONE:
355				break;
356			case BHNDB_PRIORITY_LOW:
357				prio_low++;
358				break;
359			case BHNDB_PRIORITY_DEFAULT:
360				prio_default++;
361				break;
362			case BHNDB_PRIORITY_HIGH:
363				prio_high++;
364				break;
365			}
366		}
367	}
368
369	/* Determine the minimum priority at which we'll allocate direct
370	 * register windows from our dynamic pool */
371	size_t prio_total = prio_low + prio_default + prio_high;
372	if (prio_total <= r->dwa_count) {
373		/* low+default+high priority regions get windows */
374		r->min_prio = BHNDB_PRIORITY_LOW;
375
376	} else if (prio_default + prio_high <= r->dwa_count) {
377		/* default+high priority regions get windows */
378		r->min_prio = BHNDB_PRIORITY_DEFAULT;
379
380	} else {
381		/* high priority regions get windows */
382		r->min_prio = BHNDB_PRIORITY_HIGH;
383	}
384
385	if (BHNDB_DEBUG(PRIO)) {
386		struct bhndb_region	*region;
387		const char		*direct_msg, *type_msg;
388		bhndb_priority_t	 prio, prio_min;
389
390		prio_min = r->min_prio;
391		device_printf(sc->dev, "min_prio: %d\n", prio_min);
392
393		STAILQ_FOREACH(region, &r->bus_regions, link) {
394			prio = region->priority;
395
396			direct_msg = prio >= prio_min ? "direct" : "indirect";
397			type_msg = region->static_regwin ? "static" : "dynamic";
398
399			device_printf(sc->dev, "region 0x%llx+0x%llx priority "
400			    "%u %s/%s\n",
401			    (unsigned long long) region->addr,
402			    (unsigned long long) region->size,
403			    region->priority,
404			    direct_msg, type_msg);
405		}
406	}
407
408	return (0);
409}
410
411/**
412 * Find a hardware specification for @p dev.
413 *
414 * @param sc The bhndb device state.
415 * @param devs All devices enumerated on the bridged bhnd bus.
416 * @param ndevs The length of @p devs.
417 * @param[out] hw On success, the matched hardware specification.
418 * with @p dev.
419 *
420 * @retval 0 success
421 * @retval non-zero if an error occurs fetching device info for comparison.
422 */
423static int
424bhndb_find_hwspec(struct bhndb_softc *sc, device_t *devs, int ndevs,
425    const struct bhndb_hw **hw)
426{
427	const struct bhndb_hw	*next, *hw_table;
428
429	/* Search for the first matching hardware config. */
430	hw_table = BHNDB_BUS_GET_HARDWARE_TABLE(sc->parent_dev, sc->dev);
431	for (next = hw_table; next->hw_reqs != NULL; next++) {
432		if (!bhndb_hw_matches(devs, ndevs, next))
433			continue;
434
435		/* Found */
436		*hw = next;
437		return (0);
438	}
439
440	return (ENOENT);
441}
442
443/**
444 * Read the ChipCommon identification data for this device.
445 *
446 * @param sc bhndb device state.
447 * @param cfg The hardware configuration to use when mapping the ChipCommon
448 * registers.
449 * @param[out] result the chip identification data.
450 *
451 * @retval 0 success
452 * @retval non-zero if the ChipCommon identification data could not be read.
453 */
454static int
455bhndb_read_chipid(struct bhndb_softc *sc, const struct bhndb_hwcfg *cfg,
456    struct bhnd_chipid *result)
457{
458	const struct bhnd_chipid	*parent_cid;
459	const struct bhndb_regwin	*cc_win;
460	struct resource_spec		 rs;
461	int				 error;
462
463	/* Let our parent device override the discovery process */
464	parent_cid = BHNDB_BUS_GET_CHIPID(sc->parent_dev, sc->dev);
465	if (parent_cid != NULL) {
466		*result = *parent_cid;
467		return (0);
468	}
469
470	/* Find a register window we can use to map the first CHIPC_CHIPID_SIZE
471	 * of ChipCommon registers. */
472	cc_win = bhndb_regwin_find_best(cfg->register_windows,
473	    BHND_DEVCLASS_CC, 0, BHND_PORT_DEVICE, 0, 0, CHIPC_CHIPID_SIZE);
474	if (cc_win == NULL) {
475		device_printf(sc->dev, "no chipcommon register window\n");
476		return (0);
477	}
478
479	/* We can assume a device without a static ChipCommon window uses the
480	 * default ChipCommon address. */
481	if (cc_win->win_type == BHNDB_REGWIN_T_DYN) {
482		error = BHNDB_SET_WINDOW_ADDR(sc->dev, cc_win,
483		    BHND_DEFAULT_CHIPC_ADDR);
484
485		if (error) {
486			device_printf(sc->dev, "failed to set chipcommon "
487			    "register window\n");
488			return (error);
489		}
490	}
491
492	/* Let the default bhnd implemenation alloc/release the resource and
493	 * perform the read */
494	rs.type = cc_win->res.type;
495	rs.rid = cc_win->res.rid;
496	rs.flags = RF_ACTIVE;
497
498	return (bhnd_read_chipid(sc->parent_dev, &rs, cc_win->win_offset,
499	    result));
500}
501
502/**
503 * Helper function that must be called by subclass bhndb(4) drivers
504 * when implementing DEVICE_ATTACH() before calling any bhnd(4) or bhndb(4)
505 * APIs on the bridge device.
506 *
507 * @param dev The bridge device to attach.
508 * @param bridge_devclass The device class of the bridging core. This is used
509 * to automatically detect the bridge core, and to disable additional bridge
510 * cores (e.g. PCMCIA on a PCIe device).
511 */
512int
513bhndb_attach(device_t dev, bhnd_devclass_t bridge_devclass)
514{
515	struct bhndb_devinfo		*dinfo;
516	struct bhndb_softc		*sc;
517	const struct bhndb_hwcfg	*cfg;
518	int				 error;
519
520	sc = device_get_softc(dev);
521	sc->dev = dev;
522	sc->parent_dev = device_get_parent(dev);
523	sc->bridge_class = bridge_devclass;
524
525	BHNDB_LOCK_INIT(sc);
526
527	/* Read our chip identification data */
528	cfg = BHNDB_BUS_GET_GENERIC_HWCFG(sc->parent_dev, sc->dev);
529	if ((error = bhndb_read_chipid(sc, cfg, &sc->chipid)))
530		return (error);
531
532	/* Populate generic resource allocation state. */
533	sc->bus_res = bhndb_alloc_resources(dev, sc->parent_dev, cfg);
534	if (sc->bus_res == NULL) {
535		return (ENXIO);
536	}
537
538	/* Attach our bridged bus device */
539	sc->bus_dev = BUS_ADD_CHILD(dev, 0, devclass_get_name(bhnd_devclass),
540	    -1);
541	if (sc->bus_dev == NULL) {
542		error = ENXIO;
543		goto failed;
544	}
545
546	/* Configure address space */
547	dinfo = device_get_ivars(sc->bus_dev);
548	dinfo->addrspace = BHNDB_ADDRSPACE_BRIDGED;
549
550	/* Finish attach */
551	return (bus_generic_attach(dev));
552
553failed:
554	BHNDB_LOCK_DESTROY(sc);
555
556	if (sc->bus_res != NULL)
557		bhndb_free_resources(sc->bus_res);
558
559	return (error);
560}
561
562/**
563 * Default bhndb(4) implementation of BHNDB_INIT_FULL_CONFIG().
564 *
565 * This function provides the default bhndb implementation of
566 * BHNDB_INIT_FULL_CONFIG(), and must be called by any subclass driver
567 * overriding BHNDB_INIT_FULL_CONFIG().
568 *
569 * As documented by BHNDB_INIT_FULL_CONFIG, this function performs final
570 * bridge configuration based on the hardware information enumerated by the
571 * child bus, and will reset all resource allocation state on the bridge.
572 *
573 * When calling this method:
574 * - Any bus resources previously allocated by @p child must be deallocated.
575 * - The @p child bus must have performed initial enumeration -- but not
576 *   probe or attachment -- of its children.
577 */
578int
579bhndb_generic_init_full_config(device_t dev, device_t child,
580    const struct bhndb_hw_priority *hw_prio_table)
581{
582	struct bhndb_softc		*sc;
583	const struct bhndb_hw		*hw;
584	struct bhndb_resources		*r;
585	device_t			*devs;
586	device_t			 hostb;
587	int				 ndevs;
588	int				 error;
589
590	sc = device_get_softc(dev);
591	hostb = NULL;
592
593	/* Fetch the full set of attached devices */
594	if ((error = device_get_children(sc->bus_dev, &devs, &ndevs)))
595		return (error);
596
597	/* Find our host bridge device */
598	for (int i = 0; i < ndevs; i++) {
599		if (bhnd_is_hostb_device(devs[i])) {
600			hostb = devs[i];
601			break;
602		}
603	}
604
605	if (hostb == NULL) {
606		device_printf(sc->dev, "no host bridge core found\n");
607		error = ENODEV;
608		goto cleanup;
609	}
610
611	/* Find our full register window configuration */
612	if ((error = bhndb_find_hwspec(sc, devs, ndevs, &hw))) {
613		device_printf(sc->dev, "unable to identify device, "
614			" using generic bridge resource definitions\n");
615		error = 0;
616		goto cleanup;
617	}
618
619	if (bootverbose)
620		device_printf(sc->dev, "%s resource configuration\n", hw->name);
621
622	/* Release existing resource state */
623	BHNDB_LOCK(sc);
624	bhndb_free_resources(sc->bus_res);
625	sc->bus_res = NULL;
626	BHNDB_UNLOCK(sc);
627
628	/* Allocate new resource state */
629	r = bhndb_alloc_resources(dev, sc->parent_dev, hw->cfg);
630	if (r == NULL) {
631		error = ENXIO;
632		goto cleanup;
633	}
634
635	/* Initialize our resource priority configuration */
636	error = bhndb_initialize_region_cfg(sc, devs, ndevs, hw_prio_table, r);
637	if (error) {
638		bhndb_free_resources(r);
639		goto cleanup;
640	}
641
642	/* Update our bridge state */
643	BHNDB_LOCK(sc);
644	sc->bus_res = r;
645	sc->hostb_dev = hostb;
646	BHNDB_UNLOCK(sc);
647
648cleanup:
649	free(devs, M_TEMP);
650	return (error);
651}
652
653/**
654 * Default bhndb(4) implementation of DEVICE_DETACH().
655 *
656 * This function detaches any child devices, and if successful, releases all
657 * resources held by the bridge device.
658 */
659int
660bhndb_generic_detach(device_t dev)
661{
662	struct bhndb_softc	*sc;
663	int			 error;
664
665	sc = device_get_softc(dev);
666
667	/* Detach children */
668	if ((error = bus_generic_detach(dev)))
669		return (error);
670
671	/* Clean up our driver state. */
672	bhndb_free_resources(sc->bus_res);
673
674	BHNDB_LOCK_DESTROY(sc);
675
676	return (0);
677}
678
679/**
680 * Default bhndb(4) implementation of DEVICE_SUSPEND().
681 *
682 * This function calls bus_generic_suspend() (or implements equivalent
683 * behavior).
684 */
685int
686bhndb_generic_suspend(device_t dev)
687{
688	return (bus_generic_suspend(dev));
689}
690
691/**
692 * Default bhndb(4) implementation of DEVICE_RESUME().
693 *
694 * This function calls bus_generic_resume() (or implements equivalent
695 * behavior).
696 */
697int
698bhndb_generic_resume(device_t dev)
699{
700	struct bhndb_softc	*sc;
701	struct bhndb_resources	*bus_res;
702	struct bhndb_dw_alloc	*dwa;
703	int			 error;
704
705	sc = device_get_softc(dev);
706	bus_res = sc->bus_res;
707
708	/* Guarantee that all in-use dynamic register windows are mapped to
709	 * their previously configured target address. */
710	BHNDB_LOCK(sc);
711	for (size_t i = 0; i < bus_res->dwa_count; i++) {
712		dwa = &bus_res->dw_alloc[i];
713
714		/* Skip regions that were not previously used */
715		if (bhndb_dw_is_free(bus_res, dwa) && dwa->target == 0x0)
716			continue;
717
718		/* Otherwise, ensure the register window is correct before
719		 * any children attempt MMIO */
720		error = BHNDB_SET_WINDOW_ADDR(dev, dwa->win, dwa->target);
721		if (error)
722			break;
723	}
724	BHNDB_UNLOCK(sc);
725
726	/* Error restoring hardware state; children cannot be safely resumed */
727	if (error) {
728		device_printf(dev, "Unable to restore hardware configuration; "
729		    "cannot resume: %d\n", error);
730		return (error);
731	}
732
733	return (bus_generic_resume(dev));
734}
735
736/**
737 * Default implementation of BHNDB_SUSPEND_RESOURCE.
738 */
739static void
740bhndb_suspend_resource(device_t dev, device_t child, int type,
741    struct resource *r)
742{
743	struct bhndb_softc	*sc;
744	struct bhndb_dw_alloc	*dwa;
745
746	sc = device_get_softc(dev);
747
748	// TODO: IRQs?
749	if (type != SYS_RES_MEMORY)
750		return;
751
752	BHNDB_LOCK(sc);
753	dwa = bhndb_dw_find_resource(sc->bus_res, r);
754	if (dwa == NULL) {
755		BHNDB_UNLOCK(sc);
756		return;
757	}
758
759	if (BHNDB_DEBUG(PRIO))
760		device_printf(child, "suspend resource type=%d 0x%jx+0x%jx\n",
761		    type, rman_get_start(r), rman_get_size(r));
762
763	/* Release the resource's window reference */
764	bhndb_dw_release(sc->bus_res, dwa, r);
765	BHNDB_UNLOCK(sc);
766}
767
768/**
769 * Default implementation of BHNDB_RESUME_RESOURCE.
770 */
771static int
772bhndb_resume_resource(device_t dev, device_t child, int type,
773    struct resource *r)
774{
775	struct bhndb_softc	*sc;
776
777	sc = device_get_softc(dev);
778
779	// TODO: IRQs?
780	if (type != SYS_RES_MEMORY)
781		return (0);
782
783	/* Inactive resources don't require reallocation of bridge resources */
784	if (!(rman_get_flags(r) & RF_ACTIVE))
785		return (0);
786
787	if (BHNDB_DEBUG(PRIO))
788		device_printf(child, "resume resource type=%d 0x%jx+0x%jx\n",
789		    type, rman_get_start(r), rman_get_size(r));
790
791	return (bhndb_try_activate_resource(sc, rman_get_device(r), type,
792	    rman_get_rid(r), r, NULL));
793}
794
795
796/**
797 * Default bhndb(4) implementation of BUS_READ_IVAR().
798 */
799static int
800bhndb_read_ivar(device_t dev, device_t child, int index,
801    uintptr_t *result)
802{
803	return (ENOENT);
804}
805
806/**
807 * Default bhndb(4) implementation of BUS_WRITE_IVAR().
808 */
809static int
810bhndb_write_ivar(device_t dev, device_t child, int index,
811    uintptr_t value)
812{
813	return (ENOENT);
814}
815
816/**
817 * Return the address space for the given @p child device.
818 */
819bhndb_addrspace
820bhndb_get_addrspace(struct bhndb_softc *sc, device_t child)
821{
822	struct bhndb_devinfo	*dinfo;
823	device_t		 imd_dev;
824
825	/* Find the directly attached parent of the requesting device */
826	imd_dev = child;
827	while (imd_dev != NULL && device_get_parent(imd_dev) != sc->dev)
828		imd_dev = device_get_parent(imd_dev);
829
830	if (imd_dev == NULL)
831		panic("bhndb address space request for non-child device %s\n",
832		     device_get_nameunit(child));
833
834	dinfo = device_get_ivars(imd_dev);
835	return (dinfo->addrspace);
836}
837
838/**
839 * Return the rman instance for a given resource @p type, if any.
840 *
841 * @param sc The bhndb device state.
842 * @param child The requesting child.
843 * @param type The resource type (e.g. SYS_RES_MEMORY, SYS_RES_IRQ, ...)
844 */
845static struct rman *
846bhndb_get_rman(struct bhndb_softc *sc, device_t child, int type)
847{
848	switch (bhndb_get_addrspace(sc, child)) {
849	case BHNDB_ADDRSPACE_NATIVE:
850		switch (type) {
851		case SYS_RES_MEMORY:
852			return (&sc->bus_res->ht_mem_rman);
853		case SYS_RES_IRQ:
854			return (NULL);
855		default:
856			return (NULL);
857		};
858
859	case BHNDB_ADDRSPACE_BRIDGED:
860		switch (type) {
861		case SYS_RES_MEMORY:
862			return (&sc->bus_res->br_mem_rman);
863		case SYS_RES_IRQ:
864			// TODO
865			// return &sc->irq_rman;
866			return (NULL);
867		default:
868			return (NULL);
869		};
870	}
871}
872
873/**
874 * Default implementation of BUS_ADD_CHILD()
875 */
876static device_t
877bhndb_add_child(device_t dev, u_int order, const char *name, int unit)
878{
879	struct bhndb_devinfo	*dinfo;
880	device_t		 child;
881
882	child = device_add_child_ordered(dev, order, name, unit);
883	if (child == NULL)
884		return (NULL);
885
886	dinfo = malloc(sizeof(struct bhndb_devinfo), M_BHND, M_NOWAIT);
887	if (dinfo == NULL) {
888		device_delete_child(dev, child);
889		return (NULL);
890	}
891
892	dinfo->addrspace = BHNDB_ADDRSPACE_NATIVE;
893	resource_list_init(&dinfo->resources);
894
895	device_set_ivars(child, dinfo);
896
897	return (child);
898}
899
900/**
901 * Default implementation of BUS_CHILD_DELETED().
902 */
903static void
904bhndb_child_deleted(device_t dev, device_t child)
905{
906	struct bhndb_devinfo *dinfo = device_get_ivars(child);
907	if (dinfo != NULL) {
908		resource_list_free(&dinfo->resources);
909		free(dinfo, M_BHND);
910	}
911
912	device_set_ivars(child, NULL);
913}
914
915/**
916 * Default implementation of BHNDB_GET_CHIPID().
917 */
918static const struct bhnd_chipid *
919bhndb_get_chipid(device_t dev, device_t child)
920{
921	struct bhndb_softc *sc = device_get_softc(dev);
922	return (&sc->chipid);
923}
924
925
926/**
927 * Default implementation of BHNDB_IS_HW_DISABLED().
928 */
929static bool
930bhndb_is_hw_disabled(device_t dev, device_t child) {
931	struct bhndb_softc	*sc;
932	struct bhnd_core_info	 core;
933
934	sc = device_get_softc(dev);
935
936	/* Requestor must be attached to the bhnd bus */
937	if (device_get_parent(child) != sc->bus_dev) {
938		return (BHND_BUS_IS_HW_DISABLED(device_get_parent(dev), child));
939	}
940
941	/* Fetch core info */
942	core = bhnd_get_core_info(child);
943
944	/* Try to defer to the bhndb bus parent */
945	if (BHNDB_BUS_IS_CORE_DISABLED(sc->parent_dev, dev, &core))
946		return (true);
947
948	/* Otherwise, we treat bridge-capable cores as unpopulated if they're
949	 * not the configured host bridge */
950	if (BHND_DEVCLASS_SUPPORTS_HOSTB(bhnd_core_class(&core)))
951		return (!BHND_BUS_IS_HOSTB_DEVICE(dev, child));
952
953	/* Otherwise, assume the core is populated */
954	return (false);
955}
956
957/* ascending core index comparison used by bhndb_is_hostb_device() */
958static int
959compare_core_index(const void *lhs, const void *rhs)
960{
961	u_int left = bhnd_get_core_index(*(const device_t *) lhs);
962	u_int right = bhnd_get_core_index(*(const device_t *) rhs);
963
964	if (left < right)
965		return (-1);
966	else if (left > right)
967		return (1);
968	else
969		return (0);
970}
971
972/**
973 * Default bhndb(4) implementation of BHND_BUS_IS_HOSTB_DEVICE().
974 *
975 * This function uses a heuristic valid on all known PCI/PCIe/PCMCIA-bridged
976 * bhnd(4) devices to determine the hostb core:
977 *
978 * - The core must have a Broadcom vendor ID.
979 * - The core devclass must match the bridge type.
980 * - The core must be the first device on the bus with the bridged device
981 *   class.
982 *
983 * @param sc The bridge device state.
984 * @param cores The table of bridge-enumerated cores.
985 * @param num_cores The length of @p cores.
986 * @param core The core to check.
987 */
988static bool
989bhndb_is_hostb_device(device_t dev, device_t child)
990{
991	struct bhndb_softc	*sc;
992	struct bhnd_core_match	 md;
993	device_t		 hostb_dev, *devlist;
994	int                      devcnt, error;
995
996
997	sc = device_get_softc(dev);
998
999	/* Requestor must be attached to the bhnd bus */
1000	if (device_get_parent(child) != sc->bus_dev)
1001		return (BHND_BUS_IS_HOSTB_DEVICE(device_get_parent(dev),
1002		    child));
1003
1004	/* Determine required device class and set up a match descriptor. */
1005	md = (struct bhnd_core_match) {
1006		.vendor = BHND_MFGID_BCM,
1007		.device = BHND_COREID_INVALID,
1008		.hwrev = { BHND_HWREV_INVALID, BHND_HWREV_INVALID },
1009		.class = sc->bridge_class,
1010		.unit = 0
1011	};
1012
1013	/* Pre-screen the device before searching over the full device list. */
1014	if (!bhnd_device_matches(child, &md))
1015		return (false);
1016
1017	/* Must be the absolute first matching device on the bus. */
1018	if ((error = device_get_children(sc->bus_dev, &devlist, &devcnt)))
1019		return (false);
1020
1021	/* Sort by core index value, ascending */
1022	qsort(devlist, devcnt, sizeof(*devlist), compare_core_index);
1023
1024	/* Find the actual hostb device */
1025	hostb_dev = NULL;
1026	for (int i = 0; i < devcnt; i++) {
1027		if (bhnd_device_matches(devlist[i], &md)) {
1028			hostb_dev = devlist[i];
1029			break;
1030		}
1031	}
1032
1033	/* Clean up */
1034	free(devlist, M_TEMP);
1035
1036	return (child == hostb_dev);
1037}
1038
1039/**
1040 * Default bhndb(4) implementation of BUS_ALLOC_RESOURCE().
1041 */
1042static struct resource *
1043bhndb_alloc_resource(device_t dev, device_t child, int type,
1044    int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1045{
1046	struct bhndb_softc		*sc;
1047	struct resource_list_entry	*rle;
1048	struct resource			*rv;
1049	struct rman			*rm;
1050	int				 error;
1051	bool				 passthrough, isdefault;
1052
1053	sc = device_get_softc(dev);
1054	passthrough = (device_get_parent(child) != dev);
1055	isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1056	rle = NULL;
1057
1058	/* Populate defaults */
1059	if (!passthrough && isdefault) {
1060		/* Fetch the resource list entry. */
1061		rle = resource_list_find(BUS_GET_RESOURCE_LIST(dev, child),
1062		    type, *rid);
1063		if (rle == NULL) {
1064			device_printf(dev,
1065			    "default resource %#x type %d for child %s "
1066			    "not found\n", *rid, type,
1067			    device_get_nameunit(child));
1068
1069			return (NULL);
1070		}
1071
1072		if (rle->res != NULL) {
1073			device_printf(dev,
1074			    "resource entry %#x type %d for child %s is busy\n",
1075			    *rid, type, device_get_nameunit(child));
1076
1077			return (NULL);
1078		}
1079
1080		start = rle->start;
1081		end = rle->end;
1082		count = ulmax(count, rle->count);
1083	}
1084
1085	/* Validate resource addresses */
1086	if (start > end || count > ((end - start) + 1))
1087		return (NULL);
1088
1089	/* Fetch the resource manager */
1090	rm = bhndb_get_rman(sc, child, type);
1091	if (rm == NULL)
1092		return (NULL);
1093
1094	/* Make our reservation */
1095	rv = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1096	    child);
1097	if (rv == NULL)
1098		return (NULL);
1099
1100	rman_set_rid(rv, *rid);
1101
1102	/* Activate */
1103	if (flags & RF_ACTIVE) {
1104		error = bus_activate_resource(child, type, *rid, rv);
1105		if (error) {
1106			device_printf(dev,
1107			    "failed to activate entry %#x type %d for "
1108				"child %s: %d\n",
1109			     *rid, type, device_get_nameunit(child), error);
1110
1111			rman_release_resource(rv);
1112
1113			return (NULL);
1114		}
1115	}
1116
1117	/* Update child's resource list entry */
1118	if (rle != NULL) {
1119		rle->res = rv;
1120		rle->start = rman_get_start(rv);
1121		rle->end = rman_get_end(rv);
1122		rle->count = rman_get_size(rv);
1123	}
1124
1125	return (rv);
1126}
1127
1128/**
1129 * Default bhndb(4) implementation of BUS_RELEASE_RESOURCE().
1130 */
1131static int
1132bhndb_release_resource(device_t dev, device_t child, int type, int rid,
1133    struct resource *r)
1134{
1135	int error;
1136
1137	/* Deactivate resources */
1138	if (rman_get_flags(r) & RF_ACTIVE) {
1139		error = BUS_DEACTIVATE_RESOURCE(dev, child, type, rid, r);
1140		if (error)
1141			return (error);
1142	}
1143
1144	if ((error = rman_release_resource(r)))
1145		return (error);
1146
1147	return (0);
1148}
1149
1150/**
1151 * Default bhndb(4) implementation of BUS_ADJUST_RESOURCE().
1152 */
1153static int
1154bhndb_adjust_resource(device_t dev, device_t child, int type,
1155    struct resource *r, rman_res_t start, rman_res_t end)
1156{
1157	struct bhndb_softc		*sc;
1158	struct rman			*rm;
1159	int				 error;
1160
1161	sc = device_get_softc(dev);
1162	error = 0;
1163
1164	/* Fetch resource manager */
1165	rm = bhndb_get_rman(sc, child, type);
1166	if (rm == NULL)
1167		return (ENXIO);
1168
1169	if (!rman_is_region_manager(r, rm))
1170		return (ENXIO);
1171
1172	/* If active, adjustment is limited by the assigned window. */
1173	BHNDB_LOCK(sc);
1174
1175	// TODO: Currently unsupported
1176	error = ENODEV;
1177
1178	BHNDB_UNLOCK(sc);
1179	if (!error)
1180		error = rman_adjust_resource(r, start, end);
1181
1182	return (error);
1183}
1184
1185/**
1186 * Initialize child resource @p r with a virtual address, tag, and handle
1187 * copied from @p parent, adjusted to contain only the range defined by
1188 * @p offsize and @p size.
1189 *
1190 * @param r The register to be initialized.
1191 * @param parent The parent bus resource that fully contains the subregion.
1192 * @param offset The subregion offset within @p parent.
1193 * @param size The subregion size.
1194 * @p r.
1195 */
1196static int
1197bhndb_init_child_resource(struct resource *r,
1198    struct resource *parent, bhnd_size_t offset, bhnd_size_t size)
1199{
1200	bus_space_handle_t	bh, child_bh;
1201	bus_space_tag_t		bt;
1202	uintptr_t		vaddr;
1203	int			error;
1204
1205	/* Fetch the parent resource's real bus values */
1206	vaddr = (uintptr_t) rman_get_virtual(parent);
1207	bt = rman_get_bustag(parent);
1208	bh = rman_get_bushandle(parent);
1209
1210	/* Configure child resource with window-adjusted real bus values */
1211	vaddr += offset;
1212	error = bus_space_subregion(bt, bh, offset, size, &child_bh);
1213	if (error)
1214		return (error);
1215
1216	rman_set_virtual(r, (void *) vaddr);
1217	rman_set_bustag(r, bt);
1218	rman_set_bushandle(r, child_bh);
1219
1220	return (0);
1221}
1222
1223/**
1224 * Attempt activation of a fixed register window mapping for @p child.
1225 *
1226 * @param sc BHNDB device state.
1227 * @param region The static region definition capable of mapping @p r.
1228 * @param child A child requesting resource activation.
1229 * @param type Resource type.
1230 * @param rid Resource identifier.
1231 * @param r Resource to be activated.
1232 *
1233 * @retval 0 if @p r was activated successfully
1234 * @retval ENOENT if no fixed register window was found.
1235 * @retval non-zero if @p r could not be activated.
1236 */
1237static int
1238bhndb_activate_static_region(struct bhndb_softc *sc,
1239    struct bhndb_region *region, device_t child, int type, int rid,
1240    struct resource *r)
1241{
1242	struct resource			*bridge_res;
1243	const struct bhndb_regwin	*win;
1244	bhnd_size_t			 parent_offset;
1245	rman_res_t			 r_start, r_size;
1246	int				 error;
1247
1248	win = region->static_regwin;
1249
1250	KASSERT(win != NULL && BHNDB_REGWIN_T_IS_STATIC(win->win_type),
1251	    ("can't activate non-static region"));
1252
1253	r_start = rman_get_start(r);
1254	r_size = rman_get_size(r);
1255
1256	/* Find the corresponding bridge resource */
1257	bridge_res = bhndb_find_regwin_resource(sc->bus_res, win);
1258	if (bridge_res == NULL)
1259		return (ENXIO);
1260
1261	/* Calculate subregion offset within the parent resource */
1262	parent_offset = r_start - region->addr;
1263	parent_offset += win->win_offset;
1264
1265	/* Configure resource with its real bus values. */
1266	error = bhndb_init_child_resource(r, bridge_res, parent_offset, r_size);
1267	if (error)
1268		return (error);
1269
1270	/* Mark active */
1271	if ((error = rman_activate_resource(r)))
1272		return (error);
1273
1274	return (0);
1275}
1276
1277/**
1278 * Attempt to allocate/retain a dynamic register window for @p r, returning
1279 * the retained window.
1280 *
1281 * @param sc The bhndb driver state.
1282 * @param r The resource for which a window will be retained.
1283 */
1284static struct bhndb_dw_alloc *
1285bhndb_retain_dynamic_window(struct bhndb_softc *sc, struct resource *r)
1286{
1287	struct bhndb_dw_alloc	*dwa;
1288	rman_res_t		 r_start, r_size;
1289	int			 error;
1290
1291	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1292
1293	r_start = rman_get_start(r);
1294	r_size = rman_get_size(r);
1295
1296	/* Look for an existing dynamic window we can reference */
1297	dwa = bhndb_dw_find_mapping(sc->bus_res, r_start, r_size);
1298	if (dwa != NULL) {
1299		if (bhndb_dw_retain(sc->bus_res, dwa, r) == 0)
1300			return (dwa);
1301
1302		return (NULL);
1303	}
1304
1305	/* Otherwise, try to reserve a free window */
1306	dwa = bhndb_dw_next_free(sc->bus_res);
1307	if (dwa == NULL) {
1308		/* No free windows */
1309		return (NULL);
1310	}
1311
1312	/* Set the window target */
1313	error = bhndb_dw_set_addr(sc->dev, sc->bus_res, dwa, rman_get_start(r),
1314	    rman_get_size(r));
1315	if (error) {
1316		device_printf(sc->dev, "dynamic window initialization "
1317			"for 0x%llx-0x%llx failed\n",
1318			(unsigned long long) r_start,
1319			(unsigned long long) r_start + r_size - 1);
1320		return (NULL);
1321	}
1322
1323	/* Add our reservation */
1324	if (bhndb_dw_retain(sc->bus_res, dwa, r))
1325		return (NULL);
1326
1327	return (dwa);
1328}
1329
1330/**
1331 * Activate a resource using any viable static or dynamic register window.
1332 *
1333 * @param sc The bhndb driver state.
1334 * @param child The child holding ownership of @p r.
1335 * @param type The type of the resource to be activated.
1336 * @param rid The resource ID of @p r.
1337 * @param r The resource to be activated
1338 * @param[out] indirect On error and if not NULL, will be set to 'true' if
1339 * the caller should instead use an indirect resource mapping.
1340 *
1341 * @retval 0 success
1342 * @retval non-zero activation failed.
1343 */
1344static int
1345bhndb_try_activate_resource(struct bhndb_softc *sc, device_t child, int type,
1346    int rid, struct resource *r, bool *indirect)
1347{
1348	struct bhndb_region	*region;
1349	struct bhndb_dw_alloc	*dwa;
1350	bhndb_priority_t	 dw_priority;
1351	rman_res_t		 r_start, r_size;
1352	rman_res_t		 parent_offset;
1353	int			 error;
1354
1355	BHNDB_LOCK_ASSERT(sc, MA_NOTOWNED);
1356
1357	// TODO - IRQs
1358	if (type != SYS_RES_MEMORY)
1359		return (ENXIO);
1360
1361	if (indirect)
1362		*indirect = false;
1363
1364	r_start = rman_get_start(r);
1365	r_size = rman_get_size(r);
1366
1367	/* Activate native addrspace resources using the host address space */
1368	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_NATIVE) {
1369		struct resource *parent;
1370
1371		/* Find the bridge resource referenced by the child */
1372		parent = bhndb_find_resource_range(sc->bus_res, r_start,
1373		    r_size);
1374		if (parent == NULL) {
1375			device_printf(sc->dev, "host resource not found "
1376			     "for 0x%llx-0x%llx\n",
1377			     (unsigned long long) r_start,
1378			     (unsigned long long) r_start + r_size - 1);
1379			return (ENOENT);
1380		}
1381
1382		/* Initialize child resource with the real bus values */
1383		error = bhndb_init_child_resource(r, parent,
1384		    r_start - rman_get_start(parent), r_size);
1385		if (error)
1386			return (error);
1387
1388		/* Try to activate child resource */
1389		return (rman_activate_resource(r));
1390	}
1391
1392	/* Default to low priority */
1393	dw_priority = BHNDB_PRIORITY_LOW;
1394
1395	/* Look for a bus region matching the resource's address range */
1396	region = bhndb_find_resource_region(sc->bus_res, r_start, r_size);
1397	if (region != NULL)
1398		dw_priority = region->priority;
1399
1400	/* Prefer static mappings over consuming a dynamic windows. */
1401	if (region && region->static_regwin) {
1402		error = bhndb_activate_static_region(sc, region, child, type,
1403		    rid, r);
1404		if (error)
1405			device_printf(sc->dev, "static window allocation "
1406			     "for 0x%llx-0x%llx failed\n",
1407			     (unsigned long long) r_start,
1408			     (unsigned long long) r_start + r_size - 1);
1409		return (error);
1410	}
1411
1412	/* A dynamic window will be required; is this resource high enough
1413	 * priority to be reserved a dynamic window? */
1414	if (dw_priority < sc->bus_res->min_prio) {
1415		if (indirect)
1416			*indirect = true;
1417
1418		return (ENOMEM);
1419	}
1420
1421	/* Find and retain a usable window */
1422	BHNDB_LOCK(sc); {
1423		dwa = bhndb_retain_dynamic_window(sc, r);
1424	} BHNDB_UNLOCK(sc);
1425
1426	if (dwa == NULL) {
1427		if (indirect)
1428			*indirect = true;
1429		return (ENOMEM);
1430	}
1431
1432	/* Configure resource with its real bus values. */
1433	parent_offset = dwa->win->win_offset;
1434	parent_offset += r_start - dwa->target;
1435
1436	error = bhndb_init_child_resource(r, dwa->parent_res, parent_offset,
1437	    dwa->win->win_size);
1438	if (error)
1439		goto failed;
1440
1441	/* Mark active */
1442	if ((error = rman_activate_resource(r)))
1443		goto failed;
1444
1445	return (0);
1446
1447failed:
1448	/* Release our region allocation. */
1449	BHNDB_LOCK(sc);
1450	bhndb_dw_release(sc->bus_res, dwa, r);
1451	BHNDB_UNLOCK(sc);
1452
1453	return (error);
1454}
1455
1456/**
1457 * Default bhndb(4) implementation of BUS_ACTIVATE_RESOURCE().
1458 *
1459 * Maps resource activation requests to a viable static or dynamic
1460 * register window, if any.
1461 */
1462static int
1463bhndb_activate_resource(device_t dev, device_t child, int type, int rid,
1464    struct resource *r)
1465{
1466	struct bhndb_softc *sc = device_get_softc(dev);
1467
1468	return (bhndb_try_activate_resource(sc, child, type, rid, r, NULL));
1469}
1470
1471/**
1472 * Default bhndb(4) implementation of BUS_DEACTIVATE_RESOURCE().
1473 */
1474static int
1475bhndb_deactivate_resource(device_t dev, device_t child, int type,
1476    int rid, struct resource *r)
1477{
1478	struct bhndb_dw_alloc	*dwa;
1479	struct bhndb_softc	*sc;
1480	struct rman		*rm;
1481	int			 error;
1482
1483	sc = device_get_softc(dev);
1484
1485	if ((rm = bhndb_get_rman(sc, child, type)) == NULL)
1486		return (EINVAL);
1487
1488	/* Mark inactive */
1489	if ((error = rman_deactivate_resource(r)))
1490		return (error);
1491
1492	/* Free any dynamic window allocation. */
1493	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED) {
1494		BHNDB_LOCK(sc);
1495		dwa = bhndb_dw_find_resource(sc->bus_res, r);
1496		if (dwa != NULL)
1497			bhndb_dw_release(sc->bus_res, dwa, r);
1498		BHNDB_UNLOCK(sc);
1499	}
1500
1501	return (0);
1502}
1503
1504/**
1505 * Default bhndb(4) implementation of BUS_GET_RESOURCE_LIST().
1506 */
1507static struct resource_list *
1508bhndb_get_resource_list(device_t dev, device_t child)
1509{
1510	struct bhndb_devinfo *dinfo = device_get_ivars(child);
1511	return (&dinfo->resources);
1512}
1513
1514/**
1515 * Default bhndb(4) implementation of BHND_BUS_ACTIVATE_RESOURCE().
1516 *
1517 * For BHNDB_ADDRSPACE_NATIVE children, all resources may be assumed to
1518 * be actived by the bridge.
1519 *
1520 * For BHNDB_ADDRSPACE_BRIDGED children, attempts to activate a static register
1521 * window, a dynamic register window, or configures @p r as an indirect
1522 * resource -- in that order.
1523 */
1524static int
1525bhndb_activate_bhnd_resource(device_t dev, device_t child,
1526    int type, int rid, struct bhnd_resource *r)
1527{
1528	struct bhndb_softc	*sc;
1529	struct bhndb_region	*region;
1530	rman_res_t		 r_start, r_size;
1531	int 			 error;
1532	bool			 indirect;
1533
1534	KASSERT(!r->direct,
1535	    ("direct flag set on inactive resource"));
1536
1537	KASSERT(!(rman_get_flags(r->res) & RF_ACTIVE),
1538	    ("RF_ACTIVE set on inactive resource"));
1539
1540	sc = device_get_softc(dev);
1541
1542	r_start = rman_get_start(r->res);
1543	r_size = rman_get_size(r->res);
1544
1545	/* Verify bridged address range's resource priority, and skip direct
1546	 * allocation if the priority is too low. */
1547	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED) {
1548		bhndb_priority_t r_prio;
1549
1550		region = bhndb_find_resource_region(sc->bus_res, r_start, r_size);
1551		if (region != NULL)
1552			r_prio = region->priority;
1553		else
1554			r_prio = BHNDB_PRIORITY_NONE;
1555
1556		/* If less than the minimum dynamic window priority, this
1557		 * resource should always be indirect. */
1558		if (r_prio < sc->bus_res->min_prio)
1559			return (0);
1560	}
1561
1562	/* Attempt direct activation */
1563	error = bhndb_try_activate_resource(sc, child, type, rid, r->res,
1564	    &indirect);
1565	if (!error) {
1566		r->direct = true;
1567	} else if (indirect) {
1568		/* The request was valid, but no viable register window is
1569		 * available; indirection must be employed. */
1570		error = 0;
1571		r->direct = false;
1572	}
1573
1574	if (BHNDB_DEBUG(PRIO) &&
1575	    bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED)
1576	{
1577		device_printf(child, "activated 0x%llx-0x%llx as %s "
1578		    "resource\n",
1579		    (unsigned long long) r_start,
1580		    (unsigned long long) r_start + r_size - 1,
1581		    r->direct ? "direct" : "indirect");
1582	}
1583
1584	return (error);
1585};
1586
1587/**
1588 * Default bhndb(4) implementation of BHND_BUS_DEACTIVATE_RESOURCE().
1589 */
1590static int
1591bhndb_deactivate_bhnd_resource(device_t dev, device_t child,
1592    int type, int rid, struct bhnd_resource *r)
1593{
1594	int error;
1595
1596	/* Indirect resources don't require activation */
1597	if (!r->direct)
1598		return (0);
1599
1600	KASSERT(rman_get_flags(r->res) & RF_ACTIVE,
1601	    ("RF_ACTIVE not set on direct resource"));
1602
1603	/* Perform deactivation */
1604	error = bus_deactivate_resource(child, type, rid, r->res);
1605	if (!error)
1606		r->direct = false;
1607
1608	return (error);
1609};
1610
1611/**
1612 * Slow path for bhndb_io_resource().
1613 *
1614 * Iterates over the existing allocated dynamic windows looking for a viable
1615 * in-use region; the first matching region is returned.
1616 */
1617static struct bhndb_dw_alloc *
1618bhndb_io_resource_slow(struct bhndb_softc *sc, bus_addr_t addr,
1619    bus_size_t size, bus_size_t *offset)
1620{
1621	struct bhndb_resources	*br;
1622	struct bhndb_dw_alloc	*dwa;
1623
1624	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1625
1626	br = sc->bus_res;
1627
1628	/* Search for an existing dynamic mapping of this address range.
1629	 * Static regions are not searched, as a statically mapped
1630	 * region would never be allocated as an indirect resource. */
1631	for (size_t i = 0; i < br->dwa_count; i++) {
1632		const struct bhndb_regwin *win;
1633
1634		dwa = &br->dw_alloc[i];
1635		win = dwa->win;
1636
1637		KASSERT(win->win_type == BHNDB_REGWIN_T_DYN,
1638			("invalid register window type"));
1639
1640		/* Verify the range */
1641		if (addr < dwa->target)
1642			continue;
1643
1644		if (addr + size > dwa->target + win->win_size)
1645			continue;
1646
1647		/* Found */
1648		*offset = dwa->win->win_offset;
1649		*offset += addr - dwa->target;
1650
1651		return (dwa);
1652	}
1653
1654	/* not found */
1655	return (NULL);
1656}
1657
1658/**
1659 * Find the bridge resource to be used for I/O requests.
1660 *
1661 * @param sc Bridge driver state.
1662 * @param addr The I/O target address.
1663 * @param size The size of the I/O operation to be performed at @p addr.
1664 * @param[out] offset The offset within the returned resource at which
1665 * to perform the I/O request.
1666 */
1667static inline struct bhndb_dw_alloc *
1668bhndb_io_resource(struct bhndb_softc *sc, bus_addr_t addr, bus_size_t size,
1669    bus_size_t *offset)
1670{
1671	struct bhndb_resources	*br;
1672	struct bhndb_dw_alloc	*dwa;
1673	int			 error;
1674
1675	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1676
1677	br = sc->bus_res;
1678
1679	/* Try to fetch a free window */
1680	dwa = bhndb_dw_next_free(br);
1681
1682	/*
1683	 * If no dynamic windows are available, look for an existing
1684	 * region that maps the target range.
1685	 *
1686	 * If none are found, this is a child driver bug -- our window
1687	 * over-commit should only fail in the case where a child driver leaks
1688	 * resources, or perform operations out-of-order.
1689	 *
1690	 * Broadcom HND chipsets are designed to not require register window
1691	 * swapping during execution; as long as the child devices are
1692	 * attached/detached correctly, using the hardware's required order
1693	 * of operations, there should always be a window available for the
1694	 * current operation.
1695	 */
1696	if (dwa == NULL) {
1697		dwa = bhndb_io_resource_slow(sc, addr, size, offset);
1698		if (dwa == NULL) {
1699			panic("register windows exhausted attempting to map "
1700			    "0x%llx-0x%llx\n",
1701			    (unsigned long long) addr,
1702			    (unsigned long long) addr+size-1);
1703		}
1704
1705		return (dwa);
1706	}
1707
1708	/* Adjust the window if the I/O request won't fit in the current
1709	 * target range. */
1710	if (addr < dwa->target ||
1711	   (dwa->target + dwa->win->win_size) - addr < size)
1712	{
1713		error = bhndb_dw_set_addr(sc->dev, sc->bus_res, dwa, addr,
1714		    size);
1715		if (error) {
1716		    panic("failed to set register window target mapping "
1717			    "0x%llx-0x%llx\n",
1718			    (unsigned long long) addr,
1719			    (unsigned long long) addr+size-1);
1720		}
1721	}
1722
1723	/* Calculate the offset and return */
1724	*offset = (addr - dwa->target) + dwa->win->win_offset;
1725	return (dwa);
1726}
1727
1728/*
1729 * BHND_BUS_(READ|WRITE_* implementations
1730 */
1731
1732/* bhndb_bus_(read|write) common implementation */
1733#define	BHNDB_IO_COMMON_SETUP(_io_size)				\
1734	struct bhndb_softc	*sc;				\
1735	struct bhndb_dw_alloc	*dwa;				\
1736	struct resource		*io_res;			\
1737	bus_size_t		 io_offset;			\
1738								\
1739	sc = device_get_softc(dev);				\
1740								\
1741	BHNDB_LOCK(sc);						\
1742	dwa = bhndb_io_resource(sc, rman_get_start(r->res) +	\
1743	    offset, _io_size, &io_offset);			\
1744	io_res = dwa->parent_res;				\
1745								\
1746	KASSERT(!r->direct,					\
1747	    ("bhnd_bus slow path used for direct resource"));	\
1748								\
1749	KASSERT(rman_get_flags(io_res) & RF_ACTIVE,		\
1750	    ("i/o resource is not active"));
1751
1752#define	BHNDB_IO_COMMON_TEARDOWN()				\
1753	BHNDB_UNLOCK(sc);
1754
1755/* Defines a bhndb_bus_read_* method implementation */
1756#define	BHNDB_IO_READ(_type, _size)				\
1757static _type							\
1758bhndb_bus_read_ ## _size (device_t dev, device_t child,		\
1759    struct bhnd_resource *r, bus_size_t offset)			\
1760{								\
1761	_type v;						\
1762	BHNDB_IO_COMMON_SETUP(sizeof(_type));			\
1763	v = bus_read_ ## _size (io_res, io_offset);		\
1764	BHNDB_IO_COMMON_TEARDOWN();				\
1765								\
1766	return (v);						\
1767}
1768
1769/* Defines a bhndb_bus_write_* method implementation */
1770#define	BHNDB_IO_WRITE(_type, _size)				\
1771static void							\
1772bhndb_bus_write_ ## _size (device_t dev, device_t child,	\
1773    struct bhnd_resource *r, bus_size_t offset, _type value)	\
1774{								\
1775	BHNDB_IO_COMMON_SETUP(sizeof(_type));			\
1776	bus_write_ ## _size (io_res, io_offset, value);		\
1777	BHNDB_IO_COMMON_TEARDOWN();				\
1778}
1779
1780BHNDB_IO_READ(uint8_t, 1);
1781BHNDB_IO_READ(uint16_t, 2);
1782BHNDB_IO_READ(uint32_t, 4);
1783
1784BHNDB_IO_WRITE(uint8_t, 1);
1785BHNDB_IO_WRITE(uint16_t, 2);
1786BHNDB_IO_WRITE(uint32_t, 4);
1787
1788/**
1789 * Default bhndb(4) implementation of BHND_BUS_BARRIER().
1790 */
1791static void
1792bhndb_bus_barrier(device_t dev, device_t child, struct bhnd_resource *r,
1793    bus_size_t offset, bus_size_t length, int flags)
1794{
1795	bus_size_t remain;
1796
1797	BHNDB_IO_COMMON_SETUP(length);
1798
1799	/* TODO: It's unclear whether we need a barrier implementation,
1800	 * and if we do, what it needs to actually do. This may need
1801	 * revisiting once we have a better idea of requirements after
1802	 * porting the core drivers. */
1803	panic("implementation incorrect");
1804
1805	/* Use 4-byte reads where possible */
1806	remain = length % sizeof(uint32_t);
1807	for (bus_size_t i = 0; i < (length - remain); i += 4)
1808		bus_read_4(io_res, io_offset + offset + i);
1809
1810	/* Use 1 byte reads for the remainder */
1811	for (bus_size_t i = 0; i < remain; i++)
1812		bus_read_1(io_res, io_offset + offset + length + i);
1813
1814	BHNDB_IO_COMMON_TEARDOWN();
1815}
1816
1817/**
1818 * Default bhndb(4) implementation of BUS_SETUP_INTR().
1819 */
1820static int
1821bhndb_setup_intr(device_t dev, device_t child, struct resource *r,
1822    int flags, driver_filter_t filter, driver_intr_t handler, void *arg,
1823    void **cookiep)
1824{
1825	// TODO
1826	return (EOPNOTSUPP);
1827}
1828
1829/**
1830 * Default bhndb(4) implementation of BUS_TEARDOWN_INTR().
1831 */
1832static int
1833bhndb_teardown_intr(device_t dev, device_t child, struct resource *r,
1834    void *cookie)
1835{
1836	// TODO
1837	return (EOPNOTSUPP);
1838}
1839
1840/**
1841 * Default bhndb(4) implementation of BUS_CONFIG_INTR().
1842 */
1843static int
1844bhndb_config_intr(device_t dev, int irq, enum intr_trigger trig,
1845    enum intr_polarity pol)
1846{
1847	// TODO
1848	return (EOPNOTSUPP);
1849}
1850
1851/**
1852 * Default bhndb(4) implementation of BUS_BIND_INTR().
1853 */
1854static int
1855bhndb_bind_intr(device_t dev, device_t child, struct resource *r, int cpu)
1856{
1857	// TODO
1858	return (EOPNOTSUPP);
1859}
1860
1861/**
1862 * Default bhndb(4) implementation of BUS_DESCRIBE_INTR().
1863 */
1864static int
1865bhndb_describe_intr(device_t dev, device_t child, struct resource *irq, void *cookie,
1866    const char *descr)
1867{
1868	// TODO
1869	return (EOPNOTSUPP);
1870}
1871
1872/**
1873 * Default bhndb(4) implementation of BUS_GET_DMA_TAG().
1874 */
1875static bus_dma_tag_t
1876bhndb_get_dma_tag(device_t dev, device_t child)
1877{
1878	// TODO
1879	return (NULL);
1880}
1881
1882static device_method_t bhndb_methods[] = {
1883	/* Device interface */ \
1884	DEVMETHOD(device_probe,			bhndb_generic_probe),
1885	DEVMETHOD(device_detach,		bhndb_generic_detach),
1886	DEVMETHOD(device_shutdown,		bus_generic_shutdown),
1887	DEVMETHOD(device_suspend,		bhndb_generic_suspend),
1888	DEVMETHOD(device_resume,		bhndb_generic_resume),
1889
1890	/* Bus interface */
1891	DEVMETHOD(bus_probe_nomatch,		bhndb_probe_nomatch),
1892	DEVMETHOD(bus_print_child,		bhndb_print_child),
1893	DEVMETHOD(bus_child_pnpinfo_str,	bhndb_child_pnpinfo_str),
1894	DEVMETHOD(bus_child_location_str,	bhndb_child_location_str),
1895	DEVMETHOD(bus_add_child,		bhndb_add_child),
1896	DEVMETHOD(bus_child_deleted,		bhndb_child_deleted),
1897
1898	DEVMETHOD(bus_alloc_resource,		bhndb_alloc_resource),
1899	DEVMETHOD(bus_release_resource,		bhndb_release_resource),
1900	DEVMETHOD(bus_activate_resource,	bhndb_activate_resource),
1901	DEVMETHOD(bus_deactivate_resource,	bhndb_deactivate_resource),
1902
1903	DEVMETHOD(bus_setup_intr,		bhndb_setup_intr),
1904	DEVMETHOD(bus_teardown_intr,		bhndb_teardown_intr),
1905	DEVMETHOD(bus_config_intr,		bhndb_config_intr),
1906	DEVMETHOD(bus_bind_intr,		bhndb_bind_intr),
1907	DEVMETHOD(bus_describe_intr,		bhndb_describe_intr),
1908
1909	DEVMETHOD(bus_get_dma_tag,		bhndb_get_dma_tag),
1910
1911	DEVMETHOD(bus_adjust_resource,		bhndb_adjust_resource),
1912	DEVMETHOD(bus_set_resource,		bus_generic_rl_set_resource),
1913	DEVMETHOD(bus_get_resource,		bus_generic_rl_get_resource),
1914	DEVMETHOD(bus_delete_resource,		bus_generic_rl_delete_resource),
1915	DEVMETHOD(bus_get_resource_list,	bhndb_get_resource_list),
1916
1917	DEVMETHOD(bus_read_ivar,		bhndb_read_ivar),
1918	DEVMETHOD(bus_write_ivar,		bhndb_write_ivar),
1919
1920	/* BHNDB interface */
1921	DEVMETHOD(bhndb_get_chipid,		bhndb_get_chipid),
1922	DEVMETHOD(bhndb_init_full_config,	bhndb_generic_init_full_config),
1923	DEVMETHOD(bhndb_suspend_resource,	bhndb_suspend_resource),
1924	DEVMETHOD(bhndb_resume_resource,	bhndb_resume_resource),
1925
1926	/* BHND interface */
1927	DEVMETHOD(bhnd_bus_is_hw_disabled,	bhndb_is_hw_disabled),
1928	DEVMETHOD(bhnd_bus_is_hostb_device,	bhndb_is_hostb_device),
1929	DEVMETHOD(bhnd_bus_get_chipid,		bhndb_get_chipid),
1930	DEVMETHOD(bhnd_bus_activate_resource,	bhndb_activate_bhnd_resource),
1931	DEVMETHOD(bhnd_bus_activate_resource,	bhndb_deactivate_bhnd_resource),
1932	DEVMETHOD(bhnd_bus_read_1,		bhndb_bus_read_1),
1933	DEVMETHOD(bhnd_bus_read_2,		bhndb_bus_read_2),
1934	DEVMETHOD(bhnd_bus_read_4,		bhndb_bus_read_4),
1935	DEVMETHOD(bhnd_bus_write_1,		bhndb_bus_write_1),
1936	DEVMETHOD(bhnd_bus_write_2,		bhndb_bus_write_2),
1937	DEVMETHOD(bhnd_bus_write_4,		bhndb_bus_write_4),
1938	DEVMETHOD(bhnd_bus_barrier,		bhndb_bus_barrier),
1939
1940	DEVMETHOD_END
1941};
1942
1943devclass_t bhndb_devclass;
1944
1945DEFINE_CLASS_0(bhndb, bhndb_driver, bhndb_methods, sizeof(struct bhndb_softc));
1946
1947MODULE_VERSION(bhndb, 1);
1948MODULE_DEPEND(bhndb, bhnd, 1, 1, 1);
1949MODULE_DEPEND(bhndb, bhnd_chipc, 1, 1, 1);
1950