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