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