xref: /btstack/platform/libusb/hci_transport_h2_libusb.c (revision 1884f13fb9884b15dacdfc04d9536827c4949e99)
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 };
585 
586 static int num_known_devices = sizeof(known_bt_devices) / sizeof(uint16_t) / 2;
587 
588 static int is_known_bt_device(uint16_t vendor_id, uint16_t product_id){
589     int i;
590     for (i=0; i<num_known_devices; i++){
591         if (known_bt_devices[i*2] == vendor_id && known_bt_devices[i*2+1] == product_id){
592             return 1;
593         }
594     }
595     return 0;
596 }
597 
598 static void scan_for_bt_endpoints(void) {
599     int r;
600 
601     event_in_addr = 0;
602     acl_in_addr = 0;
603     acl_out_addr = 0;
604     sco_out_addr = 0;
605     sco_in_addr = 0;
606 
607     // get endpoints from interface descriptor
608     struct libusb_config_descriptor *config_descriptor;
609     r = libusb_get_active_config_descriptor(dev, &config_descriptor);
610 
611     int num_interfaces = config_descriptor->bNumInterfaces;
612     log_info("active configuration has %u interfaces", num_interfaces);
613 
614     int i;
615     for (i = 0; i < num_interfaces ; i++){
616         const struct libusb_interface *interface = &config_descriptor->interface[i];
617         const struct libusb_interface_descriptor * interface_descriptor = interface->altsetting;
618         log_info("interface %u: %u endpoints", i, interface_descriptor->bNumEndpoints);
619 
620         const struct libusb_endpoint_descriptor *endpoint = interface_descriptor->endpoint;
621 
622         for (r=0;r<interface_descriptor->bNumEndpoints;r++,endpoint++){
623             log_info("- endpoint %x, attributes %x", endpoint->bEndpointAddress, endpoint->bmAttributes);
624 
625             switch (endpoint->bmAttributes & 0x3){
626                 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
627                     if (event_in_addr) continue;
628                     event_in_addr = endpoint->bEndpointAddress;
629                     log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
630                     break;
631                 case LIBUSB_TRANSFER_TYPE_BULK:
632                     if (endpoint->bEndpointAddress & 0x80) {
633                         if (acl_in_addr) continue;
634                         acl_in_addr = endpoint->bEndpointAddress;
635                         log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
636                     } else {
637                         if (acl_out_addr) continue;
638                         acl_out_addr = endpoint->bEndpointAddress;
639                         log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
640                     }
641                     break;
642                 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
643                     if (endpoint->bEndpointAddress & 0x80) {
644                         if (sco_in_addr) continue;
645                         sco_in_addr = endpoint->bEndpointAddress;
646                         log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
647                     } else {
648                         if (sco_out_addr) continue;
649                         sco_out_addr = endpoint->bEndpointAddress;
650                         log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
651                     }
652                     break;
653                 default:
654                     break;
655             }
656         }
657     }
658     libusb_free_config_descriptor(config_descriptor);
659 }
660 
661 // returns index of found device or -1
662 static int scan_for_bt_device(libusb_device **devs, int start_index) {
663     int i;
664     for (i = start_index; devs[i] ; i++){
665         dev = devs[i];
666         int r = libusb_get_device_descriptor(dev, &desc);
667         if (r < 0) {
668             log_error("failed to get device descriptor");
669             return 0;
670         }
671 
672         log_info("%04x:%04x (bus %d, device %d) - class %x subclass %x protocol %x ",
673                desc.idVendor, desc.idProduct,
674                libusb_get_bus_number(dev), libusb_get_device_address(dev),
675                desc.bDeviceClass, desc.bDeviceSubClass, desc.bDeviceProtocol);
676 
677         // Detect USB Dongle based Class, Subclass, and Protocol
678         // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
679         // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
680         // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
681         // if (desc.bDeviceClass == 0xe0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01){
682         if (desc.bDeviceClass == 0xE0 && desc.bDeviceSubClass == 0x01 && desc.bDeviceProtocol == 0x01) {
683             return i;
684         }
685 
686         // Detect USB Dongle based on whitelist
687         if (is_known_bt_device(desc.idVendor, desc.idProduct)) {
688             return i;
689         }
690     }
691     return -1;
692 }
693 #endif
694 
695 static int prepare_device(libusb_device_handle * aHandle){
696 
697     // print device path
698     uint8_t port_numbers[USB_MAX_PATH_LEN];
699     libusb_device * device = libusb_get_device(aHandle);
700     int path_len = libusb_get_port_numbers(device, port_numbers, USB_MAX_PATH_LEN);
701     printf("USB Path: ");
702     int i;
703     for (i=0;i<path_len;i++){
704         if (i) printf("-");
705         printf("%02x", port_numbers[i]);
706     }
707     printf("\n");
708 
709     int r;
710     int kernel_driver_detached = 0;
711 
712     // Detach OS driver (not possible for OS X and WIN32)
713 #if !defined(__APPLE__) && !defined(_WIN32)
714     r = libusb_kernel_driver_active(aHandle, 0);
715     if (r < 0) {
716         log_error("libusb_kernel_driver_active error %d", r);
717         libusb_close(aHandle);
718         return r;
719     }
720 
721     if (r == 1) {
722         r = libusb_detach_kernel_driver(aHandle, 0);
723         if (r < 0) {
724             log_error("libusb_detach_kernel_driver error %d", r);
725             libusb_close(aHandle);
726             return r;
727         }
728         kernel_driver_detached = 1;
729     }
730     log_info("libusb_detach_kernel_driver");
731 #endif
732 
733     const int configuration = 1;
734     log_info("setting configuration %d...", configuration);
735     r = libusb_set_configuration(aHandle, configuration);
736     if (r < 0) {
737         log_error("Error libusb_set_configuration: %d", r);
738         if (kernel_driver_detached){
739             libusb_attach_kernel_driver(aHandle, 0);
740         }
741         libusb_close(aHandle);
742         return r;
743     }
744 
745     // reserve access to device
746     log_info("claiming interface 0...");
747     r = libusb_claim_interface(aHandle, 0);
748     if (r < 0) {
749         log_error("Error claiming interface %d", r);
750         if (kernel_driver_detached){
751             libusb_attach_kernel_driver(aHandle, 0);
752         }
753         libusb_close(aHandle);
754         return r;
755     }
756 
757 #ifdef ENABLE_SCO_OVER_HCI
758     log_info("claiming interface 1...");
759     r = libusb_claim_interface(aHandle, 1);
760     if (r < 0) {
761         log_error("Error claiming interface %d", r);
762         if (kernel_driver_detached){
763             libusb_attach_kernel_driver(aHandle, 0);
764         }
765         libusb_close(aHandle);
766         return r;
767     }
768 #endif
769 
770     return 0;
771 }
772 
773 static libusb_device_handle * try_open_device(libusb_device * device){
774     int r;
775 
776     libusb_device_handle * dev_handle;
777     r = libusb_open(device, &dev_handle);
778 
779     if (r < 0) {
780         log_error("libusb_open failed!");
781         dev_handle = NULL;
782         return NULL;
783     }
784 
785     log_info("libusb open %d, handle %p", r, dev_handle);
786 
787     // reset device
788     libusb_reset_device(dev_handle);
789     if (r < 0) {
790         log_error("libusb_reset_device failed!");
791         libusb_close(dev_handle);
792         return NULL;
793     }
794     return dev_handle;
795 }
796 
797 #ifdef ENABLE_SCO_OVER_HCI
798 
799 static int usb_sco_start(void){
800 
801     printf("usb_sco_start\n");
802     log_info("usb_sco_start");
803 
804     sco_state_machine_init();
805     sco_ring_init();
806 
807     int alt_setting;
808     if (sco_voice_setting & 0x0020){
809         // 16-bit PCM
810         alt_setting = alt_setting_16_bit[sco_num_connections-1];
811     } else {
812         // 8-bit PCM or mSBC
813         alt_setting = alt_setting_8_bit[sco_num_connections-1];
814     }
815     // derive iso packet size from alt setting
816     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
817 
818     log_info("Switching to setting %u on interface 1..", alt_setting);
819     int r = libusb_set_interface_alt_setting(handle, 1, alt_setting);
820     if (r < 0) {
821         log_error("Error setting alternative setting %u for interface 1: %s\n", alt_setting, libusb_error_name(r));
822         return r;
823     }
824 
825     // incoming
826     int c;
827     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
828         sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in
829         if (!sco_in_transfer[c]) {
830             usb_close();
831             return LIBUSB_ERROR_NO_MEM;
832         }
833         // configure sco_in handlers
834         libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr,
835             hci_sco_in_buffer[c], NUM_ISO_PACKETS * iso_packet_size, NUM_ISO_PACKETS, async_callback, NULL, 0);
836         libusb_set_iso_packet_lengths(sco_in_transfer[c], iso_packet_size);
837         r = libusb_submit_transfer(sco_in_transfer[c]);
838         if (r) {
839             log_error("Error submitting isochronous in transfer %d", r);
840             usb_close();
841             return r;
842         }
843     }
844 
845     // outgoing
846     for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
847         sco_out_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts
848         sco_out_transfers_in_flight[c] = 0;
849     }
850     return 0;
851 }
852 
853 static void usb_sco_stop(void){
854 
855     printf("usb_sco_stop\n");
856 
857     log_info("usb_sco_stop");
858     sco_shutdown = 1;
859 
860     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
861 
862     int c;
863     for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
864         libusb_cancel_transfer(sco_in_transfer[c]);
865     }
866 
867     for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
868         if (sco_out_transfers_in_flight[c]) {
869             libusb_cancel_transfer(sco_out_transfers[c]);
870         } else {
871             libusb_free_transfer(sco_out_transfers[c]);
872             sco_out_transfers[c] = 0;
873         }
874     }
875 
876     // wait until all transfers are completed
877     int completed = 0;
878     while (!completed){
879         struct timeval tv;
880         memset(&tv, 0, sizeof(struct timeval));
881         libusb_handle_events_timeout(NULL, &tv);
882         // check if all done
883         completed = 1;
884 
885         // Cancel all synchronous transfer
886         for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
887             if (sco_in_transfer[c]){
888                 completed = 0;
889                 break;
890             }
891         }
892 
893         if (!completed) continue;
894 
895         for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
896             if (sco_out_transfers[c]){
897                 completed = 0;
898                 break;
899             }
900         }
901     }
902     sco_shutdown = 0;
903     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
904 
905     log_info("Switching to setting %u on interface 1..", 0);
906     int r = libusb_set_interface_alt_setting(handle, 1, 0);
907     if (r < 0) {
908         log_error("Error setting alternative setting %u for interface 1: %s", 0, libusb_error_name(r));
909         return;
910     }
911 
912     printf("usb_sco_stop done\n");
913 }
914 
915 
916 
917 #endif
918 
919 static int usb_open(void){
920     int r;
921 
922     handle_packet = NULL;
923 
924     // default endpoint addresses
925     event_in_addr = 0x81; // EP1, IN interrupt
926     acl_in_addr =   0x82; // EP2, IN bulk
927     acl_out_addr =  0x02; // EP2, OUT bulk
928     sco_in_addr  =  0x83; // EP3, IN isochronous
929     sco_out_addr =  0x03; // EP3, OUT isochronous
930 
931     // USB init
932     r = libusb_init(NULL);
933     if (r < 0) return -1;
934 
935     libusb_state = LIB_USB_OPENED;
936 
937     // configure debug level
938     libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
939 
940 #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID
941 
942     // Use a specified device
943     log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID);
944     handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID);
945 
946     if (!handle){
947         log_error("libusb_open_device_with_vid_pid failed!");
948         usb_close();
949         return -1;
950     }
951     log_info("libusb open %d, handle %p", r, handle);
952 
953     r = prepare_device(handle);
954     if (r < 0){
955         usb_close();
956         return -1;
957     }
958 
959 #else
960     // Scan system for an appropriate devices
961     libusb_device **devs;
962     ssize_t num_devices;
963 
964     log_info("Scanning for USB Bluetooth device");
965     num_devices = libusb_get_device_list(NULL, &devs);
966     if (num_devices < 0) {
967         usb_close();
968         return -1;
969     }
970 
971     dev = NULL;
972 
973     if (usb_path_len){
974         int i;
975         for (i=0;i<num_devices;i++){
976             uint8_t port_numbers[USB_MAX_PATH_LEN];
977             int len = libusb_get_port_numbers(devs[i], port_numbers, USB_MAX_PATH_LEN);
978             if (len != usb_path_len) continue;
979             if (memcmp(usb_path, port_numbers, len) == 0){
980                 log_info("USB device found at specified path");
981                 handle = try_open_device(devs[i]);
982                 if (!handle) continue;
983 
984                 r = prepare_device(handle);
985                 if (r < 0) continue;
986 
987                 dev = devs[i];
988                 libusb_state = LIB_USB_INTERFACE_CLAIMED;
989                 break;
990             };
991         }
992         if (!handle){
993             log_error("USB device with given path not found");
994             printf("USB device with given path not found\n");
995             return -1;
996         }
997     } else {
998 
999         int deviceIndex = -1;
1000         while (1){
1001             // look for next Bluetooth dongle
1002             deviceIndex = scan_for_bt_device(devs, deviceIndex+1);
1003             if (deviceIndex < 0) break;
1004 
1005             log_info("USB Bluetooth device found, index %u", deviceIndex);
1006 
1007             handle = try_open_device(devs[deviceIndex]);
1008             if (!handle) continue;
1009 
1010             r = prepare_device(handle);
1011             if (r < 0) continue;
1012 
1013             dev = devs[deviceIndex];
1014             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1015             break;
1016         }
1017     }
1018 
1019     libusb_free_device_list(devs, 1);
1020 
1021     if (handle == 0){
1022         log_error("No USB Bluetooth device found");
1023         return -1;
1024     }
1025 
1026     scan_for_bt_endpoints();
1027 
1028 #endif
1029 
1030     // allocate transfer handlers
1031     int c;
1032     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1033         event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events
1034         if (!event_in_transfer[c]) {
1035             usb_close();
1036             return LIBUSB_ERROR_NO_MEM;
1037         }
1038     }
1039     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1040         acl_in_transfer[c]  =  libusb_alloc_transfer(0); // 0 isochronous transfers ACL in
1041         if (!acl_in_transfer[c]) {
1042             usb_close();
1043             return LIBUSB_ERROR_NO_MEM;
1044         }
1045     }
1046 
1047     command_out_transfer = libusb_alloc_transfer(0);
1048     acl_out_transfer     = libusb_alloc_transfer(0);
1049 
1050     // TODO check for error
1051 
1052     libusb_state = LIB_USB_TRANSFERS_ALLOCATED;
1053 
1054     for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1055         // configure event_in handlers
1056         libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr,
1057                 hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1058         r = libusb_submit_transfer(event_in_transfer[c]);
1059         if (r) {
1060             log_error("Error submitting interrupt transfer %d", r);
1061             usb_close();
1062             return r;
1063         }
1064     }
1065 
1066     for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1067         // configure acl_in handlers
1068         libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr,
1069                 hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ;
1070         r = libusb_submit_transfer(acl_in_transfer[c]);
1071         if (r) {
1072             log_error("Error submitting bulk in transfer %d", r);
1073             usb_close();
1074             return r;
1075         }
1076 
1077      }
1078 
1079     // Check for pollfds functionality
1080     doing_pollfds = libusb_pollfds_handle_timeouts(NULL);
1081 
1082     // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation here
1083     doing_pollfds = 0;
1084 
1085     if (doing_pollfds) {
1086         log_info("Async using pollfds:");
1087 
1088         const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL);
1089         for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++);
1090         pollfd_data_sources = (btstack_data_source_t *)malloc(sizeof(btstack_data_source_t) * num_pollfds);
1091         if (!pollfd_data_sources){
1092             log_error("Cannot allocate data sources for pollfds");
1093             usb_close();
1094             return 1;
1095         }
1096         for (r = 0 ; r < num_pollfds ; r++) {
1097             btstack_data_source_t *ds = &pollfd_data_sources[r];
1098             btstack_run_loop_set_data_source_fd(ds, pollfd[r]->fd);
1099             btstack_run_loop_set_data_source_handler(ds, &usb_process_ds);
1100             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
1101             btstack_run_loop_add_data_source(ds);
1102             log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events);
1103         }
1104         free(pollfd);
1105     } else {
1106         log_info("Async using timers:");
1107 
1108         usb_timer.process = usb_process_ts;
1109         btstack_run_loop_set_timer(&usb_timer, ASYNC_POLLING_INTERVAL_MS);
1110         btstack_run_loop_add_timer(&usb_timer);
1111         usb_timer_active = 1;
1112     }
1113 
1114     return 0;
1115 }
1116 
1117 static int usb_close(void){
1118     int c;
1119     int completed = 0;
1120 
1121     log_info("usb_close");
1122 
1123     switch (libusb_state){
1124         case LIB_USB_CLOSED:
1125             break;
1126 
1127         case LIB_USB_TRANSFERS_ALLOCATED:
1128             libusb_state = LIB_USB_INTERFACE_CLAIMED;
1129 
1130             if(usb_timer_active) {
1131                 btstack_run_loop_remove_timer(&usb_timer);
1132                 usb_timer_active = 0;
1133             }
1134 
1135             if (doing_pollfds){
1136                 int r;
1137                 for (r = 0 ; r < num_pollfds ; r++) {
1138                     btstack_data_source_t *ds = &pollfd_data_sources[r];
1139                     btstack_run_loop_remove_data_source(ds);
1140                 }
1141                 free(pollfd_data_sources);
1142                 pollfd_data_sources = NULL;
1143                 num_pollfds = 0;
1144                 doing_pollfds = 0;
1145             }
1146 
1147         case LIB_USB_INTERFACE_CLAIMED:
1148             // Cancel all transfers, ignore warnings for this
1149             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_ERROR);
1150             for (c = 0 ; c < EVENT_IN_BUFFER_COUNT ; c++) {
1151                 if (event_in_transfer[c]){
1152                     log_info("cancel event_in_transfer[%u] = %p", c, event_in_transfer[c]);
1153                     libusb_cancel_transfer(event_in_transfer[c]);
1154                 }
1155             }
1156             for (c = 0 ; c < ACL_IN_BUFFER_COUNT ; c++) {
1157                 if (acl_in_transfer[c]){
1158                     log_info("cancel acl_in_transfer[%u] = %p", c, acl_in_transfer[c]);
1159                     libusb_cancel_transfer(acl_in_transfer[c]);
1160                 }
1161             }
1162 #ifdef ENABLE_SCO_OVER_HCI
1163             for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1164                 if (sco_in_transfer[c]){
1165                     log_info("cancel sco_in_transfer[%u] = %p", c, sco_in_transfer[c]);
1166                     libusb_cancel_transfer(sco_in_transfer[c]);
1167                 }
1168             }
1169             for (c = 0; c < SCO_OUT_BUFFER_COUNT ; c++){
1170                 if (sco_out_transfers_in_flight[c]) {
1171                     log_info("cancel sco_out_transfers[%u] = %p", c, sco_out_transfers[c]);
1172                     libusb_cancel_transfer(sco_out_transfers[c]);
1173                 } else {
1174                     libusb_free_transfer(sco_out_transfers[c]);
1175                     sco_out_transfers[c] = 0;
1176                 }
1177             }
1178 #endif
1179             libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
1180 
1181             // wait until all transfers are completed - or 20 iterations
1182             int countdown = 20;
1183             while (!completed){
1184 
1185                 if (--countdown == 0){
1186                     log_info("Not all transfers cancelled, leaking a bit.");
1187                     break;
1188                 }
1189 
1190                 struct timeval tv;
1191                 memset(&tv, 0, sizeof(struct timeval));
1192                 libusb_handle_events_timeout(NULL, &tv);
1193                 // check if all done
1194                 completed = 1;
1195                 for (c=0;c<EVENT_IN_BUFFER_COUNT;c++){
1196                     if (event_in_transfer[c]) {
1197                         log_info("event_in_transfer[%u] still active (%p)", c, event_in_transfer[c]);
1198                         completed = 0;
1199                         break;
1200                     }
1201                 }
1202 
1203                 if (!completed) continue;
1204 
1205                 for (c=0;c<ACL_IN_BUFFER_COUNT;c++){
1206                     if (acl_in_transfer[c]) {
1207                         log_info("acl_in_transfer[%u] still active (%p)", c, acl_in_transfer[c]);
1208                         completed = 0;
1209                         break;
1210                     }
1211                 }
1212 
1213 #ifdef ENABLE_SCO_OVER_HCI
1214                 if (!completed) continue;
1215 
1216                 // Cancel all synchronous transfer
1217                 for (c = 0 ; c < SCO_IN_BUFFER_COUNT ; c++) {
1218                     if (sco_in_transfer[c]){
1219                         log_info("sco_in_transfer[%u] still active (%p)", c, sco_in_transfer[c]);
1220                         completed = 0;
1221                         break;
1222                     }
1223                 }
1224 
1225                 if (!completed) continue;
1226 
1227                 for (c=0; c < SCO_OUT_BUFFER_COUNT ; c++){
1228                     if (sco_out_transfers[c]){
1229                         log_info("sco_out_transfers[%u] still active (%p)", c, sco_out_transfers[c]);
1230                         completed = 0;
1231                         break;
1232                     }
1233                 }
1234 #endif
1235             }
1236 
1237             // finally release interface
1238             libusb_release_interface(handle, 0);
1239 #ifdef ENABLE_SCO_OVER_HCI
1240             libusb_release_interface(handle, 1);
1241 #endif
1242             log_info("Libusb shutdown complete");
1243 
1244         case LIB_USB_DEVICE_OPENDED:
1245             libusb_close(handle);
1246 
1247         case LIB_USB_OPENED:
1248             libusb_exit(NULL);
1249     }
1250 
1251     libusb_state = LIB_USB_CLOSED;
1252     handle = NULL;
1253 
1254     return 0;
1255 }
1256 
1257 static int usb_send_cmd_packet(uint8_t *packet, int size){
1258     int r;
1259 
1260     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1261 
1262     // async
1263     libusb_fill_control_setup(hci_cmd_buffer, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, 0, 0, 0, size);
1264     memcpy(hci_cmd_buffer + LIBUSB_CONTROL_SETUP_SIZE, packet, size);
1265 
1266     // prepare transfer
1267     int completed = 0;
1268     libusb_fill_control_transfer(command_out_transfer, handle, hci_cmd_buffer, async_callback, &completed, 0);
1269     command_out_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
1270 
1271     // update stata before submitting transfer
1272     usb_command_active = 1;
1273 
1274     // submit transfer
1275     r = libusb_submit_transfer(command_out_transfer);
1276 
1277     if (r < 0) {
1278         usb_command_active = 0;
1279         log_error("Error submitting cmd transfer %d", r);
1280         return -1;
1281     }
1282 
1283     return 0;
1284 }
1285 
1286 static int usb_send_acl_packet(uint8_t *packet, int size){
1287     int r;
1288 
1289     if (libusb_state != LIB_USB_TRANSFERS_ALLOCATED) return -1;
1290 
1291     // log_info("usb_send_acl_packet enter, size %u", size);
1292 
1293     // prepare transfer
1294     int completed = 0;
1295     libusb_fill_bulk_transfer(acl_out_transfer, handle, acl_out_addr, packet, size,
1296         async_callback, &completed, 0);
1297     acl_out_transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1298 
1299     // update stata before submitting transfer
1300     usb_acl_out_active = 1;
1301 
1302     r = libusb_submit_transfer(acl_out_transfer);
1303     if (r < 0) {
1304         usb_acl_out_active = 0;
1305         log_error("Error submitting acl transfer, %d", r);
1306         return -1;
1307     }
1308 
1309     return 0;
1310 }
1311 
1312 static int usb_can_send_packet_now(uint8_t packet_type){
1313     switch (packet_type){
1314         case HCI_COMMAND_DATA_PACKET:
1315             return !usb_command_active;
1316         case HCI_ACL_DATA_PACKET:
1317             return !usb_acl_out_active;
1318 #ifdef ENABLE_SCO_OVER_HCI
1319         case HCI_SCO_DATA_PACKET:
1320             return sco_ring_have_space();
1321 #endif
1322         default:
1323             return 0;
1324     }
1325 }
1326 
1327 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1328     switch (packet_type){
1329         case HCI_COMMAND_DATA_PACKET:
1330             return usb_send_cmd_packet(packet, size);
1331         case HCI_ACL_DATA_PACKET:
1332             return usb_send_acl_packet(packet, size);
1333 #ifdef ENABLE_SCO_OVER_HCI
1334         case HCI_SCO_DATA_PACKET:
1335             return usb_send_sco_packet(packet, size);
1336 #endif
1337         default:
1338             return -1;
1339     }
1340 }
1341 
1342 #ifdef ENABLE_SCO_OVER_HCI
1343 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1344     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1345 
1346     if (num_connections != sco_num_connections){
1347         sco_voice_setting = voice_setting;
1348         if (sco_num_connections){
1349             usb_sco_stop();
1350         }
1351         sco_num_connections = num_connections;
1352         if (num_connections){
1353             usb_sco_start();
1354         }
1355     }
1356 }
1357 #endif
1358 
1359 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1360     log_info("registering packet handler");
1361     packet_handler = handler;
1362 }
1363 
1364 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1365     UNUSED(packet_type);
1366     UNUSED(packet);
1367     UNUSED(size);
1368 }
1369 
1370 // get usb singleton
1371 const hci_transport_t * hci_transport_usb_instance(void) {
1372     if (!hci_transport_usb) {
1373         hci_transport_usb = (hci_transport_t*) malloc( sizeof(hci_transport_t));
1374         memset(hci_transport_usb, 0, sizeof(hci_transport_t));
1375         hci_transport_usb->name                          = "H2_LIBUSB";
1376         hci_transport_usb->open                          = usb_open;
1377         hci_transport_usb->close                         = usb_close;
1378         hci_transport_usb->register_packet_handler       = usb_register_packet_handler;
1379         hci_transport_usb->can_send_packet_now           = usb_can_send_packet_now;
1380         hci_transport_usb->send_packet                   = usb_send_packet;
1381 #ifdef ENABLE_SCO_OVER_HCI
1382         hci_transport_usb->set_sco_config                = usb_set_sco_config;
1383 #endif
1384     }
1385     return hci_transport_usb;
1386 }
1387