xref: /btstack/platform/windows/hci_transport_h2_winusb.c (revision 398a95ec8e0d408db97ed8e80c67c74e30698a03)
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 writing");
535         }
536         return;
537     }
538 
539     // notify uppper
540     packet_handler(HCI_ACL_DATA_PACKET, hci_acl_in_buffer, bytes_read);
541 
542 	// re-submit transfer
543 	usb_submit_acl_in_transfer();
544 }
545 
546 #ifdef ENABLE_SCO_OVER_HCI
547 static void sco_state_machine_init(void){
548     sco_state = H2_W4_SCO_HEADER;
549     sco_read_pos = 0;
550     sco_bytes_to_read = 3;
551 }
552 
553 static void sco_handle_data(uint8_t * buffer, uint16_t size){
554 	// printf("sco_handle_data: state %u, pos %u, to read %u, size %u", sco_state, sco_read_pos, sco_bytes_to_read, size);
555     while (size){
556         if (size < sco_bytes_to_read){
557             // just store incomplete data
558             memcpy(&sco_buffer[sco_read_pos], buffer, size);
559             sco_read_pos      += size;
560             sco_bytes_to_read -= size;
561             return;
562         }
563         // copy requested data
564         memcpy(&sco_buffer[sco_read_pos], buffer, sco_bytes_to_read);
565         sco_read_pos += sco_bytes_to_read;
566         buffer       += sco_bytes_to_read;
567         size         -= sco_bytes_to_read;
568 
569         // chunk read successfully, next action
570         switch (sco_state){
571             case H2_W4_SCO_HEADER:
572                 sco_state = H2_W4_PAYLOAD;
573                 sco_bytes_to_read = sco_buffer[2];
574                 if (sco_bytes_to_read > (sizeof(sco_buffer)-3)){
575                 	log_error("sco_handle_data: sco packet len > packet size");
576 	                sco_state_machine_init();
577                 }
578                 break;
579             case H2_W4_PAYLOAD:
580                 // packet complete
581                 packet_handler(HCI_SCO_DATA_PACKET, sco_buffer, sco_read_pos);
582                 sco_state_machine_init();
583                 break;
584         }
585     }
586 }
587 
588 static void usb_process_sco_out(btstack_data_source_t *ds,  btstack_data_source_callback_type_t callback_type){
589 
590     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
591 
592     if (sco_shutdown){
593         log_info("USB SCO Shutdown:: usb_process_sco_out called");
594         return;
595     }
596 
597     // get current frame number
598     ULONG current_frame_number;
599     LARGE_INTEGER timestamp;
600     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
601 
602     // find index
603     int transfer_index;
604     for (transfer_index=0;transfer_index<SCO_RING_BUFFER_COUNT;transfer_index++){
605         if (ds == &usb_data_source_sco_out[transfer_index]) break;
606     }
607 
608     // log_info("usb_process_sco_out[%02u] -- current frame %lu", transfer_index, current_frame_number);
609 
610     DWORD bytes_transferred;
611     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_sco_out[transfer_index], &bytes_transferred, FALSE);
612     // log_info("usb_process_sco_out_done: #%u result %u, bytes %u, state %u", transfer_index, ok, (int) bytes_transferred, sco_state);
613     if(!ok){
614         DWORD err = GetLastError();
615         if (err == ERROR_IO_INCOMPLETE){
616             // IO_INCOMPLETE -> wait for completed
617             btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
618             return;
619         }
620         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);
621     }
622 
623     // decrease tab
624     sco_ring_transfers_active--;
625 
626     // enable next data source callback
627     if (sco_ring_transfers_active){
628         // update expected and wait for completion
629         usb_sco_out_expected_transfer = (transfer_index+ 1) % SCO_RING_BUFFER_COUNT;
630         // log_info("usb_process_sco_out_done[%02u]: wait for transfer %02u", transfer_index, usb_sco_out_expected_transfer);
631         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[usb_sco_out_expected_transfer], DATA_SOURCE_CALLBACK_WRITE);
632     }
633 
634     // log_info("usb_process_sco_out_done: transfers active %u", sco_ring_transfers_active);
635 
636     // mark free
637     if (sco_ring_have_space()) {
638         uint8_t event[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
639         packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
640     }
641 }
642 
643 static void usb_process_sco_in(btstack_data_source_t *ds,  btstack_data_source_callback_type_t callback_type){
644 
645     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
646 
647     if (sco_shutdown){
648         log_info("USB SCO Shutdown: usb_process_sco_out called");
649         return;
650     }
651 
652     // find index
653     int i;
654     for (i=0;i<ISOC_BUFFERS;i++){
655         if (ds == &usb_data_source_sco_in[i]) break;
656     }
657     int transfer_index = i;
658 
659     // ULONG current_frame_number;
660     // LARGE_INTEGER timestamp;
661     // BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
662 
663     // log_info("usb_process_sco_in[%02u] -- current frame %lu", transfer_index, current_frame_number);
664 
665     DWORD bytes_transferred;
666     BOOL ok = WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_sco_in[transfer_index], &bytes_transferred, FALSE);
667 
668     if(!ok) {
669         DWORD err = GetLastError();
670         if (err == ERROR_IO_INCOMPLETE) {
671             // IO_INCOMPLETE -> wait for completed
672             btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ);
673             return;
674         }
675         log_error("usb_process_sco_in[%02u]: error reading %u, Internal %x", transfer_index, (int) err, (int) usb_overlapped_sco_out[i].Internal);
676     }
677 
678     if (ok){
679         for (i=0;i<NUM_ISO_PACKETS;i++){
680             USBD_ISO_PACKET_DESCRIPTOR * packet_descriptor = &hci_sco_packet_descriptors[transfer_index * NUM_ISO_PACKETS + i];
681             if (packet_descriptor->Length){
682                 uint8_t * iso_data = &hci_sco_in_buffer[transfer_index * SCO_PACKET_SIZE + packet_descriptor->Offset];
683                 uint16_t  iso_len  = packet_descriptor->Length;
684                 sco_handle_data(iso_data, iso_len);
685             }
686         }
687     }
688 
689 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
690     usb_submit_sco_in_transfer_at_frame(i, &sco_next_transfer_at_frame);
691 #else
692     usb_submit_sco_in_transfer_asap(transfer_index, 1);
693 #endif
694     // update expected and wait for completion
695     usb_sco_in_expected_transfer = (transfer_index+ 1) % ISOC_BUFFERS;
696 
697     // log_info("usb_process_sco_in[%02u]: enable data source %02u", transfer_index, usb_sco_in_expected_transfer);
698     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_in[usb_sco_in_expected_transfer], DATA_SOURCE_CALLBACK_READ);
699 }
700 #endif
701 
702 static void usb_process_command_out(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
703 
704     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
705 
706     // update stata before submitting transfer
707     usb_command_out_active = 0;
708 
709     // notify upper stack that provided buffer can be used again
710     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
711     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
712 }
713 
714 static void usb_process_acl_out(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type){
715 
716     btstack_run_loop_disable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_WRITE);
717 
718     // update stata before submitting transfer
719     usb_acl_out_active = 0;
720 
721     // notify upper stack that provided buffer can be used again
722     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
723     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
724 }
725 
726 static BOOL usb_scan_for_bluetooth_endpoints(void) {
727     int i;
728     USB_INTERFACE_DESCRIPTOR usb_interface_descriptor;
729 
730     // reset
731     event_in_addr = 0;
732     acl_in_addr = 0;
733     acl_out_addr = 0;
734 
735     log_info("Scanning USB Entpoints:");
736 
737     // look for Event and ACL pipes on Interface #0
738     BOOL result = WinUsb_QueryInterfaceSettings(usb_interface_0_handle, 0, &usb_interface_descriptor);
739     if (!result) goto exit_on_error;
740     for (i=0;i<usb_interface_descriptor.bNumEndpoints;i++){
741         WINUSB_PIPE_INFORMATION pipe;
742         result = WinUsb_QueryPipe(
743                      usb_interface_0_handle,
744                      0,
745                      (UCHAR) i,
746                      &pipe);
747         if (!result) goto exit_on_error;
748         log_info("Interface #0, Alt #0, Pipe idx #%u: type %u, id 0x%02x, max packet size %u,",
749             i, pipe.PipeType, pipe.PipeId, pipe.MaximumPacketSize);
750         switch (pipe.PipeType){
751             case USB_ENDPOINT_TYPE_INTERRUPT:
752                 if (event_in_addr) continue;
753                 event_in_addr = pipe.PipeId;
754                 log_info("-> using 0x%2.2X for HCI Events", event_in_addr);
755                 break;
756             case USB_ENDPOINT_TYPE_BULK:
757                 if (pipe.PipeId & 0x80) {
758                     if (acl_in_addr) continue;
759                     acl_in_addr = pipe.PipeId;
760                     log_info("-> using 0x%2.2X for ACL Data In", acl_in_addr);
761                 } else {
762                     if (acl_out_addr) continue;
763                     acl_out_addr = pipe.PipeId;
764                     log_info("-> using 0x%2.2X for ACL Data Out", acl_out_addr);
765                 }
766                 break;
767             default:
768                 break;
769         }
770     }
771 
772 #ifdef ENABLE_SCO_OVER_HCI
773     sco_out_addr = 0;
774     sco_in_addr = 0;
775 
776     // look for SCO pipes on Interface #1, Alt Setting 1
777     int alt_setting = 1;
778     result = WinUsb_QueryInterfaceSettings(usb_interface_1_handle, alt_setting, &usb_interface_descriptor);
779     if (!result) goto exit_on_error;
780     for (i=0;i<usb_interface_descriptor.bNumEndpoints;i++){
781         BTSTACK_WINUSB_PIPE_INFORMATION_EX pipe;
782         result = BTstack_WinUsb_QueryPipeEx(
783                      usb_interface_1_handle,
784                      alt_setting,
785                      (UCHAR) i,
786                      &pipe);
787         if (!result) goto exit_on_error;
788         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",
789             alt_setting, i, pipe.PipeType, pipe.PipeId, pipe.MaximumPacketSize, pipe.Interval, (int) pipe.MaximumBytesPerInterval);
790         switch (pipe.PipeType){
791             case USB_ENDPOINT_TYPE_ISOCHRONOUS:
792                 if (pipe.PipeId & 0x80) {
793                     if (sco_in_addr) continue;
794                     sco_in_addr = pipe.PipeId;
795                     log_info("-> using 0x%2.2X for SCO Data In", sco_in_addr);
796                 } else {
797                     if (sco_out_addr) continue;
798                     sco_out_addr = pipe.PipeId;
799                     log_info("-> using 0x%2.2X for SCO Data Out", sco_out_addr);
800                 }
801                 break;
802             default:
803                 break;
804         }
805     }
806     if (!sco_in_addr){
807         log_error("Couldn't find pipe for SCO IN!");
808         return FALSE;
809     }
810     if (!sco_out_addr){
811         log_error("Couldn't find pipe for SCO IN!");
812         return FALSE;
813     }
814 #endif
815 
816     // check if all found
817     if (!event_in_addr){
818         log_error("Couldn't find pipe for Event IN!");
819         return FALSE;
820     }
821     if (!acl_in_addr){
822         log_error("Couldn't find pipe for ACL IN!");
823         return FALSE;
824     }
825     if (!acl_out_addr){
826         log_error("Couldn't find pipe for ACL OUT!");
827         return FALSE;
828     }
829 
830     // all clear
831     return TRUE;
832 
833 exit_on_error:
834     log_error("usb_scan_for_bluetooth_endpoints: last error %lu", GetLastError());
835     return FALSE;
836 }
837 
838 #ifdef ENABLE_SCO_OVER_HCI
839 
840 static int usb_sco_start(void){
841     printf("usb_sco_start\n");
842     log_info("usb_sco_start");
843 
844     sco_shutdown = 0;
845 
846     sco_state_machine_init();
847     sco_ring_init();
848 
849     // calc alt setting
850     int alt_setting;
851     if (sco_voice_setting & 0x0020){
852         // 16-bit PCM
853         alt_setting = alt_setting_16_bit[sco_num_connections-1];
854     } else {
855         // 8-bit PCM or mSBC
856         alt_setting = alt_setting_8_bit[sco_num_connections-1];
857     }
858 
859     log_info("Switching to setting %u on interface 1..", alt_setting);
860     // WinUsb_SetCurrentAlternateSetting returns TRUE if the operation succeeds.
861     BOOL result = WinUsb_SetCurrentAlternateSetting(usb_interface_1_handle, alt_setting);
862     if (!result) goto exit_on_error;
863 
864     // derive iso packet size from alt setting
865     iso_packet_size = iso_packet_size_for_alt_setting[alt_setting];
866 
867     // register isochronous buffer after setting alternate setting
868     usb_sco_register_buffers();
869 
870 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
871     // get current frame number
872     ULONG current_frame_number;
873     LARGE_INTEGER timestamp;
874     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
875     // plan for next tranfer
876     sco_next_transfer_at_frame = current_frame_number + ISOC_BUFFERS * NUM_ISO_PACKETS;
877 #endif
878 
879     int i;
880     for (i=0;i<ISOC_BUFFERS;i++){
881 #ifdef SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
882         usb_submit_sco_in_transfer_at_frame(i, &sco_next_transfer_at_frame);
883 #else
884         usb_submit_sco_in_transfer_asap(i, 0);
885 #endif
886     }
887 
888     usb_sco_in_expected_transfer = 0;
889 
890     // only await first transfer to return
891     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_in[usb_sco_in_expected_transfer], DATA_SOURCE_CALLBACK_READ);
892     return 1;
893 
894 exit_on_error:
895     log_error("usb_sco_start: last error %lu", GetLastError());
896     usb_free_resources();
897     return 0;
898 }
899 
900 static void usb_sco_stop(void){
901     printf("usb_sco_stop\n");
902     log_info("usb_sco_stop");
903 
904     sco_shutdown = 1;
905 
906     // abort SCO transfers
907     WinUsb_AbortPipe(usb_interface_0_handle, sco_in_addr);
908     WinUsb_AbortPipe(usb_interface_0_handle, sco_out_addr);
909 
910     // unlock/free SCO buffers
911     usb_sco_unregister_buffers();
912 
913     int alt_setting = 0;
914     log_info("Switching to setting %u on interface 1..", alt_setting);
915     // WinUsb_SetCurrentAlternateSetting returns TRUE if the operation succeeds.
916     WinUsb_SetCurrentAlternateSetting(usb_interface_1_handle, alt_setting);
917 }
918 #endif
919 
920 // returns 0 if successful, -1 otherwise
921 static int usb_try_open_device(const char * device_path){
922 
923 	// open file
924 	usb_device_handle = CreateFile(device_path,
925 		GENERIC_WRITE | GENERIC_READ,
926         FILE_SHARE_WRITE | FILE_SHARE_READ,
927         NULL,
928         OPEN_EXISTING,
929         FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
930         NULL);
931 	log_info("Opening USB device: %p", usb_device_handle);
932 	if (!usb_device_handle) goto exit_on_error;
933 
934 	// WinUsb_Initialize returns TRUE if the operation succeed
935 	BOOL result = WinUsb_Initialize(usb_device_handle, &usb_interface_0_handle);
936 	if (!result) goto exit_on_error;
937 
938     // Detect USB Dongle based Class, Subclass, and Protocol
939     // The class code (bDeviceClass) is 0xE0 – Wireless Controller.
940     // The SubClass code (bDeviceSubClass) is 0x01 – RF Controller.
941     // The Protocol code (bDeviceProtocol) is 0x01 – Bluetooth programming.
942     USB_INTERFACE_DESCRIPTOR usb_interface_descriptor;
943     result = WinUsb_QueryInterfaceSettings(usb_interface_0_handle, 0, &usb_interface_descriptor);
944     if (!result) goto exit_on_error;
945 
946     // ignore virtual Bluetooth adapter of VMware
947     if (usb_is_vmware_bluetooth_adapter(device_path)) {
948         log_info("Ignoring simulated VMware Bluetooth adapter");
949         usb_free_resources();
950         return -1;
951     }
952 
953     //
954     if (usb_interface_descriptor.bInterfaceClass    != 0xe0 ||
955         usb_interface_descriptor.bInterfaceSubClass != 0x01 ||
956         usb_interface_descriptor.bInterfaceProtocol != 0x01){
957 
958         // check whitelist
959         if (!usb_is_known_bluetooth_device(device_path)){
960             log_info("Class, Subclass, Protocol does not match Bluetooth device");
961             usb_free_resources();
962             return 0;
963         }
964     }
965 
966 #ifdef ENABLE_SCO_OVER_HCI
967 	log_info("Claiming interface 1...");
968 	// WinUsb_GetAssociatedInterface returns TRUE if the operation succeeds.
969 	// We use index 1 - assuming it refers to interface #1 with libusb
970 	// A value of 0 indicates the first associated interface, a value of 1 indicates the second associated interface, and so on.
971 	result = WinUsb_GetAssociatedInterface(usb_interface_0_handle, 0, &usb_interface_1_handle);
972 	if (!result) goto exit_on_error;
973 	log_info("Claiming interface 1: success");
974 #endif
975 
976     result = usb_scan_for_bluetooth_endpoints();
977     if (!result) {
978         log_error("Could not find all Bluetooth Endpoints!");
979         usb_free_resources();
980         return 0;
981     }
982 
983 #ifdef ENABLE_SCO_OVER_HCI
984     int i;
985 
986 	memset(hci_sco_packet_descriptors, 0, sizeof(hci_sco_packet_descriptors));
987 	log_info("Size of packet descriptors for SCO IN%u", (int) sizeof(hci_sco_packet_descriptors));
988 
989 	// setup async io && btstack handler
990 	memset(&usb_overlapped_sco_in, 0, sizeof(usb_overlapped_sco_in));
991 	for (i=0;i<ISOC_BUFFERS;i++){
992 		usb_overlapped_sco_in[i].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
993 		// log_info_hexdump(&usb_overlapped_sco_in[i], sizeof(OVERLAPPED));
994         // log_info("data source SCO in %u, handle %p", i, usb_overlapped_sco_in[i].hEvent);
995 		usb_data_source_sco_in[i].handle = usb_overlapped_sco_in[i].hEvent;
996 	    btstack_run_loop_set_data_source_handler(&usb_data_source_sco_in[i], &usb_process_sco_in);
997         btstack_run_loop_add_data_source(&usb_data_source_sco_in[i]);
998 	}
999 
1000     memset(&usb_overlapped_sco_out, 0, sizeof(usb_overlapped_sco_out));
1001     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1002         usb_overlapped_sco_out[i].hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1003         // log_info("data source SCO out %u, handle %p", i, usb_overlapped_sco_out[i].hEvent);
1004         usb_data_source_sco_out[i].handle = usb_overlapped_sco_out[i].hEvent;
1005         btstack_run_loop_set_data_source_handler(&usb_data_source_sco_out[i], &usb_process_sco_out);
1006         btstack_run_loop_add_data_source(&usb_data_source_sco_out[i]);
1007     }
1008 #endif
1009 
1010 	// setup async io
1011     memset(&usb_overlapped_event_in,     0, sizeof(usb_overlapped_event_in));
1012     memset(&usb_overlapped_command_out,  0, sizeof(usb_overlapped_command_out));
1013     memset(&usb_overlapped_acl_out,      0, sizeof(usb_overlapped_acl_out));
1014     memset(&usb_overlapped_acl_in,       0, sizeof(usb_overlapped_acl_in));
1015     usb_overlapped_event_in.hEvent    = CreateEvent(NULL, TRUE, FALSE, NULL);
1016     usb_overlapped_command_out.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1017     usb_overlapped_acl_in.hEvent      = CreateEvent(NULL, TRUE, FALSE, NULL);
1018     usb_overlapped_acl_out.hEvent     = CreateEvent(NULL, TRUE, FALSE, NULL);
1019 
1020 	// setup btstack data soures
1021     usb_data_source_event_in.handle = usb_overlapped_event_in.hEvent;
1022     btstack_run_loop_set_data_source_handler(&usb_data_source_event_in, &usb_process_event_in);
1023     btstack_run_loop_add_data_source(&usb_data_source_event_in);
1024 
1025     usb_data_source_command_out.handle = usb_overlapped_command_out.hEvent;
1026     btstack_run_loop_set_data_source_handler(&usb_data_source_command_out, &usb_process_command_out);
1027     btstack_run_loop_add_data_source(&usb_data_source_command_out);
1028 
1029     usb_data_source_acl_in.handle = usb_overlapped_acl_in.hEvent;
1030     btstack_run_loop_set_data_source_handler(&usb_data_source_acl_in, &usb_process_acl_in);
1031     btstack_run_loop_add_data_source(&usb_data_source_acl_in);
1032 
1033     usb_data_source_acl_out.handle = usb_overlapped_acl_out.hEvent;
1034     btstack_run_loop_set_data_source_handler(&usb_data_source_acl_out, &usb_process_acl_out);
1035     btstack_run_loop_add_data_source(&usb_data_source_acl_out);
1036 
1037     // submit all incoming transfers
1038     usb_submit_event_in_transfer();
1039     usb_submit_acl_in_transfer();
1040 	return 1;
1041 
1042 exit_on_error:
1043 	log_error("usb_try_open_device: last error %lu", GetLastError());
1044 	usb_free_resources();
1045 	return 0;
1046 }
1047 
1048 #ifdef ENABLE_SCO_OVER_HCI
1049 
1050 #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)
1051 
1052 static BOOL usb_lookup_symbols(void){
1053 	// lookup runtime symbols missing in current mingw64 distribution
1054 	HMODULE h = GetModuleHandleA("WinUSB");
1055 	log_info("%-30s %p", "WinUSB", h);
1056 	WinUSB_Lookup(WinUsb_QueryPipeEx);
1057 	WinUSB_Lookup(WinUsb_RegisterIsochBuffer);
1058 	WinUSB_Lookup(WinUsb_ReadIsochPipe);
1059 	WinUSB_Lookup(WinUsb_ReadIsochPipeAsap);
1060 	WinUSB_Lookup(WinUsb_WriteIsochPipe);
1061 	WinUSB_Lookup(WinUsb_WriteIsochPipeAsap);
1062 	WinUSB_Lookup(WinUsb_UnregisterIsochBuffer);
1063     WinUSB_Lookup(WinUsb_GetCurrentFrameNumber);
1064     return TRUE;
1065 }
1066 #endif
1067 
1068 // returns 0 on success, -1 otherwise
1069 static int usb_open(void){
1070 
1071     int r = -1;
1072 
1073 #ifdef ENABLE_SCO_OVER_HCI
1074 	BOOL ok = usb_lookup_symbols();
1075     if (!ok){
1076         log_error("usb_open: Failed to lookup WinSUB ISOCHRONOUS functions. Please disable ENABLE_SCO_OVER_HCI or use Windows 8.1 or higher");
1077         return r;
1078     }
1079     sco_state_machine_init();
1080     sco_ring_init();
1081 #endif
1082 
1083 	HDEVINFO                         hDevInfo;
1084 	SP_DEVICE_INTERFACE_DATA         DevIntfData;
1085 	PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
1086 	SP_DEVINFO_DATA                  DevData;
1087 
1088 	DWORD dwSize;
1089 	DWORD dwMemberIdx;
1090 
1091     // default endpoint addresses
1092     event_in_addr = 0x81; // EP1, IN interrupt
1093     acl_in_addr =   0x82; // EP2, IN bulk
1094     acl_out_addr =  0x02; // EP2, OUT bulk
1095     sco_in_addr  =  0x83; // EP3, IN isochronous
1096     sco_out_addr =  0x03; // EP3, OUT isochronous
1097 
1098 	// We will try to get device information set for all USB devices that have a
1099 	// device interface and are currently present on the system (plugged in).
1100 	hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
1101 
1102 	log_info("usb_open: SetupDiGetClassDevs -> %p", hDevInfo);
1103 	if (hDevInfo == INVALID_HANDLE_VALUE) return -1;
1104 
1105 	// Prepare to enumerate all device interfaces for the device information
1106 	// set that we retrieved with SetupDiGetClassDevs(..)
1107 	DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
1108 	dwMemberIdx = 0;
1109 
1110 	// Next, we will keep calling this SetupDiEnumDeviceInterfaces(..) until this
1111 	// function causes GetLastError() to return  ERROR_NO_MORE_ITEMS. With each
1112 	// call the dwMemberIdx value needs to be incremented to retrieve the next
1113 	// device interface information.
1114 
1115 	SetupDiEnumDeviceInterfaces(hDevInfo, NULL, (LPGUID) &GUID_DEVINTERFACE_USB_DEVICE,
1116 		dwMemberIdx, &DevIntfData);
1117 
1118 	while(GetLastError() != ERROR_NO_MORE_ITEMS){
1119 
1120 		// As a last step we will need to get some more details for each
1121 		// of device interface information we are able to retrieve. This
1122 		// device interface detail gives us the information we need to identify
1123 		// the device (VID/PID), and decide if it's useful to us. It will also
1124 		// provide a DEVINFO_DATA structure which we can use to know the serial
1125 		// port name for a virtual com port.
1126 
1127 		DevData.cbSize = sizeof(DevData);
1128 
1129 		// Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with
1130 		// a NULL DevIntfDetailData pointer, a DevIntfDetailDataSize
1131 		// of zero, and a valid RequiredSize variable. In response to such a call,
1132 		// this function returns the required buffer size at dwSize.
1133 
1134 		SetupDiGetDeviceInterfaceDetail(
1135 			  hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
1136 
1137 		// Allocate memory for the DeviceInterfaceDetail struct. Don't forget to
1138 		// deallocate it later!
1139 		DevIntfDetailData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
1140 		DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
1141 
1142 		if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData,
1143 			DevIntfDetailData, dwSize, &dwSize, &DevData))
1144 		{
1145 			// Finally we can start checking if we've found a useable device,
1146 			// by inspecting the DevIntfDetailData->DevicePath variable.
1147 			// The DevicePath looks something like this:
1148 			//
1149 			// \\?\usb#vid_04d8&pid_0033#5&19f2438f&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
1150 			//
1151 
1152 			log_info("usb_open: Device Path: %s", DevIntfDetailData->DevicePath);
1153 
1154 #if 0
1155             // check for hard-coded vendor/product ids
1156 			char vid_pid_match[30];
1157 			uint16_t vid = 0x0a12;
1158 			uint16_t pid = 0x0001;
1159 			sprintf(vid_pid_match, "\\\\?\\usb#vid_%04x&pid_%04x", vid, pid);
1160 			if (strncmp(DevIntfDetailData->DevicePath, &vid_pid_match[0], strlen(vid_pid_match)) == 0 ){
1161 				log_info("Matched search string %s", vid_pid_match);
1162 
1163 				BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1164 				if (result){
1165 					log_info("usb_open: Device opened, stop scanning");
1166 					r = 0;
1167 				} else {
1168 					log_error("usb_open: Device open failed");
1169 				}
1170 			}
1171 #endif
1172 
1173             // try all devices
1174             BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1175             if (result){
1176                 log_info("usb_open: Device opened, stop scanning");
1177                 r = 0;
1178             } else {
1179                 log_error("usb_open: Device open failed");
1180             }
1181         }
1182 		HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
1183 
1184 		if (r == 0) break;
1185 
1186 		// Continue looping
1187 		SetupDiEnumDeviceInterfaces(
1188 			hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, ++dwMemberIdx, &DevIntfData);
1189 	}
1190 
1191 	SetupDiDestroyDeviceInfoList(hDevInfo);
1192 
1193 	log_info("usb_open: done");
1194 
1195     return r;
1196 }
1197 
1198 static int usb_close(void){
1199 
1200     // remove data sources
1201     btstack_run_loop_remove_data_source(&usb_data_source_command_out);
1202     btstack_run_loop_remove_data_source(&usb_data_source_event_in);
1203     btstack_run_loop_remove_data_source(&usb_data_source_acl_in);
1204     btstack_run_loop_remove_data_source(&usb_data_source_acl_out);
1205 
1206 #ifdef ENABLE_SCO_OVER_HCI
1207     int i;
1208     for (i=0;i<ISOC_BUFFERS;i++){
1209         btstack_run_loop_remove_data_source(&usb_data_source_sco_in[i]);
1210     }
1211     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1212         btstack_run_loop_remove_data_source(&usb_data_source_sco_out[i]);
1213     }
1214 #endif
1215 
1216     // stop transfers
1217     WinUsb_AbortPipe(usb_interface_0_handle, event_in_addr);
1218     WinUsb_AbortPipe(usb_interface_0_handle, acl_in_addr);
1219     WinUsb_AbortPipe(usb_interface_0_handle, acl_out_addr);
1220 #ifdef ENABLE_SCO_OVER_HCI
1221     usb_sco_stop();
1222 #endif
1223     usb_acl_out_active = 0;
1224 
1225     // control transfer cannot be stopped, just wait for completion
1226     if (usb_command_out_active){
1227         DWORD bytes_transferred;
1228         WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_command_out, &bytes_transferred, TRUE);
1229         usb_command_out_active = 0;
1230     }
1231 
1232     // free everything
1233     usb_free_resources();
1234     return 0;
1235 }
1236 
1237 static int usb_can_send_packet_now(uint8_t packet_type){
1238     // return 0;
1239     switch (packet_type){
1240         case HCI_COMMAND_DATA_PACKET:
1241             return !usb_command_out_active;
1242         case HCI_ACL_DATA_PACKET:
1243             return !usb_acl_out_active;
1244 #ifdef ENABLE_SCO_OVER_HCI
1245         case HCI_SCO_DATA_PACKET:
1246             // return 0;
1247             return sco_ring_have_space();
1248 #endif
1249         default:
1250             return 0;
1251     }
1252 }
1253 
1254 static int usb_send_cmd_packet(uint8_t *packet, int size){
1255 
1256     // update stata before submitting transfer
1257     usb_command_out_active = 1;
1258 
1259 	// Start trasnsfer
1260 	WINUSB_SETUP_PACKET setup_packet;
1261 	memset(&setup_packet, 0, sizeof(setup_packet));
1262 	setup_packet.RequestType =  USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE;
1263 	setup_packet.Length = sizeof(size);
1264 	BOOL result = WinUsb_ControlTransfer(usb_interface_0_handle, setup_packet, packet, size,  NULL, &usb_overlapped_command_out);
1265 	if (!result) {
1266 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1267 	}
1268 
1269     // IO_PENDING -> wait for completed
1270     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_command_out, DATA_SOURCE_CALLBACK_WRITE);
1271 
1272     return 0;
1273 
1274 exit_on_error:
1275 	log_error("winusb: last error %lu", GetLastError());
1276 	return -1;
1277 }
1278 
1279 static int usb_send_acl_packet(uint8_t *packet, int size){
1280 
1281     // update stata before submitting transfer
1282     usb_acl_out_active = 1;
1283 
1284 	// Start trasnsfer
1285 	BOOL ok = WinUsb_WritePipe(usb_interface_0_handle, acl_out_addr, packet, size,  NULL, &usb_overlapped_acl_out);
1286 	if (!ok) {
1287 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1288 	}
1289 
1290     // IO_PENDING -> wait for completed
1291     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_acl_out, DATA_SOURCE_CALLBACK_WRITE);
1292     return 0;
1293 
1294 exit_on_error:
1295 	log_error("winusb: last error %lu", GetLastError());
1296 	return -1;
1297 }
1298 
1299 #ifdef ENABLE_SCO_OVER_HCI
1300 static int usb_send_sco_packet(uint8_t *packet, int size){
1301 
1302     if (size > SCO_PACKET_SIZE){
1303         log_error("usb_send_sco_packet: size %u > SCO_PACKET_SIZE %u", size, SCO_PACKET_SIZE);
1304         return -1;
1305     }
1306 
1307     // get current frame number
1308     ULONG current_frame_number;
1309     LARGE_INTEGER timestamp;
1310     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
1311 
1312     // store packet in free slot
1313     int transfer_index = sco_ring_write;
1314     uint8_t * data = &sco_ring_buffer[transfer_index * SCO_PACKET_SIZE];
1315     memcpy(data, packet, size);
1316 
1317 
1318     // setup transfer
1319     int continue_stream = sco_ring_transfers_active > 0;
1320     BOOL ok = BTstack_WinUsb_WriteIsochPipeAsap(hci_sco_out_buffer_handle, transfer_index * SCO_PACKET_SIZE, size, continue_stream, &usb_overlapped_sco_out[transfer_index]);
1321     // 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);
1322     if (!ok) {
1323         if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1324     }
1325 
1326     // successful started transfer, enable data source callback if first active transfer
1327     if (sco_ring_transfers_active == 0){
1328         usb_sco_out_expected_transfer = transfer_index;
1329         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
1330     }
1331 
1332     // mark slot as full
1333     sco_ring_write = (sco_ring_write + 1) % SCO_RING_BUFFER_COUNT;
1334     sco_ring_transfers_active++;
1335 
1336     // notify upper stack that provided buffer can be used again
1337     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
1338     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
1339 
1340     // log_info("usb_send_sco_packet: transfers active %u", sco_ring_transfers_active);
1341 
1342     // and if we have more space for SCO packets
1343     if (sco_ring_have_space()) {
1344         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
1345         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
1346     }
1347     return 0;
1348 
1349 exit_on_error:
1350     log_error("usb_send_sco_packet: last error %lu", GetLastError());
1351     return -1;
1352 }
1353 #endif
1354 
1355 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1356     switch (packet_type){
1357         case HCI_COMMAND_DATA_PACKET:
1358             return usb_send_cmd_packet(packet, size);
1359         case HCI_ACL_DATA_PACKET:
1360             return usb_send_acl_packet(packet, size);
1361 #ifdef ENABLE_SCO_OVER_HCI
1362         case HCI_SCO_DATA_PACKET:
1363             return usb_send_sco_packet(packet, size);
1364 #endif
1365         default:
1366             return -1;
1367     }
1368 }
1369 
1370 #ifdef ENABLE_SCO_OVER_HCI
1371 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1372     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1373 
1374     if (num_connections != sco_num_connections){
1375         sco_voice_setting = voice_setting;
1376         if (sco_num_connections){
1377            usb_sco_stop();
1378         }
1379         sco_num_connections = num_connections;
1380         if (num_connections){
1381            usb_sco_start();
1382         }
1383     }
1384 }
1385 #endif
1386 
1387 // get usb singleton
1388 static const hci_transport_t hci_transport_usb = {
1389     /* const char * name; */                                        "H2_WINUSB",
1390     /* void   (*init) (const void *transport_config); */            &usb_init,
1391     /* int    (*open)(void); */                                     &usb_open,
1392     /* int    (*close)(void); */                                    &usb_close,
1393     /* void   (*register_packet_handler)(void (*handler)(...); */   &usb_register_packet_handler,
1394     /* int    (*can_send_packet_now)(uint8_t packet_type); */       &usb_can_send_packet_now,
1395     /* int    (*send_packet)(...); */                               &usb_send_packet,
1396     /* int    (*set_baudrate)(uint32_t baudrate); */                NULL,
1397     /* void   (*reset_link)(void); */                               NULL,
1398 #ifdef ENABLE_SCO_OVER_HCI
1399     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ usb_set_sco_config,
1400 #else
1401     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ NULL,
1402 #endif
1403 };
1404 
1405 const hci_transport_t * hci_transport_usb_instance(void) {
1406     return &hci_transport_usb;
1407 }
1408