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