xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision bc37f7b0d0a3eaa5763a873c5730bc14b849aaa0)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  hci_transport_usb.c
40  *
41  *  HCI Transport API implementation for USB
42  *
43  *  Created by Matthias Ringwald on 7/5/09.
44  */
45 
46 // Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size
47 // HCI Commands 0 0 0x00 Control 8/16/32/64
48 // HCI Events   0 0 0x81 Interrupt (IN) 16
49 // ACL Data     0 0 0x82 Bulk (IN) 32/64
50 // ACL Data     0 0 0x02 Bulk (OUT) 32/64
51 // SCO Data     0 0 0x83 Isochronous (IN)
52 // SCO Data     0 0 0x03 Isochronous (Out)
53 
54 #include <stdio.h>
55 #include <strings.h>
56 #include <string.h>
57 #include <unistd.h>   /* UNIX standard function definitions */
58 #include <sys/types.h>
59 
60 #include <libusb.h>
61 
62 #include "btstack_config.h"
63 
64 #include "btstack_debug.h"
65 #include "hci.h"
66 #include "hci_transport.h"
67 
68 #if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0)
69 #define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
70 #endif
71 
72 #define ASYNC_BUFFERS  3
73 #define ISOC_BUFFERS  10
74 
75 #define ASYNC_POLLING_INTERVAL_MS 1
76 
77 //
78 // Bluetooth USB Transport Alternate Settings:
79 //
80 // 0: No active voice channels (for USB compliance)
81 // 1: One 8 kHz voice channel with 8-bit encoding
82 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
83 // 3: Three 8 kHz voice channels with 8-bit encoding
84 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
85 // 5: Three 8 kHz voice channels with 16-bit encoding or one 8 kHz voice channel with 16-bit encoding and one 16 kHz voice channel with 16-bit encoding
86 // --> support only a single SCO connection
87 #define ALT_SETTING (2)
88 
89 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
90 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
91 #define NUM_ISO_PACKETS (3)
92 // results in 9 bytes per frame
93 #define ISO_PACKET_SIZE (9)
94 
95 // 49 bytes is the max usb packet size for alternate setting 5 (Three 8 kHz 16-bit channels or one 8 kHz 16-bit channel and one 16 kHz 16-bit channel)
96 // note: alt setting 6 has max packet size of 63 every 7.5 ms = 472.5 bytes / HCI packet, while max SCO packet has 255 byte payload
97 #define SCO_PACKET_SIZE  (49)
98 
99 // Outgoing SCO packet queue
100 // simplified ring buffer implementation
101 #define SCO_RING_BUFFER_COUNT  (8)
102 #define SCO_RING_BUFFER_SIZE (SCO_RING_BUFFER_COUNT * SCO_PACKET_SIZE)
103 
104 // seems to be the max depth for USB 3
105 #define USB_MAX_PATH_LEN 7
106 
107 // prototypes
108 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
109 static int usb_close(void);
110 
111 typedef enum {
112     LIB_USB_CLOSED = 0,
113     LIB_USB_OPENED,
114     LIB_USB_DEVICE_OPENDED,
115     LIB_USB_INTERFACE_CLAIMED,
116     LIB_USB_TRANSFERS_ALLOCATED
117 } libusb_state_t;
118 
119 // SCO packet state machine
120 typedef enum {
121     H2_W4_SCO_HEADER = 1,
122     H2_W4_PAYLOAD,
123 } H2_SCO_STATE;
124 
125 static libusb_state_t libusb_state = LIB_USB_CLOSED;
126 
127 // single instance
128 static hci_transport_t * hci_transport_usb = NULL;
129 
130 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
131 
132 // libusb
133 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
134 static struct libusb_device_descriptor desc;
135 static libusb_device        * dev;
136 #endif
137 static libusb_device_handle * handle;
138 
139 static struct libusb_transfer *command_out_transfer;
140 static struct libusb_transfer *acl_out_transfer;
141 static struct libusb_transfer *event_in_transfer[ASYNC_BUFFERS];
142 static struct libusb_transfer *acl_in_transfer[ASYNC_BUFFERS];
143 
144 #ifdef ENABLE_SCO_OVER_HCI
145 
146 #ifdef _WIN32
147 #error "SCO not working on Win32 (Windows 8, libusb 1.0.19, Zadic WinUSB), please uncomment ENABLE_SCO_OVER_HCI in btstack-config.h for now"
148 #endif
149 
150 // incoming SCO
151 static H2_SCO_STATE sco_state;
152 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
153 static uint16_t sco_read_pos;
154 static uint16_t sco_bytes_to_read;
155 static struct  libusb_transfer *sco_in_transfer[ISOC_BUFFERS];
156 static uint8_t hci_sco_in_buffer[ISOC_BUFFERS][SCO_PACKET_SIZE];
157 
158 // outgoing SCO
159 static uint8_t  sco_ring_buffer[SCO_RING_BUFFER_SIZE];
160 static int      sco_ring_write;  // packet idx
161 static int      sco_ring_transfers_active;
162 static struct libusb_transfer *sco_ring_transfers[SCO_RING_BUFFER_COUNT];
163 #endif
164 
165 // outgoing buffer for HCI Command packets
166 static uint8_t hci_cmd_buffer[3 + 256 + LIBUSB_CONTROL_SETUP_SIZE];
167 
168 // incoming buffer for HCI Events and ACL Packets
169 static uint8_t hci_event_in_buffer[ASYNC_BUFFERS][HCI_ACL_BUFFER_SIZE]; // bigger than largest packet
170 static uint8_t hci_acl_in_buffer[ASYNC_BUFFERS][HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
171 
172 // For (ab)use as a linked list of received packets
173 static struct libusb_transfer *handle_packet;
174 
175 static int doing_pollfds;
176 static int num_pollfds;
177 static btstack_data_source_t * pollfd_data_sources;
178 static btstack_timer_source_t usb_timer;
179 static int usb_timer_active;
180 
181 static int usb_acl_out_active = 0;
182 static int usb_command_active = 0;
183 
184 // endpoint addresses
185 static int event_in_addr;
186 static int acl_in_addr;
187 static int acl_out_addr;
188 static int sco_in_addr;
189 static int sco_out_addr;
190 
191 // device path
192 static int usb_path_len;
193 static uint8_t usb_path[USB_MAX_PATH_LEN];
194 
195 
196 #ifdef ENABLE_SCO_OVER_HCI
197 static void sco_ring_init(void){
198     sco_ring_write = 0;
199     sco_ring_transfers_active = 0;
200 }
201 static int sco_ring_have_space(void){
202     return sco_ring_transfers_active < SCO_RING_BUFFER_COUNT;
203 }
204 #endif
205 
206 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
207     if (len > USB_MAX_PATH_LEN || !port_numbers){
208         log_error("hci_transport_usb_set_path: len or port numbers invalid");
209         return;
210     }
211     usb_path_len = len;
212     memcpy(usb_path, port_numbers, len);
213 }
214 
215 //
216 static void queue_transfer(struct libusb_transfer *transfer){
217 
218     // log_info("queue_transfer %p, endpoint %x size %u", transfer, transfer->endpoint, transfer->actual_length);
219 
220     transfer->user_data = NULL;
221 
222     // insert first element
223     if (handle_packet == NULL) {
224         handle_packet = transfer;
225         return;
226     }
227 
228     // Walk to end of list and add current packet there
229     struct libusb_transfer *temp = handle_packet;
230     while (temp->user_data) {
231         temp = (struct libusb_transfer*)temp->user_data;
232     }
233     temp->user_data = transfer;
234 }
235 
236 static void async_callback(struct libusb_transfer *transfer)
237 {
238     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED)  return;
239     int r;
240     // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
241 
242     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
243         queue_transfer(transfer);
244     } else if (transfer->status == LIBUSB_TRANSFER_STALL){
245         log_info("-> Transfer stalled, trying again");
246         r = libusb_clear_halt(handle, transfer->endpoint);
247         if (r) {
248             log_error("Error rclearing halt %d", r);
249         }
250         r = libusb_submit_transfer(transfer);
251         if (r) {
252             log_error("Error re-submitting transfer %d", r);
253         }
254     } else {
255         log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
256         // No usable data, just resubmit packet
257         r = libusb_submit_transfer(transfer);
258         if (r) {
259             log_error("Error re-submitting transfer %d", r);
260         }
261     }
262     // log_info("end async_callback");
263 }
264 
265 
266 #ifdef ENABLE_SCO_OVER_HCI
267 static int usb_send_sco_packet(uint8_t *packet, int size){
268     int r;
269 
270     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
271 
272     // log_info("usb_send_acl_packet enter, size %u", size);
273 
274     // store packet in free slot
275     int tranfer_index = sco_ring_write;
276     uint8_t * data = &sco_ring_buffer[tranfer_index * SCO_PACKET_SIZE];
277     memcpy(data, packet, size);
278 
279     // setup transfer
280     struct libusb_transfer * sco_transfer = sco_ring_transfers[tranfer_index];
281     libusb_fill_iso_transfer(sco_transfer, handle, sco_out_addr, data, size, NUM_ISO_PACKETS, async_callback, NULL, 0);
282     libusb_set_iso_packet_lengths(sco_transfer, ISO_PACKET_SIZE);
283     r = libusb_submit_transfer(sco_transfer);
284     if (r < 0) {
285         log_error("Error submitting sco transfer, %d", r);
286         return -1;
287     }
288 
289     // mark slot as full
290     sco_ring_write++;
291     if (sco_ring_write == SCO_RING_BUFFER_COUNT){
292         sco_ring_write = 0;
293     }
294     sco_ring_transfers_active++;
295 
296     // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_ring_transfers_active);
297 
298     // notify upper stack that provided buffer can be used again
299     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
300     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
301 
302     // and if we have more space for SCO packets
303     if (sco_ring_have_space()) {
304         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
305         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
306     }
307     return 0;
308 }
309 
310 static void sco_state_machine_init(void){
311     sco_state = H2_W4_SCO_HEADER;
312     sco_read_pos = 0;
313     sco_bytes_to_read = 3;
314 }
315 
316 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
317     while (size){
318         if (size < sco_bytes_to_read){
319             // just store incomplete data
320             memcpy(&sco_buffer[sco_read_pos], buffer, size);
321             sco_read_pos      += size;
322             sco_bytes_to_read -= size;
323             return;
324         }
325         // copy requested data
326         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
327         sco_read_pos += sco_bytes_to_read;
328         buffer       += sco_bytes_to_read;
329         size         -= sco_bytes_to_read;
330 
331         // chunk read successfully, next action
332         switch (sco_state){
333             case H2_W4_SCO_HEADER:
334                 sco_state = H2_W4_PAYLOAD;
335                 sco_bytes_to_read = sco_buffer[2];
336                 break;
337             case H2_W4_PAYLOAD:
338                 // packet complete
339                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
340                 sco_state_machine_init();
341                 break;
342         }
343     }
344 }
345 #endif
346 
347 static void handle_completed_transfer(struct libusb_transfer *transfer){
348 
349     int resubmit = 0;
350     int signal_done = 0;
351 
352     if (transfer->endpoint == event_in_addr) {
353         packet_handler(HCI_EVENT_PACKET, transfer-> buffer, transfer->actual_length);
354         resubmit = 1;
355     } else if (transfer->endpoint == acl_in_addr) {
356         // log_info("-> acl");
357         packet_handler(HCI_ACL_DATA_PACKET, transfer-> buffer, transfer->actual_length);
358         resubmit = 1;
359     } else if (transfer->endpoint == 0){
360         // log_info("command done, size %u", transfer->actual_length);
361         usb_command_active = 0;
362         signal_done = 1;
363     } else if (transfer->endpoint == acl_out_addr){
364         // log_info("acl out done, size %u", transfer->actual_length);
365         usb_acl_out_active = 0;
366         signal_done = 1;
367 #ifdef ENABLE_SCO_OVER_HCI
368     } else if (transfer->endpoint == sco_in_addr) {
369         // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
370         int i;
371         for (i = 0; i < transfer->num_iso_packets; i++) {
372             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
373             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
374                 log_error("Error: pack %u status %d\n", i, pack->status);
375                 continue;
376             }
377             if (!pack->actual_length) continue;
378             uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
379             // printf_hexdump(data, pack->actual_length);
380             // log_info("handle_isochronous_data,size %u/%u", pack->length, pack->actual_length);
381             handle_isochronous_data(data, pack->actual_length);
382         }
383         resubmit = 1;
384     } else if (transfer->endpoint == sco_out_addr){
385         log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
386             transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
387             transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
388             transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
389         // notify upper layer if there's space for new SCO packets
390         if (sco_ring_have_space()) {
391             uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
392             packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
393         }
394         // decrease tab
395         sco_ring_transfers_active--;
396         // log_info("H2: sco out complete, num active num active %u", sco_ring_transfers_active);
397 #endif
398     } else {
399         log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
400     }
401 
402     if (signal_done){
403         // notify upper stack that provided buffer can be used again
404         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
405         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
406     }
407 
408     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
409 
410     if (resubmit){
411         // Re-submit transfer
412         transfer->user_data = NULL;
413         int r = libusb_submit_transfer(transfer);
414         if (r) {
415             log_error("Error re-submitting transfer %d", r);
416         }
417     }
418 }
419 
420 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
421     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
422 
423     // log_info("begin usb_process_ds");
424     // always handling an event as we're called when data is ready
425     struct timeval tv;
426     memset(&tv, 0, sizeof(struct timeval));
427     libusb_handle_events_timeout(NULL, &tv);
428 
429     // Handle any packet in the order that they were received
430     while (handle_packet) {
431         // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
432         void * next = handle_packet->user_data;
433         handle_completed_transfer(handle_packet);
434         // handle case where libusb_close might be called by hci packet handler
435         if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
436 
437         // Move to next in the list of packets to handle
438         if (next) {
439             handle_packet = (struct libusb_transfer*)next;
440         } else {
441             handle_packet = NULL;
442         }
443     }
444     // log_info("end usb_process_ds");
445 }
446 
447 static void usb_process_ts(btstack_timer_source_t *timer) {
448     // log_info("in usb_process_ts");
449 
450     // timer is deactive, when timer callback gets called
451     usb_timer_active = 0;
452 
453     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
454 
455     // actually handled the packet in the pollfds function
456     usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
457 
458     // Get the amount of time until next event is due
459     long msec = ASYNC_POLLING_INTERVAL_MS;
460 
461     // Activate timer
462     btstack_run_loop_set_timer(&usb_timer, msec);
463     btstack_run_loop_add_timer(&usb_timer);
464     usb_timer_active = 1;
465 
466     return;
467 }
468 
469 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
470 
471 // list of known devices, using VendorID/ProductID tuples
472 static const uint16_t known_bt_devices[] = {
473     // DeLOCK Bluetooth 4.0
474     0x0a5c, 0x21e8,
475     // Asus BT400
476     0x0b05, 0x17cb,
477 };
478 
479 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
480 
481 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
482     int i;
483     for (i=0; i<num_known_devices; i++){
484         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
485             return 1;
486         }
487     }
488     return 0;
489 }
490 
491 static void scan_for_bt_endpoints(void) {
492     int r;
493 
494     event_in_addr = 0;
495     acl_in_addr = 0;
496     acl_out_addr = 0;
497     sco_out_addr = 0;
498     sco_in_addr = 0;
499 
500     // get endpoints from interface descriptor
501     struct libusb_config_descriptor *config_descriptor;
502     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
503 
504     int num_interfaces = config_descriptor->bNumInterfaces;
505     log_info("active configuration has %u interfaces", num_interfaces);
506 
507     int i;
508     for (i = 0; i < num_interfaces ; i++){
509         const struct libusb_interface *interface = &config_descriptor->interface[i];
510         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
511         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
512 
513         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
514 
515         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
516             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
517 
518             switch (endpoint->bmAttributes & 0x3){
519                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
520                     if (event_in_addr) continue;
521                     event_in_addr = endpoint->bEndpointAddress;
522                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
523                     break;
524                 case LIBUSB_TRANSFER_TYPE_BULK:
525                     if (endpoint->bEndpointAddress & 0x80) {
526                         if (acl_in_addr) continue;
527                         acl_in_addr = endpoint->bEndpointAddress;
528                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
529                     } else {
530                         if (acl_out_addr) continue;
531                         acl_out_addr = endpoint->bEndpointAddress;
532                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
533                     }
534                     break;
535                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
536                     if (endpoint->bEndpointAddress & 0x80) {
537                         if (sco_in_addr) continue;
538                         sco_in_addr = endpoint->bEndpointAddress;
539                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
540                     } else {
541                         if (sco_out_addr) continue;
542                         sco_out_addr = endpoint->bEndpointAddress;
543                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
544                     }
545                     break;
546                 default:
547                     break;
548             }
549         }
550     }
551     libusb_free_config_descriptor(config_descriptor);
552 }
553 
554 // returns index of found device or -1
555 static int scan_for_bt_device(libusb_device **devs, int start_index) {
556     int i;
557     for (i = start_index; devs[i] ; i++){
558         dev = devs[i];
559         int r = libusb_get_device_descriptor(dev, &desc);
560         if (r < 0) {
561             log_error("failed to get device descriptor");
562             return 0;
563         }
564 
565         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
566                desc.idVendor, desc.idProduct,
567                libusb_get_bus_number(dev), libusb_get_device_address(dev),
568                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
569 
570         // Detect USB Dongle based Class, Subclass, and Protocol
571         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
572         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
573         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
574         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
575         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
576             return i;
577         }
578 
579         // Detect USB Dongle based on whitelist
580         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
581             return i;
582         }
583     }
584     return -1;
585 }
586 #endif
587 
588 static int prepare_device(libusb_device_handle * aHandle){
589 
590     // print device path
591     uint8_t port_numbers[USB_MAX_PATH_LEN];
592     libusb_device * device = libusb_get_device(aHandle);
593     int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
594     printf("USB Path: ");
595     int i;
596     for (i=0;i<path_len;i++){
597         if (i) printf("-");
598         printf("%02x", port_numbers[i]);
599     }
600     printf("\n");
601 
602     int r;
603     int kernel_driver_detached = 0;
604 
605     // Detach OS driver (not possible for OS X and WIN32)
606 #if !defined(__APPLE__) && !defined(_WIN32)
607     r = libusb_kernel_driver_active(aHandle, 0);
608     if (r < 0) {
609         log_error("libusb_kernel_driver_active error %d", r);
610         libusb_close(aHandle);
611         return r;
612     }
613 
614     if (r == 1) {
615         r = libusb_detach_kernel_driver(aHandle, 0);
616         if (r < 0) {
617             log_error("libusb_detach_kernel_driver error %d", r);
618             libusb_close(aHandle);
619             return r;
620         }
621         kernel_driver_detached = 1;
622     }
623     log_info("libusb_detach_kernel_driver");
624 #endif
625 
626     const int configuration = 1;
627     log_info("setting configuration %d...", configuration);
628     r = libusb_set_configuration(aHandle, configuration);
629     if (r < 0) {
630         log_error("Error libusb_set_configuration: %d", r);
631         if (kernel_driver_detached){
632             libusb_attach_kernel_driver(aHandle, 0);
633         }
634         libusb_close(aHandle);
635         return r;
636     }
637 
638     // reserve access to device
639     log_info("claiming interface 0...");
640     r = libusb_claim_interface(aHandle, 0);
641     if (r < 0) {
642         log_error("Error claiming interface %d", r);
643         if (kernel_driver_detached){
644             libusb_attach_kernel_driver(aHandle, 0);
645         }
646         libusb_close(aHandle);
647         return r;
648     }
649 
650 #ifdef ENABLE_SCO_OVER_HCI
651     log_info("claiming interface 1...");
652     r = libusb_claim_interface(aHandle, 1);
653     if (r < 0) {
654         log_error("Error claiming interface %d", r);
655         if (kernel_driver_detached){
656             libusb_attach_kernel_driver(aHandle, 0);
657         }
658         libusb_close(aHandle);
659         return r;
660     }
661     log_info("Switching to setting %u on interface 1..", ALT_SETTING);
662     r = libusb_set_interface_alt_setting(aHandle, 1, ALT_SETTING);
663     if (r < 0) {
664         fprintf(stderr, "Error setting alternative setting %u for interface 1: %s\n", ALT_SETTING, libusb_error_name(r));
665         libusb_close(aHandle);
666         return r;
667     }
668 #endif
669 
670     return 0;
671 }
672 
673 static libusb_device_handle * try_open_device(libusb_device * device){
674     int r;
675 
676     libusb_device_handle * dev_handle;
677     r = libusb_open(device, &dev_handle);
678 
679     if (r < 0) {
680         log_error("libusb_open failed!");
681         dev_handle = NULL;
682         return NULL;
683     }
684 
685     log_info("libusb open %d, handle %p", r, dev_handle);
686 
687     // reset device
688     libusb_reset_device(dev_handle);
689     if (r < 0) {
690         log_error("libusb_reset_device failed!");
691         libusb_close(dev_handle);
692         return NULL;
693     }
694     return dev_handle;
695 }
696 
697 static int usb_open(void){
698     int r;
699 
700 #ifdef ENABLE_SCO_OVER_HCI
701     sco_state_machine_init();
702     sco_ring_init();
703 #endif
704 
705     handle_packet = NULL;
706 
707     // default endpoint addresses
708     event_in_addr = 0x81; // EP1, IN interrupt
709     acl_in_addr =   0x82; // EP2, IN bulk
710     acl_out_addr =  0x02; // EP2, OUT bulk
711     sco_in_addr  =  0x83; // EP3, IN isochronous
712     sco_out_addr =  0x03; // EP3, OUT isochronous
713 
714     // USB init
715     r = libusb_init(NULL);
716     if (r < 0) return -1;
717 
718     libusb_state = LIB_USB_OPENED;
719 
720     // configure debug level
721     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
722 
723 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
724 
725     // Use a specified device
726     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
727     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
728 
729     if (!handle){
730         log_error("libusb_open_device_with_vid_pid failed!");
731         usb_close();
732         return -1;
733     }
734     log_info("libusb open %d, handle %p", r, handle);
735 
736     r = prepare_device(handle);
737     if (r < 0){
738         usb_close();
739         return -1;
740     }
741 
742 #else
743     // Scan system for an appropriate devices
744     libusb_device **devs;
745     ssize_t num_devices;
746 
747     log_info("Scanning for USB Bluetooth device");
748     num_devices = libusb_get_device_list(NULL, &devs);
749     if (num_devices < 0) {
750         usb_close();
751         return -1;
752     }
753 
754     dev = NULL;
755 
756     if (usb_path_len){
757         int i;
758         for (i=0;i<num_devices;i++){
759             uint8_t port_numbers[USB_MAX_PATH_LEN];
760             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
761             if (len != usb_path_len) continue;
762             if (memcmp(usb_path, port_numbers, len) == 0){
763                 log_info("USB device found at specified path");
764                 handle = try_open_device(devs[i]);
765                 if (!handle) continue;
766 
767                 r = prepare_device(handle);
768                 if (r < 0) continue;
769 
770                 dev = devs[i];
771                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
772                 break;
773             };
774         }
775         if (!handle){
776             log_error("USB device with given path not found");
777             printf("USB device with given path not found\n");
778             return -1;
779         }
780     } else {
781 
782         int deviceIndex = -1;
783         while (1){
784             // look for next Bluetooth dongle
785             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
786             if (deviceIndex < 0) break;
787 
788             log_info("USB Bluetooth device found, index %u", deviceIndex);
789 
790             handle = try_open_device(devs[deviceIndex]);
791             if (!handle) continue;
792 
793             r = prepare_device(handle);
794             if (r < 0) continue;
795 
796             dev = devs[deviceIndex];
797             libusb_state = LIB_USB_INTERFACE_CLAIMED;
798             break;
799         }
800     }
801 
802     libusb_free_device_list(devs, 1);
803 
804     if (handle == 0){
805         log_error("No USB Bluetooth device found");
806         return -1;
807     }
808 
809     scan_for_bt_endpoints();
810 
811 #endif
812 
813     // allocate transfer handlers
814     int c;
815     for (c = 0 ; c < ASYNC_BUFFERS ; c++) {
816         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
817         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
818         if ( !event_in_transfer[c] || !acl_in_transfer[c]) {
819             usb_close();
820             return LIBUSB_ERROR_NO_MEM;
821         }
822     }
823 
824     command_out_transfer = libusb_alloc_transfer(0);
825     acl_out_transfer     = libusb_alloc_transfer(0);
826 
827     // TODO check for error
828 
829     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
830 
831 #ifdef ENABLE_SCO_OVER_HCI
832 
833     // incoming
834     for (c = 0 ; c < ISOC_BUFFERS ; c++) {
835         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
836         log_info("Alloc iso transfer");
837         if (!sco_in_transfer[c]) {
838             usb_close();
839             return LIBUSB_ERROR_NO_MEM;
840         }
841         // configure sco_in handlers
842         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
843             hci_sco_in_buffer[c], SCO_PACKET_SIZE, NUM_ISO_PACKETS, async_callback, NULL, 0);
844         libusb_set_iso_packet_lengths(sco_in_transfer[c], ISO_PACKET_SIZE);
845         r = libusb_submit_transfer(sco_in_transfer[c]);
846         log_info("Submit iso transfer res = %d", r);
847         if (r) {
848             log_error("Error submitting isochronous in transfer %d", r);
849             usb_close();
850             return r;
851         }
852     }
853 
854     // outgoing
855     for (c=0; c < SCO_RING_BUFFER_COUNT ; c++){
856         sco_ring_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
857     }
858 #endif
859 
860     for (c = 0 ; c < ASYNC_BUFFERS ; c++) {
861         // configure event_in handlers
862         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
863                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
864         r = libusb_submit_transfer(event_in_transfer[c]);
865         if (r) {
866             log_error("Error submitting interrupt transfer %d", r);
867             usb_close();
868             return r;
869         }
870 
871         // configure acl_in handlers
872         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
873                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
874         r = libusb_submit_transfer(acl_in_transfer[c]);
875         if (r) {
876             log_error("Error submitting bulk in transfer %d", r);
877             usb_close();
878             return r;
879         }
880 
881      }
882 
883     // Check for pollfds functionality
884     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
885 
886     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation here
887     doing_pollfds = 0;
888 
889     if (doing_pollfds) {
890         log_info("Async using pollfds:");
891 
892         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
893         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
894         pollfd_data_sources = malloc(sizeof(btstack_data_source_t) * num_pollfds);
895         if (!pollfd_data_sources){
896             log_error("Cannot allocate data sources for pollfds");
897             usb_close();
898             return 1;
899         }
900         for (r = 0 ; r < num_pollfds ; r++) {
901             btstack_data_source_t *ds = &pollfd_data_sources[r];
902             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
903             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
904             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
905             btstack_run_loop_add_data_source(ds);
906             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
907         }
908         free(pollfd);
909     } else {
910         log_info("Async using timers:");
911 
912         usb_timer.process = usb_process_ts;
913         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
914         btstack_run_loop_add_timer(&usb_timer);
915         usb_timer_active = 1;
916     }
917 
918     return 0;
919 }
920 
921 
922 static int usb_close(void){
923     int c;
924     // @TODO: remove all run loops!
925 
926     switch (libusb_state){
927         case LIB_USB_CLOSED:
928             break;
929 
930         case LIB_USB_TRANSFERS_ALLOCATED:
931             libusb_state = LIB_USB_INTERFACE_CLAIMED;
932 
933             if(usb_timer_active) {
934                 btstack_run_loop_remove_timer(&usb_timer);
935                 usb_timer_active = 0;
936             }
937 
938             // Cancel any asynchronous transfers
939             for (c = 0 ; c < ASYNC_BUFFERS ; c++) {
940                 libusb_cancel_transfer(event_in_transfer[c]);
941                 libusb_cancel_transfer(acl_in_transfer[c]);
942             }
943 #ifdef ENABLE_SCO_OVER_HCI
944             // Cancel all synchronous transfer
945             for (c = 0 ; c < ISOC_BUFFERS ; c++) {
946                 libusb_cancel_transfer(sco_in_transfer[c]);
947             }
948 #endif
949 
950             /* TODO - find a better way to ensure that all transfers have completed */
951             struct timeval tv;
952             memset(&tv, 0, sizeof(struct timeval));
953             libusb_handle_events_timeout(NULL, &tv);
954 
955             if (doing_pollfds){
956                 int r;
957                 for (r = 0 ; r < num_pollfds ; r++) {
958                     btstack_data_source_t *ds = &pollfd_data_sources[r];
959                     btstack_run_loop_remove_data_source(ds);
960                 }
961                 free(pollfd_data_sources);
962                 pollfd_data_sources = NULL;
963                 num_pollfds = 0;
964                 doing_pollfds = 0;
965             }
966 
967         case LIB_USB_INTERFACE_CLAIMED:
968             // Cancel any asynchronous transfers
969             for (c = 0 ; c < ASYNC_BUFFERS ; c++) {
970                 libusb_cancel_transfer(event_in_transfer[c]);
971                 libusb_cancel_transfer(acl_in_transfer[c]);
972             }
973 #ifdef ENABLE_SCO_OVER_HCI
974             // Cancel all synchronous transfer
975             for (c = 0 ; c < ISOC_BUFFERS ; c++) {
976                 libusb_cancel_transfer(sco_in_transfer[c]);
977             }
978 #endif
979 
980             // TODO free control and acl out transfers
981             libusb_release_interface(handle, 0);
982 
983         case LIB_USB_DEVICE_OPENDED:
984             libusb_close(handle);
985 
986         case LIB_USB_OPENED:
987             libusb_exit(NULL);
988     }
989 
990     libusb_state = LIB_USB_CLOSED;
991     handle = NULL;
992 
993     return 0;
994 }
995 
996 static int usb_send_cmd_packet(uint8_t *packet, int size){
997     int r;
998 
999     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1000 
1001     // async
1002     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1003     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1004 
1005     // prepare transfer
1006     int completed = 0;
1007     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1008     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1009 
1010     // update stata before submitting transfer
1011     usb_command_active = 1;
1012 
1013     // submit transfer
1014     r = libusb_submit_transfer(command_out_transfer);
1015 
1016     if (r < 0) {
1017         usb_command_active = 0;
1018         log_error("Error submitting cmd transfer %d", r);
1019         return -1;
1020     }
1021 
1022     return 0;
1023 }
1024 
1025 static int usb_send_acl_packet(uint8_t *packet, int size){
1026     int r;
1027 
1028     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1029 
1030     // log_info("usb_send_acl_packet enter, size %u", size);
1031 
1032     // prepare transfer
1033     int completed = 0;
1034     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1035         async_callback, &completed, 0);
1036     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1037 
1038     // update stata before submitting transfer
1039     usb_acl_out_active = 1;
1040 
1041     r = libusb_submit_transfer(acl_out_transfer);
1042     if (r < 0) {
1043         usb_acl_out_active = 0;
1044         log_error("Error submitting acl transfer, %d", r);
1045         return -1;
1046     }
1047 
1048     return 0;
1049 }
1050 
1051 static int usb_can_send_packet_now(uint8_t packet_type){
1052     switch (packet_type){
1053         case HCI_COMMAND_DATA_PACKET:
1054             return !usb_command_active;
1055         case HCI_ACL_DATA_PACKET:
1056             return !usb_acl_out_active;
1057 #ifdef ENABLE_SCO_OVER_HCI
1058         case HCI_SCO_DATA_PACKET:
1059             return sco_ring_have_space();
1060 #endif
1061         default:
1062             return 0;
1063     }
1064 }
1065 
1066 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1067     switch (packet_type){
1068         case HCI_COMMAND_DATA_PACKET:
1069             return usb_send_cmd_packet(packet, size);
1070         case HCI_ACL_DATA_PACKET:
1071             return usb_send_acl_packet(packet, size);
1072 #ifdef ENABLE_SCO_OVER_HCI
1073         case HCI_SCO_DATA_PACKET:
1074             return usb_send_sco_packet(packet, size);
1075 #endif
1076         default:
1077             return -1;
1078     }
1079 }
1080 
1081 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1082     log_info("registering packet handler");
1083     packet_handler = handler;
1084 }
1085 
1086 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1087 }
1088 
1089 // get usb singleton
1090 const hci_transport_t * hci_transport_usb_instance(void) {
1091     if (!hci_transport_usb) {
1092         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1093         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1094         hci_transport_usb->name                          = "H2_LIBUSB";
1095         hci_transport_usb->open                          = usb_open;
1096         hci_transport_usb->close                         = usb_close;
1097         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1098         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1099         hci_transport_usb->send_packet                   = usb_send_packet;
1100     }
1101     return hci_transport_usb;
1102 }
1103