6 * Copyright (c) 2001-2009 Maksim Yevmenkin <m_evmenkin@yahoo.com>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
30 * $Id: ng_ubt.c,v 1.16 2003/10/10 19:15:06 max Exp $
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
40 * NOTE ON LOCKS USED: ng_ubt2 drives uses 2 locks (mutexes)
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.
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.
51 * NOTE ON LOCKING STRATEGY: ng_ubt2 driver operates in 3 different contexts.
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.
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.
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.
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
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.
96 #include <dev/usb/usb.h>
97 #include <dev/usb/usb_mfunc.h>
98 #include <dev/usb/usb_error.h>
100 #define USB_DEBUG_VAR usb2_debug
102 #include <dev/usb/usb_core.h>
103 #include <dev/usb/usb_debug.h>
104 #include <dev/usb/usb_parse.h>
105 #include <dev/usb/usb_lookup.h>
106 #include <dev/usb/usb_util.h>
107 #include <dev/usb/usb_busdma.h>
108 #include <dev/usb/usb_process.h>
109 #include <dev/usb/usb_transfer.h>
111 #include <sys/mbuf.h>
112 #include <sys/taskqueue.h>
114 #include <netgraph/ng_message.h>
115 #include <netgraph/netgraph.h>
116 #include <netgraph/ng_parse.h>
117 #include <netgraph/bluetooth/include/ng_bluetooth.h>
118 #include <netgraph/bluetooth/include/ng_hci.h>
119 #include <netgraph/bluetooth/include/ng_ubt.h>
120 #include <netgraph/bluetooth/drivers/ubt/ng_ubt_var.h>
122 static int ubt_modevent(module_t, int, void *);
123 static device_probe_t ubt_probe;
124 static device_attach_t ubt_attach;
125 static device_detach_t ubt_detach;
127 static void ubt_task_schedule(ubt_softc_p, int);
128 static task_fn_t ubt_task;
130 #define ubt_xfer_start(sc, i) usb2_transfer_start((sc)->sc_xfer[(i)])
132 /* Netgraph methods */
133 static ng_constructor_t ng_ubt_constructor;
134 static ng_shutdown_t ng_ubt_shutdown;
135 static ng_newhook_t ng_ubt_newhook;
136 static ng_connect_t ng_ubt_connect;
137 static ng_disconnect_t ng_ubt_disconnect;
138 static ng_rcvmsg_t ng_ubt_rcvmsg;
139 static ng_rcvdata_t ng_ubt_rcvdata;
142 static const struct ng_parse_struct_field ng_ubt_node_qlen_type_fields[] =
144 { "queue", &ng_parse_int32_type, },
145 { "qlen", &ng_parse_int32_type, },
148 static const struct ng_parse_type ng_ubt_node_qlen_type =
150 &ng_parse_struct_type,
151 &ng_ubt_node_qlen_type_fields
155 static const struct ng_parse_struct_field ng_ubt_node_stat_type_fields[] =
157 { "pckts_recv", &ng_parse_uint32_type, },
158 { "bytes_recv", &ng_parse_uint32_type, },
159 { "pckts_sent", &ng_parse_uint32_type, },
160 { "bytes_sent", &ng_parse_uint32_type, },
161 { "oerrors", &ng_parse_uint32_type, },
162 { "ierrors", &ng_parse_uint32_type, },
165 static const struct ng_parse_type ng_ubt_node_stat_type =
167 &ng_parse_struct_type,
168 &ng_ubt_node_stat_type_fields
171 /* Netgraph node command list */
172 static const struct ng_cmdlist ng_ubt_cmdlist[] =
176 NGM_UBT_NODE_SET_DEBUG,
178 &ng_parse_uint16_type,
183 NGM_UBT_NODE_GET_DEBUG,
186 &ng_parse_uint16_type
190 NGM_UBT_NODE_SET_QLEN,
192 &ng_ubt_node_qlen_type,
197 NGM_UBT_NODE_GET_QLEN,
199 &ng_ubt_node_qlen_type,
200 &ng_ubt_node_qlen_type
204 NGM_UBT_NODE_GET_STAT,
207 &ng_ubt_node_stat_type
211 NGM_UBT_NODE_RESET_STAT,
219 /* Netgraph node type */
220 static struct ng_type typestruct =
222 .version = NG_ABI_VERSION,
223 .name = NG_UBT_NODE_TYPE,
224 .constructor = ng_ubt_constructor,
225 .rcvmsg = ng_ubt_rcvmsg,
226 .shutdown = ng_ubt_shutdown,
227 .newhook = ng_ubt_newhook,
228 .connect = ng_ubt_connect,
229 .rcvdata = ng_ubt_rcvdata,
230 .disconnect = ng_ubt_disconnect,
231 .cmdlist = ng_ubt_cmdlist
234 /****************************************************************************
235 ****************************************************************************
237 ****************************************************************************
238 ****************************************************************************/
241 static usb_callback_t ubt_ctrl_write_callback;
242 static usb_callback_t ubt_intr_read_callback;
243 static usb_callback_t ubt_bulk_read_callback;
244 static usb_callback_t ubt_bulk_write_callback;
245 static usb_callback_t ubt_isoc_read_callback;
246 static usb_callback_t ubt_isoc_write_callback;
248 static int ubt_fwd_mbuf_up(ubt_softc_p, struct mbuf **);
249 static int ubt_isoc_read_one_frame(struct usb_xfer *, int);
254 * The following desribes usb transfers that could be submitted on USB device.
256 * Interface 0 on the USB device must present the following endpoints
257 * 1) Interrupt endpoint to receive HCI events
258 * 2) Bulk IN endpoint to receive ACL data
259 * 3) Bulk OUT endpoint to send ACL data
261 * Interface 1 on the USB device must present the following endpoints
262 * 1) Isochronous IN endpoint to receive SCO data
263 * 2) Isochronous OUT endpoint to send SCO data
266 static const struct usb_config ubt_config[UBT_N_TRANSFER] =
272 /* Outgoing bulk transfer - ACL packets */
273 [UBT_IF_0_BULK_DT_WR] = {
275 .endpoint = UE_ADDR_ANY,
276 .direction = UE_DIR_OUT,
278 .bufsize = UBT_BULK_WRITE_BUFFER_SIZE,
279 .flags = { .pipe_bof = 1, .force_short_xfer = 1, },
280 .callback = &ubt_bulk_write_callback,
282 /* Incoming bulk transfer - ACL packets */
283 [UBT_IF_0_BULK_DT_RD] = {
285 .endpoint = UE_ADDR_ANY,
286 .direction = UE_DIR_IN,
288 .bufsize = UBT_BULK_READ_BUFFER_SIZE,
289 .flags = { .pipe_bof = 1, .short_xfer_ok = 1, },
290 .callback = &ubt_bulk_read_callback,
292 /* Incoming interrupt transfer - HCI events */
293 [UBT_IF_0_INTR_DT_RD] = {
294 .type = UE_INTERRUPT,
295 .endpoint = UE_ADDR_ANY,
296 .direction = UE_DIR_IN,
298 .flags = { .pipe_bof = 1, .short_xfer_ok = 1, },
299 .bufsize = UBT_INTR_BUFFER_SIZE,
300 .callback = &ubt_intr_read_callback,
302 /* Outgoing control transfer - HCI commands */
303 [UBT_IF_0_CTRL_DT_WR] = {
305 .endpoint = 0x00, /* control pipe */
306 .direction = UE_DIR_ANY,
308 .bufsize = UBT_CTRL_BUFFER_SIZE,
309 .callback = &ubt_ctrl_write_callback,
310 .timeout = 5000, /* 5 seconds */
317 /* Incoming isochronous transfer #1 - SCO packets */
318 [UBT_IF_1_ISOC_DT_RD1] = {
319 .type = UE_ISOCHRONOUS,
320 .endpoint = UE_ADDR_ANY,
321 .direction = UE_DIR_IN,
323 .bufsize = 0, /* use "wMaxPacketSize * frames" */
324 .frames = UBT_ISOC_NFRAMES,
325 .flags = { .short_xfer_ok = 1, },
326 .callback = &ubt_isoc_read_callback,
328 /* Incoming isochronous transfer #2 - SCO packets */
329 [UBT_IF_1_ISOC_DT_RD2] = {
330 .type = UE_ISOCHRONOUS,
331 .endpoint = UE_ADDR_ANY,
332 .direction = UE_DIR_IN,
334 .bufsize = 0, /* use "wMaxPacketSize * frames" */
335 .frames = UBT_ISOC_NFRAMES,
336 .flags = { .short_xfer_ok = 1, },
337 .callback = &ubt_isoc_read_callback,
339 /* Outgoing isochronous transfer #1 - SCO packets */
340 [UBT_IF_1_ISOC_DT_WR1] = {
341 .type = UE_ISOCHRONOUS,
342 .endpoint = UE_ADDR_ANY,
343 .direction = UE_DIR_OUT,
345 .bufsize = 0, /* use "wMaxPacketSize * frames" */
346 .frames = UBT_ISOC_NFRAMES,
347 .flags = { .short_xfer_ok = 1, },
348 .callback = &ubt_isoc_write_callback,
350 /* Outgoing isochronous transfer #2 - SCO packets */
351 [UBT_IF_1_ISOC_DT_WR2] = {
352 .type = UE_ISOCHRONOUS,
353 .endpoint = UE_ADDR_ANY,
354 .direction = UE_DIR_OUT,
356 .bufsize = 0, /* use "wMaxPacketSize * frames" */
357 .frames = UBT_ISOC_NFRAMES,
358 .flags = { .short_xfer_ok = 1, },
359 .callback = &ubt_isoc_write_callback,
364 * If for some reason device should not be attached then put
365 * VendorID/ProductID pair into the list below. The format is
368 * { USB_VPI(VENDOR_ID, PRODUCT_ID, 0) },
370 * where VENDOR_ID and PRODUCT_ID are hex numbers.
373 static const struct usb_device_id ubt_ignore_devs[] =
375 /* AVM USB Bluetooth-Adapter BlueFritz! v1.0 */
376 { USB_VPI(USB_VENDOR_AVM, 0x2200, 0) },
379 /* List of supported bluetooth devices */
380 static const struct usb_device_id ubt_devs[] =
382 /* Generic Bluetooth class devices */
383 { USB_IFACE_CLASS(UDCLASS_WIRELESS),
384 USB_IFACE_SUBCLASS(UDSUBCLASS_RF),
385 USB_IFACE_PROTOCOL(UDPROTO_BLUETOOTH) },
387 /* AVM USB Bluetooth-Adapter BlueFritz! v2.0 */
388 { USB_VPI(USB_VENDOR_AVM, 0x3800, 0) },
392 * Probe for a USB Bluetooth device.
397 ubt_probe(device_t dev)
399 struct usb_attach_arg *uaa = device_get_ivars(dev);
401 if (uaa->usb_mode != USB_MODE_HOST)
404 if (uaa->info.bIfaceIndex != 0)
407 if (uaa->use_generic == 0)
410 if (usb2_lookup_id_by_uaa(ubt_ignore_devs,
411 sizeof(ubt_ignore_devs), uaa) == 0)
414 return (usb2_lookup_id_by_uaa(ubt_devs, sizeof(ubt_devs), uaa));
423 ubt_attach(device_t dev)
425 struct usb_attach_arg *uaa = device_get_ivars(dev);
426 struct ubt_softc *sc = device_get_softc(dev);
427 struct usb_endpoint_descriptor *ed;
428 struct usb_interface_descriptor *id;
429 uint16_t wMaxPacketSize;
430 uint8_t alt_index, i, j;
431 uint8_t iface_index[2] = { 0, 1 };
433 device_set_usb2_desc(dev);
436 sc->sc_debug = NG_UBT_WARN_LEVEL;
439 * Create Netgraph node
442 if (ng_make_node_common(&typestruct, &sc->sc_node) != 0) {
443 UBT_ALERT(sc, "could not create Netgraph node\n");
447 /* Name Netgraph node */
448 if (ng_name_node(sc->sc_node, device_get_nameunit(dev)) != 0) {
449 UBT_ALERT(sc, "could not name Netgraph node\n");
450 NG_NODE_UNREF(sc->sc_node);
453 NG_NODE_SET_PRIVATE(sc->sc_node, sc);
454 NG_NODE_FORCE_WRITER(sc->sc_node);
457 * Initialize device softc structure
460 /* initialize locks */
461 mtx_init(&sc->sc_ng_mtx, "ubt ng", NULL, MTX_DEF);
462 mtx_init(&sc->sc_if_mtx, "ubt if", NULL, MTX_DEF | MTX_RECURSE);
464 /* initialize packet queues */
465 NG_BT_MBUFQ_INIT(&sc->sc_cmdq, UBT_DEFAULT_QLEN);
466 NG_BT_MBUFQ_INIT(&sc->sc_aclq, UBT_DEFAULT_QLEN);
467 NG_BT_MBUFQ_INIT(&sc->sc_scoq, UBT_DEFAULT_QLEN);
469 /* initialize glue task */
470 TASK_INIT(&sc->sc_task, 0, ubt_task, sc);
473 * Configure Bluetooth USB device. Discover all required USB
474 * interfaces and endpoints.
476 * USB device must present two interfaces:
477 * 1) Interface 0 that has 3 endpoints
478 * 1) Interrupt endpoint to receive HCI events
479 * 2) Bulk IN endpoint to receive ACL data
480 * 3) Bulk OUT endpoint to send ACL data
482 * 2) Interface 1 then has 2 endpoints
483 * 1) Isochronous IN endpoint to receive SCO data
484 * 2) Isochronous OUT endpoint to send SCO data
486 * Interface 1 (with isochronous endpoints) has several alternate
487 * configurations with different packet size.
491 * For interface #1 search alternate settings, and find
492 * the descriptor with the largest wMaxPacketSize
502 * Search through all the descriptors looking for the largest
505 while ((ed = (struct usb_endpoint_descriptor *)usb2_desc_foreach(
506 usb2_get_config_descriptor(uaa->device),
507 (struct usb_descriptor *)ed))) {
509 if ((ed->bDescriptorType == UDESC_INTERFACE) &&
510 (ed->bLength >= sizeof(*id))) {
511 id = (struct usb_interface_descriptor *)ed;
512 i = id->bInterfaceNumber;
513 j = id->bAlternateSetting;
516 if ((ed->bDescriptorType == UDESC_ENDPOINT) &&
517 (ed->bLength >= sizeof(*ed)) &&
521 temp = UGETW(ed->wMaxPacketSize);
522 if (temp > wMaxPacketSize) {
523 wMaxPacketSize = temp;
529 /* Set alt configuration on interface #1 only if we found it */
530 if (wMaxPacketSize > 0 &&
531 usb2_set_alt_interface_index(uaa->device, 1, alt_index)) {
532 UBT_ALERT(sc, "could not set alternate setting %d " \
533 "for interface 1!\n", alt_index);
537 /* Setup transfers for both interfaces */
538 if (usb2_transfer_setup(uaa->device, iface_index, sc->sc_xfer,
539 ubt_config, UBT_N_TRANSFER, sc, &sc->sc_if_mtx)) {
540 UBT_ALERT(sc, "could not allocate transfers\n");
544 /* Claim all interfaces on the device */
545 for (i = 1; usb2_get_iface(uaa->device, i) != NULL; i ++)
546 usb2_set_parent_iface(uaa->device, i, uaa->info.bIfaceIndex);
548 return (0); /* success */
562 ubt_detach(device_t dev)
564 struct ubt_softc *sc = device_get_softc(dev);
565 node_p node = sc->sc_node;
567 /* Destroy Netgraph node */
570 NG_NODE_REALLY_DIE(node);
571 ng_rmnode_self(node);
574 /* Make sure ubt_task in gone */
575 taskqueue_drain(taskqueue_swi, &sc->sc_task);
577 /* Free USB transfers, if any */
578 usb2_transfer_unsetup(sc->sc_xfer, UBT_N_TRANSFER);
582 NG_BT_MBUFQ_DESTROY(&sc->sc_cmdq);
583 NG_BT_MBUFQ_DESTROY(&sc->sc_aclq);
584 NG_BT_MBUFQ_DESTROY(&sc->sc_scoq);
587 mtx_destroy(&sc->sc_if_mtx);
588 mtx_destroy(&sc->sc_ng_mtx);
594 * Called when outgoing control request (HCI command) has completed, i.e.
595 * HCI command was sent to the device.
600 ubt_ctrl_write_callback(struct usb_xfer *xfer)
602 struct ubt_softc *sc = xfer->priv_sc;
603 struct usb_device_request req;
606 switch (USB_GET_STATE(xfer)) {
607 case USB_ST_TRANSFERRED:
608 UBT_INFO(sc, "sent %d bytes to control pipe\n", xfer->actlen);
609 UBT_STAT_BYTES_SENT(sc, xfer->actlen);
610 UBT_STAT_PCKTS_SENT(sc);
615 /* Get next command mbuf, if any */
617 NG_BT_MBUFQ_DEQUEUE(&sc->sc_cmdq, m);
621 UBT_INFO(sc, "HCI command queue is empty\n");
622 break; /* transfer complete */
625 /* Initialize a USB control request and then schedule it */
626 bzero(&req, sizeof(req));
627 req.bmRequestType = UBT_HCI_REQUEST;
628 USETW(req.wLength, m->m_pkthdr.len);
630 UBT_INFO(sc, "Sending control request, " \
631 "bmRequestType=0x%02x, wLength=%d\n",
632 req.bmRequestType, UGETW(req.wLength));
634 usb2_copy_in(xfer->frbuffers, 0, &req, sizeof(req));
635 usb2_m_copy_in(xfer->frbuffers + 1, 0, m, 0, m->m_pkthdr.len);
637 xfer->frlengths[0] = sizeof(req);
638 xfer->frlengths[1] = m->m_pkthdr.len;
643 usb2_start_hardware(xfer);
647 if (xfer->error != USB_ERR_CANCELLED) {
648 UBT_WARN(sc, "control transfer failed: %s\n",
649 usb2_errstr(xfer->error));
655 /* transfer cancelled */
658 } /* ubt_ctrl_write_callback */
661 * Called when incoming interrupt transfer (HCI event) has completed, i.e.
662 * HCI event was received from the device.
667 ubt_intr_read_callback(struct usb_xfer *xfer)
669 struct ubt_softc *sc = xfer->priv_sc;
671 ng_hci_event_pkt_t *hdr;
675 switch (USB_GET_STATE(xfer)) {
676 case USB_ST_TRANSFERRED:
677 /* Allocate a new mbuf */
678 MGETHDR(m, M_DONTWAIT, MT_DATA);
684 MCLGET(m, M_DONTWAIT);
685 if (!(m->m_flags & M_EXT)) {
690 /* Add HCI packet type */
691 *mtod(m, uint8_t *)= NG_HCI_EVENT_PKT;
692 m->m_pkthdr.len = m->m_len = 1;
694 if (xfer->actlen > MCLBYTES - 1)
695 xfer->actlen = MCLBYTES - 1;
697 usb2_copy_out(xfer->frbuffers, 0, mtod(m, uint8_t *) + 1,
699 m->m_pkthdr.len += xfer->actlen;
700 m->m_len += xfer->actlen;
702 UBT_INFO(sc, "got %d bytes from interrupt pipe\n",
705 /* Validate packet and send it up the stack */
706 if (m->m_pkthdr.len < sizeof(*hdr)) {
707 UBT_INFO(sc, "HCI event packet is too short\n");
713 hdr = mtod(m, ng_hci_event_pkt_t *);
714 if (hdr->length != (m->m_pkthdr.len - sizeof(*hdr))) {
715 UBT_ERR(sc, "Invalid HCI event packet size, " \
716 "length=%d, pktlen=%d\n",
717 hdr->length, m->m_pkthdr.len);
723 UBT_INFO(sc, "got complete HCI event frame, pktlen=%d, " \
724 "length=%d\n", m->m_pkthdr.len, hdr->length);
726 UBT_STAT_PCKTS_RECV(sc);
727 UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
729 ubt_fwd_mbuf_up(sc, &m);
730 /* m == NULL at this point */
735 NG_FREE_M(m); /* checks for m != NULL */
737 xfer->frlengths[0] = xfer->max_data_length;
738 usb2_start_hardware(xfer);
742 if (xfer->error != USB_ERR_CANCELLED) {
743 UBT_WARN(sc, "interrupt transfer failed: %s\n",
744 usb2_errstr(xfer->error));
746 /* Try to clear stall first */
747 xfer->flags.stall_pipe = 1;
750 /* transfer cancelled */
753 } /* ubt_intr_read_callback */
756 * Called when incoming bulk transfer (ACL packet) has completed, i.e.
757 * ACL packet was received from the device.
762 ubt_bulk_read_callback(struct usb_xfer *xfer)
764 struct ubt_softc *sc = xfer->priv_sc;
766 ng_hci_acldata_pkt_t *hdr;
771 switch (USB_GET_STATE(xfer)) {
772 case USB_ST_TRANSFERRED:
773 /* Allocate new mbuf */
774 MGETHDR(m, M_DONTWAIT, MT_DATA);
780 MCLGET(m, M_DONTWAIT);
781 if (!(m->m_flags & M_EXT)) {
786 /* Add HCI packet type */
787 *mtod(m, uint8_t *)= NG_HCI_ACL_DATA_PKT;
788 m->m_pkthdr.len = m->m_len = 1;
790 if (xfer->actlen > MCLBYTES - 1)
791 xfer->actlen = MCLBYTES - 1;
793 usb2_copy_out(xfer->frbuffers, 0, mtod(m, uint8_t *) + 1,
795 m->m_pkthdr.len += xfer->actlen;
796 m->m_len += xfer->actlen;
798 UBT_INFO(sc, "got %d bytes from bulk-in pipe\n",
801 /* Validate packet and send it up the stack */
802 if (m->m_pkthdr.len < sizeof(*hdr)) {
803 UBT_INFO(sc, "HCI ACL packet is too short\n");
809 hdr = mtod(m, ng_hci_acldata_pkt_t *);
810 len = le16toh(hdr->length);
811 if (len != (m->m_pkthdr.len - sizeof(*hdr))) {
812 UBT_ERR(sc, "Invalid ACL packet size, length=%d, " \
813 "pktlen=%d\n", len, m->m_pkthdr.len);
819 UBT_INFO(sc, "got complete ACL data packet, pktlen=%d, " \
820 "length=%d\n", m->m_pkthdr.len, len);
822 UBT_STAT_PCKTS_RECV(sc);
823 UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
825 ubt_fwd_mbuf_up(sc, &m);
826 /* m == NULL at this point */
831 NG_FREE_M(m); /* checks for m != NULL */
833 xfer->frlengths[0] = xfer->max_data_length;
834 usb2_start_hardware(xfer);
838 if (xfer->error != USB_ERR_CANCELLED) {
839 UBT_WARN(sc, "bulk-in transfer failed: %s\n",
840 usb2_errstr(xfer->error));
842 /* Try to clear stall first */
843 xfer->flags.stall_pipe = 1;
846 /* transfer cancelled */
849 } /* ubt_bulk_read_callback */
852 * Called when outgoing bulk transfer (ACL packet) has completed, i.e.
853 * ACL packet was sent to the device.
858 ubt_bulk_write_callback(struct usb_xfer *xfer)
860 struct ubt_softc *sc = xfer->priv_sc;
863 switch (USB_GET_STATE(xfer)) {
864 case USB_ST_TRANSFERRED:
865 UBT_INFO(sc, "sent %d bytes to bulk-out pipe\n", xfer->actlen);
866 UBT_STAT_BYTES_SENT(sc, xfer->actlen);
867 UBT_STAT_PCKTS_SENT(sc);
872 /* Get next mbuf, if any */
874 NG_BT_MBUFQ_DEQUEUE(&sc->sc_aclq, m);
878 UBT_INFO(sc, "ACL data queue is empty\n");
879 break; /* transfer completed */
883 * Copy ACL data frame back to a linear USB transfer buffer
884 * and schedule transfer
887 usb2_m_copy_in(xfer->frbuffers, 0, m, 0, m->m_pkthdr.len);
888 xfer->frlengths[0] = m->m_pkthdr.len;
890 UBT_INFO(sc, "bulk-out transfer has been started, len=%d\n",
895 usb2_start_hardware(xfer);
899 if (xfer->error != USB_ERR_CANCELLED) {
900 UBT_WARN(sc, "bulk-out transfer failed: %s\n",
901 usb2_errstr(xfer->error));
905 /* try to clear stall first */
906 xfer->flags.stall_pipe = 1;
909 /* transfer cancelled */
912 } /* ubt_bulk_write_callback */
915 * Called when incoming isoc transfer (SCO packet) has completed, i.e.
916 * SCO packet was received from the device.
921 ubt_isoc_read_callback(struct usb_xfer *xfer)
923 struct ubt_softc *sc = xfer->priv_sc;
926 switch (USB_GET_STATE(xfer)) {
927 case USB_ST_TRANSFERRED:
928 for (n = 0; n < xfer->nframes; n ++)
929 if (ubt_isoc_read_one_frame(xfer, n) < 0)
935 for (n = 0; n < xfer->nframes; n ++)
936 xfer->frlengths[n] = xfer->max_frame_size;
938 usb2_start_hardware(xfer);
942 if (xfer->error != USB_ERR_CANCELLED) {
947 /* transfer cancelled */
950 } /* ubt_isoc_read_callback */
953 * Helper function. Called from ubt_isoc_read_callback() to read
954 * SCO data from one frame.
959 ubt_isoc_read_one_frame(struct usb_xfer *xfer, int frame_no)
961 struct ubt_softc *sc = xfer->priv_sc;
965 /* Get existing SCO reassembly buffer */
966 m = sc->sc_isoc_in_buffer;
967 sc->sc_isoc_in_buffer = NULL;
969 /* While we have data in the frame */
970 while ((len = xfer->frlengths[frame_no]) > 0) {
972 /* Start new reassembly buffer */
973 MGETHDR(m, M_DONTWAIT, MT_DATA);
976 return (-1); /* XXX out of sync! */
979 MCLGET(m, M_DONTWAIT);
980 if (!(m->m_flags & M_EXT)) {
983 return (-1); /* XXX out of sync! */
986 /* Expect SCO header */
987 *mtod(m, uint8_t *) = NG_HCI_SCO_DATA_PKT;
988 m->m_pkthdr.len = m->m_len = got = 1;
989 want = sizeof(ng_hci_scodata_pkt_t);
992 * Check if we have SCO header and if so
993 * adjust amount of data we want
995 got = m->m_pkthdr.len;
996 want = sizeof(ng_hci_scodata_pkt_t);
999 want += mtod(m, ng_hci_scodata_pkt_t *)->length;
1002 /* Append frame data to the SCO reassembly buffer */
1003 if (got + len > want)
1006 usb2_copy_out(xfer->frbuffers, frame_no * xfer->max_frame_size,
1007 mtod(m, uint8_t *) + m->m_pkthdr.len, len);
1009 m->m_pkthdr.len += len;
1011 xfer->frlengths[frame_no] -= len;
1013 /* Check if we got everything we wanted, if not - continue */
1017 /* If we got here then we got complete SCO frame */
1018 UBT_INFO(sc, "got complete SCO data frame, pktlen=%d, " \
1019 "length=%d\n", m->m_pkthdr.len,
1020 mtod(m, ng_hci_scodata_pkt_t *)->length);
1022 UBT_STAT_PCKTS_RECV(sc);
1023 UBT_STAT_BYTES_RECV(sc, m->m_pkthdr.len);
1025 ubt_fwd_mbuf_up(sc, &m);
1026 /* m == NULL at this point */
1029 /* Put SCO reassembly buffer back */
1030 sc->sc_isoc_in_buffer = m;
1033 } /* ubt_isoc_read_one_frame */
1036 * Called when outgoing isoc transfer (SCO packet) has completed, i.e.
1037 * SCO packet was sent to the device.
1042 ubt_isoc_write_callback(struct usb_xfer *xfer)
1044 struct ubt_softc *sc = xfer->priv_sc;
1046 int n, space, offset;
1048 switch (USB_GET_STATE(xfer)) {
1049 case USB_ST_TRANSFERRED:
1050 UBT_INFO(sc, "sent %d bytes to isoc-out pipe\n", xfer->actlen);
1051 UBT_STAT_BYTES_SENT(sc, xfer->actlen);
1052 UBT_STAT_PCKTS_SENT(sc);
1058 space = xfer->max_frame_size * xfer->nframes;
1064 NG_BT_MBUFQ_DEQUEUE(&sc->sc_scoq, m);
1071 n = min(space, m->m_pkthdr.len);
1073 usb2_m_copy_in(xfer->frbuffers, offset, m,0, n);
1080 if (m->m_pkthdr.len == 0)
1081 NG_FREE_M(m); /* sets m = NULL */
1084 /* Put whatever is left from mbuf back on queue */
1087 NG_BT_MBUFQ_PREPEND(&sc->sc_scoq, m);
1092 * Calculate sizes for isoc frames.
1093 * Note that offset could be 0 at this point (i.e. we have
1094 * nothing to send). That is fine, as we have isoc. transfers
1095 * going in both directions all the time. In this case it
1096 * would be just empty isoc. transfer.
1099 for (n = 0; n < xfer->nframes; n ++) {
1100 xfer->frlengths[n] = min(offset, xfer->max_frame_size);
1101 offset -= xfer->frlengths[n];
1104 usb2_start_hardware(xfer);
1107 default: /* Error */
1108 if (xfer->error != USB_ERR_CANCELLED) {
1109 UBT_STAT_OERROR(sc);
1113 /* transfer cancelled */
1119 * Utility function to forward provided mbuf upstream (i.e. up the stack).
1120 * Modifies value of the mbuf pointer (sets it to NULL).
1121 * Save to call from any context.
1125 ubt_fwd_mbuf_up(ubt_softc_p sc, struct mbuf **m)
1131 * Close the race with Netgraph hook newhook/disconnect methods.
1132 * Save the hook pointer atomically. Two cases are possible:
1134 * 1) The hook pointer is NULL. It means disconnect method got
1135 * there first. In this case we are done.
1137 * 2) The hook pointer is not NULL. It means that hook pointer
1138 * could be either in valid or invalid (i.e. in the process
1139 * of disconnect) state. In any case grab an extra reference
1140 * to protect the hook pointer.
1142 * It is ok to pass hook in invalid state to NG_SEND_DATA_ONLY() as
1143 * it checks for it. Drop extra reference after NG_SEND_DATA_ONLY().
1147 if ((hook = sc->sc_hook) != NULL)
1156 NG_SEND_DATA_ONLY(error, hook, *m);
1157 NG_HOOK_UNREF(hook);
1160 UBT_STAT_IERROR(sc);
1163 } /* ubt_fwd_mbuf_up */
1165 /****************************************************************************
1166 ****************************************************************************
1168 ****************************************************************************
1169 ****************************************************************************/
1172 * Schedule glue task. Should be called with sc_ng_mtx held.
1177 ubt_task_schedule(ubt_softc_p sc, int action)
1179 mtx_assert(&sc->sc_ng_mtx, MA_OWNED);
1182 * Try to handle corner case when "start all" and "stop all"
1183 * actions can both be set before task is executed.
1187 * sc_task_flags action new sc_task_flags
1188 * ------------------------------------------------------
1193 * stop start stop|start
1195 * stop|start start stop|start
1196 * stop|start stop stop
1200 if ((action & UBT_FLAG_T_STOP_ALL) != 0)
1201 sc->sc_task_flags &= ~UBT_FLAG_T_START_ALL;
1203 sc->sc_task_flags |= action;
1206 if (sc->sc_task_flags & UBT_FLAG_T_PENDING)
1209 if (taskqueue_enqueue(taskqueue_swi, &sc->sc_task) == 0) {
1210 sc->sc_task_flags |= UBT_FLAG_T_PENDING;
1214 /* XXX: i think this should never happen */
1215 } /* ubt_task_schedule */
1218 * Glue task. Examines sc_task_flags and does things depending on it.
1219 * Taskqueue context.
1223 ubt_task(void *context, int pending)
1225 ubt_softc_p sc = context;
1229 task_flags = sc->sc_task_flags;
1230 sc->sc_task_flags = 0;
1234 * Stop all USB transfers synchronously.
1235 * Stop interface #0 and #1 transfers at the same time and in the
1236 * same loop. usb2_transfer_drain() will do appropriate locking.
1239 if (task_flags & UBT_FLAG_T_STOP_ALL)
1240 for (i = 0; i < UBT_N_TRANSFER; i ++)
1241 usb2_transfer_drain(sc->sc_xfer[i]);
1243 /* Start incoming interrupt and bulk, and all isoc. USB transfers */
1244 if (task_flags & UBT_FLAG_T_START_ALL) {
1249 mtx_lock(&sc->sc_if_mtx);
1251 ubt_xfer_start(sc, UBT_IF_0_INTR_DT_RD);
1252 ubt_xfer_start(sc, UBT_IF_0_BULK_DT_RD);
1256 * Start both read and write isoc. transfers by default.
1257 * Get them going all the time even if we have nothing
1258 * to send to avoid any delays.
1261 ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_RD1);
1262 ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_RD2);
1263 ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_WR1);
1264 ubt_xfer_start(sc, UBT_IF_1_ISOC_DT_WR2);
1266 mtx_unlock(&sc->sc_if_mtx);
1269 /* Start outgoing control transfer */
1270 if (task_flags & UBT_FLAG_T_START_CTRL) {
1271 mtx_lock(&sc->sc_if_mtx);
1272 ubt_xfer_start(sc, UBT_IF_0_CTRL_DT_WR);
1273 mtx_unlock(&sc->sc_if_mtx);
1276 /* Start outgoing bulk transfer */
1277 if (task_flags & UBT_FLAG_T_START_BULK) {
1278 mtx_lock(&sc->sc_if_mtx);
1279 ubt_xfer_start(sc, UBT_IF_0_BULK_DT_WR);
1280 mtx_unlock(&sc->sc_if_mtx);
1284 /****************************************************************************
1285 ****************************************************************************
1286 ** Netgraph specific
1287 ****************************************************************************
1288 ****************************************************************************/
1291 * Netgraph node constructor. Do not allow to create node of this type.
1296 ng_ubt_constructor(node_p node)
1299 } /* ng_ubt_constructor */
1302 * Netgraph node destructor. Destroy node only when device has been detached.
1307 ng_ubt_shutdown(node_p node)
1309 if (node->nd_flags & NGF_REALLY_DIE) {
1311 * We came here because the USB device is being
1312 * detached, so stop being persistant.
1314 NG_NODE_SET_PRIVATE(node, NULL);
1315 NG_NODE_UNREF(node);
1317 NG_NODE_REVIVE(node); /* tell ng_rmnode we are persisant */
1320 } /* ng_ubt_shutdown */
1323 * Create new hook. There can only be one.
1328 ng_ubt_newhook(node_p node, hook_p hook, char const *name)
1330 struct ubt_softc *sc = NG_NODE_PRIVATE(node);
1332 if (strcmp(name, NG_UBT_HOOK) != 0)
1336 if (sc->sc_hook != NULL) {
1346 } /* ng_ubt_newhook */
1349 * Connect hook. Start incoming USB transfers.
1354 ng_ubt_connect(hook_p hook)
1356 struct ubt_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1358 NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
1361 ubt_task_schedule(sc, UBT_FLAG_T_START_ALL);
1365 } /* ng_ubt_connect */
1373 ng_ubt_disconnect(hook_p hook)
1375 struct ubt_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1379 if (hook != sc->sc_hook) {
1387 /* Kick off task to stop all USB xfers */
1388 ubt_task_schedule(sc, UBT_FLAG_T_STOP_ALL);
1391 NG_BT_MBUFQ_DRAIN(&sc->sc_cmdq);
1392 NG_BT_MBUFQ_DRAIN(&sc->sc_aclq);
1393 NG_BT_MBUFQ_DRAIN(&sc->sc_scoq);
1398 } /* ng_ubt_disconnect */
1401 * Process control message.
1406 ng_ubt_rcvmsg(node_p node, item_p item, hook_p lasthook)
1408 struct ubt_softc *sc = NG_NODE_PRIVATE(node);
1409 struct ng_mesg *msg, *rsp = NULL;
1410 struct ng_bt_mbufq *q;
1411 int error = 0, queue, qlen;
1413 NGI_GET_MSG(item, msg);
1415 switch (msg->header.typecookie) {
1416 case NGM_GENERIC_COOKIE:
1417 switch (msg->header.cmd) {
1418 case NGM_TEXT_STATUS:
1419 NG_MKRESPONSE(rsp, msg, NG_TEXTRESPONSE, M_NOWAIT);
1425 snprintf(rsp->data, NG_TEXTRESPONSE,
1427 "Task flags: %#x\n" \
1429 "CMD queue: [have:%d,max:%d]\n" \
1430 "ACL queue: [have:%d,max:%d]\n" \
1431 "SCO queue: [have:%d,max:%d]",
1432 (sc->sc_hook != NULL) ? NG_UBT_HOOK : "",
1440 sc->sc_scoq.maxlen);
1449 case NGM_UBT_COOKIE:
1450 switch (msg->header.cmd) {
1451 case NGM_UBT_NODE_SET_DEBUG:
1452 if (msg->header.arglen != sizeof(ng_ubt_node_debug_ep)){
1457 sc->sc_debug = *((ng_ubt_node_debug_ep *) (msg->data));
1460 case NGM_UBT_NODE_GET_DEBUG:
1461 NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_debug_ep),
1468 *((ng_ubt_node_debug_ep *) (rsp->data)) = sc->sc_debug;
1471 case NGM_UBT_NODE_SET_QLEN:
1472 if (msg->header.arglen != sizeof(ng_ubt_node_qlen_ep)) {
1477 queue = ((ng_ubt_node_qlen_ep *) (msg->data))->queue;
1478 qlen = ((ng_ubt_node_qlen_ep *) (msg->data))->qlen;
1481 case NGM_UBT_NODE_QUEUE_CMD:
1485 case NGM_UBT_NODE_QUEUE_ACL:
1489 case NGM_UBT_NODE_QUEUE_SCO:
1502 case NGM_UBT_NODE_GET_QLEN:
1503 if (msg->header.arglen != sizeof(ng_ubt_node_qlen_ep)) {
1508 queue = ((ng_ubt_node_qlen_ep *) (msg->data))->queue;
1511 case NGM_UBT_NODE_QUEUE_CMD:
1515 case NGM_UBT_NODE_QUEUE_ACL:
1519 case NGM_UBT_NODE_QUEUE_SCO:
1529 NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_qlen_ep),
1536 ((ng_ubt_node_qlen_ep *) (rsp->data))->queue = queue;
1537 ((ng_ubt_node_qlen_ep *) (rsp->data))->qlen = q->maxlen;
1540 case NGM_UBT_NODE_GET_STAT:
1541 NG_MKRESPONSE(rsp, msg, sizeof(ng_ubt_node_stat_ep),
1548 bcopy(&sc->sc_stat, rsp->data,
1549 sizeof(ng_ubt_node_stat_ep));
1552 case NGM_UBT_NODE_RESET_STAT:
1567 NG_RESPOND_MSG(error, node, item, rsp);
1571 } /* ng_ubt_rcvmsg */
1579 ng_ubt_rcvdata(hook_p hook, item_p item)
1581 struct ubt_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
1583 struct ng_bt_mbufq *q;
1584 int action, error = 0;
1586 if (hook != sc->sc_hook) {
1591 /* Deatch mbuf and get HCI frame type */
1595 * Minimal size of the HCI frame is 4 bytes: 1 byte frame type,
1596 * 2 bytes connection handle and at least 1 byte of length.
1597 * Panic on data frame that has size smaller than 4 bytes (it
1598 * should not happen)
1601 if (m->m_pkthdr.len < 4)
1602 panic("HCI frame size is too small! pktlen=%d\n",
1605 /* Process HCI frame */
1606 switch (*mtod(m, uint8_t *)) { /* XXX call m_pullup ? */
1607 case NG_HCI_CMD_PKT:
1608 if (m->m_pkthdr.len - 1 > UBT_CTRL_BUFFER_SIZE)
1609 panic("HCI command frame size is too big! " \
1610 "buffer size=%zd, packet len=%d\n",
1611 UBT_CTRL_BUFFER_SIZE, m->m_pkthdr.len);
1614 action = UBT_FLAG_T_START_CTRL;
1617 case NG_HCI_ACL_DATA_PKT:
1618 if (m->m_pkthdr.len - 1 > UBT_BULK_WRITE_BUFFER_SIZE)
1619 panic("ACL data frame size is too big! " \
1620 "buffer size=%d, packet len=%d\n",
1621 UBT_BULK_WRITE_BUFFER_SIZE, m->m_pkthdr.len);
1624 action = UBT_FLAG_T_START_BULK;
1627 case NG_HCI_SCO_DATA_PKT:
1633 UBT_ERR(sc, "Dropping unsupported HCI frame, type=0x%02x, " \
1634 "pktlen=%d\n", *mtod(m, uint8_t *), m->m_pkthdr.len);
1643 if (NG_BT_MBUFQ_FULL(q)) {
1644 NG_BT_MBUFQ_DROP(q);
1647 UBT_ERR(sc, "Dropping HCI frame 0x%02x, len=%d. Queue full\n",
1648 *mtod(m, uint8_t *), m->m_pkthdr.len);
1652 /* Loose HCI packet type, enqueue mbuf and kick off task */
1653 m_adj(m, sizeof(uint8_t));
1654 NG_BT_MBUFQ_ENQUEUE(q, m);
1655 ubt_task_schedule(sc, action);
1662 } /* ng_ubt_rcvdata */
1664 /****************************************************************************
1665 ****************************************************************************
1667 ****************************************************************************
1668 ****************************************************************************/
1671 * Load/Unload the driver module
1675 ubt_modevent(module_t mod, int event, void *data)
1681 error = ng_newtype(&typestruct);
1683 printf("%s: Could not register Netgraph node type, " \
1684 "error=%d\n", NG_UBT_NODE_TYPE, error);
1688 error = ng_rmtype(&typestruct);
1697 } /* ubt_modevent */
1699 static devclass_t ubt_devclass;
1701 static device_method_t ubt_methods[] =
1703 DEVMETHOD(device_probe, ubt_probe),
1704 DEVMETHOD(device_attach, ubt_attach),
1705 DEVMETHOD(device_detach, ubt_detach),
1709 static driver_t ubt_driver =
1712 .methods = ubt_methods,
1713 .size = sizeof(struct ubt_softc),
1716 DRIVER_MODULE(ng_ubt, uhub, ubt_driver, ubt_devclass, ubt_modevent, 0);
1717 MODULE_VERSION(ng_ubt, NG_BLUETOOTH_VERSION);
1718 MODULE_DEPEND(ng_ubt, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
1719 MODULE_DEPEND(ng_ubt, ng_hci, NG_BLUETOOTH_VERSION, NG_BLUETOOTH_VERSION, NG_BLUETOOTH_VERSION);
1720 MODULE_DEPEND(ng_ubt, usb, 1, 1, 1);