xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision a64cbea79fa5fb9daa58e135a19c6cce10f3e642)
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 BLUEKITCHEN
24  * GMBH 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 #define BTSTACK_FILE__ "hci_transport_h2_libusb.c"
39 
40 /*
41  *  hci_transport_usb.c
42  *
43  *  HCI Transport API implementation for USB
44  *
45  *  Created by Matthias Ringwald on 7/5/09.
46  */
47 
48 // Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size
49 // HCI Commands 0 0 0x00 Control 8/16/32/64
50 // HCI Events   0 0 0x81 Interrupt (IN) 16
51 // ACL Data     0 0 0x82 Bulk (IN) 32/64
52 // ACL Data     0 0 0x02 Bulk (OUT) 32/64
53 // SCO Data     0 0 0x83 Isochronous (IN)
54 // SCO Data     0 0 0x03 Isochronous (Out)
55 
56 #include <stdio.h>
57 #include <strings.h>
58 #include <string.h>
59 #include <unistd.h>   /* UNIX standard function definitions */
60 #include <sys/types.h>
61 
62 #include <libusb.h>
63 
64 #include "btstack_config.h"
65 
66 #include "btstack_debug.h"
67 #include "hci.h"
68 #include "hci_transport.h"
69 #include "hci_transport_usb.h"
70 
71 // deal with changes in libusb API:
72 #ifdef LIBUSB_API_VERSION
73 #if LIBUSB_API_VERSION >= 0x01000106
74 // since 1.0.22, libusb_set_option replaces libusb_set_debug
75 #define libusb_set_debug(context,level) libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, level)
76 #endif
77 #endif
78 
79 #if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0)
80 #define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
81 #endif
82 
83 #define ACL_IN_BUFFER_COUNT    3
84 #define EVENT_IN_BUFFER_COUNT  3
85 #define SCO_IN_BUFFER_COUNT   10
86 
87 #define ASYNC_POLLING_INTERVAL_MS 1
88 
89 //
90 // Bluetooth USB Transport Alternate Settings:
91 //
92 // 0: No active voice channels (for USB compliance)
93 // 1: One 8 kHz voice channel with 8-bit encoding
94 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
95 // 3: Three 8 kHz voice channels with 8-bit encoding
96 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
97 // 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
98 // --> support only a single SCO connection
99 // #define ALT_SETTING (1)
100 
101 #ifdef ENABLE_SCO_OVER_HCI
102 // alt setting for 1-3 connections and 8/16 bit
103 static const int alt_setting_8_bit[]  = {1,2,3};
104 static const int alt_setting_16_bit[] = {2,4,5};
105 
106 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
107 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
108 #define NUM_ISO_PACKETS (3)
109 
110 static const uint16_t iso_packet_size_for_alt_setting[] = {
111     0,
112     9,
113     17,
114     25,
115     33,
116     49,
117     63,
118 };
119 #endif
120 
121 // 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)
122 // 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
123 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
124 
125 // Outgoing SCO packet queue
126 // simplified ring buffer implementation
127 #define SCO_OUT_BUFFER_COUNT  (8)
128 #define SCO_OUT_BUFFER_SIZE (SCO_OUT_BUFFER_COUNT * SCO_PACKET_SIZE)
129 
130 // seems to be the max depth for USB 3
131 #define USB_MAX_PATH_LEN 7
132 
133 // prototypes
134 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
135 static int usb_close(void);
136 
137 typedef enum {
138     LIB_USB_CLOSED = 0,
139     LIB_USB_OPENED,
140     LIB_USB_DEVICE_OPENDED,
141     LIB_USB_INTERFACE_CLAIMED,
142     LIB_USB_TRANSFERS_ALLOCATED
143 } libusb_state_t;
144 
145 // SCO packet state machine
146 typedef enum {
147     H2_W4_SCO_HEADER = 1,
148     H2_W4_PAYLOAD,
149 } H2_SCO_STATE;
150 
151 static libusb_state_t libusb_state = LIB_USB_CLOSED;
152 
153 // single instance
154 static hci_transport_t * hci_transport_usb = NULL;
155 
156 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
157 
158 // libusb
159 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
160 static struct libusb_device_descriptor desc;
161 #endif
162 static libusb_device_handle * handle;
163 
164 static struct libusb_transfer *command_out_transfer;
165 static struct libusb_transfer *acl_out_transfer;
166 static struct libusb_transfer *event_in_transfer[EVENT_IN_BUFFER_COUNT];
167 static struct libusb_transfer *acl_in_transfer[ACL_IN_BUFFER_COUNT];
168 
169 #ifdef ENABLE_SCO_OVER_HCI
170 
171 #ifdef _WIN32
172 #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"
173 #endif
174 
175 // incoming SCO
176 static H2_SCO_STATE sco_state;
177 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
178 static uint16_t sco_read_pos;
179 static uint16_t sco_bytes_to_read;
180 static struct  libusb_transfer *sco_in_transfer[SCO_IN_BUFFER_COUNT];
181 static uint8_t hci_sco_in_buffer[SCO_IN_BUFFER_COUNT][SCO_PACKET_SIZE];
182 
183 // outgoing SCO
184 static uint8_t  sco_out_ring_buffer[SCO_OUT_BUFFER_SIZE];
185 static int      sco_ring_write;  // packet idx
186 static int      sco_out_transfers_active;
187 static struct libusb_transfer *sco_out_transfers[SCO_OUT_BUFFER_COUNT];
188 static int      sco_out_transfers_in_flight[SCO_OUT_BUFFER_COUNT];
189 
190 // pause/resume
191 static uint16_t sco_voice_setting;
192 static int      sco_num_connections;
193 static int      sco_shutdown;
194 
195 // dynamic SCO configuration
196 static uint16_t iso_packet_size;
197 static int      sco_enabled;
198 
199 #endif
200 
201 // outgoing buffer for HCI Command packets
202 static uint8_t hci_cmd_buffer[3 + 256 + LIBUSB_CONTROL_SETUP_SIZE];
203 
204 // incoming buffer for HCI Events and ACL Packets
205 static uint8_t hci_event_in_buffer[EVENT_IN_BUFFER_COUNT][HCI_ACL_BUFFER_SIZE]; // bigger than largest packet
206 static uint8_t hci_acl_in_buffer[ACL_IN_BUFFER_COUNT][HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
207 
208 // For (ab)use as a linked list of received packets
209 static struct libusb_transfer *handle_packet;
210 
211 static int doing_pollfds;
212 static int num_pollfds;
213 static btstack_data_source_t * pollfd_data_sources;
214 static btstack_timer_source_t usb_timer;
215 static int usb_timer_active;
216 
217 static int usb_acl_out_active = 0;
218 static int usb_command_active = 0;
219 
220 // endpoint addresses
221 static int event_in_addr;
222 static int acl_in_addr;
223 static int acl_out_addr;
224 static int sco_in_addr;
225 static int sco_out_addr;
226 
227 // device path
228 static int usb_path_len;
229 static uint8_t usb_path[USB_MAX_PATH_LEN];
230 
231 // transport interface state
232 static int usb_transport_open;
233 
234 
235 #ifdef ENABLE_SCO_OVER_HCI
236 static void sco_ring_init(void){
237     sco_ring_write = 0;
238     sco_out_transfers_active = 0;
239 }
240 static int sco_ring_have_space(void){
241     return sco_out_transfers_active < SCO_OUT_BUFFER_COUNT;
242 }
243 #endif
244 
245 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
246     if (len > USB_MAX_PATH_LEN || !port_numbers){
247         log_error("hci_transport_usb_set_path: len or port numbers invalid");
248         return;
249     }
250     usb_path_len = len;
251     memcpy(usb_path, port_numbers, len);
252 }
253 
254 //
255 static void queue_transfer(struct libusb_transfer *transfer){
256 
257     // log_info("queue_transfer %p, endpoint %x size %u", transfer, transfer->endpoint, transfer->actual_length);
258 
259     transfer->user_data = NULL;
260 
261     // insert first element
262     if (handle_packet == NULL) {
263         handle_packet = transfer;
264         return;
265     }
266 
267     // Walk to end of list and add current packet there
268     struct libusb_transfer *temp = handle_packet;
269     while (temp->user_data) {
270         temp = (struct libusb_transfer*)temp->user_data;
271     }
272     temp->user_data = transfer;
273 }
274 
275 LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer){
276 
277     int c;
278 
279     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED){
280         log_info("shutdown, transfer %p", transfer);
281     }
282 
283 
284     // identify and free transfers as part of shutdown
285 #ifdef ENABLE_SCO_OVER_HCI
286     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED || sco_shutdown) {
287         for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
288             if (transfer == sco_in_transfer[c]){
289                 libusb_free_transfer(transfer);
290                 sco_in_transfer[c] = NULL;
291                 return;
292             }
293         }
294 
295         for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
296             if (transfer == sco_out_transfers[c]){
297                 sco_out_transfers_in_flight[c] = 0;
298                 libusb_free_transfer(transfer);
299                 sco_out_transfers[c] = NULL;
300                 return;
301             }
302         }
303     }
304 #endif
305 
306     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) {
307         for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
308             if (transfer == event_in_transfer[c]){
309                 libusb_free_transfer(transfer);
310                 event_in_transfer[c] = 0;
311                 return;
312             }
313         }
314         for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
315             if (transfer == acl_in_transfer[c]){
316                 libusb_free_transfer(transfer);
317                 acl_in_transfer[c] = 0;
318                 return;
319             }
320         }
321         return;
322     }
323 
324 #ifdef ENABLE_SCO_OVER_HCI
325     // mark SCO OUT transfer as done
326     for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
327         if (transfer == sco_out_transfers[c]){
328             sco_out_transfers_in_flight[c] = 0;
329         }
330     }
331 #endif
332 
333     int r;
334     // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
335 
336     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
337         queue_transfer(transfer);
338     } else if (transfer->status == LIBUSB_TRANSFER_STALL){
339         log_info("-> Transfer stalled, trying again");
340         r = libusb_clear_halt(handle, transfer->endpoint);
341         if (r) {
342             log_error("Error rclearing halt %d", r);
343         }
344         r = libusb_submit_transfer(transfer);
345         if (r) {
346             log_error("Error re-submitting transfer %d", r);
347         }
348     } else {
349         log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
350         // No usable data, just resubmit packet
351         r = libusb_submit_transfer(transfer);
352         if (r) {
353             log_error("Error re-submitting transfer %d", r);
354         }
355     }
356     // log_info("end async_callback");
357 }
358 
359 
360 #ifdef ENABLE_SCO_OVER_HCI
361 static int usb_send_sco_packet(uint8_t *packet, int size){
362     int r;
363 
364     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
365 
366     // log_info("usb_send_acl_packet enter, size %u", size);
367 
368     // store packet in free slot
369     int tranfer_index = sco_ring_write;
370     uint8_t * data = &sco_out_ring_buffer[tranfer_index * SCO_PACKET_SIZE];
371     memcpy(data, packet, size);
372 
373     // setup transfer
374     // log_info("usb_send_sco_packet: size %u, max size %u, iso packet size %u", size, NUM_ISO_PACKETS * iso_packet_size, iso_packet_size);
375     struct libusb_transfer * sco_transfer = sco_out_transfers[tranfer_index];
376     libusb_fill_iso_transfer(sco_transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
377     libusb_set_iso_packet_lengths(sco_transfer, iso_packet_size);
378     r = libusb_submit_transfer(sco_transfer);
379     if (r < 0) {
380         log_error("Error submitting sco transfer, %d", r);
381         return -1;
382     }
383 
384     // mark slot as full
385     sco_ring_write++;
386     if (sco_ring_write == SCO_OUT_BUFFER_COUNT){
387         sco_ring_write = 0;
388     }
389     sco_out_transfers_active++;
390     sco_out_transfers_in_flight[tranfer_index] = 1;
391 
392     // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active);
393 
394     // notify upper stack that provided buffer can be used again
395     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
396     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
397 
398     // and if we have more space for SCO packets
399     if (sco_ring_have_space()) {
400         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
401         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
402     }
403     return 0;
404 }
405 
406 static void sco_state_machine_init(void){
407     sco_state = H2_W4_SCO_HEADER;
408     sco_read_pos = 0;
409     sco_bytes_to_read = 3;
410 }
411 
412 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
413     while (size){
414         if (size < sco_bytes_to_read){
415             // just store incomplete data
416             memcpy(&sco_buffer[sco_read_pos], buffer, size);
417             sco_read_pos      += size;
418             sco_bytes_to_read -= size;
419             return;
420         }
421         // copy requested data
422         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
423         sco_read_pos += sco_bytes_to_read;
424         buffer       += sco_bytes_to_read;
425         size         -= sco_bytes_to_read;
426 
427         // chunk read successfully, next action
428         switch (sco_state){
429             case H2_W4_SCO_HEADER:
430                 sco_state = H2_W4_PAYLOAD;
431                 sco_bytes_to_read = sco_buffer[2];
432                 break;
433             case H2_W4_PAYLOAD:
434                 // packet complete
435                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
436                 sco_state_machine_init();
437                 break;
438 			default:
439 				btstack_assert(false);
440 				break;
441         }
442     }
443 }
444 #endif
445 
446 static void handle_completed_transfer(struct libusb_transfer *transfer){
447 
448     int resubmit = 0;
449     int signal_done = 0;
450 
451     if (transfer->endpoint == event_in_addr) {
452         packet_handler(HCI_EVENT_PACKET, transfer->buffer, transfer->actual_length);
453         resubmit = 1;
454     } else if (transfer->endpoint == acl_in_addr) {
455         // log_info("-> acl");
456         packet_handler(HCI_ACL_DATA_PACKET, transfer->buffer, transfer->actual_length);
457         resubmit = 1;
458     } else if (transfer->endpoint == 0){
459         // log_info("command done, size %u", transfer->actual_length);
460         usb_command_active = 0;
461         signal_done = 1;
462     } else if (transfer->endpoint == acl_out_addr){
463         // log_info("acl out done, size %u", transfer->actual_length);
464         usb_acl_out_active = 0;
465         signal_done = 1;
466 #ifdef ENABLE_SCO_OVER_HCI
467     } else if (transfer->endpoint == sco_in_addr) {
468         // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
469         int i;
470         for (i = 0; i < transfer->num_iso_packets; i++) {
471             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
472             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
473                 log_error("Error: pack %u status %d\n", i, pack->status);
474                 continue;
475             }
476             if (!pack->actual_length) continue;
477             uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
478             // printf_hexdump(data, pack->actual_length);
479             // log_info("handle_isochronous_data,size %u/%u", pack->length, pack->actual_length);
480             handle_isochronous_data(data, pack->actual_length);
481         }
482         resubmit = 1;
483     } else if (transfer->endpoint == sco_out_addr){
484         int i;
485         for (i = 0; i < transfer->num_iso_packets; i++) {
486             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
487             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
488                 log_error("Error: pack %u status %d\n", i, pack->status);
489             }
490         }
491         // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
492         //     transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
493         //     transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
494         //     transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
495         // notify upper layer if there's space for new SCO packets
496 
497         if (sco_ring_have_space()) {
498             uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
499             packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
500         }
501         // decrease tab
502         sco_out_transfers_active--;
503         // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active);
504 #endif
505     } else {
506         log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
507     }
508 
509     if (signal_done){
510         // notify upper stack that provided buffer can be used again
511         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
512         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
513     }
514 
515     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
516 
517     if (resubmit){
518         // Re-submit transfer
519         transfer->user_data = NULL;
520         int r = libusb_submit_transfer(transfer);
521         if (r) {
522             log_error("Error re-submitting transfer %d", r);
523         }
524     }
525 }
526 
527 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
528 
529     UNUSED(ds);
530     UNUSED(callback_type);
531 
532     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
533 
534     // log_info("begin usb_process_ds");
535     // always handling an event as we're called when data is ready
536     struct timeval tv;
537     memset(&tv, 0, sizeof(struct timeval));
538     libusb_handle_events_timeout(NULL, &tv);
539 
540     // Handle any packet in the order that they were received
541     while (handle_packet) {
542         // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
543 
544         // pop next transfer
545         struct libusb_transfer * transfer = handle_packet;
546         handle_packet = (struct libusb_transfer*) handle_packet->user_data;
547 
548         // handle transfer
549         handle_completed_transfer(transfer);
550 
551         // handle case where libusb_close might be called by hci packet handler
552         if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
553     }
554     // log_info("end usb_process_ds");
555 }
556 
557 static void usb_process_ts(btstack_timer_source_t *timer) {
558 
559     UNUSED(timer);
560 
561     // log_info("in usb_process_ts");
562 
563     // timer is deactive, when timer callback gets called
564     usb_timer_active = 0;
565 
566     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
567 
568     // actually handled the packet in the pollfds function
569     usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
570 
571     // Get the amount of time until next event is due
572     long msec = ASYNC_POLLING_INTERVAL_MS;
573 
574     // Activate timer
575     btstack_run_loop_set_timer(&usb_timer, msec);
576     btstack_run_loop_add_timer(&usb_timer);
577     usb_timer_active = 1;
578 
579     return;
580 }
581 
582 
583 static int scan_for_bt_endpoints(libusb_device *dev) {
584     int r;
585 
586     event_in_addr = 0;
587     acl_in_addr = 0;
588     acl_out_addr = 0;
589     sco_out_addr = 0;
590     sco_in_addr = 0;
591 
592     // get endpoints from interface descriptor
593     struct libusb_config_descriptor *config_descriptor;
594     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
595     if (r < 0) return r;
596 
597     int num_interfaces = config_descriptor->bNumInterfaces;
598     log_info("active configuration has %u interfaces", num_interfaces);
599 
600     int i;
601     for (i = 0; i < num_interfaces ; i++){
602         const struct libusb_interface *interface = &config_descriptor->interface[i];
603         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
604         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
605 
606         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
607 
608         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
609             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
610 
611             switch (endpoint->bmAttributes & 0x3){
612                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
613                     if (event_in_addr) continue;
614                     event_in_addr = endpoint->bEndpointAddress;
615                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
616                     break;
617                 case LIBUSB_TRANSFER_TYPE_BULK:
618                     if (endpoint->bEndpointAddress & 0x80) {
619                         if (acl_in_addr) continue;
620                         acl_in_addr = endpoint->bEndpointAddress;
621                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
622                     } else {
623                         if (acl_out_addr) continue;
624                         acl_out_addr = endpoint->bEndpointAddress;
625                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
626                     }
627                     break;
628                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
629                     if (endpoint->bEndpointAddress & 0x80) {
630                         if (sco_in_addr) continue;
631                         sco_in_addr = endpoint->bEndpointAddress;
632                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
633                     } else {
634                         if (sco_out_addr) continue;
635                         sco_out_addr = endpoint->bEndpointAddress;
636                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
637                     }
638                     break;
639                 default:
640                     break;
641             }
642         }
643     }
644     libusb_free_config_descriptor(config_descriptor);
645     return 0;
646 }
647 
648 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
649 
650 // list of known devices, using VendorID/ProductID tuples
651 static const uint16_t known_bluetooth_devices[] = {
652     // BCM20702A0 - DeLOCK Bluetooth 4.0
653     0x0a5c, 0x21e8,
654     // BCM20702A0 - Asus BT400
655     0x0b05, 0x17cb,
656     // BCM20702B0 - Generic USB Detuned Class 1 @ 20 MHz
657     0x0a5c, 0x22be,
658     // nRF5x Zephyr USB HCI, e.g nRF52840-PCA10056
659     0x2fe3, 0x0100,
660     0x2fe3, 0x000b,
661 };
662 
663 static int num_known_devices = sizeof(known_bluetooth_devices) / sizeof(uint16_t) / 2;
664 
665 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
666     int i;
667     for (i=0; i<num_known_devices; i++){
668         if (known_bluetooth_devices[i*2] == vendor_id && known_bluetooth_devices[i*2+1] == product_id){
669             return 1;
670         }
671     }
672     return 0;
673 }
674 
675 // returns index of found device or -1
676 static int scan_for_bt_device(libusb_device **devs, int start_index) {
677     int i;
678     for (i = start_index; devs[i] ; i++){
679         libusb_device * dev = devs[i];
680         int r = libusb_get_device_descriptor(dev, &desc);
681         if (r < 0) {
682             log_error("failed to get device descriptor");
683             return 0;
684         }
685 
686         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
687                desc.idVendor, desc.idProduct,
688                libusb_get_bus_number(dev), libusb_get_device_address(dev),
689                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
690 
691         // Detect USB Dongle based Class, Subclass, and Protocol
692         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
693         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
694         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
695         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
696             return i;
697         }
698 
699         // Detect USB Dongle based on whitelist
700         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
701             return i;
702         }
703     }
704     return -1;
705 }
706 #endif
707 
708 static int prepare_device(libusb_device_handle * aHandle){
709 
710     // get device path
711     libusb_device * device = libusb_get_device(aHandle);
712     usb_path_len = libusb_get_port_numbers(device, usb_path, USB_MAX_PATH_LEN);
713 
714     // print device path
715     printf("USB Path: ");
716     int i;
717     for (i=0;i<usb_path_len;i++){
718         if (i) printf("-");
719         printf("%02x", usb_path[i]);
720     }
721     printf("\n");
722 
723     int r;
724     int kernel_driver_detached = 0;
725 
726     // Detach OS driver (not possible for OS X, FreeBSD, and Windows)
727 #if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
728     r = libusb_kernel_driver_active(aHandle, 0);
729     if (r < 0) {
730         log_error("libusb_kernel_driver_active error %d", r);
731         libusb_close(aHandle);
732         return r;
733     }
734 
735     if (r == 1) {
736         r = libusb_detach_kernel_driver(aHandle, 0);
737         if (r < 0) {
738             log_error("libusb_detach_kernel_driver error %d", r);
739             libusb_close(aHandle);
740             return r;
741         }
742         kernel_driver_detached = 1;
743     }
744     log_info("libusb_detach_kernel_driver");
745 #endif
746 
747     const int configuration = 1;
748     log_info("setting configuration %d...", configuration);
749     r = libusb_set_configuration(aHandle, configuration);
750     if (r < 0) {
751         log_error("Error libusb_set_configuration: %d", r);
752         if (kernel_driver_detached){
753             libusb_attach_kernel_driver(aHandle, 0);
754         }
755         libusb_close(aHandle);
756         return r;
757     }
758 
759     // reserve access to device
760     log_info("claiming interface 0...");
761     r = libusb_claim_interface(aHandle, 0);
762     if (r < 0) {
763         log_error("Error %d claiming interface 0", r);
764         if (kernel_driver_detached){
765             libusb_attach_kernel_driver(aHandle, 0);
766         }
767         libusb_close(aHandle);
768         return r;
769     }
770 
771 #ifdef ENABLE_SCO_OVER_HCI
772     // get endpoints from interface descriptor
773     struct libusb_config_descriptor *config_descriptor;
774     r = libusb_get_active_config_descriptor(device, &config_descriptor);
775     if (r >= 0){
776         int num_interfaces = config_descriptor->bNumInterfaces;
777         if (num_interfaces > 1) {
778             r = libusb_claim_interface(aHandle, 1);
779             if (r < 0) {
780                 log_error("Error %d claiming interface 1: - disabling SCO over HCI", r);
781             } else {
782                 sco_enabled = 1;
783             }
784         } else {
785             log_info("Device has only on interface, disabling SCO over HCI");
786         }
787     }
788 #endif
789 
790     return 0;
791 }
792 
793 static libusb_device_handle * try_open_device(libusb_device * device){
794     int r;
795 
796     libusb_device_handle * dev_handle;
797     r = libusb_open(device, &dev_handle);
798 
799     if (r < 0) {
800         log_error("libusb_open failed!");
801         dev_handle = NULL;
802         return NULL;
803     }
804 
805     log_info("libusb open %d, handle %p", r, dev_handle);
806 
807     // reset device (Not currently possible under FreeBSD 11.x/12.x due to usb framework)
808 #if !defined(__FreeBSD__)
809     r = libusb_reset_device(dev_handle);
810     if (r < 0) {
811         log_error("libusb_reset_device failed!");
812         libusb_close(dev_handle);
813         return NULL;
814     }
815 #endif
816     return dev_handle;
817 }
818 
819 #ifdef ENABLE_SCO_OVER_HCI
820 
821 static int usb_sco_start(void){
822 
823     printf("usb_sco_start\n");
824     log_info("usb_sco_start");
825 
826     sco_state_machine_init();
827     sco_ring_init();
828 
829     int alt_setting;
830     if (sco_voice_setting & 0x0020){
831         // 16-bit PCM
832         alt_setting = alt_setting_16_bit[sco_num_connections-1];
833     } else {
834         // 8-bit PCM or mSBC
835         alt_setting = alt_setting_8_bit[sco_num_connections-1];
836     }
837     // derive iso packet size from alt setting
838     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
839 
840     log_info("Switching to setting %u on interface 1..", alt_setting);
841     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
842     if (r < 0) {
843         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
844         return r;
845     }
846 
847     // incoming
848     int c;
849     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
850         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
851         if (!sco_in_transfer[c]) {
852             usb_close();
853             return LIBUSB_ERROR_NO_MEM;
854         }
855         // configure sco_in handlers
856         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
857             hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
858         libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
859         r = libusb_submit_transfer(sco_in_transfer[c]);
860         if (r) {
861             log_error("Error submitting isochronous in transfer %d", r);
862             usb_close();
863             return r;
864         }
865     }
866 
867     // outgoing
868     for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
869         sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
870         sco_out_transfers_in_flight[c] = 0;
871     }
872     return 0;
873 }
874 
875 static void usb_sco_stop(void){
876 
877     printf("usb_sco_stop\n");
878 
879     log_info("usb_sco_stop");
880     sco_shutdown = 1;
881 
882     // Free SCO transfers already in queue
883     struct libusb_transfer* transfer = handle_packet;
884     struct libusb_transfer* prev_transfer = NULL;
885     while (transfer != NULL) {
886         uint16_t c;
887         bool drop_transfer = false;
888         for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
889             if (transfer == sco_in_transfer[c]){
890                 sco_in_transfer[c] = NULL;
891                 drop_transfer = true;
892                 break;
893             }
894         }
895         for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
896             if (transfer == sco_out_transfers[c]){
897                 sco_out_transfers_in_flight[c] = 0;
898                 sco_out_transfers[c] = NULL;
899                 drop_transfer = true;
900                 break;
901             }
902         }
903         struct libusb_transfer * next_transfer = (struct libusb_transfer *) transfer->user_data;
904         if (drop_transfer) {
905             printf("Drop completed SCO transfer %p\n", transfer);
906             if (prev_transfer == NULL) {
907                 // first item
908                 handle_packet = (struct libusb_transfer *) next_transfer;
909             } else {
910                 // other item
911                 prev_transfer->user_data = (struct libusb_transfer *) next_transfer;
912             }
913             libusb_free_transfer(transfer);
914         } else {
915             prev_transfer = transfer;
916         }
917         transfer = next_transfer;
918     }
919 
920     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
921 
922     int c;
923     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
924         if (sco_in_transfer[c] != NULL) {
925             libusb_cancel_transfer(sco_in_transfer[c]);
926         }
927     }
928 
929     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
930         if (sco_out_transfers_in_flight[c]) {
931             libusb_cancel_transfer(sco_out_transfers[c]);
932         } else {
933             if (sco_out_transfers[c] != NULL) {
934                 libusb_free_transfer(sco_out_transfers[c]);
935                 sco_out_transfers[c] = 0;
936             }
937         }
938     }
939 
940     // wait until all transfers are completed
941     int completed = 0;
942     while (!completed){
943         struct timeval tv;
944         memset(&tv, 0, sizeof(struct timeval));
945         libusb_handle_events_timeout(NULL, &tv);
946         // check if all done
947         completed = 1;
948 
949         // Cancel all synchronous transfer
950         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
951             if (sco_in_transfer[c] != NULL){
952                 completed = 0;
953                 break;
954             }
955         }
956 
957         if (!completed) continue;
958 
959         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
960             if (sco_out_transfers[c] != NULL){
961                 completed = 0;
962                 break;
963             }
964         }
965     }
966     sco_shutdown = 0;
967     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
968 
969     log_info("Switching to setting %u on interface 1..", 0);
970     int r = libusb_set_interface_alt_setting(handle, 1, 0);
971     if (r < 0) {
972         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
973         return;
974     }
975 
976     printf("usb_sco_stop done\n");
977 }
978 
979 
980 
981 #endif
982 
983 static int usb_open(void){
984     int r;
985 
986     if (usb_transport_open) return 0;
987 
988     handle_packet = NULL;
989 
990     // default endpoint addresses
991     event_in_addr = 0x81; // EP1, IN interrupt
992     acl_in_addr =   0x82; // EP2, IN bulk
993     acl_out_addr =  0x02; // EP2, OUT bulk
994     sco_in_addr  =  0x83; // EP3, IN isochronous
995     sco_out_addr =  0x03; // EP3, OUT isochronous
996 
997     // USB init
998     r = libusb_init(NULL);
999     if (r < 0) return -1;
1000 
1001     libusb_state = LIB_USB_OPENED;
1002 
1003     // configure debug level
1004     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1005 
1006     libusb_device * dev = NULL;
1007 
1008 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
1009 
1010     // Use a specified device
1011     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
1012     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
1013 
1014     if (!handle){
1015         log_error("libusb_open_device_with_vid_pid failed!");
1016         usb_close();
1017         return -1;
1018     }
1019     log_info("libusb open %d, handle %p", r, handle);
1020 
1021     r = prepare_device(handle);
1022     if (r < 0){
1023         usb_close();
1024         return -1;
1025     }
1026 
1027     dev = libusb_get_device(handle);
1028     r = scan_for_bt_endpoints(dev);
1029     if (r < 0){
1030         usb_close();
1031         return -1;
1032     }
1033 
1034 #else
1035     // Scan system for an appropriate devices
1036     libusb_device **devs;
1037     ssize_t num_devices;
1038 
1039     log_info("Scanning for USB Bluetooth device");
1040     num_devices = libusb_get_device_list(NULL, &devs);
1041     if (num_devices < 0) {
1042         usb_close();
1043         return -1;
1044     }
1045 
1046     if (usb_path_len){
1047         int i;
1048         for (i=0;i<num_devices;i++){
1049             uint8_t port_numbers[USB_MAX_PATH_LEN];
1050             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
1051             if (len != usb_path_len) continue;
1052             if (memcmp(usb_path, port_numbers, len) == 0){
1053                 log_info("USB device found at specified path");
1054                 handle = try_open_device(devs[i]);
1055                 if (!handle) continue;
1056 
1057                 r = prepare_device(handle);
1058                 if (r < 0) {
1059                     handle = NULL;
1060                     continue;
1061                 }
1062 
1063                 dev = devs[i];
1064                 r = scan_for_bt_endpoints(dev);
1065                 if (r < 0) {
1066                     handle = NULL;
1067                     continue;
1068                 }
1069 
1070                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
1071                 break;
1072             };
1073         }
1074         if (!handle){
1075             log_error("USB device with given path not found");
1076             printf("USB device with given path not found\n");
1077             return -1;
1078         }
1079     } else {
1080 
1081         int deviceIndex = -1;
1082         while (true){
1083             // look for next Bluetooth dongle
1084             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
1085             if (deviceIndex < 0) break;
1086 
1087             log_info("USB Bluetooth device found, index %u", deviceIndex);
1088 
1089             handle = try_open_device(devs[deviceIndex]);
1090             if (!handle) continue;
1091 
1092             r = prepare_device(handle);
1093             if (r < 0) {
1094                 handle = NULL;
1095                 continue;
1096             }
1097 
1098             dev = devs[deviceIndex];
1099             r = scan_for_bt_endpoints(dev);
1100             if (r < 0) {
1101                 handle = NULL;
1102                 continue;
1103             }
1104 
1105             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1106             break;
1107         }
1108     }
1109 
1110     libusb_free_device_list(devs, 1);
1111 
1112     if (handle == 0){
1113         log_error("No USB Bluetooth device found");
1114         return -1;
1115     }
1116 
1117 #endif
1118 
1119     // allocate transfer handlers
1120     int c;
1121     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1122         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1123         if (!event_in_transfer[c]) {
1124             usb_close();
1125             return LIBUSB_ERROR_NO_MEM;
1126         }
1127     }
1128     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1129         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1130         if (!acl_in_transfer[c]) {
1131             usb_close();
1132             return LIBUSB_ERROR_NO_MEM;
1133         }
1134     }
1135 
1136     command_out_transfer = libusb_alloc_transfer(0);
1137     acl_out_transfer     = libusb_alloc_transfer(0);
1138 
1139     // TODO check for error
1140 
1141     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1142 
1143     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1144         // configure event_in handlers
1145         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1146                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1147         r = libusb_submit_transfer(event_in_transfer[c]);
1148         if (r) {
1149             log_error("Error submitting interrupt transfer %d", r);
1150             usb_close();
1151             return r;
1152         }
1153     }
1154 
1155     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1156         // configure acl_in handlers
1157         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1158                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1159         r = libusb_submit_transfer(acl_in_transfer[c]);
1160         if (r) {
1161             log_error("Error submitting bulk in transfer %d", r);
1162             usb_close();
1163             return r;
1164         }
1165 
1166      }
1167 
1168  #if 0
1169     // Check for pollfds functionality
1170     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1171 #else
1172     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation
1173     doing_pollfds = 0;
1174 #endif
1175 
1176     if (doing_pollfds) {
1177         log_info("Async using pollfds:");
1178 
1179         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1180         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1181         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1182         if (!pollfd_data_sources){
1183             log_error("Cannot allocate data sources for pollfds");
1184             usb_close();
1185             return 1;
1186         }
1187         memset(pollfd_data_sources, 0, sizeof(btstack_data_source_t) * num_pollfds);
1188         for (r = 0 ; r < num_pollfds ; r++) {
1189             btstack_data_source_t *ds = &pollfd_data_sources[r];
1190             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1191             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1192             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1193             btstack_run_loop_add_data_source(ds);
1194             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1195         }
1196         free(pollfd);
1197     } else {
1198         log_info("Async using timers:");
1199 
1200         usb_timer.process = usb_process_ts;
1201         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1202         btstack_run_loop_add_timer(&usb_timer);
1203         usb_timer_active = 1;
1204     }
1205 
1206     usb_transport_open = 1;
1207 
1208     return 0;
1209 }
1210 
1211 static int usb_close(void){
1212     int c;
1213     int completed = 0;
1214 
1215     if (!usb_transport_open) return 0;
1216 
1217     log_info("usb_close");
1218 
1219     switch (libusb_state){
1220         case LIB_USB_CLOSED:
1221             break;
1222 
1223         case LIB_USB_TRANSFERS_ALLOCATED:
1224             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1225 
1226             if(usb_timer_active) {
1227                 btstack_run_loop_remove_timer(&usb_timer);
1228                 usb_timer_active = 0;
1229             }
1230 
1231             if (doing_pollfds){
1232                 int r;
1233                 for (r = 0 ; r < num_pollfds ; r++) {
1234                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1235                     btstack_run_loop_remove_data_source(ds);
1236                 }
1237                 free(pollfd_data_sources);
1238                 pollfd_data_sources = NULL;
1239                 num_pollfds = 0;
1240                 doing_pollfds = 0;
1241             }
1242 
1243             /* fall through */
1244 
1245         case LIB_USB_INTERFACE_CLAIMED:
1246             // Cancel all transfers, ignore warnings for this
1247             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1248             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1249                 if (event_in_transfer[c]){
1250                     log_info("cancel event_in_transfer[%u] = %p", c, event_in_transfer[c]);
1251                     libusb_cancel_transfer(event_in_transfer[c]);
1252                 }
1253             }
1254             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1255                 if (acl_in_transfer[c]){
1256                     log_info("cancel acl_in_transfer[%u] = %p", c, acl_in_transfer[c]);
1257                     libusb_cancel_transfer(acl_in_transfer[c]);
1258                 }
1259             }
1260 #ifdef ENABLE_SCO_OVER_HCI
1261             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1262                 if (sco_in_transfer[c]){
1263                     log_info("cancel sco_in_transfer[%u] = %p", c, sco_in_transfer[c]);
1264                     libusb_cancel_transfer(sco_in_transfer[c]);
1265                 }
1266             }
1267             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1268                 if (sco_out_transfers_in_flight[c]) {
1269                     log_info("cancel sco_out_transfers[%u] = %p", c, sco_out_transfers[c]);
1270                     libusb_cancel_transfer(sco_out_transfers[c]);
1271                 } else {
1272                     if (sco_out_transfers[c] != NULL){
1273                         libusb_free_transfer(sco_out_transfers[c]);
1274                         sco_out_transfers[c] = 0;
1275                     }
1276                 }
1277             }
1278 #endif
1279             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1280 
1281             // wait until all transfers are completed - or 20 iterations
1282             int countdown = 20;
1283             while (!completed){
1284 
1285                 if (--countdown == 0){
1286                     log_info("Not all transfers cancelled, leaking a bit.");
1287                     break;
1288                 }
1289 
1290                 struct timeval tv;
1291                 memset(&tv, 0, sizeof(struct timeval));
1292                 libusb_handle_events_timeout(NULL, &tv);
1293                 // check if all done
1294                 completed = 1;
1295                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1296                     if (event_in_transfer[c]) {
1297                         log_info("event_in_transfer[%u] still active (%p)", c, event_in_transfer[c]);
1298                         completed = 0;
1299                         break;
1300                     }
1301                 }
1302 
1303                 if (!completed) continue;
1304 
1305                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1306                     if (acl_in_transfer[c]) {
1307                         log_info("acl_in_transfer[%u] still active (%p)", c, acl_in_transfer[c]);
1308                         completed = 0;
1309                         break;
1310                     }
1311                 }
1312 
1313 #ifdef ENABLE_SCO_OVER_HCI
1314                 if (!completed) continue;
1315 
1316                 // Cancel all synchronous transfer
1317                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1318                     if (sco_in_transfer[c]){
1319                         log_info("sco_in_transfer[%u] still active (%p)", c, sco_in_transfer[c]);
1320                         completed = 0;
1321                         break;
1322                     }
1323                 }
1324 
1325                 if (!completed) continue;
1326 
1327                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1328                     if (sco_out_transfers[c] != NULL){
1329                         log_info("sco_out_transfers[%u] still active (%p)", c, sco_out_transfers[c]);
1330                         completed = 0;
1331                         break;
1332                     }
1333                 }
1334                 sco_enabled = 0;
1335 #endif
1336             }
1337 
1338             // finally release interface
1339             libusb_release_interface(handle, 0);
1340 #ifdef ENABLE_SCO_OVER_HCI
1341             libusb_release_interface(handle, 1);
1342 #endif
1343             log_info("Libusb shutdown complete");
1344 
1345 			/* fall through */
1346 
1347         case LIB_USB_DEVICE_OPENDED:
1348             libusb_close(handle);
1349 
1350 			/* fall through */
1351 
1352         case LIB_USB_OPENED:
1353             libusb_exit(NULL);
1354             break;
1355 
1356 		default:
1357 			btstack_assert(false);
1358 			break;
1359     }
1360 
1361     libusb_state = LIB_USB_CLOSED;
1362     handle = NULL;
1363     usb_transport_open = 0;
1364 
1365     return 0;
1366 }
1367 
1368 static int usb_send_cmd_packet(uint8_t *packet, int size){
1369     int r;
1370 
1371     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1372 
1373     // async
1374     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1375     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1376 
1377     // prepare transfer
1378     int completed = 0;
1379     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1380     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1381 
1382     // update stata before submitting transfer
1383     usb_command_active = 1;
1384 
1385     // submit transfer
1386     r = libusb_submit_transfer(command_out_transfer);
1387 
1388     if (r < 0) {
1389         usb_command_active = 0;
1390         log_error("Error submitting cmd transfer %d", r);
1391         return -1;
1392     }
1393 
1394     return 0;
1395 }
1396 
1397 static int usb_send_acl_packet(uint8_t *packet, int size){
1398     int r;
1399 
1400     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1401 
1402     // log_info("usb_send_acl_packet enter, size %u", size);
1403 
1404     // prepare transfer
1405     int completed = 0;
1406     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1407         async_callback, &completed, 0);
1408     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1409 
1410     // update stata before submitting transfer
1411     usb_acl_out_active = 1;
1412 
1413     r = libusb_submit_transfer(acl_out_transfer);
1414     if (r < 0) {
1415         usb_acl_out_active = 0;
1416         log_error("Error submitting acl transfer, %d", r);
1417         return -1;
1418     }
1419 
1420     return 0;
1421 }
1422 
1423 static int usb_can_send_packet_now(uint8_t packet_type){
1424     switch (packet_type){
1425         case HCI_COMMAND_DATA_PACKET:
1426             return !usb_command_active;
1427         case HCI_ACL_DATA_PACKET:
1428             return !usb_acl_out_active;
1429 #ifdef ENABLE_SCO_OVER_HCI
1430         case HCI_SCO_DATA_PACKET:
1431             if (!sco_enabled) return 0;
1432             return sco_ring_have_space();
1433 #endif
1434         default:
1435             return 0;
1436     }
1437 }
1438 
1439 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1440     switch (packet_type){
1441         case HCI_COMMAND_DATA_PACKET:
1442             return usb_send_cmd_packet(packet, size);
1443         case HCI_ACL_DATA_PACKET:
1444             return usb_send_acl_packet(packet, size);
1445 #ifdef ENABLE_SCO_OVER_HCI
1446         case HCI_SCO_DATA_PACKET:
1447             if (!sco_enabled) return -1;
1448             return usb_send_sco_packet(packet, size);
1449 #endif
1450         default:
1451             return -1;
1452     }
1453 }
1454 
1455 #ifdef ENABLE_SCO_OVER_HCI
1456 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1457     if (!sco_enabled) return;
1458 
1459     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1460 
1461     if (num_connections != sco_num_connections){
1462         sco_voice_setting = voice_setting;
1463         if (sco_num_connections){
1464             usb_sco_stop();
1465         }
1466         sco_num_connections = num_connections;
1467         if (num_connections){
1468             usb_sco_start();
1469         }
1470     }
1471 }
1472 #endif
1473 
1474 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1475     log_info("registering packet handler");
1476     packet_handler = handler;
1477 }
1478 
1479 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1480     UNUSED(packet_type);
1481     UNUSED(packet);
1482     UNUSED(size);
1483 }
1484 
1485 // get usb singleton
1486 const hci_transport_t * hci_transport_usb_instance(void) {
1487     if (!hci_transport_usb) {
1488         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1489         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1490         hci_transport_usb->name                          = "H2_LIBUSB";
1491         hci_transport_usb->open                          = usb_open;
1492         hci_transport_usb->close                         = usb_close;
1493         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1494         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1495         hci_transport_usb->send_packet                   = usb_send_packet;
1496 #ifdef ENABLE_SCO_OVER_HCI
1497         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1498 #endif
1499     }
1500     return hci_transport_usb;
1501 }
1502