xref: /freebsd/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c (revision dd41de95a84d979615a2ef11df6850622bf6184e)
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 /* List of supported bluetooth devices */
438 static const STRUCT_USB_HOST_ID ubt_devs[] =
439 {
440 	/* Generic Bluetooth class devices */
441 	{ USB_IFACE_CLASS(UDCLASS_WIRELESS),
442 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
443 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
444 
445 	/* AVM USB Bluetooth-Adapter BlueFritz! v2.0 */
446 	{ USB_VPI(USB_VENDOR_AVM, 0x3800, 0) },
447 
448 	/* Broadcom USB dongles, mostly BCM20702 and BCM20702A0 */
449 	{ USB_VENDOR(USB_VENDOR_BROADCOM),
450 	  USB_IFACE_CLASS(UICLASS_VENDOR),
451 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
452 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
453 
454 	/* Apple-specific (Broadcom) devices */
455 	{ USB_VENDOR(USB_VENDOR_APPLE),
456 	  USB_IFACE_CLASS(UICLASS_VENDOR),
457 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
458 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
459 
460 	/* Foxconn - Hon Hai */
461 	{ USB_VENDOR(USB_VENDOR_FOXCONN),
462 	  USB_IFACE_CLASS(UICLASS_VENDOR),
463 	  USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
464 	  USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
465 
466 	/* MediaTek MT76x0E */
467 	{ USB_VPI(USB_VENDOR_MEDIATEK, 0x763f, 0) },
468 
469 	/* Broadcom SoftSailing reporting vendor specific */
470 	{ USB_VPI(USB_VENDOR_BROADCOM, 0x21e1, 0) },
471 
472 	/* Apple MacBookPro 7,1 */
473 	{ USB_VPI(USB_VENDOR_APPLE, 0x8213, 0) },
474 
475 	/* Apple iMac11,1 */
476 	{ USB_VPI(USB_VENDOR_APPLE, 0x8215, 0) },
477 
478 	/* Apple MacBookPro6,2 */
479 	{ USB_VPI(USB_VENDOR_APPLE, 0x8218, 0) },
480 
481 	/* Apple MacBookAir3,1, MacBookAir3,2 */
482 	{ USB_VPI(USB_VENDOR_APPLE, 0x821b, 0) },
483 
484 	/* Apple MacBookAir4,1 */
485 	{ USB_VPI(USB_VENDOR_APPLE, 0x821f, 0) },
486 
487 	/* MacBookAir6,1 */
488 	{ USB_VPI(USB_VENDOR_APPLE, 0x828f, 0) },
489 
490 	/* Apple MacBookPro8,2 */
491 	{ USB_VPI(USB_VENDOR_APPLE, 0x821a, 0) },
492 
493 	/* Apple MacMini5,1 */
494 	{ USB_VPI(USB_VENDOR_APPLE, 0x8281, 0) },
495 
496 	/* Bluetooth Ultraport Module from IBM */
497 	{ USB_VPI(USB_VENDOR_TDK, 0x030a, 0) },
498 
499 	/* ALPS Modules with non-standard ID */
500 	{ USB_VPI(USB_VENDOR_ALPS, 0x3001, 0) },
501 	{ USB_VPI(USB_VENDOR_ALPS, 0x3002, 0) },
502 
503 	{ USB_VPI(USB_VENDOR_ERICSSON2, 0x1002, 0) },
504 
505 	/* Canyon CN-BTU1 with HID interfaces */
506 	{ USB_VPI(USB_VENDOR_CANYON, 0x0000, 0) },
507 
508 	/* Broadcom BCM20702A0 */
509 	{ USB_VPI(USB_VENDOR_ASUS, 0x17b5, 0) },
510 	{ USB_VPI(USB_VENDOR_ASUS, 0x17cb, 0) },
511 	{ USB_VPI(USB_VENDOR_LITEON, 0x2003, 0) },
512 	{ USB_VPI(USB_VENDOR_FOXCONN, 0xe042, 0) },
513 	{ USB_VPI(USB_VENDOR_DELL, 0x8197, 0) },
514 	{ USB_VPI(USB_VENDOR_BELKIN, 0x065a, 0) },
515 };
516 
517 /*
518  * Does a synchronous (waits for completion event) execution of HCI command.
519  * Size of both command and response buffers are passed in length field of
520  * corresponding structures in "Parameter Total Length" format i.e.
521  * not including HCI packet headers.
522  *
523  * Must not be used after USB transfers have been configured in attach routine.
524  */
525 
526 usb_error_t
527 ubt_do_hci_request(struct usb_device *udev, struct ubt_hci_cmd *cmd,
528     void *evt, usb_timeout_t timeout)
529 {
530 	static const struct usb_config ubt_probe_config = {
531 		.type = UE_INTERRUPT,
532 		.endpoint = UE_ADDR_ANY,
533 		.direction = UE_DIR_IN,
534 		.flags = { .pipe_bof = 1, .short_xfer_ok = 1 },
535 		.bufsize = UBT_INTR_BUFFER_SIZE,
536 		.callback = &ubt_probe_intr_callback,
537 	};
538 	struct usb_device_request req;
539 	struct usb_xfer *xfer[1];
540 	struct mtx mtx;
541 	usb_error_t error = USB_ERR_NORMAL_COMPLETION;
542 	uint8_t iface_index = 0;
543 
544 	/* Initialize a USB control request and then do it */
545 	bzero(&req, sizeof(req));
546 	req.bmRequestType = UBT_HCI_REQUEST;
547 	req.wIndex[0] = iface_index;
548 	USETW(req.wLength, UBT_HCI_CMD_SIZE(cmd));
549 
550 	error = usbd_do_request(udev, NULL, &req, cmd);
551 	if (error != USB_ERR_NORMAL_COMPLETION) {
552 		printf("ng_ubt: usbd_do_request error=%s\n",
553 			usbd_errstr(error));
554 		return (error);
555 	}
556 
557 	if (evt == NULL)
558 		return (USB_ERR_NORMAL_COMPLETION);
559 
560 	/* Initialize INTR endpoint xfer and wait for response */
561 	mtx_init(&mtx, "ubt pb", NULL, MTX_DEF | MTX_NEW);
562 
563 	error = usbd_transfer_setup(udev, &iface_index, xfer,
564 	    &ubt_probe_config, 1, evt, &mtx);
565 	if (error == USB_ERR_NORMAL_COMPLETION) {
566 		mtx_lock(&mtx);
567 		usbd_transfer_start(*xfer);
568 
569 		if (msleep_sbt(evt, &mtx, 0, "ubt pb", SBT_1MS * timeout,
570 				0, C_HARDCLOCK) == EWOULDBLOCK) {
571 			printf("ng_ubt: HCI command 0x%04x timed out\n",
572 				le16toh(cmd->opcode));
573 			error = USB_ERR_TIMEOUT;
574 		}
575 
576 		usbd_transfer_stop(*xfer);
577 		mtx_unlock(&mtx);
578 
579 		usbd_transfer_unsetup(xfer, 1);
580 	} else
581 		printf("ng_ubt: usbd_transfer_setup error=%s\n",
582 			usbd_errstr(error));
583 
584 	mtx_destroy(&mtx);
585 
586 	return (error);
587 }
588 
589 /*
590  * Probe for a USB Bluetooth device.
591  * USB context.
592  */
593 
594 static int
595 ubt_probe(device_t dev)
596 {
597 	struct usb_attach_arg	*uaa = device_get_ivars(dev);
598 	int error;
599 
600 	if (uaa->usb_mode != USB_MODE_HOST)
601 		return (ENXIO);
602 
603 	if (uaa->info.bIfaceIndex != 0)
604 		return (ENXIO);
605 
606 	if (usbd_lookup_id_by_uaa(ubt_ignore_devs,
607 			sizeof(ubt_ignore_devs), uaa) == 0)
608 		return (ENXIO);
609 
610 	error = usbd_lookup_id_by_uaa(ubt_devs, sizeof(ubt_devs), uaa);
611 	if (error == 0)
612 		return (BUS_PROBE_GENERIC);
613 	return (error);
614 } /* ubt_probe */
615 
616 /*
617  * Attach the device.
618  * USB context.
619  */
620 
621 static int
622 ubt_attach(device_t dev)
623 {
624 	struct usb_attach_arg		*uaa = device_get_ivars(dev);
625 	struct ubt_softc		*sc = device_get_softc(dev);
626 	struct usb_endpoint_descriptor	*ed;
627 	struct usb_interface_descriptor *id;
628 	struct usb_interface		*iface;
629 	uint32_t			wMaxPacketSize;
630 	uint8_t				alt_index, i, j;
631 	uint8_t				iface_index[2] = { 0, 1 };
632 
633 	device_set_usb_desc(dev);
634 
635 	sc->sc_dev = dev;
636 	sc->sc_debug = NG_UBT_WARN_LEVEL;
637 
638 	/*
639 	 * Create Netgraph node
640 	 */
641 
642 	if (ng_make_node_common(&typestruct, &sc->sc_node) != 0) {
643 		UBT_ALERT(sc, "could not create Netgraph node\n");
644 		return (ENXIO);
645 	}
646 
647 	/* Name Netgraph node */
648 	if (ng_name_node(sc->sc_node, device_get_nameunit(dev)) != 0) {
649 		UBT_ALERT(sc, "could not name Netgraph node\n");
650 		NG_NODE_UNREF(sc->sc_node);
651 		return (ENXIO);
652 	}
653 	NG_NODE_SET_PRIVATE(sc->sc_node, sc);
654 	NG_NODE_FORCE_WRITER(sc->sc_node);
655 
656 	/*
657 	 * Initialize device softc structure
658 	 */
659 
660 	/* initialize locks */
661 	mtx_init(&sc->sc_ng_mtx, "ubt ng", NULL, MTX_DEF);
662 	mtx_init(&sc->sc_if_mtx, "ubt if", NULL, MTX_DEF | MTX_RECURSE);
663 
664 	/* initialize packet queues */
665 	NG_BT_MBUFQ_INIT(&sc->sc_cmdq, UBT_DEFAULT_QLEN);
666 	NG_BT_MBUFQ_INIT(&sc->sc_aclq, UBT_DEFAULT_QLEN);
667 	NG_BT_MBUFQ_INIT(&sc->sc_scoq, UBT_DEFAULT_QLEN);
668 
669 	/* initialize glue task */
670 	TASK_INIT(&sc->sc_task, 0, ubt_task, sc);
671 
672 	/*
673 	 * Configure Bluetooth USB device. Discover all required USB
674 	 * interfaces and endpoints.
675 	 *
676 	 * USB device must present two interfaces:
677 	 * 1) Interface 0 that has 3 endpoints
678 	 *	1) Interrupt endpoint to receive HCI events
679 	 *	2) Bulk IN endpoint to receive ACL data
680 	 *	3) Bulk OUT endpoint to send ACL data
681 	 *
682 	 * 2) Interface 1 then has 2 endpoints
683 	 *	1) Isochronous IN endpoint to receive SCO data
684  	 *	2) Isochronous OUT endpoint to send SCO data
685 	 *
686 	 * Interface 1 (with isochronous endpoints) has several alternate
687 	 * configurations with different packet size.
688 	 */
689 
690 	/*
691 	 * For interface #1 search alternate settings, and find
692 	 * the descriptor with the largest wMaxPacketSize
693 	 */
694 
695 	wMaxPacketSize = 0;
696 	alt_index = 0;
697 	i = 0;
698 	j = 0;
699 	ed = NULL;
700 
701 	/*
702 	 * Search through all the descriptors looking for the largest
703 	 * packet size:
704 	 */
705 	while ((ed = (struct usb_endpoint_descriptor *)usb_desc_foreach(
706 	    usbd_get_config_descriptor(uaa->device),
707 	    (struct usb_descriptor *)ed))) {
708 		if ((ed->bDescriptorType == UDESC_INTERFACE) &&
709 		    (ed->bLength >= sizeof(*id))) {
710 			id = (struct usb_interface_descriptor *)ed;
711 			i = id->bInterfaceNumber;
712 			j = id->bAlternateSetting;
713 		}
714 
715 		if ((ed->bDescriptorType == UDESC_ENDPOINT) &&
716 		    (ed->bLength >= sizeof(*ed)) &&
717 		    (i == 1)) {
718 			uint32_t temp;
719 
720 			temp = usbd_get_max_frame_length(
721 			    ed, NULL, usbd_get_speed(uaa->device));
722 			if (temp > wMaxPacketSize) {
723 				wMaxPacketSize = temp;
724 				alt_index = j;
725 			}
726 		}
727 	}
728 
729 	/* Set alt configuration on interface #1 only if we found it */
730 	if (wMaxPacketSize > 0 &&
731 	    usbd_set_alt_interface_index(uaa->device, 1, alt_index)) {
732 		UBT_ALERT(sc, "could not set alternate setting %d " \
733 			"for interface 1!\n", alt_index);
734 		goto detach;
735 	}
736 
737 	/* Setup transfers for both interfaces */
738 	if (usbd_transfer_setup(uaa->device, iface_index, sc->sc_xfer,
739 			ubt_config, UBT_N_TRANSFER, sc, &sc->sc_if_mtx)) {
740 		UBT_ALERT(sc, "could not allocate transfers\n");
741 		goto detach;
742 	}
743 
744 	/* Claim all interfaces belonging to the Bluetooth part */
745 	for (i = 1;; i++) {
746 		iface = usbd_get_iface(uaa->device, i);
747 		if (iface == NULL)
748 			break;
749 		id = usbd_get_interface_descriptor(iface);
750 
751 		if ((id != NULL) &&
752 		    (id->bInterfaceClass == UICLASS_WIRELESS) &&
753 		    (id->bInterfaceSubClass == UISUBCLASS_RF) &&
754 		    (id->bInterfaceProtocol == UIPROTO_BLUETOOTH)) {
755 			usbd_set_parent_iface(uaa->device, i,
756 			    uaa->info.bIfaceIndex);
757 		}
758 	}
759 	return (0); /* success */
760 
761 detach:
762 	ubt_detach(dev);
763 
764 	return (ENXIO);
765 } /* ubt_attach */
766 
767 /*
768  * Detach the device.
769  * USB context.
770  */
771 
772 int
773 ubt_detach(device_t dev)
774 {
775 	struct ubt_softc	*sc = device_get_softc(dev);
776 	node_p			node = sc->sc_node;
777 
778 	/* Destroy Netgraph node */
779 	if (node != NULL) {
780 		sc->sc_node = NULL;
781 		NG_NODE_REALLY_DIE(node);
782 		ng_rmnode_self(node);
783 	}
784 
785 	/* Make sure ubt_task in gone */
786 	taskqueue_drain(taskqueue_swi, &sc->sc_task);
787 
788 	/* Free USB transfers, if any */
789 	usbd_transfer_unsetup(sc->sc_xfer, UBT_N_TRANSFER);
790 
791 	/* Destroy queues */
792 	UBT_NG_LOCK(sc);
793 	NG_BT_MBUFQ_DESTROY(&sc->sc_cmdq);
794 	NG_BT_MBUFQ_DESTROY(&sc->sc_aclq);
795 	NG_BT_MBUFQ_DESTROY(&sc->sc_scoq);
796 	UBT_NG_UNLOCK(sc);
797 
798 	mtx_destroy(&sc->sc_if_mtx);
799 	mtx_destroy(&sc->sc_ng_mtx);
800 
801 	return (0);
802 } /* ubt_detach */
803 
804 /*
805  * Called when incoming interrupt transfer (HCI event) has completed, i.e.
806  * HCI event was received from the device during device probe stage.
807  * USB context.
808  */
809 
810 static void
811 ubt_probe_intr_callback(struct usb_xfer *xfer, usb_error_t error)
812 {
813 	struct ubt_hci_event	*evt = usbd_xfer_softc(xfer);
814 	struct usb_page_cache	*pc;
815 	int			actlen;
816 
817 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
818 
819 	switch (USB_GET_STATE(xfer)) {
820 	case USB_ST_TRANSFERRED:
821 		if (actlen > UBT_HCI_EVENT_SIZE(evt))
822 			actlen = UBT_HCI_EVENT_SIZE(evt);
823 		pc = usbd_xfer_get_frame(xfer, 0);
824 		usbd_copy_out(pc, 0, evt, actlen);
825 		/* OneShot mode */
826 		wakeup(evt);
827 		break;
828 
829         case USB_ST_SETUP:
830 submit_next:
831 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
832 		usbd_transfer_submit(xfer);
833 		break;
834 
835 	default:
836 		if (error != USB_ERR_CANCELLED) {
837 			printf("ng_ubt: interrupt transfer failed: %s\n",
838 				usbd_errstr(error));
839 			/* Try clear stall first */
840 			usbd_xfer_set_stall(xfer);
841 			goto submit_next;
842 		}
843 		break;
844 	}
845 } /* ubt_probe_intr_callback */
846 
847 /*
848  * Called when outgoing control request (HCI command) has completed, i.e.
849  * HCI command was sent to the device.
850  * USB context.
851  */
852 
853 static void
854 ubt_ctrl_write_callback(struct usb_xfer *xfer, usb_error_t error)
855 {
856 	struct ubt_softc		*sc = usbd_xfer_softc(xfer);
857 	struct usb_device_request	req;
858 	struct mbuf			*m;
859 	struct usb_page_cache		*pc;
860 	int				actlen;
861 
862 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
863 
864 	switch (USB_GET_STATE(xfer)) {
865 	case USB_ST_TRANSFERRED:
866 		UBT_INFO(sc, "sent %d bytes to control pipe\n", actlen);
867 		UBT_STAT_BYTES_SENT(sc, actlen);
868 		UBT_STAT_PCKTS_SENT(sc);
869 		/* FALLTHROUGH */
870 
871 	case USB_ST_SETUP:
872 send_next:
873 		/* Get next command mbuf, if any */
874 		UBT_NG_LOCK(sc);
875 		NG_BT_MBUFQ_DEQUEUE(&sc->sc_cmdq, m);
876 		UBT_NG_UNLOCK(sc);
877 
878 		if (m == NULL) {
879 			UBT_INFO(sc, "HCI command queue is empty\n");
880 			break;	/* transfer complete */
881 		}
882 
883 		/* Initialize a USB control request and then schedule it */
884 		bzero(&req, sizeof(req));
885 		req.bmRequestType = UBT_HCI_REQUEST;
886 		USETW(req.wLength, m->m_pkthdr.len);
887 
888 		UBT_INFO(sc, "Sending control request, " \
889 			"bmRequestType=0x%02x, wLength=%d\n",
890 			req.bmRequestType, UGETW(req.wLength));
891 
892 		pc = usbd_xfer_get_frame(xfer, 0);
893 		usbd_copy_in(pc, 0, &req, sizeof(req));
894 		pc = usbd_xfer_get_frame(xfer, 1);
895 		usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len);
896 
897 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
898 		usbd_xfer_set_frame_len(xfer, 1, m->m_pkthdr.len);
899 		usbd_xfer_set_frames(xfer, 2);
900 
901 		NG_FREE_M(m);
902 
903 		usbd_transfer_submit(xfer);
904 		break;
905 
906 	default: /* Error */
907 		if (error != USB_ERR_CANCELLED) {
908 			UBT_WARN(sc, "control transfer failed: %s\n",
909 				usbd_errstr(error));
910 
911 			UBT_STAT_OERROR(sc);
912 			goto send_next;
913 		}
914 
915 		/* transfer cancelled */
916 		break;
917 	}
918 } /* ubt_ctrl_write_callback */
919 
920 /*
921  * Called when incoming interrupt transfer (HCI event) has completed, i.e.
922  * HCI event was received from the device.
923  * USB context.
924  */
925 
926 static void
927 ubt_intr_read_callback(struct usb_xfer *xfer, usb_error_t error)
928 {
929 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
930 	struct mbuf		*m;
931 	ng_hci_event_pkt_t	*hdr;
932 	struct usb_page_cache	*pc;
933 	int			actlen;
934 
935 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
936 
937 	m = NULL;
938 
939 	switch (USB_GET_STATE(xfer)) {
940 	case USB_ST_TRANSFERRED:
941 		/* Allocate a new mbuf */
942 		MGETHDR(m, M_NOWAIT, MT_DATA);
943 		if (m == NULL) {
944 			UBT_STAT_IERROR(sc);
945 			goto submit_next;
946 		}
947 
948 		if (!(MCLGET(m, M_NOWAIT))) {
949 			UBT_STAT_IERROR(sc);
950 			goto submit_next;
951 		}
952 
953 		/* Add HCI packet type */
954 		*mtod(m, uint8_t *)= NG_HCI_EVENT_PKT;
955 		m->m_pkthdr.len = m->m_len = 1;
956 
957 		if (actlen > MCLBYTES - 1)
958 			actlen = MCLBYTES - 1;
959 
960 		pc = usbd_xfer_get_frame(xfer, 0);
961 		usbd_copy_out(pc, 0, mtod(m, uint8_t *) + 1, actlen);
962 		m->m_pkthdr.len += actlen;
963 		m->m_len += actlen;
964 
965 		UBT_INFO(sc, "got %d bytes from interrupt pipe\n",
966 			actlen);
967 
968 		/* Validate packet and send it up the stack */
969 		if (m->m_pkthdr.len < (int)sizeof(*hdr)) {
970 			UBT_INFO(sc, "HCI event packet is too short\n");
971 
972 			UBT_STAT_IERROR(sc);
973 			goto submit_next;
974 		}
975 
976 		hdr = mtod(m, ng_hci_event_pkt_t *);
977 		if (hdr->length != (m->m_pkthdr.len - sizeof(*hdr))) {
978 			UBT_ERR(sc, "Invalid HCI event packet size, " \
979 				"length=%d, pktlen=%d\n",
980 				hdr->length, m->m_pkthdr.len);
981 
982 			UBT_STAT_IERROR(sc);
983 			goto submit_next;
984 		}
985 
986 		UBT_INFO(sc, "got complete HCI event frame, pktlen=%d, " \
987 			"length=%d\n", m->m_pkthdr.len, hdr->length);
988 
989 		UBT_STAT_PCKTS_RECV(sc);
990 		UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
991 
992 		ubt_fwd_mbuf_up(sc, &m);
993 		/* m == NULL at this point */
994 		/* FALLTHROUGH */
995 
996 	case USB_ST_SETUP:
997 submit_next:
998 		NG_FREE_M(m); /* checks for m != NULL */
999 
1000 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1001 		usbd_transfer_submit(xfer);
1002 		break;
1003 
1004 	default: /* Error */
1005 		if (error != USB_ERR_CANCELLED) {
1006 			UBT_WARN(sc, "interrupt transfer failed: %s\n",
1007 				usbd_errstr(error));
1008 
1009 			/* Try to clear stall first */
1010 			usbd_xfer_set_stall(xfer);
1011 			goto submit_next;
1012 		}
1013 			/* transfer cancelled */
1014 		break;
1015 	}
1016 } /* ubt_intr_read_callback */
1017 
1018 /*
1019  * Called when incoming bulk transfer (ACL packet) has completed, i.e.
1020  * ACL packet was received from the device.
1021  * USB context.
1022  */
1023 
1024 static void
1025 ubt_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1026 {
1027 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1028 	struct mbuf		*m;
1029 	ng_hci_acldata_pkt_t	*hdr;
1030 	struct usb_page_cache	*pc;
1031 	int len;
1032 	int actlen;
1033 
1034 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1035 
1036 	m = NULL;
1037 
1038 	switch (USB_GET_STATE(xfer)) {
1039 	case USB_ST_TRANSFERRED:
1040 		/* Allocate new mbuf */
1041 		MGETHDR(m, M_NOWAIT, MT_DATA);
1042 		if (m == NULL) {
1043 			UBT_STAT_IERROR(sc);
1044 			goto submit_next;
1045 		}
1046 
1047 		if (!(MCLGET(m, M_NOWAIT))) {
1048 			UBT_STAT_IERROR(sc);
1049 			goto submit_next;
1050 		}
1051 
1052 		/* Add HCI packet type */
1053 		*mtod(m, uint8_t *)= NG_HCI_ACL_DATA_PKT;
1054 		m->m_pkthdr.len = m->m_len = 1;
1055 
1056 		if (actlen > MCLBYTES - 1)
1057 			actlen = MCLBYTES - 1;
1058 
1059 		pc = usbd_xfer_get_frame(xfer, 0);
1060 		usbd_copy_out(pc, 0, mtod(m, uint8_t *) + 1, actlen);
1061 		m->m_pkthdr.len += actlen;
1062 		m->m_len += actlen;
1063 
1064 		UBT_INFO(sc, "got %d bytes from bulk-in pipe\n",
1065 			actlen);
1066 
1067 		/* Validate packet and send it up the stack */
1068 		if (m->m_pkthdr.len < (int)sizeof(*hdr)) {
1069 			UBT_INFO(sc, "HCI ACL packet is too short\n");
1070 
1071 			UBT_STAT_IERROR(sc);
1072 			goto submit_next;
1073 		}
1074 
1075 		hdr = mtod(m, ng_hci_acldata_pkt_t *);
1076 		len = le16toh(hdr->length);
1077 		if (len != (int)(m->m_pkthdr.len - sizeof(*hdr))) {
1078 			UBT_ERR(sc, "Invalid ACL packet size, length=%d, " \
1079 				"pktlen=%d\n", len, m->m_pkthdr.len);
1080 
1081 			UBT_STAT_IERROR(sc);
1082 			goto submit_next;
1083 		}
1084 
1085 		UBT_INFO(sc, "got complete ACL data packet, pktlen=%d, " \
1086 			"length=%d\n", m->m_pkthdr.len, len);
1087 
1088 		UBT_STAT_PCKTS_RECV(sc);
1089 		UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
1090 
1091 		ubt_fwd_mbuf_up(sc, &m);
1092 		/* m == NULL at this point */
1093 		/* FALLTHOUGH */
1094 
1095 	case USB_ST_SETUP:
1096 submit_next:
1097 		NG_FREE_M(m); /* checks for m != NULL */
1098 
1099 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1100 		usbd_transfer_submit(xfer);
1101 		break;
1102 
1103 	default: /* Error */
1104 		if (error != USB_ERR_CANCELLED) {
1105 			UBT_WARN(sc, "bulk-in transfer failed: %s\n",
1106 				usbd_errstr(error));
1107 
1108 			/* Try to clear stall first */
1109 			usbd_xfer_set_stall(xfer);
1110 			goto submit_next;
1111 		}
1112 			/* transfer cancelled */
1113 		break;
1114 	}
1115 } /* ubt_bulk_read_callback */
1116 
1117 /*
1118  * Called when outgoing bulk transfer (ACL packet) has completed, i.e.
1119  * ACL packet was sent to the device.
1120  * USB context.
1121  */
1122 
1123 static void
1124 ubt_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1125 {
1126 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1127 	struct mbuf		*m;
1128 	struct usb_page_cache	*pc;
1129 	int			actlen;
1130 
1131 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1132 
1133 	switch (USB_GET_STATE(xfer)) {
1134 	case USB_ST_TRANSFERRED:
1135 		UBT_INFO(sc, "sent %d bytes to bulk-out pipe\n", actlen);
1136 		UBT_STAT_BYTES_SENT(sc, actlen);
1137 		UBT_STAT_PCKTS_SENT(sc);
1138 		/* FALLTHROUGH */
1139 
1140 	case USB_ST_SETUP:
1141 send_next:
1142 		/* Get next mbuf, if any */
1143 		UBT_NG_LOCK(sc);
1144 		NG_BT_MBUFQ_DEQUEUE(&sc->sc_aclq, m);
1145 		UBT_NG_UNLOCK(sc);
1146 
1147 		if (m == NULL) {
1148 			UBT_INFO(sc, "ACL data queue is empty\n");
1149 			break; /* transfer completed */
1150 		}
1151 
1152 		/*
1153 		 * Copy ACL data frame back to a linear USB transfer buffer
1154 		 * and schedule transfer
1155 		 */
1156 
1157 		pc = usbd_xfer_get_frame(xfer, 0);
1158 		usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len);
1159 		usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len);
1160 
1161 		UBT_INFO(sc, "bulk-out transfer has been started, len=%d\n",
1162 			m->m_pkthdr.len);
1163 
1164 		NG_FREE_M(m);
1165 
1166 		usbd_transfer_submit(xfer);
1167 		break;
1168 
1169 	default: /* Error */
1170 		if (error != USB_ERR_CANCELLED) {
1171 			UBT_WARN(sc, "bulk-out transfer failed: %s\n",
1172 				usbd_errstr(error));
1173 
1174 			UBT_STAT_OERROR(sc);
1175 
1176 			/* try to clear stall first */
1177 			usbd_xfer_set_stall(xfer);
1178 			goto send_next;
1179 		}
1180 			/* transfer cancelled */
1181 		break;
1182 	}
1183 } /* ubt_bulk_write_callback */
1184 
1185 /*
1186  * Called when incoming isoc transfer (SCO packet) has completed, i.e.
1187  * SCO packet was received from the device.
1188  * USB context.
1189  */
1190 
1191 static void
1192 ubt_isoc_read_callback(struct usb_xfer *xfer, usb_error_t error)
1193 {
1194 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1195 	int			n;
1196 	int actlen, nframes;
1197 
1198 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1199 
1200 	switch (USB_GET_STATE(xfer)) {
1201 	case USB_ST_TRANSFERRED:
1202 		for (n = 0; n < nframes; n ++)
1203 			if (ubt_isoc_read_one_frame(xfer, n) < 0)
1204 				break;
1205 		/* FALLTHROUGH */
1206 
1207 	case USB_ST_SETUP:
1208 read_next:
1209 		for (n = 0; n < nframes; n ++)
1210 			usbd_xfer_set_frame_len(xfer, n,
1211 			    usbd_xfer_max_framelen(xfer));
1212 
1213 		usbd_transfer_submit(xfer);
1214 		break;
1215 
1216 	default: /* Error */
1217                 if (error != USB_ERR_CANCELLED) {
1218                         UBT_STAT_IERROR(sc);
1219                         goto read_next;
1220                 }
1221 
1222 		/* transfer cancelled */
1223 		break;
1224 	}
1225 } /* ubt_isoc_read_callback */
1226 
1227 /*
1228  * Helper function. Called from ubt_isoc_read_callback() to read
1229  * SCO data from one frame.
1230  * USB context.
1231  */
1232 
1233 static int
1234 ubt_isoc_read_one_frame(struct usb_xfer *xfer, int frame_no)
1235 {
1236 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1237 	struct usb_page_cache	*pc;
1238 	struct mbuf		*m;
1239 	int			len, want, got, total;
1240 
1241 	/* Get existing SCO reassembly buffer */
1242 	pc = usbd_xfer_get_frame(xfer, 0);
1243 	m = sc->sc_isoc_in_buffer;
1244 	total = usbd_xfer_frame_len(xfer, frame_no);
1245 
1246 	/* While we have data in the frame */
1247 	while (total > 0) {
1248 		if (m == NULL) {
1249 			/* Start new reassembly buffer */
1250 			MGETHDR(m, M_NOWAIT, MT_DATA);
1251 			if (m == NULL) {
1252 				UBT_STAT_IERROR(sc);
1253 				return (-1);	/* XXX out of sync! */
1254 			}
1255 
1256 			if (!(MCLGET(m, M_NOWAIT))) {
1257 				UBT_STAT_IERROR(sc);
1258 				NG_FREE_M(m);
1259 				return (-1);	/* XXX out of sync! */
1260 			}
1261 
1262 			/* Expect SCO header */
1263 			*mtod(m, uint8_t *) = NG_HCI_SCO_DATA_PKT;
1264 			m->m_pkthdr.len = m->m_len = got = 1;
1265 			want = sizeof(ng_hci_scodata_pkt_t);
1266 		} else {
1267 			/*
1268 			 * Check if we have SCO header and if so
1269 			 * adjust amount of data we want
1270 			 */
1271 			got = m->m_pkthdr.len;
1272 			want = sizeof(ng_hci_scodata_pkt_t);
1273 
1274 			if (got >= want)
1275 				want += mtod(m, ng_hci_scodata_pkt_t *)->length;
1276 		}
1277 
1278 		/* Append frame data to the SCO reassembly buffer */
1279 		len = total;
1280 		if (got + len > want)
1281 			len = want - got;
1282 
1283 		usbd_copy_out(pc, frame_no * usbd_xfer_max_framelen(xfer),
1284 			mtod(m, uint8_t *) + m->m_pkthdr.len, len);
1285 
1286 		m->m_pkthdr.len += len;
1287 		m->m_len += len;
1288 		total -= len;
1289 
1290 		/* Check if we got everything we wanted, if not - continue */
1291 		if (got != want)
1292 			continue;
1293 
1294 		/* If we got here then we got complete SCO frame */
1295 		UBT_INFO(sc, "got complete SCO data frame, pktlen=%d, " \
1296 			"length=%d\n", m->m_pkthdr.len,
1297 			mtod(m, ng_hci_scodata_pkt_t *)->length);
1298 
1299 		UBT_STAT_PCKTS_RECV(sc);
1300 		UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
1301 
1302 		ubt_fwd_mbuf_up(sc, &m);
1303 		/* m == NULL at this point */
1304 	}
1305 
1306 	/* Put SCO reassembly buffer back */
1307 	sc->sc_isoc_in_buffer = m;
1308 
1309 	return (0);
1310 } /* ubt_isoc_read_one_frame */
1311 
1312 /*
1313  * Called when outgoing isoc transfer (SCO packet) has completed, i.e.
1314  * SCO packet was sent to the device.
1315  * USB context.
1316  */
1317 
1318 static void
1319 ubt_isoc_write_callback(struct usb_xfer *xfer, usb_error_t error)
1320 {
1321 	struct ubt_softc	*sc = usbd_xfer_softc(xfer);
1322 	struct usb_page_cache	*pc;
1323 	struct mbuf		*m;
1324 	int			n, space, offset;
1325 	int			actlen, nframes;
1326 
1327 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1328 	pc = usbd_xfer_get_frame(xfer, 0);
1329 
1330 	switch (USB_GET_STATE(xfer)) {
1331 	case USB_ST_TRANSFERRED:
1332 		UBT_INFO(sc, "sent %d bytes to isoc-out pipe\n", actlen);
1333 		UBT_STAT_BYTES_SENT(sc, actlen);
1334 		UBT_STAT_PCKTS_SENT(sc);
1335 		/* FALLTHROUGH */
1336 
1337 	case USB_ST_SETUP:
1338 send_next:
1339 		offset = 0;
1340 		space = usbd_xfer_max_framelen(xfer) * nframes;
1341 		m = NULL;
1342 
1343 		while (space > 0) {
1344 			if (m == NULL) {
1345 				UBT_NG_LOCK(sc);
1346 				NG_BT_MBUFQ_DEQUEUE(&sc->sc_scoq, m);
1347 				UBT_NG_UNLOCK(sc);
1348 
1349 				if (m == NULL)
1350 					break;
1351 			}
1352 
1353 			n = min(space, m->m_pkthdr.len);
1354 			if (n > 0) {
1355 				usbd_m_copy_in(pc, offset, m,0, n);
1356 				m_adj(m, n);
1357 
1358 				offset += n;
1359 				space -= n;
1360 			}
1361 
1362 			if (m->m_pkthdr.len == 0)
1363 				NG_FREE_M(m); /* sets m = NULL */
1364 		}
1365 
1366 		/* Put whatever is left from mbuf back on queue */
1367 		if (m != NULL) {
1368 			UBT_NG_LOCK(sc);
1369 			NG_BT_MBUFQ_PREPEND(&sc->sc_scoq, m);
1370 			UBT_NG_UNLOCK(sc);
1371 		}
1372 
1373 		/*
1374 		 * Calculate sizes for isoc frames.
1375 		 * Note that offset could be 0 at this point (i.e. we have
1376 		 * nothing to send). That is fine, as we have isoc. transfers
1377 		 * going in both directions all the time. In this case it
1378 		 * would be just empty isoc. transfer.
1379 		 */
1380 
1381 		for (n = 0; n < nframes; n ++) {
1382 			usbd_xfer_set_frame_len(xfer, n,
1383 			    min(offset, usbd_xfer_max_framelen(xfer)));
1384 			offset -= usbd_xfer_frame_len(xfer, n);
1385 		}
1386 
1387 		usbd_transfer_submit(xfer);
1388 		break;
1389 
1390 	default: /* Error */
1391 		if (error != USB_ERR_CANCELLED) {
1392 			UBT_STAT_OERROR(sc);
1393 			goto send_next;
1394 		}
1395 
1396 		/* transfer cancelled */
1397 		break;
1398 	}
1399 }
1400 
1401 /*
1402  * Utility function to forward provided mbuf upstream (i.e. up the stack).
1403  * Modifies value of the mbuf pointer (sets it to NULL).
1404  * Save to call from any context.
1405  */
1406 
1407 static int
1408 ubt_fwd_mbuf_up(ubt_softc_p sc, struct mbuf **m)
1409 {
1410 	hook_p	hook;
1411 	int	error;
1412 
1413 	/*
1414 	 * Close the race with Netgraph hook newhook/disconnect methods.
1415 	 * Save the hook pointer atomically. Two cases are possible:
1416 	 *
1417 	 * 1) The hook pointer is NULL. It means disconnect method got
1418 	 *    there first. In this case we are done.
1419 	 *
1420 	 * 2) The hook pointer is not NULL. It means that hook pointer
1421 	 *    could be either in valid or invalid (i.e. in the process
1422 	 *    of disconnect) state. In any case grab an extra reference
1423 	 *    to protect the hook pointer.
1424 	 *
1425 	 * It is ok to pass hook in invalid state to NG_SEND_DATA_ONLY() as
1426 	 * it checks for it. Drop extra reference after NG_SEND_DATA_ONLY().
1427 	 */
1428 
1429 	UBT_NG_LOCK(sc);
1430 	if ((hook = sc->sc_hook) != NULL)
1431 		NG_HOOK_REF(hook);
1432 	UBT_NG_UNLOCK(sc);
1433 
1434 	if (hook == NULL) {
1435 		NG_FREE_M(*m);
1436 		return (ENETDOWN);
1437 	}
1438 
1439 	NG_SEND_DATA_ONLY(error, hook, *m);
1440 	NG_HOOK_UNREF(hook);
1441 
1442 	if (error != 0)
1443 		UBT_STAT_IERROR(sc);
1444 
1445 	return (error);
1446 } /* ubt_fwd_mbuf_up */
1447 
1448 /****************************************************************************
1449  ****************************************************************************
1450  **                                 Glue
1451  ****************************************************************************
1452  ****************************************************************************/
1453 
1454 /*
1455  * Schedule glue task. Should be called with sc_ng_mtx held.
1456  * Netgraph context.
1457  */
1458 
1459 static void
1460 ubt_task_schedule(ubt_softc_p sc, int action)
1461 {
1462 	mtx_assert(&sc->sc_ng_mtx, MA_OWNED);
1463 
1464 	/*
1465 	 * Try to handle corner case when "start all" and "stop all"
1466 	 * actions can both be set before task is executed.
1467 	 *
1468 	 * The rules are
1469 	 *
1470 	 * sc_task_flags	action		new sc_task_flags
1471 	 * ------------------------------------------------------
1472 	 * 0			start		start
1473 	 * 0			stop		stop
1474 	 * start		start		start
1475 	 * start		stop		stop
1476 	 * stop			start		stop|start
1477 	 * stop			stop		stop
1478 	 * stop|start		start		stop|start
1479 	 * stop|start		stop		stop
1480 	 */
1481 
1482 	if (action != 0) {
1483 		if ((action & UBT_FLAG_T_STOP_ALL) != 0)
1484 			sc->sc_task_flags &= ~UBT_FLAG_T_START_ALL;
1485 
1486 		sc->sc_task_flags |= action;
1487 	}
1488 
1489 	if (sc->sc_task_flags & UBT_FLAG_T_PENDING)
1490 		return;
1491 
1492 	if (taskqueue_enqueue(taskqueue_swi, &sc->sc_task) == 0) {
1493 		sc->sc_task_flags |= UBT_FLAG_T_PENDING;
1494 		return;
1495 	}
1496 
1497 	/* XXX: i think this should never happen */
1498 } /* ubt_task_schedule */
1499 
1500 /*
1501  * Glue task. Examines sc_task_flags and does things depending on it.
1502  * Taskqueue context.
1503  */
1504 
1505 static void
1506 ubt_task(void *context, int pending)
1507 {
1508 	ubt_softc_p	sc = context;
1509 	int		task_flags, i;
1510 
1511 	UBT_NG_LOCK(sc);
1512 	task_flags = sc->sc_task_flags;
1513 	sc->sc_task_flags = 0;
1514 	UBT_NG_UNLOCK(sc);
1515 
1516 	/*
1517 	 * Stop all USB transfers synchronously.
1518 	 * Stop interface #0 and #1 transfers at the same time and in the
1519 	 * same loop. usbd_transfer_drain() will do appropriate locking.
1520 	 */
1521 
1522 	if (task_flags & UBT_FLAG_T_STOP_ALL)
1523 		for (i = 0; i < UBT_N_TRANSFER; i ++)
1524 			usbd_transfer_drain(sc->sc_xfer[i]);
1525 
1526 	/* Start incoming interrupt and bulk, and all isoc. USB transfers */
1527 	if (task_flags & UBT_FLAG_T_START_ALL) {
1528 		/*
1529 		 * Interface #0
1530 		 */
1531 
1532 		mtx_lock(&sc->sc_if_mtx);
1533 
1534 		ubt_xfer_start(sc, UBT_IF_0_INTR_DT_RD);
1535 		ubt_xfer_start(sc, UBT_IF_0_BULK_DT_RD);
1536 
1537 		/*
1538 		 * Interface #1
1539 		 * Start both read and write isoc. transfers by default.
1540 		 * Get them going all the time even if we have nothing
1541 		 * to send to avoid any delays.
1542 		 */
1543 
1544 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_RD1);
1545 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_RD2);
1546 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_WR1);
1547 		ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_WR2);
1548 
1549 		mtx_unlock(&sc->sc_if_mtx);
1550 	}
1551 
1552  	/* Start outgoing control transfer */
1553 	if (task_flags & UBT_FLAG_T_START_CTRL) {
1554 		mtx_lock(&sc->sc_if_mtx);
1555 		ubt_xfer_start(sc, UBT_IF_0_CTRL_DT_WR);
1556 		mtx_unlock(&sc->sc_if_mtx);
1557 	}
1558 
1559 	/* Start outgoing bulk transfer */
1560 	if (task_flags & UBT_FLAG_T_START_BULK) {
1561 		mtx_lock(&sc->sc_if_mtx);
1562 		ubt_xfer_start(sc, UBT_IF_0_BULK_DT_WR);
1563 		mtx_unlock(&sc->sc_if_mtx);
1564 	}
1565 } /* ubt_task */
1566 
1567 /****************************************************************************
1568  ****************************************************************************
1569  **                        Netgraph specific
1570  ****************************************************************************
1571  ****************************************************************************/
1572 
1573 /*
1574  * Netgraph node constructor. Do not allow to create node of this type.
1575  * Netgraph context.
1576  */
1577 
1578 static int
1579 ng_ubt_constructor(node_p node)
1580 {
1581 	return (EINVAL);
1582 } /* ng_ubt_constructor */
1583 
1584 /*
1585  * Netgraph node destructor. Destroy node only when device has been detached.
1586  * Netgraph context.
1587  */
1588 
1589 static int
1590 ng_ubt_shutdown(node_p node)
1591 {
1592 	if (node->nd_flags & NGF_REALLY_DIE) {
1593 		/*
1594                  * We came here because the USB device is being
1595 		 * detached, so stop being persistent.
1596                  */
1597 		NG_NODE_SET_PRIVATE(node, NULL);
1598 		NG_NODE_UNREF(node);
1599 	} else
1600 		NG_NODE_REVIVE(node); /* tell ng_rmnode we are persisant */
1601 
1602 	return (0);
1603 } /* ng_ubt_shutdown */
1604 
1605 /*
1606  * Create new hook. There can only be one.
1607  * Netgraph context.
1608  */
1609 
1610 static int
1611 ng_ubt_newhook(node_p node, hook_p hook, char const *name)
1612 {
1613 	struct ubt_softc	*sc = NG_NODE_PRIVATE(node);
1614 
1615 	if (strcmp(name, NG_UBT_HOOK) != 0)
1616 		return (EINVAL);
1617 
1618 	UBT_NG_LOCK(sc);
1619 	if (sc->sc_hook != NULL) {
1620 		UBT_NG_UNLOCK(sc);
1621 
1622 		return (EISCONN);
1623 	}
1624 
1625 	sc->sc_hook = hook;
1626 	UBT_NG_UNLOCK(sc);
1627 
1628 	return (0);
1629 } /* ng_ubt_newhook */
1630 
1631 /*
1632  * Connect hook. Start incoming USB transfers.
1633  * Netgraph context.
1634  */
1635 
1636 static int
1637 ng_ubt_connect(hook_p hook)
1638 {
1639 	struct ubt_softc	*sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1640 
1641 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
1642 
1643 	UBT_NG_LOCK(sc);
1644 	ubt_task_schedule(sc, UBT_FLAG_T_START_ALL);
1645 	UBT_NG_UNLOCK(sc);
1646 
1647 	return (0);
1648 } /* ng_ubt_connect */
1649 
1650 /*
1651  * Disconnect hook.
1652  * Netgraph context.
1653  */
1654 
1655 static int
1656 ng_ubt_disconnect(hook_p hook)
1657 {
1658 	struct ubt_softc	*sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1659 
1660 	UBT_NG_LOCK(sc);
1661 
1662 	if (hook != sc->sc_hook) {
1663 		UBT_NG_UNLOCK(sc);
1664 
1665 		return (EINVAL);
1666 	}
1667 
1668 	sc->sc_hook = NULL;
1669 
1670 	/* Kick off task to stop all USB xfers */
1671 	ubt_task_schedule(sc, UBT_FLAG_T_STOP_ALL);
1672 
1673 	/* Drain queues */
1674 	NG_BT_MBUFQ_DRAIN(&sc->sc_cmdq);
1675 	NG_BT_MBUFQ_DRAIN(&sc->sc_aclq);
1676 	NG_BT_MBUFQ_DRAIN(&sc->sc_scoq);
1677 
1678 	UBT_NG_UNLOCK(sc);
1679 
1680 	return (0);
1681 } /* ng_ubt_disconnect */
1682 
1683 /*
1684  * Process control message.
1685  * Netgraph context.
1686  */
1687 
1688 static int
1689 ng_ubt_rcvmsg(node_p node, item_p item, hook_p lasthook)
1690 {
1691 	struct ubt_softc	*sc = NG_NODE_PRIVATE(node);
1692 	struct ng_mesg		*msg, *rsp = NULL;
1693 	struct ng_bt_mbufq	*q;
1694 	int			error = 0, queue, qlen;
1695 
1696 	NGI_GET_MSG(item, msg);
1697 
1698 	switch (msg->header.typecookie) {
1699 	case NGM_GENERIC_COOKIE:
1700 		switch (msg->header.cmd) {
1701 		case NGM_TEXT_STATUS:
1702 			NG_MKRESPONSE(rsp, msg, NG_TEXTRESPONSE, M_NOWAIT);
1703 			if (rsp == NULL) {
1704 				error = ENOMEM;
1705 				break;
1706 			}
1707 
1708 			snprintf(rsp->data, NG_TEXTRESPONSE,
1709 				"Hook: %s\n" \
1710 				"Task flags: %#x\n" \
1711 				"Debug: %d\n" \
1712 				"CMD queue: [have:%d,max:%d]\n" \
1713 				"ACL queue: [have:%d,max:%d]\n" \
1714 				"SCO queue: [have:%d,max:%d]",
1715 				(sc->sc_hook != NULL) ? NG_UBT_HOOK : "",
1716 				sc->sc_task_flags,
1717 				sc->sc_debug,
1718 				sc->sc_cmdq.len,
1719 				sc->sc_cmdq.maxlen,
1720 				sc->sc_aclq.len,
1721 				sc->sc_aclq.maxlen,
1722 				sc->sc_scoq.len,
1723 				sc->sc_scoq.maxlen);
1724 			break;
1725 
1726 		default:
1727 			error = EINVAL;
1728 			break;
1729 		}
1730 		break;
1731 
1732 	case NGM_UBT_COOKIE:
1733 		switch (msg->header.cmd) {
1734 		case NGM_UBT_NODE_SET_DEBUG:
1735 			if (msg->header.arglen != sizeof(ng_ubt_node_debug_ep)){
1736 				error = EMSGSIZE;
1737 				break;
1738 			}
1739 
1740 			sc->sc_debug = *((ng_ubt_node_debug_ep *) (msg->data));
1741 			break;
1742 
1743 		case NGM_UBT_NODE_GET_DEBUG:
1744 			NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_debug_ep),
1745 			    M_NOWAIT);
1746 			if (rsp == NULL) {
1747 				error = ENOMEM;
1748 				break;
1749 			}
1750 
1751 			*((ng_ubt_node_debug_ep *) (rsp->data)) = sc->sc_debug;
1752 			break;
1753 
1754 		case NGM_UBT_NODE_SET_QLEN:
1755 			if (msg->header.arglen != sizeof(ng_ubt_node_qlen_ep)) {
1756 				error = EMSGSIZE;
1757 				break;
1758 			}
1759 
1760 			queue = ((ng_ubt_node_qlen_ep *) (msg->data))->queue;
1761 			qlen = ((ng_ubt_node_qlen_ep *) (msg->data))->qlen;
1762 
1763 			switch (queue) {
1764 			case NGM_UBT_NODE_QUEUE_CMD:
1765 				q = &sc->sc_cmdq;
1766 				break;
1767 
1768 			case NGM_UBT_NODE_QUEUE_ACL:
1769 				q = &sc->sc_aclq;
1770 				break;
1771 
1772 			case NGM_UBT_NODE_QUEUE_SCO:
1773 				q = &sc->sc_scoq;
1774 				break;
1775 
1776 			default:
1777 				error = EINVAL;
1778 				goto done;
1779 				/* NOT REACHED */
1780 			}
1781 
1782 			q->maxlen = qlen;
1783 			break;
1784 
1785 		case NGM_UBT_NODE_GET_QLEN:
1786 			if (msg->header.arglen != sizeof(ng_ubt_node_qlen_ep)) {
1787 				error = EMSGSIZE;
1788 				break;
1789 			}
1790 
1791 			queue = ((ng_ubt_node_qlen_ep *) (msg->data))->queue;
1792 
1793 			switch (queue) {
1794 			case NGM_UBT_NODE_QUEUE_CMD:
1795 				q = &sc->sc_cmdq;
1796 				break;
1797 
1798 			case NGM_UBT_NODE_QUEUE_ACL:
1799 				q = &sc->sc_aclq;
1800 				break;
1801 
1802 			case NGM_UBT_NODE_QUEUE_SCO:
1803 				q = &sc->sc_scoq;
1804 				break;
1805 
1806 			default:
1807 				error = EINVAL;
1808 				goto done;
1809 				/* NOT REACHED */
1810 			}
1811 
1812 			NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_qlen_ep),
1813 				M_NOWAIT);
1814 			if (rsp == NULL) {
1815 				error = ENOMEM;
1816 				break;
1817 			}
1818 
1819 			((ng_ubt_node_qlen_ep *) (rsp->data))->queue = queue;
1820 			((ng_ubt_node_qlen_ep *) (rsp->data))->qlen = q->maxlen;
1821 			break;
1822 
1823 		case NGM_UBT_NODE_GET_STAT:
1824 			NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_stat_ep),
1825 			    M_NOWAIT);
1826 			if (rsp == NULL) {
1827 				error = ENOMEM;
1828 				break;
1829 			}
1830 
1831 			bcopy(&sc->sc_stat, rsp->data,
1832 				sizeof(ng_ubt_node_stat_ep));
1833 			break;
1834 
1835 		case NGM_UBT_NODE_RESET_STAT:
1836 			UBT_STAT_RESET(sc);
1837 			break;
1838 
1839 		default:
1840 			error = EINVAL;
1841 			break;
1842 		}
1843 		break;
1844 
1845 	default:
1846 		error = EINVAL;
1847 		break;
1848 	}
1849 done:
1850 	NG_RESPOND_MSG(error, node, item, rsp);
1851 	NG_FREE_MSG(msg);
1852 
1853 	return (error);
1854 } /* ng_ubt_rcvmsg */
1855 
1856 /*
1857  * Process data.
1858  * Netgraph context.
1859  */
1860 
1861 static int
1862 ng_ubt_rcvdata(hook_p hook, item_p item)
1863 {
1864 	struct ubt_softc	*sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1865 	struct mbuf		*m;
1866 	struct ng_bt_mbufq	*q;
1867 	int			action, error = 0;
1868 
1869 	if (hook != sc->sc_hook) {
1870 		error = EINVAL;
1871 		goto done;
1872 	}
1873 
1874 	/* Deatch mbuf and get HCI frame type */
1875 	NGI_GET_M(item, m);
1876 
1877 	/*
1878 	 * Minimal size of the HCI frame is 4 bytes: 1 byte frame type,
1879 	 * 2 bytes connection handle and at least 1 byte of length.
1880 	 * Panic on data frame that has size smaller than 4 bytes (it
1881 	 * should not happen)
1882 	 */
1883 
1884 	if (m->m_pkthdr.len < 4)
1885 		panic("HCI frame size is too small! pktlen=%d\n",
1886 			m->m_pkthdr.len);
1887 
1888 	/* Process HCI frame */
1889 	switch (*mtod(m, uint8_t *)) {	/* XXX call m_pullup ? */
1890 	case NG_HCI_CMD_PKT:
1891 		if (m->m_pkthdr.len - 1 > (int)UBT_CTRL_BUFFER_SIZE)
1892 			panic("HCI command frame size is too big! " \
1893 				"buffer size=%zd, packet len=%d\n",
1894 				UBT_CTRL_BUFFER_SIZE, m->m_pkthdr.len);
1895 
1896 		q = &sc->sc_cmdq;
1897 		action = UBT_FLAG_T_START_CTRL;
1898 		break;
1899 
1900 	case NG_HCI_ACL_DATA_PKT:
1901 		if (m->m_pkthdr.len - 1 > UBT_BULK_WRITE_BUFFER_SIZE)
1902 			panic("ACL data frame size is too big! " \
1903 				"buffer size=%d, packet len=%d\n",
1904 				UBT_BULK_WRITE_BUFFER_SIZE, m->m_pkthdr.len);
1905 
1906 		q = &sc->sc_aclq;
1907 		action = UBT_FLAG_T_START_BULK;
1908 		break;
1909 
1910 	case NG_HCI_SCO_DATA_PKT:
1911 		q = &sc->sc_scoq;
1912 		action = 0;
1913 		break;
1914 
1915 	default:
1916 		UBT_ERR(sc, "Dropping unsupported HCI frame, type=0x%02x, " \
1917 			"pktlen=%d\n", *mtod(m, uint8_t *), m->m_pkthdr.len);
1918 
1919 		NG_FREE_M(m);
1920 		error = EINVAL;
1921 		goto done;
1922 		/* NOT REACHED */
1923 	}
1924 
1925 	UBT_NG_LOCK(sc);
1926 	if (NG_BT_MBUFQ_FULL(q)) {
1927 		NG_BT_MBUFQ_DROP(q);
1928 		UBT_NG_UNLOCK(sc);
1929 
1930 		UBT_ERR(sc, "Dropping HCI frame 0x%02x, len=%d. Queue full\n",
1931 			*mtod(m, uint8_t *), m->m_pkthdr.len);
1932 
1933 		NG_FREE_M(m);
1934 	} else {
1935 		/* Loose HCI packet type, enqueue mbuf and kick off task */
1936 		m_adj(m, sizeof(uint8_t));
1937 		NG_BT_MBUFQ_ENQUEUE(q, m);
1938 		ubt_task_schedule(sc, action);
1939 		UBT_NG_UNLOCK(sc);
1940 	}
1941 done:
1942 	NG_FREE_ITEM(item);
1943 
1944 	return (error);
1945 } /* ng_ubt_rcvdata */
1946 
1947 /****************************************************************************
1948  ****************************************************************************
1949  **                              Module
1950  ****************************************************************************
1951  ****************************************************************************/
1952 
1953 /*
1954  * Load/Unload the driver module
1955  */
1956 
1957 static int
1958 ubt_modevent(module_t mod, int event, void *data)
1959 {
1960 	int	error;
1961 
1962 	switch (event) {
1963 	case MOD_LOAD:
1964 		error = ng_newtype(&typestruct);
1965 		if (error != 0)
1966 			printf("%s: Could not register Netgraph node type, " \
1967 				"error=%d\n", NG_UBT_NODE_TYPE, error);
1968 		break;
1969 
1970 	case MOD_UNLOAD:
1971 		error = ng_rmtype(&typestruct);
1972 		break;
1973 
1974 	default:
1975 		error = EOPNOTSUPP;
1976 		break;
1977 	}
1978 
1979 	return (error);
1980 } /* ubt_modevent */
1981 
1982 devclass_t	ubt_devclass;
1983 
1984 static device_method_t	ubt_methods[] =
1985 {
1986 	DEVMETHOD(device_probe,	ubt_probe),
1987 	DEVMETHOD(device_attach, ubt_attach),
1988 	DEVMETHOD(device_detach, ubt_detach),
1989 	DEVMETHOD_END
1990 };
1991 
1992 driver_t		ubt_driver =
1993 {
1994 	.name =	   "ubt",
1995 	.methods = ubt_methods,
1996 	.size =	   sizeof(struct ubt_softc),
1997 };
1998 
1999 DRIVER_MODULE(ng_ubt, uhub, ubt_driver, ubt_devclass, ubt_modevent, 0);
2000 MODULE_VERSION(ng_ubt, NG_BLUETOOTH_VERSION);
2001 MODULE_DEPEND(ng_ubt, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
2002 MODULE_DEPEND(ng_ubt, ng_hci, NG_BLUETOOTH_VERSION, NG_BLUETOOTH_VERSION, NG_BLUETOOTH_VERSION);
2003 MODULE_DEPEND(ng_ubt, usb, 1, 1, 1);
2004 USB_PNP_HOST_INFO(ubt_devs);
2005