xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision 80e33422a96c028b3a9c308fc4b9b874712dafb4)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "hci_transport_h2_libusb.c"
39 
40 /*
41  *  hci_transport_usb.c
42  *
43  *  HCI Transport API implementation for USB
44  *
45  *  Created by Matthias Ringwald on 7/5/09.
46  */
47 
48 // Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size
49 // HCI Commands 0 0 0x00 Control 8/16/32/64
50 // HCI Events   0 0 0x81 Interrupt (IN) 16
51 // ACL Data     0 0 0x82 Bulk (IN) 32/64
52 // ACL Data     0 0 0x02 Bulk (OUT) 32/64
53 // SCO Data     0 0 0x83 Isochronous (IN)
54 // SCO Data     0 0 0x03 Isochronous (Out)
55 
56 #include <stdio.h>
57 #include <strings.h>
58 #include <string.h>
59 #include <unistd.h>   /* UNIX standard function definitions */
60 #include <sys/types.h>
61 
62 #include <libusb.h>
63 
64 #include "btstack_config.h"
65 
66 #include "btstack_debug.h"
67 #include "hci.h"
68 #include "hci_transport.h"
69 
70 // deal with changes in libusb API:
71 #ifdef LIBUSB_API_VERSION
72 #if LIBUSB_API_VERSION >= 0x01000106
73 // since 1.0.22, libusb_set_option replaces libusb_set_debug
74 #define libusb_set_debug(context,level) libusb_set_option(context, LIBUSB_OPTION_LOG_LEVEL, level)
75 #endif
76 #endif
77 
78 #if (USB_VENDOR_ID != 0) && (USB_PRODUCT_ID != 0)
79 #define HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
80 #endif
81 
82 #define ACL_IN_BUFFER_COUNT    3
83 #define EVENT_IN_BUFFER_COUNT  3
84 #define SCO_IN_BUFFER_COUNT   10
85 
86 #define ASYNC_POLLING_INTERVAL_MS 1
87 
88 //
89 // Bluetooth USB Transport Alternate Settings:
90 //
91 // 0: No active voice channels (for USB compliance)
92 // 1: One 8 kHz voice channel with 8-bit encoding
93 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
94 // 3: Three 8 kHz voice channels with 8-bit encoding
95 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
96 // 5: Three 8 kHz voice channels with 16-bit encoding or one 8 kHz voice channel with 16-bit encoding and one 16 kHz voice channel with 16-bit encoding
97 // --> support only a single SCO connection
98 // #define ALT_SETTING (1)
99 
100 #ifdef ENABLE_SCO_OVER_HCI
101 // alt setting for 1-3 connections and 8/16 bit
102 static const int alt_setting_8_bit[]  = {1,2,3};
103 static const int alt_setting_16_bit[] = {2,4,5};
104 
105 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
106 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
107 #define NUM_ISO_PACKETS (3)
108 
109 static const uint16_t iso_packet_size_for_alt_setting[] = {
110     0,
111     9,
112     17,
113     25,
114     33,
115     49,
116     63,
117 };
118 #endif
119 
120 // 49 bytes is the max usb packet size for alternate setting 5 (Three 8 kHz 16-bit channels or one 8 kHz 16-bit channel and one 16 kHz 16-bit channel)
121 // note: alt setting 6 has max packet size of 63 every 7.5 ms = 472.5 bytes / HCI packet, while max SCO packet has 255 byte payload
122 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
123 
124 // Outgoing SCO packet queue
125 // simplified ring buffer implementation
126 #define SCO_OUT_BUFFER_COUNT  (8)
127 #define SCO_OUT_BUFFER_SIZE (SCO_OUT_BUFFER_COUNT * SCO_PACKET_SIZE)
128 
129 // seems to be the max depth for USB 3
130 #define USB_MAX_PATH_LEN 7
131 
132 // prototypes
133 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
134 static int usb_close(void);
135 
136 typedef enum {
137     LIB_USB_CLOSED = 0,
138     LIB_USB_OPENED,
139     LIB_USB_DEVICE_OPENDED,
140     LIB_USB_INTERFACE_CLAIMED,
141     LIB_USB_TRANSFERS_ALLOCATED
142 } libusb_state_t;
143 
144 // SCO packet state machine
145 typedef enum {
146     H2_W4_SCO_HEADER = 1,
147     H2_W4_PAYLOAD,
148 } H2_SCO_STATE;
149 
150 static libusb_state_t libusb_state = LIB_USB_CLOSED;
151 
152 // single instance
153 static hci_transport_t * hci_transport_usb = NULL;
154 
155 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = dummy_handler;
156 
157 // libusb
158 #ifndef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
159 static struct libusb_device_descriptor desc;
160 #endif
161 static libusb_device_handle * handle;
162 
163 static struct libusb_transfer *command_out_transfer;
164 static struct libusb_transfer *acl_out_transfer;
165 static struct libusb_transfer *event_in_transfer[EVENT_IN_BUFFER_COUNT];
166 static struct libusb_transfer *acl_in_transfer[ACL_IN_BUFFER_COUNT];
167 
168 #ifdef ENABLE_SCO_OVER_HCI
169 
170 #ifdef _WIN32
171 #error "SCO not working on Win32 (Windows 8, libusb 1.0.19, Zadic WinUSB), please uncomment ENABLE_SCO_OVER_HCI in btstack-config.h for now"
172 #endif
173 
174 // incoming SCO
175 static H2_SCO_STATE sco_state;
176 static uint8_t  sco_buffer[255+3 + SCO_PACKET_SIZE];
177 static uint16_t sco_read_pos;
178 static uint16_t sco_bytes_to_read;
179 static struct  libusb_transfer *sco_in_transfer[SCO_IN_BUFFER_COUNT];
180 static uint8_t hci_sco_in_buffer[SCO_IN_BUFFER_COUNT][SCO_PACKET_SIZE];
181 
182 // outgoing SCO
183 static uint8_t  sco_out_ring_buffer[SCO_OUT_BUFFER_SIZE];
184 static int      sco_ring_write;  // packet idx
185 static int      sco_out_transfers_active;
186 static struct libusb_transfer *sco_out_transfers[SCO_OUT_BUFFER_COUNT];
187 static int      sco_out_transfers_in_flight[SCO_OUT_BUFFER_COUNT];
188 
189 // pause/resume
190 static uint16_t sco_voice_setting;
191 static int      sco_num_connections;
192 static int      sco_shutdown;
193 
194 // dynamic SCO configuration
195 static uint16_t iso_packet_size;
196 static int      sco_enabled;
197 
198 #endif
199 
200 // outgoing buffer for HCI Command packets
201 static uint8_t hci_cmd_buffer[3 + 256 + LIBUSB_CONTROL_SETUP_SIZE];
202 
203 // incoming buffer for HCI Events and ACL Packets
204 static uint8_t hci_event_in_buffer[EVENT_IN_BUFFER_COUNT][HCI_ACL_BUFFER_SIZE]; // bigger than largest packet
205 static uint8_t hci_acl_in_buffer[ACL_IN_BUFFER_COUNT][HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
206 
207 // For (ab)use as a linked list of received packets
208 static struct libusb_transfer *handle_packet;
209 
210 static int doing_pollfds;
211 static int num_pollfds;
212 static btstack_data_source_t * pollfd_data_sources;
213 static btstack_timer_source_t usb_timer;
214 static int usb_timer_active;
215 
216 static int usb_acl_out_active = 0;
217 static int usb_command_active = 0;
218 
219 // endpoint addresses
220 static int event_in_addr;
221 static int acl_in_addr;
222 static int acl_out_addr;
223 static int sco_in_addr;
224 static int sco_out_addr;
225 
226 // device path
227 static int usb_path_len;
228 static uint8_t usb_path[USB_MAX_PATH_LEN];
229 
230 // transport interface state
231 static int usb_transport_open;
232 
233 
234 #ifdef ENABLE_SCO_OVER_HCI
235 static void sco_ring_init(void){
236     sco_ring_write = 0;
237     sco_out_transfers_active = 0;
238 }
239 static int sco_ring_have_space(void){
240     return sco_out_transfers_active < SCO_OUT_BUFFER_COUNT;
241 }
242 #endif
243 
244 void hci_transport_usb_set_path(int len, uint8_t * port_numbers){
245     if (len > USB_MAX_PATH_LEN || !port_numbers){
246         log_error("hci_transport_usb_set_path: len or port numbers invalid");
247         return;
248     }
249     usb_path_len = len;
250     memcpy(usb_path, port_numbers, len);
251 }
252 
253 //
254 static void queue_transfer(struct libusb_transfer *transfer){
255 
256     // log_info("queue_transfer %p, endpoint %x size %u", transfer, transfer->endpoint, transfer->actual_length);
257 
258     transfer->user_data = NULL;
259 
260     // insert first element
261     if (handle_packet == NULL) {
262         handle_packet = transfer;
263         return;
264     }
265 
266     // Walk to end of list and add current packet there
267     struct libusb_transfer *temp = handle_packet;
268     while (temp->user_data) {
269         temp = (struct libusb_transfer*)temp->user_data;
270     }
271     temp->user_data = transfer;
272 }
273 
274 LIBUSB_CALL static void async_callback(struct libusb_transfer *transfer){
275 
276     int c;
277 
278     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED){
279         log_info("shutdown, transfer %p", transfer);
280     }
281 
282 
283     // identify and free transfers as part of shutdown
284 #ifdef ENABLE_SCO_OVER_HCI
285     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED || sco_shutdown) {
286         for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
287             if (transfer == sco_in_transfer[c]){
288                 libusb_free_transfer(transfer);
289                 sco_in_transfer[c] = 0;
290                 return;
291             }
292         }
293 
294         for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
295             if (transfer == sco_out_transfers[c]){
296                 sco_out_transfers_in_flight[c] = 0;
297                 libusb_free_transfer(transfer);
298                 sco_out_transfers[c] = 0;
299                 return;
300             }
301         }
302     }
303 #endif
304 
305     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) {
306         for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
307             if (transfer == event_in_transfer[c]){
308                 libusb_free_transfer(transfer);
309                 event_in_transfer[c] = 0;
310                 return;
311             }
312         }
313         for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
314             if (transfer == acl_in_transfer[c]){
315                 libusb_free_transfer(transfer);
316                 acl_in_transfer[c] = 0;
317                 return;
318             }
319         }
320         return;
321     }
322 
323 #ifdef ENABLE_SCO_OVER_HCI
324     // mark SCO OUT transfer as done
325     for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
326         if (transfer == sco_out_transfers[c]){
327             sco_out_transfers_in_flight[c] = 0;
328         }
329     }
330 #endif
331 
332     int r;
333     // log_info("begin async_callback endpoint %x, status %x, actual length %u", transfer->endpoint, transfer->status, transfer->actual_length );
334 
335     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
336         queue_transfer(transfer);
337     } else if (transfer->status == LIBUSB_TRANSFER_STALL){
338         log_info("-> Transfer stalled, trying again");
339         r = libusb_clear_halt(handle, transfer->endpoint);
340         if (r) {
341             log_error("Error rclearing halt %d", r);
342         }
343         r = libusb_submit_transfer(transfer);
344         if (r) {
345             log_error("Error re-submitting transfer %d", r);
346         }
347     } else {
348         log_info("async_callback. not data -> resubmit transfer, endpoint %x, status %x, length %u", transfer->endpoint, transfer->status, transfer->actual_length);
349         // No usable data, just resubmit packet
350         r = libusb_submit_transfer(transfer);
351         if (r) {
352             log_error("Error re-submitting transfer %d", r);
353         }
354     }
355     // log_info("end async_callback");
356 }
357 
358 
359 #ifdef ENABLE_SCO_OVER_HCI
360 static int usb_send_sco_packet(uint8_t *packet, int size){
361     int r;
362 
363     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
364 
365     // log_info("usb_send_acl_packet enter, size %u", size);
366 
367     // store packet in free slot
368     int tranfer_index = sco_ring_write;
369     uint8_t * data = &sco_out_ring_buffer[tranfer_index * SCO_PACKET_SIZE];
370     memcpy(data, packet, size);
371 
372     // setup transfer
373     // log_info("usb_send_sco_packet: size %u, max size %u, iso packet size %u", size, NUM_ISO_PACKETS * iso_packet_size, iso_packet_size);
374     struct libusb_transfer * sco_transfer = sco_out_transfers[tranfer_index];
375     libusb_fill_iso_transfer(sco_transfer, handle, sco_out_addr, data, NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
376     libusb_set_iso_packet_lengths(sco_transfer, iso_packet_size);
377     r = libusb_submit_transfer(sco_transfer);
378     if (r < 0) {
379         log_error("Error submitting sco transfer, %d", r);
380         return -1;
381     }
382 
383     // mark slot as full
384     sco_ring_write++;
385     if (sco_ring_write == SCO_OUT_BUFFER_COUNT){
386         sco_ring_write = 0;
387     }
388     sco_out_transfers_active++;
389     sco_out_transfers_in_flight[tranfer_index] = 1;
390 
391     // log_info("H2: queued packet at index %u, num active %u", tranfer_index, sco_out_transfers_active);
392 
393     // notify upper stack that provided buffer can be used again
394     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
395     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
396 
397     // and if we have more space for SCO packets
398     if (sco_ring_have_space()) {
399         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
400         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
401     }
402     return 0;
403 }
404 
405 static void sco_state_machine_init(void){
406     sco_state = H2_W4_SCO_HEADER;
407     sco_read_pos = 0;
408     sco_bytes_to_read = 3;
409 }
410 
411 static void handle_isochronous_data(uint8_t * buffer, uint16_t size){
412     while (size){
413         if (size < sco_bytes_to_read){
414             // just store incomplete data
415             memcpy(&sco_buffer[sco_read_pos], buffer, size);
416             sco_read_pos      += size;
417             sco_bytes_to_read -= size;
418             return;
419         }
420         // copy requested data
421         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
422         sco_read_pos += sco_bytes_to_read;
423         buffer       += sco_bytes_to_read;
424         size         -= sco_bytes_to_read;
425 
426         // chunk read successfully, next action
427         switch (sco_state){
428             case H2_W4_SCO_HEADER:
429                 sco_state = H2_W4_PAYLOAD;
430                 sco_bytes_to_read = sco_buffer[2];
431                 break;
432             case H2_W4_PAYLOAD:
433                 // packet complete
434                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
435                 sco_state_machine_init();
436                 break;
437         }
438     }
439 }
440 #endif
441 
442 static void handle_completed_transfer(struct libusb_transfer *transfer){
443 
444     int resubmit = 0;
445     int signal_done = 0;
446 
447     if (transfer->endpoint == event_in_addr) {
448         packet_handler(HCI_EVENT_PACKET, transfer-> buffer, transfer->actual_length);
449         resubmit = 1;
450     } else if (transfer->endpoint == acl_in_addr) {
451         // log_info("-> acl");
452         packet_handler(HCI_ACL_DATA_PACKET, transfer-> buffer, transfer->actual_length);
453         resubmit = 1;
454     } else if (transfer->endpoint == 0){
455         // log_info("command done, size %u", transfer->actual_length);
456         usb_command_active = 0;
457         signal_done = 1;
458     } else if (transfer->endpoint == acl_out_addr){
459         // log_info("acl out done, size %u", transfer->actual_length);
460         usb_acl_out_active = 0;
461         signal_done = 1;
462 #ifdef ENABLE_SCO_OVER_HCI
463     } else if (transfer->endpoint == sco_in_addr) {
464         // log_info("handle_completed_transfer for SCO IN! num packets %u", transfer->NUM_ISO_PACKETS);
465         int i;
466         for (i = 0; i < transfer->num_iso_packets; i++) {
467             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
468             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
469                 log_error("Error: pack %u status %d\n", i, pack->status);
470                 continue;
471             }
472             if (!pack->actual_length) continue;
473             uint8_t * data = libusb_get_iso_packet_buffer_simple(transfer, i);
474             // printf_hexdump(data, pack->actual_length);
475             // log_info("handle_isochronous_data,size %u/%u", pack->length, pack->actual_length);
476             handle_isochronous_data(data, pack->actual_length);
477         }
478         resubmit = 1;
479     } else if (transfer->endpoint == sco_out_addr){
480         int i;
481         for (i = 0; i < transfer->num_iso_packets; i++) {
482             struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[i];
483             if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
484                 log_error("Error: pack %u status %d\n", i, pack->status);
485             }
486         }
487         // log_info("sco out done, {{ %u/%u (%x)}, { %u/%u (%x)}, { %u/%u (%x)}}",
488         //     transfer->iso_packet_desc[0].actual_length, transfer->iso_packet_desc[0].length, transfer->iso_packet_desc[0].status,
489         //     transfer->iso_packet_desc[1].actual_length, transfer->iso_packet_desc[1].length, transfer->iso_packet_desc[1].status,
490         //     transfer->iso_packet_desc[2].actual_length, transfer->iso_packet_desc[2].length, transfer->iso_packet_desc[2].status);
491         // notify upper layer if there's space for new SCO packets
492 
493         if (sco_ring_have_space()) {
494             uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
495             packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
496         }
497         // decrease tab
498         sco_out_transfers_active--;
499         // log_info("H2: sco out complete, num active num active %u", sco_out_transfers_active);
500 #endif
501     } else {
502         log_info("usb_process_ds endpoint unknown %x", transfer->endpoint);
503     }
504 
505     if (signal_done){
506         // notify upper stack that provided buffer can be used again
507         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
508         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
509     }
510 
511     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
512 
513     if (resubmit){
514         // Re-submit transfer
515         transfer->user_data = NULL;
516         int r = libusb_submit_transfer(transfer);
517         if (r) {
518             log_error("Error re-submitting transfer %d", r);
519         }
520     }
521 }
522 
523 static void usb_process_ds(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
524 
525     UNUSED(ds);
526     UNUSED(callback_type);
527 
528     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return;
529 
530     // log_info("begin usb_process_ds");
531     // always handling an event as we're called when data is ready
532     struct timeval tv;
533     memset(&tv, 0, sizeof(struct timeval));
534     libusb_handle_events_timeout(NULL, &tv);
535 
536     // Handle any packet in the order that they were received
537     while (handle_packet) {
538         // log_info("handle packet %p, endpoint %x, status %x", handle_packet, handle_packet->endpoint, handle_packet->status);
539         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     // Zephyr e.g nRF52840-PCA10056
590     0x2fe3, 0x0100,
591 };
592 
593 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
594 
595 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
596     int i;
597     for (i=0; i<num_known_devices; i++){
598         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
599             return 1;
600         }
601     }
602     return 0;
603 }
604 
605 static int scan_for_bt_endpoints(libusb_device *dev) {
606     int r;
607 
608     event_in_addr = 0;
609     acl_in_addr = 0;
610     acl_out_addr = 0;
611     sco_out_addr = 0;
612     sco_in_addr = 0;
613 
614     // get endpoints from interface descriptor
615     struct libusb_config_descriptor *config_descriptor;
616     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
617     if (r < 0) return r;
618 
619     int num_interfaces = config_descriptor->bNumInterfaces;
620     log_info("active configuration has %u interfaces", num_interfaces);
621 
622     int i;
623     for (i = 0; i < num_interfaces ; i++){
624         const struct libusb_interface *interface = &config_descriptor->interface[i];
625         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
626         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
627 
628         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
629 
630         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
631             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
632 
633             switch (endpoint->bmAttributes & 0x3){
634                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
635                     if (event_in_addr) continue;
636                     event_in_addr = endpoint->bEndpointAddress;
637                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
638                     break;
639                 case LIBUSB_TRANSFER_TYPE_BULK:
640                     if (endpoint->bEndpointAddress & 0x80) {
641                         if (acl_in_addr) continue;
642                         acl_in_addr = endpoint->bEndpointAddress;
643                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
644                     } else {
645                         if (acl_out_addr) continue;
646                         acl_out_addr = endpoint->bEndpointAddress;
647                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
648                     }
649                     break;
650                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
651                     if (endpoint->bEndpointAddress & 0x80) {
652                         if (sco_in_addr) continue;
653                         sco_in_addr = endpoint->bEndpointAddress;
654                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
655                     } else {
656                         if (sco_out_addr) continue;
657                         sco_out_addr = endpoint->bEndpointAddress;
658                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
659                     }
660                     break;
661                 default:
662                     break;
663             }
664         }
665     }
666     libusb_free_config_descriptor(config_descriptor);
667     return 0;
668 }
669 
670 // returns index of found device or -1
671 static int scan_for_bt_device(libusb_device **devs, int start_index) {
672     int i;
673     for (i = start_index; devs[i] ; i++){
674         libusb_device * dev = devs[i];
675         int r = libusb_get_device_descriptor(dev, &desc);
676         if (r < 0) {
677             log_error("failed to get device descriptor");
678             return 0;
679         }
680 
681         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
682                desc.idVendor, desc.idProduct,
683                libusb_get_bus_number(dev), libusb_get_device_address(dev),
684                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
685 
686         // Detect USB Dongle based Class, Subclass, and Protocol
687         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
688         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
689         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
690         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
691         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
692             return i;
693         }
694 
695         // Detect USB Dongle based on whitelist
696         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
697             return i;
698         }
699     }
700     return -1;
701 }
702 #endif
703 
704 static int prepare_device(libusb_device_handle * aHandle){
705 
706     // print device path
707     uint8_t port_numbers[USB_MAX_PATH_LEN];
708     libusb_device * device = libusb_get_device(aHandle);
709     int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
710     printf("USB Path: ");
711     int i;
712     for (i=0;i<path_len;i++){
713         if (i) printf("-");
714         printf("%02x", port_numbers[i]);
715     }
716     printf("\n");
717 
718     int r;
719     int kernel_driver_detached = 0;
720 
721     // Detach OS driver (not possible for OS X and WIN32)
722 #if !defined(__APPLE__) && !defined(_WIN32)
723     r = libusb_kernel_driver_active(aHandle, 0);
724     if (r < 0) {
725         log_error("libusb_kernel_driver_active error %d", r);
726         libusb_close(aHandle);
727         return r;
728     }
729 
730     if (r == 1) {
731         r = libusb_detach_kernel_driver(aHandle, 0);
732         if (r < 0) {
733             log_error("libusb_detach_kernel_driver error %d", r);
734             libusb_close(aHandle);
735             return r;
736         }
737         kernel_driver_detached = 1;
738     }
739     log_info("libusb_detach_kernel_driver");
740 #endif
741 
742     const int configuration = 1;
743     log_info("setting configuration %d...", configuration);
744     r = libusb_set_configuration(aHandle, configuration);
745     if (r < 0) {
746         log_error("Error libusb_set_configuration: %d", r);
747         if (kernel_driver_detached){
748             libusb_attach_kernel_driver(aHandle, 0);
749         }
750         libusb_close(aHandle);
751         return r;
752     }
753 
754     // reserve access to device
755     log_info("claiming interface 0...");
756     r = libusb_claim_interface(aHandle, 0);
757     if (r < 0) {
758         log_error("Error %d claiming interface 0", r);
759         if (kernel_driver_detached){
760             libusb_attach_kernel_driver(aHandle, 0);
761         }
762         libusb_close(aHandle);
763         return r;
764     }
765 
766 #ifdef ENABLE_SCO_OVER_HCI
767     log_info("claiming interface 1...");
768     r = libusb_claim_interface(aHandle, 1);
769     if (r < 0) {
770         log_error("Error %d claiming interface 1: - disabling SCO over HCI", r);
771     } else {
772         sco_enabled = 1;
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                 sco_enabled = 0;
1271 #endif
1272             }
1273 
1274             // finally release interface
1275             libusb_release_interface(handle, 0);
1276 #ifdef ENABLE_SCO_OVER_HCI
1277             libusb_release_interface(handle, 1);
1278 #endif
1279             log_info("Libusb shutdown complete");
1280 
1281         case LIB_USB_DEVICE_OPENDED:
1282             libusb_close(handle);
1283 
1284         case LIB_USB_OPENED:
1285             libusb_exit(NULL);
1286     }
1287 
1288     libusb_state = LIB_USB_CLOSED;
1289     handle = NULL;
1290     usb_transport_open = 0;
1291 
1292     return 0;
1293 }
1294 
1295 static int usb_send_cmd_packet(uint8_t *packet, int size){
1296     int r;
1297 
1298     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1299 
1300     // async
1301     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1302     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1303 
1304     // prepare transfer
1305     int completed = 0;
1306     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1307     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1308 
1309     // update stata before submitting transfer
1310     usb_command_active = 1;
1311 
1312     // submit transfer
1313     r = libusb_submit_transfer(command_out_transfer);
1314 
1315     if (r < 0) {
1316         usb_command_active = 0;
1317         log_error("Error submitting cmd transfer %d", r);
1318         return -1;
1319     }
1320 
1321     return 0;
1322 }
1323 
1324 static int usb_send_acl_packet(uint8_t *packet, int size){
1325     int r;
1326 
1327     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1328 
1329     // log_info("usb_send_acl_packet enter, size %u", size);
1330 
1331     // prepare transfer
1332     int completed = 0;
1333     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1334         async_callback, &completed, 0);
1335     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1336 
1337     // update stata before submitting transfer
1338     usb_acl_out_active = 1;
1339 
1340     r = libusb_submit_transfer(acl_out_transfer);
1341     if (r < 0) {
1342         usb_acl_out_active = 0;
1343         log_error("Error submitting acl transfer, %d", r);
1344         return -1;
1345     }
1346 
1347     return 0;
1348 }
1349 
1350 static int usb_can_send_packet_now(uint8_t packet_type){
1351     switch (packet_type){
1352         case HCI_COMMAND_DATA_PACKET:
1353             return !usb_command_active;
1354         case HCI_ACL_DATA_PACKET:
1355             return !usb_acl_out_active;
1356 #ifdef ENABLE_SCO_OVER_HCI
1357         case HCI_SCO_DATA_PACKET:
1358             if (!sco_enabled) return 0;
1359             return sco_ring_have_space();
1360 #endif
1361         default:
1362             return 0;
1363     }
1364 }
1365 
1366 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1367     switch (packet_type){
1368         case HCI_COMMAND_DATA_PACKET:
1369             return usb_send_cmd_packet(packet, size);
1370         case HCI_ACL_DATA_PACKET:
1371             return usb_send_acl_packet(packet, size);
1372 #ifdef ENABLE_SCO_OVER_HCI
1373         case HCI_SCO_DATA_PACKET:
1374             if (!sco_enabled) return -1;
1375             return usb_send_sco_packet(packet, size);
1376 #endif
1377         default:
1378             return -1;
1379     }
1380 }
1381 
1382 #ifdef ENABLE_SCO_OVER_HCI
1383 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1384     if (!sco_enabled) return;
1385 
1386     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1387 
1388     if (num_connections != sco_num_connections){
1389         sco_voice_setting = voice_setting;
1390         if (sco_num_connections){
1391             usb_sco_stop();
1392         }
1393         sco_num_connections = num_connections;
1394         if (num_connections){
1395             usb_sco_start();
1396         }
1397     }
1398 }
1399 #endif
1400 
1401 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1402     log_info("registering packet handler");
1403     packet_handler = handler;
1404 }
1405 
1406 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1407     UNUSED(packet_type);
1408     UNUSED(packet);
1409     UNUSED(size);
1410 }
1411 
1412 // get usb singleton
1413 const hci_transport_t * hci_transport_usb_instance(void) {
1414     if (!hci_transport_usb) {
1415         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1416         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1417         hci_transport_usb->name                          = "H2_LIBUSB";
1418         hci_transport_usb->open                          = usb_open;
1419         hci_transport_usb->close                         = usb_close;
1420         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1421         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1422         hci_transport_usb->send_packet                   = usb_send_packet;
1423 #ifdef ENABLE_SCO_OVER_HCI
1424         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1425 #endif
1426     }
1427     return hci_transport_usb;
1428 }
1429