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