Home | History | Annotate | Line # | Download | only in usb
ubt.c revision 1.51.4.7
      1 /*	$NetBSD: ubt.c,v 1.51.4.7 2015/12/28 09:26:33 skrll 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.51.4.7 2015/12/28 09:26:33 skrll 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/kmem.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 	struct usbd_xfer *	 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 	struct usbd_device *	 sc_udev;
    172 	int			 sc_refcnt;
    173 	int			 sc_dying;
    174 	int			 sc_enabled;
    175 
    176 	/* Control Interface */
    177 	struct usbd_interface *	 sc_iface0;
    178 
    179 	/* Commands (control) */
    180 	struct usbd_xfer *	 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 	struct usbd_pipe *	 sc_evt_pipe;
    188 	uint8_t			*sc_evt_buf;
    189 
    190 	/* ACL data (in) */
    191 	int			 sc_aclrd_addr;	/* endpoint address */
    192 	struct usbd_pipe *	 sc_aclrd_pipe;	/* read pipe */
    193 	struct usbd_xfer *	 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 	struct usbd_pipe *	 sc_aclwr_pipe;	/* write pipe */
    200 	struct usbd_xfer *	 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 	struct usbd_interface *	 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 	struct usbd_pipe *	 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 	struct usbd_pipe *	 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(struct usbd_xfer *,
    246 				void *, 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(struct usbd_xfer *,
    251 				void *, 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(struct usbd_xfer *,
    257 				void *, usbd_status);
    258 
    259 static void ubt_recv_event(struct usbd_xfer *,
    260 				void *, usbd_status);
    261 
    262 static void ubt_recv_acl_start(struct ubt_softc *);
    263 static void ubt_recv_acl_complete(struct usbd_xfer *,
    264 				void *, usbd_status);
    265 
    266 static void ubt_recv_sco_start1(struct ubt_softc *, struct ubt_isoc_xfer *);
    267 static void ubt_recv_sco_complete(struct usbd_xfer *,
    268 				void *, 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_C },
    313 	  UMATCH_VENDOR_PRODUCT },
    314 };
    315 #define ubt_lookup(vendor, product) \
    316 	((const struct ubt_devno *)usb_lookup(ubt_dev, vendor, product))
    317 
    318 int
    319 ubt_match(device_t parent, cfdata_t match, void *aux)
    320 {
    321 	struct usb_attach_arg *uaa = aux;
    322 	const struct ubt_devno *dev;
    323 
    324 	DPRINTFN(50, "ubt_match\n");
    325 
    326 	if ((dev = ubt_lookup(uaa->uaa_vendor, uaa->uaa_product)) != NULL)
    327 		return dev->match;
    328 
    329 	if (uaa->uaa_class == UDCLASS_WIRELESS
    330 	    && uaa->uaa_subclass == UDSUBCLASS_RF
    331 	    && uaa->uaa_proto == UDPROTO_BLUETOOTH)
    332 		return UMATCH_DEVCLASS_DEVSUBCLASS_DEVPROTO;
    333 
    334 	return UMATCH_NONE;
    335 }
    336 
    337 void
    338 ubt_attach(device_t parent, device_t self, void *aux)
    339 {
    340 	struct ubt_softc *sc = device_private(self);
    341 	struct usb_attach_arg *uaa = aux;
    342 	usb_config_descriptor_t *cd;
    343 	usb_endpoint_descriptor_t *ed;
    344 	const struct sysctlnode *node;
    345 	char *devinfop;
    346 	int err;
    347 	uint8_t count, i;
    348 
    349 	DPRINTFN(50, "ubt_attach: sc=%p\n", sc);
    350 
    351 	sc->sc_dev = self;
    352 	sc->sc_udev = uaa->uaa_device;
    353 
    354 	MBUFQ_INIT(&sc->sc_cmd_queue);
    355 	MBUFQ_INIT(&sc->sc_aclwr_queue);
    356 	MBUFQ_INIT(&sc->sc_scowr_queue);
    357 
    358 	aprint_naive("\n");
    359 	aprint_normal("\n");
    360 
    361 	devinfop = usbd_devinfo_alloc(sc->sc_udev, 0);
    362 	aprint_normal_dev(self, "%s\n", devinfop);
    363 	usbd_devinfo_free(devinfop);
    364 
    365 	/*
    366 	 * Move the device into the configured state
    367 	 */
    368 	err = usbd_set_config_index(sc->sc_udev, 0, 1);
    369 	if (err) {
    370 		aprint_error_dev(self, "failed to set configuration idx 0: %s\n",
    371 		    usbd_errstr(err));
    372 
    373 		return;
    374 	}
    375 
    376 	/*
    377 	 * Interface 0 must have 3 endpoints
    378 	 *	1) Interrupt endpoint to receive HCI events
    379 	 *	2) Bulk IN endpoint to receive ACL data
    380 	 *	3) Bulk OUT endpoint to send ACL data
    381 	 */
    382 	err = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface0);
    383 	if (err) {
    384 		aprint_error_dev(self, "Could not get interface 0 handle %s (%d)\n",
    385 				usbd_errstr(err), err);
    386 
    387 		return;
    388 	}
    389 
    390 	sc->sc_evt_addr = -1;
    391 	sc->sc_aclrd_addr = -1;
    392 	sc->sc_aclwr_addr = -1;
    393 
    394 	count = 0;
    395 	(void)usbd_endpoint_count(sc->sc_iface0, &count);
    396 
    397 	for (i = 0 ; i < count ; i++) {
    398 		int dir, type;
    399 
    400 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface0, i);
    401 		if (ed == NULL) {
    402 			aprint_error_dev(self,
    403 			    "could not read endpoint descriptor %d\n", i);
    404 
    405 			return;
    406 		}
    407 
    408 		dir = UE_GET_DIR(ed->bEndpointAddress);
    409 		type = UE_GET_XFERTYPE(ed->bmAttributes);
    410 
    411 		if (dir == UE_DIR_IN && type == UE_INTERRUPT)
    412 			sc->sc_evt_addr = ed->bEndpointAddress;
    413 		else if (dir == UE_DIR_IN && type == UE_BULK)
    414 			sc->sc_aclrd_addr = ed->bEndpointAddress;
    415 		else if (dir == UE_DIR_OUT && type == UE_BULK)
    416 			sc->sc_aclwr_addr = ed->bEndpointAddress;
    417 	}
    418 
    419 	if (sc->sc_evt_addr == -1) {
    420 		aprint_error_dev(self,
    421 		    "missing INTERRUPT endpoint on interface 0\n");
    422 
    423 		return;
    424 	}
    425 	if (sc->sc_aclrd_addr == -1) {
    426 		aprint_error_dev(self,
    427 		    "missing BULK IN endpoint on interface 0\n");
    428 
    429 		return;
    430 	}
    431 	if (sc->sc_aclwr_addr == -1) {
    432 		aprint_error_dev(self,
    433 		    "missing BULK OUT endpoint on interface 0\n");
    434 
    435 		return;
    436 	}
    437 
    438 	/*
    439 	 * Interface 1 must have 2 endpoints
    440 	 *	1) Isochronous IN endpoint to receive SCO data
    441 	 *	2) Isochronous OUT endpoint to send SCO data
    442 	 *
    443 	 * and will have several configurations, which can be selected
    444 	 * via a sysctl variable. We select config 0 to start, which
    445 	 * means that no SCO data will be available.
    446 	 */
    447 	err = usbd_device2interface_handle(sc->sc_udev, 1, &sc->sc_iface1);
    448 	if (err) {
    449 		aprint_error_dev(self,
    450 		    "Could not get interface 1 handle %s (%d)\n",
    451 		    usbd_errstr(err), err);
    452 
    453 		return;
    454 	}
    455 
    456 	cd = usbd_get_config_descriptor(sc->sc_udev);
    457 	if (cd == NULL) {
    458 		aprint_error_dev(self, "could not get config descriptor\n");
    459 
    460 		return;
    461 	}
    462 
    463 	sc->sc_alt_config = usbd_get_no_alts(cd, 1);
    464 
    465 	/* set initial config */
    466 	err = ubt_set_isoc_config(sc);
    467 	if (err) {
    468 		aprint_error_dev(self, "ISOC config failed\n");
    469 
    470 		return;
    471 	}
    472 
    473 	/* Attach HCI */
    474 	sc->sc_unit = hci_attach_pcb(&ubt_hci, sc->sc_dev, 0);
    475 
    476 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    477 			   sc->sc_dev);
    478 
    479 	/* sysctl set-up for alternate configs */
    480 	sysctl_createv(&sc->sc_log, 0, NULL, &node,
    481 		0,
    482 		CTLTYPE_NODE, device_xname(sc->sc_dev),
    483 		SYSCTL_DESCR("ubt driver information"),
    484 		NULL, 0,
    485 		NULL, 0,
    486 		CTL_HW,
    487 		CTL_CREATE, CTL_EOL);
    488 
    489 	if (node != NULL) {
    490 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    491 			CTLFLAG_READWRITE,
    492 			CTLTYPE_INT, "config",
    493 			SYSCTL_DESCR("configuration number"),
    494 			ubt_sysctl_config, 0,
    495 			(void *)sc, 0,
    496 			CTL_HW, node->sysctl_num,
    497 			CTL_CREATE, CTL_EOL);
    498 
    499 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    500 			CTLFLAG_READONLY,
    501 			CTLTYPE_INT, "alt_config",
    502 			SYSCTL_DESCR("number of alternate configurations"),
    503 			NULL, 0,
    504 			&sc->sc_alt_config, sizeof(sc->sc_alt_config),
    505 			CTL_HW, node->sysctl_num,
    506 			CTL_CREATE, CTL_EOL);
    507 
    508 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    509 			CTLFLAG_READONLY,
    510 			CTLTYPE_INT, "sco_rxsize",
    511 			SYSCTL_DESCR("max SCO receive size"),
    512 			NULL, 0,
    513 			&sc->sc_scord_size, sizeof(sc->sc_scord_size),
    514 			CTL_HW, node->sysctl_num,
    515 			CTL_CREATE, CTL_EOL);
    516 
    517 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    518 			CTLFLAG_READONLY,
    519 			CTLTYPE_INT, "sco_txsize",
    520 			SYSCTL_DESCR("max SCO transmit size"),
    521 			NULL, 0,
    522 			&sc->sc_scowr_size, sizeof(sc->sc_scowr_size),
    523 			CTL_HW, node->sysctl_num,
    524 			CTL_CREATE, CTL_EOL);
    525 	}
    526 
    527 	sc->sc_ok = 1;
    528 
    529 	if (!pmf_device_register(self, NULL, NULL))
    530 		aprint_error_dev(self, "couldn't establish power handler\n");
    531 
    532 	return;
    533 }
    534 
    535 int
    536 ubt_detach(device_t self, int flags)
    537 {
    538 	struct ubt_softc *sc = device_private(self);
    539 	int s;
    540 
    541 	DPRINTF("sc=%p flags=%d\n", sc, flags);
    542 
    543 	pmf_device_deregister(self);
    544 
    545 	sc->sc_dying = 1;
    546 
    547 	if (!sc->sc_ok)
    548 		return 0;
    549 
    550 	/* delete sysctl nodes */
    551 	sysctl_teardown(&sc->sc_log);
    552 
    553 	/* Detach HCI interface */
    554 	if (sc->sc_unit) {
    555 		hci_detach_pcb(sc->sc_unit);
    556 		sc->sc_unit = NULL;
    557 	}
    558 
    559 	/*
    560 	 * Abort all pipes. Causes processes waiting for transfer to wake.
    561 	 *
    562 	 * Actually, hci_detach_pcb() above will call ubt_disable() which
    563 	 * may call ubt_abortdealloc(), but lets be sure since doing it
    564 	 * twice wont cause an error.
    565 	 */
    566 	ubt_abortdealloc(sc);
    567 
    568 	/* wait for all processes to finish */
    569 	s = splusb();
    570 	if (sc->sc_refcnt-- > 0)
    571 		usb_detach_waitold(sc->sc_dev);
    572 
    573 	splx(s);
    574 
    575 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    576 			   sc->sc_dev);
    577 
    578 	DPRINTFN(1, "driver detached\n");
    579 
    580 	return 0;
    581 }
    582 
    583 int
    584 ubt_activate(device_t self, enum devact act)
    585 {
    586 	struct ubt_softc *sc = device_private(self);
    587 
    588 	DPRINTFN(1, "sc=%p, act=%d\n", sc, act);
    589 
    590 	switch (act) {
    591 	case DVACT_DEACTIVATE:
    592 		sc->sc_dying = 1;
    593 		return 0;
    594 	default:
    595 		return EOPNOTSUPP;
    596 	}
    597 }
    598 
    599 /* set ISOC configuration */
    600 static int
    601 ubt_set_isoc_config(struct ubt_softc *sc)
    602 {
    603 	usb_endpoint_descriptor_t *ed;
    604 	int rd_addr, wr_addr, rd_size, wr_size;
    605 	uint8_t count, i;
    606 	int err;
    607 
    608 	err = usbd_set_interface(sc->sc_iface1, sc->sc_config);
    609 	if (err != USBD_NORMAL_COMPLETION) {
    610 		aprint_error_dev(sc->sc_dev,
    611 		    "Could not set config %d on ISOC interface. %s (%d)\n",
    612 		    sc->sc_config, usbd_errstr(err), err);
    613 
    614 		return err == USBD_IN_USE ? EBUSY : EIO;
    615 	}
    616 
    617 	/*
    618 	 * We wont get past the above if there are any pipes open, so no
    619 	 * need to worry about buf/xfer/pipe deallocation. If we get an
    620 	 * error after this, the frame quantities will be 0 and no SCO
    621 	 * data will be possible.
    622 	 */
    623 
    624 	sc->sc_scord_size = rd_size = 0;
    625 	sc->sc_scord_addr = rd_addr = -1;
    626 
    627 	sc->sc_scowr_size = wr_size = 0;
    628 	sc->sc_scowr_addr = wr_addr = -1;
    629 
    630 	count = 0;
    631 	(void)usbd_endpoint_count(sc->sc_iface1, &count);
    632 
    633 	for (i = 0 ; i < count ; i++) {
    634 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface1, i);
    635 		if (ed == NULL) {
    636 			aprint_error_dev(sc->sc_dev,
    637 			    "could not read endpoint descriptor %d\n", i);
    638 
    639 			return EIO;
    640 		}
    641 
    642 		DPRINTFN(5, "%s: endpoint type %02x (%02x) addr %02x (%s)\n",
    643 			device_xname(sc->sc_dev),
    644 			UE_GET_XFERTYPE(ed->bmAttributes),
    645 			UE_GET_ISO_TYPE(ed->bmAttributes),
    646 			ed->bEndpointAddress,
    647 			UE_GET_DIR(ed->bEndpointAddress) ? "in" : "out");
    648 
    649 		if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
    650 			continue;
    651 
    652 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN) {
    653 			rd_addr = ed->bEndpointAddress;
    654 			rd_size = UGETW(ed->wMaxPacketSize);
    655 		} else {
    656 			wr_addr = ed->bEndpointAddress;
    657 			wr_size = UGETW(ed->wMaxPacketSize);
    658 		}
    659 	}
    660 
    661 	if (rd_addr == -1) {
    662 		aprint_error_dev(sc->sc_dev,
    663 		    "missing ISOC IN endpoint on interface config %d\n",
    664 		    sc->sc_config);
    665 
    666 		return ENOENT;
    667 	}
    668 	if (wr_addr == -1) {
    669 		aprint_error_dev(sc->sc_dev,
    670 		    "missing ISOC OUT endpoint on interface config %d\n",
    671 		    sc->sc_config);
    672 
    673 		return ENOENT;
    674 	}
    675 
    676 	if (rd_size > MLEN) {
    677 		aprint_error_dev(sc->sc_dev, "rd_size=%d exceeds MLEN\n",
    678 		    rd_size);
    679 
    680 		return EOVERFLOW;
    681 	}
    682 
    683 	if (wr_size > MLEN) {
    684 		aprint_error_dev(sc->sc_dev, "wr_size=%d exceeds MLEN\n",
    685 		    wr_size);
    686 
    687 		return EOVERFLOW;
    688 	}
    689 
    690 	sc->sc_scord_size = rd_size;
    691 	sc->sc_scord_addr = rd_addr;
    692 
    693 	sc->sc_scowr_size = wr_size;
    694 	sc->sc_scowr_addr = wr_addr;
    695 
    696 	return 0;
    697 }
    698 
    699 /* sysctl helper to set alternate configurations */
    700 static int
    701 ubt_sysctl_config(SYSCTLFN_ARGS)
    702 {
    703 	struct sysctlnode node;
    704 	struct ubt_softc *sc;
    705 	int t, error;
    706 
    707 	node = *rnode;
    708 	sc = node.sysctl_data;
    709 
    710 	t = sc->sc_config;
    711 	node.sysctl_data = &t;
    712 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    713 	if (error || newp == NULL)
    714 		return error;
    715 
    716 	if (t < 0 || t >= sc->sc_alt_config)
    717 		return EINVAL;
    718 
    719 	/* This may not change when the unit is enabled */
    720 	if (sc->sc_enabled)
    721 		return EBUSY;
    722 
    723 	KERNEL_LOCK(1, curlwp);
    724 	sc->sc_config = t;
    725 	error = ubt_set_isoc_config(sc);
    726 	KERNEL_UNLOCK_ONE(curlwp);
    727 	return error;
    728 }
    729 
    730 static void
    731 ubt_abortdealloc(struct ubt_softc *sc)
    732 {
    733 	int i;
    734 
    735 	DPRINTFN(1, "sc=%p\n", sc);
    736 
    737 	/* Abort all pipes */
    738 	usbd_abort_default_pipe(sc->sc_udev);
    739 
    740 	if (sc->sc_evt_pipe != NULL) {
    741 		usbd_abort_pipe(sc->sc_evt_pipe);
    742 	}
    743 
    744 	if (sc->sc_aclrd_pipe != NULL) {
    745 		usbd_abort_pipe(sc->sc_aclrd_pipe);
    746 	}
    747 
    748 	if (sc->sc_aclwr_pipe != NULL) {
    749 		usbd_abort_pipe(sc->sc_aclwr_pipe);
    750 	}
    751 
    752 	if (sc->sc_scord_pipe != NULL) {
    753 		usbd_abort_pipe(sc->sc_scord_pipe);
    754 	}
    755 
    756 	if (sc->sc_scowr_pipe != NULL) {
    757 		usbd_abort_pipe(sc->sc_scowr_pipe);
    758 	}
    759 
    760 	/* Free event buffer */
    761 	if (sc->sc_evt_buf != NULL) {
    762 		kmem_free(sc->sc_evt_buf, UBT_BUFSIZ_EVENT);
    763 		sc->sc_evt_buf = NULL;
    764 	}
    765 
    766 	/* Free all xfers and xfer buffers (implicit) */
    767 	if (sc->sc_cmd_xfer != NULL) {
    768 		usbd_destroy_xfer(sc->sc_cmd_xfer);
    769 		sc->sc_cmd_xfer = NULL;
    770 		sc->sc_cmd_buf = NULL;
    771 	}
    772 
    773 	if (sc->sc_aclrd_xfer != NULL) {
    774 		usbd_destroy_xfer(sc->sc_aclrd_xfer);
    775 		sc->sc_aclrd_xfer = NULL;
    776 		sc->sc_aclrd_buf = NULL;
    777 	}
    778 
    779 	if (sc->sc_aclwr_xfer != NULL) {
    780 		usbd_destroy_xfer(sc->sc_aclwr_xfer);
    781 		sc->sc_aclwr_xfer = NULL;
    782 		sc->sc_aclwr_buf = NULL;
    783 	}
    784 
    785 	for (i = 0 ; i < UBT_NXFERS ; i++) {
    786 		if (sc->sc_scord[i].xfer != NULL) {
    787 			usbd_destroy_xfer(sc->sc_scord[i].xfer);
    788 			sc->sc_scord[i].xfer = NULL;
    789 			sc->sc_scord[i].buf = NULL;
    790 		}
    791 
    792 		if (sc->sc_scowr[i].xfer != NULL) {
    793 			usbd_destroy_xfer(sc->sc_scowr[i].xfer);
    794 			sc->sc_scowr[i].xfer = NULL;
    795 			sc->sc_scowr[i].buf = NULL;
    796 		}
    797 	}
    798 
    799 	if (sc->sc_evt_pipe != NULL) {
    800 		usbd_close_pipe(sc->sc_evt_pipe);
    801 		sc->sc_evt_pipe = NULL;
    802 	}
    803 
    804 	if (sc->sc_aclrd_pipe != NULL) {
    805 		usbd_close_pipe(sc->sc_aclrd_pipe);
    806 		sc->sc_aclrd_pipe = NULL;
    807 	}
    808 
    809 	if (sc->sc_aclwr_pipe != NULL) {
    810 		usbd_close_pipe(sc->sc_aclwr_pipe);
    811 		sc->sc_aclwr_pipe = NULL;
    812 	}
    813 
    814 	if (sc->sc_scord_pipe != NULL) {
    815 		usbd_close_pipe(sc->sc_scord_pipe);
    816 		sc->sc_scord_pipe = NULL;
    817 	}
    818 
    819 	if (sc->sc_scowr_pipe != NULL) {
    820 		usbd_close_pipe(sc->sc_scowr_pipe);
    821 		sc->sc_scowr_pipe = NULL;
    822 	}
    823 
    824 	/* Free partial SCO packets */
    825 	if (sc->sc_scord_mbuf != NULL) {
    826 		m_freem(sc->sc_scord_mbuf);
    827 		sc->sc_scord_mbuf = NULL;
    828 	}
    829 
    830 	if (sc->sc_scowr_mbuf != NULL) {
    831 		m_freem(sc->sc_scowr_mbuf);
    832 		sc->sc_scowr_mbuf = NULL;
    833 	}
    834 
    835 	/* Empty mbuf queues */
    836 	MBUFQ_DRAIN(&sc->sc_cmd_queue);
    837 	MBUFQ_DRAIN(&sc->sc_aclwr_queue);
    838 	MBUFQ_DRAIN(&sc->sc_scowr_queue);
    839 }
    840 
    841 /*******************************************************************************
    842  *
    843  * Bluetooth Unit/USB callbacks
    844  *
    845  */
    846 static int
    847 ubt_enable(device_t self)
    848 {
    849 	struct ubt_softc *sc = device_private(self);
    850 	usbd_status err;
    851 	int s, i, error;
    852 
    853 	DPRINTFN(1, "sc=%p\n", sc);
    854 
    855 	if (sc->sc_enabled)
    856 		return 0;
    857 
    858 	s = splusb();
    859 
    860 	/* Events */
    861 	sc->sc_evt_buf = kmem_alloc(UBT_BUFSIZ_EVENT, KM_SLEEP);
    862 	if (sc->sc_evt_buf == NULL) {
    863 		error = ENOMEM;
    864 		goto bad;
    865 	}
    866 	err = usbd_open_pipe_intr(sc->sc_iface0,
    867 				  sc->sc_evt_addr,
    868 				  USBD_SHORT_XFER_OK,
    869 				  &sc->sc_evt_pipe,
    870 				  sc,
    871 				  sc->sc_evt_buf,
    872 				  UBT_BUFSIZ_EVENT,
    873 				  ubt_recv_event,
    874 				  USBD_DEFAULT_INTERVAL);
    875 	if (err != USBD_NORMAL_COMPLETION) {
    876 		error = EIO;
    877 		goto bad;
    878 	}
    879 
    880 	/* Commands */
    881 	struct usbd_pipe *pipe0 = usbd_get_pipe0(sc->sc_udev);
    882 	error = usbd_create_xfer(pipe0, UBT_BUFSIZ_CMD, 0, 0,
    883 	    &sc->sc_cmd_xfer);
    884 	if (error)
    885 		goto bad;
    886 	sc->sc_cmd_buf = usbd_get_buffer(sc->sc_cmd_xfer);
    887 	sc->sc_cmd_busy = 0;
    888 
    889 	/* ACL read */
    890 	err = usbd_open_pipe(sc->sc_iface0, sc->sc_aclrd_addr,
    891 				USBD_EXCLUSIVE_USE, &sc->sc_aclrd_pipe);
    892 	if (err != USBD_NORMAL_COMPLETION) {
    893 		error = EIO;
    894 		goto bad;
    895 	}
    896 	error = usbd_create_xfer(sc->sc_aclrd_pipe, UBT_BUFSIZ_ACL,
    897 	    USBD_SHORT_XFER_OK, 0, &sc->sc_aclrd_xfer);
    898 	if (error)
    899 		goto bad;
    900 	sc->sc_aclrd_buf = usbd_get_buffer(sc->sc_aclrd_xfer);
    901 	sc->sc_aclrd_busy = 0;
    902 	ubt_recv_acl_start(sc);
    903 
    904 	/* ACL write */
    905 	err = usbd_open_pipe(sc->sc_iface0, sc->sc_aclwr_addr,
    906 				USBD_EXCLUSIVE_USE, &sc->sc_aclwr_pipe);
    907 	if (err != USBD_NORMAL_COMPLETION) {
    908 		error = EIO;
    909 		goto bad;
    910 	}
    911 	error = usbd_create_xfer(sc->sc_aclwr_pipe, UBT_BUFSIZ_ACL,
    912 	    USBD_FORCE_SHORT_XFER, 0, &sc->sc_aclwr_xfer);
    913 	if (error)
    914 		goto bad;
    915 	sc->sc_aclwr_buf = usbd_get_buffer(sc->sc_aclwr_xfer);
    916 	sc->sc_aclwr_busy = 0;
    917 
    918 	/* SCO read */
    919 	if (sc->sc_scord_size > 0) {
    920 		err = usbd_open_pipe(sc->sc_iface1, sc->sc_scord_addr,
    921 					USBD_EXCLUSIVE_USE, &sc->sc_scord_pipe);
    922 		if (err != USBD_NORMAL_COMPLETION) {
    923 			error = EIO;
    924 			goto bad;
    925 		}
    926 
    927 		for (i = 0 ; i < UBT_NXFERS ; i++) {
    928 		        error = usbd_create_xfer(sc->sc_scord_pipe,
    929 			    sc->sc_scord_size * UBT_NFRAMES,
    930 			    USBD_SHORT_XFER_OK, UBT_NFRAMES,
    931 			    &sc->sc_scord[i].xfer);
    932 			if (error)
    933 				goto bad;
    934 
    935 			sc->sc_scord[i].buf =
    936 			    usbd_get_buffer(sc->sc_scord[i].xfer);
    937 			sc->sc_scord[i].softc = sc;
    938 			sc->sc_scord[i].busy = 0;
    939 			ubt_recv_sco_start1(sc, &sc->sc_scord[i]);
    940 		}
    941 	}
    942 
    943 	/* SCO write */
    944 	if (sc->sc_scowr_size > 0) {
    945 		err = usbd_open_pipe(sc->sc_iface1, sc->sc_scowr_addr,
    946 					USBD_EXCLUSIVE_USE, &sc->sc_scowr_pipe);
    947 		if (err != USBD_NORMAL_COMPLETION) {
    948 			error = EIO;
    949 			goto bad;
    950 		}
    951 
    952 		for (i = 0 ; i < UBT_NXFERS ; i++) {
    953 			error = usbd_create_xfer(sc->sc_scowr_pipe,
    954 			    sc->sc_scowr_size * UBT_NFRAMES,
    955 			    USBD_FORCE_SHORT_XFER, UBT_NFRAMES,
    956 			    &sc->sc_scowr[i].xfer);
    957 			if (error)
    958 				goto bad;
    959 			sc->sc_scowr[i].buf =
    960 			    usbd_get_buffer(sc->sc_scowr[i].xfer);
    961 			sc->sc_scowr[i].softc = sc;
    962 			sc->sc_scowr[i].busy = 0;
    963 		}
    964 
    965 		sc->sc_scowr_busy = 0;
    966 	}
    967 
    968 	sc->sc_enabled = 1;
    969 	splx(s);
    970 	return 0;
    971 
    972 bad:
    973 	ubt_abortdealloc(sc);
    974 	splx(s);
    975 	return error;
    976 }
    977 
    978 static void
    979 ubt_disable(device_t self)
    980 {
    981 	struct ubt_softc *sc = device_private(self);
    982 	int s;
    983 
    984 	DPRINTFN(1, "sc=%p\n", sc);
    985 
    986 	if (sc->sc_enabled == 0)
    987 		return;
    988 
    989 	s = splusb();
    990 	ubt_abortdealloc(sc);
    991 
    992 	sc->sc_enabled = 0;
    993 	splx(s);
    994 }
    995 
    996 static void
    997 ubt_xmit_cmd(device_t self, struct mbuf *m)
    998 {
    999 	struct ubt_softc *sc = device_private(self);
   1000 	int s;
   1001 
   1002 	KASSERT(sc->sc_enabled);
   1003 
   1004 	s = splusb();
   1005 	MBUFQ_ENQUEUE(&sc->sc_cmd_queue, m);
   1006 
   1007 	if (sc->sc_cmd_busy == 0)
   1008 		ubt_xmit_cmd_start(sc);
   1009 
   1010 	splx(s);
   1011 }
   1012 
   1013 static void
   1014 ubt_xmit_cmd_start(struct ubt_softc *sc)
   1015 {
   1016 	usb_device_request_t req;
   1017 	usbd_status status;
   1018 	struct mbuf *m;
   1019 	int len;
   1020 
   1021 	if (sc->sc_dying)
   1022 		return;
   1023 
   1024 	if (MBUFQ_FIRST(&sc->sc_cmd_queue) == NULL)
   1025 		return;
   1026 
   1027 	MBUFQ_DEQUEUE(&sc->sc_cmd_queue, m);
   1028 	KASSERT(m != NULL);
   1029 
   1030 	DPRINTFN(15, "%s: xmit CMD packet (%d bytes)\n",
   1031 			device_xname(sc->sc_dev), m->m_pkthdr.len);
   1032 
   1033 	sc->sc_refcnt++;
   1034 	sc->sc_cmd_busy = 1;
   1035 
   1036 	len = m->m_pkthdr.len - 1;
   1037 	m_copydata(m, 1, len, sc->sc_cmd_buf);
   1038 	m_freem(m);
   1039 
   1040 	memset(&req, 0, sizeof(req));
   1041 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
   1042 	USETW(req.wLength, len);
   1043 
   1044 	usbd_setup_default_xfer(sc->sc_cmd_xfer,
   1045 				sc->sc_udev,
   1046 				sc,
   1047 				UBT_CMD_TIMEOUT,
   1048 				&req,
   1049 				sc->sc_cmd_buf,
   1050 				len,
   1051 				USBD_FORCE_SHORT_XFER,
   1052 				ubt_xmit_cmd_complete);
   1053 
   1054 	status = usbd_transfer(sc->sc_cmd_xfer);
   1055 
   1056 	KASSERT(status != USBD_NORMAL_COMPLETION);
   1057 
   1058 	if (status != USBD_IN_PROGRESS) {
   1059 		DPRINTF("usbd_transfer status=%s (%d)\n",
   1060 			usbd_errstr(status), status);
   1061 
   1062 		sc->sc_refcnt--;
   1063 		sc->sc_cmd_busy = 0;
   1064 	}
   1065 }
   1066 
   1067 static void
   1068 ubt_xmit_cmd_complete(struct usbd_xfer *xfer,
   1069 			void * h, usbd_status status)
   1070 {
   1071 	struct ubt_softc *sc = h;
   1072 	uint32_t count;
   1073 
   1074 	DPRINTFN(15, "%s: CMD complete status=%s (%d)\n",
   1075 			device_xname(sc->sc_dev), usbd_errstr(status), status);
   1076 
   1077 	sc->sc_cmd_busy = 0;
   1078 
   1079 	if (--sc->sc_refcnt < 0) {
   1080 		DPRINTF("sc_refcnt=%d\n", sc->sc_refcnt);
   1081 		usb_detach_wakeupold(sc->sc_dev);
   1082 		return;
   1083 	}
   1084 
   1085 	if (sc->sc_dying) {
   1086 		DPRINTF("sc_dying\n");
   1087 		return;
   1088 	}
   1089 
   1090 	if (status != USBD_NORMAL_COMPLETION) {
   1091 		DPRINTF("status=%s (%d)\n",
   1092 			usbd_errstr(status), status);
   1093 
   1094 		sc->sc_stats.err_tx++;
   1095 		return;
   1096 	}
   1097 
   1098 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1099 	sc->sc_stats.cmd_tx++;
   1100 	sc->sc_stats.byte_tx += count;
   1101 
   1102 	ubt_xmit_cmd_start(sc);
   1103 }
   1104 
   1105 static void
   1106 ubt_xmit_acl(device_t self, struct mbuf *m)
   1107 {
   1108 	struct ubt_softc *sc = device_private(self);
   1109 	int s;
   1110 
   1111 	KASSERT(sc->sc_enabled);
   1112 
   1113 	s = splusb();
   1114 	MBUFQ_ENQUEUE(&sc->sc_aclwr_queue, m);
   1115 
   1116 	if (sc->sc_aclwr_busy == 0)
   1117 		ubt_xmit_acl_start(sc);
   1118 
   1119 	splx(s);
   1120 }
   1121 
   1122 static void
   1123 ubt_xmit_acl_start(struct ubt_softc *sc)
   1124 {
   1125 	struct mbuf *m;
   1126 	usbd_status status;
   1127 	int len;
   1128 
   1129 	if (sc->sc_dying)
   1130 		return;
   1131 
   1132 	if (MBUFQ_FIRST(&sc->sc_aclwr_queue) == NULL)
   1133 		return;
   1134 
   1135 	sc->sc_refcnt++;
   1136 	sc->sc_aclwr_busy = 1;
   1137 
   1138 	MBUFQ_DEQUEUE(&sc->sc_aclwr_queue, m);
   1139 	KASSERT(m != NULL);
   1140 
   1141 	DPRINTFN(15, "%s: xmit ACL packet (%d bytes)\n",
   1142 			device_xname(sc->sc_dev), m->m_pkthdr.len);
   1143 
   1144 	len = m->m_pkthdr.len - 1;
   1145 	if (len > UBT_BUFSIZ_ACL) {
   1146 		DPRINTF("%s: truncating ACL packet (%d => %d)!\n",
   1147 			device_xname(sc->sc_dev), len, UBT_BUFSIZ_ACL);
   1148 
   1149 		len = UBT_BUFSIZ_ACL;
   1150 	}
   1151 
   1152 	m_copydata(m, 1, len, sc->sc_aclwr_buf);
   1153 	m_freem(m);
   1154 
   1155 	sc->sc_stats.acl_tx++;
   1156 	sc->sc_stats.byte_tx += len;
   1157 
   1158 	usbd_setup_xfer(sc->sc_aclwr_xfer,
   1159 			sc,
   1160 			sc->sc_aclwr_buf,
   1161 			len,
   1162 			USBD_FORCE_SHORT_XFER,
   1163 			UBT_ACL_TIMEOUT,
   1164 			ubt_xmit_acl_complete);
   1165 
   1166 	status = usbd_transfer(sc->sc_aclwr_xfer);
   1167 
   1168 	KASSERT(status != USBD_NORMAL_COMPLETION);
   1169 
   1170 	if (status != USBD_IN_PROGRESS) {
   1171 		DPRINTF("usbd_transfer status=%s (%d)\n",
   1172 			usbd_errstr(status), status);
   1173 
   1174 		sc->sc_refcnt--;
   1175 		sc->sc_aclwr_busy = 0;
   1176 	}
   1177 }
   1178 
   1179 static void
   1180 ubt_xmit_acl_complete(struct usbd_xfer *xfer,
   1181 		void * h, usbd_status status)
   1182 {
   1183 	struct ubt_softc *sc = h;
   1184 
   1185 	DPRINTFN(15, "%s: ACL complete status=%s (%d)\n",
   1186 		device_xname(sc->sc_dev), usbd_errstr(status), status);
   1187 
   1188 	sc->sc_aclwr_busy = 0;
   1189 
   1190 	if (--sc->sc_refcnt < 0) {
   1191 		usb_detach_wakeupold(sc->sc_dev);
   1192 		return;
   1193 	}
   1194 
   1195 	if (sc->sc_dying)
   1196 		return;
   1197 
   1198 	if (status != USBD_NORMAL_COMPLETION) {
   1199 		DPRINTF("status=%s (%d)\n",
   1200 			usbd_errstr(status), status);
   1201 
   1202 		sc->sc_stats.err_tx++;
   1203 
   1204 		if (status == USBD_STALLED)
   1205 			usbd_clear_endpoint_stall_async(sc->sc_aclwr_pipe);
   1206 		else
   1207 			return;
   1208 	}
   1209 
   1210 	ubt_xmit_acl_start(sc);
   1211 }
   1212 
   1213 static void
   1214 ubt_xmit_sco(device_t self, struct mbuf *m)
   1215 {
   1216 	struct ubt_softc *sc = device_private(self);
   1217 	int s;
   1218 
   1219 	KASSERT(sc->sc_enabled);
   1220 
   1221 	s = splusb();
   1222 	MBUFQ_ENQUEUE(&sc->sc_scowr_queue, m);
   1223 
   1224 	if (sc->sc_scowr_busy == 0)
   1225 		ubt_xmit_sco_start(sc);
   1226 
   1227 	splx(s);
   1228 }
   1229 
   1230 static void
   1231 ubt_xmit_sco_start(struct ubt_softc *sc)
   1232 {
   1233 	int i;
   1234 
   1235 	if (sc->sc_dying || sc->sc_scowr_size == 0)
   1236 		return;
   1237 
   1238 	for (i = 0 ; i < UBT_NXFERS ; i++) {
   1239 		if (sc->sc_scowr[i].busy)
   1240 			continue;
   1241 
   1242 		ubt_xmit_sco_start1(sc, &sc->sc_scowr[i]);
   1243 	}
   1244 }
   1245 
   1246 static void
   1247 ubt_xmit_sco_start1(struct ubt_softc *sc, struct ubt_isoc_xfer *isoc)
   1248 {
   1249 	struct mbuf *m;
   1250 	uint8_t *buf;
   1251 	int num, len, size, space;
   1252 
   1253 	space = sc->sc_scowr_size * UBT_NFRAMES;
   1254 	buf = isoc->buf;
   1255 	len = 0;
   1256 
   1257 	/*
   1258 	 * Fill the request buffer with data from the queue,
   1259 	 * keeping any leftover packet on our private hook.
   1260 	 *
   1261 	 * Complete packets are passed back up to the stack
   1262 	 * for disposal, since we can't rely on the controller
   1263 	 * to tell us when it has finished with them.
   1264 	 */
   1265 
   1266 	m = sc->sc_scowr_mbuf;
   1267 	while (space > 0) {
   1268 		if (m == NULL) {
   1269 			MBUFQ_DEQUEUE(&sc->sc_scowr_queue, m);
   1270 			if (m == NULL)
   1271 				break;
   1272 
   1273 			m_adj(m, 1);	/* packet type */
   1274 		}
   1275 
   1276 		if (m->m_pkthdr.len > 0) {
   1277 			size = MIN(m->m_pkthdr.len, space);
   1278 
   1279 			m_copydata(m, 0, size, buf);
   1280 			m_adj(m, size);
   1281 
   1282 			buf += size;
   1283 			len += size;
   1284 			space -= size;
   1285 		}
   1286 
   1287 		if (m->m_pkthdr.len == 0) {
   1288 			sc->sc_stats.sco_tx++;
   1289 			if (!hci_complete_sco(sc->sc_unit, m))
   1290 				sc->sc_stats.err_tx++;
   1291 
   1292 			m = NULL;
   1293 		}
   1294 	}
   1295 	sc->sc_scowr_mbuf = m;
   1296 
   1297 	DPRINTFN(15, "isoc=%p, len=%d, space=%d\n", isoc, len, space);
   1298 
   1299 	if (len == 0)	/* nothing to send */
   1300 		return;
   1301 
   1302 	sc->sc_refcnt++;
   1303 	sc->sc_scowr_busy = 1;
   1304 	sc->sc_stats.byte_tx += len;
   1305 	isoc->busy = 1;
   1306 
   1307 	/*
   1308 	 * calculate number of isoc frames and sizes
   1309 	 */
   1310 
   1311 	for (num = 0 ; len > 0 ; num++) {
   1312 		size = MIN(sc->sc_scowr_size, len);
   1313 
   1314 		isoc->size[num] = size;
   1315 		len -= size;
   1316 	}
   1317 
   1318 	usbd_setup_isoc_xfer(isoc->xfer,
   1319 			     isoc,
   1320 			     isoc->size,
   1321 			     num,
   1322 			     USBD_FORCE_SHORT_XFER,
   1323 			     ubt_xmit_sco_complete);
   1324 
   1325 	usbd_transfer(isoc->xfer);
   1326 }
   1327 
   1328 static void
   1329 ubt_xmit_sco_complete(struct usbd_xfer *xfer,
   1330 		void * h, usbd_status status)
   1331 {
   1332 	struct ubt_isoc_xfer *isoc = h;
   1333 	struct ubt_softc *sc;
   1334 	int i;
   1335 
   1336 	KASSERT(xfer == isoc->xfer);
   1337 	sc = isoc->softc;
   1338 
   1339 	DPRINTFN(15, "isoc=%p, status=%s (%d)\n",
   1340 		isoc, usbd_errstr(status), status);
   1341 
   1342 	isoc->busy = 0;
   1343 
   1344 	for (i = 0 ; ; i++) {
   1345 		if (i == UBT_NXFERS) {
   1346 			sc->sc_scowr_busy = 0;
   1347 			break;
   1348 		}
   1349 
   1350 		if (sc->sc_scowr[i].busy)
   1351 			break;
   1352 	}
   1353 
   1354 	if (--sc->sc_refcnt < 0) {
   1355 		usb_detach_wakeupold(sc->sc_dev);
   1356 		return;
   1357 	}
   1358 
   1359 	if (sc->sc_dying)
   1360 		return;
   1361 
   1362 	if (status != USBD_NORMAL_COMPLETION) {
   1363 		DPRINTF("status=%s (%d)\n",
   1364 			usbd_errstr(status), status);
   1365 
   1366 		sc->sc_stats.err_tx++;
   1367 
   1368 		if (status == USBD_STALLED)
   1369 			usbd_clear_endpoint_stall_async(sc->sc_scowr_pipe);
   1370 		else
   1371 			return;
   1372 	}
   1373 
   1374 	ubt_xmit_sco_start(sc);
   1375 }
   1376 
   1377 /*
   1378  * load incoming data into an mbuf with
   1379  * leading type byte
   1380  */
   1381 static struct mbuf *
   1382 ubt_mbufload(uint8_t *buf, int count, uint8_t type)
   1383 {
   1384 	struct mbuf *m;
   1385 
   1386 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1387 	if (m == NULL)
   1388 		return NULL;
   1389 
   1390 	*mtod(m, uint8_t *) = type;
   1391 	m->m_pkthdr.len = m->m_len = MHLEN;
   1392 	m_copyback(m, 1, count, buf);	// (extends if necessary)
   1393 	if (m->m_pkthdr.len != MAX(MHLEN, count + 1)) {
   1394 		m_free(m);
   1395 		return NULL;
   1396 	}
   1397 
   1398 	m->m_pkthdr.len = count + 1;
   1399 	m->m_len = MIN(MHLEN, m->m_pkthdr.len);
   1400 
   1401 	return m;
   1402 }
   1403 
   1404 static void
   1405 ubt_recv_event(struct usbd_xfer *xfer, void * h, usbd_status status)
   1406 {
   1407 	struct ubt_softc *sc = h;
   1408 	struct mbuf *m;
   1409 	uint32_t count;
   1410 	void *buf;
   1411 
   1412 	DPRINTFN(15, "sc=%p status=%s (%d)\n",
   1413 		    sc, usbd_errstr(status), status);
   1414 
   1415 	if (status != USBD_NORMAL_COMPLETION || sc->sc_dying)
   1416 		return;
   1417 
   1418 	usbd_get_xfer_status(xfer, NULL, &buf, &count, NULL);
   1419 
   1420 	if (count < sizeof(hci_event_hdr_t) - 1) {
   1421 		DPRINTF("dumped undersized event (count = %d)\n", count);
   1422 		sc->sc_stats.err_rx++;
   1423 		return;
   1424 	}
   1425 
   1426 	sc->sc_stats.evt_rx++;
   1427 	sc->sc_stats.byte_rx += count;
   1428 
   1429 	m = ubt_mbufload(buf, count, HCI_EVENT_PKT);
   1430 	if (m == NULL || !hci_input_event(sc->sc_unit, m))
   1431 		sc->sc_stats.err_rx++;
   1432 }
   1433 
   1434 static void
   1435 ubt_recv_acl_start(struct ubt_softc *sc)
   1436 {
   1437 	usbd_status status;
   1438 
   1439 	DPRINTFN(15, "sc=%p\n", sc);
   1440 
   1441 	if (sc->sc_aclrd_busy || sc->sc_dying) {
   1442 		DPRINTF("sc_aclrd_busy=%d, sc_dying=%d\n",
   1443 			sc->sc_aclrd_busy,
   1444 			sc->sc_dying);
   1445 
   1446 		return;
   1447 	}
   1448 
   1449 	sc->sc_refcnt++;
   1450 	sc->sc_aclrd_busy = 1;
   1451 
   1452 	usbd_setup_xfer(sc->sc_aclrd_xfer,
   1453 			sc,
   1454 			sc->sc_aclrd_buf,
   1455 			UBT_BUFSIZ_ACL,
   1456 			USBD_SHORT_XFER_OK,
   1457 			USBD_NO_TIMEOUT,
   1458 			ubt_recv_acl_complete);
   1459 
   1460 	status = usbd_transfer(sc->sc_aclrd_xfer);
   1461 
   1462 	KASSERT(status != USBD_NORMAL_COMPLETION);
   1463 
   1464 	if (status != USBD_IN_PROGRESS) {
   1465 		DPRINTF("usbd_transfer status=%s (%d)\n",
   1466 			usbd_errstr(status), status);
   1467 
   1468 		sc->sc_refcnt--;
   1469 		sc->sc_aclrd_busy = 0;
   1470 	}
   1471 }
   1472 
   1473 static void
   1474 ubt_recv_acl_complete(struct usbd_xfer *xfer,
   1475 		void * h, usbd_status status)
   1476 {
   1477 	struct ubt_softc *sc = h;
   1478 	struct mbuf *m;
   1479 	uint32_t count;
   1480 	void *buf;
   1481 
   1482 	DPRINTFN(15, "sc=%p status=%s (%d)\n",
   1483 			sc, usbd_errstr(status), status);
   1484 
   1485 	sc->sc_aclrd_busy = 0;
   1486 
   1487 	if (--sc->sc_refcnt < 0) {
   1488 		DPRINTF("refcnt = %d\n", sc->sc_refcnt);
   1489 		usb_detach_wakeupold(sc->sc_dev);
   1490 		return;
   1491 	}
   1492 
   1493 	if (sc->sc_dying) {
   1494 		DPRINTF("sc_dying\n");
   1495 		return;
   1496 	}
   1497 
   1498 	if (status != USBD_NORMAL_COMPLETION) {
   1499 		DPRINTF("status=%s (%d)\n",
   1500 			usbd_errstr(status), status);
   1501 
   1502 		sc->sc_stats.err_rx++;
   1503 
   1504 		if (status == USBD_STALLED)
   1505 			usbd_clear_endpoint_stall_async(sc->sc_aclrd_pipe);
   1506 		else
   1507 			return;
   1508 	} else {
   1509 		usbd_get_xfer_status(xfer, NULL, &buf, &count, NULL);
   1510 
   1511 		if (count < sizeof(hci_acldata_hdr_t) - 1) {
   1512 			DPRINTF("dumped undersized packet (%d)\n", count);
   1513 			sc->sc_stats.err_rx++;
   1514 		} else {
   1515 			sc->sc_stats.acl_rx++;
   1516 			sc->sc_stats.byte_rx += count;
   1517 
   1518 			m = ubt_mbufload(buf, count, HCI_ACL_DATA_PKT);
   1519 			if (m == NULL || !hci_input_acl(sc->sc_unit, m))
   1520 				sc->sc_stats.err_rx++;
   1521 		}
   1522 	}
   1523 
   1524 	/* and restart */
   1525 	ubt_recv_acl_start(sc);
   1526 }
   1527 
   1528 static void
   1529 ubt_recv_sco_start1(struct ubt_softc *sc, struct ubt_isoc_xfer *isoc)
   1530 {
   1531 	int i;
   1532 
   1533 	DPRINTFN(15, "sc=%p, isoc=%p\n", sc, isoc);
   1534 
   1535 	if (isoc->busy || sc->sc_dying || sc->sc_scord_size == 0) {
   1536 		DPRINTF("%s%s%s\n",
   1537 			isoc->busy ? " busy" : "",
   1538 			sc->sc_dying ? " dying" : "",
   1539 			sc->sc_scord_size == 0 ? " size=0" : "");
   1540 
   1541 		return;
   1542 	}
   1543 
   1544 	sc->sc_refcnt++;
   1545 	isoc->busy = 1;
   1546 
   1547 	for (i = 0 ; i < UBT_NFRAMES ; i++)
   1548 		isoc->size[i] = sc->sc_scord_size;
   1549 
   1550 	usbd_setup_isoc_xfer(isoc->xfer,
   1551 			     isoc,
   1552 			     isoc->size,
   1553 			     UBT_NFRAMES,
   1554 			     USBD_SHORT_XFER_OK,
   1555 			     ubt_recv_sco_complete);
   1556 
   1557 	usbd_transfer(isoc->xfer);
   1558 }
   1559 
   1560 static void
   1561 ubt_recv_sco_complete(struct usbd_xfer *xfer,
   1562 		void * h, usbd_status status)
   1563 {
   1564 	struct ubt_isoc_xfer *isoc = h;
   1565 	struct ubt_softc *sc;
   1566 	struct mbuf *m;
   1567 	uint32_t count;
   1568 	uint8_t *ptr, *frame;
   1569 	int i, size, got, want;
   1570 
   1571 	KASSERT(isoc != NULL);
   1572 	KASSERT(isoc->xfer == xfer);
   1573 
   1574 	sc = isoc->softc;
   1575 	isoc->busy = 0;
   1576 
   1577 	if (--sc->sc_refcnt < 0) {
   1578 		DPRINTF("refcnt=%d\n", sc->sc_refcnt);
   1579 		usb_detach_wakeupold(sc->sc_dev);
   1580 		return;
   1581 	}
   1582 
   1583 	if (sc->sc_dying) {
   1584 		DPRINTF("sc_dying\n");
   1585 		return;
   1586 	}
   1587 
   1588 	if (status != USBD_NORMAL_COMPLETION) {
   1589 		DPRINTF("status=%s (%d)\n",
   1590 			usbd_errstr(status), status);
   1591 
   1592 		sc->sc_stats.err_rx++;
   1593 
   1594 		if (status == USBD_STALLED) {
   1595 			usbd_clear_endpoint_stall_async(sc->sc_scord_pipe);
   1596 			goto restart;
   1597 		}
   1598 
   1599 		return;
   1600 	}
   1601 
   1602 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   1603 	if (count == 0)
   1604 		goto restart;
   1605 
   1606 	DPRINTFN(15, "sc=%p, isoc=%p, count=%u\n",
   1607 			sc, isoc, count);
   1608 
   1609 	sc->sc_stats.byte_rx += count;
   1610 
   1611 	/*
   1612 	 * Extract SCO packets from ISOC frames. The way we have it,
   1613 	 * no SCO packet can be bigger than MHLEN. This is unlikely
   1614 	 * to actually happen, but if we ran out of mbufs and lost
   1615 	 * sync then we may get spurious data that makes it seem that
   1616 	 * way, so we discard data that wont fit. This doesnt really
   1617 	 * help with the lost sync situation alas.
   1618 	 */
   1619 
   1620 	m = sc->sc_scord_mbuf;
   1621 	if (m != NULL) {
   1622 		sc->sc_scord_mbuf = NULL;
   1623 		ptr = mtod(m, uint8_t *) + m->m_pkthdr.len;
   1624 		got = m->m_pkthdr.len;
   1625 		want = sizeof(hci_scodata_hdr_t);
   1626 		if (got >= want)
   1627 			want += mtod(m, hci_scodata_hdr_t *)->length ;
   1628 	} else {
   1629 		ptr = NULL;
   1630 		got = 0;
   1631 		want = 0;
   1632 	}
   1633 
   1634 	for (i = 0 ; i < UBT_NFRAMES ; i++) {
   1635 		frame = isoc->buf + (i * sc->sc_scord_size);
   1636 
   1637 		while (isoc->size[i] > 0) {
   1638 			size = isoc->size[i];
   1639 
   1640 			if (m == NULL) {
   1641 				MGETHDR(m, M_DONTWAIT, MT_DATA);
   1642 				if (m == NULL) {
   1643 					aprint_error_dev(sc->sc_dev,
   1644 					    "out of memory (xfer halted)\n");
   1645 
   1646 					sc->sc_stats.err_rx++;
   1647 					return;		/* lost sync */
   1648 				}
   1649 
   1650 				ptr = mtod(m, uint8_t *);
   1651 				*ptr++ = HCI_SCO_DATA_PKT;
   1652 				got = 1;
   1653 				want = sizeof(hci_scodata_hdr_t);
   1654 			}
   1655 
   1656 			if (got + size > want)
   1657 				size = want - got;
   1658 
   1659 			memcpy(ptr, frame, size);
   1660 
   1661 			ptr += size;
   1662 			got += size;
   1663 			frame += size;
   1664 
   1665 			if (got == want) {
   1666 				/*
   1667 				 * If we only got a header, add the packet
   1668 				 * length to our want count. Send complete
   1669 				 * packets up to protocol stack.
   1670 				 */
   1671 				if (want == sizeof(hci_scodata_hdr_t)) {
   1672 					uint32_t len =
   1673 					    mtod(m, hci_scodata_hdr_t *)->length;
   1674 					want += len;
   1675 					if (len == 0 || want > MHLEN) {
   1676 						aprint_error_dev(sc->sc_dev,
   1677 						    "packet too large %u "
   1678 						    "(lost sync)\n", len);
   1679 						sc->sc_stats.err_rx++;
   1680 						return;
   1681 					}
   1682 				}
   1683 
   1684 				if (got == want) {
   1685 					m->m_pkthdr.len = m->m_len = got;
   1686 					sc->sc_stats.sco_rx++;
   1687 					if (!hci_input_sco(sc->sc_unit, m))
   1688 						sc->sc_stats.err_rx++;
   1689 
   1690 					m = NULL;
   1691 				}
   1692 			}
   1693 
   1694 			isoc->size[i] -= size;
   1695 		}
   1696 	}
   1697 
   1698 	if (m != NULL) {
   1699 		m->m_pkthdr.len = m->m_len = got;
   1700 		sc->sc_scord_mbuf = m;
   1701 	}
   1702 
   1703 restart: /* and restart */
   1704 	ubt_recv_sco_start1(sc, isoc);
   1705 }
   1706 
   1707 void
   1708 ubt_stats(device_t self, struct bt_stats *dest, int flush)
   1709 {
   1710 	struct ubt_softc *sc = device_private(self);
   1711 	int s;
   1712 
   1713 	s = splusb();
   1714 	memcpy(dest, &sc->sc_stats, sizeof(struct bt_stats));
   1715 
   1716 	if (flush)
   1717 		memset(&sc->sc_stats, 0, sizeof(struct bt_stats));
   1718 
   1719 	splx(s);
   1720 }
   1721