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