xref: /btstack/platform/windows/hci_transport_h2_winusb.c (revision 507db0376297d52ae8f6d71e83cf005235d6dfc9)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "hci_transport_h2_winusb.c"
39 
40 /*
41  *  hci_transport_usb.c
42  *
43  *  HCI Transport API implementation for USB
44  *
45  *  Created by Matthias Ringwald on 7/5/09.
46  */
47 
48 // Interface Number - Alternate Setting - suggested Endpoint Address - Endpoint Type - Suggested Max Packet Size
49 // HCI Commands 0 0 0x00 Control 8/16/32/64
50 // HCI Events   0 0 0x81 Interrupt (IN) 16
51 // ACL Data     0 0 0x82 Bulk (IN) 32/64
52 // ACL Data     0 0 0x02 Bulk (OUT) 32/64
53 // SCO Data     0 0 0x83 Isochronous (IN)
54 // SCO Data     0 0 0x03 Isochronous (Out)
55 
56 #include <stdio.h>
57 #include <strings.h>
58 #include <string.h>
59 #include <unistd.h>   /* UNIX standard function definitions */
60 #include <sys/types.h>
61 #include <inttypes.h>   // to print long long int (aka 64 bit ints)
62 
63 #include "btstack_config.h"
64 
65 #include "btstack_debug.h"
66 #include "hci.h"
67 #include "hci_transport.h"
68 
69 #include <Windows.h>
70 #include <SetupAPI.h>
71 #include <Winusb.h>
72 
73 #ifdef ENABLE_SCO_OVER_HCI
74 
75 // Isochronous Add-On
76 
77 // Function signatures frome https://abi-laboratory.pro/compatibility/Windows_7.0_to_Windows_8.1/x86_64/info/winusb.dll/symbols.html
78 // MSDN documentation has multiple errors (Jan 2017), annotated below
79 
80 // As Isochochronous functions are provided by newer versions of ming64, we use a BTstack/BTSTACK prefix to prevent name collisions
81 
82 typedef PVOID BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE, *BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE;
83 
84 typedef struct _BTSTACK_WINUSB_PIPE_INFORMATION_EX {
85   USBD_PIPE_TYPE PipeType;
86   UCHAR          PipeId;
87   USHORT         MaximumPacketSize;
88   UCHAR          Interval;
89   ULONG          MaximumBytesPerInterval;
90 } BTSTACK_WINUSB_PIPE_INFORMATION_EX, *BTSTACK_PWINUSB_PIPE_INFORMATION_EX;
91 
92 typedef WINBOOL (WINAPI * BTstack_WinUsb_QueryPipeEx_t) (
93 	WINUSB_INTERFACE_HANDLE 	InterfaceHandle,
94 	UCHAR						AlternateInterfaceNumber,
95 	UCHAR 						PipeIndex,
96 	BTSTACK_PWINUSB_PIPE_INFORMATION_EX PipeInformationEx
97 );
98 typedef WINBOOL (WINAPI * BTstack_WinUsb_RegisterIsochBuffer_t)(
99 	WINUSB_INTERFACE_HANDLE     InterfaceHandle,
100 	UCHAR                       PipeID,
101 	PVOID                       Buffer,
102 	ULONG                       BufferLength,
103 	BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle
104 );
105 typedef WINBOOL (WINAPI * BTstack_WinUsb_ReadIsochPipe_t)(
106     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
107     ULONG                       Offset,
108     ULONG                       Length,
109     PULONG                      FrameNumber,
110     ULONG                       NumberOfPackets,        // MSDN lists PULONG
111     PUSBD_ISO_PACKET_DESCRIPTOR IsoPacketDescriptors,   // MSDN lists PULONG
112     LPOVERLAPPED                Overlapped
113 );
114 typedef WINBOOL (WINAPI * BTstack_WinUsb_ReadIsochPipeAsap_t)(
115     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
116     ULONG                       Offset,
117     ULONG                       Length,
118     BOOL                        ContinueStream,
119     ULONG                      	NumberOfPackets,        // MSDN lists PULONG
120     PUSBD_ISO_PACKET_DESCRIPTOR IsoPacketDescriptors,
121  	LPOVERLAPPED                Overlapped
122 );
123 typedef WINBOOL (WINAPI * BTstack_WinUsb_WriteIsochPipe_t)(
124     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
125     ULONG                       Offset,
126     ULONG                       Length,
127     PULONG                      FrameNumber,
128 	LPOVERLAPPED                Overlapped
129 );
130 typedef WINBOOL (WINAPI * BTstack_WinUsb_WriteIsochPipeAsap_t)(
131     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
132     ULONG                       Offset,
133     ULONG                       Length,
134     BOOL                        ContinueStream,
135 	LPOVERLAPPED                Overlapped
136 );
137 typedef WINBOOL (WINAPI * BTstack_WinUsb_UnregisterIsochBuffer_t)(
138 	BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle
139 );
140 typedef WINBOOL (WINAPI * BTstack_WinUsb_GetCurrentFrameNumber_t)(
141     WINUSB_INTERFACE_HANDLE     InterfaceHandle,        // MSDN lists 'Device handle returned from CreateFile'
142     PULONG                      CurrentFrameNumber,
143     LARGE_INTEGER               *TimeStamp
144 );
145 
146 static BTstack_WinUsb_QueryPipeEx_t 			BTstack_WinUsb_QueryPipeEx;
147 static BTstack_WinUsb_RegisterIsochBuffer_t 	BTstack_WinUsb_RegisterIsochBuffer;
148 static BTstack_WinUsb_ReadIsochPipe_t 			BTstack_WinUsb_ReadIsochPipe;
149 static BTstack_WinUsb_ReadIsochPipeAsap_t 		BTstack_WinUsb_ReadIsochPipeAsap;
150 static BTstack_WinUsb_WriteIsochPipe_t 			BTstack_WinUsb_WriteIsochPipe;
151 static BTstack_WinUsb_WriteIsochPipeAsap_t 		BTstack_WinUsb_WriteIsochPipeAsap;
152 static BTstack_WinUsb_UnregisterIsochBuffer_t 	BTstack_WinUsb_UnregisterIsochBuffer;
153 static BTstack_WinUsb_GetCurrentFrameNumber_t   BTstack_WinUsb_GetCurrentFrameNumber;
154 #endif
155 
156 // Doesn't work as expected
157 // #define SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
158 
159 // Not tested yet
160 // #define SCHEDULE_SCO_OUT_TRANSFERS_MANUALLY
161 
162 //
163 // Bluetooth USB Transport Alternate Settings:
164 //
165 // 0: No active voice channels (for USB compliance)
166 // 1: One 8 kHz voice channel with 8-bit encoding
167 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
168 // 3: Three 8 kHz voice channels with 8-bit encoding
169 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
170 // 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
171 // --> support only a single SCO connection
172 #define ALT_SETTING (1)
173 
174 // alt setting for 1-3 connections and 8/16 bit
175 const int alt_setting_8_bit[]  = {1,2,3};
176 const int alt_setting_16_bit[] = {2,4,5};
177 
178 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
179 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
180 #define NUM_ISO_PACKETS (3)
181 
182 const uint16_t iso_packet_size_for_alt_setting[] = {
183     0,
184     9,
185     17,
186     25,
187     33,
188     49,
189     63,
190 };
191 
192 // 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)
193 // 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
194 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
195 
196 #define ISOC_BUFFERS   8
197 
198 // Outgoing SCO packet queue
199 // simplified ring buffer implementation
200 #define SCO_RING_BUFFER_COUNT  (20)
201 #define SCO_RING_BUFFER_SIZE (SCO_RING_BUFFER_COUNT * SCO_PACKET_SIZE)
202 
203 /** Request type bits of the "bmRequestType" field in control transfers. */
204 enum usb_request_type {
205 	USB_REQUEST_TYPE_STANDARD = (0x00 << 5),
206 	USB_REQUEST_TYPE_CLASS = (0x01 << 5),
207 	USB_REQUEST_TYPE_VENDOR = (0x02 << 5),
208 };
209 
210 /** Recipient bits of the "bmRequestType" field in control transfers. Values 4 through 31 are reserved. */
211 enum usb_request_recipient {
212 	USB_RECIPIENT_DEVICE = 0x00,
213 	USB_RECIPIENT_INTERFACE = 0x01,
214 	USB_RECIPIENT_ENDPOINT = 0x02,
215 	USB_RECIPIENT_OTHER = 0x03,
216 };
217 
218 // This is the GUID for the USB device class
219 static GUID GUID_DEVINTERFACE_USB_DEVICE =
220 { 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
221 
222 static void usb_dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
223 
224 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = &usb_dummy_handler;
225 
226 // endpoint addresses
227 static int event_in_addr;
228 static int acl_in_addr;
229 static int acl_out_addr;
230 static int sco_in_addr;
231 static int sco_out_addr;
232 
233 //
234 static HANDLE usb_device_handle;
235 static WINUSB_INTERFACE_HANDLE usb_interface_0_handle;
236 static WINUSB_INTERFACE_HANDLE usb_interface_1_handle;
237 static OVERLAPPED usb_overlapped_event_in;
238 static OVERLAPPED usb_overlapped_command_out;
239 static OVERLAPPED usb_overlapped_acl_in;
240 static OVERLAPPED usb_overlapped_acl_out;
241 static btstack_data_source_t usb_data_source_event_in;
242 static btstack_data_source_t usb_data_source_command_out;
243 static btstack_data_source_t usb_data_source_acl_in;
244 static btstack_data_source_t usb_data_source_acl_out;
245 
246 //
247 static int usb_command_out_active;
248 static int usb_acl_out_active;
249 
250 // buffer for HCI Events and ACL Packets
251 static uint8_t hci_event_in_buffer[2 + 255];
252 static uint8_t hci_acl_in_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
253 
254 
255 #ifdef ENABLE_SCO_OVER_HCI
256 
257 typedef enum {
258     H2_W4_SCO_HEADER = 1,
259     H2_W4_PAYLOAD,
260 } H2_SCO_STATE;
261 
262 // SCO Incoming Windows
263 static uint8_t hci_sco_in_buffer[ISOC_BUFFERS * SCO_PACKET_SIZE];
264 static BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE hci_sco_in_buffer_handle;
265 static USBD_ISO_PACKET_DESCRIPTOR hci_sco_packet_descriptors[ISOC_BUFFERS * NUM_ISO_PACKETS];
266 static OVERLAPPED usb_overlapped_sco_in[ISOC_BUFFERS];
267 static int usb_sco_in_expected_transfer;
268 
269 // SCO Incoming Run Loop
270 static btstack_data_source_t usb_data_source_sco_in[ISOC_BUFFERS];
271 
272 // SCO Incoming HCI
273 static H2_SCO_STATE sco_state;
274 static uint8_t  sco_buffer[SCO_PACKET_SIZE];
275 static uint16_t sco_read_pos;
276 static uint16_t sco_bytes_to_read;
277 
278 // SCO Outgoing Windows
279 static BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE hci_sco_out_buffer_handle;
280 static OVERLAPPED usb_overlapped_sco_out[SCO_RING_BUFFER_COUNT];
281 static int        sco_ring_transfers_active;
282 static int        usb_sco_out_expected_transfer;
283 
284 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
285 // next tranfer
286 static ULONG sco_next_transfer_at_frame;
287 #endif
288 
289 // SCO Outgoing Run Loop
290 static btstack_data_source_t usb_data_source_sco_out[SCO_RING_BUFFER_COUNT];
291 
292 // SCO Outgoing HCI
293 static uint8_t  sco_ring_buffer[SCO_RING_BUFFER_SIZE];
294 static int      sco_ring_write;  // packet idx
295 
296 // SCO Reconfiguration - pause/resume
297 static uint16_t sco_voice_setting;
298 static int      sco_num_connections;
299 static int      sco_shutdown;
300 
301 static uint16_t iso_packet_size;
302 #endif
303 
304 // list of known devices, using VendorID/ProductID tuples
305 static const uint16_t known_bluetooth_devices[] = {
306     // DeLOCK Bluetooth 4.0
307     0x0a5c, 0x21e8,
308     // Asus BT400
309     0x0b05, 0x17cb,
310     // BCM20702B0 (Generic USB Detuned Class 1 @ 20 MHz)
311     0x0a5c, 0x22be,
312 };
313 
314 static int num_known_devices = sizeof(known_bluetooth_devices) / sizeof(uint16_t) / 2;
315 
316 static int usb_is_known_bluetooth_device(const char * device_path){
317     int i;
318     for (i=0; i<num_known_devices; i++){
319         // construct pid/vid substring
320         char substring[20];
321         sprintf(substring, "vid_%04x&pid_%04x", known_bluetooth_devices[i*2], known_bluetooth_devices[i*2+1]);
322         const char * pos = strstr(device_path, substring);
323         log_info("check %s in %s -> %p", substring, device_path, pos);
324         if (pos){
325             return 1;
326         }
327     }
328     return 0;
329 }
330 
331 static int usb_is_vmware_bluetooth_adapter(const char * device_path){
332     // VMware Vendor ID 0e0f
333     const char * pos = strstr(device_path, "\\usb#vid_0e0f&pid");
334     return pos ? 1 : 0;
335 }
336 
337 #ifdef ENABLE_SCO_OVER_HCI
338 static void sco_ring_init(void){
339     sco_ring_write = 0;
340     sco_ring_transfers_active = 0;
341 }
342 static int sco_ring_have_space(void){
343     return sco_ring_transfers_active < SCO_RING_BUFFER_COUNT;
344 }
345 static void usb_sco_register_buffers(void){
346     BOOL result;
347     result = BTstack_WinUsb_RegisterIsochBuffer(usb_interface_1_handle, sco_in_addr, hci_sco_in_buffer, sizeof(hci_sco_in_buffer), &hci_sco_in_buffer_handle);
348     if (!result) {
349         log_error("usb_sco_register_buffers: register in buffer failed, error %lu", GetLastError());
350     }
351     log_info("hci_sco_in_buffer_handle %p", hci_sco_in_buffer_handle);
352 
353     result = BTstack_WinUsb_RegisterIsochBuffer(usb_interface_1_handle, sco_out_addr, sco_ring_buffer, sizeof(sco_ring_buffer), &hci_sco_out_buffer_handle);
354     if (!result) {
355         log_error("usb_sco_unregister_buffers: register out buffer failed, error %lu", GetLastError());
356     }
357     log_info("hci_sco_out_buffer_handle %p", hci_sco_out_buffer_handle);
358 }
359 static void usb_sco_unregister_buffers(void){
360     if (hci_sco_in_buffer_handle){
361         BTstack_WinUsb_UnregisterIsochBuffer(hci_sco_in_buffer_handle);
362         hci_sco_in_buffer_handle = NULL;
363     }
364     if (hci_sco_out_buffer_handle){
365         BTstack_WinUsb_UnregisterIsochBuffer(hci_sco_out_buffer_handle);
366         hci_sco_out_buffer_handle = NULL;
367     }
368 }
369 #endif
370 
371 static void usb_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
372     log_info("registering packet handler");
373     packet_handler = handler;
374 }
375 
376 static void usb_dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
377 }
378 
379 static void usb_init(const void *transport_config){
380 }
381 
382 static void usb_free_resources(void){
383 	if (usb_interface_1_handle){
384 		WinUsb_Free(usb_interface_1_handle);
385 		usb_interface_1_handle = NULL;
386 	}
387 
388 	if (usb_interface_0_handle){
389 		WinUsb_Free(usb_interface_0_handle);
390 		usb_interface_0_handle = NULL;
391 	}
392 
393 	if (usb_device_handle) {
394 		CloseHandle(usb_device_handle);
395 		usb_device_handle = NULL;
396 	}
397 
398 #ifdef ENABLE_SCO_OVER_HCI
399     usb_sco_unregister_buffers();
400 #endif
401 }
402 
403 static void usb_submit_event_in_transfer(void){
404 	// submit transfer
405 	BOOL result = WinUsb_ReadPipe(usb_interface_0_handle, event_in_addr, hci_event_in_buffer, sizeof(hci_event_in_buffer), NULL, &usb_overlapped_event_in);
406 	if (!result) {
407 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
408 	}
409 
410     // IO_PENDING -> wait for completed
411     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_event_in, DATA_SOURCE_CALLBACK_READ);
412     return;
413 
414 exit_on_error:
415 	log_error("usb_submit_event_in_transfer: winusb last error %lu", GetLastError());
416 }
417 
418 static void usb_submit_acl_in_transfer(void){
419 	// submit transfer
420 	BOOL result = WinUsb_ReadPipe(usb_interface_0_handle, acl_in_addr, hci_acl_in_buffer, sizeof(hci_acl_in_buffer), NULL, &usb_overlapped_acl_in);
421 	if (!result) {
422 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
423 	}
424 
425     // IO_PENDING -> wait for completed
426     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_acl_in, DATA_SOURCE_CALLBACK_READ);
427     return;
428 
429 exit_on_error:
430 	log_error("usb_submit_acl_in_transfer: winusb last error %lu", GetLastError());
431 }
432 
433 #ifdef ENABLE_SCO_OVER_HCI
434 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
435 
436 // frame number gets updated
437 static void usb_submit_sco_in_transfer_at_frame(int i, ULONG * frame_number){
438 
439     if (sco_shutdown){
440         log_info("USB SCO Shutdown:: usb_submit_sco_in_transfer_at_frame called");
441         return;
442     }
443 
444     LARGE_INTEGER timestamp;
445     ULONG current_frame_number;
446     WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
447 
448     ULONG frame_before = *frame_number;
449 
450     BOOL result = BTstack_WinUsb_ReadIsochPipe(hci_sco_in_buffer_handle, i * SCO_PACKET_SIZE, iso_packet_size * NUM_ISO_PACKETS,
451         frame_number, NUM_ISO_PACKETS, &hci_sco_packet_descriptors[i * NUM_ISO_PACKETS], &usb_overlapped_sco_in[i]);
452 
453     // log_info("BTstack_WinUsb_ReadIsochPipe #%02u: current %lu, planned %lu - buffer %lu", i, current_frame_number, frame_before, frame_before - current_frame_number);
454 
455     if (!result) {
456         if (GetLastError() == ERROR_IO_PENDING) {
457         } else {
458             goto exit_on_error;
459         }
460     }
461 
462     return;
463 
464 exit_on_error:
465     log_error("usb_submit_sco_in_transfer: winusb last error %lu", GetLastError());
466 }
467 
468 #else
469 
470 static void usb_submit_sco_in_transfer_asap(int i, int continue_stream){
471 
472     if (sco_shutdown){
473         log_info("USB SCO Shutdown:: usb_submit_sco_in_transfer_at_frame called");
474         return;
475     }
476 
477     LARGE_INTEGER timestamp;
478     ULONG current_frame_number;
479     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
480 
481     // log_info("usb_submit_sco_in_transfer[%02u]: current frame %lu", i, current_frame_number);
482 
483     BOOL result = BTstack_WinUsb_ReadIsochPipeAsap(hci_sco_in_buffer_handle, i * SCO_PACKET_SIZE, iso_packet_size * NUM_ISO_PACKETS,
484         continue_stream, NUM_ISO_PACKETS, &hci_sco_packet_descriptors[i * NUM_ISO_PACKETS], &usb_overlapped_sco_in[i]);
485 
486     if (!result) {
487         if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
488     }
489 
490     return;
491 
492 exit_on_error:
493     log_error("usb_submit_sco_in_transfer: winusb last error %lu", GetLastError());
494 }
495 #endif
496 #endif
497 
498 static void usb_process_event_in(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
499 
500     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
501 
502     DWORD bytes_read;
503     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_event_in, &bytes_read, FALSE);
504     if(!ok){
505         DWORD err = GetLastError();
506         if (err == ERROR_IO_INCOMPLETE){
507             // IO_INCOMPLETE -> wait for completed
508             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
509         } else {
510             log_error("usb_process_event_in: error reading");
511         }
512         return;
513     }
514 
515     // notify uppper
516     packet_handler(HCI_EVENT_PACKET, hci_event_in_buffer, bytes_read);
517 
518 	// re-submit transfer
519 	usb_submit_event_in_transfer();
520 }
521 
522 static void usb_process_acl_in(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
523 
524     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
525 
526     DWORD bytes_read;
527     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_acl_in, &bytes_read, FALSE);
528     if(!ok){
529         DWORD err = GetLastError();
530         if (err == ERROR_IO_INCOMPLETE){
531             // IO_INCOMPLETE -> wait for completed
532             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
533         } else {
534             log_error("usb_process_acl_in: error reading");
535 
536             // Reset Pipe
537             err = WinUsb_ResetPipe(usb_interface_0_handle, acl_in_addr);
538             log_info("WinUsb_ResetPipe: result %u", err);
539             if (err){
540                 log_info("WinUsb_ResetPipe error %u", GetLastError());
541             }
542 
543             // re-submit transfer
544             usb_submit_acl_in_transfer();
545         }
546         return;
547     }
548 
549     // notify uppper
550     packet_handler(HCI_ACL_DATA_PACKET, hci_acl_in_buffer, bytes_read);
551 
552 	// re-submit transfer
553 	usb_submit_acl_in_transfer();
554 }
555 
556 #ifdef ENABLE_SCO_OVER_HCI
557 static void sco_state_machine_init(void){
558     sco_state = H2_W4_SCO_HEADER;
559     sco_read_pos = 0;
560     sco_bytes_to_read = 3;
561 }
562 
563 static void sco_handle_data(uint8_t * buffer, uint16_t size){
564 	// printf("sco_handle_data: state %u, pos %u, to read %u, size %u", sco_state, sco_read_pos, sco_bytes_to_read, size);
565     while (size){
566         if (size < sco_bytes_to_read){
567             // just store incomplete data
568             memcpy(&sco_buffer[sco_read_pos], buffer, size);
569             sco_read_pos      += size;
570             sco_bytes_to_read -= size;
571             return;
572         }
573         // copy requested data
574         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
575         sco_read_pos += sco_bytes_to_read;
576         buffer       += sco_bytes_to_read;
577         size         -= sco_bytes_to_read;
578 
579         // chunk read successfully, next action
580         switch (sco_state){
581             case H2_W4_SCO_HEADER:
582                 sco_state = H2_W4_PAYLOAD;
583                 sco_bytes_to_read = sco_buffer[2];
584                 if (sco_bytes_to_read > (sizeof(sco_buffer)-3)){
585                 	log_error("sco_handle_data: sco packet len > packet size");
586 	                sco_state_machine_init();
587                 }
588                 break;
589             case H2_W4_PAYLOAD:
590                 // packet complete
591                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
592                 sco_state_machine_init();
593                 break;
594         }
595     }
596 }
597 
598 static void usb_process_sco_out(btstack_data_source_t *ds,  btstack_data_source_callback_type_t callback_type){
599 
600     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
601 
602     if (sco_shutdown){
603         log_info("USB SCO Shutdown:: usb_process_sco_out called");
604         return;
605     }
606 
607     // get current frame number
608     ULONG current_frame_number;
609     LARGE_INTEGER timestamp;
610     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
611 
612     // find index
613     int transfer_index;
614     for (transfer_index=0;transfer_index<SCO_RING_BUFFER_COUNT;transfer_index++){
615         if (ds == &usb_data_source_sco_out[transfer_index]) break;
616     }
617 
618     // log_info("usb_process_sco_out[%02u] -- current frame %lu", transfer_index, current_frame_number);
619 
620     DWORD bytes_transferred;
621     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_sco_out[transfer_index], &bytes_transferred, FALSE);
622     // log_info("usb_process_sco_out_done: #%u result %u, bytes %u, state %u", transfer_index, ok, (int) bytes_transferred, sco_state);
623     if(!ok){
624         DWORD err = GetLastError();
625         if (err == ERROR_IO_INCOMPLETE){
626             // IO_INCOMPLETE -> wait for completed
627             btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
628             return;
629         }
630         log_error("usb_process_sco_out_done[%02u]: error writing %u, Internal %x", transfer_index, (int) err, (int) usb_overlapped_sco_out[transfer_index].Internal);
631     }
632 
633     // decrease tab
634     sco_ring_transfers_active--;
635 
636     // enable next data source callback
637     if (sco_ring_transfers_active){
638         // update expected and wait for completion
639         usb_sco_out_expected_transfer = (transfer_index+ 1) % SCO_RING_BUFFER_COUNT;
640         // log_info("usb_process_sco_out_done[%02u]: wait for transfer %02u", transfer_index, usb_sco_out_expected_transfer);
641         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[usb_sco_out_expected_transfer], DATA_SOURCE_CALLBACK_WRITE);
642     }
643 
644     // log_info("usb_process_sco_out_done: transfers active %u", sco_ring_transfers_active);
645 
646     // mark free
647     if (sco_ring_have_space()) {
648         uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
649         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
650     }
651 }
652 
653 static void usb_process_sco_in(btstack_data_source_t *ds,  btstack_data_source_callback_type_t callback_type){
654 
655     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
656 
657     if (sco_shutdown){
658         log_info("USB SCO Shutdown: usb_process_sco_out called");
659         return;
660     }
661 
662     // find index
663     int i;
664     for (i=0;i<ISOC_BUFFERS;i++){
665         if (ds == &usb_data_source_sco_in[i]) break;
666     }
667     int transfer_index = i;
668 
669     // ULONG current_frame_number;
670     // LARGE_INTEGER timestamp;
671     // BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
672 
673     // log_info("usb_process_sco_in[%02u] -- current frame %lu", transfer_index, current_frame_number);
674 
675     DWORD bytes_transferred;
676     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_sco_in[transfer_index], &bytes_transferred, FALSE);
677 
678     if(!ok) {
679         DWORD err = GetLastError();
680         if (err == ERROR_IO_INCOMPLETE) {
681             // IO_INCOMPLETE -> wait for completed
682             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
683             return;
684         }
685         log_error("usb_process_sco_in[%02u]: error reading %u, Internal %x", transfer_index, (int) err, (int) usb_overlapped_sco_out[i].Internal);
686     }
687 
688     if (ok){
689         for (i=0;i<NUM_ISO_PACKETS;i++){
690             USBD_ISO_PACKET_DESCRIPTOR * packet_descriptor = &hci_sco_packet_descriptors[transfer_index * NUM_ISO_PACKETS + i];
691             if (packet_descriptor->Length){
692                 uint8_t * iso_data = &hci_sco_in_buffer[transfer_index * SCO_PACKET_SIZE + packet_descriptor->Offset];
693                 uint16_t  iso_len  = packet_descriptor->Length;
694                 sco_handle_data(iso_data, iso_len);
695             }
696         }
697     }
698 
699 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
700     usb_submit_sco_in_transfer_at_frame(i, &sco_next_transfer_at_frame);
701 #else
702     usb_submit_sco_in_transfer_asap(transfer_index, 1);
703 #endif
704     // update expected and wait for completion
705     usb_sco_in_expected_transfer = (transfer_index+ 1) % ISOC_BUFFERS;
706 
707     // log_info("usb_process_sco_in[%02u]: enable data source %02u", transfer_index, usb_sco_in_expected_transfer);
708     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_in[usb_sco_in_expected_transfer], DATA_SOURCE_CALLBACK_READ);
709 }
710 #endif
711 
712 static void usb_process_command_out(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
713 
714     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
715 
716     // update stata before submitting transfer
717     usb_command_out_active = 0;
718 
719     // notify upper stack that provided buffer can be used again
720     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
721     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
722 }
723 
724 static void usb_process_acl_out(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
725 
726     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
727 
728     // update stata before submitting transfer
729     usb_acl_out_active = 0;
730 
731     // notify upper stack that provided buffer can be used again
732     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
733     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
734 }
735 
736 static BOOL usb_scan_for_bluetooth_endpoints(void) {
737     int i;
738     USB_INTERFACE_DESCRIPTOR usb_interface_descriptor;
739 
740     // reset
741     event_in_addr = 0;
742     acl_in_addr = 0;
743     acl_out_addr = 0;
744 
745     log_info("Scanning USB Entpoints:");
746 
747     // look for Event and ACL pipes on Interface #0
748     BOOL result = WinUsb_QueryInterfaceSettings(usb_interface_0_handle, 0, &usb_interface_descriptor);
749     if (!result) goto exit_on_error;
750     for (i=0;i<usb_interface_descriptor.bNumEndpoints;i++){
751         WINUSB_PIPE_INFORMATION pipe;
752         result = WinUsb_QueryPipe(
753                      usb_interface_0_handle,
754                      0,
755                      (UCHAR) i,
756                      &pipe);
757         if (!result) goto exit_on_error;
758         log_info("Interface #0, Alt #0, Pipe idx #%u: type %u, id 0x%02x, max packet size %u,",
759             i, pipe.PipeType, pipe.PipeId, pipe.MaximumPacketSize);
760         switch (pipe.PipeType){
761             case USB_ENDPOINT_TYPE_INTERRUPT:
762                 if (event_in_addr) continue;
763                 event_in_addr = pipe.PipeId;
764                 log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
765                 break;
766             case USB_ENDPOINT_TYPE_BULK:
767                 if (pipe.PipeId & 0x80) {
768                     if (acl_in_addr) continue;
769                     acl_in_addr = pipe.PipeId;
770                     log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
771                 } else {
772                     if (acl_out_addr) continue;
773                     acl_out_addr = pipe.PipeId;
774                     log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
775                 }
776                 break;
777             default:
778                 break;
779         }
780     }
781 
782 #ifdef ENABLE_SCO_OVER_HCI
783     sco_out_addr = 0;
784     sco_in_addr = 0;
785 
786     // look for SCO pipes on Interface #1, Alt Setting 1
787     int alt_setting = 1;
788     result = WinUsb_QueryInterfaceSettings(usb_interface_1_handle, alt_setting, &usb_interface_descriptor);
789     if (!result) goto exit_on_error;
790     for (i=0;i<usb_interface_descriptor.bNumEndpoints;i++){
791         BTSTACK_WINUSB_PIPE_INFORMATION_EX pipe;
792         result = BTstack_WinUsb_QueryPipeEx(
793                      usb_interface_1_handle,
794                      alt_setting,
795                      (UCHAR) i,
796                      &pipe);
797         if (!result) goto exit_on_error;
798         log_info("Interface #1, Alt #%u, Pipe idx #%u: type %u, id 0x%02x, max packet size %u, interval %u, max bytes per interval %u",
799             alt_setting, i, pipe.PipeType, pipe.PipeId, pipe.MaximumPacketSize, pipe.Interval, (int) pipe.MaximumBytesPerInterval);
800         switch (pipe.PipeType){
801             case USB_ENDPOINT_TYPE_ISOCHRONOUS:
802                 if (pipe.PipeId & 0x80) {
803                     if (sco_in_addr) continue;
804                     sco_in_addr = pipe.PipeId;
805                     log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
806                 } else {
807                     if (sco_out_addr) continue;
808                     sco_out_addr = pipe.PipeId;
809                     log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
810                 }
811                 break;
812             default:
813                 break;
814         }
815     }
816     if (!sco_in_addr){
817         log_error("Couldn't find pipe for SCO IN!");
818         return FALSE;
819     }
820     if (!sco_out_addr){
821         log_error("Couldn't find pipe for SCO IN!");
822         return FALSE;
823     }
824 #endif
825 
826     // check if all found
827     if (!event_in_addr){
828         log_error("Couldn't find pipe for Event IN!");
829         return FALSE;
830     }
831     if (!acl_in_addr){
832         log_error("Couldn't find pipe for ACL IN!");
833         return FALSE;
834     }
835     if (!acl_out_addr){
836         log_error("Couldn't find pipe for ACL OUT!");
837         return FALSE;
838     }
839 
840     // all clear
841     return TRUE;
842 
843 exit_on_error:
844     log_error("usb_scan_for_bluetooth_endpoints: last error %lu", GetLastError());
845     return FALSE;
846 }
847 
848 #ifdef ENABLE_SCO_OVER_HCI
849 
850 static int usb_sco_start(void){
851     printf("usb_sco_start\n");
852     log_info("usb_sco_start");
853 
854     sco_shutdown = 0;
855 
856     sco_state_machine_init();
857     sco_ring_init();
858 
859     // calc alt setting
860     int alt_setting;
861     if (sco_voice_setting & 0x0020){
862         // 16-bit PCM
863         alt_setting = alt_setting_16_bit[sco_num_connections-1];
864     } else {
865         // 8-bit PCM or mSBC
866         alt_setting = alt_setting_8_bit[sco_num_connections-1];
867     }
868 
869     log_info("Switching to setting %u on interface 1..", alt_setting);
870     // WinUsb_SetCurrentAlternateSetting returns TRUE if the operation succeeds.
871     BOOL result = WinUsb_SetCurrentAlternateSetting(usb_interface_1_handle, alt_setting);
872     if (!result) goto exit_on_error;
873 
874     // derive iso packet size from alt setting
875     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
876 
877     // register isochronous buffer after setting alternate setting
878     usb_sco_register_buffers();
879 
880 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
881     // get current frame number
882     ULONG current_frame_number;
883     LARGE_INTEGER timestamp;
884     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
885     // plan for next tranfer
886     sco_next_transfer_at_frame = current_frame_number + ISOC_BUFFERS * NUM_ISO_PACKETS;
887 #endif
888 
889     int i;
890     for (i=0;i<ISOC_BUFFERS;i++){
891 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
892         usb_submit_sco_in_transfer_at_frame(i, &sco_next_transfer_at_frame);
893 #else
894         usb_submit_sco_in_transfer_asap(i, 0);
895 #endif
896     }
897 
898     usb_sco_in_expected_transfer = 0;
899 
900     // only await first transfer to return
901     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_in[usb_sco_in_expected_transfer], DATA_SOURCE_CALLBACK_READ);
902     return 1;
903 
904 exit_on_error:
905     log_error("usb_sco_start: last error %lu", GetLastError());
906     usb_free_resources();
907     return 0;
908 }
909 
910 static void usb_sco_stop(void){
911     printf("usb_sco_stop\n");
912     log_info("usb_sco_stop");
913 
914     sco_shutdown = 1;
915 
916     // abort SCO transfers
917     WinUsb_AbortPipe(usb_interface_0_handle, sco_in_addr);
918     WinUsb_AbortPipe(usb_interface_0_handle, sco_out_addr);
919 
920     // unlock/free SCO buffers
921     usb_sco_unregister_buffers();
922 
923     int alt_setting = 0;
924     log_info("Switching to setting %u on interface 1..", alt_setting);
925     // WinUsb_SetCurrentAlternateSetting returns TRUE if the operation succeeds.
926     WinUsb_SetCurrentAlternateSetting(usb_interface_1_handle, alt_setting);
927 }
928 #endif
929 
930 // returns 0 if successful, -1 otherwise
931 static int usb_try_open_device(const char * device_path){
932 
933 	// open file
934 	usb_device_handle = CreateFile(device_path,
935 		GENERIC_WRITE | GENERIC_READ,
936         FILE_SHARE_WRITE | FILE_SHARE_READ,
937         NULL,
938         OPEN_EXISTING,
939         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
940         NULL);
941 	log_info("Opening USB device: %p", usb_device_handle);
942 	if (!usb_device_handle) goto exit_on_error;
943 
944 	// WinUsb_Initialize returns TRUE if the operation succeed
945 	BOOL result = WinUsb_Initialize(usb_device_handle, &usb_interface_0_handle);
946 	if (!result) goto exit_on_error;
947 
948     // Detect USB Dongle based Class, Subclass, and Protocol
949     // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
950     // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
951     // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
952     USB_INTERFACE_DESCRIPTOR usb_interface_descriptor;
953     result = WinUsb_QueryInterfaceSettings(usb_interface_0_handle, 0, &usb_interface_descriptor);
954     if (!result) goto exit_on_error;
955 
956     // ignore virtual Bluetooth adapter of VMware
957     if (usb_is_vmware_bluetooth_adapter(device_path)) {
958         log_info("Ignoring simulated VMware Bluetooth adapter");
959         usb_free_resources();
960         return -1;
961     }
962 
963     //
964     if (usb_interface_descriptor.bInterfaceClass    != 0xe0 ||
965         usb_interface_descriptor.bInterfaceSubClass != 0x01 ||
966         usb_interface_descriptor.bInterfaceProtocol != 0x01){
967 
968         // check whitelist
969         if (!usb_is_known_bluetooth_device(device_path)){
970             log_info("Class, Subclass, Protocol does not match Bluetooth device");
971             usb_free_resources();
972             return 0;
973         }
974     }
975 
976 #ifdef ENABLE_SCO_OVER_HCI
977 	log_info("Claiming interface 1...");
978 	// WinUsb_GetAssociatedInterface returns TRUE if the operation succeeds.
979 	// We use index 1 - assuming it refers to interface #1 with libusb
980 	// A value of 0 indicates the first associated interface, a value of 1 indicates the second associated interface, and so on.
981 	result = WinUsb_GetAssociatedInterface(usb_interface_0_handle, 0, &usb_interface_1_handle);
982 	if (!result) goto exit_on_error;
983 	log_info("Claiming interface 1: success");
984 #endif
985 
986     result = usb_scan_for_bluetooth_endpoints();
987     if (!result) {
988         log_error("Could not find all Bluetooth Endpoints!");
989         usb_free_resources();
990         return 0;
991     }
992 
993 #ifdef ENABLE_SCO_OVER_HCI
994     int i;
995 
996 	memset(hci_sco_packet_descriptors, 0, sizeof(hci_sco_packet_descriptors));
997 	log_info("Size of packet descriptors for SCO IN%u", (int) sizeof(hci_sco_packet_descriptors));
998 
999 	// setup async io && btstack handler
1000 	memset(&usb_overlapped_sco_in, 0, sizeof(usb_overlapped_sco_in));
1001 	for (i=0;i<ISOC_BUFFERS;i++){
1002 		usb_overlapped_sco_in[i].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1003 		// log_info_hexdump(&usb_overlapped_sco_in[i], sizeof(OVERLAPPED));
1004         // log_info("data source SCO in %u, handle %p", i, usb_overlapped_sco_in[i].hEvent);
1005 		usb_data_source_sco_in[i].source.handle = usb_overlapped_sco_in[i].hEvent;
1006 	    btstack_run_loop_set_data_source_handler(&usb_data_source_sco_in[i], &usb_process_sco_in);
1007         btstack_run_loop_add_data_source(&usb_data_source_sco_in[i]);
1008 	}
1009 
1010     memset(&usb_overlapped_sco_out, 0, sizeof(usb_overlapped_sco_out));
1011     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1012         usb_overlapped_sco_out[i].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1013         // log_info("data source SCO out %u, handle %p", i, usb_overlapped_sco_out[i].hEvent);
1014         usb_data_source_sco_out[i].source.handle = usb_overlapped_sco_out[i].hEvent;
1015         btstack_run_loop_set_data_source_handler(&usb_data_source_sco_out[i], &usb_process_sco_out);
1016         btstack_run_loop_add_data_source(&usb_data_source_sco_out[i]);
1017     }
1018 #endif
1019 
1020 	// setup async io
1021     memset(&usb_overlapped_event_in,     0, sizeof(usb_overlapped_event_in));
1022     memset(&usb_overlapped_command_out,  0, sizeof(usb_overlapped_command_out));
1023     memset(&usb_overlapped_acl_out,      0, sizeof(usb_overlapped_acl_out));
1024     memset(&usb_overlapped_acl_in,       0, sizeof(usb_overlapped_acl_in));
1025     usb_overlapped_event_in.hEvent    = CreateEvent(NULL, TRUE, FALSE, NULL);
1026     usb_overlapped_command_out.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1027     usb_overlapped_acl_in.hEvent      = CreateEvent(NULL, TRUE, FALSE, NULL);
1028     usb_overlapped_acl_out.hEvent     = CreateEvent(NULL, TRUE, FALSE, NULL);
1029 
1030 	// setup btstack data soures
1031     usb_data_source_event_in.source.handle = usb_overlapped_event_in.hEvent;
1032     btstack_run_loop_set_data_source_handler(&usb_data_source_event_in, &usb_process_event_in);
1033     btstack_run_loop_add_data_source(&usb_data_source_event_in);
1034 
1035     usb_data_source_command_out.source.handle = usb_overlapped_command_out.hEvent;
1036     btstack_run_loop_set_data_source_handler(&usb_data_source_command_out, &usb_process_command_out);
1037     btstack_run_loop_add_data_source(&usb_data_source_command_out);
1038 
1039     usb_data_source_acl_in.source.handle = usb_overlapped_acl_in.hEvent;
1040     btstack_run_loop_set_data_source_handler(&usb_data_source_acl_in, &usb_process_acl_in);
1041     btstack_run_loop_add_data_source(&usb_data_source_acl_in);
1042 
1043     usb_data_source_acl_out.source.handle = usb_overlapped_acl_out.hEvent;
1044     btstack_run_loop_set_data_source_handler(&usb_data_source_acl_out, &usb_process_acl_out);
1045     btstack_run_loop_add_data_source(&usb_data_source_acl_out);
1046 
1047     // submit all incoming transfers
1048     usb_submit_event_in_transfer();
1049     usb_submit_acl_in_transfer();
1050 	return 1;
1051 
1052 exit_on_error:
1053 	log_error("usb_try_open_device: last error %lu", GetLastError());
1054 	usb_free_resources();
1055 	return 0;
1056 }
1057 
1058 #ifdef ENABLE_SCO_OVER_HCI
1059 
1060 #define WinUSB_Lookup(fn) do { BTstack_##fn = (BTstack_##fn##_t) GetProcAddress(h, #fn); log_info("%-30s %p", #fn, BTstack_##fn); if (!BTstack_##fn) return FALSE; } while(0)
1061 
1062 static BOOL usb_lookup_symbols(void){
1063 	// lookup runtime symbols missing in current mingw64 distribution
1064 	HMODULE h = GetModuleHandleA("WinUSB");
1065 	log_info("%-30s %p", "WinUSB", h);
1066 	WinUSB_Lookup(WinUsb_QueryPipeEx);
1067 	WinUSB_Lookup(WinUsb_RegisterIsochBuffer);
1068 	WinUSB_Lookup(WinUsb_ReadIsochPipe);
1069 	WinUSB_Lookup(WinUsb_ReadIsochPipeAsap);
1070 	WinUSB_Lookup(WinUsb_WriteIsochPipe);
1071 	WinUSB_Lookup(WinUsb_WriteIsochPipeAsap);
1072 	WinUSB_Lookup(WinUsb_UnregisterIsochBuffer);
1073     WinUSB_Lookup(WinUsb_GetCurrentFrameNumber);
1074     return TRUE;
1075 }
1076 #endif
1077 
1078 // returns 0 on success, -1 otherwise
1079 static int usb_open(void){
1080 
1081     int r = -1;
1082 
1083 #ifdef ENABLE_SCO_OVER_HCI
1084 	BOOL ok = usb_lookup_symbols();
1085     if (!ok){
1086         log_error("usb_open: Failed to lookup WinSUB ISOCHRONOUS functions. Please disable ENABLE_SCO_OVER_HCI or use Windows 8.1 or higher");
1087         return r;
1088     }
1089     sco_state_machine_init();
1090     sco_ring_init();
1091 #endif
1092 
1093 	HDEVINFO                         hDevInfo;
1094 	SP_DEVICE_INTERFACE_DATA         DevIntfData;
1095 	PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
1096 	SP_DEVINFO_DATA                  DevData;
1097 
1098 	DWORD dwSize;
1099 	DWORD dwMemberIdx;
1100 
1101     // default endpoint addresses
1102     event_in_addr = 0x81; // EP1, IN interrupt
1103     acl_in_addr =   0x82; // EP2, IN bulk
1104     acl_out_addr =  0x02; // EP2, OUT bulk
1105     sco_in_addr  =  0x83; // EP3, IN isochronous
1106     sco_out_addr =  0x03; // EP3, OUT isochronous
1107 
1108 	// We will try to get device information set for all USB devices that have a
1109 	// device interface and are currently present on the system (plugged in).
1110 	hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
1111 
1112 	log_info("usb_open: SetupDiGetClassDevs -> %p", hDevInfo);
1113 	if (hDevInfo == INVALID_HANDLE_VALUE) return -1;
1114 
1115 	// Prepare to enumerate all device interfaces for the device information
1116 	// set that we retrieved with SetupDiGetClassDevs(..)
1117 	DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
1118 	dwMemberIdx = 0;
1119 
1120 	// Next, we will keep calling this SetupDiEnumDeviceInterfaces(..) until this
1121 	// function causes GetLastError() to return  ERROR_NO_MORE_ITEMS. With each
1122 	// call the dwMemberIdx value needs to be incremented to retrieve the next
1123 	// device interface information.
1124 
1125 	SetupDiEnumDeviceInterfaces(hDevInfo, NULL, (LPGUID) &GUID_DEVINTERFACE_USB_DEVICE,
1126 		dwMemberIdx, &DevIntfData);
1127 
1128 	while(GetLastError() != ERROR_NO_MORE_ITEMS){
1129 
1130 		// As a last step we will need to get some more details for each
1131 		// of device interface information we are able to retrieve. This
1132 		// device interface detail gives us the information we need to identify
1133 		// the device (VID/PID), and decide if it's useful to us. It will also
1134 		// provide a DEVINFO_DATA structure which we can use to know the serial
1135 		// port name for a virtual com port.
1136 
1137 		DevData.cbSize = sizeof(DevData);
1138 
1139 		// Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with
1140 		// a NULL DevIntfDetailData pointer, a DevIntfDetailDataSize
1141 		// of zero, and a valid RequiredSize variable. In response to such a call,
1142 		// this function returns the required buffer size at dwSize.
1143 
1144 		SetupDiGetDeviceInterfaceDetail(
1145 			  hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
1146 
1147 		// Allocate memory for the DeviceInterfaceDetail struct. Don't forget to
1148 		// deallocate it later!
1149 		DevIntfDetailData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
1150 		DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
1151 
1152 		if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData,
1153 			DevIntfDetailData, dwSize, &dwSize, &DevData))
1154 		{
1155 			// Finally we can start checking if we've found a useable device,
1156 			// by inspecting the DevIntfDetailData->DevicePath variable.
1157 			// The DevicePath looks something like this:
1158 			//
1159 			// \\?\usb#vid_04d8&pid_0033#5&19f2438f&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
1160 			//
1161 
1162 			log_info("usb_open: Device Path: %s", DevIntfDetailData->DevicePath);
1163 
1164 #if 0
1165             // check for hard-coded vendor/product ids
1166 			char vid_pid_match[30];
1167 			uint16_t vid = 0x0a12;
1168 			uint16_t pid = 0x0001;
1169 			sprintf(vid_pid_match, "\\\\?\\usb#vid_%04x&pid_%04x", vid, pid);
1170 			if (strncmp(DevIntfDetailData->DevicePath, &vid_pid_match[0], strlen(vid_pid_match)) == 0 ){
1171 				log_info("Matched search string %s", vid_pid_match);
1172 
1173 				BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1174 				if (result){
1175 					log_info("usb_open: Device opened, stop scanning");
1176 					r = 0;
1177 				} else {
1178 					log_error("usb_open: Device open failed");
1179 				}
1180 			}
1181 #endif
1182 
1183             // try all devices
1184             BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1185             if (result){
1186                 log_info("usb_open: Device opened, stop scanning");
1187                 r = 0;
1188             } else {
1189                 log_error("usb_open: Device open failed");
1190             }
1191         }
1192 		HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
1193 
1194 		if (r == 0) break;
1195 
1196 		// Continue looping
1197 		SetupDiEnumDeviceInterfaces(
1198 			hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, ++dwMemberIdx, &DevIntfData);
1199 	}
1200 
1201 	SetupDiDestroyDeviceInfoList(hDevInfo);
1202 
1203 	log_info("usb_open: done");
1204 
1205     return r;
1206 }
1207 
1208 static int usb_close(void){
1209 
1210     // remove data sources
1211     btstack_run_loop_remove_data_source(&usb_data_source_command_out);
1212     btstack_run_loop_remove_data_source(&usb_data_source_event_in);
1213     btstack_run_loop_remove_data_source(&usb_data_source_acl_in);
1214     btstack_run_loop_remove_data_source(&usb_data_source_acl_out);
1215 
1216 #ifdef ENABLE_SCO_OVER_HCI
1217     int i;
1218     for (i=0;i<ISOC_BUFFERS;i++){
1219         btstack_run_loop_remove_data_source(&usb_data_source_sco_in[i]);
1220     }
1221     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1222         btstack_run_loop_remove_data_source(&usb_data_source_sco_out[i]);
1223     }
1224 #endif
1225 
1226     log_info("usb_close abort event and acl pipes");
1227 
1228     // stop transfers
1229     WinUsb_AbortPipe(usb_interface_0_handle, event_in_addr);
1230     WinUsb_AbortPipe(usb_interface_0_handle, acl_in_addr);
1231     WinUsb_AbortPipe(usb_interface_0_handle, acl_out_addr);
1232 #ifdef ENABLE_SCO_OVER_HCI
1233     usb_sco_stop();
1234 #endif
1235     usb_acl_out_active = 0;
1236 
1237     // control transfer cannot be stopped, just wait for completion
1238     if (usb_command_out_active){
1239         log_info("usb_close command out active, wait for complete");
1240         DWORD bytes_transferred;
1241         WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_command_out, &bytes_transferred, TRUE);
1242         usb_command_out_active = 0;
1243     }
1244 
1245     log_info("usb_close free resources");
1246 
1247     // free everything
1248     usb_free_resources();
1249     return 0;
1250 }
1251 
1252 static int usb_can_send_packet_now(uint8_t packet_type){
1253     // return 0;
1254     switch (packet_type){
1255         case HCI_COMMAND_DATA_PACKET:
1256             return !usb_command_out_active;
1257         case HCI_ACL_DATA_PACKET:
1258             return !usb_acl_out_active;
1259 #ifdef ENABLE_SCO_OVER_HCI
1260         case HCI_SCO_DATA_PACKET:
1261             // return 0;
1262             return sco_ring_have_space();
1263 #endif
1264         default:
1265             return 0;
1266     }
1267 }
1268 
1269 static int usb_send_cmd_packet(uint8_t *packet, int size){
1270 
1271     // update stata before submitting transfer
1272     usb_command_out_active = 1;
1273 
1274 	// Start trasnsfer
1275 	WINUSB_SETUP_PACKET setup_packet;
1276 	memset(&setup_packet, 0, sizeof(setup_packet));
1277 	setup_packet.RequestType =  USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE;
1278 	setup_packet.Length = sizeof(size);
1279 	BOOL result = WinUsb_ControlTransfer(usb_interface_0_handle, setup_packet, packet, size,  NULL, &usb_overlapped_command_out);
1280 	if (!result) {
1281 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1282 	}
1283 
1284     // IO_PENDING -> wait for completed
1285     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_command_out, DATA_SOURCE_CALLBACK_WRITE);
1286 
1287     return 0;
1288 
1289 exit_on_error:
1290 	log_error("winusb: last error %lu", GetLastError());
1291 	return -1;
1292 }
1293 
1294 static int usb_send_acl_packet(uint8_t *packet, int size){
1295 
1296     // update stata before submitting transfer
1297     usb_acl_out_active = 1;
1298 
1299 	// Start trasnsfer
1300 	BOOL ok = WinUsb_WritePipe(usb_interface_0_handle, acl_out_addr, packet, size,  NULL, &usb_overlapped_acl_out);
1301 	if (!ok) {
1302 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1303 	}
1304 
1305     // IO_PENDING -> wait for completed
1306     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_acl_out, DATA_SOURCE_CALLBACK_WRITE);
1307     return 0;
1308 
1309 exit_on_error:
1310 	log_error("winusb: last error %lu", GetLastError());
1311 	return -1;
1312 }
1313 
1314 #ifdef ENABLE_SCO_OVER_HCI
1315 static int usb_send_sco_packet(uint8_t *packet, int size){
1316 
1317     if (size > SCO_PACKET_SIZE){
1318         log_error("usb_send_sco_packet: size %u > SCO_PACKET_SIZE %u", size, SCO_PACKET_SIZE);
1319         return -1;
1320     }
1321 
1322     // get current frame number
1323     ULONG current_frame_number;
1324     LARGE_INTEGER timestamp;
1325     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
1326 
1327     // store packet in free slot
1328     int transfer_index = sco_ring_write;
1329     uint8_t * data = &sco_ring_buffer[transfer_index * SCO_PACKET_SIZE];
1330     memcpy(data, packet, size);
1331 
1332 
1333     // setup transfer
1334     int continue_stream = sco_ring_transfers_active > 0;
1335     BOOL ok = BTstack_WinUsb_WriteIsochPipeAsap(hci_sco_out_buffer_handle, transfer_index * SCO_PACKET_SIZE, size, continue_stream, &usb_overlapped_sco_out[transfer_index]);
1336     // log_info("usb_send_sco_packet: using slot #%02u, current frame %lu, continue stream %u, ok %u", transfer_index, current_frame_number, continue_stream, ok);
1337     if (!ok) {
1338         if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1339     }
1340 
1341     // successful started transfer, enable data source callback if first active transfer
1342     if (sco_ring_transfers_active == 0){
1343         usb_sco_out_expected_transfer = transfer_index;
1344         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
1345     }
1346 
1347     // mark slot as full
1348     sco_ring_write = (sco_ring_write + 1) % SCO_RING_BUFFER_COUNT;
1349     sco_ring_transfers_active++;
1350 
1351     // notify upper stack that provided buffer can be used again
1352     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
1353     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
1354 
1355     // log_info("usb_send_sco_packet: transfers active %u", sco_ring_transfers_active);
1356 
1357     // and if we have more space for SCO packets
1358     if (sco_ring_have_space()) {
1359         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
1360         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
1361     }
1362     return 0;
1363 
1364 exit_on_error:
1365     log_error("usb_send_sco_packet: last error %lu", GetLastError());
1366     return -1;
1367 }
1368 #endif
1369 
1370 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1371     switch (packet_type){
1372         case HCI_COMMAND_DATA_PACKET:
1373             return usb_send_cmd_packet(packet, size);
1374         case HCI_ACL_DATA_PACKET:
1375             return usb_send_acl_packet(packet, size);
1376 #ifdef ENABLE_SCO_OVER_HCI
1377         case HCI_SCO_DATA_PACKET:
1378             return usb_send_sco_packet(packet, size);
1379 #endif
1380         default:
1381             return -1;
1382     }
1383 }
1384 
1385 #ifdef ENABLE_SCO_OVER_HCI
1386 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1387     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1388 
1389     if (num_connections != sco_num_connections){
1390         sco_voice_setting = voice_setting;
1391         if (sco_num_connections){
1392            usb_sco_stop();
1393         }
1394         sco_num_connections = num_connections;
1395         if (num_connections){
1396            usb_sco_start();
1397         }
1398     }
1399 }
1400 #endif
1401 
1402 // get usb singleton
1403 static const hci_transport_t hci_transport_usb = {
1404     /* const char * name; */                                        "H2_WINUSB",
1405     /* void   (*init) (const void *transport_config); */            &usb_init,
1406     /* int    (*open)(void); */                                     &usb_open,
1407     /* int    (*close)(void); */                                    &usb_close,
1408     /* void   (*register_packet_handler)(void (*handler)(...); */   &usb_register_packet_handler,
1409     /* int    (*can_send_packet_now)(uint8_t packet_type); */       &usb_can_send_packet_now,
1410     /* int    (*send_packet)(...); */                               &usb_send_packet,
1411     /* int    (*set_baudrate)(uint32_t baudrate); */                NULL,
1412     /* void   (*reset_link)(void); */                               NULL,
1413 #ifdef ENABLE_SCO_OVER_HCI
1414     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ usb_set_sco_config,
1415 #else
1416     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ NULL,
1417 #endif
1418 };
1419 
1420 const hci_transport_t * hci_transport_usb_instance(void) {
1421     return &hci_transport_usb;
1422 }
1423