xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision 630ffdd469bbec3276322f46b93e6cfdfcb21c27)
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 static libusb_device        * dev;
161 #endif
162 static libusb_device_handle * handle;
163 
164 static struct libusb_transfer *command_out_transfer;
165 static struct libusb_transfer *acl_out_transfer;
166 static struct libusb_transfer *event_in_transfer[EVENT_IN_BUFFER_COUNT];
167 static struct libusb_transfer *acl_in_transfer[ACL_IN_BUFFER_COUNT];
168 
169 #ifdef ENABLE_SCO_OVER_HCI
170 
171 #ifdef _WIN32
172 #error "SCO not working on Win32 (Windows 8, libusb 1.0.19, Zadic WinUSB), please uncomment ENABLE_SCO_OVER_HCI in btstack-config.h for now"
173 #endif
174 
175 // incoming SCO
176 static H2_SCO_STATE sco_state;
177 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
178 static uint16_t sco_read_pos;
179 static uint16_t sco_bytes_to_read;
180 static struct  libusb_transfer *sco_in_transfer[SCO_IN_BUFFER_COUNT];
181 static uint8_t hci_sco_in_buffer[SCO_IN_BUFFER_COUNT][SCO_PACKET_SIZE];
182 
183 // outgoing SCO
184 static uint8_t  sco_out_ring_buffer[SCO_OUT_BUFFER_SIZE];
185 static int      sco_ring_write;  // packet idx
186 static int      sco_out_transfers_active;
187 static struct libusb_transfer *sco_out_transfers[SCO_OUT_BUFFER_COUNT];
188 static int      sco_out_transfers_in_flight[SCO_OUT_BUFFER_COUNT];
189 
190 // pause/resume
191 static uint16_t sco_voice_setting;
192 static int      sco_num_connections;
193 static int      sco_shutdown;
194 
195 // dynamic SCO configuration
196 static uint16_t iso_packet_size;
197 
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         void * next = handle_packet->user_data;
540         handle_completed_transfer(handle_packet);
541         // handle case where libusb_close might be called by hci packet handler
542         if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
543 
544         // Move to next in the list of packets to handle
545         if (next) {
546             handle_packet = (struct libusb_transfer*)next;
547         } else {
548             handle_packet = NULL;
549         }
550     }
551     // log_info("end usb_process_ds");
552 }
553 
554 static void usb_process_ts(btstack_timer_source_t *timer) {
555 
556     UNUSED(timer);
557 
558     // log_info("in usb_process_ts");
559 
560     // timer is deactive, when timer callback gets called
561     usb_timer_active = 0;
562 
563     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
564 
565     // actually handled the packet in the pollfds function
566     usb_process_ds((struct btstack_data_source *) NULL, DATA_SOURCE_CALLBACK_READ);
567 
568     // Get the amount of time until next event is due
569     long msec = ASYNC_POLLING_INTERVAL_MS;
570 
571     // Activate timer
572     btstack_run_loop_set_timer(&usb_timer, msec);
573     btstack_run_loop_add_timer(&usb_timer);
574     usb_timer_active = 1;
575 
576     return;
577 }
578 
579 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
580 
581 // list of known devices, using VendorID/ProductID tuples
582 static const uint16_t known_bt_devices[] = {
583     // DeLOCK Bluetooth 4.0
584     0x0a5c, 0x21e8,
585     // Asus BT400
586     0x0b05, 0x17cb,
587     // BCM20702B0 (Generic USB Detuned Class 1 @ 20 MHz)
588     0x0a5c, 0x22be
589 };
590 
591 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
592 
593 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
594     int i;
595     for (i=0; i<num_known_devices; i++){
596         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
597             return 1;
598         }
599     }
600     return 0;
601 }
602 
603 static void scan_for_bt_endpoints(void) {
604     int r;
605 
606     event_in_addr = 0;
607     acl_in_addr = 0;
608     acl_out_addr = 0;
609     sco_out_addr = 0;
610     sco_in_addr = 0;
611 
612     // get endpoints from interface descriptor
613     struct libusb_config_descriptor *config_descriptor;
614     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
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 }
665 
666 // returns index of found device or -1
667 static int scan_for_bt_device(libusb_device **devs, int start_index) {
668     int i;
669     for (i = start_index; devs[i] ; i++){
670         dev = devs[i];
671         int r = libusb_get_device_descriptor(dev, &desc);
672         if (r < 0) {
673             log_error("failed to get device descriptor");
674             return 0;
675         }
676 
677         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
678                desc.idVendor, desc.idProduct,
679                libusb_get_bus_number(dev), libusb_get_device_address(dev),
680                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
681 
682         // Detect USB Dongle based Class, Subclass, and Protocol
683         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
684         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
685         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
686         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
687         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
688             return i;
689         }
690 
691         // Detect USB Dongle based on whitelist
692         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
693             return i;
694         }
695     }
696     return -1;
697 }
698 #endif
699 
700 static int prepare_device(libusb_device_handle * aHandle){
701 
702     // print device path
703     uint8_t port_numbers[USB_MAX_PATH_LEN];
704     libusb_device * device = libusb_get_device(aHandle);
705     int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
706     printf("USB Path: ");
707     int i;
708     for (i=0;i<path_len;i++){
709         if (i) printf("-");
710         printf("%02x", port_numbers[i]);
711     }
712     printf("\n");
713 
714     int r;
715     int kernel_driver_detached = 0;
716 
717     // Detach OS driver (not possible for OS X and WIN32)
718 #if !defined(__APPLE__) && !defined(_WIN32)
719     r = libusb_kernel_driver_active(aHandle, 0);
720     if (r < 0) {
721         log_error("libusb_kernel_driver_active error %d", r);
722         libusb_close(aHandle);
723         return r;
724     }
725 
726     if (r == 1) {
727         r = libusb_detach_kernel_driver(aHandle, 0);
728         if (r < 0) {
729             log_error("libusb_detach_kernel_driver error %d", r);
730             libusb_close(aHandle);
731             return r;
732         }
733         kernel_driver_detached = 1;
734     }
735     log_info("libusb_detach_kernel_driver");
736 #endif
737 
738     const int configuration = 1;
739     log_info("setting configuration %d...", configuration);
740     r = libusb_set_configuration(aHandle, configuration);
741     if (r < 0) {
742         log_error("Error libusb_set_configuration: %d", r);
743         if (kernel_driver_detached){
744             libusb_attach_kernel_driver(aHandle, 0);
745         }
746         libusb_close(aHandle);
747         return r;
748     }
749 
750     // reserve access to device
751     log_info("claiming interface 0...");
752     r = libusb_claim_interface(aHandle, 0);
753     if (r < 0) {
754         log_error("Error claiming interface %d", r);
755         if (kernel_driver_detached){
756             libusb_attach_kernel_driver(aHandle, 0);
757         }
758         libusb_close(aHandle);
759         return r;
760     }
761 
762 #ifdef ENABLE_SCO_OVER_HCI
763     log_info("claiming interface 1...");
764     r = libusb_claim_interface(aHandle, 1);
765     if (r < 0) {
766         log_error("Error claiming interface %d", r);
767         if (kernel_driver_detached){
768             libusb_attach_kernel_driver(aHandle, 0);
769         }
770         libusb_close(aHandle);
771         return r;
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
793     libusb_reset_device(dev_handle);
794     if (r < 0) {
795         log_error("libusb_reset_device failed!");
796         libusb_close(dev_handle);
797         return NULL;
798     }
799     return dev_handle;
800 }
801 
802 #ifdef ENABLE_SCO_OVER_HCI
803 
804 static int usb_sco_start(void){
805 
806     printf("usb_sco_start\n");
807     log_info("usb_sco_start");
808 
809     sco_state_machine_init();
810     sco_ring_init();
811 
812     int alt_setting;
813     if (sco_voice_setting & 0x0020){
814         // 16-bit PCM
815         alt_setting = alt_setting_16_bit[sco_num_connections-1];
816     } else {
817         // 8-bit PCM or mSBC
818         alt_setting = alt_setting_8_bit[sco_num_connections-1];
819     }
820     // derive iso packet size from alt setting
821     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
822 
823     log_info("Switching to setting %u on interface 1..", alt_setting);
824     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
825     if (r < 0) {
826         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
827         return r;
828     }
829 
830     // incoming
831     int c;
832     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
833         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
834         if (!sco_in_transfer[c]) {
835             usb_close();
836             return LIBUSB_ERROR_NO_MEM;
837         }
838         // configure sco_in handlers
839         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
840             hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
841         libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
842         r = libusb_submit_transfer(sco_in_transfer[c]);
843         if (r) {
844             log_error("Error submitting isochronous in transfer %d", r);
845             usb_close();
846             return r;
847         }
848     }
849 
850     // outgoing
851     for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
852         sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
853         sco_out_transfers_in_flight[c] = 0;
854     }
855     return 0;
856 }
857 
858 static void usb_sco_stop(void){
859 
860     printf("usb_sco_stop\n");
861 
862     log_info("usb_sco_stop");
863     sco_shutdown = 1;
864 
865     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
866 
867     int c;
868     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
869         libusb_cancel_transfer(sco_in_transfer[c]);
870     }
871 
872     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
873         if (sco_out_transfers_in_flight[c]) {
874             libusb_cancel_transfer(sco_out_transfers[c]);
875         } else {
876             libusb_free_transfer(sco_out_transfers[c]);
877             sco_out_transfers[c] = 0;
878         }
879     }
880 
881     // wait until all transfers are completed
882     int completed = 0;
883     while (!completed){
884         struct timeval tv;
885         memset(&tv, 0, sizeof(struct timeval));
886         libusb_handle_events_timeout(NULL, &tv);
887         // check if all done
888         completed = 1;
889 
890         // Cancel all synchronous transfer
891         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
892             if (sco_in_transfer[c]){
893                 completed = 0;
894                 break;
895             }
896         }
897 
898         if (!completed) continue;
899 
900         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
901             if (sco_out_transfers[c]){
902                 completed = 0;
903                 break;
904             }
905         }
906     }
907     sco_shutdown = 0;
908     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
909 
910     log_info("Switching to setting %u on interface 1..", 0);
911     int r = libusb_set_interface_alt_setting(handle, 1, 0);
912     if (r < 0) {
913         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
914         return;
915     }
916 
917     printf("usb_sco_stop done\n");
918 }
919 
920 
921 
922 #endif
923 
924 static int usb_open(void){
925     int r;
926 
927     if (usb_transport_open) return 0;
928 
929     handle_packet = NULL;
930 
931     // default endpoint addresses
932     event_in_addr = 0x81; // EP1, IN interrupt
933     acl_in_addr =   0x82; // EP2, IN bulk
934     acl_out_addr =  0x02; // EP2, OUT bulk
935     sco_in_addr  =  0x83; // EP3, IN isochronous
936     sco_out_addr =  0x03; // EP3, OUT isochronous
937 
938     // USB init
939     r = libusb_init(NULL);
940     if (r < 0) return -1;
941 
942     libusb_state = LIB_USB_OPENED;
943 
944     // configure debug level
945     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
946 
947 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
948 
949     // Use a specified device
950     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
951     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
952 
953     if (!handle){
954         log_error("libusb_open_device_with_vid_pid failed!");
955         usb_close();
956         return -1;
957     }
958     log_info("libusb open %d, handle %p", r, handle);
959 
960     r = prepare_device(handle);
961     if (r < 0){
962         usb_close();
963         return -1;
964     }
965 
966 #else
967     // Scan system for an appropriate devices
968     libusb_device **devs;
969     ssize_t num_devices;
970 
971     log_info("Scanning for USB Bluetooth device");
972     num_devices = libusb_get_device_list(NULL, &devs);
973     if (num_devices < 0) {
974         usb_close();
975         return -1;
976     }
977 
978     dev = NULL;
979 
980     if (usb_path_len){
981         int i;
982         for (i=0;i<num_devices;i++){
983             uint8_t port_numbers[USB_MAX_PATH_LEN];
984             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
985             if (len != usb_path_len) continue;
986             if (memcmp(usb_path, port_numbers, len) == 0){
987                 log_info("USB device found at specified path");
988                 handle = try_open_device(devs[i]);
989                 if (!handle) continue;
990 
991                 r = prepare_device(handle);
992                 if (r < 0) continue;
993 
994                 dev = devs[i];
995                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
996                 break;
997             };
998         }
999         if (!handle){
1000             log_error("USB device with given path not found");
1001             printf("USB device with given path not found\n");
1002             return -1;
1003         }
1004     } else {
1005 
1006         int deviceIndex = -1;
1007         while (1){
1008             // look for next Bluetooth dongle
1009             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
1010             if (deviceIndex < 0) break;
1011 
1012             log_info("USB Bluetooth device found, index %u", deviceIndex);
1013 
1014             handle = try_open_device(devs[deviceIndex]);
1015             if (!handle) continue;
1016 
1017             r = prepare_device(handle);
1018             if (r < 0) continue;
1019 
1020             dev = devs[deviceIndex];
1021             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1022             break;
1023         }
1024     }
1025 
1026     libusb_free_device_list(devs, 1);
1027 
1028     if (handle == 0){
1029         log_error("No USB Bluetooth device found");
1030         return -1;
1031     }
1032 
1033     scan_for_bt_endpoints();
1034 
1035 #endif
1036 
1037     // allocate transfer handlers
1038     int c;
1039     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1040         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1041         if (!event_in_transfer[c]) {
1042             usb_close();
1043             return LIBUSB_ERROR_NO_MEM;
1044         }
1045     }
1046     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1047         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1048         if (!acl_in_transfer[c]) {
1049             usb_close();
1050             return LIBUSB_ERROR_NO_MEM;
1051         }
1052     }
1053 
1054     command_out_transfer = libusb_alloc_transfer(0);
1055     acl_out_transfer     = libusb_alloc_transfer(0);
1056 
1057     // TODO check for error
1058 
1059     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1060 
1061     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1062         // configure event_in handlers
1063         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1064                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1065         r = libusb_submit_transfer(event_in_transfer[c]);
1066         if (r) {
1067             log_error("Error submitting interrupt transfer %d", r);
1068             usb_close();
1069             return r;
1070         }
1071     }
1072 
1073     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1074         // configure acl_in handlers
1075         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1076                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1077         r = libusb_submit_transfer(acl_in_transfer[c]);
1078         if (r) {
1079             log_error("Error submitting bulk in transfer %d", r);
1080             usb_close();
1081             return r;
1082         }
1083 
1084      }
1085 
1086     // Check for pollfds functionality
1087     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1088 
1089     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation here
1090     doing_pollfds = 0;
1091 
1092     if (doing_pollfds) {
1093         log_info("Async using pollfds:");
1094 
1095         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1096         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1097         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1098         if (!pollfd_data_sources){
1099             log_error("Cannot allocate data sources for pollfds");
1100             usb_close();
1101             return 1;
1102         }
1103         for (r = 0 ; r < num_pollfds ; r++) {
1104             btstack_data_source_t *ds = &pollfd_data_sources[r];
1105             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1106             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1107             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1108             btstack_run_loop_add_data_source(ds);
1109             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1110         }
1111         free(pollfd);
1112     } else {
1113         log_info("Async using timers:");
1114 
1115         usb_timer.process = usb_process_ts;
1116         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1117         btstack_run_loop_add_timer(&usb_timer);
1118         usb_timer_active = 1;
1119     }
1120 
1121     usb_transport_open = 1;
1122 
1123     return 0;
1124 }
1125 
1126 static int usb_close(void){
1127     int c;
1128     int completed = 0;
1129 
1130     if (!usb_transport_open) return 0;
1131 
1132     log_info("usb_close");
1133 
1134     switch (libusb_state){
1135         case LIB_USB_CLOSED:
1136             break;
1137 
1138         case LIB_USB_TRANSFERS_ALLOCATED:
1139             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1140 
1141             if(usb_timer_active) {
1142                 btstack_run_loop_remove_timer(&usb_timer);
1143                 usb_timer_active = 0;
1144             }
1145 
1146             if (doing_pollfds){
1147                 int r;
1148                 for (r = 0 ; r < num_pollfds ; r++) {
1149                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1150                     btstack_run_loop_remove_data_source(ds);
1151                 }
1152                 free(pollfd_data_sources);
1153                 pollfd_data_sources = NULL;
1154                 num_pollfds = 0;
1155                 doing_pollfds = 0;
1156             }
1157 
1158         case LIB_USB_INTERFACE_CLAIMED:
1159             // Cancel all transfers, ignore warnings for this
1160             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1161             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1162                 if (event_in_transfer[c]){
1163                     log_info("cancel event_in_transfer[%u] = %p", c, event_in_transfer[c]);
1164                     libusb_cancel_transfer(event_in_transfer[c]);
1165                 }
1166             }
1167             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1168                 if (acl_in_transfer[c]){
1169                     log_info("cancel acl_in_transfer[%u] = %p", c, acl_in_transfer[c]);
1170                     libusb_cancel_transfer(acl_in_transfer[c]);
1171                 }
1172             }
1173 #ifdef ENABLE_SCO_OVER_HCI
1174             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1175                 if (sco_in_transfer[c]){
1176                     log_info("cancel sco_in_transfer[%u] = %p", c, sco_in_transfer[c]);
1177                     libusb_cancel_transfer(sco_in_transfer[c]);
1178                 }
1179             }
1180             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1181                 if (sco_out_transfers_in_flight[c]) {
1182                     log_info("cancel sco_out_transfers[%u] = %p", c, sco_out_transfers[c]);
1183                     libusb_cancel_transfer(sco_out_transfers[c]);
1184                 } else {
1185                     libusb_free_transfer(sco_out_transfers[c]);
1186                     sco_out_transfers[c] = 0;
1187                 }
1188             }
1189 #endif
1190             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1191 
1192             // wait until all transfers are completed - or 20 iterations
1193             int countdown = 20;
1194             while (!completed){
1195 
1196                 if (--countdown == 0){
1197                     log_info("Not all transfers cancelled, leaking a bit.");
1198                     break;
1199                 }
1200 
1201                 struct timeval tv;
1202                 memset(&tv, 0, sizeof(struct timeval));
1203                 libusb_handle_events_timeout(NULL, &tv);
1204                 // check if all done
1205                 completed = 1;
1206                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1207                     if (event_in_transfer[c]) {
1208                         log_info("event_in_transfer[%u] still active (%p)", c, event_in_transfer[c]);
1209                         completed = 0;
1210                         break;
1211                     }
1212                 }
1213 
1214                 if (!completed) continue;
1215 
1216                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1217                     if (acl_in_transfer[c]) {
1218                         log_info("acl_in_transfer[%u] still active (%p)", c, acl_in_transfer[c]);
1219                         completed = 0;
1220                         break;
1221                     }
1222                 }
1223 
1224 #ifdef ENABLE_SCO_OVER_HCI
1225                 if (!completed) continue;
1226 
1227                 // Cancel all synchronous transfer
1228                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1229                     if (sco_in_transfer[c]){
1230                         log_info("sco_in_transfer[%u] still active (%p)", c, sco_in_transfer[c]);
1231                         completed = 0;
1232                         break;
1233                     }
1234                 }
1235 
1236                 if (!completed) continue;
1237 
1238                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1239                     if (sco_out_transfers[c]){
1240                         log_info("sco_out_transfers[%u] still active (%p)", c, sco_out_transfers[c]);
1241                         completed = 0;
1242                         break;
1243                     }
1244                 }
1245 #endif
1246             }
1247 
1248             // finally release interface
1249             libusb_release_interface(handle, 0);
1250 #ifdef ENABLE_SCO_OVER_HCI
1251             libusb_release_interface(handle, 1);
1252 #endif
1253             log_info("Libusb shutdown complete");
1254 
1255         case LIB_USB_DEVICE_OPENDED:
1256             libusb_close(handle);
1257 
1258         case LIB_USB_OPENED:
1259             libusb_exit(NULL);
1260     }
1261 
1262     libusb_state = LIB_USB_CLOSED;
1263     handle = NULL;
1264     usb_transport_open = 0;
1265 
1266     return 0;
1267 }
1268 
1269 static int usb_send_cmd_packet(uint8_t *packet, int size){
1270     int r;
1271 
1272     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1273 
1274     // async
1275     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1276     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1277 
1278     // prepare transfer
1279     int completed = 0;
1280     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1281     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1282 
1283     // update stata before submitting transfer
1284     usb_command_active = 1;
1285 
1286     // submit transfer
1287     r = libusb_submit_transfer(command_out_transfer);
1288 
1289     if (r < 0) {
1290         usb_command_active = 0;
1291         log_error("Error submitting cmd transfer %d", r);
1292         return -1;
1293     }
1294 
1295     return 0;
1296 }
1297 
1298 static int usb_send_acl_packet(uint8_t *packet, int size){
1299     int r;
1300 
1301     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1302 
1303     // log_info("usb_send_acl_packet enter, size %u", size);
1304 
1305     // prepare transfer
1306     int completed = 0;
1307     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1308         async_callback, &completed, 0);
1309     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1310 
1311     // update stata before submitting transfer
1312     usb_acl_out_active = 1;
1313 
1314     r = libusb_submit_transfer(acl_out_transfer);
1315     if (r < 0) {
1316         usb_acl_out_active = 0;
1317         log_error("Error submitting acl transfer, %d", r);
1318         return -1;
1319     }
1320 
1321     return 0;
1322 }
1323 
1324 static int usb_can_send_packet_now(uint8_t packet_type){
1325     switch (packet_type){
1326         case HCI_COMMAND_DATA_PACKET:
1327             return !usb_command_active;
1328         case HCI_ACL_DATA_PACKET:
1329             return !usb_acl_out_active;
1330 #ifdef ENABLE_SCO_OVER_HCI
1331         case HCI_SCO_DATA_PACKET:
1332             return sco_ring_have_space();
1333 #endif
1334         default:
1335             return 0;
1336     }
1337 }
1338 
1339 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1340     switch (packet_type){
1341         case HCI_COMMAND_DATA_PACKET:
1342             return usb_send_cmd_packet(packet, size);
1343         case HCI_ACL_DATA_PACKET:
1344             return usb_send_acl_packet(packet, size);
1345 #ifdef ENABLE_SCO_OVER_HCI
1346         case HCI_SCO_DATA_PACKET:
1347             return usb_send_sco_packet(packet, size);
1348 #endif
1349         default:
1350             return -1;
1351     }
1352 }
1353 
1354 #ifdef ENABLE_SCO_OVER_HCI
1355 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1356     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1357 
1358     if (num_connections != sco_num_connections){
1359         sco_voice_setting = voice_setting;
1360         if (sco_num_connections){
1361             usb_sco_stop();
1362         }
1363         sco_num_connections = num_connections;
1364         if (num_connections){
1365             usb_sco_start();
1366         }
1367     }
1368 }
1369 #endif
1370 
1371 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1372     log_info("registering packet handler");
1373     packet_handler = handler;
1374 }
1375 
1376 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1377     UNUSED(packet_type);
1378     UNUSED(packet);
1379     UNUSED(size);
1380 }
1381 
1382 // get usb singleton
1383 const hci_transport_t * hci_transport_usb_instance(void) {
1384     if (!hci_transport_usb) {
1385         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1386         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1387         hci_transport_usb->name                          = "H2_LIBUSB";
1388         hci_transport_usb->open                          = usb_open;
1389         hci_transport_usb->close                         = usb_close;
1390         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1391         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1392         hci_transport_usb->send_packet                   = usb_send_packet;
1393 #ifdef ENABLE_SCO_OVER_HCI
1394         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1395 #endif
1396     }
1397     return hci_transport_usb;
1398 }
1399