xref: /btstack/platform/windows/hci_transport_h2_winusb.c (revision d58a1b5f11ada8ddf896c41fff5a35e7f140c37e)
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 <string.h>
58 #include <sys/types.h>
59 #include <inttypes.h>   // to print long long int (aka 64 bit ints)
60 
61 #include "btstack_config.h"
62 
63 #include "btstack_debug.h"
64 #include "hci.h"
65 #include "hci_transport.h"
66 
67 #include <Windows.h>
68 #include <SetupAPI.h>
69 #include <Winusb.h>
70 
71 #ifdef ENABLE_SCO_OVER_HCI
72 
73 // Isochronous Add-On
74 
75 // Function signatures frome https://abi-laboratory.pro/compatibility/Windows_7.0_to_Windows_8.1/x86_64/info/winusb.dll/symbols.html
76 // MSDN documentation has multiple errors (Jan 2017), annotated below
77 
78 // As Isochochronous functions are provided by newer versions of ming64, we use a BTstack/BTSTACK prefix to prevent name collisions
79 
80 typedef PVOID BTSTACK_WINUSB_ISOCH_BUFFER_HANDLE, *BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE;
81 
82 typedef struct _BTSTACK_WINUSB_PIPE_INFORMATION_EX {
83   USBD_PIPE_TYPE PipeType;
84   UCHAR          PipeId;
85   USHORT         MaximumPacketSize;
86   UCHAR          Interval;
87   ULONG          MaximumBytesPerInterval;
88 } BTSTACK_WINUSB_PIPE_INFORMATION_EX, *BTSTACK_PWINUSB_PIPE_INFORMATION_EX;
89 
90 typedef WINBOOL (WINAPI * BTstack_WinUsb_QueryPipeEx_t) (
91 	WINUSB_INTERFACE_HANDLE 	InterfaceHandle,
92 	UCHAR						AlternateInterfaceNumber,
93 	UCHAR 						PipeIndex,
94 	BTSTACK_PWINUSB_PIPE_INFORMATION_EX PipeInformationEx
95 );
96 typedef WINBOOL (WINAPI * BTstack_WinUsb_RegisterIsochBuffer_t)(
97 	WINUSB_INTERFACE_HANDLE     InterfaceHandle,
98 	UCHAR                       PipeID,
99 	PVOID                       Buffer,
100 	ULONG                       BufferLength,
101 	BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle
102 );
103 typedef WINBOOL (WINAPI * BTstack_WinUsb_ReadIsochPipe_t)(
104     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
105     ULONG                       Offset,
106     ULONG                       Length,
107     PULONG                      FrameNumber,
108     ULONG                       NumberOfPackets,        // MSDN lists PULONG
109     PUSBD_ISO_PACKET_DESCRIPTOR IsoPacketDescriptors,   // MSDN lists PULONG
110     LPOVERLAPPED                Overlapped
111 );
112 typedef WINBOOL (WINAPI * BTstack_WinUsb_ReadIsochPipeAsap_t)(
113     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
114     ULONG                       Offset,
115     ULONG                       Length,
116     BOOL                        ContinueStream,
117     ULONG                      	NumberOfPackets,        // MSDN lists PULONG
118     PUSBD_ISO_PACKET_DESCRIPTOR IsoPacketDescriptors,
119  	LPOVERLAPPED                Overlapped
120 );
121 typedef WINBOOL (WINAPI * BTstack_WinUsb_WriteIsochPipe_t)(
122     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
123     ULONG                       Offset,
124     ULONG                       Length,
125     PULONG                      FrameNumber,
126 	LPOVERLAPPED                Overlapped
127 );
128 typedef WINBOOL (WINAPI * BTstack_WinUsb_WriteIsochPipeAsap_t)(
129     BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle,
130     ULONG                       Offset,
131     ULONG                       Length,
132     BOOL                        ContinueStream,
133 	LPOVERLAPPED                Overlapped
134 );
135 typedef WINBOOL (WINAPI * BTstack_WinUsb_UnregisterIsochBuffer_t)(
136 	BTSTACK_PWINUSB_ISOCH_BUFFER_HANDLE BufferHandle
137 );
138 typedef WINBOOL (WINAPI * BTstack_WinUsb_GetCurrentFrameNumber_t)(
139     WINUSB_INTERFACE_HANDLE     InterfaceHandle,        // MSDN lists 'Device handle returned from CreateFile'
140     PULONG                      CurrentFrameNumber,
141     LARGE_INTEGER               *TimeStamp
142 );
143 
144 static BTstack_WinUsb_QueryPipeEx_t 			BTstack_WinUsb_QueryPipeEx;
145 static BTstack_WinUsb_RegisterIsochBuffer_t 	BTstack_WinUsb_RegisterIsochBuffer;
146 static BTstack_WinUsb_ReadIsochPipe_t 			BTstack_WinUsb_ReadIsochPipe;
147 static BTstack_WinUsb_ReadIsochPipeAsap_t 		BTstack_WinUsb_ReadIsochPipeAsap;
148 static BTstack_WinUsb_WriteIsochPipe_t 			BTstack_WinUsb_WriteIsochPipe;
149 static BTstack_WinUsb_WriteIsochPipeAsap_t 		BTstack_WinUsb_WriteIsochPipeAsap;
150 static BTstack_WinUsb_UnregisterIsochBuffer_t 	BTstack_WinUsb_UnregisterIsochBuffer;
151 static BTstack_WinUsb_GetCurrentFrameNumber_t   BTstack_WinUsb_GetCurrentFrameNumber;
152 #endif
153 
154 // Doesn't work as expected
155 // #define SCHEDULE_SCO_IN_TRANSFERS_MANUALLY
156 
157 // Not tested yet
158 // #define SCHEDULE_SCO_OUT_TRANSFERS_MANUALLY
159 
160 //
161 // Bluetooth USB Transport Alternate Settings:
162 //
163 // 0: No active voice channels (for USB compliance)
164 // 1: One 8 kHz voice channel with 8-bit encoding
165 // 2: Two 8 kHz voice channels with 8-bit encoding or one 8 kHz voice channel with 16-bit encoding
166 // 3: Three 8 kHz voice channels with 8-bit encoding
167 // 4: Two 8 kHz voice channels with 16-bit encoding or one 16 kHz voice channel with 16-bit encoding
168 // 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
169 // --> support only a single SCO connection
170 #define ALT_SETTING (1)
171 
172 // alt setting for 1-3 connections and 8/16 bit
173 const int alt_setting_8_bit[]  = {1,2,3};
174 const int alt_setting_16_bit[] = {2,4,5};
175 
176 // for ALT_SETTING >= 1 and 8-bit channel, we need the following isochronous packets
177 // One complete SCO packet with 24 frames every 3 frames (== 3 ms)
178 #define NUM_ISO_PACKETS (3)
179 
180 const uint16_t iso_packet_size_for_alt_setting[] = {
181     0,
182     9,
183     17,
184     25,
185     33,
186     49,
187     63,
188 };
189 
190 // 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)
191 // 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
192 #define SCO_PACKET_SIZE  (49 * NUM_ISO_PACKETS)
193 
194 #define ISOC_BUFFERS   8
195 
196 // Outgoing SCO packet queue
197 // simplified ring buffer implementation
198 #define SCO_RING_BUFFER_COUNT  (20)
199 #define SCO_RING_BUFFER_SIZE (SCO_RING_BUFFER_COUNT * SCO_PACKET_SIZE)
200 
201 /** Request type bits of the "bmRequestType" field in control transfers. */
202 enum usb_request_type {
203 	USB_REQUEST_TYPE_STANDARD = (0x00 << 5),
204 	USB_REQUEST_TYPE_CLASS = (0x01 << 5),
205 	USB_REQUEST_TYPE_VENDOR = (0x02 << 5),
206 };
207 
208 /** Recipient bits of the "bmRequestType" field in control transfers. Values 4 through 31 are reserved. */
209 enum usb_request_recipient {
210 	USB_RECIPIENT_DEVICE = 0x00,
211 	USB_RECIPIENT_INTERFACE = 0x01,
212 	USB_RECIPIENT_ENDPOINT = 0x02,
213 	USB_RECIPIENT_OTHER = 0x03,
214 };
215 
216 // This is the GUID for the USB device class
217 static GUID GUID_DEVINTERFACE_USB_DEVICE =
218 { 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
219 
220 static void usb_dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
221 
222 static void (*packet_handler)(uint8_t packet_type, uint8_t *packet, uint16_t size) = &usb_dummy_handler;
223 
224 // endpoint addresses
225 static int event_in_addr;
226 static int acl_in_addr;
227 static int acl_out_addr;
228 static int sco_in_addr;
229 static int sco_out_addr;
230 
231 //
232 static HANDLE usb_device_handle;
233 static WINUSB_INTERFACE_HANDLE usb_interface_0_handle;
234 static WINUSB_INTERFACE_HANDLE usb_interface_1_handle;
235 static OVERLAPPED usb_overlapped_event_in;
236 static OVERLAPPED usb_overlapped_command_out;
237 static OVERLAPPED usb_overlapped_acl_in;
238 static OVERLAPPED usb_overlapped_acl_out;
239 static btstack_data_source_t usb_data_source_event_in;
240 static btstack_data_source_t usb_data_source_command_out;
241 static btstack_data_source_t usb_data_source_acl_in;
242 static btstack_data_source_t usb_data_source_acl_out;
243 
244 //
245 static int usb_command_out_active;
246 static int usb_acl_out_active;
247 
248 // buffer for HCI Events and ACL Packets
249 static uint8_t hci_event_in_buffer[2 + 255];
250 static uint8_t hci_acl_in_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + HCI_ACL_BUFFER_SIZE];
251 
252 // transport interface state
253 static int usb_transport_open;
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", (int) err);
539             if (err){
540                 log_info("WinUsb_ResetPipe error %u", (int) 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     if (usb_transport_open) return 0;
1082 
1083     int r = -1;
1084 
1085 #ifdef ENABLE_SCO_OVER_HCI
1086 	BOOL ok = usb_lookup_symbols();
1087     if (!ok){
1088         log_error("usb_open: Failed to lookup WinSUB ISOCHRONOUS functions. Please disable ENABLE_SCO_OVER_HCI or use Windows 8.1 or higher");
1089         return r;
1090     }
1091     sco_state_machine_init();
1092     sco_ring_init();
1093 #endif
1094 
1095 	HDEVINFO                         hDevInfo;
1096 	SP_DEVICE_INTERFACE_DATA         DevIntfData;
1097 	PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
1098 	SP_DEVINFO_DATA                  DevData;
1099 
1100 	DWORD dwSize;
1101 	DWORD dwMemberIdx;
1102 
1103     // default endpoint addresses
1104     event_in_addr = 0x81; // EP1, IN interrupt
1105     acl_in_addr =   0x82; // EP2, IN bulk
1106     acl_out_addr =  0x02; // EP2, OUT bulk
1107     sco_in_addr  =  0x83; // EP3, IN isochronous
1108     sco_out_addr =  0x03; // EP3, OUT isochronous
1109 
1110 	// We will try to get device information set for all USB devices that have a
1111 	// device interface and are currently present on the system (plugged in).
1112 	hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
1113 
1114 	log_info("usb_open: SetupDiGetClassDevs -> %p", hDevInfo);
1115 	if (hDevInfo == INVALID_HANDLE_VALUE) return -1;
1116 
1117 	// Prepare to enumerate all device interfaces for the device information
1118 	// set that we retrieved with SetupDiGetClassDevs(..)
1119 	DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
1120 	dwMemberIdx = 0;
1121 
1122 	// Next, we will keep calling this SetupDiEnumDeviceInterfaces(..) until this
1123 	// function causes GetLastError() to return  ERROR_NO_MORE_ITEMS. With each
1124 	// call the dwMemberIdx value needs to be incremented to retrieve the next
1125 	// device interface information.
1126 
1127 	SetupDiEnumDeviceInterfaces(hDevInfo, NULL, (LPGUID) &GUID_DEVINTERFACE_USB_DEVICE,
1128 		dwMemberIdx, &DevIntfData);
1129 
1130 	while(GetLastError() != ERROR_NO_MORE_ITEMS){
1131 
1132 		// As a last step we will need to get some more details for each
1133 		// of device interface information we are able to retrieve. This
1134 		// device interface detail gives us the information we need to identify
1135 		// the device (VID/PID), and decide if it's useful to us. It will also
1136 		// provide a DEVINFO_DATA structure which we can use to know the serial
1137 		// port name for a virtual com port.
1138 
1139 		DevData.cbSize = sizeof(DevData);
1140 
1141 		// Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with
1142 		// a NULL DevIntfDetailData pointer, a DevIntfDetailDataSize
1143 		// of zero, and a valid RequiredSize variable. In response to such a call,
1144 		// this function returns the required buffer size at dwSize.
1145 
1146 		SetupDiGetDeviceInterfaceDetail(
1147 			  hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
1148 
1149 		// Allocate memory for the DeviceInterfaceDetail struct. Don't forget to
1150 		// deallocate it later!
1151 		DevIntfDetailData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
1152 		DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
1153 
1154 		if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData,
1155 			DevIntfDetailData, dwSize, &dwSize, &DevData))
1156 		{
1157 			// Finally we can start checking if we've found a useable device,
1158 			// by inspecting the DevIntfDetailData->DevicePath variable.
1159 			// The DevicePath looks something like this:
1160 			//
1161 			// \\?\usb#vid_04d8&pid_0033#5&19f2438f&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
1162 			//
1163 
1164 			log_info("usb_open: Device Path: %s", DevIntfDetailData->DevicePath);
1165 
1166 #if 0
1167             // check for hard-coded vendor/product ids
1168 			char vid_pid_match[30];
1169 			uint16_t vid = 0x0a12;
1170 			uint16_t pid = 0x0001;
1171 			sprintf(vid_pid_match, "\\\\?\\usb#vid_%04x&pid_%04x", vid, pid);
1172 			if (strncmp(DevIntfDetailData->DevicePath, &vid_pid_match[0], strlen(vid_pid_match)) == 0 ){
1173 				log_info("Matched search string %s", vid_pid_match);
1174 
1175 				BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1176 				if (result){
1177 					log_info("usb_open: Device opened, stop scanning");
1178 					r = 0;
1179 				} else {
1180 					log_error("usb_open: Device open failed");
1181 				}
1182 			}
1183 #endif
1184 
1185             // try all devices
1186             BOOL result = usb_try_open_device(DevIntfDetailData->DevicePath);
1187             if (result){
1188                 log_info("usb_open: Device opened, stop scanning");
1189                 r = 0;
1190             } else {
1191                 log_error("usb_open: Device open failed");
1192             }
1193         }
1194 		HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
1195 
1196 		if (r == 0) break;
1197 
1198 		// Continue looping
1199 		SetupDiEnumDeviceInterfaces(
1200 			hDevInfo, NULL, &GUID_DEVINTERFACE_USB_DEVICE, ++dwMemberIdx, &DevIntfData);
1201 	}
1202 
1203 	SetupDiDestroyDeviceInfoList(hDevInfo);
1204 
1205 	log_info("usb_open: done, r = %x", r);
1206 
1207     if (r == 0){
1208         // opened
1209         usb_transport_open = 1;
1210     }
1211 
1212     return r;
1213 }
1214 
1215 static int usb_close(void){
1216 
1217     if (!usb_transport_open == 0) return 0;
1218 
1219     // remove data sources
1220     btstack_run_loop_remove_data_source(&usb_data_source_command_out);
1221     btstack_run_loop_remove_data_source(&usb_data_source_event_in);
1222     btstack_run_loop_remove_data_source(&usb_data_source_acl_in);
1223     btstack_run_loop_remove_data_source(&usb_data_source_acl_out);
1224 
1225 #ifdef ENABLE_SCO_OVER_HCI
1226     int i;
1227     for (i=0;i<ISOC_BUFFERS;i++){
1228         btstack_run_loop_remove_data_source(&usb_data_source_sco_in[i]);
1229     }
1230     for (i=0;i<SCO_RING_BUFFER_COUNT;i++){
1231         btstack_run_loop_remove_data_source(&usb_data_source_sco_out[i]);
1232     }
1233 #endif
1234 
1235     log_info("usb_close abort event and acl pipes");
1236 
1237     // stop transfers
1238     WinUsb_AbortPipe(usb_interface_0_handle, event_in_addr);
1239     WinUsb_AbortPipe(usb_interface_0_handle, acl_in_addr);
1240     WinUsb_AbortPipe(usb_interface_0_handle, acl_out_addr);
1241 #ifdef ENABLE_SCO_OVER_HCI
1242     usb_sco_stop();
1243 #endif
1244     usb_acl_out_active = 0;
1245 
1246     // control transfer cannot be stopped, just wait for completion
1247     if (usb_command_out_active){
1248         log_info("usb_close command out active, wait for complete");
1249         DWORD bytes_transferred;
1250         WinUsb_GetOverlappedResult(usb_interface_0_handle, &usb_overlapped_command_out, &bytes_transferred, TRUE);
1251         usb_command_out_active = 0;
1252     }
1253 
1254     log_info("usb_close free resources");
1255 
1256     // free everything
1257     usb_free_resources();
1258 
1259     // transport closed
1260     usb_transport_open = 0;
1261 
1262     return 0;
1263 }
1264 
1265 static int usb_can_send_packet_now(uint8_t packet_type){
1266     // return 0;
1267     switch (packet_type){
1268         case HCI_COMMAND_DATA_PACKET:
1269             return !usb_command_out_active;
1270         case HCI_ACL_DATA_PACKET:
1271             return !usb_acl_out_active;
1272 #ifdef ENABLE_SCO_OVER_HCI
1273         case HCI_SCO_DATA_PACKET:
1274             // return 0;
1275             return sco_ring_have_space();
1276 #endif
1277         default:
1278             return 0;
1279     }
1280 }
1281 
1282 static int usb_send_cmd_packet(uint8_t *packet, int size){
1283 
1284     // update stata before submitting transfer
1285     usb_command_out_active = 1;
1286 
1287 	// Start trasnsfer
1288 	WINUSB_SETUP_PACKET setup_packet;
1289 	memset(&setup_packet, 0, sizeof(setup_packet));
1290 	setup_packet.RequestType =  USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE;
1291 	setup_packet.Length = sizeof(size);
1292 	BOOL result = WinUsb_ControlTransfer(usb_interface_0_handle, setup_packet, packet, size,  NULL, &usb_overlapped_command_out);
1293 	if (!result) {
1294 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1295 	}
1296 
1297     // IO_PENDING -> wait for completed
1298     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_command_out, DATA_SOURCE_CALLBACK_WRITE);
1299 
1300     return 0;
1301 
1302 exit_on_error:
1303 	log_error("winusb: last error %lu", GetLastError());
1304 	return -1;
1305 }
1306 
1307 static int usb_send_acl_packet(uint8_t *packet, int size){
1308 
1309     // update stata before submitting transfer
1310     usb_acl_out_active = 1;
1311 
1312 	// Start trasnsfer
1313 	BOOL ok = WinUsb_WritePipe(usb_interface_0_handle, acl_out_addr, packet, size,  NULL, &usb_overlapped_acl_out);
1314 	if (!ok) {
1315 		if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1316 	}
1317 
1318     // IO_PENDING -> wait for completed
1319     btstack_run_loop_enable_data_source_callbacks(&usb_data_source_acl_out, DATA_SOURCE_CALLBACK_WRITE);
1320     return 0;
1321 
1322 exit_on_error:
1323 	log_error("winusb: last error %lu", GetLastError());
1324 	return -1;
1325 }
1326 
1327 #ifdef ENABLE_SCO_OVER_HCI
1328 static int usb_send_sco_packet(uint8_t *packet, int size){
1329 
1330     if (size > SCO_PACKET_SIZE){
1331         log_error("usb_send_sco_packet: size %u > SCO_PACKET_SIZE %u", size, SCO_PACKET_SIZE);
1332         return -1;
1333     }
1334 
1335     // get current frame number
1336     ULONG current_frame_number;
1337     LARGE_INTEGER timestamp;
1338     BTstack_WinUsb_GetCurrentFrameNumber(usb_interface_0_handle, &current_frame_number, &timestamp);
1339 
1340     // store packet in free slot
1341     int transfer_index = sco_ring_write;
1342     uint8_t * data = &sco_ring_buffer[transfer_index * SCO_PACKET_SIZE];
1343     memcpy(data, packet, size);
1344 
1345 
1346     // setup transfer
1347     int continue_stream = sco_ring_transfers_active > 0;
1348     BOOL ok = BTstack_WinUsb_WriteIsochPipeAsap(hci_sco_out_buffer_handle, transfer_index * SCO_PACKET_SIZE, size, continue_stream, &usb_overlapped_sco_out[transfer_index]);
1349     // 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);
1350     if (!ok) {
1351         if (GetLastError() != ERROR_IO_PENDING) goto exit_on_error;
1352     }
1353 
1354     // successful started transfer, enable data source callback if first active transfer
1355     if (sco_ring_transfers_active == 0){
1356         usb_sco_out_expected_transfer = transfer_index;
1357         btstack_run_loop_enable_data_source_callbacks(&usb_data_source_sco_out[transfer_index], DATA_SOURCE_CALLBACK_WRITE);
1358     }
1359 
1360     // mark slot as full
1361     sco_ring_write = (sco_ring_write + 1) % SCO_RING_BUFFER_COUNT;
1362     sco_ring_transfers_active++;
1363 
1364     // notify upper stack that provided buffer can be used again
1365     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
1366     packet_handler(HCI_EVENT_PACKET, &event[0], sizeof(event));
1367 
1368     // log_info("usb_send_sco_packet: transfers active %u", sco_ring_transfers_active);
1369 
1370     // and if we have more space for SCO packets
1371     if (sco_ring_have_space()) {
1372         uint8_t event_sco[] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0};
1373         packet_handler(HCI_EVENT_PACKET, &event_sco[0], sizeof(event_sco));
1374     }
1375     return 0;
1376 
1377 exit_on_error:
1378     log_error("usb_send_sco_packet: last error %lu", GetLastError());
1379     return -1;
1380 }
1381 #endif
1382 
1383 static int usb_send_packet(uint8_t packet_type, uint8_t * packet, int size){
1384     switch (packet_type){
1385         case HCI_COMMAND_DATA_PACKET:
1386             return usb_send_cmd_packet(packet, size);
1387         case HCI_ACL_DATA_PACKET:
1388             return usb_send_acl_packet(packet, size);
1389 #ifdef ENABLE_SCO_OVER_HCI
1390         case HCI_SCO_DATA_PACKET:
1391             return usb_send_sco_packet(packet, size);
1392 #endif
1393         default:
1394             return -1;
1395     }
1396 }
1397 
1398 #ifdef ENABLE_SCO_OVER_HCI
1399 static void usb_set_sco_config(uint16_t voice_setting, int num_connections){
1400     log_info("usb_set_sco_config: voice settings 0x%04x, num connections %u", voice_setting, num_connections);
1401 
1402     if (num_connections != sco_num_connections){
1403         sco_voice_setting = voice_setting;
1404         if (sco_num_connections){
1405            usb_sco_stop();
1406         }
1407         sco_num_connections = num_connections;
1408         if (num_connections){
1409            usb_sco_start();
1410         }
1411     }
1412 }
1413 #endif
1414 
1415 // get usb singleton
1416 static const hci_transport_t hci_transport_usb = {
1417     /* const char * name; */                                        "H2_WINUSB",
1418     /* void   (*init) (const void *transport_config); */            &usb_init,
1419     /* int    (*open)(void); */                                     &usb_open,
1420     /* int    (*close)(void); */                                    &usb_close,
1421     /* void   (*register_packet_handler)(void (*handler)(...); */   &usb_register_packet_handler,
1422     /* int    (*can_send_packet_now)(uint8_t packet_type); */       &usb_can_send_packet_now,
1423     /* int    (*send_packet)(...); */                               &usb_send_packet,
1424     /* int    (*set_baudrate)(uint32_t baudrate); */                NULL,
1425     /* void   (*reset_link)(void); */                               NULL,
1426 #ifdef ENABLE_SCO_OVER_HCI
1427     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ usb_set_sco_config,
1428 #else
1429     /* void   (*set_sco_config)(uint16_t voice_setting, int num_connections); */ NULL,
1430 #endif
1431 };
1432 
1433 const hci_transport_t * hci_transport_usb_instance(void) {
1434     return &hci_transport_usb;
1435 }
1436