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