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