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