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