xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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_bt_devices[] = {
585     // DeLOCK Bluetooth 4.0
586     0x0a5c, 0x21e8,
587     // Asus BT400
588     0x0b05, 0x17cb,
589     // BCM20702B0 (Generic USB Detuned Class 1 @ 20 MHz)
590     0x0a5c, 0x22be,
591     // Zephyr e.g nRF52840-PCA10056
592     0x2fe3, 0x0100,
593 };
594 
595 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
596 
597 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
598     int i;
599     for (i=0; i<num_known_devices; i++){
600         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
601             return 1;
602         }
603     }
604     return 0;
605 }
606 
607 static int scan_for_bt_endpoints(libusb_device *dev) {
608     int r;
609 
610     event_in_addr = 0;
611     acl_in_addr = 0;
612     acl_out_addr = 0;
613     sco_out_addr = 0;
614     sco_in_addr = 0;
615 
616     // get endpoints from interface descriptor
617     struct libusb_config_descriptor *config_descriptor;
618     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
619     if (r < 0) return r;
620 
621     int num_interfaces = config_descriptor->bNumInterfaces;
622     log_info("active configuration has %u interfaces", num_interfaces);
623 
624     int i;
625     for (i = 0; i < num_interfaces ; i++){
626         const struct libusb_interface *interface = &config_descriptor->interface[i];
627         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
628         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
629 
630         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
631 
632         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
633             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
634 
635             switch (endpoint->bmAttributes & 0x3){
636                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
637                     if (event_in_addr) continue;
638                     event_in_addr = endpoint->bEndpointAddress;
639                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
640                     break;
641                 case LIBUSB_TRANSFER_TYPE_BULK:
642                     if (endpoint->bEndpointAddress & 0x80) {
643                         if (acl_in_addr) continue;
644                         acl_in_addr = endpoint->bEndpointAddress;
645                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
646                     } else {
647                         if (acl_out_addr) continue;
648                         acl_out_addr = endpoint->bEndpointAddress;
649                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
650                     }
651                     break;
652                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
653                     if (endpoint->bEndpointAddress & 0x80) {
654                         if (sco_in_addr) continue;
655                         sco_in_addr = endpoint->bEndpointAddress;
656                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
657                     } else {
658                         if (sco_out_addr) continue;
659                         sco_out_addr = endpoint->bEndpointAddress;
660                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
661                     }
662                     break;
663                 default:
664                     break;
665             }
666         }
667     }
668     libusb_free_config_descriptor(config_descriptor);
669     return 0;
670 }
671 
672 // returns index of found device or -1
673 static int scan_for_bt_device(libusb_device **devs, int start_index) {
674     int i;
675     for (i = start_index; devs[i] ; i++){
676         libusb_device * dev = devs[i];
677         int r = libusb_get_device_descriptor(dev, &desc);
678         if (r < 0) {
679             log_error("failed to get device descriptor");
680             return 0;
681         }
682 
683         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
684                desc.idVendor, desc.idProduct,
685                libusb_get_bus_number(dev), libusb_get_device_address(dev),
686                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
687 
688         // Detect USB Dongle based Class, Subclass, and Protocol
689         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
690         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
691         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
692         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
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     log_info("claiming interface 1...");
770     r = libusb_claim_interface(aHandle, 1);
771     if (r < 0) {
772         log_error("Error %d claiming interface 1: - disabling SCO over HCI", r);
773     } else {
774         sco_enabled = 1;
775     }
776 #endif
777 
778     return 0;
779 }
780 
781 static libusb_device_handle * try_open_device(libusb_device * device){
782     int r;
783 
784     libusb_device_handle * dev_handle;
785     r = libusb_open(device, &dev_handle);
786 
787     if (r < 0) {
788         log_error("libusb_open failed!");
789         dev_handle = NULL;
790         return NULL;
791     }
792 
793     log_info("libusb open %d, handle %p", r, dev_handle);
794 
795     // reset device (Not currently possible under FreeBSD 11.x/12.x due to usb framework)
796 #if !defined(__FreeBSD__)
797     r = libusb_reset_device(dev_handle);
798     if (r < 0) {
799         log_error("libusb_reset_device failed!");
800         libusb_close(dev_handle);
801         return NULL;
802     }
803 #endif
804     return dev_handle;
805 }
806 
807 #ifdef ENABLE_SCO_OVER_HCI
808 
809 static int usb_sco_start(void){
810 
811     printf("usb_sco_start\n");
812     log_info("usb_sco_start");
813 
814     sco_state_machine_init();
815     sco_ring_init();
816 
817     int alt_setting;
818     if (sco_voice_setting & 0x0020){
819         // 16-bit PCM
820         alt_setting = alt_setting_16_bit[sco_num_connections-1];
821     } else {
822         // 8-bit PCM or mSBC
823         alt_setting = alt_setting_8_bit[sco_num_connections-1];
824     }
825     // derive iso packet size from alt setting
826     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
827 
828     log_info("Switching to setting %u on interface 1..", alt_setting);
829     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
830     if (r < 0) {
831         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
832         return r;
833     }
834 
835     // incoming
836     int c;
837     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
838         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
839         if (!sco_in_transfer[c]) {
840             usb_close();
841             return LIBUSB_ERROR_NO_MEM;
842         }
843         // configure sco_in handlers
844         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
845             hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
846         libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
847         r = libusb_submit_transfer(sco_in_transfer[c]);
848         if (r) {
849             log_error("Error submitting isochronous in transfer %d", r);
850             usb_close();
851             return r;
852         }
853     }
854 
855     // outgoing
856     for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
857         sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
858         sco_out_transfers_in_flight[c] = 0;
859     }
860     return 0;
861 }
862 
863 static void usb_sco_stop(void){
864 
865     printf("usb_sco_stop\n");
866 
867     log_info("usb_sco_stop");
868     sco_shutdown = 1;
869 
870     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
871 
872     int c;
873     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
874         libusb_cancel_transfer(sco_in_transfer[c]);
875     }
876 
877     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
878         if (sco_out_transfers_in_flight[c]) {
879             libusb_cancel_transfer(sco_out_transfers[c]);
880         } else {
881             libusb_free_transfer(sco_out_transfers[c]);
882             sco_out_transfers[c] = 0;
883         }
884     }
885 
886     // wait until all transfers are completed
887     int completed = 0;
888     while (!completed){
889         struct timeval tv;
890         memset(&tv, 0, sizeof(struct timeval));
891         libusb_handle_events_timeout(NULL, &tv);
892         // check if all done
893         completed = 1;
894 
895         // Cancel all synchronous transfer
896         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
897             if (sco_in_transfer[c]){
898                 completed = 0;
899                 break;
900             }
901         }
902 
903         if (!completed) continue;
904 
905         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
906             if (sco_out_transfers[c]){
907                 completed = 0;
908                 break;
909             }
910         }
911     }
912     sco_shutdown = 0;
913     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
914 
915     log_info("Switching to setting %u on interface 1..", 0);
916     int r = libusb_set_interface_alt_setting(handle, 1, 0);
917     if (r < 0) {
918         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
919         return;
920     }
921 
922     printf("usb_sco_stop done\n");
923 }
924 
925 
926 
927 #endif
928 
929 static int usb_open(void){
930     int r;
931 
932     if (usb_transport_open) return 0;
933 
934     handle_packet = NULL;
935 
936     // default endpoint addresses
937     event_in_addr = 0x81; // EP1, IN interrupt
938     acl_in_addr =   0x82; // EP2, IN bulk
939     acl_out_addr =  0x02; // EP2, OUT bulk
940     sco_in_addr  =  0x83; // EP3, IN isochronous
941     sco_out_addr =  0x03; // EP3, OUT isochronous
942 
943     // USB init
944     r = libusb_init(NULL);
945     if (r < 0) return -1;
946 
947     libusb_state = LIB_USB_OPENED;
948 
949     // configure debug level
950     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
951 
952     libusb_device * dev = NULL;
953 
954 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
955 
956     // Use a specified device
957     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
958     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
959 
960     if (!handle){
961         log_error("libusb_open_device_with_vid_pid failed!");
962         usb_close();
963         return -1;
964     }
965     log_info("libusb open %d, handle %p", r, handle);
966 
967     r = prepare_device(handle);
968     if (r < 0){
969         usb_close();
970         return -1;
971     }
972 
973     dev = libusb_get_device(aHandle);
974     r = scan_for_bt_endpoints(dev);
975     if (r < 0){
976         usb_close();
977         return -1;
978     }
979 
980 #else
981     // Scan system for an appropriate devices
982     libusb_device **devs;
983     ssize_t num_devices;
984 
985     log_info("Scanning for USB Bluetooth device");
986     num_devices = libusb_get_device_list(NULL, &devs);
987     if (num_devices < 0) {
988         usb_close();
989         return -1;
990     }
991 
992     if (usb_path_len){
993         int i;
994         for (i=0;i<num_devices;i++){
995             uint8_t port_numbers[USB_MAX_PATH_LEN];
996             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
997             if (len != usb_path_len) continue;
998             if (memcmp(usb_path, port_numbers, len) == 0){
999                 log_info("USB device found at specified path");
1000                 handle = try_open_device(devs[i]);
1001                 if (!handle) continue;
1002 
1003                 r = prepare_device(handle);
1004                 if (r < 0) {
1005                     handle = NULL;
1006                     continue;
1007                 }
1008 
1009                 dev = devs[i];
1010                 r = scan_for_bt_endpoints(dev);
1011                 if (r < 0) {
1012                     handle = NULL;
1013                     continue;
1014                 }
1015 
1016                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
1017                 break;
1018             };
1019         }
1020         if (!handle){
1021             log_error("USB device with given path not found");
1022             printf("USB device with given path not found\n");
1023             return -1;
1024         }
1025     } else {
1026 
1027         int deviceIndex = -1;
1028         while (true){
1029             // look for next Bluetooth dongle
1030             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
1031             if (deviceIndex < 0) break;
1032 
1033             log_info("USB Bluetooth device found, index %u", deviceIndex);
1034 
1035             handle = try_open_device(devs[deviceIndex]);
1036             if (!handle) continue;
1037 
1038             r = prepare_device(handle);
1039             if (r < 0) {
1040                 handle = NULL;
1041                 continue;
1042             }
1043 
1044             dev = devs[deviceIndex];
1045             r = scan_for_bt_endpoints(dev);
1046             if (r < 0) {
1047                 handle = NULL;
1048                 continue;
1049             }
1050 
1051             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1052             break;
1053         }
1054     }
1055 
1056     libusb_free_device_list(devs, 1);
1057 
1058     if (handle == 0){
1059         log_error("No USB Bluetooth device found");
1060         return -1;
1061     }
1062 
1063 #endif
1064 
1065     // allocate transfer handlers
1066     int c;
1067     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1068         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1069         if (!event_in_transfer[c]) {
1070             usb_close();
1071             return LIBUSB_ERROR_NO_MEM;
1072         }
1073     }
1074     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1075         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1076         if (!acl_in_transfer[c]) {
1077             usb_close();
1078             return LIBUSB_ERROR_NO_MEM;
1079         }
1080     }
1081 
1082     command_out_transfer = libusb_alloc_transfer(0);
1083     acl_out_transfer     = libusb_alloc_transfer(0);
1084 
1085     // TODO check for error
1086 
1087     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1088 
1089     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1090         // configure event_in handlers
1091         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1092                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1093         r = libusb_submit_transfer(event_in_transfer[c]);
1094         if (r) {
1095             log_error("Error submitting interrupt transfer %d", r);
1096             usb_close();
1097             return r;
1098         }
1099     }
1100 
1101     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1102         // configure acl_in handlers
1103         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1104                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1105         r = libusb_submit_transfer(acl_in_transfer[c]);
1106         if (r) {
1107             log_error("Error submitting bulk in transfer %d", r);
1108             usb_close();
1109             return r;
1110         }
1111 
1112      }
1113 
1114  #if 0
1115     // Check for pollfds functionality
1116     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1117 #else
1118     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation
1119     doing_pollfds = 0;
1120 #endif
1121 
1122     if (doing_pollfds) {
1123         log_info("Async using pollfds:");
1124 
1125         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1126         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1127         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1128         if (!pollfd_data_sources){
1129             log_error("Cannot allocate data sources for pollfds");
1130             usb_close();
1131             return 1;
1132         }
1133         memset(pollfd_data_sources, 0, sizeof(btstack_data_source_t) * num_pollfds);
1134         for (r = 0 ; r < num_pollfds ; r++) {
1135             btstack_data_source_t *ds = &pollfd_data_sources[r];
1136             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1137             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1138             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1139             btstack_run_loop_add_data_source(ds);
1140             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1141         }
1142         free(pollfd);
1143     } else {
1144         log_info("Async using timers:");
1145 
1146         usb_timer.process = usb_process_ts;
1147         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1148         btstack_run_loop_add_timer(&usb_timer);
1149         usb_timer_active = 1;
1150     }
1151 
1152     usb_transport_open = 1;
1153 
1154     return 0;
1155 }
1156 
1157 static int usb_close(void){
1158     int c;
1159     int completed = 0;
1160 
1161     if (!usb_transport_open) return 0;
1162 
1163     log_info("usb_close");
1164 
1165     switch (libusb_state){
1166         case LIB_USB_CLOSED:
1167             break;
1168 
1169         case LIB_USB_TRANSFERS_ALLOCATED:
1170             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1171 
1172             if(usb_timer_active) {
1173                 btstack_run_loop_remove_timer(&usb_timer);
1174                 usb_timer_active = 0;
1175             }
1176 
1177             if (doing_pollfds){
1178                 int r;
1179                 for (r = 0 ; r < num_pollfds ; r++) {
1180                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1181                     btstack_run_loop_remove_data_source(ds);
1182                 }
1183                 free(pollfd_data_sources);
1184                 pollfd_data_sources = NULL;
1185                 num_pollfds = 0;
1186                 doing_pollfds = 0;
1187             }
1188 
1189             /* fall through */
1190 
1191         case LIB_USB_INTERFACE_CLAIMED:
1192             // Cancel all transfers, ignore warnings for this
1193             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1194             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1195                 if (event_in_transfer[c]){
1196                     log_info("cancel event_in_transfer[%u] = %p", c, event_in_transfer[c]);
1197                     libusb_cancel_transfer(event_in_transfer[c]);
1198                 }
1199             }
1200             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1201                 if (acl_in_transfer[c]){
1202                     log_info("cancel acl_in_transfer[%u] = %p", c, acl_in_transfer[c]);
1203                     libusb_cancel_transfer(acl_in_transfer[c]);
1204                 }
1205             }
1206 #ifdef ENABLE_SCO_OVER_HCI
1207             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1208                 if (sco_in_transfer[c]){
1209                     log_info("cancel sco_in_transfer[%u] = %p", c, sco_in_transfer[c]);
1210                     libusb_cancel_transfer(sco_in_transfer[c]);
1211                 }
1212             }
1213             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1214                 if (sco_out_transfers_in_flight[c]) {
1215                     log_info("cancel sco_out_transfers[%u] = %p", c, sco_out_transfers[c]);
1216                     libusb_cancel_transfer(sco_out_transfers[c]);
1217                 } else {
1218                     libusb_free_transfer(sco_out_transfers[c]);
1219                     sco_out_transfers[c] = 0;
1220                 }
1221             }
1222 #endif
1223             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1224 
1225             // wait until all transfers are completed - or 20 iterations
1226             int countdown = 20;
1227             while (!completed){
1228 
1229                 if (--countdown == 0){
1230                     log_info("Not all transfers cancelled, leaking a bit.");
1231                     break;
1232                 }
1233 
1234                 struct timeval tv;
1235                 memset(&tv, 0, sizeof(struct timeval));
1236                 libusb_handle_events_timeout(NULL, &tv);
1237                 // check if all done
1238                 completed = 1;
1239                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1240                     if (event_in_transfer[c]) {
1241                         log_info("event_in_transfer[%u] still active (%p)", c, event_in_transfer[c]);
1242                         completed = 0;
1243                         break;
1244                     }
1245                 }
1246 
1247                 if (!completed) continue;
1248 
1249                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1250                     if (acl_in_transfer[c]) {
1251                         log_info("acl_in_transfer[%u] still active (%p)", c, acl_in_transfer[c]);
1252                         completed = 0;
1253                         break;
1254                     }
1255                 }
1256 
1257 #ifdef ENABLE_SCO_OVER_HCI
1258                 if (!completed) continue;
1259 
1260                 // Cancel all synchronous transfer
1261                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1262                     if (sco_in_transfer[c]){
1263                         log_info("sco_in_transfer[%u] still active (%p)", c, sco_in_transfer[c]);
1264                         completed = 0;
1265                         break;
1266                     }
1267                 }
1268 
1269                 if (!completed) continue;
1270 
1271                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1272                     if (sco_out_transfers[c]){
1273                         log_info("sco_out_transfers[%u] still active (%p)", c, sco_out_transfers[c]);
1274                         completed = 0;
1275                         break;
1276                     }
1277                 }
1278                 sco_enabled = 0;
1279 #endif
1280             }
1281 
1282             // finally release interface
1283             libusb_release_interface(handle, 0);
1284 #ifdef ENABLE_SCO_OVER_HCI
1285             libusb_release_interface(handle, 1);
1286 #endif
1287             log_info("Libusb shutdown complete");
1288 
1289 			/* fall through */
1290 
1291         case LIB_USB_DEVICE_OPENDED:
1292             libusb_close(handle);
1293 
1294 			/* fall through */
1295 
1296         case LIB_USB_OPENED:
1297             libusb_exit(NULL);
1298             break;
1299 
1300 		default:
1301 			btstack_assert(false);
1302 			break;
1303     }
1304 
1305     libusb_state = LIB_USB_CLOSED;
1306     handle = NULL;
1307     usb_transport_open = 0;
1308 
1309     return 0;
1310 }
1311 
1312 static int usb_send_cmd_packet(uint8_t *packet, int size){
1313     int r;
1314 
1315     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1316 
1317     // async
1318     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1319     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1320 
1321     // prepare transfer
1322     int completed = 0;
1323     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1324     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1325 
1326     // update stata before submitting transfer
1327     usb_command_active = 1;
1328 
1329     // submit transfer
1330     r = libusb_submit_transfer(command_out_transfer);
1331 
1332     if (r < 0) {
1333         usb_command_active = 0;
1334         log_error("Error submitting cmd transfer %d", r);
1335         return -1;
1336     }
1337 
1338     return 0;
1339 }
1340 
1341 static int usb_send_acl_packet(uint8_t *packet, int size){
1342     int r;
1343 
1344     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1345 
1346     // log_info("usb_send_acl_packet enter, size %u", size);
1347 
1348     // prepare transfer
1349     int completed = 0;
1350     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1351         async_callback, &completed, 0);
1352     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1353 
1354     // update stata before submitting transfer
1355     usb_acl_out_active = 1;
1356 
1357     r = libusb_submit_transfer(acl_out_transfer);
1358     if (r < 0) {
1359         usb_acl_out_active = 0;
1360         log_error("Error submitting acl transfer, %d", r);
1361         return -1;
1362     }
1363 
1364     return 0;
1365 }
1366 
1367 static int usb_can_send_packet_now(uint8_t packet_type){
1368     switch (packet_type){
1369         case HCI_COMMAND_DATA_PACKET:
1370             return !usb_command_active;
1371         case HCI_ACL_DATA_PACKET:
1372             return !usb_acl_out_active;
1373 #ifdef ENABLE_SCO_OVER_HCI
1374         case HCI_SCO_DATA_PACKET:
1375             if (!sco_enabled) return 0;
1376             return sco_ring_have_space();
1377 #endif
1378         default:
1379             return 0;
1380     }
1381 }
1382 
1383 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1384     switch (packet_type){
1385         case HCI_COMMAND_DATA_PACKET:
1386             return usb_send_cmd_packet(packet, size);
1387         case HCI_ACL_DATA_PACKET:
1388             return usb_send_acl_packet(packet, size);
1389 #ifdef ENABLE_SCO_OVER_HCI
1390         case HCI_SCO_DATA_PACKET:
1391             if (!sco_enabled) return -1;
1392             return usb_send_sco_packet(packet, size);
1393 #endif
1394         default:
1395             return -1;
1396     }
1397 }
1398 
1399 #ifdef ENABLE_SCO_OVER_HCI
1400 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1401     if (!sco_enabled) return;
1402 
1403     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1404 
1405     if (num_connections != sco_num_connections){
1406         sco_voice_setting = voice_setting;
1407         if (sco_num_connections){
1408             usb_sco_stop();
1409         }
1410         sco_num_connections = num_connections;
1411         if (num_connections){
1412             usb_sco_start();
1413         }
1414     }
1415 }
1416 #endif
1417 
1418 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1419     log_info("registering packet handler");
1420     packet_handler = handler;
1421 }
1422 
1423 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1424     UNUSED(packet_type);
1425     UNUSED(packet);
1426     UNUSED(size);
1427 }
1428 
1429 // get usb singleton
1430 const hci_transport_t * hci_transport_usb_instance(void) {
1431     if (!hci_transport_usb) {
1432         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1433         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1434         hci_transport_usb->name                          = "H2_LIBUSB";
1435         hci_transport_usb->open                          = usb_open;
1436         hci_transport_usb->close                         = usb_close;
1437         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1438         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1439         hci_transport_usb->send_packet                   = usb_send_packet;
1440 #ifdef ENABLE_SCO_OVER_HCI
1441         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1442 #endif
1443     }
1444     return hci_transport_usb;
1445 }
1446