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