xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision 883fce102a0c89c52a97a5f32faa9148c871c1e4)
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     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         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     for( int i=0; i<list->nbr; ++i ) {
279         usb_transfer_list_entry_t *current = &list->entries[i];
280         if( current->in_flight ) {
281             libusb_cancel_transfer( current->t );
282         }
283     }
284 }
285 
286 static int usb_transfer_list_in_flight( usb_transfer_list_t *list ) {
287     int cnt = 0;
288     for(int i=0; i<list->nbr; ++i) {
289         usb_transfer_list_entry_t *entry = &list->entries[i];
290         if( entry->in_flight ) {
291             ++cnt;
292         }
293     }
294     return cnt;
295 }
296 
297 
298 static void usb_transfer_list_free_entry( struct libusb_transfer *transfer ) {
299     usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)transfer->user_data;
300     free( current->data );
301     libusb_free_transfer( transfer );
302     current->in_flight = false;
303     current->t = NULL;
304     current->data = NULL;
305 }
306 
307 void usb_transfer_list_free( usb_transfer_list_t *list ) {
308     for( int i=0; i<list->nbr; ++i ) {
309         usb_transfer_list_entry_t *entry = &list->entries[i];
310         assert( entry->in_flight == false );
311         if( entry->t ) {
312             usb_transfer_list_free_entry( entry->t );
313         }
314     }
315     free( list );
316 }
317 
318 static usb_transfer_list_t *default_transfer_list = NULL;
319 
320 // For (ab)use as a linked list of received packets
321 static list_head_t handle_packet_list = LIST_HEAD_INIT(handle_packet_list);
322 
323 static void enqueue_transfer(struct libusb_transfer *transfer) {
324     usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)transfer->user_data;
325     assert( current != NULL );
326     list_add_tail( &current->list, &handle_packet_list );
327 }
328 
329 static void signal_acknowledge(void);
330 static void signal_sco_can_send_now(void);
331 
332 #ifdef ENABLE_SCO_OVER_HCI
333 
334 #ifdef _WIN32
335 #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"
336 #endif
337 
338 // incoming SCO
339 static H2_SCO_STATE sco_state;
340 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
341 static uint16_t sco_read_pos;
342 static uint16_t sco_bytes_to_read;
343 
344 // pause/resume
345 static uint16_t sco_voice_setting;
346 static int      sco_num_connections;
347 static bool     sco_activated;
348 
349 // dynamic SCO configuration
350 static uint16_t iso_packet_size;
351 static int      sco_enabled;
352 
353 usb_transfer_list_t *sco_transfer_list = NULL;
354 
355 #endif
356 
357 
358 static int doing_pollfds;
359 static int num_pollfds;
360 static btstack_data_source_t * pollfd_data_sources;
361 
362 static void usb_transport_response_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type);
363 static btstack_data_source_t transport_response;
364 
365 static btstack_timer_source_t usb_timer;
366 static int usb_timer_active;
367 
368 // endpoint addresses
369 static int event_in_addr;
370 static int acl_in_addr;
371 static int acl_out_addr;
372 static int sco_in_addr;
373 static int sco_out_addr;
374 
375 // device info
376 static int usb_path_len;
377 static uint8_t usb_path[USB_MAX_PATH_LEN];
378 static uint16_t usb_vendor_id;
379 static uint16_t usb_product_id;
380 
381 // transport interface state
382 static int usb_transport_open;
383 
384 static void hci_transport_h2_libusb_emit_usb_info(void) {
385     uint8_t event[7 + USB_MAX_PATH_LEN];
386     uint16_t pos = 0;
387     event[pos++] = HCI_EVENT_TRANSPORT_USB_INFO;
388     event[pos++] = 5 + usb_path_len;
389     little_endian_store_16(event, pos, usb_vendor_id);
390     pos+=2;
391     little_endian_store_16(event, pos, usb_product_id);
392     pos+=2;
393     event[pos++] = usb_path_len;
394     memcpy(&event[pos], usb_path, usb_path_len);
395     pos += usb_path_len;
396     (*packet_handler)(HCI_EVENT_PACKET, event, pos);
397 }
398 
399 void hci_transport_usb_add_device(uint16_t vendor_id, uint16_t product_id) {
400     usb_known_device_t * device = malloc(sizeof(usb_known_device_t));
401     if (device != NULL) {
402         device->vendor_id = vendor_id;
403         device->product_id = product_id;
404         btstack_linked_list_add(&usb_knwon_devices, (btstack_linked_item_t *) device);
405     }
406 }
407 
408 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
409     if (len > USB_MAX_PATH_LEN || !port_numbers){
410         log_error("hci_transport_usb_set_path: len or port numbers invalid");
411         return;
412     }
413     usb_path_len = len;
414     memcpy(usb_path, port_numbers, len);
415 }
416 
417 LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer) {
418     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) {
419         log_info("shutdown, transfer %p", transfer);
420         usb_transfer_list_free_entry( transfer );
421         return;
422     }
423 
424     int r;
425     // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
426 
427     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
428         enqueue_transfer(transfer);
429     } else if (transfer->status == LIBUSB_TRANSFER_STALL){
430         log_info("-> Transfer stalled, trying again");
431         r = libusb_clear_halt(handle, transfer->endpoint);
432         if (r) {
433             log_error("Error rclearing halt %d", r);
434         }
435         r = libusb_submit_transfer(transfer);
436         if (r) {
437             log_error("Error re-submitting transfer %d", r);
438         }
439     } else if ( transfer->status == LIBUSB_TRANSFER_CANCELLED ) {
440         if(( transfer->endpoint == sco_in_addr) || (transfer->endpoint == sco_out_addr)) {
441             usb_transfer_list_release( sco_transfer_list, transfer );
442         } else {
443             usb_transfer_list_release( default_transfer_list, transfer );
444         }
445     } else {
446         log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
447         // No usable data, just resubmit packet
448         r = libusb_submit_transfer(transfer);
449         if (r) {
450             log_error("Error re-submitting transfer %d", r);
451         }
452     }
453     // log_info("end async_callback");
454 }
455 
456 
457 #ifdef ENABLE_SCO_OVER_HCI
458 static int usb_send_sco_packet(uint8_t *packet, int size){
459     int r;
460 
461     if( !sco_activated ) {
462         log_error("sco send without beeing active!");
463         return -1;
464     }
465 
466     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
467 
468     struct libusb_transfer *transfer = usb_transfer_list_acquire( sco_transfer_list );
469     uint8_t *data = transfer->buffer;
470     void *user_data = transfer->user_data;
471 
472     // log_info("usb_send_acl_packet enter, size %u", size);
473 
474     // store packet in free slot
475     memcpy(data, packet, size);
476 
477     // setup transfer
478     // 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);
479     libusb_fill_iso_transfer(transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, user_data, 0);
480     libusb_set_iso_packet_lengths(transfer, iso_packet_size);
481     r = libusb_submit_transfer(transfer);
482     if (r < 0) {
483         log_error("Error submitting sco transfer, %d", r);
484         return -1;
485     }
486 
487     // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active);
488     signal_acknowledge();
489 
490     if( !usb_transfer_list_empty( sco_transfer_list ) ) {
491         signal_sco_can_send_now();
492     }
493 
494     return 0;
495 }
496 
497 static void sco_state_machine_init(void){
498     sco_state = H2_W4_SCO_HEADER;
499     sco_read_pos = 0;
500     sco_bytes_to_read = 3;
501 }
502 
503 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
504     while (size){
505         if (size < sco_bytes_to_read){
506             // just store incomplete data
507             memcpy(&sco_buffer[sco_read_pos], buffer, size);
508             sco_read_pos      += size;
509             sco_bytes_to_read -= size;
510             return;
511         }
512         // copy requested data
513         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
514         sco_read_pos += sco_bytes_to_read;
515         buffer       += sco_bytes_to_read;
516         size         -= sco_bytes_to_read;
517 
518         // chunk read successfully, next action
519         switch (sco_state){
520             case H2_W4_SCO_HEADER:
521                 sco_state = H2_W4_PAYLOAD;
522                 sco_bytes_to_read = sco_buffer[2];
523                 break;
524             case H2_W4_PAYLOAD:
525                 // packet complete
526                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
527                 sco_state_machine_init();
528                 break;
529 			default:
530 				btstack_assert(false);
531 				break;
532         }
533     }
534 }
535 #endif
536 
537 static void handle_completed_transfer(struct libusb_transfer *transfer){
538 
539     int resubmit = 0;
540     assert(transfer->user_data != NULL );
541     if (transfer->endpoint == event_in_addr) {
542         packet_handler(HCI_EVENT_PACKET, transfer->buffer, transfer->actual_length);
543         resubmit = 1;
544     } else if (transfer->endpoint == acl_in_addr) {
545         // log_info("-> acl");
546         packet_handler(HCI_ACL_DATA_PACKET, transfer->buffer, transfer->actual_length);
547         resubmit = 1;
548     } else if (transfer->endpoint == 0){
549         // log_info("command done, size %u", transfer->actual_length);
550 //        printf("%s cmd release\n", __FUNCTION__ );
551         usb_transfer_list_release( default_transfer_list, transfer );
552     } else if (transfer->endpoint == acl_out_addr){
553         // log_info("acl out done, size %u", transfer->actual_length);
554 //        printf("%s acl release\n", __FUNCTION__ );
555         usb_transfer_list_release( default_transfer_list, transfer );
556 #ifdef ENABLE_SCO_OVER_HCI
557     } else if (transfer->endpoint == sco_in_addr) {
558         // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
559 
560         // give the transfer back to the pool, without resubmiting
561         if( !sco_activated ) {
562             usb_transfer_list_release( sco_transfer_list, transfer );
563             return;
564         }
565 
566         int i;
567         for (i = 0; i < transfer->num_iso_packets; i++) {
568             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
569             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
570                 log_error("Error: pack %u status %d\n", i, pack->status);
571                 continue;
572             }
573             if (!pack->actual_length) continue;
574             uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
575             handle_isochronous_data(data, pack->actual_length);
576         }
577         resubmit = 1;
578     } else if (transfer->endpoint == sco_out_addr){
579         int i;
580         for (i = 0; i < transfer->num_iso_packets; i++) {
581             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
582             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
583                 log_error("Error: pack %u status %d\n", i, pack->status);
584             }
585         }
586         usb_transfer_list_release( sco_transfer_list, transfer );
587         if( !sco_activated ) {
588             return;
589         }
590         // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
591         //     transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
592         //     transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
593         //     transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
594         // notify upper layer if there's space for new SCO packets
595 
596         if (!usb_transfer_list_empty(sco_transfer_list)) {
597             signal_sco_can_send_now();
598         }
599         // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active);
600 #endif
601     } else {
602         log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
603     }
604 
605     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
606 
607     if (resubmit){
608         // Re-submit transfer
609         int r = libusb_submit_transfer(transfer);
610         if (r) {
611             log_error("Error re-submitting transfer %d", r);
612         }
613     }
614 }
615 
616 void usb_handle_pending_events(void);
617 void usb_handle_pending_events(void) {
618     struct timeval tv = { 0 };
619     libusb_handle_events_timeout_completed(NULL, &tv, NULL);
620 }
621 
622 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
623 
624     UNUSED(ds);
625     UNUSED(callback_type);
626 
627    if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
628 
629     // log_info("begin usb_process_ds");
630     // always handling an event as we're called when data is ready
631     usb_handle_pending_events();
632 
633     // Handle any packet in the order that they were received
634     while (!list_empty(&handle_packet_list)) {
635         // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
636 
637         // pop next transfer
638         usb_transfer_list_entry_t *current = (usb_transfer_list_entry_t*)list_pop_front( &handle_packet_list );
639 
640         // handle transfer
641         handle_completed_transfer(current->t);
642 
643         // handle case where libusb_close might be called by hci packet handler
644         if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
645     }
646     // log_info("end usb_process_ds");
647 }
648 
649 static void usb_process_ts(btstack_timer_source_t *timer) {
650 
651     UNUSED(timer);
652 
653     // log_info("in usb_process_ts");
654 
655     // timer is deactive, when timer callback gets called
656     usb_timer_active = 0;
657 
658     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
659 
660     // actually handled the packet in the pollfds function
661     usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
662 
663     // Get the amount of time until next event is due
664     long msec = ASYNC_POLLING_INTERVAL_MS;
665 
666     // Activate timer
667     btstack_run_loop_set_timer(&usb_timer, msec);
668     btstack_run_loop_add_timer(&usb_timer);
669     usb_timer_active = 1;
670 
671     return;
672 }
673 
674 
675 static int scan_for_bt_endpoints(libusb_device *dev) {
676     int r;
677 
678     event_in_addr = 0;
679     acl_in_addr = 0;
680     acl_out_addr = 0;
681     sco_out_addr = 0;
682     sco_in_addr = 0;
683 
684     // get endpoints from interface descriptor
685     struct libusb_config_descriptor *config_descriptor;
686     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
687     if (r < 0) return r;
688 
689     int num_interfaces = config_descriptor->bNumInterfaces;
690     log_info("active configuration has %u interfaces", num_interfaces);
691 
692     int i;
693     for (i = 0; i < num_interfaces ; i++){
694         const struct libusb_interface *interface = &config_descriptor->interface[i];
695         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
696         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
697 
698         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
699 
700         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
701             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
702 
703             switch (endpoint->bmAttributes & 0x3){
704                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
705                     if (event_in_addr) continue;
706                     event_in_addr = endpoint->bEndpointAddress;
707                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
708                     break;
709                 case LIBUSB_TRANSFER_TYPE_BULK:
710                     if (endpoint->bEndpointAddress & 0x80) {
711                         if (acl_in_addr) continue;
712                         acl_in_addr = endpoint->bEndpointAddress;
713                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
714                     } else {
715                         if (acl_out_addr) continue;
716                         acl_out_addr = endpoint->bEndpointAddress;
717                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
718                     }
719                     break;
720                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
721                     if (endpoint->bEndpointAddress & 0x80) {
722                         if (sco_in_addr) continue;
723                         sco_in_addr = endpoint->bEndpointAddress;
724                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
725                     } else {
726                         if (sco_out_addr) continue;
727                         sco_out_addr = endpoint->bEndpointAddress;
728                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
729                     }
730                     break;
731                 default:
732                     break;
733             }
734         }
735     }
736     libusb_free_config_descriptor(config_descriptor);
737     return 0;
738 }
739 
740 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
741 
742 // list of known devices, using VendorID/ProductID tuples
743 static const uint16_t known_bluetooth_devices[] = {
744     // BCM20702A0 - DeLOCK Bluetooth 4.0
745     0x0a5c, 0x21e8,
746     // BCM20702A0 - Asus BT400
747     0x0b05, 0x17cb,
748     // BCM20702B0 - Generic USB Detuned Class 1 @ 20 MHz
749     0x0a5c, 0x22be,
750     // nRF5x Zephyr USB HCI, e.g nRF52840-PCA10056
751     0x2fe3, 0x0100,
752     0x2fe3, 0x000b,
753 };
754 
755 static int num_known_devices = sizeof(known_bluetooth_devices) / sizeof(uint16_t) / 2;
756 
757 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
758     int i;
759     for (i=0; i<num_known_devices; i++){
760         if (known_bluetooth_devices[i*2] == vendor_id && known_bluetooth_devices[i*2+1] == product_id){
761             return 1;
762         }
763     }
764     btstack_linked_list_iterator_t it;
765     btstack_linked_list_iterator_init(&it, &usb_knwon_devices);
766     while (btstack_linked_list_iterator_has_next(&it)) {
767         usb_known_device_t * device = (usb_known_device_t *) btstack_linked_list_iterator_next(&it);
768         if (device->vendor_id != vendor_id) continue;
769         if (device->product_id != product_id) continue;
770         return 1;
771     }
772     return 0;
773 }
774 
775 // returns index of found device or -1
776 static int scan_for_bt_device(libusb_device **devs, int start_index) {
777     int i;
778     for (i = start_index; devs[i] ; i++){
779         libusb_device * dev = devs[i];
780         int r = libusb_get_device_descriptor(dev, &desc);
781         if (r < 0) {
782             log_error("failed to get device descriptor");
783             return 0;
784         }
785 
786         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
787                desc.idVendor, desc.idProduct,
788                libusb_get_bus_number(dev), libusb_get_device_address(dev),
789                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
790 
791         // Detect USB Dongle based Class, Subclass, and Protocol
792         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
793         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
794         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
795         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
796             return i;
797         }
798 
799         // Detect USB Dongle based on whitelist
800         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
801             return i;
802         }
803     }
804     return -1;
805 }
806 #endif
807 
808 static int prepare_device(libusb_device_handle * aHandle){
809 
810     // get device path
811     libusb_device * device = libusb_get_device(aHandle);
812     usb_path_len = libusb_get_port_numbers(device, usb_path, USB_MAX_PATH_LEN);
813 
814     int r;
815     int kernel_driver_detached = 0;
816 
817     // Detach OS driver (not possible for OS X, FreeBSD, and Windows)
818 #if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
819     r = libusb_kernel_driver_active(aHandle, 0);
820     if (r < 0) {
821         log_error("libusb_kernel_driver_active error %d", r);
822         libusb_close(aHandle);
823         return r;
824     }
825 
826     if (r == 1) {
827         r = libusb_detach_kernel_driver(aHandle, 0);
828         if (r < 0) {
829             log_error("libusb_detach_kernel_driver error %d", r);
830             libusb_close(aHandle);
831             return r;
832         }
833         kernel_driver_detached = 1;
834     }
835     log_info("libusb_detach_kernel_driver");
836 #endif
837 
838     const int configuration = 1;
839     log_info("setting configuration %d...", configuration);
840     r = libusb_set_configuration(aHandle, configuration);
841     if (r < 0) {
842         log_error("Error libusb_set_configuration: %d", r);
843         if (kernel_driver_detached){
844             libusb_attach_kernel_driver(aHandle, 0);
845         }
846         libusb_close(aHandle);
847         return r;
848     }
849 
850     // reserve access to device
851     log_info("claiming interface 0...");
852     r = libusb_claim_interface(aHandle, 0);
853     if (r < 0) {
854         log_error("Error %d claiming interface 0", r);
855         if (kernel_driver_detached){
856             libusb_attach_kernel_driver(aHandle, 0);
857         }
858         libusb_close(aHandle);
859         return r;
860     }
861 
862 #ifdef ENABLE_SCO_OVER_HCI
863     // get endpoints from interface descriptor
864     struct libusb_config_descriptor *config_descriptor;
865     r = libusb_get_active_config_descriptor(device, &config_descriptor);
866     if (r >= 0){
867         int num_interfaces = config_descriptor->bNumInterfaces;
868         if (num_interfaces > 1) {
869             r = libusb_claim_interface(aHandle, 1);
870             if (r < 0) {
871                 log_error("Error %d claiming interface 1: - disabling SCO over HCI", r);
872             } else {
873                 sco_enabled = 1;
874             }
875         } else {
876             log_info("Device has only on interface, disabling SCO over HCI");
877         }
878     }
879 #endif
880 
881     return 0;
882 }
883 
884 static libusb_device_handle * try_open_device(libusb_device * device){
885     int r;
886 
887     r = libusb_get_device_descriptor(device, &desc);
888     if (r < 0) {
889         log_error("libusb_get_device_descriptor failed!");
890         return NULL;
891     }
892     usb_vendor_id = desc.idVendor;
893     usb_product_id = desc.idProduct;
894 
895     libusb_device_handle * dev_handle;
896     r = libusb_open(device, &dev_handle);
897 
898     if (r < 0) {
899         log_error("libusb_open failed!");
900         dev_handle = NULL;
901         return NULL;
902     }
903 
904     log_info("libusb open %d, handle %p", r, dev_handle);
905 
906     // reset device (Not currently possible under FreeBSD 11.x/12.x due to usb framework)
907 #if !defined(__FreeBSD__)
908     r = libusb_reset_device(dev_handle);
909     if (r < 0) {
910         log_error("libusb_reset_device failed!");
911         libusb_close(dev_handle);
912         return NULL;
913     }
914 #endif
915     return dev_handle;
916 }
917 
918 #ifdef ENABLE_SCO_OVER_HCI
919 static int usb_sco_start(void){
920 
921     log_info("usb_sco_start");
922     if( sco_activated ) {
923         log_error("double sco start!");
924         return -1;
925     }
926     sco_activated = true;
927 
928     sco_state_machine_init();
929 
930     int alt_setting;
931     if (sco_voice_setting & 0x0020){
932         // 16-bit PCM
933         alt_setting = alt_setting_16_bit[sco_num_connections-1];
934     } else {
935         // 8-bit PCM or mSBC
936         alt_setting = alt_setting_8_bit[sco_num_connections-1];
937     }
938     // derive iso packet size from alt setting
939     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
940 
941     log_info("Switching to setting %u on interface 1..", alt_setting);
942     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
943     if (r < 0) {
944         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
945         return r;
946     }
947 
948 #ifdef DEBUG
949     int in_flight = usb_transfer_list_in_flight( sco_transfer_list );
950     // there need to be at least SCO_IN_BUFFER_COUNT packets available to
951     // fill them in below
952     assert( in_flight <= SCO_OUT_BUFFER_COUNT );
953 #endif
954 
955     // incoming
956     int c;
957     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
958 
959         struct libusb_transfer *transfer = usb_transfer_list_acquire( sco_transfer_list );
960         uint8_t *data = transfer->buffer;
961         void *user_data = transfer->user_data;
962 
963         // configure sco_in handlers
964         libusb_fill_iso_transfer(transfer, handle, sco_in_addr,
965                 data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, user_data, 0);
966         libusb_set_iso_packet_lengths(transfer, iso_packet_size);
967         r = libusb_submit_transfer(transfer);
968         if (r) {
969             log_error("Error submitting isochronous in transfer %d", r);
970             usb_close();
971             return r;
972         }
973     }
974     return 0;
975 }
976 
977 static void usb_sco_stop(void){
978 
979     log_info("usb_sco_stop");
980     sco_activated = false;
981 
982     usb_transfer_list_cancel( sco_transfer_list );
983 
984     log_info("Switching to setting %u on interface 1..", 0);
985     int r = libusb_set_interface_alt_setting(handle, 1, 0);
986     if (r < 0) {
987         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
988         return;
989     }
990 
991     log_info("usb_sco_stop done");
992 }
993 #endif
994 
995 void pollfd_added_cb(int fd, short events, void *user_data);
996 void pollfd_remove_cb(int fd, void *user_data);
997 
998 void pollfd_added_cb(int fd, short events, void *user_data) {
999     UNUSED(events);
1000     UNUSED(user_data);
1001     log_error("add fd: %d", fd);
1002     assert(0);
1003 }
1004 
1005 void pollfd_remove_cb(int fd, void *user_data) {
1006     UNUSED(user_data);
1007     log_error("remove fd: %d", fd);
1008     assert(0);
1009 }
1010 
1011 static int usb_open(void){
1012     int r;
1013 
1014     if (usb_transport_open) return 0;
1015 
1016     // default endpoint addresses
1017     event_in_addr = 0x81; // EP1, IN interrupt
1018     acl_in_addr =   0x82; // EP2, IN bulk
1019     acl_out_addr =  0x02; // EP2, OUT bulk
1020     sco_in_addr  =  0x83; // EP3, IN isochronous
1021     sco_out_addr =  0x03; // EP3, OUT isochronous
1022 
1023     // USB init
1024     r = libusb_init(NULL);
1025     if (r < 0) return -1;
1026 
1027     libusb_state = LIB_USB_OPENED;
1028 
1029     // configure debug level
1030     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1031 
1032     libusb_device * dev = NULL;
1033 
1034 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
1035 
1036     // Use a specified device
1037     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
1038     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
1039 
1040     if (!handle){
1041         log_error("libusb_open_device_with_vid_pid failed!");
1042         usb_close();
1043         return -1;
1044     }
1045     log_info("libusb open %d, handle %p", r, handle);
1046 
1047     r = prepare_device(handle);
1048     if (r < 0){
1049         usb_close();
1050         return -1;
1051     }
1052 
1053     dev = libusb_get_device(handle);
1054     r = scan_for_bt_endpoints(dev);
1055     if (r < 0){
1056         usb_close();
1057         return -1;
1058     }
1059 
1060     usb_vendor_id = USB_VENDOR_ID;
1061     usb_product_id = USB_PRODUCT_ID;
1062 
1063 #else
1064     // Scan system for an appropriate devices
1065     libusb_device **devs;
1066     ssize_t num_devices;
1067 
1068     log_info("Scanning for USB Bluetooth device");
1069     num_devices = libusb_get_device_list(NULL, &devs);
1070     if (num_devices < 0) {
1071         usb_close();
1072         return -1;
1073     }
1074 
1075     if (usb_path_len){
1076         int i;
1077         for (i=0;i<num_devices;i++){
1078             uint8_t port_numbers[USB_MAX_PATH_LEN];
1079             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
1080             if (len != usb_path_len) continue;
1081             if (memcmp(usb_path, port_numbers, len) == 0){
1082                 log_info("USB device found at specified path");
1083                 handle = try_open_device(devs[i]);
1084                 if (!handle) continue;
1085 
1086                 r = prepare_device(handle);
1087                 if (r < 0) {
1088                     handle = NULL;
1089                     continue;
1090                 }
1091 
1092                 dev = devs[i];
1093                 r = scan_for_bt_endpoints(dev);
1094                 if (r < 0) {
1095                     handle = NULL;
1096                     continue;
1097                 }
1098 
1099                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
1100                 break;
1101             };
1102         }
1103         if (!handle){
1104             log_error("USB device with given path not found");
1105             return -1;
1106         }
1107     } else {
1108 
1109         int deviceIndex = -1;
1110         while (true){
1111             // look for next Bluetooth dongle
1112             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
1113             if (deviceIndex < 0) break;
1114 
1115             log_info("USB Bluetooth device found, index %u", deviceIndex);
1116 
1117             handle = try_open_device(devs[deviceIndex]);
1118             if (!handle) continue;
1119 
1120             r = prepare_device(handle);
1121             if (r < 0) {
1122                 handle = NULL;
1123                 continue;
1124             }
1125 
1126             dev = devs[deviceIndex];
1127             r = scan_for_bt_endpoints(dev);
1128             if (r < 0) {
1129                 handle = NULL;
1130                 continue;
1131             }
1132 
1133             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1134             break;
1135         }
1136     }
1137 
1138     libusb_free_device_list(devs, 1);
1139 
1140     if (handle == 0){
1141         log_error("No USB Bluetooth device found");
1142         return -1;
1143     }
1144 
1145 #endif
1146 
1147     // allocate transfer handlers
1148     int c;
1149 
1150     default_transfer_list = usb_transfer_list_alloc(
1151             EVENT_OUT_BUFFER_COUNT+EVENT_IN_BUFFER_COUNT+ACL_IN_BUFFER_COUNT,
1152             0,
1153             LIBUSB_CONTROL_SETUP_SIZE + HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE ); // biggest packet ever to expect
1154 
1155 #ifdef ENABLE_SCO_OVER_HCI
1156     sco_transfer_list = usb_transfer_list_alloc(
1157             SCO_OUT_BUFFER_COUNT+SCO_IN_BUFFER_COUNT,
1158             NUM_ISO_PACKETS,
1159             SCO_PACKET_SIZE
1160             );
1161 #endif
1162 
1163     // TODO check for error
1164 
1165     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1166 
1167     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1168         struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list );
1169         uint8_t *data = transfer->buffer;
1170         void *user_data = transfer->user_data;
1171         // configure event_in handlers
1172         libusb_fill_interrupt_transfer(transfer, handle, event_in_addr,
1173                 data, HCI_ACL_BUFFER_SIZE, async_callback, user_data, 0);
1174         r = libusb_submit_transfer(transfer);
1175         if (r) {
1176             log_error("Error submitting interrupt transfer %d", r);
1177             usb_close();
1178             return r;
1179         }
1180     }
1181 
1182     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1183         struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list );
1184         usb_transfer_list_entry_t *transfer_meta_data = (usb_transfer_list_entry_t*)transfer->user_data;
1185         uint8_t *data = transfer_meta_data->data;
1186         void *user_data = transfer->user_data;
1187         // configure acl_in handlers
1188         libusb_fill_bulk_transfer(transfer, handle, acl_in_addr,
1189                 data + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, user_data, 0) ;
1190         r = libusb_submit_transfer(transfer);
1191         if (r) {
1192             log_error("Error submitting bulk in transfer %d", r);
1193             usb_close();
1194             return r;
1195         }
1196 
1197      }
1198 
1199     // Check for pollfds functionality
1200     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1201 
1202     libusb_set_pollfd_notifiers( NULL,  pollfd_added_cb, pollfd_remove_cb, NULL );
1203 
1204     if (doing_pollfds) {
1205         log_info("Async using pollfds:");
1206 
1207         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1208         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1209         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1210         if (!pollfd_data_sources){
1211             log_error("Cannot allocate data sources for pollfds");
1212             usb_close();
1213             return 1;
1214         }
1215         memset(pollfd_data_sources, 0, sizeof(btstack_data_source_t) * num_pollfds);
1216         for (r = 0 ; r < num_pollfds ; r++) {
1217             btstack_data_source_t *ds = &pollfd_data_sources[r];
1218             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1219             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1220             if( pollfd[r]->events & POLLIN )
1221                 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1222             else
1223                 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
1224             btstack_run_loop_add_data_source(ds);
1225             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1226         }
1227         libusb_free_pollfds(pollfd);
1228     } else {
1229         log_info("Async using timers:");
1230 
1231         usb_timer.process = usb_process_ts;
1232         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1233         btstack_run_loop_add_timer(&usb_timer);
1234         usb_timer_active = 1;
1235     }
1236 
1237     usb_transport_open = 1;
1238 
1239     hci_transport_h2_libusb_emit_usb_info();
1240 
1241     btstack_data_source_t *ds = &transport_response;
1242     btstack_run_loop_set_data_source_handler(ds, &usb_transport_response_ds);
1243     btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_POLL);
1244     btstack_run_loop_add_data_source(ds);
1245     return 0;
1246 }
1247 
1248 static int usb_close(void) {
1249     if (!usb_transport_open) return 0;
1250 
1251     log_info("usb_close");
1252 
1253     switch (libusb_state){
1254         case LIB_USB_CLOSED:
1255             break;
1256 
1257         case LIB_USB_TRANSFERS_ALLOCATED:
1258             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1259 
1260             if(usb_timer_active) {
1261                 btstack_run_loop_remove_timer(&usb_timer);
1262                 usb_timer_active = 0;
1263             }
1264 
1265             if (doing_pollfds){
1266                 int r;
1267                 for (r = 0 ; r < num_pollfds ; r++) {
1268                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1269                     btstack_run_loop_remove_data_source(ds);
1270                 }
1271                 free(pollfd_data_sources);
1272                 pollfd_data_sources = NULL;
1273                 num_pollfds = 0;
1274                 doing_pollfds = 0;
1275             }
1276 
1277             /* fall through */
1278 
1279         case LIB_USB_INTERFACE_CLAIMED:
1280             libusb_set_pollfd_notifiers( NULL, NULL, NULL, NULL );
1281             usb_transfer_list_cancel( default_transfer_list );
1282 #ifdef ENABLE_SCO_OVER_HCI
1283             usb_transfer_list_cancel( sco_transfer_list );
1284 #endif
1285 
1286             int in_flight_transfers = usb_transfer_list_in_flight( default_transfer_list );
1287 #ifdef ENABLE_SCO_OVER_HCI
1288             in_flight_transfers += usb_transfer_list_in_flight( sco_transfer_list );
1289 #endif
1290             while( in_flight_transfers > 0 ) {
1291                 struct timeval tv = { 0 };
1292                 libusb_handle_events_timeout(NULL, &tv);
1293 
1294                 in_flight_transfers = usb_transfer_list_in_flight( default_transfer_list );
1295 #ifdef ENABLE_SCO_OVER_HCI
1296                 in_flight_transfers += usb_transfer_list_in_flight( sco_transfer_list );
1297 #endif
1298             }
1299 
1300             usb_transfer_list_free( default_transfer_list );
1301 #ifdef ENABLE_SCO_OVER_HCI
1302             usb_transfer_list_free( sco_transfer_list );
1303             sco_enabled = 0;
1304 #endif
1305 
1306             // finally release interface
1307             libusb_release_interface(handle, 0);
1308 #ifdef ENABLE_SCO_OVER_HCI
1309             libusb_release_interface(handle, 1);
1310 #endif
1311             log_info("Libusb shutdown complete");
1312 
1313 			/* fall through */
1314 
1315         case LIB_USB_DEVICE_OPENDED:
1316             libusb_close(handle);
1317 
1318 			/* fall through */
1319 
1320         case LIB_USB_OPENED:
1321             libusb_exit(NULL);
1322             break;
1323 
1324 		default:
1325 			btstack_assert(false);
1326 			break;
1327     }
1328 
1329     libusb_state = LIB_USB_CLOSED;
1330     handle = NULL;
1331     usb_transport_open = 0;
1332 
1333     return 0;
1334 }
1335 
1336 static int acknowledge_count = 0;
1337 static void signal_acknowledge() {
1338     ++acknowledge_count;
1339     btstack_run_loop_poll_data_sources_from_irq();
1340 }
1341 
1342 static int sco_can_send_now_count = 0;
1343 static void signal_sco_can_send_now() {
1344     ++sco_can_send_now_count;
1345     btstack_run_loop_poll_data_sources_from_irq();
1346 }
1347 
1348 static void usb_transport_response_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
1349     UNUSED(ds);
1350     UNUSED(callback_type);
1351 //    printf("%s packet sent: %d sco can send now: %d\n", __FUNCTION__, acknowledge_count, sco_can_send_now_count);
1352     for(; acknowledge_count>0; --acknowledge_count) {
1353         static const uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0 };
1354         packet_handler(HCI_EVENT_PACKET, (uint8_t*)&event[0], sizeof(event));
1355     }
1356 
1357     for(; sco_can_send_now_count>0; --sco_can_send_now_count) {
1358         static const uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
1359         packet_handler(HCI_EVENT_PACKET, (uint8_t*)&event[0], sizeof(event));
1360     }
1361 
1362 }
1363 
1364 static int usb_send_cmd_packet(uint8_t *packet, int size){
1365     int r;
1366 
1367     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1368 //    printf("%s( %p, %d )\n", __FUNCTION__, packet, size );
1369 
1370     struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list );
1371     uint8_t *data = transfer->buffer;
1372     void *user_data = transfer->user_data;
1373 
1374     // async
1375     libusb_fill_control_setup(data, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1376     memcpy(data + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1377 
1378     // prepare transfer
1379     libusb_fill_control_transfer(transfer, handle, data, async_callback, user_data, 0);
1380 
1381     // submit transfer
1382     assert( transfer->user_data != NULL );
1383     r = libusb_submit_transfer(transfer);
1384 
1385     if (r < 0) {
1386         log_error("Error submitting cmd transfer %d", r);
1387         return -1;
1388     }
1389 
1390     signal_acknowledge();
1391 
1392     return 0;
1393 }
1394 
1395 static int usb_send_acl_packet(uint8_t *packet, int size){
1396     int r;
1397 
1398     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1399 //   printf("%s( %p, %d )\n", __FUNCTION__, packet, size );
1400     // log_info("usb_send_acl_packet enter, size %u", size);
1401 
1402     struct libusb_transfer *transfer = usb_transfer_list_acquire( default_transfer_list );
1403     uint8_t *data = transfer->buffer;
1404 
1405     // prepare transfer
1406     memcpy( data, packet, size );
1407     libusb_fill_bulk_transfer(transfer, handle, acl_out_addr, data, size,
1408         async_callback, transfer->user_data, 0);
1409 
1410     assert( transfer->user_data != NULL );
1411     r = libusb_submit_transfer(transfer);
1412 
1413     if (r < 0) {
1414         log_error("Error submitting acl transfer, %d", r);
1415         return -1;
1416     }
1417 
1418     signal_acknowledge();
1419 
1420     return 0;
1421 }
1422 
1423 static int usb_can_send_packet_now(uint8_t packet_type){
1424     switch (packet_type){
1425         case HCI_COMMAND_DATA_PACKET: {
1426             int ret = !usb_transfer_list_empty( default_transfer_list );
1427             if( !ret ) {
1428                 log_error("command transfers shouldn't be empty!");
1429             }
1430             return ret;
1431         }
1432         case HCI_ACL_DATA_PACKET: {
1433             int ret = !usb_transfer_list_empty( default_transfer_list );
1434             if( !ret ) {
1435                 log_error("acl transfers shouldn't be empty!");
1436             }
1437             return ret;
1438         }
1439 
1440 #ifdef ENABLE_SCO_OVER_HCI
1441         case HCI_SCO_DATA_PACKET: {
1442             if (!sco_enabled || !sco_activated) return 0;
1443             int ret = !usb_transfer_list_empty( sco_transfer_list );
1444             if( !ret ) {
1445                 log_error("sco transfers shouldn't be empty!");
1446             }
1447             return ret;
1448         }
1449 #endif
1450         default:
1451             return 0;
1452     }
1453 }
1454 
1455 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1456     switch (packet_type){
1457         case HCI_COMMAND_DATA_PACKET:
1458             return usb_send_cmd_packet(packet, size);
1459         case HCI_ACL_DATA_PACKET:
1460             return usb_send_acl_packet(packet, size);
1461 #ifdef ENABLE_SCO_OVER_HCI
1462         case HCI_SCO_DATA_PACKET:
1463             if (!sco_enabled) return -1;
1464             return usb_send_sco_packet(packet, size);
1465 #endif
1466         default:
1467             return -1;
1468     }
1469 }
1470 
1471 #ifdef ENABLE_SCO_OVER_HCI
1472 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1473     if (!sco_enabled) return;
1474 
1475     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1476 
1477     if (num_connections != sco_num_connections){
1478         sco_voice_setting = voice_setting;
1479         if (sco_num_connections){
1480             usb_sco_stop();
1481         }
1482         sco_num_connections = num_connections;
1483         if (num_connections){
1484             usb_sco_start();
1485         }
1486     }
1487 }
1488 #endif
1489 
1490 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1491     log_info("registering packet handler");
1492     packet_handler = handler;
1493 }
1494 
1495 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1496     UNUSED(packet_type);
1497     UNUSED(packet);
1498     UNUSED(size);
1499 }
1500 
1501 // get usb singleton
1502 const hci_transport_t * hci_transport_usb_instance(void) {
1503     if (!hci_transport_usb) {
1504         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1505         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1506         hci_transport_usb->name                          = "H2_LIBUSB";
1507         hci_transport_usb->open                          = usb_open;
1508         hci_transport_usb->close                         = usb_close;
1509         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1510         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1511         hci_transport_usb->send_packet                   = usb_send_packet;
1512 #ifdef ENABLE_SCO_OVER_HCI
1513         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1514 #endif
1515     }
1516     return hci_transport_usb;
1517 }
1518