xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision 2c4f9bbb6d93b3f1a90ed62ac67e4cd019f0736a)
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] = NULL;
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] = NULL;
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     // Free SCO transfers already in queue
881     struct libusb_transfer* transfer = handle_packet;
882     struct libusb_transfer* prev_transfer = NULL;
883     while (transfer != NULL) {
884         uint16_t c;
885         bool drop_transfer = false;
886         for (c=0;c<SCO_IN_BUFFER_COUNT;c++){
887             if (transfer == sco_in_transfer[c]){
888                 sco_in_transfer[c] = NULL;
889                 drop_transfer = true;
890                 break;
891             }
892         }
893         for (c=0;c<SCO_OUT_BUFFER_COUNT;c++){
894             if (transfer == sco_out_transfers[c]){
895                 sco_out_transfers_in_flight[c] = 0;
896                 sco_out_transfers[c] = NULL;
897                 drop_transfer = true;
898                 break;
899             }
900         }
901         struct libusb_transfer * next_transfer = (struct libusb_transfer *) transfer->user_data;
902         if (drop_transfer) {
903             printf("Drop completed SCO transfer %p\n", transfer);
904             if (prev_transfer == NULL) {
905                 // first item
906                 handle_packet = (struct libusb_transfer *) next_transfer;
907             } else {
908                 // other item
909                 prev_transfer->user_data = (struct libusb_transfer *) next_transfer;
910             }
911             libusb_free_transfer(transfer);
912         } else {
913             prev_transfer = transfer;
914         }
915         transfer = next_transfer;
916     }
917 
918     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
919 
920     int c;
921     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
922         if (sco_in_transfer[c] != NULL) {
923             libusb_cancel_transfer(sco_in_transfer[c]);
924         }
925     }
926 
927     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
928         if (sco_out_transfers_in_flight[c]) {
929             libusb_cancel_transfer(sco_out_transfers[c]);
930         } else {
931             if (sco_out_transfers[c] != NULL) {
932                 libusb_free_transfer(sco_out_transfers[c]);
933                 sco_out_transfers[c] = 0;
934             }
935         }
936     }
937 
938     // wait until all transfers are completed
939     int completed = 0;
940     while (!completed){
941         struct timeval tv;
942         memset(&tv, 0, sizeof(struct timeval));
943         libusb_handle_events_timeout(NULL, &tv);
944         // check if all done
945         completed = 1;
946 
947         // Cancel all synchronous transfer
948         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
949             if (sco_in_transfer[c] != NULL){
950                 completed = 0;
951                 break;
952             }
953         }
954 
955         if (!completed) continue;
956 
957         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
958             if (sco_out_transfers[c] != NULL){
959                 completed = 0;
960                 break;
961             }
962         }
963     }
964     sco_shutdown = 0;
965     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
966 
967     log_info("Switching to setting %u on interface 1..", 0);
968     int r = libusb_set_interface_alt_setting(handle, 1, 0);
969     if (r < 0) {
970         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
971         return;
972     }
973 
974     printf("usb_sco_stop done\n");
975 }
976 
977 
978 
979 #endif
980 
981 static int usb_open(void){
982     int r;
983 
984     if (usb_transport_open) return 0;
985 
986     handle_packet = NULL;
987 
988     // default endpoint addresses
989     event_in_addr = 0x81; // EP1, IN interrupt
990     acl_in_addr =   0x82; // EP2, IN bulk
991     acl_out_addr =  0x02; // EP2, OUT bulk
992     sco_in_addr  =  0x83; // EP3, IN isochronous
993     sco_out_addr =  0x03; // EP3, OUT isochronous
994 
995     // USB init
996     r = libusb_init(NULL);
997     if (r < 0) return -1;
998 
999     libusb_state = LIB_USB_OPENED;
1000 
1001     // configure debug level
1002     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1003 
1004     libusb_device * dev = NULL;
1005 
1006 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
1007 
1008     // Use a specified device
1009     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
1010     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
1011 
1012     if (!handle){
1013         log_error("libusb_open_device_with_vid_pid failed!");
1014         usb_close();
1015         return -1;
1016     }
1017     log_info("libusb open %d, handle %p", r, handle);
1018 
1019     r = prepare_device(handle);
1020     if (r < 0){
1021         usb_close();
1022         return -1;
1023     }
1024 
1025     dev = libusb_get_device(aHandle);
1026     r = scan_for_bt_endpoints(dev);
1027     if (r < 0){
1028         usb_close();
1029         return -1;
1030     }
1031 
1032 #else
1033     // Scan system for an appropriate devices
1034     libusb_device **devs;
1035     ssize_t num_devices;
1036 
1037     log_info("Scanning for USB Bluetooth device");
1038     num_devices = libusb_get_device_list(NULL, &devs);
1039     if (num_devices < 0) {
1040         usb_close();
1041         return -1;
1042     }
1043 
1044     if (usb_path_len){
1045         int i;
1046         for (i=0;i<num_devices;i++){
1047             uint8_t port_numbers[USB_MAX_PATH_LEN];
1048             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
1049             if (len != usb_path_len) continue;
1050             if (memcmp(usb_path, port_numbers, len) == 0){
1051                 log_info("USB device found at specified path");
1052                 handle = try_open_device(devs[i]);
1053                 if (!handle) continue;
1054 
1055                 r = prepare_device(handle);
1056                 if (r < 0) {
1057                     handle = NULL;
1058                     continue;
1059                 }
1060 
1061                 dev = devs[i];
1062                 r = scan_for_bt_endpoints(dev);
1063                 if (r < 0) {
1064                     handle = NULL;
1065                     continue;
1066                 }
1067 
1068                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
1069                 break;
1070             };
1071         }
1072         if (!handle){
1073             log_error("USB device with given path not found");
1074             printf("USB device with given path not found\n");
1075             return -1;
1076         }
1077     } else {
1078 
1079         int deviceIndex = -1;
1080         while (true){
1081             // look for next Bluetooth dongle
1082             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
1083             if (deviceIndex < 0) break;
1084 
1085             log_info("USB Bluetooth device found, index %u", deviceIndex);
1086 
1087             handle = try_open_device(devs[deviceIndex]);
1088             if (!handle) continue;
1089 
1090             r = prepare_device(handle);
1091             if (r < 0) {
1092                 handle = NULL;
1093                 continue;
1094             }
1095 
1096             dev = devs[deviceIndex];
1097             r = scan_for_bt_endpoints(dev);
1098             if (r < 0) {
1099                 handle = NULL;
1100                 continue;
1101             }
1102 
1103             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1104             break;
1105         }
1106     }
1107 
1108     libusb_free_device_list(devs, 1);
1109 
1110     if (handle == 0){
1111         log_error("No USB Bluetooth device found");
1112         return -1;
1113     }
1114 
1115 #endif
1116 
1117     // allocate transfer handlers
1118     int c;
1119     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1120         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1121         if (!event_in_transfer[c]) {
1122             usb_close();
1123             return LIBUSB_ERROR_NO_MEM;
1124         }
1125     }
1126     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1127         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1128         if (!acl_in_transfer[c]) {
1129             usb_close();
1130             return LIBUSB_ERROR_NO_MEM;
1131         }
1132     }
1133 
1134     command_out_transfer = libusb_alloc_transfer(0);
1135     acl_out_transfer     = libusb_alloc_transfer(0);
1136 
1137     // TODO check for error
1138 
1139     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1140 
1141     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1142         // configure event_in handlers
1143         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1144                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1145         r = libusb_submit_transfer(event_in_transfer[c]);
1146         if (r) {
1147             log_error("Error submitting interrupt transfer %d", r);
1148             usb_close();
1149             return r;
1150         }
1151     }
1152 
1153     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1154         // configure acl_in handlers
1155         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1156                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1157         r = libusb_submit_transfer(acl_in_transfer[c]);
1158         if (r) {
1159             log_error("Error submitting bulk in transfer %d", r);
1160             usb_close();
1161             return r;
1162         }
1163 
1164      }
1165 
1166  #if 0
1167     // Check for pollfds functionality
1168     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1169 #else
1170     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation
1171     doing_pollfds = 0;
1172 #endif
1173 
1174     if (doing_pollfds) {
1175         log_info("Async using pollfds:");
1176 
1177         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1178         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1179         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1180         if (!pollfd_data_sources){
1181             log_error("Cannot allocate data sources for pollfds");
1182             usb_close();
1183             return 1;
1184         }
1185         memset(pollfd_data_sources, 0, sizeof(btstack_data_source_t) * num_pollfds);
1186         for (r = 0 ; r < num_pollfds ; r++) {
1187             btstack_data_source_t *ds = &pollfd_data_sources[r];
1188             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1189             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1190             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1191             btstack_run_loop_add_data_source(ds);
1192             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1193         }
1194         free(pollfd);
1195     } else {
1196         log_info("Async using timers:");
1197 
1198         usb_timer.process = usb_process_ts;
1199         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1200         btstack_run_loop_add_timer(&usb_timer);
1201         usb_timer_active = 1;
1202     }
1203 
1204     usb_transport_open = 1;
1205 
1206     return 0;
1207 }
1208 
1209 static int usb_close(void){
1210     int c;
1211     int completed = 0;
1212 
1213     if (!usb_transport_open) return 0;
1214 
1215     log_info("usb_close");
1216 
1217     switch (libusb_state){
1218         case LIB_USB_CLOSED:
1219             break;
1220 
1221         case LIB_USB_TRANSFERS_ALLOCATED:
1222             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1223 
1224             if(usb_timer_active) {
1225                 btstack_run_loop_remove_timer(&usb_timer);
1226                 usb_timer_active = 0;
1227             }
1228 
1229             if (doing_pollfds){
1230                 int r;
1231                 for (r = 0 ; r < num_pollfds ; r++) {
1232                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1233                     btstack_run_loop_remove_data_source(ds);
1234                 }
1235                 free(pollfd_data_sources);
1236                 pollfd_data_sources = NULL;
1237                 num_pollfds = 0;
1238                 doing_pollfds = 0;
1239             }
1240 
1241             /* fall through */
1242 
1243         case LIB_USB_INTERFACE_CLAIMED:
1244             // Cancel all transfers, ignore warnings for this
1245             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1246             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1247                 if (event_in_transfer[c]){
1248                     log_info("cancel event_in_transfer[%u] = %p", c, event_in_transfer[c]);
1249                     libusb_cancel_transfer(event_in_transfer[c]);
1250                 }
1251             }
1252             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1253                 if (acl_in_transfer[c]){
1254                     log_info("cancel acl_in_transfer[%u] = %p", c, acl_in_transfer[c]);
1255                     libusb_cancel_transfer(acl_in_transfer[c]);
1256                 }
1257             }
1258 #ifdef ENABLE_SCO_OVER_HCI
1259             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1260                 if (sco_in_transfer[c]){
1261                     log_info("cancel sco_in_transfer[%u] = %p", c, sco_in_transfer[c]);
1262                     libusb_cancel_transfer(sco_in_transfer[c]);
1263                 }
1264             }
1265             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1266                 if (sco_out_transfers_in_flight[c]) {
1267                     log_info("cancel sco_out_transfers[%u] = %p", c, sco_out_transfers[c]);
1268                     libusb_cancel_transfer(sco_out_transfers[c]);
1269                 } else {
1270                     if (sco_out_transfers[c] != NULL){
1271                         libusb_free_transfer(sco_out_transfers[c]);
1272                         sco_out_transfers[c] = 0;
1273                     }
1274                 }
1275             }
1276 #endif
1277             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1278 
1279             // wait until all transfers are completed - or 20 iterations
1280             int countdown = 20;
1281             while (!completed){
1282 
1283                 if (--countdown == 0){
1284                     log_info("Not all transfers cancelled, leaking a bit.");
1285                     break;
1286                 }
1287 
1288                 struct timeval tv;
1289                 memset(&tv, 0, sizeof(struct timeval));
1290                 libusb_handle_events_timeout(NULL, &tv);
1291                 // check if all done
1292                 completed = 1;
1293                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1294                     if (event_in_transfer[c]) {
1295                         log_info("event_in_transfer[%u] still active (%p)", c, event_in_transfer[c]);
1296                         completed = 0;
1297                         break;
1298                     }
1299                 }
1300 
1301                 if (!completed) continue;
1302 
1303                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1304                     if (acl_in_transfer[c]) {
1305                         log_info("acl_in_transfer[%u] still active (%p)", c, acl_in_transfer[c]);
1306                         completed = 0;
1307                         break;
1308                     }
1309                 }
1310 
1311 #ifdef ENABLE_SCO_OVER_HCI
1312                 if (!completed) continue;
1313 
1314                 // Cancel all synchronous transfer
1315                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1316                     if (sco_in_transfer[c]){
1317                         log_info("sco_in_transfer[%u] still active (%p)", c, sco_in_transfer[c]);
1318                         completed = 0;
1319                         break;
1320                     }
1321                 }
1322 
1323                 if (!completed) continue;
1324 
1325                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1326                     if (sco_out_transfers[c] != NULL){
1327                         log_info("sco_out_transfers[%u] still active (%p)", c, sco_out_transfers[c]);
1328                         completed = 0;
1329                         break;
1330                     }
1331                 }
1332                 sco_enabled = 0;
1333 #endif
1334             }
1335 
1336             // finally release interface
1337             libusb_release_interface(handle, 0);
1338 #ifdef ENABLE_SCO_OVER_HCI
1339             libusb_release_interface(handle, 1);
1340 #endif
1341             log_info("Libusb shutdown complete");
1342 
1343 			/* fall through */
1344 
1345         case LIB_USB_DEVICE_OPENDED:
1346             libusb_close(handle);
1347 
1348 			/* fall through */
1349 
1350         case LIB_USB_OPENED:
1351             libusb_exit(NULL);
1352             break;
1353 
1354 		default:
1355 			btstack_assert(false);
1356 			break;
1357     }
1358 
1359     libusb_state = LIB_USB_CLOSED;
1360     handle = NULL;
1361     usb_transport_open = 0;
1362 
1363     return 0;
1364 }
1365 
1366 static int usb_send_cmd_packet(uint8_t *packet, int size){
1367     int r;
1368 
1369     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1370 
1371     // async
1372     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1373     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1374 
1375     // prepare transfer
1376     int completed = 0;
1377     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1378     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1379 
1380     // update stata before submitting transfer
1381     usb_command_active = 1;
1382 
1383     // submit transfer
1384     r = libusb_submit_transfer(command_out_transfer);
1385 
1386     if (r < 0) {
1387         usb_command_active = 0;
1388         log_error("Error submitting cmd transfer %d", r);
1389         return -1;
1390     }
1391 
1392     return 0;
1393 }
1394 
1395 static int usb_send_acl_packet(uint8_t *packet, int size){
1396     int r;
1397 
1398     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1399 
1400     // log_info("usb_send_acl_packet enter, size %u", size);
1401 
1402     // prepare transfer
1403     int completed = 0;
1404     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1405         async_callback, &completed, 0);
1406     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1407 
1408     // update stata before submitting transfer
1409     usb_acl_out_active = 1;
1410 
1411     r = libusb_submit_transfer(acl_out_transfer);
1412     if (r < 0) {
1413         usb_acl_out_active = 0;
1414         log_error("Error submitting acl transfer, %d", r);
1415         return -1;
1416     }
1417 
1418     return 0;
1419 }
1420 
1421 static int usb_can_send_packet_now(uint8_t packet_type){
1422     switch (packet_type){
1423         case HCI_COMMAND_DATA_PACKET:
1424             return !usb_command_active;
1425         case HCI_ACL_DATA_PACKET:
1426             return !usb_acl_out_active;
1427 #ifdef ENABLE_SCO_OVER_HCI
1428         case HCI_SCO_DATA_PACKET:
1429             if (!sco_enabled) return 0;
1430             return sco_ring_have_space();
1431 #endif
1432         default:
1433             return 0;
1434     }
1435 }
1436 
1437 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1438     switch (packet_type){
1439         case HCI_COMMAND_DATA_PACKET:
1440             return usb_send_cmd_packet(packet, size);
1441         case HCI_ACL_DATA_PACKET:
1442             return usb_send_acl_packet(packet, size);
1443 #ifdef ENABLE_SCO_OVER_HCI
1444         case HCI_SCO_DATA_PACKET:
1445             if (!sco_enabled) return -1;
1446             return usb_send_sco_packet(packet, size);
1447 #endif
1448         default:
1449             return -1;
1450     }
1451 }
1452 
1453 #ifdef ENABLE_SCO_OVER_HCI
1454 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1455     if (!sco_enabled) return;
1456 
1457     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1458 
1459     if (num_connections != sco_num_connections){
1460         sco_voice_setting = voice_setting;
1461         if (sco_num_connections){
1462             usb_sco_stop();
1463         }
1464         sco_num_connections = num_connections;
1465         if (num_connections){
1466             usb_sco_start();
1467         }
1468     }
1469 }
1470 #endif
1471 
1472 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1473     log_info("registering packet handler");
1474     packet_handler = handler;
1475 }
1476 
1477 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1478     UNUSED(packet_type);
1479     UNUSED(packet);
1480     UNUSED(size);
1481 }
1482 
1483 // get usb singleton
1484 const hci_transport_t * hci_transport_usb_instance(void) {
1485     if (!hci_transport_usb) {
1486         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1487         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1488         hci_transport_usb->name                          = "H2_LIBUSB";
1489         hci_transport_usb->open                          = usb_open;
1490         hci_transport_usb->close                         = usb_close;
1491         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1492         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1493         hci_transport_usb->send_packet                   = usb_send_packet;
1494 #ifdef ENABLE_SCO_OVER_HCI
1495         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1496 #endif
1497     }
1498     return hci_transport_usb;
1499 }
1500