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