]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/bhnd/bhnd_subr.c
Import lua 5.3.4 to contrib
[FreeBSD/FreeBSD.git] / sys / dev / bhnd / bhnd_subr.c
1 /*-
2  * Copyright (c) 2015-2016 Landon Fuller <landon@landonf.org>
3  * Copyright (c) 2017 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Landon Fuller
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
17  *    redistribution must be conditioned upon including a substantially
18  *    similar Disclaimer requirement for further binary redistribution.
19  *
20  * NO WARRANTY
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
24  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
25  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
26  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
29  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31  * THE POSSIBILITY OF SUCH DAMAGES.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/param.h>
38 #include <sys/bus.h>
39 #include <sys/refcount.h>
40 #include <sys/systm.h>
41
42 #include <machine/bus.h>
43 #include <sys/rman.h>
44 #include <machine/resource.h>
45
46 #include <dev/bhnd/siba/sibareg.h>
47
48 #include <dev/bhnd/cores/chipc/chipcreg.h>
49
50 #include "nvram/bhnd_nvram.h"
51
52 #include "bhnd_chipc_if.h"
53
54 #include "bhnd_nvram_if.h"
55 #include "bhnd_nvram_map.h"
56
57 #include "bhndreg.h"
58 #include "bhndvar.h"
59 #include "bhnd_private.h"
60
61 static void     bhnd_service_registry_free_entry(
62                     struct bhnd_service_entry *entry);
63
64 static int      compare_ascending_probe_order(const void *lhs, const void *rhs);
65 static int      compare_descending_probe_order(const void *lhs,
66                     const void *rhs);
67
68 /* BHND core device description table. */
69 static const struct bhnd_core_desc {
70         uint16_t         vendor;
71         uint16_t         device;
72         bhnd_devclass_t  class;
73         const char      *desc;
74 } bhnd_core_descs[] = {
75         #define BHND_CDESC(_mfg, _cid, _cls, _desc)             \
76             { BHND_MFGID_ ## _mfg, BHND_COREID_ ## _cid,        \
77                 BHND_DEVCLASS_ ## _cls, _desc }
78
79         BHND_CDESC(BCM, CC,             CC,             "ChipCommon I/O Controller"),
80         BHND_CDESC(BCM, ILINE20,        OTHER,          "iLine20 HPNA"),
81         BHND_CDESC(BCM, SRAM,           RAM,            "SRAM"),
82         BHND_CDESC(BCM, SDRAM,          RAM,            "SDRAM"),
83         BHND_CDESC(BCM, PCI,            PCI,            "PCI Bridge"),
84         BHND_CDESC(BCM, MIPS,           CPU,            "BMIPS CPU"),
85         BHND_CDESC(BCM, ENET,           ENET_MAC,       "Fast Ethernet MAC"),
86         BHND_CDESC(BCM, CODEC,          OTHER,          "V.90 Modem Codec"),
87         BHND_CDESC(BCM, USB,            USB_DUAL,       "USB 1.1 Device/Host Controller"),
88         BHND_CDESC(BCM, ADSL,           OTHER,          "ADSL Core"),
89         BHND_CDESC(BCM, ILINE100,       OTHER,          "iLine100 HPNA"),
90         BHND_CDESC(BCM, IPSEC,          OTHER,          "IPsec Accelerator"),
91         BHND_CDESC(BCM, UTOPIA,         OTHER,          "UTOPIA ATM Core"),
92         BHND_CDESC(BCM, PCMCIA,         PCCARD,         "PCMCIA Bridge"),
93         BHND_CDESC(BCM, SOCRAM,         RAM,            "Internal Memory"),
94         BHND_CDESC(BCM, MEMC,           MEMC,           "MEMC SDRAM Controller"),
95         BHND_CDESC(BCM, OFDM,           OTHER,          "OFDM PHY"),
96         BHND_CDESC(BCM, EXTIF,          OTHER,          "External Interface"),
97         BHND_CDESC(BCM, D11,            WLAN,           "802.11 MAC/PHY/Radio"),
98         BHND_CDESC(BCM, APHY,           WLAN_PHY,       "802.11a PHY"),
99         BHND_CDESC(BCM, BPHY,           WLAN_PHY,       "802.11b PHY"),
100         BHND_CDESC(BCM, GPHY,           WLAN_PHY,       "802.11g PHY"),
101         BHND_CDESC(BCM, MIPS33,         CPU,            "BMIPS33 CPU"),
102         BHND_CDESC(BCM, USB11H,         USB_HOST,       "USB 1.1 Host Controller"),
103         BHND_CDESC(BCM, USB11D,         USB_DEV,        "USB 1.1 Device Controller"),
104         BHND_CDESC(BCM, USB20H,         USB_HOST,       "USB 2.0 Host Controller"),
105         BHND_CDESC(BCM, USB20D,         USB_DEV,        "USB 2.0 Device Controller"),
106         BHND_CDESC(BCM, SDIOH,          OTHER,          "SDIO Host Controller"),
107         BHND_CDESC(BCM, ROBO,           OTHER,          "RoboSwitch"),
108         BHND_CDESC(BCM, ATA100,         OTHER,          "Parallel ATA Controller"),
109         BHND_CDESC(BCM, SATAXOR,        OTHER,          "SATA DMA/XOR Controller"),
110         BHND_CDESC(BCM, GIGETH,         ENET_MAC,       "Gigabit Ethernet MAC"),
111         BHND_CDESC(BCM, PCIE,           PCIE,           "PCIe Bridge"),
112         BHND_CDESC(BCM, NPHY,           WLAN_PHY,       "802.11n 2x2 PHY"),
113         BHND_CDESC(BCM, SRAMC,          MEMC,           "SRAM Controller"),
114         BHND_CDESC(BCM, MINIMAC,        OTHER,          "MINI MAC/PHY"),
115         BHND_CDESC(BCM, ARM11,          CPU,            "ARM1176 CPU"),
116         BHND_CDESC(BCM, ARM7S,          CPU,            "ARM7TDMI-S CPU"),
117         BHND_CDESC(BCM, LPPHY,          WLAN_PHY,       "802.11a/b/g PHY"),
118         BHND_CDESC(BCM, PMU,            PMU,            "PMU"),
119         BHND_CDESC(BCM, SSNPHY,         WLAN_PHY,       "802.11n Single-Stream PHY"),
120         BHND_CDESC(BCM, SDIOD,          OTHER,          "SDIO Device Core"),
121         BHND_CDESC(BCM, ARMCM3,         CPU,            "ARM Cortex-M3 CPU"),
122         BHND_CDESC(BCM, HTPHY,          WLAN_PHY,       "802.11n 4x4 PHY"),
123         BHND_CDESC(MIPS,MIPS74K,        CPU,            "MIPS74k CPU"),
124         BHND_CDESC(BCM, GMAC,           ENET_MAC,       "Gigabit MAC core"),
125         BHND_CDESC(BCM, DMEMC,          MEMC,           "DDR1/DDR2 Memory Controller"),
126         BHND_CDESC(BCM, PCIERC,         OTHER,          "PCIe Root Complex"),
127         BHND_CDESC(BCM, OCP,            SOC_BRIDGE,     "OCP to OCP Bridge"),
128         BHND_CDESC(BCM, SC,             OTHER,          "Shared Common Core"),
129         BHND_CDESC(BCM, AHB,            SOC_BRIDGE,     "OCP to AHB Bridge"),
130         BHND_CDESC(BCM, SPIH,           OTHER,          "SPI Host Controller"),
131         BHND_CDESC(BCM, I2S,            OTHER,          "I2S Digital Audio Interface"),
132         BHND_CDESC(BCM, DMEMS,          MEMC,           "SDR/DDR1 Memory Controller"),
133         BHND_CDESC(BCM, UBUS_SHIM,      OTHER,          "BCM6362/UBUS WLAN SHIM"),
134         BHND_CDESC(BCM, PCIE2,          PCIE,           "PCIe Bridge (Gen2)"),
135
136         BHND_CDESC(ARM, APB_BRIDGE,     SOC_BRIDGE,     "BP135 AMBA3 AXI to APB Bridge"),
137         BHND_CDESC(ARM, PL301,          SOC_ROUTER,     "PL301 AMBA3 Interconnect"),
138         BHND_CDESC(ARM, EROM,           EROM,           "PL366 Device Enumeration ROM"),
139         BHND_CDESC(ARM, OOB_ROUTER,     OTHER,          "PL367 OOB Interrupt Router"),
140         BHND_CDESC(ARM, AXI_UNMAPPED,   OTHER,          "Unmapped Address Ranges"),
141
142         BHND_CDESC(BCM, 4706_CC,        CC,             "ChipCommon I/O Controller"),
143         BHND_CDESC(BCM, NS_PCIE2,       PCIE,           "PCIe Bridge (Gen2)"),
144         BHND_CDESC(BCM, NS_DMA,         OTHER,          "DMA engine"),
145         BHND_CDESC(BCM, NS_SDIO,        OTHER,          "SDIO 3.0 Host Controller"),
146         BHND_CDESC(BCM, NS_USB20H,      USB_HOST,       "USB 2.0 Host Controller"),
147         BHND_CDESC(BCM, NS_USB30H,      USB_HOST,       "USB 3.0 Host Controller"),
148         BHND_CDESC(BCM, NS_A9JTAG,      OTHER,          "ARM Cortex A9 JTAG Interface"),
149         BHND_CDESC(BCM, NS_DDR23_MEMC,  MEMC,           "Denali DDR2/DD3 Memory Controller"),
150         BHND_CDESC(BCM, NS_ROM,         NVRAM,          "System ROM"),
151         BHND_CDESC(BCM, NS_NAND,        NVRAM,          "NAND Flash Controller"),
152         BHND_CDESC(BCM, NS_QSPI,        NVRAM,          "QSPI Flash Controller"),
153         BHND_CDESC(BCM, NS_CC_B,        CC_B,           "ChipCommon B Auxiliary I/O Controller"),
154         BHND_CDESC(BCM, 4706_SOCRAM,    RAM,            "Internal Memory"),
155         BHND_CDESC(BCM, IHOST_ARMCA9,   CPU,            "ARM Cortex A9 CPU"),
156         BHND_CDESC(BCM, 4706_GMAC_CMN,  ENET,           "Gigabit MAC (Common)"),
157         BHND_CDESC(BCM, 4706_GMAC,      ENET_MAC,       "Gigabit MAC"),
158         BHND_CDESC(BCM, AMEMC,          MEMC,           "Denali DDR1/DDR2 Memory Controller"),
159 #undef  BHND_CDESC
160
161         /* Derived from inspection of the BCM4331 cores that provide PrimeCell
162          * IDs. Due to lack of documentation, the surmised device name/purpose
163          * provided here may be incorrect. */
164         { BHND_MFGID_ARM,       BHND_PRIMEID_EROM,      BHND_DEVCLASS_OTHER,
165             "PL364 Device Enumeration ROM" },
166         { BHND_MFGID_ARM,       BHND_PRIMEID_SWRAP,     BHND_DEVCLASS_OTHER,
167             "PL368 Device Management Interface" },
168         { BHND_MFGID_ARM,       BHND_PRIMEID_MWRAP,     BHND_DEVCLASS_OTHER,
169             "PL369 Device Management Interface" },
170
171         { 0, 0, 0, NULL }
172 };
173
174 static const struct bhnd_device_quirk bhnd_chipc_clkctl_quirks[];
175 static const struct bhnd_device_quirk bhnd_pcmcia_clkctl_quirks[];
176
177 /**
178  * Device table entries for core-specific CLKCTL quirk lookup.
179  */
180 static const struct bhnd_device bhnd_clkctl_devices[] = {
181         BHND_DEVICE(BCM, CC,            NULL,   bhnd_chipc_clkctl_quirks),
182         BHND_DEVICE(BCM, PCMCIA,        NULL,   bhnd_pcmcia_clkctl_quirks),
183         BHND_DEVICE_END,
184 };
185
186 /** ChipCommon CLKCTL quirks */
187 static const struct bhnd_device_quirk bhnd_chipc_clkctl_quirks[] = {
188         /* HTAVAIL/ALPAVAIL are bitswapped in chipc's CLKCTL */
189         BHND_CHIP_QUIRK(4328,   HWREV_ANY,      BHND_CLKCTL_QUIRK_CCS0),
190         BHND_CHIP_QUIRK(5354,   HWREV_ANY,      BHND_CLKCTL_QUIRK_CCS0),
191         BHND_DEVICE_QUIRK_END
192 };
193
194 /** PCMCIA CLKCTL quirks */
195 static const struct bhnd_device_quirk bhnd_pcmcia_clkctl_quirks[] = {
196         /* HTAVAIL/ALPAVAIL are bitswapped in pcmcia's CLKCTL */
197         BHND_CHIP_QUIRK(4328,   HWREV_ANY,      BHND_CLKCTL_QUIRK_CCS0),
198         BHND_CHIP_QUIRK(5354,   HWREV_ANY,      BHND_CLKCTL_QUIRK_CCS0),
199         BHND_DEVICE_QUIRK_END
200 };
201
202 /**
203  * Return the name for a given JEP106 manufacturer ID.
204  * 
205  * @param vendor A JEP106 Manufacturer ID, including the non-standard ARM 4-bit
206  * JEP106 continuation code.
207  */
208 const char *
209 bhnd_vendor_name(uint16_t vendor)
210 {
211         switch (vendor) {
212         case BHND_MFGID_ARM:
213                 return "ARM";
214         case BHND_MFGID_BCM:
215                 return "Broadcom";
216         case BHND_MFGID_MIPS:
217                 return "MIPS";
218         default:
219                 return "unknown";
220         }
221 }
222
223 /**
224  * Return the name of a port type.
225  * 
226  * @param port_type The port type to look up.
227  */
228 const char *
229 bhnd_port_type_name(bhnd_port_type port_type)
230 {
231         switch (port_type) {
232         case BHND_PORT_DEVICE:
233                 return ("device");
234         case BHND_PORT_BRIDGE:
235                 return ("bridge");
236         case BHND_PORT_AGENT:
237                 return ("agent");
238         default:
239                 return "unknown";
240         }
241 }
242
243 /**
244  * Return the name of an NVRAM source.
245  * 
246  * @param nvram_src The NVRAM source type to look up.
247  */
248 const char *
249 bhnd_nvram_src_name(bhnd_nvram_src nvram_src)
250 {
251         switch (nvram_src) {
252         case BHND_NVRAM_SRC_FLASH:
253                 return ("flash");
254         case BHND_NVRAM_SRC_OTP:
255                 return ("OTP");
256         case BHND_NVRAM_SRC_SPROM:
257                 return ("SPROM");
258         case BHND_NVRAM_SRC_UNKNOWN:
259                 return ("none");
260         default:
261                 return ("unknown");
262         }
263 }
264
265 static const struct bhnd_core_desc *
266 bhnd_find_core_desc(uint16_t vendor, uint16_t device)
267 {
268         for (u_int i = 0; bhnd_core_descs[i].desc != NULL; i++) {
269                 if (bhnd_core_descs[i].vendor != vendor)
270                         continue;
271                 
272                 if (bhnd_core_descs[i].device != device)
273                         continue;
274                 
275                 return (&bhnd_core_descs[i]);
276         }
277         
278         return (NULL);
279 }
280
281 /**
282  * Return a human-readable name for a BHND core.
283  * 
284  * @param vendor The core designer's JEDEC-106 Manufacturer ID.
285  * @param device The core identifier.
286  */
287 const char *
288 bhnd_find_core_name(uint16_t vendor, uint16_t device)
289 {
290         const struct bhnd_core_desc *desc;
291         
292         if ((desc = bhnd_find_core_desc(vendor, device)) == NULL)
293                 return ("unknown");
294
295         return desc->desc;
296 }
297
298 /**
299  * Return the device class for a BHND core.
300  * 
301  * @param vendor The core designer's JEDEC-106 Manufacturer ID.
302  * @param device The core identifier.
303  */
304 bhnd_devclass_t
305 bhnd_find_core_class(uint16_t vendor, uint16_t device)
306 {
307         const struct bhnd_core_desc *desc;
308         
309         if ((desc = bhnd_find_core_desc(vendor, device)) == NULL)
310                 return (BHND_DEVCLASS_OTHER);
311
312         return desc->class;
313 }
314
315 /**
316  * Return a human-readable name for a BHND core.
317  * 
318  * @param ci The core's info record.
319  */
320 const char *
321 bhnd_core_name(const struct bhnd_core_info *ci)
322 {
323         return bhnd_find_core_name(ci->vendor, ci->device);
324 }
325
326 /**
327  * Return the device class for a BHND core.
328  * 
329  * @param ci The core's info record.
330  */
331 bhnd_devclass_t
332 bhnd_core_class(const struct bhnd_core_info *ci)
333 {
334         return bhnd_find_core_class(ci->vendor, ci->device);
335 }
336
337 /**
338  * Write a human readable name representation of the given
339  * BHND_CHIPID_* constant to @p buffer.
340  * 
341  * @param buffer Output buffer, or NULL to compute the required size.
342  * @param size Capacity of @p buffer, in bytes.
343  * @param chip_id Chip ID to be formatted.
344  * 
345  * @return The required number of bytes on success, or a negative integer on
346  * failure. No more than @p size-1 characters be written, with the @p size'th
347  * set to '\0'.
348  * 
349  * @sa BHND_CHIPID_MAX_NAMELEN
350  */
351 int
352 bhnd_format_chip_id(char *buffer, size_t size, uint16_t chip_id)
353 {
354         /* All hex formatted IDs are within the range of 0x4000-0x9C3F (40000-1) */
355         if (chip_id >= 0x4000 && chip_id <= 0x9C3F)
356                 return (snprintf(buffer, size, "BCM%hX", chip_id));
357         else
358                 return (snprintf(buffer, size, "BCM%hu", chip_id));
359 }
360
361 /**
362  * Return a core info record populated from a bhnd-attached @p dev.
363  * 
364  * @param dev A bhnd device.
365  * 
366  * @return A core info record for @p dev.
367  */
368 struct bhnd_core_info
369 bhnd_get_core_info(device_t dev) {
370         return (struct bhnd_core_info) {
371                 .vendor         = bhnd_get_vendor(dev),
372                 .device         = bhnd_get_device(dev),
373                 .hwrev          = bhnd_get_hwrev(dev),
374                 .core_idx       = bhnd_get_core_index(dev),
375                 .unit           = bhnd_get_core_unit(dev)
376         };
377 }
378
379 /**
380  * Find a @p class child device with @p unit on @p bus.
381  * 
382  * @param bus The bhnd-compatible bus to be searched.
383  * @param class The device class to match on.
384  * @param unit The core unit number; specify -1 to return the first match
385  * regardless of unit number.
386  * 
387  * @retval device_t if a matching child device is found.
388  * @retval NULL if no matching child device is found.
389  */
390 device_t
391 bhnd_bus_find_child(device_t bus, bhnd_devclass_t class, int unit)
392 {
393         struct bhnd_core_match md = {
394                 BHND_MATCH_CORE_CLASS(class),
395                 BHND_MATCH_CORE_UNIT(unit)
396         };
397
398         if (unit == -1)
399                 md.m.match.core_unit = 0;
400
401         return bhnd_bus_match_child(bus, &md);
402 }
403
404 /**
405  * Find the first child device on @p bus that matches @p desc.
406  * 
407  * @param bus The bhnd-compatible bus to be searched.
408  * @param desc A match descriptor.
409  * 
410  * @retval device_t if a matching child device is found.
411  * @retval NULL if no matching child device is found.
412  */
413 device_t
414 bhnd_bus_match_child(device_t bus, const struct bhnd_core_match *desc)
415 {
416         device_t        *devlistp;
417         device_t         match;
418         int              devcnt;
419         int              error;
420
421         error = device_get_children(bus, &devlistp, &devcnt);
422         if (error != 0)
423                 return (NULL);
424
425         match = NULL;
426         for (int i = 0; i < devcnt; i++) {
427                 struct bhnd_core_info ci = bhnd_get_core_info(devlistp[i]);
428
429                 if (bhnd_core_matches(&ci, desc)) {
430                         match = devlistp[i];
431                         goto done;
432                 }
433         }
434
435 done:
436         free(devlistp, M_TEMP);
437         return match;
438 }
439
440 /**
441  * Retrieve an ordered list of all device instances currently connected to
442  * @p bus, returning a pointer to the array in @p devlistp and the count
443  * in @p ndevs.
444  * 
445  * The memory allocated for the table must be freed via
446  * bhnd_bus_free_children().
447  * 
448  * @param       bus             The bhnd-compatible bus to be queried.
449  * @param[out]  devlist         The array of devices.
450  * @param[out]  devcount        The number of devices in @p devlistp
451  * @param       order           The order in which devices will be returned
452  *                              in @p devlist.
453  * 
454  * @retval 0            success
455  * @retval non-zero     if an error occurs, a regular unix error code will
456  *                      be returned.
457  */
458 int
459 bhnd_bus_get_children(device_t bus, device_t **devlist, int *devcount,
460     bhnd_device_order order)
461 {
462         int error;
463
464         /* Fetch device array */
465         if ((error = device_get_children(bus, devlist, devcount)))
466                 return (error);
467
468         /* Perform requested sorting */
469         if ((error = bhnd_sort_devices(*devlist, *devcount, order))) {
470                 bhnd_bus_free_children(*devlist);
471                 return (error);
472         }
473
474         return (0);
475 }
476
477 /**
478  * Free any memory allocated in a previous call to bhnd_bus_get_children().
479  *
480  * @param devlist The device array returned by bhnd_bus_get_children().
481  */
482 void
483 bhnd_bus_free_children(device_t *devlist)
484 {
485         free(devlist, M_TEMP);
486 }
487
488 /**
489  * Perform in-place sorting of an array of bhnd device instances.
490  * 
491  * @param devlist       An array of bhnd devices.
492  * @param devcount      The number of devices in @p devs.
493  * @param order         The sort order to be used.
494  * 
495  * @retval 0            success
496  * @retval EINVAL       if the sort order is unknown.
497  */
498 int
499 bhnd_sort_devices(device_t *devlist, size_t devcount, bhnd_device_order order)
500 {
501         int (*compare)(const void *, const void *);
502
503         switch (order) {
504         case BHND_DEVICE_ORDER_ATTACH:
505                 compare = compare_ascending_probe_order;
506                 break;
507         case BHND_DEVICE_ORDER_DETACH:
508                 compare = compare_descending_probe_order;
509                 break;
510         default:
511                 printf("unknown sort order: %d\n", order);
512                 return (EINVAL);
513         }
514
515         qsort(devlist, devcount, sizeof(*devlist), compare);
516         return (0);
517 }
518
519 /*
520  * Ascending comparison of bhnd device's probe order.
521  */
522 static int
523 compare_ascending_probe_order(const void *lhs, const void *rhs)
524 {
525         device_t        ldev, rdev;
526         int             lorder, rorder;
527
528         ldev = (*(const device_t *) lhs);
529         rdev = (*(const device_t *) rhs);
530
531         lorder = BHND_BUS_GET_PROBE_ORDER(device_get_parent(ldev), ldev);
532         rorder = BHND_BUS_GET_PROBE_ORDER(device_get_parent(rdev), rdev);
533
534         if (lorder < rorder) {
535                 return (-1);
536         } else if (lorder > rorder) {
537                 return (1);
538         } else {
539                 return (0);
540         }
541 }
542
543 /*
544  * Descending comparison of bhnd device's probe order.
545  */
546 static int
547 compare_descending_probe_order(const void *lhs, const void *rhs)
548 {
549         return (compare_ascending_probe_order(rhs, lhs));
550 }
551
552 /**
553  * Call device_probe_and_attach() for each of the bhnd bus device's
554  * children, in bhnd attach order.
555  * 
556  * @param bus The bhnd-compatible bus for which all children should be probed
557  * and attached.
558  */
559 int
560 bhnd_bus_probe_children(device_t bus)
561 {
562         device_t        *devs;
563         int              ndevs;
564         int              error;
565
566         /* Fetch children in attach order */
567         error = bhnd_bus_get_children(bus, &devs, &ndevs,
568             BHND_DEVICE_ORDER_ATTACH);
569         if (error)
570                 return (error);
571
572         /* Probe and attach all children */
573         for (int i = 0; i < ndevs; i++) {
574                 device_t child = devs[i];
575                 device_probe_and_attach(child);
576         }
577
578         bhnd_bus_free_children(devs);
579
580         return (0);
581 }
582
583 /**
584  * Walk up the bhnd device hierarchy to locate the root device
585  * to which the bhndb bridge is attached.
586  * 
587  * This can be used from within bhnd host bridge drivers to locate the
588  * actual upstream host device.
589  * 
590  * @param dev A bhnd device.
591  * @param bus_class The expected bus (e.g. "pci") to which the bridge root
592  * should be attached.
593  * 
594  * @retval device_t if a matching parent device is found.
595  * @retval NULL if @p dev is not attached via a bhndb bus.
596  * @retval NULL if no parent device is attached via @p bus_class.
597  */
598 device_t
599 bhnd_find_bridge_root(device_t dev, devclass_t bus_class)
600 {
601         devclass_t      bhndb_class;
602         device_t        parent;
603
604         KASSERT(device_get_devclass(device_get_parent(dev)) == bhnd_devclass,
605            ("%s not a bhnd device", device_get_nameunit(dev)));
606
607         bhndb_class = devclass_find("bhndb");
608
609         /* Walk the device tree until we hit a bridge */
610         parent = dev;
611         while ((parent = device_get_parent(parent)) != NULL) {
612                 if (device_get_devclass(parent) == bhndb_class)
613                         break;
614         }
615
616         /* No bridge? */
617         if (parent == NULL)
618                 return (NULL);
619
620         /* Search for a parent attached to the expected bus class */
621         while ((parent = device_get_parent(parent)) != NULL) {
622                 device_t bus;
623
624                 bus = device_get_parent(parent);
625                 if (bus != NULL && device_get_devclass(bus) == bus_class)
626                         return (parent);
627         }
628
629         /* Not found */
630         return (NULL);
631 }
632
633 /**
634  * Find the first core in @p cores that matches @p desc.
635  * 
636  * @param cores The table to search.
637  * @param num_cores The length of @p cores.
638  * @param desc A match descriptor.
639  * 
640  * @retval bhnd_core_info if a matching core is found.
641  * @retval NULL if no matching core is found.
642  */
643 const struct bhnd_core_info *
644 bhnd_match_core(const struct bhnd_core_info *cores, u_int num_cores,
645     const struct bhnd_core_match *desc)
646 {
647         for (u_int i = 0; i < num_cores; i++) {
648                 if (bhnd_core_matches(&cores[i], desc))
649                         return &cores[i];
650         }
651
652         return (NULL);
653 }
654
655
656 /**
657  * Find the first core in @p cores with the given @p class.
658  * 
659  * @param cores The table to search.
660  * @param num_cores The length of @p cores.
661  * @param class The device class to match on.
662  * 
663  * @retval non-NULL if a matching core is found.
664  * @retval NULL if no matching core is found.
665  */
666 const struct bhnd_core_info *
667 bhnd_find_core(const struct bhnd_core_info *cores, u_int num_cores,
668     bhnd_devclass_t class)
669 {
670         struct bhnd_core_match md = {
671                 BHND_MATCH_CORE_CLASS(class)
672         };
673
674         return bhnd_match_core(cores, num_cores, &md);
675 }
676
677
678 /**
679  * Create an equality match descriptor for @p core.
680  * 
681  * @param core The core info to be matched on.
682  * 
683  * @return an equality match descriptor for @p core.
684  */
685 struct bhnd_core_match
686 bhnd_core_get_match_desc(const struct bhnd_core_info *core)
687 {
688         return ((struct bhnd_core_match) {
689                 BHND_MATCH_CORE_VENDOR(core->vendor),
690                 BHND_MATCH_CORE_ID(core->device),
691                 BHND_MATCH_CORE_REV(HWREV_EQ(core->hwrev)),
692                 BHND_MATCH_CORE_CLASS(bhnd_core_class(core)),
693                 BHND_MATCH_CORE_IDX(core->core_idx),
694                 BHND_MATCH_CORE_UNIT(core->unit)
695         });
696 }
697
698
699 /**
700  * Return true if the @p lhs is equal to @p rhs.
701  * 
702  * @param lhs The first bhnd core descriptor to compare.
703  * @param rhs The second bhnd core descriptor to compare.
704  * 
705  * @retval true if @p lhs is equal to @p rhs
706  * @retval false if @p lhs is not equal to @p rhs
707  */
708 bool
709 bhnd_cores_equal(const struct bhnd_core_info *lhs,
710     const struct bhnd_core_info *rhs)
711 {
712         struct bhnd_core_match md;
713
714         /* Use an equality match descriptor to perform the comparison */
715         md = bhnd_core_get_match_desc(rhs);
716         return (bhnd_core_matches(lhs, &md));
717 }
718
719 /**
720  * Return true if the @p core matches @p desc.
721  * 
722  * @param core A bhnd core descriptor.
723  * @param desc A match descriptor to compare against @p core.
724  * 
725  * @retval true if @p core matches @p match.
726  * @retval false if @p core does not match @p match.
727  */
728 bool
729 bhnd_core_matches(const struct bhnd_core_info *core,
730     const struct bhnd_core_match *desc)
731 {
732         if (desc->m.match.core_vendor && desc->core_vendor != core->vendor)
733                 return (false);
734
735         if (desc->m.match.core_id && desc->core_id != core->device)
736                 return (false);
737
738         if (desc->m.match.core_unit && desc->core_unit != core->unit)
739                 return (false);
740
741         if (desc->m.match.core_rev && 
742             !bhnd_hwrev_matches(core->hwrev, &desc->core_rev))
743                 return (false);
744
745         if (desc->m.match.core_idx && desc->core_idx != core->core_idx)
746                 return (false);
747
748         if (desc->m.match.core_class &&
749             desc->core_class != bhnd_core_class(core))
750                 return (false);
751
752         return true;
753 }
754
755 /**
756  * Return true if the @p chip matches @p desc.
757  * 
758  * @param chip A bhnd chip identifier.
759  * @param desc A match descriptor to compare against @p chip.
760  * 
761  * @retval true if @p chip matches @p match.
762  * @retval false if @p chip does not match @p match.
763  */
764 bool
765 bhnd_chip_matches(const struct bhnd_chipid *chip,
766     const struct bhnd_chip_match *desc)
767 {
768         if (desc->m.match.chip_id && chip->chip_id != desc->chip_id)
769                 return (false);
770
771         if (desc->m.match.chip_pkg && chip->chip_pkg != desc->chip_pkg)
772                 return (false);
773
774         if (desc->m.match.chip_rev &&
775             !bhnd_hwrev_matches(chip->chip_rev, &desc->chip_rev))
776                 return (false);
777
778         if (desc->m.match.chip_type && chip->chip_type != desc->chip_type)
779                 return (false);
780
781         return (true);
782 }
783
784 /**
785  * Return true if the @p board matches @p desc.
786  * 
787  * @param board The bhnd board info.
788  * @param desc A match descriptor to compare against @p board.
789  * 
790  * @retval true if @p chip matches @p match.
791  * @retval false if @p chip does not match @p match.
792  */
793 bool
794 bhnd_board_matches(const struct bhnd_board_info *board,
795     const struct bhnd_board_match *desc)
796 {
797         if (desc->m.match.board_srom_rev &&
798             !bhnd_hwrev_matches(board->board_srom_rev, &desc->board_srom_rev))
799                 return (false);
800
801         if (desc->m.match.board_vendor &&
802             board->board_vendor != desc->board_vendor)
803                 return (false);
804
805         if (desc->m.match.board_type && board->board_type != desc->board_type)
806                 return (false);
807
808         if (desc->m.match.board_rev &&
809             !bhnd_hwrev_matches(board->board_rev, &desc->board_rev))
810                 return (false);
811
812         return (true);
813 }
814
815 /**
816  * Return true if the @p hwrev matches @p desc.
817  * 
818  * @param hwrev A bhnd hardware revision.
819  * @param desc A match descriptor to compare against @p core.
820  * 
821  * @retval true if @p hwrev matches @p match.
822  * @retval false if @p hwrev does not match @p match.
823  */
824 bool
825 bhnd_hwrev_matches(uint16_t hwrev, const struct bhnd_hwrev_match *desc)
826 {
827         if (desc->start != BHND_HWREV_INVALID &&
828             desc->start > hwrev)
829                 return false;
830                 
831         if (desc->end != BHND_HWREV_INVALID &&
832             desc->end < hwrev)
833                 return false;
834
835         return true;
836 }
837
838 /**
839  * Return true if the @p dev matches @p desc.
840  * 
841  * @param dev A bhnd device.
842  * @param desc A match descriptor to compare against @p dev.
843  * 
844  * @retval true if @p dev matches @p match.
845  * @retval false if @p dev does not match @p match.
846  */
847 bool
848 bhnd_device_matches(device_t dev, const struct bhnd_device_match *desc)
849 {
850         struct bhnd_core_info            core;
851         const struct bhnd_chipid        *chip;
852         struct bhnd_board_info           board;
853         device_t                         parent;
854         int                              error;
855
856         /* Construct individual match descriptors */
857         struct bhnd_core_match  m_core  = { _BHND_CORE_MATCH_COPY(desc) };
858         struct bhnd_chip_match  m_chip  = { _BHND_CHIP_MATCH_COPY(desc) };
859         struct bhnd_board_match m_board = { _BHND_BOARD_MATCH_COPY(desc) };
860
861         /* Fetch and match core info */
862         if (m_core.m.match_flags) {
863                 /* Only applicable to bhnd-attached cores */
864                 parent = device_get_parent(dev);
865                 if (device_get_devclass(parent) != bhnd_devclass) {
866                         device_printf(dev, "attempting to match core "
867                             "attributes against non-core device\n");
868                         return (false);
869                 }
870
871                 core = bhnd_get_core_info(dev);
872                 if (!bhnd_core_matches(&core, &m_core))
873                         return (false);
874         }
875
876         /* Fetch and match chip info */
877         if (m_chip.m.match_flags) {
878                 chip = bhnd_get_chipid(dev);
879
880                 if (!bhnd_chip_matches(chip, &m_chip))
881                         return (false);
882         }
883
884         /* Fetch and match board info.
885          *
886          * This is not available until  after NVRAM is up; earlier device
887          * matches should not include board requirements */
888         if (m_board.m.match_flags) {
889                 if ((error = bhnd_read_board_info(dev, &board))) {
890                         device_printf(dev, "failed to read required board info "
891                             "during device matching: %d\n", error);
892                         return (false);
893                 }
894
895                 if (!bhnd_board_matches(&board, &m_board))
896                         return (false);
897         }
898
899         /* All matched */
900         return (true);
901 }
902
903 /**
904  * Search @p table for an entry matching @p dev.
905  * 
906  * @param dev A bhnd device to match against @p table.
907  * @param table The device table to search.
908  * @param entry_size The @p table entry size, in bytes.
909  * 
910  * @retval non-NULL the first matching device, if any.
911  * @retval NULL if no matching device is found in @p table.
912  */
913 const struct bhnd_device *
914 bhnd_device_lookup(device_t dev, const struct bhnd_device *table,
915     size_t entry_size)
916 {
917         const struct bhnd_device        *entry;
918         device_t                         hostb, parent;
919         bhnd_attach_type                 attach_type;
920         uint32_t                         dflags;
921
922         parent = device_get_parent(dev);
923         hostb = bhnd_bus_find_hostb_device(parent);
924         attach_type = bhnd_get_attach_type(dev);
925
926         for (entry = table; !BHND_DEVICE_IS_END(entry); entry =
927             (const struct bhnd_device *) ((const char *) entry + entry_size))
928         {
929                 /* match core info */
930                 if (!bhnd_device_matches(dev, &entry->core))
931                         continue;
932
933                 /* match device flags */
934                 dflags = entry->device_flags;
935
936                 /* hostb implies BHND_ATTACH_ADAPTER requirement */
937                 if (dflags & BHND_DF_HOSTB)
938                         dflags |= BHND_DF_ADAPTER;
939         
940                 if (dflags & BHND_DF_ADAPTER)
941                         if (attach_type != BHND_ATTACH_ADAPTER)
942                                 continue;
943
944                 if (dflags & BHND_DF_HOSTB)
945                         if (dev != hostb)
946                                 continue;
947
948                 if (dflags & BHND_DF_SOC)
949                         if (attach_type != BHND_ATTACH_NATIVE)
950                                 continue;
951
952                 /* device found */
953                 return (entry);
954         }
955
956         /* not found */
957         return (NULL);
958 }
959
960 /**
961  * Scan the device @p table for all quirk flags applicable to @p dev.
962  * 
963  * @param dev A bhnd device to match against @p table.
964  * @param table The device table to search.
965  * @param entry_size The @p table entry size, in bytes.
966  * 
967  * @return all matching quirk flags.
968  */
969 uint32_t
970 bhnd_device_quirks(device_t dev, const struct bhnd_device *table,
971     size_t entry_size)
972 {
973         const struct bhnd_device        *dent;
974         const struct bhnd_device_quirk  *qent, *qtable;
975         uint32_t                         quirks;
976
977         /* Locate the device entry */
978         if ((dent = bhnd_device_lookup(dev, table, entry_size)) == NULL)
979                 return (0);
980
981         /* Quirks table is optional */
982         qtable = dent->quirks_table;
983         if (qtable == NULL)
984                 return (0);
985
986         /* Collect matching device quirk entries */
987         quirks = 0;
988         for (qent = qtable; !BHND_DEVICE_QUIRK_IS_END(qent); qent++) {
989                 if (bhnd_device_matches(dev, &qent->desc))
990                         quirks |= qent->quirks;
991         }
992
993         return (quirks);
994 }
995
996
997 /**
998  * Allocate bhnd(4) resources defined in @p rs from a parent bus.
999  * 
1000  * @param dev The device requesting ownership of the resources.
1001  * @param rs A standard bus resource specification. This will be updated
1002  * with the allocated resource's RIDs.
1003  * @param res On success, the allocated bhnd resources.
1004  * 
1005  * @retval 0 success
1006  * @retval non-zero if allocation of any non-RF_OPTIONAL resource fails,
1007  *                  all allocated resources will be released and a regular
1008  *                  unix error code will be returned.
1009  */
1010 int
1011 bhnd_alloc_resources(device_t dev, struct resource_spec *rs,
1012     struct bhnd_resource **res)
1013 {
1014         /* Initialize output array */
1015         for (u_int i = 0; rs[i].type != -1; i++)
1016                 res[i] = NULL;
1017
1018         for (u_int i = 0; rs[i].type != -1; i++) {
1019                 res[i] = bhnd_alloc_resource_any(dev, rs[i].type, &rs[i].rid,
1020                     rs[i].flags);
1021
1022                 /* Clean up all allocations on failure */
1023                 if (res[i] == NULL && !(rs[i].flags & RF_OPTIONAL)) {
1024                         bhnd_release_resources(dev, rs, res);
1025                         return (ENXIO);
1026                 }
1027         }
1028
1029         return (0);
1030 }
1031
1032 /**
1033  * Release bhnd(4) resources defined in @p rs from a parent bus.
1034  * 
1035  * @param dev The device that owns the resources.
1036  * @param rs A standard bus resource specification previously initialized
1037  * by @p bhnd_alloc_resources.
1038  * @param res The bhnd resources to be released.
1039  */
1040 void
1041 bhnd_release_resources(device_t dev, const struct resource_spec *rs,
1042     struct bhnd_resource **res)
1043 {
1044         for (u_int i = 0; rs[i].type != -1; i++) {
1045                 if (res[i] == NULL)
1046                         continue;
1047
1048                 bhnd_release_resource(dev, rs[i].type, rs[i].rid, res[i]);
1049                 res[i] = NULL;
1050         }
1051 }
1052
1053 /**
1054  * Parse the CHIPC_ID_* fields from the ChipCommon CHIPC_ID
1055  * register, returning its bhnd_chipid representation.
1056  * 
1057  * @param idreg The CHIPC_ID register value.
1058  * @param enum_addr The enumeration address to include in the result.
1059  *
1060  * @warning
1061  * On early siba(4) devices, the ChipCommon core does not provide
1062  * a valid CHIPC_ID_NUMCORE field. On these ChipCommon revisions
1063  * (see CHIPC_NCORES_MIN_HWREV()), this function will parse and return
1064  * an invalid `ncores` value.
1065  */
1066 struct bhnd_chipid
1067 bhnd_parse_chipid(uint32_t idreg, bhnd_addr_t enum_addr)
1068 {
1069         struct bhnd_chipid result;
1070
1071         /* Fetch the basic chip info */
1072         result.chip_id = CHIPC_GET_BITS(idreg, CHIPC_ID_CHIP);
1073         result.chip_pkg = CHIPC_GET_BITS(idreg, CHIPC_ID_PKG);
1074         result.chip_rev = CHIPC_GET_BITS(idreg, CHIPC_ID_REV);
1075         result.chip_type = CHIPC_GET_BITS(idreg, CHIPC_ID_BUS);
1076         result.ncores = CHIPC_GET_BITS(idreg, CHIPC_ID_NUMCORE);
1077
1078         result.enum_addr = enum_addr;
1079
1080         return (result);
1081 }
1082
1083
1084 /**
1085  * Determine the correct core count for a chip identification value that
1086  * may contain an invalid core count.
1087  * 
1088  * On some early siba(4) devices (see CHIPC_NCORES_MIN_HWREV()), the ChipCommon
1089  * core does not provide a valid CHIPC_ID_NUMCORE field.
1090  * 
1091  * @param cid The chip identification to be queried.
1092  * @param chipc_hwrev The hardware revision of the ChipCommon core from which
1093  * @p cid was parsed.
1094  * @param[out] ncores On success, will be set to the correct core count.
1095  * 
1096  * @retval 0 If the core count is already correct, or was mapped to a
1097  * a correct value.
1098  * @retval EINVAL If the core count is incorrect, but the chip was not
1099  * recognized.
1100  */
1101 int
1102 bhnd_chipid_fixed_ncores(const struct bhnd_chipid *cid, uint16_t chipc_hwrev,
1103     uint8_t *ncores)
1104 {
1105         /* bcma(4), and most siba(4) devices */
1106         if (CHIPC_NCORES_MIN_HWREV(chipc_hwrev)) {
1107                 *ncores = cid->ncores;
1108                 return (0);
1109         }
1110
1111         /* broken siba(4) chipsets */
1112         switch (cid->chip_id) {
1113         case BHND_CHIPID_BCM4306:
1114                 *ncores = 6;
1115                 break;
1116         case BHND_CHIPID_BCM4704:
1117                 *ncores = 9;
1118                 break;
1119         case BHND_CHIPID_BCM5365:
1120                 /*
1121                 * BCM5365 does support ID_NUMCORE in at least
1122                 * some of its revisions, but for unknown
1123                 * reasons, Broadcom's drivers always exclude
1124                 * the ChipCommon revision (0x5) used by BCM5365
1125                 * from the set of revisions supporting
1126                 * ID_NUMCORE, and instead supply a fixed value.
1127                 * 
1128                 * Presumably, at least some of these devices
1129                 * shipped with a broken ID_NUMCORE value.
1130                 */
1131                 *ncores = 7;
1132                 break;
1133         default:
1134                 return (EINVAL);
1135         }
1136
1137         return (0);
1138 }
1139
1140 /**
1141  * Allocate the resource defined by @p rs via @p dev, use it
1142  * to read the ChipCommon ID register relative to @p chipc_offset,
1143  * then release the resource.
1144  * 
1145  * @param dev The device owning @p rs.
1146  * @param rs A resource spec that encompasses the ChipCommon register block.
1147  * @param chipc_offset The offset of the ChipCommon registers within @p rs.
1148  * @param[out] result The chip identification data.
1149  * 
1150  * @retval 0 success
1151  * @retval non-zero if the ChipCommon identification data could not be read.
1152  */
1153 int
1154 bhnd_read_chipid(device_t dev, struct resource_spec *rs,
1155     bus_size_t chipc_offset, struct bhnd_chipid *result)
1156 {
1157         struct resource                 *res;
1158         bhnd_addr_t                      enum_addr;
1159         uint32_t                         reg;
1160         uint8_t                          chip_type;
1161         int                              error, rid, rtype;
1162
1163         rid = rs->rid;
1164         rtype = rs->type;
1165         error = 0;
1166
1167         /* Allocate the ChipCommon window resource and fetch the chipid data */
1168         res = bus_alloc_resource_any(dev, rtype, &rid, RF_ACTIVE);
1169         if (res == NULL) {
1170                 device_printf(dev,
1171                     "failed to allocate bhnd chipc resource\n");
1172                 return (ENXIO);
1173         }
1174
1175         /* Fetch the basic chip info */
1176         reg = bus_read_4(res, chipc_offset + CHIPC_ID);
1177         chip_type = CHIPC_GET_BITS(reg, CHIPC_ID_BUS);
1178
1179         /* Fetch the EROMPTR */
1180         if (BHND_CHIPTYPE_HAS_EROM(chip_type)) {
1181                 enum_addr = bus_read_4(res, chipc_offset + CHIPC_EROMPTR);
1182         } else if (chip_type == BHND_CHIPTYPE_SIBA) {
1183                 /* siba(4) uses the ChipCommon base address as the enumeration
1184                  * address */
1185                 enum_addr = BHND_DEFAULT_CHIPC_ADDR;
1186         } else {
1187                 device_printf(dev, "unknown chip type %hhu\n", chip_type);
1188                 error = ENODEV;
1189                 goto cleanup;
1190         }
1191
1192         *result = bhnd_parse_chipid(reg, enum_addr);
1193
1194         /* Fix the core count on early siba(4) devices */
1195         if (chip_type == BHND_CHIPTYPE_SIBA) {
1196                 uint32_t        idh;
1197                 uint16_t        chipc_hwrev;
1198
1199                 /* 
1200                  * We need the ChipCommon revision to determine whether
1201                  * the ncore field is valid.
1202                  * 
1203                  * We can safely assume the siba IDHIGH register is mapped
1204                  * within the chipc register block.
1205                  */
1206                 idh = bus_read_4(res, SB0_REG_ABS(SIBA_CFG0_IDHIGH));
1207                 chipc_hwrev = SIBA_IDH_CORE_REV(idh);
1208
1209                 error = bhnd_chipid_fixed_ncores(result, chipc_hwrev,
1210                     &result->ncores);
1211                 if (error)
1212                         goto cleanup;
1213         }
1214
1215 cleanup:
1216         /* Clean up */
1217         bus_release_resource(dev, rtype, rid, res);
1218         return (error);
1219 }
1220
1221 /**
1222  * Allocate and return a new per-core PMU clock control/status (clkctl)
1223  * instance for @p dev.
1224  * 
1225  * @param dev           The bhnd(4) core device mapped by @p r.
1226  * @param pmu_dev       The bhnd(4) PMU device, implmenting the bhnd_pmu_if
1227  *                      interface. The caller is responsible for ensuring that
1228  *                      this reference remains valid for the lifetime of the
1229  *                      returned clkctl instance.
1230  * @param r             A resource mapping the core's clock control register
1231  *                      (see BHND_CLK_CTL_ST). The caller is responsible for
1232  *                      ensuring that this resource remains valid for the
1233  *                      lifetime of the returned clkctl instance.
1234  * @param offset        The offset to the clock control register within @p r.
1235  * @param max_latency   The PMU's maximum state transition latency in
1236  *                      microseconds; this upper bound will be used to busy-wait
1237  *                      on PMU state transitions.
1238  * 
1239  * @retval non-NULL     success
1240  * @retval NULL         if allocation fails.
1241  * 
1242  */
1243 struct bhnd_core_clkctl *
1244 bhnd_alloc_core_clkctl(device_t dev, device_t pmu_dev, struct bhnd_resource *r,
1245     bus_size_t offset, u_int max_latency)
1246 {
1247         struct bhnd_core_clkctl *clkctl;
1248
1249         clkctl = malloc(sizeof(*clkctl), M_BHND, M_ZERO | M_NOWAIT);
1250         if (clkctl == NULL)
1251                 return (NULL);
1252
1253         clkctl->cc_dev = dev;
1254         clkctl->cc_pmu_dev = pmu_dev;
1255         clkctl->cc_res = r;
1256         clkctl->cc_res_offset = offset;
1257         clkctl->cc_max_latency = max_latency;
1258         clkctl->cc_quirks = bhnd_device_quirks(dev, bhnd_clkctl_devices,
1259             sizeof(bhnd_clkctl_devices[0]));
1260
1261         BHND_CLKCTL_LOCK_INIT(clkctl);
1262
1263         return (clkctl);
1264 }
1265
1266 /**
1267  * Free a clkctl instance previously allocated via bhnd_alloc_core_clkctl().
1268  * 
1269  * @param clkctl        The clkctl instance to be freed.
1270  */
1271 void
1272 bhnd_free_core_clkctl(struct bhnd_core_clkctl *clkctl)
1273 {
1274         BHND_CLKCTL_LOCK_DESTROY(clkctl);
1275
1276         free(clkctl, M_BHND);
1277 }
1278
1279 /**
1280  * Wait for the per-core clock status to be equal to @p value after
1281  * applying @p mask, timing out after the maximum transition latency is reached.
1282  * 
1283  * @param clkctl        Per-core clkctl state to be queryied.
1284  * @param value         Value to wait for.
1285  * @param mask          Mask to apply prior to value comparison.
1286  * 
1287  * @retval 0            success
1288  * @retval ETIMEDOUT    if the PMU's maximum transition delay is reached before
1289  *                      the clock status matches @p value and @p mask.
1290  */
1291 int
1292 bhnd_core_clkctl_wait(struct bhnd_core_clkctl *clkctl, uint32_t value,
1293     uint32_t mask)
1294 {
1295         uint32_t        clkst;
1296
1297         BHND_CLKCTL_LOCK_ASSERT(clkctl, MA_OWNED);
1298
1299         /* Bitswapped HTAVAIL/ALPAVAIL work-around */
1300         if (clkctl->cc_quirks & BHND_CLKCTL_QUIRK_CCS0) {
1301                 uint32_t fmask, fval;
1302
1303                 fmask = mask & ~(BHND_CCS_HTAVAIL | BHND_CCS_ALPAVAIL);
1304                 fval = value & ~(BHND_CCS_HTAVAIL | BHND_CCS_ALPAVAIL);
1305
1306                 if (mask & BHND_CCS_HTAVAIL)
1307                         fmask |= BHND_CCS0_HTAVAIL;
1308                 if (value & BHND_CCS_HTAVAIL)
1309                         fval |= BHND_CCS0_HTAVAIL;
1310
1311                 if (mask & BHND_CCS_ALPAVAIL) 
1312                         fmask |= BHND_CCS0_ALPAVAIL;
1313                 if (value & BHND_CCS_ALPAVAIL)
1314                         fval |= BHND_CCS0_ALPAVAIL;
1315
1316                 mask = fmask;
1317                 value = fval;
1318         }
1319
1320         for (u_int i = 0; i < clkctl->cc_max_latency; i += 10) {
1321                 clkst = bhnd_bus_read_4(clkctl->cc_res, clkctl->cc_res_offset);
1322                 if ((clkst & mask) == (value & mask))
1323                         return (0);
1324
1325                 DELAY(10);
1326         }
1327
1328         device_printf(clkctl->cc_dev, "clkst wait timeout (value=%#x, "
1329             "mask=%#x)\n", value, mask);
1330
1331         return (ETIMEDOUT);
1332 }
1333
1334 /**
1335  * Read an NVRAM variable's NUL-terminated string value.
1336  *
1337  * @param       dev     A bhnd bus child device.
1338  * @param       name    The NVRAM variable name.
1339  * @param[out]  buf     A buffer large enough to hold @p len bytes. On
1340  *                      success, the NUL-terminated string value will be
1341  *                      written to this buffer. This argment may be NULL if
1342  *                      the value is not desired.
1343  * @param       len     The maximum capacity of @p buf.
1344  * @param[out]  rlen    On success, will be set to the actual size of
1345  *                      the requested value (including NUL termination). This
1346  *                      argment may be NULL if the size is not desired.
1347  *
1348  * @retval 0            success
1349  * @retval ENOENT       The requested variable was not found.
1350  * @retval ENODEV       No valid NVRAM source could be found.
1351  * @retval ENOMEM       If @p buf is non-NULL and a buffer of @p len is too
1352  *                      small to hold the requested value.
1353  * @retval EFTYPE       If the variable data cannot be coerced to a valid
1354  *                      string representation.
1355  * @retval ERANGE       If value coercion would overflow @p type.
1356  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1357  *                      error code will be returned.
1358  */
1359 int
1360 bhnd_nvram_getvar_str(device_t dev, const char *name, char *buf, size_t len,
1361     size_t *rlen)
1362 {
1363         size_t  larg;
1364         int     error;
1365
1366         larg = len;
1367         error = bhnd_nvram_getvar(dev, name, buf, &larg,
1368             BHND_NVRAM_TYPE_STRING);
1369         if (rlen != NULL)
1370                 *rlen = larg;
1371
1372         return (error);
1373 }
1374
1375 /**
1376  * Read an NVRAM variable's unsigned integer value.
1377  *
1378  * @param               dev     A bhnd bus child device.
1379  * @param               name    The NVRAM variable name.
1380  * @param[out]          value   On success, the requested value will be written
1381  *                              to this pointer.
1382  * @param               width   The output integer type width (1, 2, or
1383  *                              4 bytes).
1384  * 
1385  * @retval 0            success
1386  * @retval ENOENT       The requested variable was not found.
1387  * @retval ENODEV       No valid NVRAM source could be found.
1388  * @retval EFTYPE       If the variable data cannot be coerced to a
1389  *                      a valid unsigned integer representation.
1390  * @retval ERANGE       If value coercion would overflow (or underflow) an
1391  *                      unsigned representation of the given @p width.
1392  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1393  *                      error code will be returned.
1394  */
1395 int
1396 bhnd_nvram_getvar_uint(device_t dev, const char *name, void *value, int width)
1397 {
1398         bhnd_nvram_type type;
1399         size_t          len;
1400
1401         switch (width) {
1402         case 1:
1403                 type = BHND_NVRAM_TYPE_UINT8;
1404                 break;
1405         case 2:
1406                 type = BHND_NVRAM_TYPE_UINT16;
1407                 break;
1408         case 4:
1409                 type = BHND_NVRAM_TYPE_UINT32;
1410                 break;
1411         default:
1412                 device_printf(dev, "unsupported NVRAM integer width: %d\n",
1413                     width);
1414                 return (EINVAL);
1415         }
1416
1417         len = width;
1418         return (bhnd_nvram_getvar(dev, name, value, &len, type));
1419 }
1420
1421 /**
1422  * Read an NVRAM variable's unsigned 8-bit integer value.
1423  *
1424  * @param               dev     A bhnd bus child device.
1425  * @param               name    The NVRAM variable name.
1426  * @param[out]          value   On success, the requested value will be written
1427  *                              to this pointer.
1428  * 
1429  * @retval 0            success
1430  * @retval ENOENT       The requested variable was not found.
1431  * @retval ENODEV       No valid NVRAM source could be found.
1432  * @retval EFTYPE       If the variable data cannot be coerced to a
1433  *                      a valid unsigned integer representation.
1434  * @retval ERANGE       If value coercion would overflow (or underflow) uint8_t.
1435  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1436  *                      error code will be returned.
1437  */
1438 int
1439 bhnd_nvram_getvar_uint8(device_t dev, const char *name, uint8_t *value)
1440 {
1441         return (bhnd_nvram_getvar_uint(dev, name, value, sizeof(*value)));
1442 }
1443
1444 /**
1445  * Read an NVRAM variable's unsigned 16-bit integer value.
1446  *
1447  * @param               dev     A bhnd bus child device.
1448  * @param               name    The NVRAM variable name.
1449  * @param[out]          value   On success, the requested value will be written
1450  *                              to this pointer.
1451  * 
1452  * @retval 0            success
1453  * @retval ENOENT       The requested variable was not found.
1454  * @retval ENODEV       No valid NVRAM source could be found.
1455  * @retval EFTYPE       If the variable data cannot be coerced to a
1456  *                      a valid unsigned integer representation.
1457  * @retval ERANGE       If value coercion would overflow (or underflow)
1458  *                      uint16_t.
1459  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1460  *                      error code will be returned.
1461  */
1462 int
1463 bhnd_nvram_getvar_uint16(device_t dev, const char *name, uint16_t *value)
1464 {
1465         return (bhnd_nvram_getvar_uint(dev, name, value, sizeof(*value)));
1466 }
1467
1468 /**
1469  * Read an NVRAM variable's unsigned 32-bit integer value.
1470  *
1471  * @param               dev     A bhnd bus child device.
1472  * @param               name    The NVRAM variable name.
1473  * @param[out]          value   On success, the requested value will be written
1474  *                              to this pointer.
1475  * 
1476  * @retval 0            success
1477  * @retval ENOENT       The requested variable was not found.
1478  * @retval ENODEV       No valid NVRAM source could be found.
1479  * @retval EFTYPE       If the variable data cannot be coerced to a
1480  *                      a valid unsigned integer representation.
1481  * @retval ERANGE       If value coercion would overflow (or underflow)
1482  *                      uint32_t.
1483  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1484  *                      error code will be returned.
1485  */
1486 int
1487 bhnd_nvram_getvar_uint32(device_t dev, const char *name, uint32_t *value)
1488 {
1489         return (bhnd_nvram_getvar_uint(dev, name, value, sizeof(*value)));
1490 }
1491
1492 /**
1493  * Read an NVRAM variable's signed integer value.
1494  *
1495  * @param               dev     A bhnd bus child device.
1496  * @param               name    The NVRAM variable name.
1497  * @param[out]          value   On success, the requested value will be written
1498  *                              to this pointer.
1499  * @param               width   The output integer type width (1, 2, or
1500  *                              4 bytes).
1501  * 
1502  * @retval 0            success
1503  * @retval ENOENT       The requested variable was not found.
1504  * @retval ENODEV       No valid NVRAM source could be found.
1505  * @retval EFTYPE       If the variable data cannot be coerced to a
1506  *                      a valid integer representation.
1507  * @retval ERANGE       If value coercion would overflow (or underflow) an
1508  *                      signed representation of the given @p width.
1509  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1510  *                      error code will be returned.
1511  */
1512 int
1513 bhnd_nvram_getvar_int(device_t dev, const char *name, void *value, int width)
1514 {
1515         bhnd_nvram_type type;
1516         size_t          len;
1517
1518         switch (width) {
1519         case 1:
1520                 type = BHND_NVRAM_TYPE_INT8;
1521                 break;
1522         case 2:
1523                 type = BHND_NVRAM_TYPE_INT16;
1524                 break;
1525         case 4:
1526                 type = BHND_NVRAM_TYPE_INT32;
1527                 break;
1528         default:
1529                 device_printf(dev, "unsupported NVRAM integer width: %d\n",
1530                     width);
1531                 return (EINVAL);
1532         }
1533
1534         len = width;
1535         return (bhnd_nvram_getvar(dev, name, value, &len, type));
1536 }
1537
1538 /**
1539  * Read an NVRAM variable's signed 8-bit integer value.
1540  *
1541  * @param               dev     A bhnd bus child device.
1542  * @param               name    The NVRAM variable name.
1543  * @param[out]          value   On success, the requested value will be written
1544  *                              to this pointer.
1545  * 
1546  * @retval 0            success
1547  * @retval ENOENT       The requested variable was not found.
1548  * @retval ENODEV       No valid NVRAM source could be found.
1549  * @retval EFTYPE       If the variable data cannot be coerced to a
1550  *                      a valid integer representation.
1551  * @retval ERANGE       If value coercion would overflow (or underflow) int8_t.
1552  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1553  *                      error code will be returned.
1554  */
1555 int
1556 bhnd_nvram_getvar_int8(device_t dev, const char *name, int8_t *value)
1557 {
1558         return (bhnd_nvram_getvar_int(dev, name, value, sizeof(*value)));
1559 }
1560
1561 /**
1562  * Read an NVRAM variable's signed 16-bit integer value.
1563  *
1564  * @param               dev     A bhnd bus child device.
1565  * @param               name    The NVRAM variable name.
1566  * @param[out]          value   On success, the requested value will be written
1567  *                              to this pointer.
1568  * 
1569  * @retval 0            success
1570  * @retval ENOENT       The requested variable was not found.
1571  * @retval ENODEV       No valid NVRAM source could be found.
1572  * @retval EFTYPE       If the variable data cannot be coerced to a
1573  *                      a valid integer representation.
1574  * @retval ERANGE       If value coercion would overflow (or underflow)
1575  *                      int16_t.
1576  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1577  *                      error code will be returned.
1578  */
1579 int
1580 bhnd_nvram_getvar_int16(device_t dev, const char *name, int16_t *value)
1581 {
1582         return (bhnd_nvram_getvar_int(dev, name, value, sizeof(*value)));
1583 }
1584
1585 /**
1586  * Read an NVRAM variable's signed 32-bit integer value.
1587  *
1588  * @param               dev     A bhnd bus child device.
1589  * @param               name    The NVRAM variable name.
1590  * @param[out]          value   On success, the requested value will be written
1591  *                              to this pointer.
1592  * 
1593  * @retval 0            success
1594  * @retval ENOENT       The requested variable was not found.
1595  * @retval ENODEV       No valid NVRAM source could be found.
1596  * @retval EFTYPE       If the variable data cannot be coerced to a
1597  *                      a valid integer representation.
1598  * @retval ERANGE       If value coercion would overflow (or underflow)
1599  *                      int32_t.
1600  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1601  *                      error code will be returned.
1602  */
1603 int
1604 bhnd_nvram_getvar_int32(device_t dev, const char *name, int32_t *value)
1605 {
1606         return (bhnd_nvram_getvar_int(dev, name, value, sizeof(*value)));
1607 }
1608
1609
1610 /**
1611  * Read an NVRAM variable's array value.
1612  *
1613  * @param               dev     A bhnd bus child device.
1614  * @param               name    The NVRAM variable name.
1615  * @param[out]          buf     A buffer large enough to hold @p size bytes.
1616  *                              On success, the requested value will be written
1617  *                              to this buffer.
1618  * @param[in,out]       size    The required number of bytes to write to
1619  *                              @p buf.
1620  * @param               type    The desired array element data representation.
1621  * 
1622  * @retval 0            success
1623  * @retval ENOENT       The requested variable was not found.
1624  * @retval ENODEV       No valid NVRAM source could be found.
1625  * @retval ENXIO        If less than @p size bytes are available.
1626  * @retval ENOMEM       If a buffer of @p size is too small to hold the
1627  *                      requested value.
1628  * @retval EFTYPE       If the variable data cannot be coerced to a
1629  *                      a valid instance of @p type.
1630  * @retval ERANGE       If value coercion would overflow (or underflow) a
1631  *                      representation of @p type.
1632  * @retval non-zero     If reading @p name otherwise fails, a regular unix
1633  *                      error code will be returned.
1634  */
1635 int
1636 bhnd_nvram_getvar_array(device_t dev, const char *name, void *buf, size_t size,
1637     bhnd_nvram_type type)
1638 {
1639         size_t  nbytes;
1640         int     error;
1641
1642         /* Attempt read */
1643         nbytes = size;
1644         if ((error = bhnd_nvram_getvar(dev, name, buf, &nbytes, type)))
1645                 return (error);
1646
1647         /* Verify that the expected number of bytes were fetched */
1648         if (nbytes < size)
1649                 return (ENXIO);
1650
1651         return (0);
1652 }
1653
1654 /**
1655  * Initialize a service provider registry.
1656  * 
1657  * @param bsr           The service registry to initialize.
1658  * 
1659  * @retval 0            success
1660  * @retval non-zero     if an error occurs initializing the service registry,
1661  *                      a regular unix error code will be returned.
1662
1663  */
1664 int
1665 bhnd_service_registry_init(struct bhnd_service_registry *bsr)
1666 {
1667         STAILQ_INIT(&bsr->entries);
1668         mtx_init(&bsr->lock, "bhnd_service_registry lock", NULL, MTX_DEF);
1669
1670         return (0);
1671 }
1672
1673 /**
1674  * Release all resources held by @p bsr.
1675  * 
1676  * @param bsr           A service registry instance previously successfully
1677  *                      initialized via bhnd_service_registry_init().
1678  *
1679  * @retval 0            success
1680  * @retval EBUSY        if active references to service providers registered
1681  *                      with @p bsr exist.
1682  */
1683 int
1684 bhnd_service_registry_fini(struct bhnd_service_registry *bsr)
1685 {
1686         struct bhnd_service_entry *entry, *enext;
1687
1688         /* Remove everthing we can */
1689         mtx_lock(&bsr->lock);
1690         STAILQ_FOREACH_SAFE(entry, &bsr->entries, link, enext) {
1691                 if (entry->refs > 0)
1692                         continue;
1693
1694                 STAILQ_REMOVE(&bsr->entries, entry, bhnd_service_entry, link);
1695                 free(entry, M_BHND);
1696         }
1697
1698         if (!STAILQ_EMPTY(&bsr->entries)) {
1699                 mtx_unlock(&bsr->lock);
1700                 return (EBUSY);
1701         }
1702         mtx_unlock(&bsr->lock);
1703
1704         mtx_destroy(&bsr->lock);
1705         return (0);
1706 }
1707
1708 /**
1709  * Register a @p provider for the given @p service.
1710  *
1711  * @param bsr           Service registry to be modified.
1712  * @param provider      Service provider to register.
1713  * @param service       Service for which @p provider will be registered.
1714  * @param flags         Service provider flags (see BHND_SPF_*).
1715  *
1716  * @retval 0            success
1717  * @retval EEXIST       if an entry for @p service already exists.
1718  * @retval EINVAL       if @p service is BHND_SERVICE_ANY.
1719  * @retval non-zero     if registering @p provider otherwise fails, a regular
1720  *                      unix error code will be returned.
1721  */
1722 int
1723 bhnd_service_registry_add(struct bhnd_service_registry *bsr, device_t provider,
1724     bhnd_service_t service, uint32_t flags)
1725 {
1726         struct bhnd_service_entry *entry;
1727
1728         if (service == BHND_SERVICE_ANY)
1729                 return (EINVAL);
1730
1731         mtx_lock(&bsr->lock);
1732
1733         /* Is a service provider already registered? */
1734         STAILQ_FOREACH(entry, &bsr->entries, link) {
1735                 if (entry->service == service) {
1736                         mtx_unlock(&bsr->lock);
1737                         return (EEXIST);
1738                 }
1739         }
1740
1741         /* Initialize and insert our new entry */
1742         entry = malloc(sizeof(*entry), M_BHND, M_NOWAIT);
1743         if (entry == NULL) {
1744                 mtx_unlock(&bsr->lock);
1745                 return (ENOMEM);
1746         }
1747
1748         entry->provider = provider;
1749         entry->service = service;
1750         entry->flags = flags;
1751         refcount_init(&entry->refs, 0);
1752
1753         STAILQ_INSERT_HEAD(&bsr->entries, entry, link);
1754
1755         mtx_unlock(&bsr->lock);
1756         return (0);
1757 }
1758
1759 /**
1760  * Free an unreferenced registry entry.
1761  * 
1762  * @param entry The entry to be deallocated.
1763  */
1764 static void
1765 bhnd_service_registry_free_entry(struct bhnd_service_entry *entry)
1766 {
1767         KASSERT(entry->refs == 0, ("provider has active references"));
1768         free(entry, M_BHND);
1769 }
1770
1771 /**
1772  * Attempt to remove the @p service provider registration for @p provider.
1773  *
1774  * @param bsr           The service registry to be modified.
1775  * @param provider      The service provider to be deregistered.
1776  * @param service       The service for which @p provider will be deregistered,
1777  *                      or BHND_SERVICE_ANY to remove all service
1778  *                      registrations for @p provider.
1779  *
1780  * @retval 0            success
1781  * @retval EBUSY        if active references to @p provider exist; see
1782  *                      bhnd_service_registry_retain() and
1783  *                      bhnd_service_registry_release().
1784  */
1785 int
1786 bhnd_service_registry_remove(struct bhnd_service_registry *bsr,
1787     device_t provider, bhnd_service_t service)
1788 {
1789         struct bhnd_service_entry *entry, *enext;
1790
1791         mtx_lock(&bsr->lock);
1792
1793 #define BHND_PROV_MATCH(_e)     \
1794         ((_e)->provider == provider &&  \
1795          (service == BHND_SERVICE_ANY || (_e)->service == service))
1796
1797         /* Validate matching provider entries before making any
1798          * modifications */
1799         STAILQ_FOREACH(entry, &bsr->entries, link) {
1800                 /* Skip non-matching entries */
1801                 if (!BHND_PROV_MATCH(entry))
1802                         continue;
1803
1804                 /* Entry is in use? */
1805                 if (entry->refs > 0) {
1806                         mtx_unlock(&bsr->lock);
1807                         return (EBUSY);
1808                 }
1809         }
1810
1811         /* We can now safely remove matching entries */
1812         STAILQ_FOREACH_SAFE(entry, &bsr->entries, link, enext) {
1813                 /* Skip non-matching entries */
1814                 if (!BHND_PROV_MATCH(entry))
1815                         continue;
1816
1817                 /* Remove from list */
1818                 STAILQ_REMOVE(&bsr->entries, entry, bhnd_service_entry, link);
1819
1820                 /* Free provider entry */
1821                 bhnd_service_registry_free_entry(entry);
1822         }
1823 #undef  BHND_PROV_MATCH
1824
1825         mtx_unlock(&bsr->lock);
1826         return (0);
1827 }
1828
1829 /**
1830  * Retain and return a reference to a registered @p service provider, if any.
1831  *
1832  * @param bsr           The service registry to be queried.
1833  * @param service       The service for which a provider should be returned.
1834  *
1835  * On success, the caller assumes ownership the returned provider, and
1836  * is responsible for releasing this reference via
1837  * bhnd_service_registry_release().
1838  *
1839  * @retval device_t     success
1840  * @retval NULL         if no provider is registered for @p service.
1841  */
1842 device_t
1843 bhnd_service_registry_retain(struct bhnd_service_registry *bsr,
1844     bhnd_service_t service)
1845 {
1846         struct bhnd_service_entry *entry;
1847
1848         mtx_lock(&bsr->lock);
1849         STAILQ_FOREACH(entry, &bsr->entries, link) {
1850                 if (entry->service != service)
1851                         continue;
1852
1853                 /* With a live refcount, entry is gauranteed to remain alive
1854                  * after we release our lock */
1855                 refcount_acquire(&entry->refs);
1856
1857                 mtx_unlock(&bsr->lock);
1858                 return (entry->provider);
1859         }
1860         mtx_unlock(&bsr->lock);
1861
1862         /* Not found */
1863         return (NULL);
1864 }
1865
1866 /**
1867  * Release a reference to a service provider previously returned by
1868  * bhnd_service_registry_retain().
1869  * 
1870  * If this is the last reference to an inherited service provider registration
1871  * (see BHND_SPF_INHERITED), the registration will also be removed, and
1872  * true will be returned.
1873  *
1874  * @param bsr           The service registry from which @p provider
1875  *                      was returned.
1876  * @param provider      The provider to be released.
1877  * @param service       The service for which @p provider was previously
1878  *                      retained.
1879  * @retval true         The inherited service provider registration was removed;
1880  *                      the caller should release its own reference to the
1881  *                      provider.
1882  * @retval false        The service provider was not inherited, or active
1883  *                      references to the provider remain.
1884  * 
1885  * @see BHND_SPF_INHERITED
1886  */
1887 bool
1888 bhnd_service_registry_release(struct bhnd_service_registry *bsr,
1889     device_t provider, bhnd_service_t service)
1890 {
1891         struct bhnd_service_entry *entry;
1892
1893         /* Exclusive lock, as we need to prevent any new references to the
1894          * entry from being taken if it's to be removed */
1895         mtx_lock(&bsr->lock);
1896         STAILQ_FOREACH(entry, &bsr->entries, link) {
1897                 bool removed;
1898
1899                 if (entry->provider != provider)
1900                         continue;
1901
1902                 if (entry->service != service)
1903                         continue;
1904
1905                 if (refcount_release(&entry->refs) &&
1906                     (entry->flags & BHND_SPF_INHERITED))
1907                 {
1908                         /* If an inherited entry is no longer actively
1909                          * referenced, remove the local registration and inform
1910                          * the caller. */
1911                         STAILQ_REMOVE(&bsr->entries, entry, bhnd_service_entry,
1912                             link);
1913                         bhnd_service_registry_free_entry(entry);
1914                         removed = true;
1915                 } else {
1916                         removed = false;
1917                 }
1918
1919                 mtx_unlock(&bsr->lock);
1920                 return (removed);
1921         }
1922
1923         /* Caller owns a reference, but no such provider is registered? */
1924         panic("invalid service provider reference");
1925 }
1926
1927 /**
1928  * Using the bhnd(4) bus-level core information and a custom core name,
1929  * populate @p dev's device description.
1930  * 
1931  * @param dev A bhnd-bus attached device.
1932  * @param dev_name The core's name (e.g. "SDIO Device Core").
1933  */
1934 void
1935 bhnd_set_custom_core_desc(device_t dev, const char *dev_name)
1936 {
1937         const char *vendor_name;
1938         char *desc;
1939
1940         vendor_name = bhnd_get_vendor_name(dev);
1941         asprintf(&desc, M_BHND, "%s %s, rev %hhu", vendor_name, dev_name,
1942             bhnd_get_hwrev(dev));
1943
1944         if (desc != NULL) {
1945                 device_set_desc_copy(dev, desc);
1946                 free(desc, M_BHND);
1947         } else {
1948                 device_set_desc(dev, dev_name);
1949         }
1950 }
1951
1952 /**
1953  * Using the bhnd(4) bus-level core information, populate @p dev's device
1954  * description.
1955  * 
1956  * @param dev A bhnd-bus attached device.
1957  */
1958 void
1959 bhnd_set_default_core_desc(device_t dev)
1960 {
1961         bhnd_set_custom_core_desc(dev, bhnd_get_device_name(dev));
1962 }
1963
1964
1965 /**
1966  * Using the bhnd @p chip_id, populate the bhnd(4) bus @p dev's device
1967  * description.
1968  * 
1969  * @param dev A bhnd-bus attached device.
1970  * @param chip_id The chip identification.
1971  */
1972 void
1973 bhnd_set_default_bus_desc(device_t dev, const struct bhnd_chipid *chip_id)
1974 {
1975         const char      *bus_name;
1976         char            *desc;
1977         char             chip_name[BHND_CHIPID_MAX_NAMELEN];
1978
1979         /* Determine chip type's bus name */
1980         switch (chip_id->chip_type) {
1981         case BHND_CHIPTYPE_SIBA:
1982                 bus_name = "SIBA bus";
1983                 break;
1984         case BHND_CHIPTYPE_BCMA:
1985         case BHND_CHIPTYPE_BCMA_ALT:
1986                 bus_name = "BCMA bus";
1987                 break;
1988         case BHND_CHIPTYPE_UBUS:
1989                 bus_name = "UBUS bus";
1990                 break;
1991         default:
1992                 bus_name = "Unknown Type";
1993                 break;
1994         }
1995
1996         /* Format chip name */
1997         bhnd_format_chip_id(chip_name, sizeof(chip_name),
1998              chip_id->chip_id);
1999
2000         /* Format and set device description */
2001         asprintf(&desc, M_BHND, "%s %s", chip_name, bus_name);
2002         if (desc != NULL) {
2003                 device_set_desc_copy(dev, desc);
2004                 free(desc, M_BHND);
2005         } else {
2006                 device_set_desc(dev, bus_name);
2007         }
2008         
2009 }
2010
2011 /**
2012  * Helper function for implementing BHND_BUS_REGISTER_PROVIDER().
2013  * 
2014  * This implementation delegates the request to the BHND_BUS_REGISTER_PROVIDER()
2015  * method on the parent of @p dev. If no parent exists, the implementation
2016  * will return an error. 
2017  */
2018 int
2019 bhnd_bus_generic_register_provider(device_t dev, device_t child,
2020     device_t provider, bhnd_service_t service)
2021 {
2022         device_t parent = device_get_parent(dev);
2023
2024         if (parent != NULL) {
2025                 return (BHND_BUS_REGISTER_PROVIDER(parent, child,
2026                     provider, service));
2027         }
2028
2029         return (ENXIO);
2030 }
2031
2032 /**
2033  * Helper function for implementing BHND_BUS_DEREGISTER_PROVIDER().
2034  * 
2035  * This implementation delegates the request to the
2036  * BHND_BUS_DEREGISTER_PROVIDER() method on the parent of @p dev. If no parent
2037  * exists, the implementation will panic.
2038  */
2039 int
2040 bhnd_bus_generic_deregister_provider(device_t dev, device_t child,
2041     device_t provider, bhnd_service_t service)
2042 {
2043         device_t parent = device_get_parent(dev);
2044
2045         if (parent != NULL) {
2046                 return (BHND_BUS_DEREGISTER_PROVIDER(parent, child,
2047                     provider, service));
2048         }
2049
2050         panic("missing BHND_BUS_DEREGISTER_PROVIDER()");
2051 }
2052
2053 /**
2054  * Helper function for implementing BHND_BUS_RETAIN_PROVIDER().
2055  * 
2056  * This implementation delegates the request to the
2057  * BHND_BUS_DEREGISTER_PROVIDER() method on the parent of @p dev. If no parent
2058  * exists, the implementation will return NULL.
2059  */
2060 device_t
2061 bhnd_bus_generic_retain_provider(device_t dev, device_t child,
2062     bhnd_service_t service)
2063 {
2064         device_t parent = device_get_parent(dev);
2065
2066         if (parent != NULL) {
2067                 return (BHND_BUS_RETAIN_PROVIDER(parent, child,
2068                     service));
2069         }
2070
2071         return (NULL);
2072 }
2073
2074 /**
2075  * Helper function for implementing BHND_BUS_RELEASE_PROVIDER().
2076  * 
2077  * This implementation delegates the request to the
2078  * BHND_BUS_DEREGISTER_PROVIDER() method on the parent of @p dev. If no parent
2079  * exists, the implementation will panic.
2080  */
2081 void
2082 bhnd_bus_generic_release_provider(device_t dev, device_t child,
2083     device_t provider, bhnd_service_t service)
2084 {
2085         device_t parent = device_get_parent(dev);
2086
2087         if (parent != NULL) {
2088                 return (BHND_BUS_RELEASE_PROVIDER(parent, child,
2089                     provider, service));
2090         }
2091
2092         panic("missing BHND_BUS_RELEASE_PROVIDER()");
2093 }
2094
2095 /**
2096  * Helper function for implementing BHND_BUS_REGISTER_PROVIDER().
2097  * 
2098  * This implementation uses the bhnd_service_registry_add() function to
2099  * do most of the work. It calls BHND_BUS_GET_SERVICE_REGISTRY() to find
2100  * a suitable service registry to edit.
2101  */
2102 int
2103 bhnd_bus_generic_sr_register_provider(device_t dev, device_t child,
2104     device_t provider, bhnd_service_t service)
2105 {
2106         struct bhnd_service_registry *bsr;
2107
2108         bsr = BHND_BUS_GET_SERVICE_REGISTRY(dev, child);
2109
2110         KASSERT(bsr != NULL, ("NULL service registry"));
2111
2112         return (bhnd_service_registry_add(bsr, provider, service, 0));
2113 }
2114
2115 /**
2116  * Helper function for implementing BHND_BUS_DEREGISTER_PROVIDER().
2117  * 
2118  * This implementation uses the bhnd_service_registry_remove() function to
2119  * do most of the work. It calls BHND_BUS_GET_SERVICE_REGISTRY() to find
2120  * a suitable service registry to edit.
2121  */
2122 int
2123 bhnd_bus_generic_sr_deregister_provider(device_t dev, device_t child,
2124     device_t provider, bhnd_service_t service)
2125 {
2126         struct bhnd_service_registry *bsr;
2127
2128         bsr = BHND_BUS_GET_SERVICE_REGISTRY(dev, child);
2129
2130         KASSERT(bsr != NULL, ("NULL service registry"));
2131
2132         return (bhnd_service_registry_remove(bsr, provider, service));
2133 }
2134
2135 /**
2136  * Helper function for implementing BHND_BUS_RETAIN_PROVIDER().
2137  * 
2138  * This implementation uses the bhnd_service_registry_retain() function to
2139  * do most of the work. It calls BHND_BUS_GET_SERVICE_REGISTRY() to find
2140  * a suitable service registry.
2141  * 
2142  * If a local provider for the service is not available, and a parent device is
2143  * available, this implementation will attempt to fetch and locally register
2144  * a service provider reference from the parent of @p dev.
2145  */
2146 device_t
2147 bhnd_bus_generic_sr_retain_provider(device_t dev, device_t child,
2148     bhnd_service_t service)
2149 {
2150         struct bhnd_service_registry    *bsr;
2151         device_t                         parent, provider;
2152         int                              error;
2153
2154         bsr = BHND_BUS_GET_SERVICE_REGISTRY(dev, child);
2155         KASSERT(bsr != NULL, ("NULL service registry"));
2156
2157         /*
2158          * Attempt to fetch a service provider reference from either the local
2159          * service registry, or if not found, from our parent.
2160          * 
2161          * If we fetch a provider from our parent, we register the provider
2162          * with the local service registry to prevent conflicting local
2163          * registrations from being added.
2164          */
2165         while (1) {
2166                 /* Check the local service registry first */
2167                 provider = bhnd_service_registry_retain(bsr, service);
2168                 if (provider != NULL)
2169                         return (provider);
2170
2171                 /* Otherwise, try to delegate to our parent (if any) */
2172                 if ((parent = device_get_parent(dev)) == NULL)
2173                         return (NULL);
2174
2175                 provider = BHND_BUS_RETAIN_PROVIDER(parent, dev, service);
2176                 if (provider == NULL)
2177                         return (NULL);
2178
2179                 /* Register the inherited service registration with the local
2180                  * registry */
2181                 error = bhnd_service_registry_add(bsr, provider, service,
2182                     BHND_SPF_INHERITED);
2183                 if (error) {
2184                         BHND_BUS_RELEASE_PROVIDER(parent, dev, provider,
2185                             service);
2186                         if (error == EEXIST) {
2187                                 /* A valid service provider was registered
2188                                  * concurrently; retry fetching from the local
2189                                  * registry */
2190                                 continue;
2191                         }
2192
2193                         device_printf(dev, "failed to register service "
2194                             "provider: %d\n", error);
2195                         return (NULL);
2196                 }
2197         }
2198 }
2199
2200 /**
2201  * Helper function for implementing BHND_BUS_RELEASE_PROVIDER().
2202  * 
2203  * This implementation uses the bhnd_service_registry_release() function to
2204  * do most of the work. It calls BHND_BUS_GET_SERVICE_REGISTRY() to find
2205  * a suitable service registry.
2206  */
2207 void
2208 bhnd_bus_generic_sr_release_provider(device_t dev, device_t child,
2209     device_t provider, bhnd_service_t service)
2210 {
2211         struct bhnd_service_registry    *bsr;
2212
2213         bsr = BHND_BUS_GET_SERVICE_REGISTRY(dev, child);
2214         KASSERT(bsr != NULL, ("NULL service registry"));
2215
2216         /* Release the provider reference; if the refcount hits zero on an
2217          * inherited reference, true will be returned, and we need to drop
2218          * our own bus reference to the provider */
2219         if (!bhnd_service_registry_release(bsr, provider, service))
2220                 return;
2221
2222         /* Drop our reference to the borrowed provider */
2223         BHND_BUS_RELEASE_PROVIDER(device_get_parent(dev), dev, provider,
2224             service);
2225 }
2226
2227 /**
2228  * Helper function for implementing BHND_BUS_IS_HW_DISABLED().
2229  * 
2230  * If a parent device is available, this implementation delegates the
2231  * request to the BHND_BUS_IS_HW_DISABLED() method on the parent of @p dev.
2232  * 
2233  * If no parent device is available (i.e. on a the bus root), the hardware
2234  * is assumed to be usable and false is returned.
2235  */
2236 bool
2237 bhnd_bus_generic_is_hw_disabled(device_t dev, device_t child)
2238 {
2239         if (device_get_parent(dev) != NULL)
2240                 return (BHND_BUS_IS_HW_DISABLED(device_get_parent(dev), child));
2241
2242         return (false);
2243 }
2244
2245 /**
2246  * Helper function for implementing BHND_BUS_GET_CHIPID().
2247  * 
2248  * This implementation delegates the request to the BHND_BUS_GET_CHIPID()
2249  * method on the parent of @p dev. If no parent exists, the implementation
2250  * will panic.
2251  */
2252 const struct bhnd_chipid *
2253 bhnd_bus_generic_get_chipid(device_t dev, device_t child)
2254 {
2255         if (device_get_parent(dev) != NULL)
2256                 return (BHND_BUS_GET_CHIPID(device_get_parent(dev), child));
2257
2258         panic("missing BHND_BUS_GET_CHIPID()");
2259 }
2260
2261 /**
2262  * Helper function for implementing BHND_BUS_GET_DMA_TRANSLATION().
2263  * 
2264  * If a parent device is available, this implementation delegates the
2265  * request to the BHND_BUS_GET_DMA_TRANSLATION() method on the parent of @p dev.
2266  *
2267  * If no parent device is available, this implementation will panic.
2268  */
2269 int
2270 bhnd_bus_generic_get_dma_translation(device_t dev, device_t child, u_int width,
2271     uint32_t flags, bus_dma_tag_t *dmat,
2272     struct bhnd_dma_translation *translation)
2273 {
2274         if (device_get_parent(dev) != NULL) {
2275                 return (BHND_BUS_GET_DMA_TRANSLATION(device_get_parent(dev),
2276                     child, width, flags, dmat, translation));
2277         }
2278
2279         panic("missing BHND_BUS_GET_DMA_TRANSLATION()");
2280 }
2281
2282 /* nvram board_info population macros for bhnd_bus_generic_read_board_info() */
2283 #define BHND_GV(_dest, _name)   \
2284         bhnd_nvram_getvar_uint(child, BHND_NVAR_ ## _name, &_dest,      \
2285             sizeof(_dest))
2286
2287 #define REQ_BHND_GV(_dest, _name)               do {                    \
2288         if ((error = BHND_GV(_dest, _name))) {                          \
2289                 device_printf(dev,                                      \
2290                     "error reading " __STRING(_name) ": %d\n", error);  \
2291                 return (error);                                         \
2292         }                                                               \
2293 } while(0)
2294
2295 #define OPT_BHND_GV(_dest, _name, _default)     do {                    \
2296         if ((error = BHND_GV(_dest, _name))) {                          \
2297                 if (error != ENOENT) {                                  \
2298                         device_printf(dev,                              \
2299                             "error reading "                            \
2300                                __STRING(_name) ": %d\n", error);        \
2301                         return (error);                                 \
2302                 }                                                       \
2303                 _dest = _default;                                       \
2304         }                                                               \
2305 } while(0)
2306
2307 /**
2308  * Helper function for implementing BHND_BUS_READ_BOARDINFO().
2309  * 
2310  * This implementation populates @p info with information from NVRAM,
2311  * defaulting board_vendor and board_type fields to 0 if the
2312  * requested variables cannot be found.
2313  * 
2314  * This behavior is correct for most SoCs, but must be overridden on
2315  * bridged (PCI, PCMCIA, etc) devices to produce a complete bhnd_board_info
2316  * result.
2317  */
2318 int
2319 bhnd_bus_generic_read_board_info(device_t dev, device_t child,
2320     struct bhnd_board_info *info)
2321 {
2322         int     error;
2323
2324         OPT_BHND_GV(info->board_vendor, BOARDVENDOR,    0);
2325         OPT_BHND_GV(info->board_type,   BOARDTYPE,      0);     /* srom >= 2 */
2326         REQ_BHND_GV(info->board_rev,    BOARDREV);
2327         OPT_BHND_GV(info->board_srom_rev,SROMREV,       0);     /* missing in
2328                                                                    some SoC
2329                                                                    NVRAM */
2330         REQ_BHND_GV(info->board_flags,  BOARDFLAGS);
2331         OPT_BHND_GV(info->board_flags2, BOARDFLAGS2,    0);     /* srom >= 4 */
2332         OPT_BHND_GV(info->board_flags3, BOARDFLAGS3,    0);     /* srom >= 11 */
2333
2334         return (0);
2335 }
2336
2337 #undef  BHND_GV
2338 #undef  BHND_GV_REQ
2339 #undef  BHND_GV_OPT
2340
2341 /**
2342  * Helper function for implementing BHND_BUS_GET_NVRAM_VAR().
2343  * 
2344  * This implementation searches @p dev for a usable NVRAM child device.
2345  * 
2346  * If no usable child device is found on @p dev, the request is delegated to
2347  * the BHND_BUS_GET_NVRAM_VAR() method on the parent of @p dev.
2348  */
2349 int
2350 bhnd_bus_generic_get_nvram_var(device_t dev, device_t child, const char *name,
2351     void *buf, size_t *size, bhnd_nvram_type type)
2352 {
2353         device_t        nvram;
2354         device_t        parent;
2355
2356         /* Make sure we're holding Giant for newbus */
2357         GIANT_REQUIRED;
2358
2359         /* Look for a directly-attached NVRAM child */
2360         if ((nvram = device_find_child(dev, "bhnd_nvram", -1)) != NULL)
2361                 return BHND_NVRAM_GETVAR(nvram, name, buf, size, type);
2362
2363         /* Try to delegate to parent */
2364         if ((parent = device_get_parent(dev)) == NULL)
2365                 return (ENODEV);
2366
2367         return (BHND_BUS_GET_NVRAM_VAR(device_get_parent(dev), child,
2368             name, buf, size, type));
2369 }
2370
2371 /**
2372  * Helper function for implementing BHND_BUS_ALLOC_RESOURCE().
2373  * 
2374  * This implementation of BHND_BUS_ALLOC_RESOURCE() delegates allocation
2375  * of the underlying resource to BUS_ALLOC_RESOURCE(), and activation
2376  * to @p dev's BHND_BUS_ACTIVATE_RESOURCE().
2377  */
2378 struct bhnd_resource *
2379 bhnd_bus_generic_alloc_resource(device_t dev, device_t child, int type,
2380         int *rid, rman_res_t start, rman_res_t end, rman_res_t count,
2381         u_int flags)
2382 {
2383         struct bhnd_resource    *br;
2384         struct resource         *res;
2385         int                      error;
2386
2387         br = NULL;
2388         res = NULL;
2389
2390         /* Allocate the real bus resource (without activating it) */
2391         res = BUS_ALLOC_RESOURCE(dev, child, type, rid, start, end, count,
2392             (flags & ~RF_ACTIVE));
2393         if (res == NULL)
2394                 return (NULL);
2395
2396         /* Allocate our bhnd resource wrapper. */
2397         br = malloc(sizeof(struct bhnd_resource), M_BHND, M_NOWAIT);
2398         if (br == NULL)
2399                 goto failed;
2400         
2401         br->direct = false;
2402         br->res = res;
2403
2404         /* Attempt activation */
2405         if (flags & RF_ACTIVE) {
2406                 error = BHND_BUS_ACTIVATE_RESOURCE(dev, child, type, *rid, br);
2407                 if (error)
2408                         goto failed;
2409         }
2410
2411         return (br);
2412         
2413 failed:
2414         if (res != NULL)
2415                 BUS_RELEASE_RESOURCE(dev, child, type, *rid, res);
2416
2417         free(br, M_BHND);
2418         return (NULL);
2419 }
2420
2421 /**
2422  * Helper function for implementing BHND_BUS_RELEASE_RESOURCE().
2423  * 
2424  * This implementation of BHND_BUS_RELEASE_RESOURCE() delegates release of
2425  * the backing resource to BUS_RELEASE_RESOURCE().
2426  */
2427 int
2428 bhnd_bus_generic_release_resource(device_t dev, device_t child, int type,
2429     int rid, struct bhnd_resource *r)
2430 {
2431         int error;
2432
2433         if ((error = BUS_RELEASE_RESOURCE(dev, child, type, rid, r->res)))
2434                 return (error);
2435
2436         free(r, M_BHND);
2437         return (0);
2438 }
2439
2440
2441 /**
2442  * Helper function for implementing BHND_BUS_ACTIVATE_RESOURCE().
2443  * 
2444  * This implementation of BHND_BUS_ACTIVATE_RESOURCE() first calls the
2445  * BHND_BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
2446  * 
2447  * If this fails, and if @p dev is the direct parent of @p child, standard
2448  * resource activation is attempted via bus_activate_resource(). This enables
2449  * direct use of the bhnd(4) resource APIs on devices that may not be attached
2450  * to a parent bhnd bus or bridge.
2451  */
2452 int
2453 bhnd_bus_generic_activate_resource(device_t dev, device_t child, int type,
2454     int rid, struct bhnd_resource *r)
2455 {
2456         int     error;
2457         bool    passthrough;
2458
2459         passthrough = (device_get_parent(child) != dev);
2460
2461         /* Try to delegate to the parent */
2462         if (device_get_parent(dev) != NULL) {
2463                 error = BHND_BUS_ACTIVATE_RESOURCE(device_get_parent(dev),
2464                     child, type, rid, r);
2465         } else {
2466                 error = ENODEV;
2467         }
2468
2469         /* If bhnd(4) activation has failed and we're the child's direct
2470          * parent, try falling back on standard resource activation.
2471          */
2472         if (error && !passthrough) {
2473                 error = bus_activate_resource(child, type, rid, r->res);
2474                 if (!error)
2475                         r->direct = true;
2476         }
2477
2478         return (error);
2479 }
2480
2481 /**
2482  * Helper function for implementing BHND_BUS_DEACTIVATE_RESOURCE().
2483  * 
2484  * This implementation of BHND_BUS_ACTIVATE_RESOURCE() simply calls the
2485  * BHND_BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
2486  */
2487 int
2488 bhnd_bus_generic_deactivate_resource(device_t dev, device_t child,
2489     int type, int rid, struct bhnd_resource *r)
2490 {
2491         if (device_get_parent(dev) != NULL)
2492                 return (BHND_BUS_DEACTIVATE_RESOURCE(device_get_parent(dev),
2493                     child, type, rid, r));
2494
2495         return (EINVAL);
2496 }
2497
2498 /**
2499  * Helper function for implementing BHND_BUS_GET_INTR_DOMAIN().
2500  * 
2501  * This implementation simply returns the address of nearest bhnd(4) bus,
2502  * which may be @p dev; this behavior may be incompatible with FDT/OFW targets.
2503  */
2504 uintptr_t
2505 bhnd_bus_generic_get_intr_domain(device_t dev, device_t child, bool self)
2506 {
2507         return ((uintptr_t)dev);
2508 }