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