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