xref: /freebsd/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c (revision b25ba58adc04ca475df1e8125d2a16a07d68b49d)
1 /*
2  * ng_ubt.c
3  */
4 
5 /*-
6  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
7  *
8  * Copyright (c) 2001-2009 Maksim Yevmenkin <m_evmenkin@yahoo.com>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Id: ng_ubt.c,v 1.16 2003/10/10 19:15:06 max Exp $
33  * $FreeBSD$
34  */
35 
36 /*
37  * NOTE: ng_ubt2 driver has a split personality. On one side it is
38  * a USB device driver and on the other it is a Netgraph node. This
39  * driver will *NOT* create traditional /dev/ enties, only Netgraph
40  * node.
41  *
42  * NOTE ON LOCKS USED: ng_ubt2 drives uses 2 locks (mutexes)
43  *
44  * 1) sc_if_mtx - lock for device's interface #0 and #1. This lock is used
45  *    by USB for any USB request going over device's interface #0 and #1,
46  *    i.e. interrupt, control, bulk and isoc. transfers.
47  *
48  * 2) sc_ng_mtx - this lock is used to protect shared (between USB, Netgraph
49  *    and Taskqueue) data, such as outgoing mbuf queues, task flags and hook
50  *    pointer. This lock *SHOULD NOT* be grabbed for a long time. In fact,
51  *    think of it as a spin lock.
52  *
53  * NOTE ON LOCKING STRATEGY: ng_ubt2 driver operates in 3 different contexts.
54  *
55  * 1) USB context. This is where all the USB related stuff happens. All
56  *    callbacks run in this context. All callbacks are called (by USB) with
57  *    appropriate interface lock held. It is (generally) allowed to grab
58  *    any additional locks.
59  *
60  * 2) Netgraph context. This is where all the Netgraph related stuff happens.
61  *    Since we mark node as WRITER, the Netgraph node will be "locked" (from
62  *    Netgraph point of view). Any variable that is only modified from the
63  *    Netgraph context does not require any additional locking. It is generally
64  *    *NOT* allowed to grab *ANY* additional locks. Whatever you do, *DO NOT*
65  *    grab any lock in the Netgraph context that could cause de-scheduling of
66  *    the Netgraph thread for significant amount of time. In fact, the only
67  *    lock that is allowed in the Netgraph context is the sc_ng_mtx lock.
68  *    Also make sure that any code that is called from the Netgraph context
69  *    follows the rule above.
70  *
71  * 3) Taskqueue context. This is where ubt_task runs. Since we are generally
72  *    NOT allowed to grab any lock that could cause de-scheduling in the
73  *    Netgraph context, and, USB requires us to grab interface lock before
74  *    doing things with transfers, it is safer to transition from the Netgraph
75  *    context to the Taskqueue context before we can call into USB subsystem.
76  *
77  * So, to put everything together, the rules are as follows.
78  *	It is OK to call from the USB context or the Taskqueue context into
79  * the Netgraph context (i.e. call NG_SEND_xxx functions). In other words
80  * it is allowed to call into the Netgraph context with locks held.
81  *	Is it *NOT* OK to call from the Netgraph context into the USB context,
82  * because USB requires us to grab interface locks, and, it is safer to
83  * avoid it. So, to make things safer we set task flags to indicate which
84  * actions we want to perform and schedule ubt_task which would run in the
85  * Taskqueue context.
86  *	Is is OK to call from the Taskqueue context into the USB context,
87  * and, ubt_task does just that (i.e. grabs appropriate interface locks
88  * before calling into USB).
89  *	Access to the outgoing queues, task flags and hook pointer is
90  * controlled by the sc_ng_mtx lock. It is an unavoidable evil. Again,
91  * sc_ng_mtx should really be a spin lock (and it is very likely to an
92  * equivalent of spin lock due to adaptive nature of FreeBSD mutexes).
93  *	All USB callbacks accept softc pointer as a private data. USB ensures
94  * that this pointer is valid.
95  */
96 
97 #include <sys/stdint.h>
98 #include <sys/stddef.h>
99 #include <sys/param.h>
100 #include <sys/queue.h>
101 #include <sys/types.h>
102 #include <sys/systm.h>
103 #include <sys/kernel.h>
104 #include <sys/bus.h>
105 #include <sys/module.h>
106 #include <sys/lock.h>
107 #include <sys/mutex.h>
108 #include <sys/condvar.h>
109 #include <sys/sysctl.h>
110 #include <sys/sx.h>
111 #include <sys/unistd.h>
112 #include <sys/callout.h>
113 #include <sys/malloc.h>
114 #include <sys/priv.h>
115 
116 #include "usbdevs.h"
117 #include <dev/usb/usb.h>
118 #include <dev/usb/usbdi.h>
119 #include <dev/usb/usbdi_util.h>
120 
121 #define	USB_DEBUG_VAR usb_debug
122 #include <dev/usb/usb_debug.h>
123 #include <dev/usb/usb_busdma.h>
124 
125 #include <sys/mbuf.h>
126 #include <sys/taskqueue.h>
127 
128 #include <netgraph/ng_message.h>
129 #include <netgraph/netgraph.h>
130 #include <netgraph/ng_parse.h>
131 #include <netgraph/bluetooth/include/ng_bluetooth.h>
132 #include <netgraph/bluetooth/include/ng_hci.h>
133 #include <netgraph/bluetooth/include/ng_ubt.h>
134 #include <netgraph/bluetooth/drivers/ubt/ng_ubt_var.h>
135 
136 static int		ubt_modevent(module_t, int, void *);
137 static device_probe_t	ubt_probe;
138 static device_attach_t	ubt_attach;
139 static device_detach_t	ubt_detach;
140 
141 static void		ubt_task_schedule(ubt_softc_p, int);
142 static task_fn_t	ubt_task;
143 
144 #define	ubt_xfer_start(sc, i)	usbd_transfer_start((sc)->sc_xfer[(i)])
145 
146 /* Netgraph methods */
147 static ng_constructor_t	ng_ubt_constructor;
148 static ng_shutdown_t	ng_ubt_shutdown;
149 static ng_newhook_t	ng_ubt_newhook;
150 static ng_connect_t	ng_ubt_connect;
151 static ng_disconnect_t	ng_ubt_disconnect;
152 static ng_rcvmsg_t	ng_ubt_rcvmsg;
153 static ng_rcvdata_t	ng_ubt_rcvdata;
154 
155 /* Queue length */
156 static const struct ng_parse_struct_field	ng_ubt_node_qlen_type_fields[] =
157 {
158 	{ "queue", &ng_parse_int32_type, },
159 	{ "qlen",  &ng_parse_int32_type, },
160 	{ NULL, }
161 };
162 static const struct ng_parse_type		ng_ubt_node_qlen_type =
163 {
164 	&ng_parse_struct_type,
165 	&ng_ubt_node_qlen_type_fields
166 };
167 
168 /* Stat info */
169 static const struct ng_parse_struct_field	ng_ubt_node_stat_type_fields[] =
170 {
171 	{ "pckts_recv", &ng_parse_uint32_type, },
172 	{ "bytes_recv", &ng_parse_uint32_type, },
173 	{ "pckts_sent", &ng_parse_uint32_type, },
174 	{ "bytes_sent", &ng_parse_uint32_type, },
175 	{ "oerrors",    &ng_parse_uint32_type, },
176 	{ "ierrors",    &ng_parse_uint32_type, },
177 	{ NULL, }
178 };
179 static const struct ng_parse_type		ng_ubt_node_stat_type =
180 {
181 	&ng_parse_struct_type,
182 	&ng_ubt_node_stat_type_fields
183 };
184 
185 /* Netgraph node command list */
186 static const struct ng_cmdlist			ng_ubt_cmdlist[] =
187 {
188 	{
189 		NGM_UBT_COOKIE,
190 		NGM_UBT_NODE_SET_DEBUG,
191 		"set_debug",
192 		&ng_parse_uint16_type,
193 		NULL
194 	},
195 	{
196 		NGM_UBT_COOKIE,
197 		NGM_UBT_NODE_GET_DEBUG,
198 		"get_debug",
199 		NULL,
200 		&ng_parse_uint16_type
201 	},
202 	{
203 		NGM_UBT_COOKIE,
204 		NGM_UBT_NODE_SET_QLEN,
205 		"set_qlen",
206 		&ng_ubt_node_qlen_type,
207 		NULL
208 	},
209 	{
210 		NGM_UBT_COOKIE,
211 		NGM_UBT_NODE_GET_QLEN,
212 		"get_qlen",
213 		&ng_ubt_node_qlen_type,
214 		&ng_ubt_node_qlen_type
215 	},
216 	{
217 		NGM_UBT_COOKIE,
218 		NGM_UBT_NODE_GET_STAT,
219 		"get_stat",
220 		NULL,
221 		&ng_ubt_node_stat_type
222 	},
223 	{
224 		NGM_UBT_COOKIE,
225 		NGM_UBT_NODE_RESET_STAT,
226 		"reset_stat",
227 		NULL,
228 		NULL
229 	},
230 	{ 0, }
231 };
232 
233 /* Netgraph node type */
234 static struct ng_type	typestruct =
235 {
236 	.version = 	NG_ABI_VERSION,
237 	.name =		NG_UBT_NODE_TYPE,
238 	.constructor =	ng_ubt_constructor,
239 	.rcvmsg =	ng_ubt_rcvmsg,
240 	.shutdown =	ng_ubt_shutdown,
241 	.newhook =	ng_ubt_newhook,
242 	.connect =	ng_ubt_connect,
243 	.rcvdata =	ng_ubt_rcvdata,
244 	.disconnect =	ng_ubt_disconnect,
245 	.cmdlist =	ng_ubt_cmdlist
246 };
247 
248 /****************************************************************************
249  ****************************************************************************
250  **                              USB specific
251  ****************************************************************************
252  ****************************************************************************/
253 
254 /* USB methods */
255 static usb_callback_t	ubt_probe_intr_callback;
256 static usb_callback_t	ubt_ctrl_write_callback;
257 static usb_callback_t	ubt_intr_read_callback;
258 static usb_callback_t	ubt_bulk_read_callback;
259 static usb_callback_t	ubt_bulk_write_callback;
260 static usb_callback_t	ubt_isoc_read_callback;
261 static usb_callback_t	ubt_isoc_write_callback;
262 
263 static int		ubt_fwd_mbuf_up(ubt_softc_p, struct mbuf **);
264 static int		ubt_isoc_read_one_frame(struct usb_xfer *, int);
265 
266 /*
267  * USB config
268  *
269  * The following desribes usb transfers that could be submitted on USB device.
270  *
271  * Interface 0 on the USB device must present the following endpoints
272  *	1) Interrupt endpoint to receive HCI events
273  *	2) Bulk IN endpoint to receive ACL data
274  *	3) Bulk OUT endpoint to send ACL data
275  *
276  * Interface 1 on the USB device must present the following endpoints
277  *	1) Isochronous IN endpoint to receive SCO data
278  *	2) Isochronous OUT endpoint to send SCO data
279  */
280 
281 static const struct usb_config		ubt_config[UBT_N_TRANSFER] =
282 {
283 	/*
284 	 * Interface #0
285  	 */
286 
287 	/* Outgoing bulk transfer - ACL packets */
288 	[UBT_IF_0_BULK_DT_WR] = {
289 		.type =		UE_BULK,
290 		.endpoint =	UE_ADDR_ANY,
291 		.direction =	UE_DIR_OUT,
292 		.if_index = 	0,
293 		.bufsize =	UBT_BULK_WRITE_BUFFER_SIZE,
294 		.flags =	{ .pipe_bof = 1, .force_short_xfer = 1, },
295 		.callback =	&ubt_bulk_write_callback,
296 	},
297 	/* Incoming bulk transfer - ACL packets */
298 	[UBT_IF_0_BULK_DT_RD] = {
299 		.type =		UE_BULK,
300 		.endpoint =	UE_ADDR_ANY,
301 		.direction =	UE_DIR_IN,
302 		.if_index = 	0,
303 		.bufsize =	UBT_BULK_READ_BUFFER_SIZE,
304 		.flags =	{ .pipe_bof = 1, .short_xfer_ok = 1, },
305 		.callback =	&ubt_bulk_read_callback,
306 	},
307 	/* Incoming interrupt transfer - HCI events */
308 	[UBT_IF_0_INTR_DT_RD] = {
309 		.type =		UE_INTERRUPT,
310 		.endpoint =	UE_ADDR_ANY,
311 		.direction =	UE_DIR_IN,
312 		.if_index = 	0,
313 		.flags =	{ .pipe_bof = 1, .short_xfer_ok = 1, },
314 		.bufsize =	UBT_INTR_BUFFER_SIZE,
315 		.callback =	&ubt_intr_read_callback,
316 	},
317 	/* Outgoing control transfer - HCI commands */
318 	[UBT_IF_0_CTRL_DT_WR] = {
319 		.type =		UE_CONTROL,
320 		.endpoint =	0x00,	/* control pipe */
321 		.direction =	UE_DIR_ANY,
322 		.if_index = 	0,
323 		.bufsize =	UBT_CTRL_BUFFER_SIZE,
324 		.callback =	&ubt_ctrl_write_callback,
325 		.timeout =	5000,	/* 5 seconds */
326 	},
327 
328 	/*
329 	 * Interface #1
330  	 */
331 
332 	/* Incoming isochronous transfer #1 - SCO packets */
333 	[UBT_IF_1_ISOC_DT_RD1] = {
334 		.type =		UE_ISOCHRONOUS,
335 		.endpoint =	UE_ADDR_ANY,
336 		.direction =	UE_DIR_IN,
337 		.if_index = 	1,
338 		.bufsize =	0,	/* use "wMaxPacketSize * frames" */
339 		.frames =	UBT_ISOC_NFRAMES,
340 		.flags =	{ .short_xfer_ok = 1, },
341 		.callback =	&ubt_isoc_read_callback,
342 	},
343 	/* Incoming isochronous transfer #2 - SCO packets */
344 	[UBT_IF_1_ISOC_DT_RD2] = {
345 		.type =		UE_ISOCHRONOUS,
346 		.endpoint =	UE_ADDR_ANY,
347 		.direction =	UE_DIR_IN,
348 		.if_index = 	1,
349 		.bufsize =	0,	/* use "wMaxPacketSize * frames" */
350 		.frames =	UBT_ISOC_NFRAMES,
351 		.flags =	{ .short_xfer_ok = 1, },
352 		.callback =	&ubt_isoc_read_callback,
353 	},
354 	/* Outgoing isochronous transfer #1 - SCO packets */
355 	[UBT_IF_1_ISOC_DT_WR1] = {
356 		.type =		UE_ISOCHRONOUS,
357 		.endpoint =	UE_ADDR_ANY,
358 		.direction =	UE_DIR_OUT,
359 		.if_index = 	1,
360 		.bufsize =	0,	/* use "wMaxPacketSize * frames" */
361 		.frames =	UBT_ISOC_NFRAMES,
362 		.flags =	{ .short_xfer_ok = 1, },
363 		.callback =	&ubt_isoc_write_callback,
364 	},
365 	/* Outgoing isochronous transfer #2 - SCO packets */
366 	[UBT_IF_1_ISOC_DT_WR2] = {
367 		.type =		UE_ISOCHRONOUS,
368 		.endpoint =	UE_ADDR_ANY,
369 		.direction =	UE_DIR_OUT,
370 		.if_index = 	1,
371 		.bufsize =	0,	/* use "wMaxPacketSize * frames" */
372 		.frames =	UBT_ISOC_NFRAMES,
373 		.flags =	{ .short_xfer_ok = 1, },
374 		.callback =	&ubt_isoc_write_callback,
375 	},
376 };
377 
378 /*
379  * If for some reason device should not be attached then put
380  * VendorID/ProductID pair into the list below. The format is
381  * as follows:
382  *
383  *	{ USB_VPI(VENDOR_ID, PRODUCT_ID, 0) },
384  *
385  * where VENDOR_ID and PRODUCT_ID are hex numbers.
386  */
387 
388 static const STRUCT_USB_HOST_ID ubt_ignore_devs[] =
389 {
390 	/* AVM USB Bluetooth-Adapter BlueFritz! v1.0 */
391 	{ USB_VPI(USB_VENDOR_AVM, 0x2200, 0) },
392 
393 	/* Atheros 3011 with sflash firmware */
394 	{ USB_VPI(0x0cf3, 0x3002, 0) },
395 	{ USB_VPI(0x0cf3, 0xe019, 0) },
396 	{ USB_VPI(0x13d3, 0x3304, 0) },
397 	{ USB_VPI(0x0930, 0x0215, 0) },
398 	{ USB_VPI(0x0489, 0xe03d, 0) },
399 	{ USB_VPI(0x0489, 0xe027, 0) },
400 
401 	/* Atheros AR9285 Malbec with sflash firmware */
402 	{ USB_VPI(0x03f0, 0x311d, 0) },
403 
404 	/* Atheros 3012 with sflash firmware */
405 	{ USB_VPI(0x0cf3, 0x3004, 0), USB_DEV_BCD_LTEQ(1) },
406 	{ USB_VPI(0x0cf3, 0x311d, 0), USB_DEV_BCD_LTEQ(1) },
407 	{ USB_VPI(0x13d3, 0x3375, 0), USB_DEV_BCD_LTEQ(1) },
408 	{ USB_VPI(0x04ca, 0x3005, 0), USB_DEV_BCD_LTEQ(1) },
409 	{ USB_VPI(0x04ca, 0x3006, 0), USB_DEV_BCD_LTEQ(1) },
410 	{ USB_VPI(0x04ca, 0x3008, 0), USB_DEV_BCD_LTEQ(1) },
411 	{ USB_VPI(0x13d3, 0x3362, 0), USB_DEV_BCD_LTEQ(1) },
412 	{ USB_VPI(0x0cf3, 0xe004, 0), USB_DEV_BCD_LTEQ(1) },
413 	{ USB_VPI(0x0930, 0x0219, 0), USB_DEV_BCD_LTEQ(1) },
414 	{ USB_VPI(0x0489, 0xe057, 0), USB_DEV_BCD_LTEQ(1) },
415 	{ USB_VPI(0x13d3, 0x3393, 0), USB_DEV_BCD_LTEQ(1) },
416 	{ USB_VPI(0x0489, 0xe04e, 0), USB_DEV_BCD_LTEQ(1) },
417 	{ USB_VPI(0x0489, 0xe056, 0), USB_DEV_BCD_LTEQ(1) },
418 
419 	/* Atheros AR5BBU12 with sflash firmware */
420 	{ USB_VPI(0x0489, 0xe02c, 0), USB_DEV_BCD_LTEQ(1) },
421 
422 	/* Atheros AR5BBU12 with sflash firmware */
423 	{ USB_VPI(0x0489, 0xe03c, 0), USB_DEV_BCD_LTEQ(1) },
424 	{ USB_VPI(0x0489, 0xe036, 0), USB_DEV_BCD_LTEQ(1) },
425 
426 	/* Intel Wireless controllers are handled in ng_ubt_intel.c */
427 	{ USB_VPI(USB_VENDOR_INTEL2, 0x07dc, 0) },
428 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0a2a, 0) },
429 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0aa7, 0) },
430 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0a2b, 0) },
431 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0aaa, 0) },
432 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0025, 0) },
433 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0026, 0) },
434 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0029, 0) },
435 
436 	/*
437 	 * Some Intel controllers are not yet supported by ng_ubt_intel and
438 	 * should be ignored.
439 	 */
440 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0032, 0) },
441 	{ USB_VPI(USB_VENDOR_INTEL2, 0x0033, 0) },
442 };
443 
444 /* List of supported bluetooth devices */
445 static const STRUCT_USB_HOST_ID ubt_devs[] =
446 {
447 	/* Generic Bluetooth class devices */
448 	{ USB_IFACE_CLASS(UDCLASS_WIRELESS),
449 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
450 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
451 
452 	/* AVM USB Bluetooth-Adapter BlueFritz! v2.0 */
453 	{ USB_VPI(USB_VENDOR_AVM, 0x3800, 0) },
454 
455 	/* Broadcom USB dongles, mostly BCM20702 and BCM20702A0 */
456 	{ USB_VENDOR(USB_VENDOR_BROADCOM),
457 	  USB_IFACE_CLASS(UICLASS_VENDOR),
458 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
459 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
460 
461 	/* Apple-specific (Broadcom) devices */
462 	{ USB_VENDOR(USB_VENDOR_APPLE),
463 	  USB_IFACE_CLASS(UICLASS_VENDOR),
464 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
465 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
466 
467 	/* Foxconn - Hon Hai */
468 	{ USB_VENDOR(USB_VENDOR_FOXCONN),
469 	  USB_IFACE_CLASS(UICLASS_VENDOR),
470 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
471 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
472 
473 	/* MediaTek MT76x0E */
474 	{ USB_VPI(USB_VENDOR_MEDIATEK, 0x763f, 0) },
475 
476 	/* Broadcom SoftSailing reporting vendor specific */
477 	{ USB_VPI(USB_VENDOR_BROADCOM, 0x21e1, 0) },
478 
479 	/* Apple MacBookPro 7,1 */
480 	{ USB_VPI(USB_VENDOR_APPLE, 0x8213, 0) },
481 
482 	/* Apple iMac11,1 */
483 	{ USB_VPI(USB_VENDOR_APPLE, 0x8215, 0) },
484 
485 	/* Apple MacBookPro6,2 */
486 	{ USB_VPI(USB_VENDOR_APPLE, 0x8218, 0) },
487 
488 	/* Apple MacBookAir3,1, MacBookAir3,2 */
489 	{ USB_VPI(USB_VENDOR_APPLE, 0x821b, 0) },
490 
491 	/* Apple MacBookAir4,1 */
492 	{ USB_VPI(USB_VENDOR_APPLE, 0x821f, 0) },
493 
494 	/* MacBookAir6,1 */
495 	{ USB_VPI(USB_VENDOR_APPLE, 0x828f, 0) },
496 
497 	/* Apple MacBookPro8,2 */
498 	{ USB_VPI(USB_VENDOR_APPLE, 0x821a, 0) },
499 
500 	/* Apple MacMini5,1 */
501 	{ USB_VPI(USB_VENDOR_APPLE, 0x8281, 0) },
502 
503 	/* Bluetooth Ultraport Module from IBM */
504 	{ USB_VPI(USB_VENDOR_TDK, 0x030a, 0) },
505 
506 	/* ALPS Modules with non-standard ID */
507 	{ USB_VPI(USB_VENDOR_ALPS, 0x3001, 0) },
508 	{ USB_VPI(USB_VENDOR_ALPS, 0x3002, 0) },
509 
510 	{ USB_VPI(USB_VENDOR_ERICSSON2, 0x1002, 0) },
511 
512 	/* Canyon CN-BTU1 with HID interfaces */
513 	{ USB_VPI(USB_VENDOR_CANYON, 0x0000, 0) },
514 
515 	/* Broadcom BCM20702A0 */
516 	{ USB_VPI(USB_VENDOR_ASUS, 0x17b5, 0) },
517 	{ USB_VPI(USB_VENDOR_ASUS, 0x17cb, 0) },
518 	{ USB_VPI(USB_VENDOR_LITEON, 0x2003, 0) },
519 	{ USB_VPI(USB_VENDOR_FOXCONN, 0xe042, 0) },
520 	{ USB_VPI(USB_VENDOR_DELL, 0x8197, 0) },
521 	{ USB_VPI(USB_VENDOR_BELKIN, 0x065a, 0) },
522 };
523 
524 /*
525  * Does a synchronous (waits for completion event) execution of HCI command.
526  * Size of both command and response buffers are passed in length field of
527  * corresponding structures in "Parameter Total Length" format i.e.
528  * not including HCI packet headers.
529  *
530  * Must not be used after USB transfers have been configured in attach routine.
531  */
532 
533 usb_error_t
534 ubt_do_hci_request(struct usb_device *udev, struct ubt_hci_cmd *cmd,
535     void *evt, usb_timeout_t timeout)
536 {
537 	static const struct usb_config ubt_probe_config = {
538 		.type = UE_INTERRUPT,
539 		.endpoint = UE_ADDR_ANY,
540 		.direction = UE_DIR_IN,
541 		.flags = { .pipe_bof = 1, .short_xfer_ok = 1 },
542 		.bufsize = UBT_INTR_BUFFER_SIZE,
543 		.callback = &ubt_probe_intr_callback,
544 	};
545 	struct usb_device_request req;
546 	struct usb_xfer *xfer[1];
547 	struct mtx mtx;
548 	usb_error_t error = USB_ERR_NORMAL_COMPLETION;
549 	uint8_t iface_index = 0;
550 
551 	/* Initialize a USB control request and then do it */
552 	bzero(&req, sizeof(req));
553 	req.bmRequestType = UBT_HCI_REQUEST;
554 	req.wIndex[0] = iface_index;
555 	USETW(req.wLength, UBT_HCI_CMD_SIZE(cmd));
556 
557 	error = usbd_do_request(udev, NULL, &req, cmd);
558 	if (error != USB_ERR_NORMAL_COMPLETION) {
559 		printf("ng_ubt: usbd_do_request error=%s\n",
560 			usbd_errstr(error));
561 		return (error);
562 	}
563 
564 	if (evt == NULL)
565 		return (USB_ERR_NORMAL_COMPLETION);
566 
567 	/* Initialize INTR endpoint xfer and wait for response */
568 	mtx_init(&mtx, "ubt pb", NULL, MTX_DEF | MTX_NEW);
569 
570 	error = usbd_transfer_setup(udev, &iface_index, xfer,
571 	    &ubt_probe_config, 1, evt, &mtx);
572 	if (error == USB_ERR_NORMAL_COMPLETION) {
573 		mtx_lock(&mtx);
574 		usbd_transfer_start(*xfer);
575 
576 		if (msleep_sbt(evt, &mtx, 0, "ubt pb", SBT_1MS * timeout,
577 				0, C_HARDCLOCK) == EWOULDBLOCK) {
578 			printf("ng_ubt: HCI command 0x%04x timed out\n",
579 				le16toh(cmd->opcode));
580 			error = USB_ERR_TIMEOUT;
581 		}
582 
583 		usbd_transfer_stop(*xfer);
584 		mtx_unlock(&mtx);
585 
586 		usbd_transfer_unsetup(xfer, 1);
587 	} else
588 		printf("ng_ubt: usbd_transfer_setup error=%s\n",
589 			usbd_errstr(error));
590 
591 	mtx_destroy(&mtx);
592 
593 	return (error);
594 }
595 
596 /*
597  * Probe for a USB Bluetooth device.
598  * USB context.
599  */
600 
601 static int
602 ubt_probe(device_t dev)
603 {
604 	struct usb_attach_arg	*uaa = device_get_ivars(dev);
605 	int error;
606 
607 	if (uaa->usb_mode != USB_MODE_HOST)
608 		return (ENXIO);
609 
610 	if (uaa->info.bIfaceIndex != 0)
611 		return (ENXIO);
612 
613 	if (usbd_lookup_id_by_uaa(ubt_ignore_devs,
614 			sizeof(ubt_ignore_devs), uaa) == 0)
615 		return (ENXIO);
616 
617 	error = usbd_lookup_id_by_uaa(ubt_devs, sizeof(ubt_devs), uaa);
618 	if (error == 0)
619 		return (BUS_PROBE_GENERIC);
620 	return (error);
621 } /* ubt_probe */
622 
623 /*
624  * Attach the device.
625  * USB context.
626  */
627 
628 static int
629 ubt_attach(device_t dev)
630 {
631 	struct usb_attach_arg		*uaa = device_get_ivars(dev);
632 	struct ubt_softc		*sc = device_get_softc(dev);
633 	struct usb_endpoint_descriptor	*ed;
634 	struct usb_interface_descriptor *id;
635 	struct usb_interface		*iface;
636 	uint32_t			wMaxPacketSize;
637 	uint8_t				alt_index, i, j;
638 	uint8_t				iface_index[2] = { 0, 1 };
639 
640 	device_set_usb_desc(dev);
641 
642 	sc->sc_dev = dev;
643 	sc->sc_debug = NG_UBT_WARN_LEVEL;
644 
645 	/*
646 	 * Create Netgraph node
647 	 */
648 
649 	if (ng_make_node_common(&typestruct, &sc->sc_node) != 0) {
650 		UBT_ALERT(sc, "could not create Netgraph node\n");
651 		return (ENXIO);
652 	}
653 
654 	/* Name Netgraph node */
655 	if (ng_name_node(sc->sc_node, device_get_nameunit(dev)) != 0) {
656 		UBT_ALERT(sc, "could not name Netgraph node\n");
657 		NG_NODE_UNREF(sc->sc_node);
658 		return (ENXIO);
659 	}
660 	NG_NODE_SET_PRIVATE(sc->sc_node, sc);
661 	NG_NODE_FORCE_WRITER(sc->sc_node);
662 
663 	/*
664 	 * Initialize device softc structure
665 	 */
666 
667 	/* initialize locks */
668 	mtx_init(&sc->sc_ng_mtx, "ubt ng", NULL, MTX_DEF);
669 	mtx_init(&sc->sc_if_mtx, "ubt if", NULL, MTX_DEF | MTX_RECURSE);
670 
671 	/* initialize packet queues */
672 	NG_BT_MBUFQ_INIT(&sc->sc_cmdq, UBT_DEFAULT_QLEN);
673 	NG_BT_MBUFQ_INIT(&sc->sc_aclq, UBT_DEFAULT_QLEN);
674 	NG_BT_MBUFQ_INIT(&sc->sc_scoq, UBT_DEFAULT_QLEN);
675 
676 	/* initialize glue task */
677 	TASK_INIT(&sc->sc_task, 0, ubt_task, sc);
678 
679 	/*
680 	 * Configure Bluetooth USB device. Discover all required USB
681 	 * interfaces and endpoints.
682 	 *
683 	 * USB device must present two interfaces:
684 	 * 1) Interface 0 that has 3 endpoints
685 	 *	1) Interrupt endpoint to receive HCI events
686 	 *	2) Bulk IN endpoint to receive ACL data
687 	 *	3) Bulk OUT endpoint to send ACL data
688 	 *
689 	 * 2) Interface 1 then has 2 endpoints
690 	 *	1) Isochronous IN endpoint to receive SCO data
691  	 *	2) Isochronous OUT endpoint to send SCO data
692 	 *
693 	 * Interface 1 (with isochronous endpoints) has several alternate
694 	 * configurations with different packet size.
695 	 */
696 
697 	/*
698 	 * For interface #1 search alternate settings, and find
699 	 * the descriptor with the largest wMaxPacketSize
700 	 */
701 
702 	wMaxPacketSize = 0;
703 	alt_index = 0;
704 	i = 0;
705 	j = 0;
706 	ed = NULL;
707 
708 	/*
709 	 * Search through all the descriptors looking for the largest
710 	 * packet size:
711 	 */
712 	while ((ed = (struct usb_endpoint_descriptor *)usb_desc_foreach(
713 	    usbd_get_config_descriptor(uaa->device),
714 	    (struct usb_descriptor *)ed))) {
715 		if ((ed->bDescriptorType == UDESC_INTERFACE) &&
716 		    (ed->bLength >= sizeof(*id))) {
717 			id = (struct usb_interface_descriptor *)ed;
718 			i = id->bInterfaceNumber;
719 			j = id->bAlternateSetting;
720 		}
721 
722 		if ((ed->bDescriptorType == UDESC_ENDPOINT) &&
723 		    (ed->bLength >= sizeof(*ed)) &&
724 		    (i == 1)) {
725 			uint32_t temp;
726 
727 			temp = usbd_get_max_frame_length(
728 			    ed, NULL, usbd_get_speed(uaa->device));
729 			if (temp > wMaxPacketSize) {
730 				wMaxPacketSize = temp;
731 				alt_index = j;
732 			}
733 		}
734 	}
735 
736 	/* Set alt configuration on interface #1 only if we found it */
737 	if (wMaxPacketSize > 0 &&
738 	    usbd_set_alt_interface_index(uaa->device, 1, alt_index)) {
739 		UBT_ALERT(sc, "could not set alternate setting %d " \
740 			"for interface 1!\n", alt_index);
741 		goto detach;
742 	}
743 
744 	/* Setup transfers for both interfaces */
745 	if (usbd_transfer_setup(uaa->device, iface_index, sc->sc_xfer,
746 			ubt_config, UBT_N_TRANSFER, sc, &sc->sc_if_mtx)) {
747 		UBT_ALERT(sc, "could not allocate transfers\n");
748 		goto detach;
749 	}
750 
751 	/* Claim all interfaces belonging to the Bluetooth part */
752 	for (i = 1;; i++) {
753 		iface = usbd_get_iface(uaa->device, i);
754 		if (iface == NULL)
755 			break;
756 		id = usbd_get_interface_descriptor(iface);
757 
758 		if ((id != NULL) &&
759 		    (id->bInterfaceClass == UICLASS_WIRELESS) &&
760 		    (id->bInterfaceSubClass == UISUBCLASS_RF) &&
761 		    (id->bInterfaceProtocol == UIPROTO_BLUETOOTH)) {
762 			usbd_set_parent_iface(uaa->device, i,
763 			    uaa->info.bIfaceIndex);
764 		}
765 	}
766 	return (0); /* success */
767 
768 detach:
769 	ubt_detach(dev);
770 
771 	return (ENXIO);
772 } /* ubt_attach */
773 
774 /*
775  * Detach the device.
776  * USB context.
777  */
778 
779 int
780 ubt_detach(device_t dev)
781 {
782 	struct ubt_softc	*sc = device_get_softc(dev);
783 	node_p			node = sc->sc_node;
784 
785 	/* Destroy Netgraph node */
786 	if (node != NULL) {
787 		sc->sc_node = NULL;
788 		NG_NODE_REALLY_DIE(node);
789 		ng_rmnode_self(node);
790 	}
791 
792 	/* Make sure ubt_task in gone */
793 	taskqueue_drain(taskqueue_swi, &sc->sc_task);
794 
795 	/* Free USB transfers, if any */
796 	usbd_transfer_unsetup(sc->sc_xfer, UBT_N_TRANSFER);
797 
798 	/* Destroy queues */
799 	UBT_NG_LOCK(sc);
800 	NG_BT_MBUFQ_DESTROY(&sc->sc_cmdq);
801 	NG_BT_MBUFQ_DESTROY(&sc->sc_aclq);
802 	NG_BT_MBUFQ_DESTROY(&sc->sc_scoq);
803 	UBT_NG_UNLOCK(sc);
804 
805 	mtx_destroy(&sc->sc_if_mtx);
806 	mtx_destroy(&sc->sc_ng_mtx);
807 
808 	return (0);
809 } /* ubt_detach */
810 
811 /*
812  * Called when incoming interrupt transfer (HCI event) has completed, i.e.
813  * HCI event was received from the device during device probe stage.
814  * USB context.
815  */
816 
817 static void
818 ubt_probe_intr_callback(struct usb_xfer *xfer, usb_error_t error)
819 {
820 	struct ubt_hci_event	*evt = usbd_xfer_softc(xfer);
821 	struct usb_page_cache	*pc;
822 	int			actlen;
823 
824 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
825 
826 	switch (USB_GET_STATE(xfer)) {
827 	case USB_ST_TRANSFERRED:
828 		if (actlen > UBT_HCI_EVENT_SIZE(evt))
829 			actlen = UBT_HCI_EVENT_SIZE(evt);
830 		pc = usbd_xfer_get_frame(xfer, 0);
831 		usbd_copy_out(pc, 0, evt, actlen);
832 		/* OneShot mode */
833 		wakeup(evt);
834 		break;
835 
836         case USB_ST_SETUP:
837 submit_next:
838 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
839 		usbd_transfer_submit(xfer);
840 		break;
841 
842 	default:
843 		if (error != USB_ERR_CANCELLED) {
844 			printf("ng_ubt: interrupt transfer failed: %s\n",
845 				usbd_errstr(error));
846 			/* Try clear stall first */
847 			usbd_xfer_set_stall(xfer);
848 			goto submit_next;
849 		}
850 		break;
851 	}
852 } /* ubt_probe_intr_callback */
853 
854 /*
855  * Called when outgoing control request (HCI command) has completed, i.e.
856  * HCI command was sent to the device.
857  * USB context.
858  */
859 
860 static void
861 ubt_ctrl_write_callback(struct usb_xfer *xfer, usb_error_t error)
862 {
863 	struct ubt_softc		*sc = usbd_xfer_softc(xfer);
864 	struct usb_device_request	req;
865 	struct mbuf			*m;
866 	struct usb_page_cache		*pc;
867 	int				actlen;
868 
869 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
870 
871 	switch (USB_GET_STATE(xfer)) {
872 	case USB_ST_TRANSFERRED:
873 		UBT_INFO(sc, "sent %d bytes to control pipe\n", actlen);
874 		UBT_STAT_BYTES_SENT(sc, actlen);
875 		UBT_STAT_PCKTS_SENT(sc);
876 		/* FALLTHROUGH */
877 
878 	case USB_ST_SETUP:
879 send_next:
880 		/* Get next command mbuf, if any */
881 		UBT_NG_LOCK(sc);
882 		NG_BT_MBUFQ_DEQUEUE(&sc->sc_cmdq, m);
883 		UBT_NG_UNLOCK(sc);
884 
885 		if (m == NULL) {
886 			UBT_INFO(sc, "HCI command queue is empty\n");
887 			break;	/* transfer complete */
888 		}
889 
890 		/* Initialize a USB control request and then schedule it */
891 		bzero(&req, sizeof(req));
892 		req.bmRequestType = UBT_HCI_REQUEST;
893 		USETW(req.wLength, m->m_pkthdr.len);
894 
895 		UBT_INFO(sc, "Sending control request, " \
896 			"bmRequestType=0x%02x, wLength=%d\n",
897 			req.bmRequestType, UGETW(req.wLength));
898 
899 		pc = usbd_xfer_get_frame(xfer, 0);
900 		usbd_copy_in(pc, 0, &req, sizeof(req));
901 		pc = usbd_xfer_get_frame(xfer, 1);
902 		usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len);
903 
904 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
905 		usbd_xfer_set_frame_len(xfer, 1, m->m_pkthdr.len);
906 		usbd_xfer_set_frames(xfer, 2);
907 
908 		NG_FREE_M(m);
909 
910 		usbd_transfer_submit(xfer);
911 		break;
912 
913 	default: /* Error */
914 		if (error != USB_ERR_CANCELLED) {
915 			UBT_WARN(sc, "control transfer failed: %s\n",
916 				usbd_errstr(error));
917 
918 			UBT_STAT_OERROR(sc);
919 			goto send_next;
920 		}
921 
922 		/* transfer cancelled */
923 		break;
924 	}
925 } /* ubt_ctrl_write_callback */
926 
927 /*
928  * Called when incoming interrupt transfer (HCI event) has completed, i.e.
929  * HCI event was received from the device.
930  * USB context.
931  */
932 
933 static void
934 ubt_intr_read_callback(struct usb_xfer *xfer, usb_error_t error)
935 {
936 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
937 	struct mbuf		*m;
938 	ng_hci_event_pkt_t	*hdr;
939 	struct usb_page_cache	*pc;
940 	int			actlen;
941 
942 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
943 
944 	m = NULL;
945 
946 	switch (USB_GET_STATE(xfer)) {
947 	case USB_ST_TRANSFERRED:
948 		/* Allocate a new mbuf */
949 		MGETHDR(m, M_NOWAIT, MT_DATA);
950 		if (m == NULL) {
951 			UBT_STAT_IERROR(sc);
952 			goto submit_next;
953 		}
954 
955 		if (!(MCLGET(m, M_NOWAIT))) {
956 			UBT_STAT_IERROR(sc);
957 			goto submit_next;
958 		}
959 
960 		/* Add HCI packet type */
961 		*mtod(m, uint8_t *)= NG_HCI_EVENT_PKT;
962 		m->m_pkthdr.len = m->m_len = 1;
963 
964 		if (actlen > MCLBYTES - 1)
965 			actlen = MCLBYTES - 1;
966 
967 		pc = usbd_xfer_get_frame(xfer, 0);
968 		usbd_copy_out(pc, 0, mtod(m, uint8_t *) + 1, actlen);
969 		m->m_pkthdr.len += actlen;
970 		m->m_len += actlen;
971 
972 		UBT_INFO(sc, "got %d bytes from interrupt pipe\n",
973 			actlen);
974 
975 		/* Validate packet and send it up the stack */
976 		if (m->m_pkthdr.len < (int)sizeof(*hdr)) {
977 			UBT_INFO(sc, "HCI event packet is too short\n");
978 
979 			UBT_STAT_IERROR(sc);
980 			goto submit_next;
981 		}
982 
983 		hdr = mtod(m, ng_hci_event_pkt_t *);
984 		if (hdr->length != (m->m_pkthdr.len - sizeof(*hdr))) {
985 			UBT_ERR(sc, "Invalid HCI event packet size, " \
986 				"length=%d, pktlen=%d\n",
987 				hdr->length, m->m_pkthdr.len);
988 
989 			UBT_STAT_IERROR(sc);
990 			goto submit_next;
991 		}
992 
993 		UBT_INFO(sc, "got complete HCI event frame, pktlen=%d, " \
994 			"length=%d\n", m->m_pkthdr.len, hdr->length);
995 
996 		UBT_STAT_PCKTS_RECV(sc);
997 		UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
998 
999 		ubt_fwd_mbuf_up(sc, &m);
1000 		/* m == NULL at this point */
1001 		/* FALLTHROUGH */
1002 
1003 	case USB_ST_SETUP:
1004 submit_next:
1005 		NG_FREE_M(m); /* checks for m != NULL */
1006 
1007 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1008 		usbd_transfer_submit(xfer);
1009 		break;
1010 
1011 	default: /* Error */
1012 		if (error != USB_ERR_CANCELLED) {
1013 			UBT_WARN(sc, "interrupt transfer failed: %s\n",
1014 				usbd_errstr(error));
1015 
1016 			/* Try to clear stall first */
1017 			usbd_xfer_set_stall(xfer);
1018 			goto submit_next;
1019 		}
1020 			/* transfer cancelled */
1021 		break;
1022 	}
1023 } /* ubt_intr_read_callback */
1024 
1025 /*
1026  * Called when incoming bulk transfer (ACL packet) has completed, i.e.
1027  * ACL packet was received from the device.
1028  * USB context.
1029  */
1030 
1031 static void
1032 ubt_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1033 {
1034 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1035 	struct mbuf		*m;
1036 	ng_hci_acldata_pkt_t	*hdr;
1037 	struct usb_page_cache	*pc;
1038 	int len;
1039 	int actlen;
1040 
1041 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1042 
1043 	m = NULL;
1044 
1045 	switch (USB_GET_STATE(xfer)) {
1046 	case USB_ST_TRANSFERRED:
1047 		/* Allocate new mbuf */
1048 		MGETHDR(m, M_NOWAIT, MT_DATA);
1049 		if (m == NULL) {
1050 			UBT_STAT_IERROR(sc);
1051 			goto submit_next;
1052 		}
1053 
1054 		if (!(MCLGET(m, M_NOWAIT))) {
1055 			UBT_STAT_IERROR(sc);
1056 			goto submit_next;
1057 		}
1058 
1059 		/* Add HCI packet type */
1060 		*mtod(m, uint8_t *)= NG_HCI_ACL_DATA_PKT;
1061 		m->m_pkthdr.len = m->m_len = 1;
1062 
1063 		if (actlen > MCLBYTES - 1)
1064 			actlen = MCLBYTES - 1;
1065 
1066 		pc = usbd_xfer_get_frame(xfer, 0);
1067 		usbd_copy_out(pc, 0, mtod(m, uint8_t *) + 1, actlen);
1068 		m->m_pkthdr.len += actlen;
1069 		m->m_len += actlen;
1070 
1071 		UBT_INFO(sc, "got %d bytes from bulk-in pipe\n",
1072 			actlen);
1073 
1074 		/* Validate packet and send it up the stack */
1075 		if (m->m_pkthdr.len < (int)sizeof(*hdr)) {
1076 			UBT_INFO(sc, "HCI ACL packet is too short\n");
1077 
1078 			UBT_STAT_IERROR(sc);
1079 			goto submit_next;
1080 		}
1081 
1082 		hdr = mtod(m, ng_hci_acldata_pkt_t *);
1083 		len = le16toh(hdr->length);
1084 		if (len != (int)(m->m_pkthdr.len - sizeof(*hdr))) {
1085 			UBT_ERR(sc, "Invalid ACL packet size, length=%d, " \
1086 				"pktlen=%d\n", len, m->m_pkthdr.len);
1087 
1088 			UBT_STAT_IERROR(sc);
1089 			goto submit_next;
1090 		}
1091 
1092 		UBT_INFO(sc, "got complete ACL data packet, pktlen=%d, " \
1093 			"length=%d\n", m->m_pkthdr.len, len);
1094 
1095 		UBT_STAT_PCKTS_RECV(sc);
1096 		UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
1097 
1098 		ubt_fwd_mbuf_up(sc, &m);
1099 		/* m == NULL at this point */
1100 		/* FALLTHOUGH */
1101 
1102 	case USB_ST_SETUP:
1103 submit_next:
1104 		NG_FREE_M(m); /* checks for m != NULL */
1105 
1106 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1107 		usbd_transfer_submit(xfer);
1108 		break;
1109 
1110 	default: /* Error */
1111 		if (error != USB_ERR_CANCELLED) {
1112 			UBT_WARN(sc, "bulk-in transfer failed: %s\n",
1113 				usbd_errstr(error));
1114 
1115 			/* Try to clear stall first */
1116 			usbd_xfer_set_stall(xfer);
1117 			goto submit_next;
1118 		}
1119 			/* transfer cancelled */
1120 		break;
1121 	}
1122 } /* ubt_bulk_read_callback */
1123 
1124 /*
1125  * Called when outgoing bulk transfer (ACL packet) has completed, i.e.
1126  * ACL packet was sent to the device.
1127  * USB context.
1128  */
1129 
1130 static void
1131 ubt_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1132 {
1133 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1134 	struct mbuf		*m;
1135 	struct usb_page_cache	*pc;
1136 	int			actlen;
1137 
1138 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1139 
1140 	switch (USB_GET_STATE(xfer)) {
1141 	case USB_ST_TRANSFERRED:
1142 		UBT_INFO(sc, "sent %d bytes to bulk-out pipe\n", actlen);
1143 		UBT_STAT_BYTES_SENT(sc, actlen);
1144 		UBT_STAT_PCKTS_SENT(sc);
1145 		/* FALLTHROUGH */
1146 
1147 	case USB_ST_SETUP:
1148 send_next:
1149 		/* Get next mbuf, if any */
1150 		UBT_NG_LOCK(sc);
1151 		NG_BT_MBUFQ_DEQUEUE(&sc->sc_aclq, m);
1152 		UBT_NG_UNLOCK(sc);
1153 
1154 		if (m == NULL) {
1155 			UBT_INFO(sc, "ACL data queue is empty\n");
1156 			break; /* transfer completed */
1157 		}
1158 
1159 		/*
1160 		 * Copy ACL data frame back to a linear USB transfer buffer
1161 		 * and schedule transfer
1162 		 */
1163 
1164 		pc = usbd_xfer_get_frame(xfer, 0);
1165 		usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len);
1166 		usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len);
1167 
1168 		UBT_INFO(sc, "bulk-out transfer has been started, len=%d\n",
1169 			m->m_pkthdr.len);
1170 
1171 		NG_FREE_M(m);
1172 
1173 		usbd_transfer_submit(xfer);
1174 		break;
1175 
1176 	default: /* Error */
1177 		if (error != USB_ERR_CANCELLED) {
1178 			UBT_WARN(sc, "bulk-out transfer failed: %s\n",
1179 				usbd_errstr(error));
1180 
1181 			UBT_STAT_OERROR(sc);
1182 
1183 			/* try to clear stall first */
1184 			usbd_xfer_set_stall(xfer);
1185 			goto send_next;
1186 		}
1187 			/* transfer cancelled */
1188 		break;
1189 	}
1190 } /* ubt_bulk_write_callback */
1191 
1192 /*
1193  * Called when incoming isoc transfer (SCO packet) has completed, i.e.
1194  * SCO packet was received from the device.
1195  * USB context.
1196  */
1197 
1198 static void
1199 ubt_isoc_read_callback(struct usb_xfer *xfer, usb_error_t error)
1200 {
1201 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1202 	int			n;
1203 	int actlen, nframes;
1204 
1205 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1206 
1207 	switch (USB_GET_STATE(xfer)) {
1208 	case USB_ST_TRANSFERRED:
1209 		for (n = 0; n < nframes; n ++)
1210 			if (ubt_isoc_read_one_frame(xfer, n) < 0)
1211 				break;
1212 		/* FALLTHROUGH */
1213 
1214 	case USB_ST_SETUP:
1215 read_next:
1216 		for (n = 0; n < nframes; n ++)
1217 			usbd_xfer_set_frame_len(xfer, n,
1218 			    usbd_xfer_max_framelen(xfer));
1219 
1220 		usbd_transfer_submit(xfer);
1221 		break;
1222 
1223 	default: /* Error */
1224                 if (error != USB_ERR_CANCELLED) {
1225                         UBT_STAT_IERROR(sc);
1226                         goto read_next;
1227                 }
1228 
1229 		/* transfer cancelled */
1230 		break;
1231 	}
1232 } /* ubt_isoc_read_callback */
1233 
1234 /*
1235  * Helper function. Called from ubt_isoc_read_callback() to read
1236  * SCO data from one frame.
1237  * USB context.
1238  */
1239 
1240 static int
1241 ubt_isoc_read_one_frame(struct usb_xfer *xfer, int frame_no)
1242 {
1243 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1244 	struct usb_page_cache	*pc;
1245 	struct mbuf		*m;
1246 	int			len, want, got, total;
1247 
1248 	/* Get existing SCO reassembly buffer */
1249 	pc = usbd_xfer_get_frame(xfer, 0);
1250 	m = sc->sc_isoc_in_buffer;
1251 	total = usbd_xfer_frame_len(xfer, frame_no);
1252 
1253 	/* While we have data in the frame */
1254 	while (total > 0) {
1255 		if (m == NULL) {
1256 			/* Start new reassembly buffer */
1257 			MGETHDR(m, M_NOWAIT, MT_DATA);
1258 			if (m == NULL) {
1259 				UBT_STAT_IERROR(sc);
1260 				return (-1);	/* XXX out of sync! */
1261 			}
1262 
1263 			if (!(MCLGET(m, M_NOWAIT))) {
1264 				UBT_STAT_IERROR(sc);
1265 				NG_FREE_M(m);
1266 				return (-1);	/* XXX out of sync! */
1267 			}
1268 
1269 			/* Expect SCO header */
1270 			*mtod(m, uint8_t *) = NG_HCI_SCO_DATA_PKT;
1271 			m->m_pkthdr.len = m->m_len = got = 1;
1272 			want = sizeof(ng_hci_scodata_pkt_t);
1273 		} else {
1274 			/*
1275 			 * Check if we have SCO header and if so
1276 			 * adjust amount of data we want
1277 			 */
1278 			got = m->m_pkthdr.len;
1279 			want = sizeof(ng_hci_scodata_pkt_t);
1280 
1281 			if (got >= want)
1282 				want += mtod(m, ng_hci_scodata_pkt_t *)->length;
1283 		}
1284 
1285 		/* Append frame data to the SCO reassembly buffer */
1286 		len = total;
1287 		if (got + len > want)
1288 			len = want - got;
1289 
1290 		usbd_copy_out(pc, frame_no * usbd_xfer_max_framelen(xfer),
1291 			mtod(m, uint8_t *) + m->m_pkthdr.len, len);
1292 
1293 		m->m_pkthdr.len += len;
1294 		m->m_len += len;
1295 		total -= len;
1296 
1297 		/* Check if we got everything we wanted, if not - continue */
1298 		if (got != want)
1299 			continue;
1300 
1301 		/* If we got here then we got complete SCO frame */
1302 		UBT_INFO(sc, "got complete SCO data frame, pktlen=%d, " \
1303 			"length=%d\n", m->m_pkthdr.len,
1304 			mtod(m, ng_hci_scodata_pkt_t *)->length);
1305 
1306 		UBT_STAT_PCKTS_RECV(sc);
1307 		UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
1308 
1309 		ubt_fwd_mbuf_up(sc, &m);
1310 		/* m == NULL at this point */
1311 	}
1312 
1313 	/* Put SCO reassembly buffer back */
1314 	sc->sc_isoc_in_buffer = m;
1315 
1316 	return (0);
1317 } /* ubt_isoc_read_one_frame */
1318 
1319 /*
1320  * Called when outgoing isoc transfer (SCO packet) has completed, i.e.
1321  * SCO packet was sent to the device.
1322  * USB context.
1323  */
1324 
1325 static void
1326 ubt_isoc_write_callback(struct usb_xfer *xfer, usb_error_t error)
1327 {
1328 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1329 	struct usb_page_cache	*pc;
1330 	struct mbuf		*m;
1331 	int			n, space, offset;
1332 	int			actlen, nframes;
1333 
1334 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1335 	pc = usbd_xfer_get_frame(xfer, 0);
1336 
1337 	switch (USB_GET_STATE(xfer)) {
1338 	case USB_ST_TRANSFERRED:
1339 		UBT_INFO(sc, "sent %d bytes to isoc-out pipe\n", actlen);
1340 		UBT_STAT_BYTES_SENT(sc, actlen);
1341 		UBT_STAT_PCKTS_SENT(sc);
1342 		/* FALLTHROUGH */
1343 
1344 	case USB_ST_SETUP:
1345 send_next:
1346 		offset = 0;
1347 		space = usbd_xfer_max_framelen(xfer) * nframes;
1348 		m = NULL;
1349 
1350 		while (space > 0) {
1351 			if (m == NULL) {
1352 				UBT_NG_LOCK(sc);
1353 				NG_BT_MBUFQ_DEQUEUE(&sc->sc_scoq, m);
1354 				UBT_NG_UNLOCK(sc);
1355 
1356 				if (m == NULL)
1357 					break;
1358 			}
1359 
1360 			n = min(space, m->m_pkthdr.len);
1361 			if (n > 0) {
1362 				usbd_m_copy_in(pc, offset, m,0, n);
1363 				m_adj(m, n);
1364 
1365 				offset += n;
1366 				space -= n;
1367 			}
1368 
1369 			if (m->m_pkthdr.len == 0)
1370 				NG_FREE_M(m); /* sets m = NULL */
1371 		}
1372 
1373 		/* Put whatever is left from mbuf back on queue */
1374 		if (m != NULL) {
1375 			UBT_NG_LOCK(sc);
1376 			NG_BT_MBUFQ_PREPEND(&sc->sc_scoq, m);
1377 			UBT_NG_UNLOCK(sc);
1378 		}
1379 
1380 		/*
1381 		 * Calculate sizes for isoc frames.
1382 		 * Note that offset could be 0 at this point (i.e. we have
1383 		 * nothing to send). That is fine, as we have isoc. transfers
1384 		 * going in both directions all the time. In this case it
1385 		 * would be just empty isoc. transfer.
1386 		 */
1387 
1388 		for (n = 0; n < nframes; n ++) {
1389 			usbd_xfer_set_frame_len(xfer, n,
1390 			    min(offset, usbd_xfer_max_framelen(xfer)));
1391 			offset -= usbd_xfer_frame_len(xfer, n);
1392 		}
1393 
1394 		usbd_transfer_submit(xfer);
1395 		break;
1396 
1397 	default: /* Error */
1398 		if (error != USB_ERR_CANCELLED) {
1399 			UBT_STAT_OERROR(sc);
1400 			goto send_next;
1401 		}
1402 
1403 		/* transfer cancelled */
1404 		break;
1405 	}
1406 }
1407 
1408 /*
1409  * Utility function to forward provided mbuf upstream (i.e. up the stack).
1410  * Modifies value of the mbuf pointer (sets it to NULL).
1411  * Save to call from any context.
1412  */
1413 
1414 static int
1415 ubt_fwd_mbuf_up(ubt_softc_p sc, struct mbuf **m)
1416 {
1417 	hook_p	hook;
1418 	int	error;
1419 
1420 	/*
1421 	 * Close the race with Netgraph hook newhook/disconnect methods.
1422 	 * Save the hook pointer atomically. Two cases are possible:
1423 	 *
1424 	 * 1) The hook pointer is NULL. It means disconnect method got
1425 	 *    there first. In this case we are done.
1426 	 *
1427 	 * 2) The hook pointer is not NULL. It means that hook pointer
1428 	 *    could be either in valid or invalid (i.e. in the process
1429 	 *    of disconnect) state. In any case grab an extra reference
1430 	 *    to protect the hook pointer.
1431 	 *
1432 	 * It is ok to pass hook in invalid state to NG_SEND_DATA_ONLY() as
1433 	 * it checks for it. Drop extra reference after NG_SEND_DATA_ONLY().
1434 	 */
1435 
1436 	UBT_NG_LOCK(sc);
1437 	if ((hook = sc->sc_hook) != NULL)
1438 		NG_HOOK_REF(hook);
1439 	UBT_NG_UNLOCK(sc);
1440 
1441 	if (hook == NULL) {
1442 		NG_FREE_M(*m);
1443 		return (ENETDOWN);
1444 	}
1445 
1446 	NG_SEND_DATA_ONLY(error, hook, *m);
1447 	NG_HOOK_UNREF(hook);
1448 
1449 	if (error != 0)
1450 		UBT_STAT_IERROR(sc);
1451 
1452 	return (error);
1453 } /* ubt_fwd_mbuf_up */
1454 
1455 /****************************************************************************
1456  ****************************************************************************
1457  **                                 Glue
1458  ****************************************************************************
1459  ****************************************************************************/
1460 
1461 /*
1462  * Schedule glue task. Should be called with sc_ng_mtx held.
1463  * Netgraph context.
1464  */
1465 
1466 static void
1467 ubt_task_schedule(ubt_softc_p sc, int action)
1468 {
1469 	mtx_assert(&sc->sc_ng_mtx, MA_OWNED);
1470 
1471 	/*
1472 	 * Try to handle corner case when "start all" and "stop all"
1473 	 * actions can both be set before task is executed.
1474 	 *
1475 	 * The rules are
1476 	 *
1477 	 * sc_task_flags	action		new sc_task_flags
1478 	 * ------------------------------------------------------
1479 	 * 0			start		start
1480 	 * 0			stop		stop
1481 	 * start		start		start
1482 	 * start		stop		stop
1483 	 * stop			start		stop|start
1484 	 * stop			stop		stop
1485 	 * stop|start		start		stop|start
1486 	 * stop|start		stop		stop
1487 	 */
1488 
1489 	if (action != 0) {
1490 		if ((action & UBT_FLAG_T_STOP_ALL) != 0)
1491 			sc->sc_task_flags &= ~UBT_FLAG_T_START_ALL;
1492 
1493 		sc->sc_task_flags |= action;
1494 	}
1495 
1496 	if (sc->sc_task_flags & UBT_FLAG_T_PENDING)
1497 		return;
1498 
1499 	if (taskqueue_enqueue(taskqueue_swi, &sc->sc_task) == 0) {
1500 		sc->sc_task_flags |= UBT_FLAG_T_PENDING;
1501 		return;
1502 	}
1503 
1504 	/* XXX: i think this should never happen */
1505 } /* ubt_task_schedule */
1506 
1507 /*
1508  * Glue task. Examines sc_task_flags and does things depending on it.
1509  * Taskqueue context.
1510  */
1511 
1512 static void
1513 ubt_task(void *context, int pending)
1514 {
1515 	ubt_softc_p	sc = context;
1516 	int		task_flags, i;
1517 
1518 	UBT_NG_LOCK(sc);
1519 	task_flags = sc->sc_task_flags;
1520 	sc->sc_task_flags = 0;
1521 	UBT_NG_UNLOCK(sc);
1522 
1523 	/*
1524 	 * Stop all USB transfers synchronously.
1525 	 * Stop interface #0 and #1 transfers at the same time and in the
1526 	 * same loop. usbd_transfer_drain() will do appropriate locking.
1527 	 */
1528 
1529 	if (task_flags & UBT_FLAG_T_STOP_ALL)
1530 		for (i = 0; i < UBT_N_TRANSFER; i ++)
1531 			usbd_transfer_drain(sc->sc_xfer[i]);
1532 
1533 	/* Start incoming interrupt and bulk, and all isoc. USB transfers */
1534 	if (task_flags & UBT_FLAG_T_START_ALL) {
1535 		/*
1536 		 * Interface #0
1537 		 */
1538 
1539 		mtx_lock(&sc->sc_if_mtx);
1540 
1541 		ubt_xfer_start(sc, UBT_IF_0_INTR_DT_RD);
1542 		ubt_xfer_start(sc, UBT_IF_0_BULK_DT_RD);
1543 
1544 		/*
1545 		 * Interface #1
1546 		 * Start both read and write isoc. transfers by default.
1547 		 * Get them going all the time even if we have nothing
1548 		 * to send to avoid any delays.
1549 		 */
1550 
1551 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_RD1);
1552 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_RD2);
1553 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_WR1);
1554 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_WR2);
1555 
1556 		mtx_unlock(&sc->sc_if_mtx);
1557 	}
1558 
1559  	/* Start outgoing control transfer */
1560 	if (task_flags & UBT_FLAG_T_START_CTRL) {
1561 		mtx_lock(&sc->sc_if_mtx);
1562 		ubt_xfer_start(sc, UBT_IF_0_CTRL_DT_WR);
1563 		mtx_unlock(&sc->sc_if_mtx);
1564 	}
1565 
1566 	/* Start outgoing bulk transfer */
1567 	if (task_flags & UBT_FLAG_T_START_BULK) {
1568 		mtx_lock(&sc->sc_if_mtx);
1569 		ubt_xfer_start(sc, UBT_IF_0_BULK_DT_WR);
1570 		mtx_unlock(&sc->sc_if_mtx);
1571 	}
1572 } /* ubt_task */
1573 
1574 /****************************************************************************
1575  ****************************************************************************
1576  **                        Netgraph specific
1577  ****************************************************************************
1578  ****************************************************************************/
1579 
1580 /*
1581  * Netgraph node constructor. Do not allow to create node of this type.
1582  * Netgraph context.
1583  */
1584 
1585 static int
1586 ng_ubt_constructor(node_p node)
1587 {
1588 	return (EINVAL);
1589 } /* ng_ubt_constructor */
1590 
1591 /*
1592  * Netgraph node destructor. Destroy node only when device has been detached.
1593  * Netgraph context.
1594  */
1595 
1596 static int
1597 ng_ubt_shutdown(node_p node)
1598 {
1599 	if (node->nd_flags & NGF_REALLY_DIE) {
1600 		/*
1601                  * We came here because the USB device is being
1602 		 * detached, so stop being persistent.
1603                  */
1604 		NG_NODE_SET_PRIVATE(node, NULL);
1605 		NG_NODE_UNREF(node);
1606 	} else
1607 		NG_NODE_REVIVE(node); /* tell ng_rmnode we are persisant */
1608 
1609 	return (0);
1610 } /* ng_ubt_shutdown */
1611 
1612 /*
1613  * Create new hook. There can only be one.
1614  * Netgraph context.
1615  */
1616 
1617 static int
1618 ng_ubt_newhook(node_p node, hook_p hook, char const *name)
1619 {
1620 	struct ubt_softc	*sc = NG_NODE_PRIVATE(node);
1621 
1622 	if (strcmp(name, NG_UBT_HOOK) != 0)
1623 		return (EINVAL);
1624 
1625 	UBT_NG_LOCK(sc);
1626 	if (sc->sc_hook != NULL) {
1627 		UBT_NG_UNLOCK(sc);
1628 
1629 		return (EISCONN);
1630 	}
1631 
1632 	sc->sc_hook = hook;
1633 	UBT_NG_UNLOCK(sc);
1634 
1635 	return (0);
1636 } /* ng_ubt_newhook */
1637 
1638 /*
1639  * Connect hook. Start incoming USB transfers.
1640  * Netgraph context.
1641  */
1642 
1643 static int
1644 ng_ubt_connect(hook_p hook)
1645 {
1646 	struct ubt_softc	*sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1647 
1648 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
1649 
1650 	UBT_NG_LOCK(sc);
1651 	ubt_task_schedule(sc, UBT_FLAG_T_START_ALL);
1652 	UBT_NG_UNLOCK(sc);
1653 
1654 	return (0);
1655 } /* ng_ubt_connect */
1656 
1657 /*
1658  * Disconnect hook.
1659  * Netgraph context.
1660  */
1661 
1662 static int
1663 ng_ubt_disconnect(hook_p hook)
1664 {
1665 	struct ubt_softc	*sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1666 
1667 	UBT_NG_LOCK(sc);
1668 
1669 	if (hook != sc->sc_hook) {
1670 		UBT_NG_UNLOCK(sc);
1671 
1672 		return (EINVAL);
1673 	}
1674 
1675 	sc->sc_hook = NULL;
1676 
1677 	/* Kick off task to stop all USB xfers */
1678 	ubt_task_schedule(sc, UBT_FLAG_T_STOP_ALL);
1679 
1680 	/* Drain queues */
1681 	NG_BT_MBUFQ_DRAIN(&sc->sc_cmdq);
1682 	NG_BT_MBUFQ_DRAIN(&sc->sc_aclq);
1683 	NG_BT_MBUFQ_DRAIN(&sc->sc_scoq);
1684 
1685 	UBT_NG_UNLOCK(sc);
1686 
1687 	return (0);
1688 } /* ng_ubt_disconnect */
1689 
1690 /*
1691  * Process control message.
1692  * Netgraph context.
1693  */
1694 
1695 static int
1696 ng_ubt_rcvmsg(node_p node, item_p item, hook_p lasthook)
1697 {
1698 	struct ubt_softc	*sc = NG_NODE_PRIVATE(node);
1699 	struct ng_mesg		*msg, *rsp = NULL;
1700 	struct ng_bt_mbufq	*q;
1701 	int			error = 0, queue, qlen;
1702 
1703 	NGI_GET_MSG(item, msg);
1704 
1705 	switch (msg->header.typecookie) {
1706 	case NGM_GENERIC_COOKIE:
1707 		switch (msg->header.cmd) {
1708 		case NGM_TEXT_STATUS:
1709 			NG_MKRESPONSE(rsp, msg, NG_TEXTRESPONSE, M_NOWAIT);
1710 			if (rsp == NULL) {
1711 				error = ENOMEM;
1712 				break;
1713 			}
1714 
1715 			snprintf(rsp->data, NG_TEXTRESPONSE,
1716 				"Hook: %s\n" \
1717 				"Task flags: %#x\n" \
1718 				"Debug: %d\n" \
1719 				"CMD queue: [have:%d,max:%d]\n" \
1720 				"ACL queue: [have:%d,max:%d]\n" \
1721 				"SCO queue: [have:%d,max:%d]",
1722 				(sc->sc_hook != NULL) ? NG_UBT_HOOK : "",
1723 				sc->sc_task_flags,
1724 				sc->sc_debug,
1725 				sc->sc_cmdq.len,
1726 				sc->sc_cmdq.maxlen,
1727 				sc->sc_aclq.len,
1728 				sc->sc_aclq.maxlen,
1729 				sc->sc_scoq.len,
1730 				sc->sc_scoq.maxlen);
1731 			break;
1732 
1733 		default:
1734 			error = EINVAL;
1735 			break;
1736 		}
1737 		break;
1738 
1739 	case NGM_UBT_COOKIE:
1740 		switch (msg->header.cmd) {
1741 		case NGM_UBT_NODE_SET_DEBUG:
1742 			if (msg->header.arglen != sizeof(ng_ubt_node_debug_ep)){
1743 				error = EMSGSIZE;
1744 				break;
1745 			}
1746 
1747 			sc->sc_debug = *((ng_ubt_node_debug_ep *) (msg->data));
1748 			break;
1749 
1750 		case NGM_UBT_NODE_GET_DEBUG:
1751 			NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_debug_ep),
1752 			    M_NOWAIT);
1753 			if (rsp == NULL) {
1754 				error = ENOMEM;
1755 				break;
1756 			}
1757 
1758 			*((ng_ubt_node_debug_ep *) (rsp->data)) = sc->sc_debug;
1759 			break;
1760 
1761 		case NGM_UBT_NODE_SET_QLEN:
1762 			if (msg->header.arglen != sizeof(ng_ubt_node_qlen_ep)) {
1763 				error = EMSGSIZE;
1764 				break;
1765 			}
1766 
1767 			queue = ((ng_ubt_node_qlen_ep *) (msg->data))->queue;
1768 			qlen = ((ng_ubt_node_qlen_ep *) (msg->data))->qlen;
1769 
1770 			switch (queue) {
1771 			case NGM_UBT_NODE_QUEUE_CMD:
1772 				q = &sc->sc_cmdq;
1773 				break;
1774 
1775 			case NGM_UBT_NODE_QUEUE_ACL:
1776 				q = &sc->sc_aclq;
1777 				break;
1778 
1779 			case NGM_UBT_NODE_QUEUE_SCO:
1780 				q = &sc->sc_scoq;
1781 				break;
1782 
1783 			default:
1784 				error = EINVAL;
1785 				goto done;
1786 				/* NOT REACHED */
1787 			}
1788 
1789 			q->maxlen = qlen;
1790 			break;
1791 
1792 		case NGM_UBT_NODE_GET_QLEN:
1793 			if (msg->header.arglen != sizeof(ng_ubt_node_qlen_ep)) {
1794 				error = EMSGSIZE;
1795 				break;
1796 			}
1797 
1798 			queue = ((ng_ubt_node_qlen_ep *) (msg->data))->queue;
1799 
1800 			switch (queue) {
1801 			case NGM_UBT_NODE_QUEUE_CMD:
1802 				q = &sc->sc_cmdq;
1803 				break;
1804 
1805 			case NGM_UBT_NODE_QUEUE_ACL:
1806 				q = &sc->sc_aclq;
1807 				break;
1808 
1809 			case NGM_UBT_NODE_QUEUE_SCO:
1810 				q = &sc->sc_scoq;
1811 				break;
1812 
1813 			default:
1814 				error = EINVAL;
1815 				goto done;
1816 				/* NOT REACHED */
1817 			}
1818 
1819 			NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_qlen_ep),
1820 				M_NOWAIT);
1821 			if (rsp == NULL) {
1822 				error = ENOMEM;
1823 				break;
1824 			}
1825 
1826 			((ng_ubt_node_qlen_ep *) (rsp->data))->queue = queue;
1827 			((ng_ubt_node_qlen_ep *) (rsp->data))->qlen = q->maxlen;
1828 			break;
1829 
1830 		case NGM_UBT_NODE_GET_STAT:
1831 			NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_stat_ep),
1832 			    M_NOWAIT);
1833 			if (rsp == NULL) {
1834 				error = ENOMEM;
1835 				break;
1836 			}
1837 
1838 			bcopy(&sc->sc_stat, rsp->data,
1839 				sizeof(ng_ubt_node_stat_ep));
1840 			break;
1841 
1842 		case NGM_UBT_NODE_RESET_STAT:
1843 			UBT_STAT_RESET(sc);
1844 			break;
1845 
1846 		default:
1847 			error = EINVAL;
1848 			break;
1849 		}
1850 		break;
1851 
1852 	default:
1853 		error = EINVAL;
1854 		break;
1855 	}
1856 done:
1857 	NG_RESPOND_MSG(error, node, item, rsp);
1858 	NG_FREE_MSG(msg);
1859 
1860 	return (error);
1861 } /* ng_ubt_rcvmsg */
1862 
1863 /*
1864  * Process data.
1865  * Netgraph context.
1866  */
1867 
1868 static int
1869 ng_ubt_rcvdata(hook_p hook, item_p item)
1870 {
1871 	struct ubt_softc	*sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1872 	struct mbuf		*m;
1873 	struct ng_bt_mbufq	*q;
1874 	int			action, error = 0;
1875 
1876 	if (hook != sc->sc_hook) {
1877 		error = EINVAL;
1878 		goto done;
1879 	}
1880 
1881 	/* Deatch mbuf and get HCI frame type */
1882 	NGI_GET_M(item, m);
1883 
1884 	/*
1885 	 * Minimal size of the HCI frame is 4 bytes: 1 byte frame type,
1886 	 * 2 bytes connection handle and at least 1 byte of length.
1887 	 * Panic on data frame that has size smaller than 4 bytes (it
1888 	 * should not happen)
1889 	 */
1890 
1891 	if (m->m_pkthdr.len < 4)
1892 		panic("HCI frame size is too small! pktlen=%d\n",
1893 			m->m_pkthdr.len);
1894 
1895 	/* Process HCI frame */
1896 	switch (*mtod(m, uint8_t *)) {	/* XXX call m_pullup ? */
1897 	case NG_HCI_CMD_PKT:
1898 		if (m->m_pkthdr.len - 1 > (int)UBT_CTRL_BUFFER_SIZE)
1899 			panic("HCI command frame size is too big! " \
1900 				"buffer size=%zd, packet len=%d\n",
1901 				UBT_CTRL_BUFFER_SIZE, m->m_pkthdr.len);
1902 
1903 		q = &sc->sc_cmdq;
1904 		action = UBT_FLAG_T_START_CTRL;
1905 		break;
1906 
1907 	case NG_HCI_ACL_DATA_PKT:
1908 		if (m->m_pkthdr.len - 1 > UBT_BULK_WRITE_BUFFER_SIZE)
1909 			panic("ACL data frame size is too big! " \
1910 				"buffer size=%d, packet len=%d\n",
1911 				UBT_BULK_WRITE_BUFFER_SIZE, m->m_pkthdr.len);
1912 
1913 		q = &sc->sc_aclq;
1914 		action = UBT_FLAG_T_START_BULK;
1915 		break;
1916 
1917 	case NG_HCI_SCO_DATA_PKT:
1918 		q = &sc->sc_scoq;
1919 		action = 0;
1920 		break;
1921 
1922 	default:
1923 		UBT_ERR(sc, "Dropping unsupported HCI frame, type=0x%02x, " \
1924 			"pktlen=%d\n", *mtod(m, uint8_t *), m->m_pkthdr.len);
1925 
1926 		NG_FREE_M(m);
1927 		error = EINVAL;
1928 		goto done;
1929 		/* NOT REACHED */
1930 	}
1931 
1932 	UBT_NG_LOCK(sc);
1933 	if (NG_BT_MBUFQ_FULL(q)) {
1934 		NG_BT_MBUFQ_DROP(q);
1935 		UBT_NG_UNLOCK(sc);
1936 
1937 		UBT_ERR(sc, "Dropping HCI frame 0x%02x, len=%d. Queue full\n",
1938 			*mtod(m, uint8_t *), m->m_pkthdr.len);
1939 
1940 		NG_FREE_M(m);
1941 	} else {
1942 		/* Loose HCI packet type, enqueue mbuf and kick off task */
1943 		m_adj(m, sizeof(uint8_t));
1944 		NG_BT_MBUFQ_ENQUEUE(q, m);
1945 		ubt_task_schedule(sc, action);
1946 		UBT_NG_UNLOCK(sc);
1947 	}
1948 done:
1949 	NG_FREE_ITEM(item);
1950 
1951 	return (error);
1952 } /* ng_ubt_rcvdata */
1953 
1954 /****************************************************************************
1955  ****************************************************************************
1956  **                              Module
1957  ****************************************************************************
1958  ****************************************************************************/
1959 
1960 /*
1961  * Load/Unload the driver module
1962  */
1963 
1964 static int
1965 ubt_modevent(module_t mod, int event, void *data)
1966 {
1967 	int	error;
1968 
1969 	switch (event) {
1970 	case MOD_LOAD:
1971 		error = ng_newtype(&typestruct);
1972 		if (error != 0)
1973 			printf("%s: Could not register Netgraph node type, " \
1974 				"error=%d\n", NG_UBT_NODE_TYPE, error);
1975 		break;
1976 
1977 	case MOD_UNLOAD:
1978 		error = ng_rmtype(&typestruct);
1979 		break;
1980 
1981 	default:
1982 		error = EOPNOTSUPP;
1983 		break;
1984 	}
1985 
1986 	return (error);
1987 } /* ubt_modevent */
1988 
1989 devclass_t	ubt_devclass;
1990 
1991 static device_method_t	ubt_methods[] =
1992 {
1993 	DEVMETHOD(device_probe,	ubt_probe),
1994 	DEVMETHOD(device_attach, ubt_attach),
1995 	DEVMETHOD(device_detach, ubt_detach),
1996 	DEVMETHOD_END
1997 };
1998 
1999 driver_t		ubt_driver =
2000 {
2001 	.name =	   "ubt",
2002 	.methods = ubt_methods,
2003 	.size =	   sizeof(struct ubt_softc),
2004 };
2005 
2006 DRIVER_MODULE(ng_ubt, uhub, ubt_driver, ubt_devclass, ubt_modevent, 0);
2007 MODULE_VERSION(ng_ubt, NG_BLUETOOTH_VERSION);
2008 MODULE_DEPEND(ng_ubt, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
2009 MODULE_DEPEND(ng_ubt, ng_hci, NG_BLUETOOTH_VERSION, NG_BLUETOOTH_VERSION, NG_BLUETOOTH_VERSION);
2010 MODULE_DEPEND(ng_ubt, usb, 1, 1, 1);
2011 USB_PNP_HOST_INFO(ubt_devs);
2012