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