bhndb.c revision 299235
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 299235 2016-05-08 17:52:12Z 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->d.core.port_type, regw->d.core.port,
264			    regw->d.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, "bhnd", -1);
540	if (sc->bus_dev == NULL) {
541		error = ENXIO;
542		goto failed;
543	}
544
545	/* Configure address space */
546	dinfo = device_get_ivars(sc->bus_dev);
547	dinfo->addrspace = BHNDB_ADDRSPACE_BRIDGED;
548
549	/* Finish attach */
550	return (bus_generic_attach(dev));
551
552failed:
553	BHNDB_LOCK_DESTROY(sc);
554
555	if (sc->bus_res != NULL)
556		bhndb_free_resources(sc->bus_res);
557
558	return (error);
559}
560
561/**
562 * Default bhndb(4) implementation of BHNDB_INIT_FULL_CONFIG().
563 *
564 * This function provides the default bhndb implementation of
565 * BHNDB_INIT_FULL_CONFIG(), and must be called by any subclass driver
566 * overriding BHNDB_INIT_FULL_CONFIG().
567 *
568 * As documented by BHNDB_INIT_FULL_CONFIG, this function performs final
569 * bridge configuration based on the hardware information enumerated by the
570 * child bus, and will reset all resource allocation state on the bridge.
571 *
572 * When calling this method:
573 * - Any bus resources previously allocated by @p child must be deallocated.
574 * - The @p child bus must have performed initial enumeration -- but not
575 *   probe or attachment -- of its children.
576 */
577int
578bhndb_generic_init_full_config(device_t dev, device_t child,
579    const struct bhndb_hw_priority *hw_prio_table)
580{
581	struct bhndb_softc		*sc;
582	const struct bhndb_hw		*hw;
583	struct bhndb_resources		*r;
584	device_t			*devs;
585	device_t			 hostb;
586	int				 ndevs;
587	int				 error;
588
589	sc = device_get_softc(dev);
590	hostb = NULL;
591
592	/* Fetch the full set of bhnd-attached cores */
593	if ((error = device_get_children(sc->bus_dev, &devs, &ndevs)))
594		return (error);
595
596	/* Find our host bridge device */
597	hostb = BHNDB_FIND_HOSTB_DEVICE(dev, child);
598	if (hostb == NULL) {
599		device_printf(sc->dev, "no host bridge core found\n");
600		error = ENODEV;
601		goto cleanup;
602	}
603
604	/* Find our full register window configuration */
605	if ((error = bhndb_find_hwspec(sc, devs, ndevs, &hw))) {
606		device_printf(sc->dev, "unable to identify device, "
607			" using generic bridge resource definitions\n");
608		error = 0;
609		goto cleanup;
610	}
611
612	if (bootverbose)
613		device_printf(sc->dev, "%s resource configuration\n", hw->name);
614
615	/* Release existing resource state */
616	BHNDB_LOCK(sc);
617	bhndb_free_resources(sc->bus_res);
618	sc->bus_res = NULL;
619	BHNDB_UNLOCK(sc);
620
621	/* Allocate new resource state */
622	r = bhndb_alloc_resources(dev, sc->parent_dev, hw->cfg);
623	if (r == NULL) {
624		error = ENXIO;
625		goto cleanup;
626	}
627
628	/* Initialize our resource priority configuration */
629	error = bhndb_initialize_region_cfg(sc, devs, ndevs, hw_prio_table, r);
630	if (error) {
631		bhndb_free_resources(r);
632		goto cleanup;
633	}
634
635	/* Update our bridge state */
636	BHNDB_LOCK(sc);
637	sc->bus_res = r;
638	sc->hostb_dev = hostb;
639	BHNDB_UNLOCK(sc);
640
641cleanup:
642	free(devs, M_TEMP);
643	return (error);
644}
645
646/**
647 * Default bhndb(4) implementation of DEVICE_DETACH().
648 *
649 * This function detaches any child devices, and if successful, releases all
650 * resources held by the bridge device.
651 */
652int
653bhndb_generic_detach(device_t dev)
654{
655	struct bhndb_softc	*sc;
656	int			 error;
657
658	sc = device_get_softc(dev);
659
660	/* Detach children */
661	if ((error = bus_generic_detach(dev)))
662		return (error);
663
664	/* Clean up our driver state. */
665	bhndb_free_resources(sc->bus_res);
666
667	BHNDB_LOCK_DESTROY(sc);
668
669	return (0);
670}
671
672/**
673 * Default bhndb(4) implementation of DEVICE_SUSPEND().
674 *
675 * This function calls bus_generic_suspend() (or implements equivalent
676 * behavior).
677 */
678int
679bhndb_generic_suspend(device_t dev)
680{
681	return (bus_generic_suspend(dev));
682}
683
684/**
685 * Default bhndb(4) implementation of DEVICE_RESUME().
686 *
687 * This function calls bus_generic_resume() (or implements equivalent
688 * behavior).
689 */
690int
691bhndb_generic_resume(device_t dev)
692{
693	struct bhndb_softc	*sc;
694	struct bhndb_resources	*bus_res;
695	struct bhndb_dw_alloc	*dwa;
696	int			 error;
697
698	sc = device_get_softc(dev);
699	bus_res = sc->bus_res;
700
701	/* Guarantee that all in-use dynamic register windows are mapped to
702	 * their previously configured target address. */
703	BHNDB_LOCK(sc);
704	for (size_t i = 0; i < bus_res->dwa_count; i++) {
705		dwa = &bus_res->dw_alloc[i];
706
707		/* Skip regions that were not previously used */
708		if (bhndb_dw_is_free(bus_res, dwa) && dwa->target == 0x0)
709			continue;
710
711		/* Otherwise, ensure the register window is correct before
712		 * any children attempt MMIO */
713		error = BHNDB_SET_WINDOW_ADDR(dev, dwa->win, dwa->target);
714		if (error)
715			break;
716	}
717	BHNDB_UNLOCK(sc);
718
719	/* Error restoring hardware state; children cannot be safely resumed */
720	if (error) {
721		device_printf(dev, "Unable to restore hardware configuration; "
722		    "cannot resume: %d\n", error);
723		return (error);
724	}
725
726	return (bus_generic_resume(dev));
727}
728
729/**
730 * Default implementation of BHNDB_SUSPEND_RESOURCE.
731 */
732static void
733bhndb_suspend_resource(device_t dev, device_t child, int type,
734    struct resource *r)
735{
736	struct bhndb_softc	*sc;
737	struct bhndb_dw_alloc	*dwa;
738
739	sc = device_get_softc(dev);
740
741	// TODO: IRQs?
742	if (type != SYS_RES_MEMORY)
743		return;
744
745	BHNDB_LOCK(sc);
746	dwa = bhndb_dw_find_resource(sc->bus_res, r);
747	if (dwa == NULL) {
748		BHNDB_UNLOCK(sc);
749		return;
750	}
751
752	if (BHNDB_DEBUG(PRIO))
753		device_printf(child, "suspend resource type=%d 0x%jx+0x%jx\n",
754		    type, rman_get_start(r), rman_get_size(r));
755
756	/* Release the resource's window reference */
757	bhndb_dw_release(sc->bus_res, dwa, r);
758	BHNDB_UNLOCK(sc);
759}
760
761/**
762 * Default implementation of BHNDB_RESUME_RESOURCE.
763 */
764static int
765bhndb_resume_resource(device_t dev, device_t child, int type,
766    struct resource *r)
767{
768	struct bhndb_softc	*sc;
769
770	sc = device_get_softc(dev);
771
772	// TODO: IRQs?
773	if (type != SYS_RES_MEMORY)
774		return (0);
775
776	/* Inactive resources don't require reallocation of bridge resources */
777	if (!(rman_get_flags(r) & RF_ACTIVE))
778		return (0);
779
780	if (BHNDB_DEBUG(PRIO))
781		device_printf(child, "resume resource type=%d 0x%jx+0x%jx\n",
782		    type, rman_get_start(r), rman_get_size(r));
783
784	return (bhndb_try_activate_resource(sc, rman_get_device(r), type,
785	    rman_get_rid(r), r, NULL));
786}
787
788
789/**
790 * Default bhndb(4) implementation of BUS_READ_IVAR().
791 */
792static int
793bhndb_read_ivar(device_t dev, device_t child, int index,
794    uintptr_t *result)
795{
796	return (ENOENT);
797}
798
799/**
800 * Default bhndb(4) implementation of BUS_WRITE_IVAR().
801 */
802static int
803bhndb_write_ivar(device_t dev, device_t child, int index,
804    uintptr_t value)
805{
806	return (ENOENT);
807}
808
809/**
810 * Return the address space for the given @p child device.
811 */
812bhndb_addrspace
813bhndb_get_addrspace(struct bhndb_softc *sc, device_t child)
814{
815	struct bhndb_devinfo	*dinfo;
816	device_t		 imd_dev;
817
818	/* Find the directly attached parent of the requesting device */
819	imd_dev = child;
820	while (imd_dev != NULL && device_get_parent(imd_dev) != sc->dev)
821		imd_dev = device_get_parent(imd_dev);
822
823	if (imd_dev == NULL)
824		panic("bhndb address space request for non-child device %s\n",
825		     device_get_nameunit(child));
826
827	dinfo = device_get_ivars(imd_dev);
828	return (dinfo->addrspace);
829}
830
831/**
832 * Return the rman instance for a given resource @p type, if any.
833 *
834 * @param sc The bhndb device state.
835 * @param child The requesting child.
836 * @param type The resource type (e.g. SYS_RES_MEMORY, SYS_RES_IRQ, ...)
837 */
838static struct rman *
839bhndb_get_rman(struct bhndb_softc *sc, device_t child, int type)
840{
841	switch (bhndb_get_addrspace(sc, child)) {
842	case BHNDB_ADDRSPACE_NATIVE:
843		switch (type) {
844		case SYS_RES_MEMORY:
845			return (&sc->bus_res->ht_mem_rman);
846		case SYS_RES_IRQ:
847			return (NULL);
848		default:
849			return (NULL);
850		};
851
852	case BHNDB_ADDRSPACE_BRIDGED:
853		switch (type) {
854		case SYS_RES_MEMORY:
855			return (&sc->bus_res->br_mem_rman);
856		case SYS_RES_IRQ:
857			// TODO
858			// return &sc->irq_rman;
859			return (NULL);
860		default:
861			return (NULL);
862		};
863	}
864
865	/* Quieten gcc */
866	return (NULL);
867}
868
869/**
870 * Default implementation of BUS_ADD_CHILD()
871 */
872static device_t
873bhndb_add_child(device_t dev, u_int order, const char *name, int unit)
874{
875	struct bhndb_devinfo	*dinfo;
876	device_t		 child;
877
878	child = device_add_child_ordered(dev, order, name, unit);
879	if (child == NULL)
880		return (NULL);
881
882	dinfo = malloc(sizeof(struct bhndb_devinfo), M_BHND, M_NOWAIT);
883	if (dinfo == NULL) {
884		device_delete_child(dev, child);
885		return (NULL);
886	}
887
888	dinfo->addrspace = BHNDB_ADDRSPACE_NATIVE;
889	resource_list_init(&dinfo->resources);
890
891	device_set_ivars(child, dinfo);
892
893	return (child);
894}
895
896/**
897 * Default implementation of BUS_CHILD_DELETED().
898 */
899static void
900bhndb_child_deleted(device_t dev, device_t child)
901{
902	struct bhndb_devinfo *dinfo = device_get_ivars(child);
903	if (dinfo != NULL) {
904		resource_list_free(&dinfo->resources);
905		free(dinfo, M_BHND);
906	}
907
908	device_set_ivars(child, NULL);
909}
910
911/**
912 * Default implementation of BHNDB_GET_CHIPID().
913 */
914static const struct bhnd_chipid *
915bhndb_get_chipid(device_t dev, device_t child)
916{
917	struct bhndb_softc *sc = device_get_softc(dev);
918	return (&sc->chipid);
919}
920
921
922/**
923 * Default implementation of BHNDB_IS_HW_DISABLED().
924 */
925static bool
926bhndb_is_hw_disabled(device_t dev, device_t child) {
927	struct bhndb_softc	*sc;
928	struct bhnd_core_info	 core;
929
930	sc = device_get_softc(dev);
931
932	/* Requestor must be attached to the bhnd bus */
933	if (device_get_parent(child) != sc->bus_dev) {
934		return (BHND_BUS_IS_HW_DISABLED(device_get_parent(dev), child));
935	}
936
937	/* Fetch core info */
938	core = bhnd_get_core_info(child);
939
940	/* Try to defer to the bhndb bus parent */
941	if (BHNDB_BUS_IS_CORE_DISABLED(sc->parent_dev, dev, &core))
942		return (true);
943
944	/* Otherwise, we treat bridge-capable cores as unpopulated if they're
945	 * not the configured host bridge */
946	if (BHND_DEVCLASS_SUPPORTS_HOSTB(bhnd_core_class(&core)))
947		return (BHNDB_FIND_HOSTB_DEVICE(dev, sc->bus_dev) != child);
948
949	/* Otherwise, assume the core is populated */
950	return (false);
951}
952
953/* ascending core index comparison used by bhndb_find_hostb_device() */
954static int
955compare_core_index(const void *lhs, const void *rhs)
956{
957	u_int left = bhnd_get_core_index(*(const device_t *) lhs);
958	u_int right = bhnd_get_core_index(*(const device_t *) rhs);
959
960	if (left < right)
961		return (-1);
962	else if (left > right)
963		return (1);
964	else
965		return (0);
966}
967
968/**
969 * Default bhndb(4) implementation of BHND_BUS_FIND_HOSTB_DEVICE().
970 *
971 * This function uses a heuristic valid on all known PCI/PCIe/PCMCIA-bridged
972 * bhnd(4) devices to determine the hostb core:
973 *
974 * - The core must have a Broadcom vendor ID.
975 * - The core devclass must match the bridge type.
976 * - The core must be the first device on the bus with the bridged device
977 *   class.
978 *
979 * @param dev The bhndb device
980 * @param child The requesting bhnd bus.
981 */
982static device_t
983bhndb_find_hostb_device(device_t dev, device_t child)
984{
985	struct bhndb_softc	*sc;
986	struct bhnd_core_match	 md;
987	device_t		 hostb_dev, *devlist;
988	int                      devcnt, error;
989
990	sc = device_get_softc(dev);
991
992	/* Determine required device class and set up a match descriptor. */
993	md = (struct bhnd_core_match) {
994		.vendor = BHND_MFGID_BCM,
995		.device = BHND_COREID_INVALID,
996		.hwrev = { BHND_HWREV_INVALID, BHND_HWREV_INVALID },
997		.class = sc->bridge_class,
998		.unit = 0
999	};
1000
1001	/* Must be the absolute first matching device on the bus. */
1002	if ((error = device_get_children(child, &devlist, &devcnt)))
1003		return (false);
1004
1005	/* Sort by core index value, ascending */
1006	qsort(devlist, devcnt, sizeof(*devlist), compare_core_index);
1007
1008	/* Find the hostb device */
1009	hostb_dev = NULL;
1010	for (int i = 0; i < devcnt; i++) {
1011		if (bhnd_device_matches(devlist[i], &md)) {
1012			hostb_dev = devlist[i];
1013			break;
1014		}
1015	}
1016
1017	/* Clean up */
1018	free(devlist, M_TEMP);
1019
1020	return (hostb_dev);
1021}
1022
1023/**
1024 * Default bhndb(4) implementation of BUS_ALLOC_RESOURCE().
1025 */
1026static struct resource *
1027bhndb_alloc_resource(device_t dev, device_t child, int type,
1028    int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1029{
1030	struct bhndb_softc		*sc;
1031	struct resource_list_entry	*rle;
1032	struct resource			*rv;
1033	struct rman			*rm;
1034	int				 error;
1035	bool				 passthrough, isdefault;
1036
1037	sc = device_get_softc(dev);
1038	passthrough = (device_get_parent(child) != dev);
1039	isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
1040	rle = NULL;
1041
1042	/* Populate defaults */
1043	if (!passthrough && isdefault) {
1044		/* Fetch the resource list entry. */
1045		rle = resource_list_find(BUS_GET_RESOURCE_LIST(dev, child),
1046		    type, *rid);
1047		if (rle == NULL) {
1048			device_printf(dev,
1049			    "default resource %#x type %d for child %s "
1050			    "not found\n", *rid, type,
1051			    device_get_nameunit(child));
1052
1053			return (NULL);
1054		}
1055
1056		if (rle->res != NULL) {
1057			device_printf(dev,
1058			    "resource entry %#x type %d for child %s is busy\n",
1059			    *rid, type, device_get_nameunit(child));
1060
1061			return (NULL);
1062		}
1063
1064		start = rle->start;
1065		end = rle->end;
1066		count = ulmax(count, rle->count);
1067	}
1068
1069	/* Validate resource addresses */
1070	if (start > end || count > ((end - start) + 1))
1071		return (NULL);
1072
1073	/* Fetch the resource manager */
1074	rm = bhndb_get_rman(sc, child, type);
1075	if (rm == NULL)
1076		return (NULL);
1077
1078	/* Make our reservation */
1079	rv = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
1080	    child);
1081	if (rv == NULL)
1082		return (NULL);
1083
1084	rman_set_rid(rv, *rid);
1085
1086	/* Activate */
1087	if (flags & RF_ACTIVE) {
1088		error = bus_activate_resource(child, type, *rid, rv);
1089		if (error) {
1090			device_printf(dev,
1091			    "failed to activate entry %#x type %d for "
1092				"child %s: %d\n",
1093			     *rid, type, device_get_nameunit(child), error);
1094
1095			rman_release_resource(rv);
1096
1097			return (NULL);
1098		}
1099	}
1100
1101	/* Update child's resource list entry */
1102	if (rle != NULL) {
1103		rle->res = rv;
1104		rle->start = rman_get_start(rv);
1105		rle->end = rman_get_end(rv);
1106		rle->count = rman_get_size(rv);
1107	}
1108
1109	return (rv);
1110}
1111
1112/**
1113 * Default bhndb(4) implementation of BUS_RELEASE_RESOURCE().
1114 */
1115static int
1116bhndb_release_resource(device_t dev, device_t child, int type, int rid,
1117    struct resource *r)
1118{
1119	int error;
1120
1121	/* Deactivate resources */
1122	if (rman_get_flags(r) & RF_ACTIVE) {
1123		error = BUS_DEACTIVATE_RESOURCE(dev, child, type, rid, r);
1124		if (error)
1125			return (error);
1126	}
1127
1128	if ((error = rman_release_resource(r)))
1129		return (error);
1130
1131	return (0);
1132}
1133
1134/**
1135 * Default bhndb(4) implementation of BUS_ADJUST_RESOURCE().
1136 */
1137static int
1138bhndb_adjust_resource(device_t dev, device_t child, int type,
1139    struct resource *r, rman_res_t start, rman_res_t end)
1140{
1141	struct bhndb_softc		*sc;
1142	struct rman			*rm;
1143	int				 error;
1144
1145	sc = device_get_softc(dev);
1146	error = 0;
1147
1148	/* Fetch resource manager */
1149	rm = bhndb_get_rman(sc, child, type);
1150	if (rm == NULL)
1151		return (ENXIO);
1152
1153	if (!rman_is_region_manager(r, rm))
1154		return (ENXIO);
1155
1156	/* If active, adjustment is limited by the assigned window. */
1157	BHNDB_LOCK(sc);
1158
1159	// TODO: Currently unsupported
1160	error = ENODEV;
1161
1162	BHNDB_UNLOCK(sc);
1163	if (!error)
1164		error = rman_adjust_resource(r, start, end);
1165
1166	return (error);
1167}
1168
1169/**
1170 * Initialize child resource @p r with a virtual address, tag, and handle
1171 * copied from @p parent, adjusted to contain only the range defined by
1172 * @p offsize and @p size.
1173 *
1174 * @param r The register to be initialized.
1175 * @param parent The parent bus resource that fully contains the subregion.
1176 * @param offset The subregion offset within @p parent.
1177 * @param size The subregion size.
1178 * @p r.
1179 */
1180static int
1181bhndb_init_child_resource(struct resource *r,
1182    struct resource *parent, bhnd_size_t offset, bhnd_size_t size)
1183{
1184	bus_space_handle_t	bh, child_bh;
1185	bus_space_tag_t		bt;
1186	uintptr_t		vaddr;
1187	int			error;
1188
1189	/* Fetch the parent resource's real bus values */
1190	vaddr = (uintptr_t) rman_get_virtual(parent);
1191	bt = rman_get_bustag(parent);
1192	bh = rman_get_bushandle(parent);
1193
1194	/* Configure child resource with window-adjusted real bus values */
1195	vaddr += offset;
1196	error = bus_space_subregion(bt, bh, offset, size, &child_bh);
1197	if (error)
1198		return (error);
1199
1200	rman_set_virtual(r, (void *) vaddr);
1201	rman_set_bustag(r, bt);
1202	rman_set_bushandle(r, child_bh);
1203
1204	return (0);
1205}
1206
1207/**
1208 * Attempt activation of a fixed register window mapping for @p child.
1209 *
1210 * @param sc BHNDB device state.
1211 * @param region The static region definition capable of mapping @p r.
1212 * @param child A child requesting resource activation.
1213 * @param type Resource type.
1214 * @param rid Resource identifier.
1215 * @param r Resource to be activated.
1216 *
1217 * @retval 0 if @p r was activated successfully
1218 * @retval ENOENT if no fixed register window was found.
1219 * @retval non-zero if @p r could not be activated.
1220 */
1221static int
1222bhndb_activate_static_region(struct bhndb_softc *sc,
1223    struct bhndb_region *region, device_t child, int type, int rid,
1224    struct resource *r)
1225{
1226	struct resource			*bridge_res;
1227	const struct bhndb_regwin	*win;
1228	bhnd_size_t			 parent_offset;
1229	rman_res_t			 r_start, r_size;
1230	int				 error;
1231
1232	win = region->static_regwin;
1233
1234	KASSERT(win != NULL && BHNDB_REGWIN_T_IS_STATIC(win->win_type),
1235	    ("can't activate non-static region"));
1236
1237	r_start = rman_get_start(r);
1238	r_size = rman_get_size(r);
1239
1240	/* Find the corresponding bridge resource */
1241	bridge_res = bhndb_find_regwin_resource(sc->bus_res, win);
1242	if (bridge_res == NULL)
1243		return (ENXIO);
1244
1245	/* Calculate subregion offset within the parent resource */
1246	parent_offset = r_start - region->addr;
1247	parent_offset += win->win_offset;
1248
1249	/* Configure resource with its real bus values. */
1250	error = bhndb_init_child_resource(r, bridge_res, parent_offset, r_size);
1251	if (error)
1252		return (error);
1253
1254	/* Mark active */
1255	if ((error = rman_activate_resource(r)))
1256		return (error);
1257
1258	return (0);
1259}
1260
1261/**
1262 * Attempt to allocate/retain a dynamic register window for @p r, returning
1263 * the retained window.
1264 *
1265 * @param sc The bhndb driver state.
1266 * @param r The resource for which a window will be retained.
1267 */
1268static struct bhndb_dw_alloc *
1269bhndb_retain_dynamic_window(struct bhndb_softc *sc, struct resource *r)
1270{
1271	struct bhndb_dw_alloc	*dwa;
1272	rman_res_t		 r_start, r_size;
1273	int			 error;
1274
1275	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1276
1277	r_start = rman_get_start(r);
1278	r_size = rman_get_size(r);
1279
1280	/* Look for an existing dynamic window we can reference */
1281	dwa = bhndb_dw_find_mapping(sc->bus_res, r_start, r_size);
1282	if (dwa != NULL) {
1283		if (bhndb_dw_retain(sc->bus_res, dwa, r) == 0)
1284			return (dwa);
1285
1286		return (NULL);
1287	}
1288
1289	/* Otherwise, try to reserve a free window */
1290	dwa = bhndb_dw_next_free(sc->bus_res);
1291	if (dwa == NULL) {
1292		/* No free windows */
1293		return (NULL);
1294	}
1295
1296	/* Set the window target */
1297	error = bhndb_dw_set_addr(sc->dev, sc->bus_res, dwa, rman_get_start(r),
1298	    rman_get_size(r));
1299	if (error) {
1300		device_printf(sc->dev, "dynamic window initialization "
1301			"for 0x%llx-0x%llx failed\n",
1302			(unsigned long long) r_start,
1303			(unsigned long long) r_start + r_size - 1);
1304		return (NULL);
1305	}
1306
1307	/* Add our reservation */
1308	if (bhndb_dw_retain(sc->bus_res, dwa, r))
1309		return (NULL);
1310
1311	return (dwa);
1312}
1313
1314/**
1315 * Activate a resource using any viable static or dynamic register window.
1316 *
1317 * @param sc The bhndb driver state.
1318 * @param child The child holding ownership of @p r.
1319 * @param type The type of the resource to be activated.
1320 * @param rid The resource ID of @p r.
1321 * @param r The resource to be activated
1322 * @param[out] indirect On error and if not NULL, will be set to 'true' if
1323 * the caller should instead use an indirect resource mapping.
1324 *
1325 * @retval 0 success
1326 * @retval non-zero activation failed.
1327 */
1328static int
1329bhndb_try_activate_resource(struct bhndb_softc *sc, device_t child, int type,
1330    int rid, struct resource *r, bool *indirect)
1331{
1332	struct bhndb_region	*region;
1333	struct bhndb_dw_alloc	*dwa;
1334	bhndb_priority_t	 dw_priority;
1335	rman_res_t		 r_start, r_size;
1336	rman_res_t		 parent_offset;
1337	int			 error;
1338
1339	BHNDB_LOCK_ASSERT(sc, MA_NOTOWNED);
1340
1341	// TODO - IRQs
1342	if (type != SYS_RES_MEMORY)
1343		return (ENXIO);
1344
1345	if (indirect)
1346		*indirect = false;
1347
1348	r_start = rman_get_start(r);
1349	r_size = rman_get_size(r);
1350
1351	/* Activate native addrspace resources using the host address space */
1352	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_NATIVE) {
1353		struct resource *parent;
1354
1355		/* Find the bridge resource referenced by the child */
1356		parent = bhndb_find_resource_range(sc->bus_res, r_start,
1357		    r_size);
1358		if (parent == NULL) {
1359			device_printf(sc->dev, "host resource not found "
1360			     "for 0x%llx-0x%llx\n",
1361			     (unsigned long long) r_start,
1362			     (unsigned long long) r_start + r_size - 1);
1363			return (ENOENT);
1364		}
1365
1366		/* Initialize child resource with the real bus values */
1367		error = bhndb_init_child_resource(r, parent,
1368		    r_start - rman_get_start(parent), r_size);
1369		if (error)
1370			return (error);
1371
1372		/* Try to activate child resource */
1373		return (rman_activate_resource(r));
1374	}
1375
1376	/* Default to low priority */
1377	dw_priority = BHNDB_PRIORITY_LOW;
1378
1379	/* Look for a bus region matching the resource's address range */
1380	region = bhndb_find_resource_region(sc->bus_res, r_start, r_size);
1381	if (region != NULL)
1382		dw_priority = region->priority;
1383
1384	/* Prefer static mappings over consuming a dynamic windows. */
1385	if (region && region->static_regwin) {
1386		error = bhndb_activate_static_region(sc, region, child, type,
1387		    rid, r);
1388		if (error)
1389			device_printf(sc->dev, "static window allocation "
1390			     "for 0x%llx-0x%llx failed\n",
1391			     (unsigned long long) r_start,
1392			     (unsigned long long) r_start + r_size - 1);
1393		return (error);
1394	}
1395
1396	/* A dynamic window will be required; is this resource high enough
1397	 * priority to be reserved a dynamic window? */
1398	if (dw_priority < sc->bus_res->min_prio) {
1399		if (indirect)
1400			*indirect = true;
1401
1402		return (ENOMEM);
1403	}
1404
1405	/* Find and retain a usable window */
1406	BHNDB_LOCK(sc); {
1407		dwa = bhndb_retain_dynamic_window(sc, r);
1408	} BHNDB_UNLOCK(sc);
1409
1410	if (dwa == NULL) {
1411		if (indirect)
1412			*indirect = true;
1413		return (ENOMEM);
1414	}
1415
1416	/* Configure resource with its real bus values. */
1417	parent_offset = dwa->win->win_offset;
1418	parent_offset += r_start - dwa->target;
1419
1420	error = bhndb_init_child_resource(r, dwa->parent_res, parent_offset,
1421	    dwa->win->win_size);
1422	if (error)
1423		goto failed;
1424
1425	/* Mark active */
1426	if ((error = rman_activate_resource(r)))
1427		goto failed;
1428
1429	return (0);
1430
1431failed:
1432	/* Release our region allocation. */
1433	BHNDB_LOCK(sc);
1434	bhndb_dw_release(sc->bus_res, dwa, r);
1435	BHNDB_UNLOCK(sc);
1436
1437	return (error);
1438}
1439
1440/**
1441 * Default bhndb(4) implementation of BUS_ACTIVATE_RESOURCE().
1442 *
1443 * Maps resource activation requests to a viable static or dynamic
1444 * register window, if any.
1445 */
1446static int
1447bhndb_activate_resource(device_t dev, device_t child, int type, int rid,
1448    struct resource *r)
1449{
1450	struct bhndb_softc *sc = device_get_softc(dev);
1451
1452	return (bhndb_try_activate_resource(sc, child, type, rid, r, NULL));
1453}
1454
1455/**
1456 * Default bhndb(4) implementation of BUS_DEACTIVATE_RESOURCE().
1457 */
1458static int
1459bhndb_deactivate_resource(device_t dev, device_t child, int type,
1460    int rid, struct resource *r)
1461{
1462	struct bhndb_dw_alloc	*dwa;
1463	struct bhndb_softc	*sc;
1464	struct rman		*rm;
1465	int			 error;
1466
1467	sc = device_get_softc(dev);
1468
1469	if ((rm = bhndb_get_rman(sc, child, type)) == NULL)
1470		return (EINVAL);
1471
1472	/* Mark inactive */
1473	if ((error = rman_deactivate_resource(r)))
1474		return (error);
1475
1476	/* Free any dynamic window allocation. */
1477	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED) {
1478		BHNDB_LOCK(sc);
1479		dwa = bhndb_dw_find_resource(sc->bus_res, r);
1480		if (dwa != NULL)
1481			bhndb_dw_release(sc->bus_res, dwa, r);
1482		BHNDB_UNLOCK(sc);
1483	}
1484
1485	return (0);
1486}
1487
1488/**
1489 * Default bhndb(4) implementation of BUS_GET_RESOURCE_LIST().
1490 */
1491static struct resource_list *
1492bhndb_get_resource_list(device_t dev, device_t child)
1493{
1494	struct bhndb_devinfo *dinfo = device_get_ivars(child);
1495	return (&dinfo->resources);
1496}
1497
1498/**
1499 * Default bhndb(4) implementation of BHND_BUS_ACTIVATE_RESOURCE().
1500 *
1501 * For BHNDB_ADDRSPACE_NATIVE children, all resources may be assumed to
1502 * be activated by the bridge.
1503 *
1504 * For BHNDB_ADDRSPACE_BRIDGED children, attempts to activate a static register
1505 * window, a dynamic register window, or configures @p r as an indirect
1506 * resource -- in that order.
1507 */
1508static int
1509bhndb_activate_bhnd_resource(device_t dev, device_t child,
1510    int type, int rid, struct bhnd_resource *r)
1511{
1512	struct bhndb_softc	*sc;
1513	struct bhndb_region	*region;
1514	rman_res_t		 r_start, r_size;
1515	int 			 error;
1516	bool			 indirect;
1517
1518	KASSERT(!r->direct,
1519	    ("direct flag set on inactive resource"));
1520
1521	KASSERT(!(rman_get_flags(r->res) & RF_ACTIVE),
1522	    ("RF_ACTIVE set on inactive resource"));
1523
1524	sc = device_get_softc(dev);
1525
1526	r_start = rman_get_start(r->res);
1527	r_size = rman_get_size(r->res);
1528
1529	/* Verify bridged address range's resource priority, and skip direct
1530	 * allocation if the priority is too low. */
1531	if (bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED) {
1532		bhndb_priority_t r_prio;
1533
1534		region = bhndb_find_resource_region(sc->bus_res, r_start, r_size);
1535		if (region != NULL)
1536			r_prio = region->priority;
1537		else
1538			r_prio = BHNDB_PRIORITY_NONE;
1539
1540		/* If less than the minimum dynamic window priority, this
1541		 * resource should always be indirect. */
1542		if (r_prio < sc->bus_res->min_prio)
1543			return (0);
1544	}
1545
1546	/* Attempt direct activation */
1547	error = bhndb_try_activate_resource(sc, child, type, rid, r->res,
1548	    &indirect);
1549	if (!error) {
1550		r->direct = true;
1551	} else if (indirect) {
1552		/* The request was valid, but no viable register window is
1553		 * available; indirection must be employed. */
1554		error = 0;
1555		r->direct = false;
1556	}
1557
1558	if (BHNDB_DEBUG(PRIO) &&
1559	    bhndb_get_addrspace(sc, child) == BHNDB_ADDRSPACE_BRIDGED)
1560	{
1561		device_printf(child, "activated 0x%llx-0x%llx as %s "
1562		    "resource\n",
1563		    (unsigned long long) r_start,
1564		    (unsigned long long) r_start + r_size - 1,
1565		    r->direct ? "direct" : "indirect");
1566	}
1567
1568	return (error);
1569};
1570
1571/**
1572 * Default bhndb(4) implementation of BHND_BUS_DEACTIVATE_RESOURCE().
1573 */
1574static int
1575bhndb_deactivate_bhnd_resource(device_t dev, device_t child,
1576    int type, int rid, struct bhnd_resource *r)
1577{
1578	int error;
1579
1580	/* Indirect resources don't require activation */
1581	if (!r->direct)
1582		return (0);
1583
1584	KASSERT(rman_get_flags(r->res) & RF_ACTIVE,
1585	    ("RF_ACTIVE not set on direct resource"));
1586
1587	/* Perform deactivation */
1588	error = bus_deactivate_resource(child, type, rid, r->res);
1589	if (!error)
1590		r->direct = false;
1591
1592	return (error);
1593};
1594
1595/**
1596 * Slow path for bhndb_io_resource().
1597 *
1598 * Iterates over the existing allocated dynamic windows looking for a viable
1599 * in-use region; the first matching region is returned.
1600 */
1601static struct bhndb_dw_alloc *
1602bhndb_io_resource_slow(struct bhndb_softc *sc, bus_addr_t addr,
1603    bus_size_t size, bus_size_t *offset)
1604{
1605	struct bhndb_resources	*br;
1606	struct bhndb_dw_alloc	*dwa;
1607
1608	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1609
1610	br = sc->bus_res;
1611
1612	/* Search for an existing dynamic mapping of this address range.
1613	 * Static regions are not searched, as a statically mapped
1614	 * region would never be allocated as an indirect resource. */
1615	for (size_t i = 0; i < br->dwa_count; i++) {
1616		const struct bhndb_regwin *win;
1617
1618		dwa = &br->dw_alloc[i];
1619		win = dwa->win;
1620
1621		KASSERT(win->win_type == BHNDB_REGWIN_T_DYN,
1622			("invalid register window type"));
1623
1624		/* Verify the range */
1625		if (addr < dwa->target)
1626			continue;
1627
1628		if (addr + size > dwa->target + win->win_size)
1629			continue;
1630
1631		/* Found */
1632		*offset = dwa->win->win_offset;
1633		*offset += addr - dwa->target;
1634
1635		return (dwa);
1636	}
1637
1638	/* not found */
1639	return (NULL);
1640}
1641
1642/**
1643 * Find the bridge resource to be used for I/O requests.
1644 *
1645 * @param sc Bridge driver state.
1646 * @param addr The I/O target address.
1647 * @param size The size of the I/O operation to be performed at @p addr.
1648 * @param[out] offset The offset within the returned resource at which
1649 * to perform the I/O request.
1650 */
1651static inline struct bhndb_dw_alloc *
1652bhndb_io_resource(struct bhndb_softc *sc, bus_addr_t addr, bus_size_t size,
1653    bus_size_t *offset)
1654{
1655	struct bhndb_resources	*br;
1656	struct bhndb_dw_alloc	*dwa;
1657	int			 error;
1658
1659	BHNDB_LOCK_ASSERT(sc, MA_OWNED);
1660
1661	br = sc->bus_res;
1662
1663	/* Try to fetch a free window */
1664	dwa = bhndb_dw_next_free(br);
1665
1666	/*
1667	 * If no dynamic windows are available, look for an existing
1668	 * region that maps the target range.
1669	 *
1670	 * If none are found, this is a child driver bug -- our window
1671	 * over-commit should only fail in the case where a child driver leaks
1672	 * resources, or perform operations out-of-order.
1673	 *
1674	 * Broadcom HND chipsets are designed to not require register window
1675	 * swapping during execution; as long as the child devices are
1676	 * attached/detached correctly, using the hardware's required order
1677	 * of operations, there should always be a window available for the
1678	 * current operation.
1679	 */
1680	if (dwa == NULL) {
1681		dwa = bhndb_io_resource_slow(sc, addr, size, offset);
1682		if (dwa == NULL) {
1683			panic("register windows exhausted attempting to map "
1684			    "0x%llx-0x%llx\n",
1685			    (unsigned long long) addr,
1686			    (unsigned long long) addr+size-1);
1687		}
1688
1689		return (dwa);
1690	}
1691
1692	/* Adjust the window if the I/O request won't fit in the current
1693	 * target range. */
1694	if (addr < dwa->target ||
1695	   (dwa->target + dwa->win->win_size) - addr < size)
1696	{
1697		error = bhndb_dw_set_addr(sc->dev, sc->bus_res, dwa, addr,
1698		    size);
1699		if (error) {
1700		    panic("failed to set register window target mapping "
1701			    "0x%llx-0x%llx\n",
1702			    (unsigned long long) addr,
1703			    (unsigned long long) addr+size-1);
1704		}
1705	}
1706
1707	/* Calculate the offset and return */
1708	*offset = (addr - dwa->target) + dwa->win->win_offset;
1709	return (dwa);
1710}
1711
1712/*
1713 * BHND_BUS_(READ|WRITE_* implementations
1714 */
1715
1716/* bhndb_bus_(read|write) common implementation */
1717#define	BHNDB_IO_COMMON_SETUP(_io_size)				\
1718	struct bhndb_softc	*sc;				\
1719	struct bhndb_dw_alloc	*dwa;				\
1720	struct resource		*io_res;			\
1721	bus_size_t		 io_offset;			\
1722								\
1723	sc = device_get_softc(dev);				\
1724								\
1725	BHNDB_LOCK(sc);						\
1726	dwa = bhndb_io_resource(sc, rman_get_start(r->res) +	\
1727	    offset, _io_size, &io_offset);			\
1728	io_res = dwa->parent_res;				\
1729								\
1730	KASSERT(!r->direct,					\
1731	    ("bhnd_bus slow path used for direct resource"));	\
1732								\
1733	KASSERT(rman_get_flags(io_res) & RF_ACTIVE,		\
1734	    ("i/o resource is not active"));
1735
1736#define	BHNDB_IO_COMMON_TEARDOWN()				\
1737	BHNDB_UNLOCK(sc);
1738
1739/* Defines a bhndb_bus_read_* method implementation */
1740#define	BHNDB_IO_READ(_type, _size)				\
1741static _type							\
1742bhndb_bus_read_ ## _size (device_t dev, device_t child,		\
1743    struct bhnd_resource *r, bus_size_t offset)			\
1744{								\
1745	_type v;						\
1746	BHNDB_IO_COMMON_SETUP(sizeof(_type));			\
1747	v = bus_read_ ## _size (io_res, io_offset);		\
1748	BHNDB_IO_COMMON_TEARDOWN();				\
1749								\
1750	return (v);						\
1751}
1752
1753/* Defines a bhndb_bus_write_* method implementation */
1754#define	BHNDB_IO_WRITE(_type, _size)				\
1755static void							\
1756bhndb_bus_write_ ## _size (device_t dev, device_t child,	\
1757    struct bhnd_resource *r, bus_size_t offset, _type value)	\
1758{								\
1759	BHNDB_IO_COMMON_SETUP(sizeof(_type));			\
1760	bus_write_ ## _size (io_res, io_offset, value);		\
1761	BHNDB_IO_COMMON_TEARDOWN();				\
1762}
1763
1764BHNDB_IO_READ(uint8_t, 1);
1765BHNDB_IO_READ(uint16_t, 2);
1766BHNDB_IO_READ(uint32_t, 4);
1767
1768BHNDB_IO_WRITE(uint8_t, 1);
1769BHNDB_IO_WRITE(uint16_t, 2);
1770BHNDB_IO_WRITE(uint32_t, 4);
1771
1772/**
1773 * Default bhndb(4) implementation of BHND_BUS_BARRIER().
1774 */
1775static void
1776bhndb_bus_barrier(device_t dev, device_t child, struct bhnd_resource *r,
1777    bus_size_t offset, bus_size_t length, int flags)
1778{
1779	bus_size_t remain;
1780
1781	BHNDB_IO_COMMON_SETUP(length);
1782
1783	/* TODO: It's unclear whether we need a barrier implementation,
1784	 * and if we do, what it needs to actually do. This may need
1785	 * revisiting once we have a better idea of requirements after
1786	 * porting the core drivers. */
1787	panic("implementation incorrect");
1788
1789	/* Use 4-byte reads where possible */
1790	remain = length % sizeof(uint32_t);
1791	for (bus_size_t i = 0; i < (length - remain); i += 4)
1792		bus_read_4(io_res, io_offset + offset + i);
1793
1794	/* Use 1 byte reads for the remainder */
1795	for (bus_size_t i = 0; i < remain; i++)
1796		bus_read_1(io_res, io_offset + offset + length + i);
1797
1798	BHNDB_IO_COMMON_TEARDOWN();
1799}
1800
1801/**
1802 * Default bhndb(4) implementation of BUS_SETUP_INTR().
1803 */
1804static int
1805bhndb_setup_intr(device_t dev, device_t child, struct resource *r,
1806    int flags, driver_filter_t filter, driver_intr_t handler, void *arg,
1807    void **cookiep)
1808{
1809	// TODO
1810	return (EOPNOTSUPP);
1811}
1812
1813/**
1814 * Default bhndb(4) implementation of BUS_TEARDOWN_INTR().
1815 */
1816static int
1817bhndb_teardown_intr(device_t dev, device_t child, struct resource *r,
1818    void *cookie)
1819{
1820	// TODO
1821	return (EOPNOTSUPP);
1822}
1823
1824/**
1825 * Default bhndb(4) implementation of BUS_CONFIG_INTR().
1826 */
1827static int
1828bhndb_config_intr(device_t dev, int irq, enum intr_trigger trig,
1829    enum intr_polarity pol)
1830{
1831	// TODO
1832	return (EOPNOTSUPP);
1833}
1834
1835/**
1836 * Default bhndb(4) implementation of BUS_BIND_INTR().
1837 */
1838static int
1839bhndb_bind_intr(device_t dev, device_t child, struct resource *r, int cpu)
1840{
1841	// TODO
1842	return (EOPNOTSUPP);
1843}
1844
1845/**
1846 * Default bhndb(4) implementation of BUS_DESCRIBE_INTR().
1847 */
1848static int
1849bhndb_describe_intr(device_t dev, device_t child, struct resource *irq, void *cookie,
1850    const char *descr)
1851{
1852	// TODO
1853	return (EOPNOTSUPP);
1854}
1855
1856/**
1857 * Default bhndb(4) implementation of BUS_GET_DMA_TAG().
1858 */
1859static bus_dma_tag_t
1860bhndb_get_dma_tag(device_t dev, device_t child)
1861{
1862	// TODO
1863	return (NULL);
1864}
1865
1866static device_method_t bhndb_methods[] = {
1867	/* Device interface */ \
1868	DEVMETHOD(device_probe,			bhndb_generic_probe),
1869	DEVMETHOD(device_detach,		bhndb_generic_detach),
1870	DEVMETHOD(device_shutdown,		bus_generic_shutdown),
1871	DEVMETHOD(device_suspend,		bhndb_generic_suspend),
1872	DEVMETHOD(device_resume,		bhndb_generic_resume),
1873
1874	/* Bus interface */
1875	DEVMETHOD(bus_probe_nomatch,		bhndb_probe_nomatch),
1876	DEVMETHOD(bus_print_child,		bhndb_print_child),
1877	DEVMETHOD(bus_child_pnpinfo_str,	bhndb_child_pnpinfo_str),
1878	DEVMETHOD(bus_child_location_str,	bhndb_child_location_str),
1879	DEVMETHOD(bus_add_child,		bhndb_add_child),
1880	DEVMETHOD(bus_child_deleted,		bhndb_child_deleted),
1881
1882	DEVMETHOD(bus_alloc_resource,		bhndb_alloc_resource),
1883	DEVMETHOD(bus_release_resource,		bhndb_release_resource),
1884	DEVMETHOD(bus_activate_resource,	bhndb_activate_resource),
1885	DEVMETHOD(bus_deactivate_resource,	bhndb_deactivate_resource),
1886
1887	DEVMETHOD(bus_setup_intr,		bhndb_setup_intr),
1888	DEVMETHOD(bus_teardown_intr,		bhndb_teardown_intr),
1889	DEVMETHOD(bus_config_intr,		bhndb_config_intr),
1890	DEVMETHOD(bus_bind_intr,		bhndb_bind_intr),
1891	DEVMETHOD(bus_describe_intr,		bhndb_describe_intr),
1892
1893	DEVMETHOD(bus_get_dma_tag,		bhndb_get_dma_tag),
1894
1895	DEVMETHOD(bus_adjust_resource,		bhndb_adjust_resource),
1896	DEVMETHOD(bus_set_resource,		bus_generic_rl_set_resource),
1897	DEVMETHOD(bus_get_resource,		bus_generic_rl_get_resource),
1898	DEVMETHOD(bus_delete_resource,		bus_generic_rl_delete_resource),
1899	DEVMETHOD(bus_get_resource_list,	bhndb_get_resource_list),
1900
1901	DEVMETHOD(bus_read_ivar,		bhndb_read_ivar),
1902	DEVMETHOD(bus_write_ivar,		bhndb_write_ivar),
1903
1904	/* BHNDB interface */
1905	DEVMETHOD(bhndb_get_chipid,		bhndb_get_chipid),
1906	DEVMETHOD(bhndb_init_full_config,	bhndb_generic_init_full_config),
1907	DEVMETHOD(bhndb_find_hostb_device,	bhndb_find_hostb_device),
1908	DEVMETHOD(bhndb_suspend_resource,	bhndb_suspend_resource),
1909	DEVMETHOD(bhndb_resume_resource,	bhndb_resume_resource),
1910
1911	/* BHND interface */
1912	DEVMETHOD(bhnd_bus_is_hw_disabled,	bhndb_is_hw_disabled),
1913	DEVMETHOD(bhnd_bus_get_chipid,		bhndb_get_chipid),
1914	DEVMETHOD(bhnd_bus_activate_resource,	bhndb_activate_bhnd_resource),
1915	DEVMETHOD(bhnd_bus_deactivate_resource,	bhndb_deactivate_bhnd_resource),
1916	DEVMETHOD(bhnd_bus_read_1,		bhndb_bus_read_1),
1917	DEVMETHOD(bhnd_bus_read_2,		bhndb_bus_read_2),
1918	DEVMETHOD(bhnd_bus_read_4,		bhndb_bus_read_4),
1919	DEVMETHOD(bhnd_bus_write_1,		bhndb_bus_write_1),
1920	DEVMETHOD(bhnd_bus_write_2,		bhndb_bus_write_2),
1921	DEVMETHOD(bhnd_bus_write_4,		bhndb_bus_write_4),
1922	DEVMETHOD(bhnd_bus_barrier,		bhndb_bus_barrier),
1923
1924	DEVMETHOD_END
1925};
1926
1927devclass_t bhndb_devclass;
1928
1929DEFINE_CLASS_0(bhndb, bhndb_driver, bhndb_methods, sizeof(struct bhndb_softc));
1930
1931MODULE_VERSION(bhndb, 1);
1932MODULE_DEPEND(bhndb, bhnd, 1, 1, 1);
1933MODULE_DEPEND(bhndb, bhnd_chipc, 1, 1, 1);
1934