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