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