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