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