Home | History | Annotate | Line # | Download | only in usb
ubt.c revision 1.52
      1 /*	$NetBSD: ubt.c,v 1.52 2016/02/17 00:49:28 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2006 Itronix Inc.
      5  * All rights reserved.
      6  *
      7  * Written by Iain Hibbert for Itronix Inc.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. The name of Itronix Inc. may not be used to endorse
     18  *    or promote products derived from this software without specific
     19  *    prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ITRONIX INC. BE LIABLE FOR ANY
     25  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     28  * ON ANY THEORY OF LIABILITY, WHETHER IN
     29  * 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 THE
     31  * POSSIBILITY OF SUCH DAMAGE.
     32  */
     33 /*
     34  * Copyright (c) 2002, 2003 The NetBSD Foundation, Inc.
     35  * All rights reserved.
     36  *
     37  * This code is derived from software contributed to The NetBSD Foundation
     38  * by Lennart Augustsson (lennart (at) augustsson.net) and
     39  * David Sainty (David.Sainty (at) dtsp.co.nz).
     40  *
     41  * Redistribution and use in source and binary forms, with or without
     42  * modification, are permitted provided that the following conditions
     43  * are met:
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  *
     50  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     51  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     52  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     53  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     54  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     55  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     56  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     57  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     58  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     59  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     60  * POSSIBILITY OF SUCH DAMAGE.
     61  */
     62 /*
     63  * This driver originally written by Lennart Augustsson and David Sainty,
     64  * but was mostly rewritten for the NetBSD Bluetooth protocol stack by
     65  * Iain Hibbert for Itronix, Inc using the FreeBSD ng_ubt.c driver as a
     66  * reference.
     67  */
     68 
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: ubt.c,v 1.52 2016/02/17 00:49:28 riastradh Exp $");
     71 
     72 #include <sys/param.h>
     73 #include <sys/device.h>
     74 #include <sys/ioctl.h>
     75 #include <sys/kernel.h>
     76 #include <sys/malloc.h>
     77 #include <sys/mbuf.h>
     78 #include <sys/proc.h>
     79 #include <sys/sysctl.h>
     80 #include <sys/systm.h>
     81 
     82 #include <dev/usb/usb.h>
     83 #include <dev/usb/usbdi.h>
     84 #include <dev/usb/usbdi_util.h>
     85 #include <dev/usb/usbdevs.h>
     86 
     87 #include <netbt/bluetooth.h>
     88 #include <netbt/hci.h>
     89 
     90 /*******************************************************************************
     91  *
     92  *	debugging stuff
     93  */
     94 #undef DPRINTF
     95 #undef DPRINTFN
     96 
     97 #ifdef UBT_DEBUG
     98 int	ubt_debug = 0;
     99 
    100 #define DPRINTF(...)		do {		\
    101 	if (ubt_debug) {			\
    102 		printf("%s: ", __func__);	\
    103 		printf(__VA_ARGS__);		\
    104 	}					\
    105 } while (/* CONSTCOND */0)
    106 
    107 #define DPRINTFN(n, ...)	do {		\
    108 	if (ubt_debug > (n)) {			\
    109 		printf("%s: ", __func__);	\
    110 		printf(__VA_ARGS__);		\
    111 	}					\
    112 } while (/* CONSTCOND */0)
    113 
    114 SYSCTL_SETUP(sysctl_hw_ubt_debug_setup, "sysctl hw.ubt_debug setup")
    115 {
    116 
    117 	sysctl_createv(NULL, 0, NULL, NULL,
    118 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    119 		CTLTYPE_INT, "ubt_debug",
    120 		SYSCTL_DESCR("ubt debug level"),
    121 		NULL, 0,
    122 		&ubt_debug, sizeof(ubt_debug),
    123 		CTL_HW, CTL_CREATE, CTL_EOL);
    124 }
    125 #else
    126 #define DPRINTF(...)
    127 #define DPRINTFN(...)
    128 #endif
    129 
    130 /*******************************************************************************
    131  *
    132  *	ubt softc structure
    133  *
    134  */
    135 
    136 /* buffer sizes */
    137 /*
    138  * NB: although ACL packets can extend to 65535 bytes, most devices
    139  * have max_acl_size at much less (largest I have seen is 384)
    140  */
    141 #define UBT_BUFSIZ_CMD		(HCI_CMD_PKT_SIZE - 1)
    142 #define UBT_BUFSIZ_ACL		(2048 - 1)
    143 #define UBT_BUFSIZ_EVENT	(HCI_EVENT_PKT_SIZE - 1)
    144 
    145 /* Transmit timeouts */
    146 #define UBT_CMD_TIMEOUT		USBD_DEFAULT_TIMEOUT
    147 #define UBT_ACL_TIMEOUT		USBD_DEFAULT_TIMEOUT
    148 
    149 /*
    150  * ISOC transfers
    151  *
    152  * xfer buffer size depends on the frame size, and the number
    153  * of frames per transfer is fixed, as each frame should be
    154  * 1ms worth of data. This keeps the rate that xfers complete
    155  * fairly constant. We use multiple xfers to keep the hardware
    156  * busy
    157  */
    158 #define UBT_NXFERS		3	/* max xfers to queue */
    159 #define UBT_NFRAMES		10	/* frames per xfer */
    160 
    161 struct ubt_isoc_xfer {
    162 	struct ubt_softc	*softc;
    163 	usbd_xfer_handle	 xfer;
    164 	uint8_t			*buf;
    165 	uint16_t		 size[UBT_NFRAMES];
    166 	int			 busy;
    167 };
    168 
    169 struct ubt_softc {
    170 	device_t		 sc_dev;
    171 	usbd_device_handle	 sc_udev;
    172 	int			 sc_refcnt;
    173 	int			 sc_dying;
    174 	int			 sc_enabled;
    175 
    176 	/* Control Interface */
    177 	usbd_interface_handle	 sc_iface0;
    178 
    179 	/* Commands (control) */
    180 	usbd_xfer_handle	 sc_cmd_xfer;
    181 	uint8_t			*sc_cmd_buf;
    182 	int			 sc_cmd_busy;	/* write active */
    183 	MBUFQ_HEAD()		 sc_cmd_queue;	/* output queue */
    184 
    185 	/* Events (interrupt) */
    186 	int			 sc_evt_addr;	/* endpoint address */
    187 	usbd_pipe_handle	 sc_evt_pipe;
    188 	uint8_t			*sc_evt_buf;
    189 
    190 	/* ACL data (in) */
    191 	int			 sc_aclrd_addr;	/* endpoint address */
    192 	usbd_pipe_handle	 sc_aclrd_pipe;	/* read pipe */
    193 	usbd_xfer_handle	 sc_aclrd_xfer;	/* read xfer */
    194 	uint8_t			*sc_aclrd_buf;	/* read buffer */
    195 	int			 sc_aclrd_busy;	/* reading */
    196 
    197 	/* ACL data (out) */
    198 	int			 sc_aclwr_addr;	/* endpoint address */
    199 	usbd_pipe_handle	 sc_aclwr_pipe;	/* write pipe */
    200 	usbd_xfer_handle	 sc_aclwr_xfer;	/* write xfer */
    201 	uint8_t			*sc_aclwr_buf;	/* write buffer */
    202 	int			 sc_aclwr_busy;	/* write active */
    203 	MBUFQ_HEAD()		 sc_aclwr_queue;/* output queue */
    204 
    205 	/* ISOC interface */
    206 	usbd_interface_handle	 sc_iface1;	/* ISOC interface */
    207 	struct sysctllog	*sc_log;	/* sysctl log */
    208 	int			 sc_config;	/* current config no */
    209 	int			 sc_alt_config;	/* no of alternates */
    210 
    211 	/* SCO data (in) */
    212 	int			 sc_scord_addr;	/* endpoint address */
    213 	usbd_pipe_handle	 sc_scord_pipe;	/* read pipe */
    214 	int			 sc_scord_size;	/* frame length */
    215 	struct ubt_isoc_xfer	 sc_scord[UBT_NXFERS];
    216 	struct mbuf		*sc_scord_mbuf;	/* current packet */
    217 
    218 	/* SCO data (out) */
    219 	int			 sc_scowr_addr;	/* endpoint address */
    220 	usbd_pipe_handle	 sc_scowr_pipe;	/* write pipe */
    221 	int			 sc_scowr_size;	/* frame length */
    222 	struct ubt_isoc_xfer	 sc_scowr[UBT_NXFERS];
    223 	struct mbuf		*sc_scowr_mbuf;	/* current packet */
    224 	int			 sc_scowr_busy;	/* write active */
    225 	MBUFQ_HEAD()		 sc_scowr_queue;/* output queue */
    226 
    227 	/* Protocol structure */
    228 	struct hci_unit		*sc_unit;
    229 	struct bt_stats		 sc_stats;
    230 
    231 	/* Successfully attached */
    232 	int			 sc_ok;
    233 };
    234 
    235 /*******************************************************************************
    236  *
    237  * Bluetooth unit/USB callback routines
    238  *
    239  */
    240 static int ubt_enable(device_t);
    241 static void ubt_disable(device_t);
    242 
    243 static void ubt_xmit_cmd(device_t, struct mbuf *);
    244 static void ubt_xmit_cmd_start(struct ubt_softc *);
    245 static void ubt_xmit_cmd_complete(usbd_xfer_handle,
    246 				usbd_private_handle, usbd_status);
    247 
    248 static void ubt_xmit_acl(device_t, struct mbuf *);
    249 static void ubt_xmit_acl_start(struct ubt_softc *);
    250 static void ubt_xmit_acl_complete(usbd_xfer_handle,
    251 				usbd_private_handle, usbd_status);
    252 
    253 static void ubt_xmit_sco(device_t, struct mbuf *);
    254 static void ubt_xmit_sco_start(struct ubt_softc *);
    255 static void ubt_xmit_sco_start1(struct ubt_softc *, struct ubt_isoc_xfer *);
    256 static void ubt_xmit_sco_complete(usbd_xfer_handle,
    257 				usbd_private_handle, usbd_status);
    258 
    259 static void ubt_recv_event(usbd_xfer_handle,
    260 				usbd_private_handle, usbd_status);
    261 
    262 static void ubt_recv_acl_start(struct ubt_softc *);
    263 static void ubt_recv_acl_complete(usbd_xfer_handle,
    264 				usbd_private_handle, usbd_status);
    265 
    266 static void ubt_recv_sco_start1(struct ubt_softc *, struct ubt_isoc_xfer *);
    267 static void ubt_recv_sco_complete(usbd_xfer_handle,
    268 				usbd_private_handle, usbd_status);
    269 
    270 static void ubt_stats(device_t, struct bt_stats *, int);
    271 
    272 static const struct hci_if ubt_hci = {
    273 	.enable = ubt_enable,
    274 	.disable = ubt_disable,
    275 	.output_cmd = ubt_xmit_cmd,
    276 	.output_acl = ubt_xmit_acl,
    277 	.output_sco = ubt_xmit_sco,
    278 	.get_stats = ubt_stats,
    279 	.ipl = IPL_USB,		/* IPL_SOFTUSB ??? */
    280 };
    281 
    282 /*******************************************************************************
    283  *
    284  * USB Autoconfig stuff
    285  *
    286  */
    287 
    288 int             ubt_match(device_t, cfdata_t, void *);
    289 void            ubt_attach(device_t, device_t, void *);
    290 int             ubt_detach(device_t, int);
    291 int             ubt_activate(device_t, enum devact);
    292 extern struct cfdriver ubt_cd;
    293 CFATTACH_DECL_NEW(ubt, sizeof(struct ubt_softc), ubt_match, ubt_attach, ubt_detach, ubt_activate);
    294 
    295 static int ubt_set_isoc_config(struct ubt_softc *);
    296 static int ubt_sysctl_config(SYSCTLFN_PROTO);
    297 static void ubt_abortdealloc(struct ubt_softc *);
    298 
    299 /*
    300  * To match or ignore forcibly, add
    301  *
    302  *	{ { VendorID, ProductID } , UMATCH_VENDOR_PRODUCT|UMATCH_NONE }
    303  *
    304  * to the ubt_dev list.
    305  */
    306 const struct ubt_devno {
    307 	struct usb_devno	devno;
    308 	int			match;
    309 } ubt_dev[] = {
    310 	{ { USB_VENDOR_BROADCOM, USB_PRODUCT_BROADCOM_BCM2033NF },
    311 	  UMATCH_NONE },
    312 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_1 },
    313 	  UMATCH_VENDOR_PRODUCT },
    314 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_2 },
    315 	  UMATCH_VENDOR_PRODUCT },
    316 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_3 },
    317 	  UMATCH_VENDOR_PRODUCT },
    318 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_4 },
    319 	  UMATCH_VENDOR_PRODUCT },
    320 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_5 },
    321 	  UMATCH_VENDOR_PRODUCT },
    322 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_6 },
    323 	  UMATCH_VENDOR_PRODUCT },
    324 	{ { USB_VENDOR_APPLE, USB_PRODUCT_APPLE_BLUETOOTH_HOST_7 },
    325 	  UMATCH_VENDOR_PRODUCT },
    326 };
    327 #define ubt_lookup(vendor, product) \
    328 	((const struct ubt_devno *)usb_lookup(ubt_dev, vendor, product))
    329 
    330 int
    331 ubt_match(device_t parent, cfdata_t match, void *aux)
    332 {
    333 	struct usb_attach_arg *uaa = aux;
    334 	const struct ubt_devno *dev;
    335 
    336 	DPRINTFN(50, "ubt_match\n");
    337 
    338 	if ((dev = ubt_lookup(uaa->vendor, uaa->product)) != NULL)
    339 		return dev->match;
    340 
    341 	if (uaa->class == UDCLASS_WIRELESS
    342 	    && uaa->subclass == UDSUBCLASS_RF
    343 	    && uaa->proto == UDPROTO_BLUETOOTH)
    344 		return UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO;
    345 
    346 	return UMATCH_NONE;
    347 }
    348 
    349 void
    350 ubt_attach(device_t parent, device_t self, void *aux)
    351 {
    352 	struct ubt_softc *sc = device_private(self);
    353 	struct usb_attach_arg *uaa = aux;
    354 	usb_config_descriptor_t *cd;
    355 	usb_endpoint_descriptor_t *ed;
    356 	const struct sysctlnode *node;
    357 	char *devinfop;
    358 	int err;
    359 	uint8_t count, i;
    360 
    361 	DPRINTFN(50, "ubt_attach: sc=%p\n", sc);
    362 
    363 	sc->sc_dev = self;
    364 	sc->sc_udev = uaa->device;
    365 
    366 	MBUFQ_INIT(&sc->sc_cmd_queue);
    367 	MBUFQ_INIT(&sc->sc_aclwr_queue);
    368 	MBUFQ_INIT(&sc->sc_scowr_queue);
    369 
    370 	aprint_naive("\n");
    371 	aprint_normal("\n");
    372 
    373 	devinfop = usbd_devinfo_alloc(sc->sc_udev, 0);
    374 	aprint_normal_dev(self, "%s\n", devinfop);
    375 	usbd_devinfo_free(devinfop);
    376 
    377 	/*
    378 	 * Move the device into the configured state
    379 	 */
    380 	err = usbd_set_config_index(sc->sc_udev, 0, 1);
    381 	if (err) {
    382 		aprint_error_dev(self, "failed to set configuration idx 0: %s\n",
    383 		    usbd_errstr(err));
    384 
    385 		return;
    386 	}
    387 
    388 	/*
    389 	 * Interface 0 must have 3 endpoints
    390 	 *	1) Interrupt endpoint to receive HCI events
    391 	 *	2) Bulk IN endpoint to receive ACL data
    392 	 *	3) Bulk OUT endpoint to send ACL data
    393 	 */
    394 	err = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface0);
    395 	if (err) {
    396 		aprint_error_dev(self, "Could not get interface 0 handle %s (%d)\n",
    397 				usbd_errstr(err), err);
    398 
    399 		return;
    400 	}
    401 
    402 	sc->sc_evt_addr = -1;
    403 	sc->sc_aclrd_addr = -1;
    404 	sc->sc_aclwr_addr = -1;
    405 
    406 	count = 0;
    407 	(void)usbd_endpoint_count(sc->sc_iface0, &count);
    408 
    409 	for (i = 0 ; i < count ; i++) {
    410 		int dir, type;
    411 
    412 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface0, i);
    413 		if (ed == NULL) {
    414 			aprint_error_dev(self,
    415 			    "could not read endpoint descriptor %d\n", i);
    416 
    417 			return;
    418 		}
    419 
    420 		dir = UE_GET_DIR(ed->bEndpointAddress);
    421 		type = UE_GET_XFERTYPE(ed->bmAttributes);
    422 
    423 		if (dir == UE_DIR_IN && type == UE_INTERRUPT)
    424 			sc->sc_evt_addr = ed->bEndpointAddress;
    425 		else if (dir == UE_DIR_IN && type == UE_BULK)
    426 			sc->sc_aclrd_addr = ed->bEndpointAddress;
    427 		else if (dir == UE_DIR_OUT && type == UE_BULK)
    428 			sc->sc_aclwr_addr = ed->bEndpointAddress;
    429 	}
    430 
    431 	if (sc->sc_evt_addr == -1) {
    432 		aprint_error_dev(self,
    433 		    "missing INTERRUPT endpoint on interface 0\n");
    434 
    435 		return;
    436 	}
    437 	if (sc->sc_aclrd_addr == -1) {
    438 		aprint_error_dev(self,
    439 		    "missing BULK IN endpoint on interface 0\n");
    440 
    441 		return;
    442 	}
    443 	if (sc->sc_aclwr_addr == -1) {
    444 		aprint_error_dev(self,
    445 		    "missing BULK OUT endpoint on interface 0\n");
    446 
    447 		return;
    448 	}
    449 
    450 	/*
    451 	 * Interface 1 must have 2 endpoints
    452 	 *	1) Isochronous IN endpoint to receive SCO data
    453 	 *	2) Isochronous OUT endpoint to send SCO data
    454 	 *
    455 	 * and will have several configurations, which can be selected
    456 	 * via a sysctl variable. We select config 0 to start, which
    457 	 * means that no SCO data will be available.
    458 	 */
    459 	err = usbd_device2interface_handle(sc->sc_udev, 1, &sc->sc_iface1);
    460 	if (err) {
    461 		aprint_error_dev(self,
    462 		    "Could not get interface 1 handle %s (%d)\n",
    463 		    usbd_errstr(err), err);
    464 
    465 		return;
    466 	}
    467 
    468 	cd = usbd_get_config_descriptor(sc->sc_udev);
    469 	if (cd == NULL) {
    470 		aprint_error_dev(self, "could not get config descriptor\n");
    471 
    472 		return;
    473 	}
    474 
    475 	sc->sc_alt_config = usbd_get_no_alts(cd, 1);
    476 
    477 	/* set initial config */
    478 	err = ubt_set_isoc_config(sc);
    479 	if (err) {
    480 		aprint_error_dev(self, "ISOC config failed\n");
    481 
    482 		return;
    483 	}
    484 
    485 	/* Attach HCI */
    486 	sc->sc_unit = hci_attach_pcb(&ubt_hci, sc->sc_dev, 0);
    487 
    488 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    489 			   sc->sc_dev);
    490 
    491 	/* sysctl set-up for alternate configs */
    492 	sysctl_createv(&sc->sc_log, 0, NULL, &node,
    493 		0,
    494 		CTLTYPE_NODE, device_xname(sc->sc_dev),
    495 		SYSCTL_DESCR("ubt driver information"),
    496 		NULL, 0,
    497 		NULL, 0,
    498 		CTL_HW,
    499 		CTL_CREATE, CTL_EOL);
    500 
    501 	if (node != NULL) {
    502 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    503 			CTLFLAG_READWRITE,
    504 			CTLTYPE_INT, "config",
    505 			SYSCTL_DESCR("configuration number"),
    506 			ubt_sysctl_config, 0,
    507 			(void *)sc, 0,
    508 			CTL_HW, node->sysctl_num,
    509 			CTL_CREATE, CTL_EOL);
    510 
    511 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    512 			CTLFLAG_READONLY,
    513 			CTLTYPE_INT, "alt_config",
    514 			SYSCTL_DESCR("number of alternate configurations"),
    515 			NULL, 0,
    516 			&sc->sc_alt_config, sizeof(sc->sc_alt_config),
    517 			CTL_HW, node->sysctl_num,
    518 			CTL_CREATE, CTL_EOL);
    519 
    520 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    521 			CTLFLAG_READONLY,
    522 			CTLTYPE_INT, "sco_rxsize",
    523 			SYSCTL_DESCR("max SCO receive size"),
    524 			NULL, 0,
    525 			&sc->sc_scord_size, sizeof(sc->sc_scord_size),
    526 			CTL_HW, node->sysctl_num,
    527 			CTL_CREATE, CTL_EOL);
    528 
    529 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    530 			CTLFLAG_READONLY,
    531 			CTLTYPE_INT, "sco_txsize",
    532 			SYSCTL_DESCR("max SCO transmit size"),
    533 			NULL, 0,
    534 			&sc->sc_scowr_size, sizeof(sc->sc_scowr_size),
    535 			CTL_HW, node->sysctl_num,
    536 			CTL_CREATE, CTL_EOL);
    537 	}
    538 
    539 	sc->sc_ok = 1;
    540 
    541 	if (!pmf_device_register(self, NULL, NULL))
    542 		aprint_error_dev(self, "couldn't establish power handler\n");
    543 
    544 	return;
    545 }
    546 
    547 int
    548 ubt_detach(device_t self, int flags)
    549 {
    550 	struct ubt_softc *sc = device_private(self);
    551 	int s;
    552 
    553 	DPRINTF("sc=%p flags=%d\n", sc, flags);
    554 
    555 	pmf_device_deregister(self);
    556 
    557 	sc->sc_dying = 1;
    558 
    559 	if (!sc->sc_ok)
    560 		return 0;
    561 
    562 	/* delete sysctl nodes */
    563 	sysctl_teardown(&sc->sc_log);
    564 
    565 	/* Detach HCI interface */
    566 	if (sc->sc_unit) {
    567 		hci_detach_pcb(sc->sc_unit);
    568 		sc->sc_unit = NULL;
    569 	}
    570 
    571 	/*
    572 	 * Abort all pipes. Causes processes waiting for transfer to wake.
    573 	 *
    574 	 * Actually, hci_detach_pcb() above will call ubt_disable() which
    575 	 * may call ubt_abortdealloc(), but lets be sure since doing it
    576 	 * twice wont cause an error.
    577 	 */
    578 	ubt_abortdealloc(sc);
    579 
    580 	/* wait for all processes to finish */
    581 	s = splusb();
    582 	if (sc->sc_refcnt-- > 0)
    583 		usb_detach_waitold(sc->sc_dev);
    584 
    585 	splx(s);
    586 
    587 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    588 			   sc->sc_dev);
    589 
    590 	DPRINTFN(1, "driver detached\n");
    591 
    592 	return 0;
    593 }
    594 
    595 int
    596 ubt_activate(device_t self, enum devact act)
    597 {
    598 	struct ubt_softc *sc = device_private(self);
    599 
    600 	DPRINTFN(1, "sc=%p, act=%d\n", sc, act);
    601 
    602 	switch (act) {
    603 	case DVACT_DEACTIVATE:
    604 		sc->sc_dying = 1;
    605 		return 0;
    606 	default:
    607 		return EOPNOTSUPP;
    608 	}
    609 }
    610 
    611 /* set ISOC configuration */
    612 static int
    613 ubt_set_isoc_config(struct ubt_softc *sc)
    614 {
    615 	usb_endpoint_descriptor_t *ed;
    616 	int rd_addr, wr_addr, rd_size, wr_size;
    617 	uint8_t count, i;
    618 	int err;
    619 
    620 	err = usbd_set_interface(sc->sc_iface1, sc->sc_config);
    621 	if (err != USBD_NORMAL_COMPLETION) {
    622 		aprint_error_dev(sc->sc_dev,
    623 		    "Could not set config %d on ISOC interface. %s (%d)\n",
    624 		    sc->sc_config, usbd_errstr(err), err);
    625 
    626 		return err == USBD_IN_USE ? EBUSY : EIO;
    627 	}
    628 
    629 	/*
    630 	 * We wont get past the above if there are any pipes open, so no
    631 	 * need to worry about buf/xfer/pipe deallocation. If we get an
    632 	 * error after this, the frame quantities will be 0 and no SCO
    633 	 * data will be possible.
    634 	 */
    635 
    636 	sc->sc_scord_size = rd_size = 0;
    637 	sc->sc_scord_addr = rd_addr = -1;
    638 
    639 	sc->sc_scowr_size = wr_size = 0;
    640 	sc->sc_scowr_addr = wr_addr = -1;
    641 
    642 	count = 0;
    643 	(void)usbd_endpoint_count(sc->sc_iface1, &count);
    644 
    645 	for (i = 0 ; i < count ; i++) {
    646 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface1, i);
    647 		if (ed == NULL) {
    648 			aprint_error_dev(sc->sc_dev,
    649 			    "could not read endpoint descriptor %d\n", i);
    650 
    651 			return EIO;
    652 		}
    653 
    654 		DPRINTFN(5, "%s: endpoint type %02x (%02x) addr %02x (%s)\n",
    655 			device_xname(sc->sc_dev),
    656 			UE_GET_XFERTYPE(ed->bmAttributes),
    657 			UE_GET_ISO_TYPE(ed->bmAttributes),
    658 			ed->bEndpointAddress,
    659 			UE_GET_DIR(ed->bEndpointAddress) ? "in" : "out");
    660 
    661 		if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
    662 			continue;
    663 
    664 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN) {
    665 			rd_addr = ed->bEndpointAddress;
    666 			rd_size = UGETW(ed->wMaxPacketSize);
    667 		} else {
    668 			wr_addr = ed->bEndpointAddress;
    669 			wr_size = UGETW(ed->wMaxPacketSize);
    670 		}
    671 	}
    672 
    673 	if (rd_addr == -1) {
    674 		aprint_error_dev(sc->sc_dev,
    675 		    "missing ISOC IN endpoint on interface config %d\n",
    676 		    sc->sc_config);
    677 
    678 		return ENOENT;
    679 	}
    680 	if (wr_addr == -1) {
    681 		aprint_error_dev(sc->sc_dev,
    682 		    "missing ISOC OUT endpoint on interface config %d\n",
    683 		    sc->sc_config);
    684 
    685 		return ENOENT;
    686 	}
    687 
    688 	if (rd_size > MLEN) {
    689 		aprint_error_dev(sc->sc_dev, "rd_size=%d exceeds MLEN\n",
    690 		    rd_size);
    691 
    692 		return EOVERFLOW;
    693 	}
    694 
    695 	if (wr_size > MLEN) {
    696 		aprint_error_dev(sc->sc_dev, "wr_size=%d exceeds MLEN\n",
    697 		    wr_size);
    698 
    699 		return EOVERFLOW;
    700 	}
    701 
    702 	sc->sc_scord_size = rd_size;
    703 	sc->sc_scord_addr = rd_addr;
    704 
    705 	sc->sc_scowr_size = wr_size;
    706 	sc->sc_scowr_addr = wr_addr;
    707 
    708 	return 0;
    709 }
    710 
    711 /* sysctl helper to set alternate configurations */
    712 static int
    713 ubt_sysctl_config(SYSCTLFN_ARGS)
    714 {
    715 	struct sysctlnode node;
    716 	struct ubt_softc *sc;
    717 	int t, error;
    718 
    719 	node = *rnode;
    720 	sc = node.sysctl_data;
    721 
    722 	t = sc->sc_config;
    723 	node.sysctl_data = &t;
    724 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    725 	if (error || newp == NULL)
    726 		return error;
    727 
    728 	if (t < 0 || t >= sc->sc_alt_config)
    729 		return EINVAL;
    730 
    731 	/* This may not change when the unit is enabled */
    732 	if (sc->sc_enabled)
    733 		return EBUSY;
    734 
    735 	KERNEL_LOCK(1, curlwp);
    736 	sc->sc_config = t;
    737 	error = ubt_set_isoc_config(sc);
    738 	KERNEL_UNLOCK_ONE(curlwp);
    739 	return error;
    740 }
    741 
    742 static void
    743 ubt_abortdealloc(struct ubt_softc *sc)
    744 {
    745 	int i;
    746 
    747 	DPRINTFN(1, "sc=%p\n", sc);
    748 
    749 	/* Abort all pipes */
    750 	usbd_abort_default_pipe(sc->sc_udev);
    751 
    752 	if (sc->sc_evt_pipe != NULL) {
    753 		usbd_abort_pipe(sc->sc_evt_pipe);
    754 		usbd_close_pipe(sc->sc_evt_pipe);
    755 		sc->sc_evt_pipe = NULL;
    756 	}
    757 
    758 	if (sc->sc_aclrd_pipe != NULL) {
    759 		usbd_abort_pipe(sc->sc_aclrd_pipe);
    760 		usbd_close_pipe(sc->sc_aclrd_pipe);
    761 		sc->sc_aclrd_pipe = NULL;
    762 	}
    763 
    764 	if (sc->sc_aclwr_pipe != NULL) {
    765 		usbd_abort_pipe(sc->sc_aclwr_pipe);
    766 		usbd_close_pipe(sc->sc_aclwr_pipe);
    767 		sc->sc_aclwr_pipe = NULL;
    768 	}
    769 
    770 	if (sc->sc_scord_pipe != NULL) {
    771 		usbd_abort_pipe(sc->sc_scord_pipe);
    772 		usbd_close_pipe(sc->sc_scord_pipe);
    773 		sc->sc_scord_pipe = NULL;
    774 	}
    775 
    776 	if (sc->sc_scowr_pipe != NULL) {
    777 		usbd_abort_pipe(sc->sc_scowr_pipe);
    778 		usbd_close_pipe(sc->sc_scowr_pipe);
    779 		sc->sc_scowr_pipe = NULL;
    780 	}
    781 
    782 	/* Free event buffer */
    783 	if (sc->sc_evt_buf != NULL) {
    784 		free(sc->sc_evt_buf, M_USBDEV);
    785 		sc->sc_evt_buf = NULL;
    786 	}
    787 
    788 	/* Free all xfers and xfer buffers (implicit) */
    789 	if (sc->sc_cmd_xfer != NULL) {
    790 		usbd_free_xfer(sc->sc_cmd_xfer);
    791 		sc->sc_cmd_xfer = NULL;
    792 		sc->sc_cmd_buf = NULL;
    793 	}
    794 
    795 	if (sc->sc_aclrd_xfer != NULL) {
    796 		usbd_free_xfer(sc->sc_aclrd_xfer);
    797 		sc->sc_aclrd_xfer = NULL;
    798 		sc->sc_aclrd_buf = NULL;
    799 	}
    800 
    801 	if (sc->sc_aclwr_xfer != NULL) {
    802 		usbd_free_xfer(sc->sc_aclwr_xfer);
    803 		sc->sc_aclwr_xfer = NULL;
    804 		sc->sc_aclwr_buf = NULL;
    805 	}
    806 
    807 	for (i = 0 ; i < UBT_NXFERS ; i++) {
    808 		if (sc->sc_scord[i].xfer != NULL) {
    809 			usbd_free_xfer(sc->sc_scord[i].xfer);
    810 			sc->sc_scord[i].xfer = NULL;
    811 			sc->sc_scord[i].buf = NULL;
    812 		}
    813 
    814 		if (sc->sc_scowr[i].xfer != NULL) {
    815 			usbd_free_xfer(sc->sc_scowr[i].xfer);
    816 			sc->sc_scowr[i].xfer = NULL;
    817 			sc->sc_scowr[i].buf = NULL;
    818 		}
    819 	}
    820 
    821 	/* Free partial SCO packets */
    822 	if (sc->sc_scord_mbuf != NULL) {
    823 		m_freem(sc->sc_scord_mbuf);
    824 		sc->sc_scord_mbuf = NULL;
    825 	}
    826 
    827 	if (sc->sc_scowr_mbuf != NULL) {
    828 		m_freem(sc->sc_scowr_mbuf);
    829 		sc->sc_scowr_mbuf = NULL;
    830 	}
    831 
    832 	/* Empty mbuf queues */
    833 	MBUFQ_DRAIN(&sc->sc_cmd_queue);
    834 	MBUFQ_DRAIN(&sc->sc_aclwr_queue);
    835 	MBUFQ_DRAIN(&sc->sc_scowr_queue);
    836 }
    837 
    838 /*******************************************************************************
    839  *
    840  * Bluetooth Unit/USB callbacks
    841  *
    842  */
    843 static int
    844 ubt_enable(device_t self)
    845 {
    846 	struct ubt_softc *sc = device_private(self);
    847 	usbd_status err;
    848 	int s, i, error;
    849 
    850 	DPRINTFN(1, "sc=%p\n", sc);
    851 
    852 	if (sc->sc_enabled)
    853 		return 0;
    854 
    855 	s = splusb();
    856 
    857 	/* Events */
    858 	sc->sc_evt_buf = malloc(UBT_BUFSIZ_EVENT, M_USBDEV, M_NOWAIT);
    859 	if (sc->sc_evt_buf == NULL) {
    860 		error = ENOMEM;
    861 		goto bad;
    862 	}
    863 	err = usbd_open_pipe_intr(sc->sc_iface0,
    864 				  sc->sc_evt_addr,
    865 				  USBD_SHORT_XFER_OK,
    866 				  &sc->sc_evt_pipe,
    867 				  sc,
    868 				  sc->sc_evt_buf,
    869 				  UBT_BUFSIZ_EVENT,
    870 				  ubt_recv_event,
    871 				  USBD_DEFAULT_INTERVAL);
    872 	if (err != USBD_NORMAL_COMPLETION) {
    873 		error = EIO;
    874 		goto bad;
    875 	}
    876 
    877 	/* Commands */
    878 	sc->sc_cmd_xfer = usbd_alloc_xfer(sc->sc_udev);
    879 	if (sc->sc_cmd_xfer == NULL) {
    880 		error = ENOMEM;
    881 		goto bad;
    882 	}
    883 	sc->sc_cmd_buf = usbd_alloc_buffer(sc->sc_cmd_xfer, UBT_BUFSIZ_CMD);
    884 	if (sc->sc_cmd_buf == NULL) {
    885 		error = ENOMEM;
    886 		goto bad;
    887 	}
    888 	sc->sc_cmd_busy = 0;
    889 
    890 	/* ACL read */
    891 	err = usbd_open_pipe(sc->sc_iface0, sc->sc_aclrd_addr,
    892 				USBD_EXCLUSIVE_USE, &sc->sc_aclrd_pipe);
    893 	if (err != USBD_NORMAL_COMPLETION) {
    894 		error = EIO;
    895 		goto bad;
    896 	}
    897 	sc->sc_aclrd_xfer = usbd_alloc_xfer(sc->sc_udev);
    898 	if (sc->sc_aclrd_xfer == NULL) {
    899 		error = ENOMEM;
    900 		goto bad;
    901 	}
    902 	sc->sc_aclrd_buf = usbd_alloc_buffer(sc->sc_aclrd_xfer, UBT_BUFSIZ_ACL);
    903 	if (sc->sc_aclrd_buf == NULL) {
    904 		error = ENOMEM;
    905 		goto bad;
    906 	}
    907 	sc->sc_aclrd_busy = 0;
    908 	ubt_recv_acl_start(sc);
    909 
    910 	/* ACL write */
    911 	err = usbd_open_pipe(sc->sc_iface0, sc->sc_aclwr_addr,
    912 				USBD_EXCLUSIVE_USE, &sc->sc_aclwr_pipe);
    913 	if (err != USBD_NORMAL_COMPLETION) {
    914 		error = EIO;
    915 		goto bad;
    916 	}
    917 	sc->sc_aclwr_xfer = usbd_alloc_xfer(sc->sc_udev);
    918 	if (sc->sc_aclwr_xfer == NULL) {
    919 		error = ENOMEM;
    920 		goto bad;
    921 	}
    922 	sc->sc_aclwr_buf = usbd_alloc_buffer(sc->sc_aclwr_xfer, UBT_BUFSIZ_ACL);
    923 	if (sc->sc_aclwr_buf == NULL) {
    924 		error = ENOMEM;
    925 		goto bad;
    926 	}
    927 	sc->sc_aclwr_busy = 0;
    928 
    929 	/* SCO read */
    930 	if (sc->sc_scord_size > 0) {
    931 		err = usbd_open_pipe(sc->sc_iface1, sc->sc_scord_addr,
    932 					USBD_EXCLUSIVE_USE, &sc->sc_scord_pipe);
    933 		if (err != USBD_NORMAL_COMPLETION) {
    934 			error = EIO;
    935 			goto bad;
    936 		}
    937 
    938 		for (i = 0 ; i < UBT_NXFERS ; i++) {
    939 			sc->sc_scord[i].xfer = usbd_alloc_xfer(sc->sc_udev);
    940 			if (sc->sc_scord[i].xfer == NULL) {
    941 				error = ENOMEM;
    942 				goto bad;
    943 			}
    944 			sc->sc_scord[i].buf = usbd_alloc_buffer(sc->sc_scord[i].xfer,
    945 						sc->sc_scord_size * UBT_NFRAMES);
    946 			if (sc->sc_scord[i].buf == NULL) {
    947 				error = ENOMEM;
    948 				goto bad;
    949 			}
    950 			sc->sc_scord[i].softc = sc;
    951 			sc->sc_scord[i].busy = 0;
    952 			ubt_recv_sco_start1(sc, &sc->sc_scord[i]);
    953 		}
    954 	}
    955 
    956 	/* SCO write */
    957 	if (sc->sc_scowr_size > 0) {
    958 		err = usbd_open_pipe(sc->sc_iface1, sc->sc_scowr_addr,
    959 					USBD_EXCLUSIVE_USE, &sc->sc_scowr_pipe);
    960 		if (err != USBD_NORMAL_COMPLETION) {
    961 			error = EIO;
    962 			goto bad;
    963 		}
    964 
    965 		for (i = 0 ; i < UBT_NXFERS ; i++) {
    966 			sc->sc_scowr[i].xfer = usbd_alloc_xfer(sc->sc_udev);
    967 			if (sc->sc_scowr[i].xfer == NULL) {
    968 				error = ENOMEM;
    969 				goto bad;
    970 			}
    971 			sc->sc_scowr[i].buf = usbd_alloc_buffer(sc->sc_scowr[i].xfer,
    972 						sc->sc_scowr_size * UBT_NFRAMES);
    973 			if (sc->sc_scowr[i].buf == NULL) {
    974 				error = ENOMEM;
    975 				goto bad;
    976 			}
    977 			sc->sc_scowr[i].softc = sc;
    978 			sc->sc_scowr[i].busy = 0;
    979 		}
    980 
    981 		sc->sc_scowr_busy = 0;
    982 	}
    983 
    984 	sc->sc_enabled = 1;
    985 	splx(s);
    986 	return 0;
    987 
    988 bad:
    989 	ubt_abortdealloc(sc);
    990 	splx(s);
    991 	return error;
    992 }
    993 
    994 static void
    995 ubt_disable(device_t self)
    996 {
    997 	struct ubt_softc *sc = device_private(self);
    998 	int s;
    999 
   1000 	DPRINTFN(1, "sc=%p\n", sc);
   1001 
   1002 	if (sc->sc_enabled == 0)
   1003 		return;
   1004 
   1005 	s = splusb();
   1006 	ubt_abortdealloc(sc);
   1007 
   1008 	sc->sc_enabled = 0;
   1009 	splx(s);
   1010 }
   1011 
   1012 static void
   1013 ubt_xmit_cmd(device_t self, struct mbuf *m)
   1014 {
   1015 	struct ubt_softc *sc = device_private(self);
   1016 	int s;
   1017 
   1018 	KASSERT(sc->sc_enabled);
   1019 
   1020 	s = splusb();
   1021 	MBUFQ_ENQUEUE(&sc->sc_cmd_queue, m);
   1022 
   1023 	if (sc->sc_cmd_busy == 0)
   1024 		ubt_xmit_cmd_start(sc);
   1025 
   1026 	splx(s);
   1027 }
   1028 
   1029 static void
   1030 ubt_xmit_cmd_start(struct ubt_softc *sc)
   1031 {
   1032 	usb_device_request_t req;
   1033 	usbd_status status;
   1034 	struct mbuf *m;
   1035 	int len;
   1036 
   1037 	if (sc->sc_dying)
   1038 		return;
   1039 
   1040 	if (MBUFQ_FIRST(&sc->sc_cmd_queue) == NULL)
   1041 		return;
   1042 
   1043 	MBUFQ_DEQUEUE(&sc->sc_cmd_queue, m);
   1044 	KASSERT(m != NULL);
   1045 
   1046 	DPRINTFN(15, "%s: xmit CMD packet (%d bytes)\n",
   1047 			device_xname(sc->sc_dev), m->m_pkthdr.len);
   1048 
   1049 	sc->sc_refcnt++;
   1050 	sc->sc_cmd_busy = 1;
   1051 
   1052 	len = m->m_pkthdr.len - 1;
   1053 	m_copydata(m, 1, len, sc->sc_cmd_buf);
   1054 	m_freem(m);
   1055 
   1056 	memset(&req, 0, sizeof(req));
   1057 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
   1058 	USETW(req.wLength, len);
   1059 
   1060 	usbd_setup_default_xfer(sc->sc_cmd_xfer,
   1061 				sc->sc_udev,
   1062 				sc,
   1063 				UBT_CMD_TIMEOUT,
   1064 				&req,
   1065 				sc->sc_cmd_buf,
   1066 				len,
   1067 				USBD_NO_COPY | USBD_FORCE_SHORT_XFER,
   1068 				ubt_xmit_cmd_complete);
   1069 
   1070 	status = usbd_transfer(sc->sc_cmd_xfer);
   1071 
   1072 	KASSERT(status != USBD_NORMAL_COMPLETION);
   1073 
   1074 	if (status != USBD_IN_PROGRESS) {
   1075 		DPRINTF("usbd_transfer status=%s (%d)\n",
   1076 			usbd_errstr(status), status);
   1077 
   1078 		sc->sc_refcnt--;
   1079 		sc->sc_cmd_busy = 0;
   1080 	}
   1081 }
   1082 
   1083 static void
   1084 ubt_xmit_cmd_complete(usbd_xfer_handle xfer,
   1085 			usbd_private_handle h, usbd_status status)
   1086 {
   1087 	struct ubt_softc *sc = h;
   1088 	uint32_t count;
   1089 
   1090 	DPRINTFN(15, "%s: CMD complete status=%s (%d)\n",
   1091 			device_xname(sc->sc_dev), usbd_errstr(status), status);
   1092 
   1093 	sc->sc_cmd_busy = 0;
   1094 
   1095 	if (--sc->sc_refcnt < 0) {
   1096 		DPRINTF("sc_refcnt=%d\n", sc->sc_refcnt);
   1097 		usb_detach_wakeupold(sc->sc_dev);
   1098 		return;
   1099 	}
   1100 
   1101 	if (sc->sc_dying) {
   1102 		DPRINTF("sc_dying\n");
   1103 		return;
   1104 	}
   1105 
   1106 	if (status != USBD_NORMAL_COMPLETION) {
   1107 		DPRINTF("status=%s (%d)\n",
   1108 			usbd_errstr(status), status);
   1109 
   1110 		sc->sc_stats.err_tx++;
   1111 		return;
   1112 	}
   1113 
   1114 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1115 	sc->sc_stats.cmd_tx++;
   1116 	sc->sc_stats.byte_tx += count;
   1117 
   1118 	ubt_xmit_cmd_start(sc);
   1119 }
   1120 
   1121 static void
   1122 ubt_xmit_acl(device_t self, struct mbuf *m)
   1123 {
   1124 	struct ubt_softc *sc = device_private(self);
   1125 	int s;
   1126 
   1127 	KASSERT(sc->sc_enabled);
   1128 
   1129 	s = splusb();
   1130 	MBUFQ_ENQUEUE(&sc->sc_aclwr_queue, m);
   1131 
   1132 	if (sc->sc_aclwr_busy == 0)
   1133 		ubt_xmit_acl_start(sc);
   1134 
   1135 	splx(s);
   1136 }
   1137 
   1138 static void
   1139 ubt_xmit_acl_start(struct ubt_softc *sc)
   1140 {
   1141 	struct mbuf *m;
   1142 	usbd_status status;
   1143 	int len;
   1144 
   1145 	if (sc->sc_dying)
   1146 		return;
   1147 
   1148 	if (MBUFQ_FIRST(&sc->sc_aclwr_queue) == NULL)
   1149 		return;
   1150 
   1151 	sc->sc_refcnt++;
   1152 	sc->sc_aclwr_busy = 1;
   1153 
   1154 	MBUFQ_DEQUEUE(&sc->sc_aclwr_queue, m);
   1155 	KASSERT(m != NULL);
   1156 
   1157 	DPRINTFN(15, "%s: xmit ACL packet (%d bytes)\n",
   1158 			device_xname(sc->sc_dev), m->m_pkthdr.len);
   1159 
   1160 	len = m->m_pkthdr.len - 1;
   1161 	if (len > UBT_BUFSIZ_ACL) {
   1162 		DPRINTF("%s: truncating ACL packet (%d => %d)!\n",
   1163 			device_xname(sc->sc_dev), len, UBT_BUFSIZ_ACL);
   1164 
   1165 		len = UBT_BUFSIZ_ACL;
   1166 	}
   1167 
   1168 	m_copydata(m, 1, len, sc->sc_aclwr_buf);
   1169 	m_freem(m);
   1170 
   1171 	sc->sc_stats.acl_tx++;
   1172 	sc->sc_stats.byte_tx += len;
   1173 
   1174 	usbd_setup_xfer(sc->sc_aclwr_xfer,
   1175 			sc->sc_aclwr_pipe,
   1176 			sc,
   1177 			sc->sc_aclwr_buf,
   1178 			len,
   1179 			USBD_NO_COPY | USBD_FORCE_SHORT_XFER,
   1180 			UBT_ACL_TIMEOUT,
   1181 			ubt_xmit_acl_complete);
   1182 
   1183 	status = usbd_transfer(sc->sc_aclwr_xfer);
   1184 
   1185 	KASSERT(status != USBD_NORMAL_COMPLETION);
   1186 
   1187 	if (status != USBD_IN_PROGRESS) {
   1188 		DPRINTF("usbd_transfer status=%s (%d)\n",
   1189 			usbd_errstr(status), status);
   1190 
   1191 		sc->sc_refcnt--;
   1192 		sc->sc_aclwr_busy = 0;
   1193 	}
   1194 }
   1195 
   1196 static void
   1197 ubt_xmit_acl_complete(usbd_xfer_handle xfer,
   1198 		usbd_private_handle h, usbd_status status)
   1199 {
   1200 	struct ubt_softc *sc = h;
   1201 
   1202 	DPRINTFN(15, "%s: ACL complete status=%s (%d)\n",
   1203 		device_xname(sc->sc_dev), usbd_errstr(status), status);
   1204 
   1205 	sc->sc_aclwr_busy = 0;
   1206 
   1207 	if (--sc->sc_refcnt < 0) {
   1208 		usb_detach_wakeupold(sc->sc_dev);
   1209 		return;
   1210 	}
   1211 
   1212 	if (sc->sc_dying)
   1213 		return;
   1214 
   1215 	if (status != USBD_NORMAL_COMPLETION) {
   1216 		DPRINTF("status=%s (%d)\n",
   1217 			usbd_errstr(status), status);
   1218 
   1219 		sc->sc_stats.err_tx++;
   1220 
   1221 		if (status == USBD_STALLED)
   1222 			usbd_clear_endpoint_stall_async(sc->sc_aclwr_pipe);
   1223 		else
   1224 			return;
   1225 	}
   1226 
   1227 	ubt_xmit_acl_start(sc);
   1228 }
   1229 
   1230 static void
   1231 ubt_xmit_sco(device_t self, struct mbuf *m)
   1232 {
   1233 	struct ubt_softc *sc = device_private(self);
   1234 	int s;
   1235 
   1236 	KASSERT(sc->sc_enabled);
   1237 
   1238 	s = splusb();
   1239 	MBUFQ_ENQUEUE(&sc->sc_scowr_queue, m);
   1240 
   1241 	if (sc->sc_scowr_busy == 0)
   1242 		ubt_xmit_sco_start(sc);
   1243 
   1244 	splx(s);
   1245 }
   1246 
   1247 static void
   1248 ubt_xmit_sco_start(struct ubt_softc *sc)
   1249 {
   1250 	int i;
   1251 
   1252 	if (sc->sc_dying || sc->sc_scowr_size == 0)
   1253 		return;
   1254 
   1255 	for (i = 0 ; i < UBT_NXFERS ; i++) {
   1256 		if (sc->sc_scowr[i].busy)
   1257 			continue;
   1258 
   1259 		ubt_xmit_sco_start1(sc, &sc->sc_scowr[i]);
   1260 	}
   1261 }
   1262 
   1263 static void
   1264 ubt_xmit_sco_start1(struct ubt_softc *sc, struct ubt_isoc_xfer *isoc)
   1265 {
   1266 	struct mbuf *m;
   1267 	uint8_t *buf;
   1268 	int num, len, size, space;
   1269 
   1270 	space = sc->sc_scowr_size * UBT_NFRAMES;
   1271 	buf = isoc->buf;
   1272 	len = 0;
   1273 
   1274 	/*
   1275 	 * Fill the request buffer with data from the queue,
   1276 	 * keeping any leftover packet on our private hook.
   1277 	 *
   1278 	 * Complete packets are passed back up to the stack
   1279 	 * for disposal, since we can't rely on the controller
   1280 	 * to tell us when it has finished with them.
   1281 	 */
   1282 
   1283 	m = sc->sc_scowr_mbuf;
   1284 	while (space > 0) {
   1285 		if (m == NULL) {
   1286 			MBUFQ_DEQUEUE(&sc->sc_scowr_queue, m);
   1287 			if (m == NULL)
   1288 				break;
   1289 
   1290 			m_adj(m, 1);	/* packet type */
   1291 		}
   1292 
   1293 		if (m->m_pkthdr.len > 0) {
   1294 			size = MIN(m->m_pkthdr.len, space);
   1295 
   1296 			m_copydata(m, 0, size, buf);
   1297 			m_adj(m, size);
   1298 
   1299 			buf += size;
   1300 			len += size;
   1301 			space -= size;
   1302 		}
   1303 
   1304 		if (m->m_pkthdr.len == 0) {
   1305 			sc->sc_stats.sco_tx++;
   1306 			if (!hci_complete_sco(sc->sc_unit, m))
   1307 				sc->sc_stats.err_tx++;
   1308 
   1309 			m = NULL;
   1310 		}
   1311 	}
   1312 	sc->sc_scowr_mbuf = m;
   1313 
   1314 	DPRINTFN(15, "isoc=%p, len=%d, space=%d\n", isoc, len, space);
   1315 
   1316 	if (len == 0)	/* nothing to send */
   1317 		return;
   1318 
   1319 	sc->sc_refcnt++;
   1320 	sc->sc_scowr_busy = 1;
   1321 	sc->sc_stats.byte_tx += len;
   1322 	isoc->busy = 1;
   1323 
   1324 	/*
   1325 	 * calculate number of isoc frames and sizes
   1326 	 */
   1327 
   1328 	for (num = 0 ; len > 0 ; num++) {
   1329 		size = MIN(sc->sc_scowr_size, len);
   1330 
   1331 		isoc->size[num] = size;
   1332 		len -= size;
   1333 	}
   1334 
   1335 	usbd_setup_isoc_xfer(isoc->xfer,
   1336 			     sc->sc_scowr_pipe,
   1337 			     isoc,
   1338 			     isoc->size,
   1339 			     num,
   1340 			     USBD_NO_COPY | USBD_FORCE_SHORT_XFER,
   1341 			     ubt_xmit_sco_complete);
   1342 
   1343 	usbd_transfer(isoc->xfer);
   1344 }
   1345 
   1346 static void
   1347 ubt_xmit_sco_complete(usbd_xfer_handle xfer,
   1348 		usbd_private_handle h, usbd_status status)
   1349 {
   1350 	struct ubt_isoc_xfer *isoc = h;
   1351 	struct ubt_softc *sc;
   1352 	int i;
   1353 
   1354 	KASSERT(xfer == isoc->xfer);
   1355 	sc = isoc->softc;
   1356 
   1357 	DPRINTFN(15, "isoc=%p, status=%s (%d)\n",
   1358 		isoc, usbd_errstr(status), status);
   1359 
   1360 	isoc->busy = 0;
   1361 
   1362 	for (i = 0 ; ; i++) {
   1363 		if (i == UBT_NXFERS) {
   1364 			sc->sc_scowr_busy = 0;
   1365 			break;
   1366 		}
   1367 
   1368 		if (sc->sc_scowr[i].busy)
   1369 			break;
   1370 	}
   1371 
   1372 	if (--sc->sc_refcnt < 0) {
   1373 		usb_detach_wakeupold(sc->sc_dev);
   1374 		return;
   1375 	}
   1376 
   1377 	if (sc->sc_dying)
   1378 		return;
   1379 
   1380 	if (status != USBD_NORMAL_COMPLETION) {
   1381 		DPRINTF("status=%s (%d)\n",
   1382 			usbd_errstr(status), status);
   1383 
   1384 		sc->sc_stats.err_tx++;
   1385 
   1386 		if (status == USBD_STALLED)
   1387 			usbd_clear_endpoint_stall_async(sc->sc_scowr_pipe);
   1388 		else
   1389 			return;
   1390 	}
   1391 
   1392 	ubt_xmit_sco_start(sc);
   1393 }
   1394 
   1395 /*
   1396  * load incoming data into an mbuf with
   1397  * leading type byte
   1398  */
   1399 static struct mbuf *
   1400 ubt_mbufload(uint8_t *buf, int count, uint8_t type)
   1401 {
   1402 	struct mbuf *m;
   1403 
   1404 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1405 	if (m == NULL)
   1406 		return NULL;
   1407 
   1408 	*mtod(m, uint8_t *) = type;
   1409 	m->m_pkthdr.len = m->m_len = MHLEN;
   1410 	m_copyback(m, 1, count, buf);	// (extends if necessary)
   1411 	if (m->m_pkthdr.len != MAX(MHLEN, count + 1)) {
   1412 		m_free(m);
   1413 		return NULL;
   1414 	}
   1415 
   1416 	m->m_pkthdr.len = count + 1;
   1417 	m->m_len = MIN(MHLEN, m->m_pkthdr.len);
   1418 
   1419 	return m;
   1420 }
   1421 
   1422 static void
   1423 ubt_recv_event(usbd_xfer_handle xfer, usbd_private_handle h, usbd_status status)
   1424 {
   1425 	struct ubt_softc *sc = h;
   1426 	struct mbuf *m;
   1427 	uint32_t count;
   1428 	void *buf;
   1429 
   1430 	DPRINTFN(15, "sc=%p status=%s (%d)\n",
   1431 		    sc, usbd_errstr(status), status);
   1432 
   1433 	if (status != USBD_NORMAL_COMPLETION || sc->sc_dying)
   1434 		return;
   1435 
   1436 	usbd_get_xfer_status(xfer, NULL, &buf, &count, NULL);
   1437 
   1438 	if (count < sizeof(hci_event_hdr_t) - 1) {
   1439 		DPRINTF("dumped undersized event (count = %d)\n", count);
   1440 		sc->sc_stats.err_rx++;
   1441 		return;
   1442 	}
   1443 
   1444 	sc->sc_stats.evt_rx++;
   1445 	sc->sc_stats.byte_rx += count;
   1446 
   1447 	m = ubt_mbufload(buf, count, HCI_EVENT_PKT);
   1448 	if (m == NULL || !hci_input_event(sc->sc_unit, m))
   1449 		sc->sc_stats.err_rx++;
   1450 }
   1451 
   1452 static void
   1453 ubt_recv_acl_start(struct ubt_softc *sc)
   1454 {
   1455 	usbd_status status;
   1456 
   1457 	DPRINTFN(15, "sc=%p\n", sc);
   1458 
   1459 	if (sc->sc_aclrd_busy || sc->sc_dying) {
   1460 		DPRINTF("sc_aclrd_busy=%d, sc_dying=%d\n",
   1461 			sc->sc_aclrd_busy,
   1462 			sc->sc_dying);
   1463 
   1464 		return;
   1465 	}
   1466 
   1467 	sc->sc_refcnt++;
   1468 	sc->sc_aclrd_busy = 1;
   1469 
   1470 	usbd_setup_xfer(sc->sc_aclrd_xfer,
   1471 			sc->sc_aclrd_pipe,
   1472 			sc,
   1473 			sc->sc_aclrd_buf,
   1474 			UBT_BUFSIZ_ACL,
   1475 			USBD_NO_COPY | USBD_SHORT_XFER_OK,
   1476 			USBD_NO_TIMEOUT,
   1477 			ubt_recv_acl_complete);
   1478 
   1479 	status = usbd_transfer(sc->sc_aclrd_xfer);
   1480 
   1481 	KASSERT(status != USBD_NORMAL_COMPLETION);
   1482 
   1483 	if (status != USBD_IN_PROGRESS) {
   1484 		DPRINTF("usbd_transfer status=%s (%d)\n",
   1485 			usbd_errstr(status), status);
   1486 
   1487 		sc->sc_refcnt--;
   1488 		sc->sc_aclrd_busy = 0;
   1489 	}
   1490 }
   1491 
   1492 static void
   1493 ubt_recv_acl_complete(usbd_xfer_handle xfer,
   1494 		usbd_private_handle h, usbd_status status)
   1495 {
   1496 	struct ubt_softc *sc = h;
   1497 	struct mbuf *m;
   1498 	uint32_t count;
   1499 	void *buf;
   1500 
   1501 	DPRINTFN(15, "sc=%p status=%s (%d)\n",
   1502 			sc, usbd_errstr(status), status);
   1503 
   1504 	sc->sc_aclrd_busy = 0;
   1505 
   1506 	if (--sc->sc_refcnt < 0) {
   1507 		DPRINTF("refcnt = %d\n", sc->sc_refcnt);
   1508 		usb_detach_wakeupold(sc->sc_dev);
   1509 		return;
   1510 	}
   1511 
   1512 	if (sc->sc_dying) {
   1513 		DPRINTF("sc_dying\n");
   1514 		return;
   1515 	}
   1516 
   1517 	if (status != USBD_NORMAL_COMPLETION) {
   1518 		DPRINTF("status=%s (%d)\n",
   1519 			usbd_errstr(status), status);
   1520 
   1521 		sc->sc_stats.err_rx++;
   1522 
   1523 		if (status == USBD_STALLED)
   1524 			usbd_clear_endpoint_stall_async(sc->sc_aclrd_pipe);
   1525 		else
   1526 			return;
   1527 	} else {
   1528 		usbd_get_xfer_status(xfer, NULL, &buf, &count, NULL);
   1529 
   1530 		if (count < sizeof(hci_acldata_hdr_t) - 1) {
   1531 			DPRINTF("dumped undersized packet (%d)\n", count);
   1532 			sc->sc_stats.err_rx++;
   1533 		} else {
   1534 			sc->sc_stats.acl_rx++;
   1535 			sc->sc_stats.byte_rx += count;
   1536 
   1537 			m = ubt_mbufload(buf, count, HCI_ACL_DATA_PKT);
   1538 			if (m == NULL || !hci_input_acl(sc->sc_unit, m))
   1539 				sc->sc_stats.err_rx++;
   1540 		}
   1541 	}
   1542 
   1543 	/* and restart */
   1544 	ubt_recv_acl_start(sc);
   1545 }
   1546 
   1547 static void
   1548 ubt_recv_sco_start1(struct ubt_softc *sc, struct ubt_isoc_xfer *isoc)
   1549 {
   1550 	int i;
   1551 
   1552 	DPRINTFN(15, "sc=%p, isoc=%p\n", sc, isoc);
   1553 
   1554 	if (isoc->busy || sc->sc_dying || sc->sc_scord_size == 0) {
   1555 		DPRINTF("%s%s%s\n",
   1556 			isoc->busy ? " busy" : "",
   1557 			sc->sc_dying ? " dying" : "",
   1558 			sc->sc_scord_size == 0 ? " size=0" : "");
   1559 
   1560 		return;
   1561 	}
   1562 
   1563 	sc->sc_refcnt++;
   1564 	isoc->busy = 1;
   1565 
   1566 	for (i = 0 ; i < UBT_NFRAMES ; i++)
   1567 		isoc->size[i] = sc->sc_scord_size;
   1568 
   1569 	usbd_setup_isoc_xfer(isoc->xfer,
   1570 			     sc->sc_scord_pipe,
   1571 			     isoc,
   1572 			     isoc->size,
   1573 			     UBT_NFRAMES,
   1574 			     USBD_NO_COPY | USBD_SHORT_XFER_OK,
   1575 			     ubt_recv_sco_complete);
   1576 
   1577 	usbd_transfer(isoc->xfer);
   1578 }
   1579 
   1580 static void
   1581 ubt_recv_sco_complete(usbd_xfer_handle xfer,
   1582 		usbd_private_handle h, usbd_status status)
   1583 {
   1584 	struct ubt_isoc_xfer *isoc = h;
   1585 	struct ubt_softc *sc;
   1586 	struct mbuf *m;
   1587 	uint32_t count;
   1588 	uint8_t *ptr, *frame;
   1589 	int i, size, got, want;
   1590 
   1591 	KASSERT(isoc != NULL);
   1592 	KASSERT(isoc->xfer == xfer);
   1593 
   1594 	sc = isoc->softc;
   1595 	isoc->busy = 0;
   1596 
   1597 	if (--sc->sc_refcnt < 0) {
   1598 		DPRINTF("refcnt=%d\n", sc->sc_refcnt);
   1599 		usb_detach_wakeupold(sc->sc_dev);
   1600 		return;
   1601 	}
   1602 
   1603 	if (sc->sc_dying) {
   1604 		DPRINTF("sc_dying\n");
   1605 		return;
   1606 	}
   1607 
   1608 	if (status != USBD_NORMAL_COMPLETION) {
   1609 		DPRINTF("status=%s (%d)\n",
   1610 			usbd_errstr(status), status);
   1611 
   1612 		sc->sc_stats.err_rx++;
   1613 
   1614 		if (status == USBD_STALLED) {
   1615 			usbd_clear_endpoint_stall_async(sc->sc_scord_pipe);
   1616 			goto restart;
   1617 		}
   1618 
   1619 		return;
   1620 	}
   1621 
   1622 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1623 	if (count == 0)
   1624 		goto restart;
   1625 
   1626 	DPRINTFN(15, "sc=%p, isoc=%p, count=%u\n",
   1627 			sc, isoc, count);
   1628 
   1629 	sc->sc_stats.byte_rx += count;
   1630 
   1631 	/*
   1632 	 * Extract SCO packets from ISOC frames. The way we have it,
   1633 	 * no SCO packet can be bigger than MHLEN. This is unlikely
   1634 	 * to actually happen, but if we ran out of mbufs and lost
   1635 	 * sync then we may get spurious data that makes it seem that
   1636 	 * way, so we discard data that wont fit. This doesnt really
   1637 	 * help with the lost sync situation alas.
   1638 	 */
   1639 
   1640 	m = sc->sc_scord_mbuf;
   1641 	if (m != NULL) {
   1642 		sc->sc_scord_mbuf = NULL;
   1643 		ptr = mtod(m, uint8_t *) + m->m_pkthdr.len;
   1644 		got = m->m_pkthdr.len;
   1645 		want = sizeof(hci_scodata_hdr_t);
   1646 		if (got >= want)
   1647 			want += mtod(m, hci_scodata_hdr_t *)->length ;
   1648 	} else {
   1649 		ptr = NULL;
   1650 		got = 0;
   1651 		want = 0;
   1652 	}
   1653 
   1654 	for (i = 0 ; i < UBT_NFRAMES ; i++) {
   1655 		frame = isoc->buf + (i * sc->sc_scord_size);
   1656 
   1657 		while (isoc->size[i] > 0) {
   1658 			size = isoc->size[i];
   1659 
   1660 			if (m == NULL) {
   1661 				MGETHDR(m, M_DONTWAIT, MT_DATA);
   1662 				if (m == NULL) {
   1663 					aprint_error_dev(sc->sc_dev,
   1664 					    "out of memory (xfer halted)\n");
   1665 
   1666 					sc->sc_stats.err_rx++;
   1667 					return;		/* lost sync */
   1668 				}
   1669 
   1670 				ptr = mtod(m, uint8_t *);
   1671 				*ptr++ = HCI_SCO_DATA_PKT;
   1672 				got = 1;
   1673 				want = sizeof(hci_scodata_hdr_t);
   1674 			}
   1675 
   1676 			if (got + size > want)
   1677 				size = want - got;
   1678 
   1679 			memcpy(ptr, frame, size);
   1680 
   1681 			ptr += size;
   1682 			got += size;
   1683 			frame += size;
   1684 
   1685 			if (got == want) {
   1686 				/*
   1687 				 * If we only got a header, add the packet
   1688 				 * length to our want count. Send complete
   1689 				 * packets up to protocol stack.
   1690 				 */
   1691 				if (want == sizeof(hci_scodata_hdr_t)) {
   1692 					uint32_t len =
   1693 					    mtod(m, hci_scodata_hdr_t *)->length;
   1694 					want += len;
   1695 					if (len == 0 || want > MHLEN) {
   1696 						aprint_error_dev(sc->sc_dev,
   1697 						    "packet too large %u "
   1698 						    "(lost sync)\n", len);
   1699 						sc->sc_stats.err_rx++;
   1700 						return;
   1701 					}
   1702 				}
   1703 
   1704 				if (got == want) {
   1705 					m->m_pkthdr.len = m->m_len = got;
   1706 					sc->sc_stats.sco_rx++;
   1707 					if (!hci_input_sco(sc->sc_unit, m))
   1708 						sc->sc_stats.err_rx++;
   1709 
   1710 					m = NULL;
   1711 				}
   1712 			}
   1713 
   1714 			isoc->size[i] -= size;
   1715 		}
   1716 	}
   1717 
   1718 	if (m != NULL) {
   1719 		m->m_pkthdr.len = m->m_len = got;
   1720 		sc->sc_scord_mbuf = m;
   1721 	}
   1722 
   1723 restart: /* and restart */
   1724 	ubt_recv_sco_start1(sc, isoc);
   1725 }
   1726 
   1727 void
   1728 ubt_stats(device_t self, struct bt_stats *dest, int flush)
   1729 {
   1730 	struct ubt_softc *sc = device_private(self);
   1731 	int s;
   1732 
   1733 	s = splusb();
   1734 	memcpy(dest, &sc->sc_stats, sizeof(struct bt_stats));
   1735 
   1736 	if (flush)
   1737 		memset(&sc->sc_stats, 0, sizeof(struct bt_stats));
   1738 
   1739 	splx(s);
   1740 }
   1741