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