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