Home | History | Annotate | Download | only in os
      1 /*
      2  * windows backend for libusbx 1.0
      3  * Copyright  2009-2012 Pete Batard <pete (at) akeo.ie>
      4  * With contributions from Michael Plante, Orin Eman et al.
      5  * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
      6  * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
      7  * Hash table functions adapted from glibc, by Ulrich Drepper et al.
      8  * Major code testing contribution by Xiaofan Chen
      9  *
     10  * This library is free software; you can redistribute it and/or
     11  * modify it under the terms of the GNU Lesser General Public
     12  * License as published by the Free Software Foundation; either
     13  * version 2.1 of the License, or (at your option) any later version.
     14  *
     15  * This library is distributed in the hope that it will be useful,
     16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     18  * Lesser General Public License for more details.
     19  *
     20  * You should have received a copy of the GNU Lesser General Public
     21  * License along with this library; if not, write to the Free Software
     22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
     23  */
     24 
     25 #include <config.h>
     26 #include <windows.h>
     27 #include <setupapi.h>
     28 #include <ctype.h>
     29 #include <errno.h>
     30 #include <fcntl.h>
     31 #include <process.h>
     32 #include <stdio.h>
     33 #include <inttypes.h>
     34 #include <objbase.h>
     35 #include <winioctl.h>
     36 
     37 #include "libusbi.h"
     38 #include "poll_windows.h"
     39 #include "windows_usb.h"
     40 
     41 // The 2 macros below are used in conjunction with safe loops.
     42 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
     43 #define LOOP_BREAK(err) { r=err; continue; }
     44 
     45 // Helper prototypes
     46 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
     47 static int windows_clock_gettime(int clk_id, struct timespec *tp);
     48 unsigned __stdcall windows_clock_gettime_threaded(void* param);
     49 // Common calls
     50 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     51 
     52 // WinUSB-like API prototypes
     53 static int winusbx_init(int sub_api, struct libusb_context *ctx);
     54 static int winusbx_exit(int sub_api);
     55 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
     56 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
     57 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     58 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     59 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     60 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
     61 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
     62 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
     63 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
     64 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
     65 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
     66 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
     67 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
     68 // HID API prototypes
     69 static int hid_init(int sub_api, struct libusb_context *ctx);
     70 static int hid_exit(int sub_api);
     71 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
     72 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
     73 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     74 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     75 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
     76 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
     77 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
     78 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
     79 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
     80 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
     81 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
     82 // Composite API prototypes
     83 static int composite_init(int sub_api, struct libusb_context *ctx);
     84 static int composite_exit(int sub_api);
     85 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
     86 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
     87 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     88 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
     89 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
     90 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
     91 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
     92 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
     93 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
     94 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
     95 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
     96 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
     97 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
     98 
     99 
    100 // Global variables
    101 uint64_t hires_frequency, hires_ticks_to_ps;
    102 const uint64_t epoch_time = UINT64_C(116444736000000000);	// 1970.01.01 00:00:000 in MS Filetime
    103 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
    104 // Concurrency
    105 static int concurrent_usage = -1;
    106 usbi_mutex_t autoclaim_lock;
    107 // Timer thread
    108 // NB: index 0 is for monotonic and 1 is for the thread exit event
    109 HANDLE timer_thread = NULL;
    110 HANDLE timer_mutex = NULL;
    111 struct timespec timer_tp;
    112 volatile LONG request_count[2] = {0, 1};	// last one must be > 0
    113 HANDLE timer_request[2] = { NULL, NULL };
    114 HANDLE timer_response = NULL;
    115 // API globals
    116 #define CHECK_WINUSBX_AVAILABLE(sub_api) do { if (sub_api == SUB_API_NOTSET) sub_api = priv->sub_api; \
    117 	if (!WinUSBX[sub_api].initialized) return LIBUSB_ERROR_ACCESS; } while(0)
    118 static struct winusb_interface WinUSBX[SUB_API_MAX];
    119 const char* sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
    120 bool api_hid_available = false;
    121 #define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
    122 
    123 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
    124 	if ((guid1 != NULL) && (guid2 != NULL)) {
    125 		return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
    126 	}
    127 	return false;
    128 }
    129 
    130 #if defined(ENABLE_LOGGING)
    131 static char* guid_to_string(const GUID* guid)
    132 {
    133 	static char guid_string[MAX_GUID_STRING_LENGTH];
    134 
    135 	if (guid == NULL) return NULL;
    136 	sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
    137 		(unsigned int)guid->Data1, guid->Data2, guid->Data3,
    138 		guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
    139 		guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
    140 	return guid_string;
    141 }
    142 #endif
    143 
    144 /*
    145  * Converts a windows error to human readable string
    146  * uses retval as errorcode, or, if 0, use GetLastError()
    147  */
    148 #if defined(ENABLE_LOGGING)
    149 static char *windows_error_str(uint32_t retval)
    150 {
    151 static char err_string[ERR_BUFFER_SIZE];
    152 
    153 	DWORD size;
    154 	ssize_t i;
    155 	uint32_t error_code, format_error;
    156 
    157 	error_code = retval?retval:GetLastError();
    158 
    159 	safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%u] ", error_code);
    160 
    161 	size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
    162 		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
    163 		ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
    164 	if (size == 0) {
    165 		format_error = GetLastError();
    166 		if (format_error)
    167 			safe_sprintf(err_string, ERR_BUFFER_SIZE,
    168 				"Windows error code %u (FormatMessage error code %u)", error_code, format_error);
    169 		else
    170 			safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
    171 	} else {
    172 		// Remove CR/LF terminators
    173 		for (i=safe_strlen(err_string)-1; (i>=0) && ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
    174 			err_string[i] = 0;
    175 		}
    176 	}
    177 	return err_string;
    178 }
    179 #endif
    180 
    181 /*
    182  * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
    183  * Return an allocated sanitized string or NULL on error.
    184  */
    185 static char* sanitize_path(const char* path)
    186 {
    187 	const char root_prefix[] = "\\\\.\\";
    188 	size_t j, size, root_size;
    189 	char* ret_path = NULL;
    190 	size_t add_root = 0;
    191 
    192 	if (path == NULL)
    193 		return NULL;
    194 
    195 	size = safe_strlen(path)+1;
    196 	root_size = sizeof(root_prefix)-1;
    197 
    198 	// Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
    199 	if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
    200 		((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
    201 		add_root = root_size;
    202 		size += add_root;
    203 	}
    204 
    205 	if ((ret_path = (char*) calloc(size, 1)) == NULL)
    206 		return NULL;
    207 
    208 	safe_strcpy(&ret_path[add_root], size-add_root, path);
    209 
    210 	// Ensure consistancy with root prefix
    211 	for (j=0; j<root_size; j++)
    212 		ret_path[j] = root_prefix[j];
    213 
    214 	// Same goes for '\' and '#' after the root prefix. Ensure '#' is used
    215 	for(j=root_size; j<size; j++) {
    216 		ret_path[j] = (char)toupper((int)ret_path[j]);	// Fix case too
    217 		if (ret_path[j] == '\\')
    218 			ret_path[j] = '#';
    219 	}
    220 
    221 	return ret_path;
    222 }
    223 
    224 /*
    225  * Cfgmgr32, OLE32 and SetupAPI DLL functions
    226  */
    227 static int init_dlls(void)
    228 {
    229 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
    230 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
    231 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
    232 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
    233 	// Prefixed to avoid conflict with header files
    234 	DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
    235 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
    236 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
    237 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
    238 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
    239 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
    240 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
    241 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
    242 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
    243 	DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
    244 	DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
    245 	return LIBUSB_SUCCESS;
    246 }
    247 
    248 /*
    249  * enumerate interfaces for the whole USB class
    250  *
    251  * Parameters:
    252  * dev_info: a pointer to a dev_info list
    253  * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
    254  * usb_class: the generic USB class for which to retrieve interface details
    255  * index: zero based index of the interface in the device info list
    256  *
    257  * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
    258  * structure returned and call this function repeatedly using the same guid (with an
    259  * incremented index starting at zero) until all interfaces have been returned.
    260  */
    261 static bool get_devinfo_data(struct libusb_context *ctx,
    262 	HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char* usb_class, unsigned _index)
    263 {
    264 	if (_index <= 0) {
    265 		*dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
    266 		if (*dev_info == INVALID_HANDLE_VALUE) {
    267 			return false;
    268 		}
    269 	}
    270 
    271 	dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
    272 	if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
    273 		if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    274 			usbi_err(ctx, "Could not obtain device info data for index %u: %s",
    275 				_index, windows_error_str(0));
    276 		}
    277 		pSetupDiDestroyDeviceInfoList(*dev_info);
    278 		*dev_info = INVALID_HANDLE_VALUE;
    279 		return false;
    280 	}
    281 	return true;
    282 }
    283 
    284 /*
    285  * enumerate interfaces for a specific GUID
    286  *
    287  * Parameters:
    288  * dev_info: a pointer to a dev_info list
    289  * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
    290  * guid: the GUID for which to retrieve interface details
    291  * index: zero based index of the interface in the device info list
    292  *
    293  * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
    294  * structure returned and call this function repeatedly using the same guid (with an
    295  * incremented index starting at zero) until all interfaces have been returned.
    296  */
    297 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
    298 	HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
    299 {
    300 	SP_DEVICE_INTERFACE_DATA dev_interface_data;
    301 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
    302 	DWORD size;
    303 
    304 	if (_index <= 0) {
    305 		*dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
    306 	}
    307 
    308 	if (dev_info_data != NULL) {
    309 		dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
    310 		if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
    311 			if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    312 				usbi_err(ctx, "Could not obtain device info data for index %u: %s",
    313 					_index, windows_error_str(0));
    314 			}
    315 			pSetupDiDestroyDeviceInfoList(*dev_info);
    316 			*dev_info = INVALID_HANDLE_VALUE;
    317 			return NULL;
    318 		}
    319 	}
    320 
    321 	dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
    322 	if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
    323 		if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    324 			usbi_err(ctx, "Could not obtain interface data for index %u: %s",
    325 				_index, windows_error_str(0));
    326 		}
    327 		pSetupDiDestroyDeviceInfoList(*dev_info);
    328 		*dev_info = INVALID_HANDLE_VALUE;
    329 		return NULL;
    330 	}
    331 
    332 	// Read interface data (dummy + actual) to access the device path
    333 	if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
    334 		// The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
    335 		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
    336 			usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
    337 				_index, windows_error_str(0));
    338 			goto err_exit;
    339 		}
    340 	} else {
    341 		usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
    342 		goto err_exit;
    343 	}
    344 
    345 	if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
    346 		usbi_err(ctx, "could not allocate interface data for index %u.", _index);
    347 		goto err_exit;
    348 	}
    349 
    350 	dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
    351 	if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
    352 		dev_interface_details, size, &size, NULL)) {
    353 		usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
    354 			_index, windows_error_str(0));
    355 	}
    356 
    357 	return dev_interface_details;
    358 
    359 err_exit:
    360 	pSetupDiDestroyDeviceInfoList(*dev_info);
    361 	*dev_info = INVALID_HANDLE_VALUE;
    362 	return NULL;
    363 }
    364 
    365 /* For libusb0 filter */
    366 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
    367 	HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index, char* filter_path){
    368 	SP_DEVICE_INTERFACE_DATA dev_interface_data;
    369 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
    370 	DWORD size;
    371 	if (_index <= 0) {
    372 		*dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
    373 	}
    374 	if (dev_info_data != NULL) {
    375 		dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
    376 		if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
    377 			if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    378 				usbi_err(ctx, "Could not obtain device info data for index %u: %s",
    379 					_index, windows_error_str(0));
    380 			}
    381 			pSetupDiDestroyDeviceInfoList(*dev_info);
    382 			*dev_info = INVALID_HANDLE_VALUE;
    383 			return NULL;
    384 		}
    385 	}
    386 	dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
    387 	if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
    388 		if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    389 			usbi_err(ctx, "Could not obtain interface data for index %u: %s",
    390 				_index, windows_error_str(0));
    391 		}
    392 		pSetupDiDestroyDeviceInfoList(*dev_info);
    393 		*dev_info = INVALID_HANDLE_VALUE;
    394 		return NULL;
    395 	}
    396 	// Read interface data (dummy + actual) to access the device path
    397 	if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
    398 		// The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
    399 		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
    400 			usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
    401 				_index, windows_error_str(0));
    402 			goto err_exit;
    403 		}
    404 	} else {
    405 		usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
    406 		goto err_exit;
    407 	}
    408 	if ((dev_interface_details = malloc(size)) == NULL) {
    409 		usbi_err(ctx, "could not allocate interface data for index %u.", _index);
    410 		goto err_exit;
    411 	}
    412 	dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
    413 	if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
    414 		dev_interface_details, size, &size, NULL)) {
    415 		usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
    416 			_index, windows_error_str(0));
    417 	}
    418 	// [trobinso] lookup the libusb0 symbolic index.
    419 	if (dev_interface_details) {
    420 		HKEY hkey_device_interface=pSetupDiOpenDeviceInterfaceRegKey(*dev_info,&dev_interface_data,0,KEY_READ);
    421 		if (hkey_device_interface != INVALID_HANDLE_VALUE) {
    422 			DWORD libusb0_symboliclink_index=0;
    423 			DWORD value_length=sizeof(DWORD);
    424 			DWORD value_type=0;
    425 			LONG status;
    426 			status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
    427 				(LPBYTE) &libusb0_symboliclink_index, &value_length);
    428 			if (status == ERROR_SUCCESS) {
    429 				if (libusb0_symboliclink_index < 256) {
    430 					// libusb0.sys is connected to this device instance.
    431 					// If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
    432 					safe_sprintf(filter_path, sizeof("\\\\.\\libusb0-0000"), "\\\\.\\libusb0-%04d", libusb0_symboliclink_index);
    433 					usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
    434 				} else {
    435 					// libusb0.sys was connected to this device instance at one time; but not anymore.
    436 				}
    437 			}
    438 			pRegCloseKey(hkey_device_interface);
    439 		}
    440 	}
    441 	return dev_interface_details;
    442 err_exit:
    443 	pSetupDiDestroyDeviceInfoList(*dev_info);
    444 	*dev_info = INVALID_HANDLE_VALUE;
    445 	return NULL;}
    446 
    447 /* Hash table functions - modified From glibc 2.3.2:
    448    [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
    449    [Knuth]            The Art of Computer Programming, part 3 (6.4)  */
    450 typedef struct htab_entry {
    451 	unsigned long used;
    452 	char* str;
    453 } htab_entry;
    454 htab_entry* htab_table = NULL;
    455 usbi_mutex_t htab_write_mutex = NULL;
    456 unsigned long htab_size, htab_filled;
    457 
    458 /* For the used double hash method the table size has to be a prime. To
    459    correct the user given table size we need a prime test.  This trivial
    460    algorithm is adequate because the code is called only during init and
    461    the number is likely to be small  */
    462 static int isprime(unsigned long number)
    463 {
    464 	// no even number will be passed
    465 	unsigned int divider = 3;
    466 
    467 	while((divider * divider < number) && (number % divider != 0))
    468 		divider += 2;
    469 
    470 	return (number % divider != 0);
    471 }
    472 
    473 /* Before using the hash table we must allocate memory for it.
    474    We allocate one element more as the found prime number says.
    475    This is done for more effective indexing as explained in the
    476    comment for the hash function.  */
    477 static int htab_create(struct libusb_context *ctx, unsigned long nel)
    478 {
    479 	if (htab_table != NULL) {
    480 		usbi_err(ctx, "hash table already allocated");
    481 	}
    482 
    483 	// Create a mutex
    484 	usbi_mutex_init(&htab_write_mutex, NULL);
    485 
    486 	// Change nel to the first prime number not smaller as nel.
    487 	nel |= 1;
    488 	while(!isprime(nel))
    489 		nel += 2;
    490 
    491 	htab_size = nel;
    492 	usbi_dbg("using %d entries hash table", nel);
    493 	htab_filled = 0;
    494 
    495 	// allocate memory and zero out.
    496 	htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
    497 	if (htab_table == NULL) {
    498 		usbi_err(ctx, "could not allocate space for hash table");
    499 		return 0;
    500 	}
    501 
    502 	return 1;
    503 }
    504 
    505 /* After using the hash table it has to be destroyed.  */
    506 static void htab_destroy(void)
    507 {
    508 	size_t i;
    509 	if (htab_table == NULL) {
    510 		return;
    511 	}
    512 
    513 	for (i=0; i<htab_size; i++) {
    514 		if (htab_table[i].used) {
    515 			safe_free(htab_table[i].str);
    516 		}
    517 	}
    518 	usbi_mutex_destroy(&htab_write_mutex);
    519 	safe_free(htab_table);
    520 }
    521 
    522 /* This is the search function. It uses double hashing with open addressing.
    523    We use an trick to speed up the lookup. The table is created with one
    524    more element available. This enables us to use the index zero special.
    525    This index will never be used because we store the first hash index in
    526    the field used where zero means not used. Every other value means used.
    527    The used field can be used as a first fast comparison for equality of
    528    the stored and the parameter value. This helps to prevent unnecessary
    529    expensive calls of strcmp.  */
    530 static unsigned long htab_hash(char* str)
    531 {
    532 	unsigned long hval, hval2;
    533 	unsigned long idx;
    534 	unsigned long r = 5381;
    535 	int c;
    536 	char* sz = str;
    537 
    538 	if (str == NULL)
    539 		return 0;
    540 
    541 	// Compute main hash value (algorithm suggested by Nokia)
    542 	while ((c = *sz++) != 0)
    543 		r = ((r << 5) + r) + c;
    544 	if (r == 0)
    545 		++r;
    546 
    547 	// compute table hash: simply take the modulus
    548 	hval = r % htab_size;
    549 	if (hval == 0)
    550 		++hval;
    551 
    552 	// Try the first index
    553 	idx = hval;
    554 
    555 	if (htab_table[idx].used) {
    556 		if ( (htab_table[idx].used == hval)
    557 		  && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
    558 			// existing hash
    559 			return idx;
    560 		}
    561 		usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
    562 
    563 		// Second hash function, as suggested in [Knuth]
    564 		hval2 = 1 + hval % (htab_size - 2);
    565 
    566 		do {
    567 			// Because size is prime this guarantees to step through all available indexes
    568 			if (idx <= hval2) {
    569 				idx = htab_size + idx - hval2;
    570 			} else {
    571 				idx -= hval2;
    572 			}
    573 
    574 			// If we visited all entries leave the loop unsuccessfully
    575 			if (idx == hval) {
    576 				break;
    577 			}
    578 
    579 			// If entry is found use it.
    580 			if ( (htab_table[idx].used == hval)
    581 			  && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
    582 				return idx;
    583 			}
    584 		}
    585 		while (htab_table[idx].used);
    586 	}
    587 
    588 	// Not found => New entry
    589 
    590 	// If the table is full return an error
    591 	if (htab_filled >= htab_size) {
    592 		usbi_err(NULL, "hash table is full (%d entries)", htab_size);
    593 		return 0;
    594 	}
    595 
    596 	// Concurrent threads might be storing the same entry at the same time
    597 	// (eg. "simultaneous" enums from different threads) => use a mutex
    598 	usbi_mutex_lock(&htab_write_mutex);
    599 	// Just free any previously allocated string (which should be the same as
    600 	// new one). The possibility of concurrent threads storing a collision
    601 	// string (same hash, different string) at the same time is extremely low
    602 	safe_free(htab_table[idx].str);
    603 	htab_table[idx].used = hval;
    604 	htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
    605 	if (htab_table[idx].str == NULL) {
    606 		usbi_err(NULL, "could not duplicate string for hash table");
    607 		usbi_mutex_unlock(&htab_write_mutex);
    608 		return 0;
    609 	}
    610 	memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
    611 	++htab_filled;
    612 	usbi_mutex_unlock(&htab_write_mutex);
    613 
    614 	return idx;
    615 }
    616 
    617 /*
    618  * Returns the session ID of a device's nth level ancestor
    619  * If there's no device at the nth level, return 0
    620  */
    621 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
    622 {
    623 	DWORD parent_devinst;
    624 	unsigned long session_id = 0;
    625 	char* sanitized_path = NULL;
    626 	char path[MAX_PATH_LENGTH];
    627 	unsigned i;
    628 
    629 	if (level < 1) return 0;
    630 	for (i = 0; i<level; i++) {
    631 		if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
    632 			return 0;
    633 		}
    634 		devinst = parent_devinst;
    635 	}
    636 	if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
    637 		return 0;
    638 	}
    639 	// TODO: (post hotplug): try without sanitizing
    640 	sanitized_path = sanitize_path(path);
    641 	if (sanitized_path == NULL) {
    642 		return 0;
    643 	}
    644 	session_id = htab_hash(sanitized_path);
    645 	safe_free(sanitized_path);
    646 	return session_id;
    647 }
    648 
    649 /*
    650  * Populate the endpoints addresses of the device_priv interface helper structs
    651  */
    652 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
    653 {
    654 	int i, r;
    655 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
    656 	struct libusb_config_descriptor *conf_desc;
    657 	const struct libusb_interface_descriptor *if_desc;
    658 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
    659 
    660 	r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
    661 	if (r != LIBUSB_SUCCESS) {
    662 		usbi_warn(ctx, "could not read config descriptor: error %d", r);
    663 		return r;
    664 	}
    665 
    666 	if_desc = &conf_desc->interface[iface].altsetting[altsetting];
    667 	safe_free(priv->usb_interface[iface].endpoint);
    668 
    669 	if (if_desc->bNumEndpoints == 0) {
    670 		usbi_dbg("no endpoints found for interface %d", iface);
    671 		return LIBUSB_SUCCESS;
    672 	}
    673 
    674 	priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
    675 	if (priv->usb_interface[iface].endpoint == NULL) {
    676 		return LIBUSB_ERROR_NO_MEM;
    677 	}
    678 
    679 	priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
    680 	for (i=0; i<if_desc->bNumEndpoints; i++) {
    681 		priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
    682 		usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
    683 	}
    684 	libusb_free_config_descriptor(conf_desc);
    685 
    686 	// Extra init may be required to configure endpoints
    687 	return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
    688 }
    689 
    690 // Lookup for a match in the list of API driver names
    691 // return -1 if not found, driver match number otherwise
    692 static int get_sub_api(char* driver, int api){
    693 	int i;
    694 	const char sep_str[2] = {LIST_SEPARATOR, 0};
    695 	char *tok, *tmp_str;
    696 	size_t len = safe_strlen(driver);
    697 
    698 	if (len == 0) return SUB_API_NOTSET;
    699 	tmp_str = (char*) calloc(len+1, 1);
    700 	if (tmp_str == NULL) return SUB_API_NOTSET;
    701 	memcpy(tmp_str, driver, len+1);
    702 	tok = strtok(tmp_str, sep_str);
    703 	while (tok != NULL) {
    704 		for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
    705 			if (safe_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
    706 				free(tmp_str);
    707 				return i;
    708 			}
    709 		}
    710 		tok = strtok(NULL, sep_str);
    711 	}
    712 	free (tmp_str);
    713 	return SUB_API_NOTSET;
    714 }
    715 
    716 /*
    717  * auto-claiming and auto-release helper functions
    718  */
    719 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
    720 {
    721 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
    722 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(
    723 		transfer->dev_handle);
    724 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
    725 	int current_interface = *interface_number;
    726 	int r = LIBUSB_SUCCESS;
    727 
    728 	switch(api_type) {
    729 	case USB_API_WINUSBX:
    730 	case USB_API_HID:
    731 		break;
    732 	default:
    733 		return LIBUSB_ERROR_INVALID_PARAM;
    734 	}
    735 
    736 	usbi_mutex_lock(&autoclaim_lock);
    737 	if (current_interface < 0)	// No serviceable interface was found
    738 	{
    739 		for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
    740 			// Must claim an interface of the same API type
    741 			if ( (priv->usb_interface[current_interface].apib->id == api_type)
    742 			  && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
    743 				usbi_dbg("auto-claimed interface %d for control request", current_interface);
    744 				if (handle_priv->autoclaim_count[current_interface] != 0) {
    745 					usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
    746 				}
    747 				handle_priv->autoclaim_count[current_interface]++;
    748 				break;
    749 			}
    750 		}
    751 		if (current_interface == USB_MAXINTERFACES) {
    752 			usbi_err(ctx, "could not auto-claim any interface");
    753 			r = LIBUSB_ERROR_NOT_FOUND;
    754 		}
    755 	} else {
    756 		// If we have a valid interface that was autoclaimed, we must increment
    757 		// its autoclaim count so that we can prevent an early release.
    758 		if (handle_priv->autoclaim_count[current_interface] != 0) {
    759 			handle_priv->autoclaim_count[current_interface]++;
    760 		}
    761 	}
    762 	usbi_mutex_unlock(&autoclaim_lock);
    763 
    764 	*interface_number = current_interface;
    765 	return r;
    766 
    767 }
    768 
    769 static void auto_release(struct usbi_transfer *itransfer)
    770 {
    771 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
    772 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    773 	libusb_device_handle *dev_handle = transfer->dev_handle;
    774 	struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
    775 	int r;
    776 
    777 	usbi_mutex_lock(&autoclaim_lock);
    778 	if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
    779 		handle_priv->autoclaim_count[transfer_priv->interface_number]--;
    780 		if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
    781 			r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
    782 			if (r == LIBUSB_SUCCESS) {
    783 				usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
    784 			} else {
    785 				usbi_dbg("failed to auto-release interface %d (%s)",
    786 					transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
    787 			}
    788 		}
    789 	}
    790 	usbi_mutex_unlock(&autoclaim_lock);
    791 }
    792 
    793 /*
    794  * init: libusbx backend init function
    795  *
    796  * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
    797  * In our implementation, we equate Windows' "HCD" to libusbx's "bus". Note that bus is zero indexed.
    798  * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
    799  */
    800 static int windows_init(struct libusb_context *ctx)
    801 {
    802 	int i, r = LIBUSB_ERROR_OTHER;
    803 	OSVERSIONINFO os_version;
    804 	HANDLE semaphore;
    805 	char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
    806 
    807 	sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
    808 	semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
    809 	if (semaphore == NULL) {
    810 		usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
    811 		return LIBUSB_ERROR_NO_MEM;
    812 	}
    813 
    814 	// A successful wait brings our semaphore count to 0 (unsignaled)
    815 	// => any concurent wait stalls until the semaphore's release
    816 	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
    817 		usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
    818 		CloseHandle(semaphore);
    819 		return LIBUSB_ERROR_NO_MEM;
    820 	}
    821 
    822 	// NB: concurrent usage supposes that init calls are equally balanced with
    823 	// exit calls. If init is called more than exit, we will not exit properly
    824 	if ( ++concurrent_usage == 0 ) {	// First init?
    825 		// Detect OS version
    826 		memset(&os_version, 0, sizeof(OSVERSIONINFO));
    827 		os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    828 		windows_version = WINDOWS_UNSUPPORTED;
    829 		if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
    830 			if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
    831 				windows_version = WINDOWS_XP;
    832 			} else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
    833 				windows_version = WINDOWS_2003;	// also includes XP 64
    834 			} else if (os_version.dwMajorVersion >= 6) {
    835 				windows_version = WINDOWS_VISTA_AND_LATER;
    836 			}
    837 		}
    838 		if (windows_version == WINDOWS_UNSUPPORTED) {
    839 			usbi_err(ctx, "This version of Windows is NOT supported");
    840 			r = LIBUSB_ERROR_NOT_SUPPORTED;
    841 			goto init_exit;
    842 		}
    843 
    844 		// We need a lock for proper auto-release
    845 		usbi_mutex_init(&autoclaim_lock, NULL);
    846 
    847 		// Initialize pollable file descriptors
    848 		init_polling();
    849 
    850 		// Load DLL imports
    851 		if (init_dlls() != LIBUSB_SUCCESS) {
    852 			usbi_err(ctx, "could not resolve DLL functions");
    853 			return LIBUSB_ERROR_NOT_FOUND;
    854 		}
    855 
    856 		// Initialize the low level APIs (we don't care about errors at this stage)
    857 		for (i=0; i<USB_API_MAX; i++) {
    858 			usb_api_backend[i].init(SUB_API_NOTSET, ctx);
    859 		}
    860 
    861 		// Because QueryPerformanceCounter might report different values when
    862 		// running on different cores, we create a separate thread for the timer
    863 		// calls, which we glue to the first core always to prevent timing discrepancies.
    864 		r = LIBUSB_ERROR_NO_MEM;
    865 		for (i = 0; i < 2; i++) {
    866 			timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    867 			if (timer_request[i] == NULL) {
    868 				usbi_err(ctx, "could not create timer request event %d - aborting", i);
    869 				goto init_exit;
    870 			}
    871 		}
    872 		timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
    873 		if (timer_response == NULL) {
    874 			usbi_err(ctx, "could not create timer response semaphore - aborting");
    875 			goto init_exit;
    876 		}
    877 		timer_mutex = CreateMutex(NULL, FALSE, NULL);
    878 		if (timer_mutex == NULL) {
    879 			usbi_err(ctx, "could not create timer mutex - aborting");
    880 			goto init_exit;
    881 		}
    882 		timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
    883 		if (timer_thread == NULL) {
    884 			usbi_err(ctx, "Unable to create timer thread - aborting");
    885 			goto init_exit;
    886 		}
    887 		SetThreadAffinityMask(timer_thread, 0);
    888 
    889 		// Create a hash table to store session ids. Second parameter is better if prime
    890 		htab_create(ctx, HTAB_SIZE);
    891 	}
    892 	// At this stage, either we went through full init successfully, or didn't need to
    893 	r = LIBUSB_SUCCESS;
    894 
    895 init_exit: // Holds semaphore here.
    896 	if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
    897 		if (timer_thread) {
    898 			SetEvent(timer_request[1]); // actually the signal to quit the thread.
    899 			if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
    900 				usbi_warn(ctx, "could not wait for timer thread to quit");
    901 				TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
    902 												  // all objects it might have held anyway.
    903 			}
    904 			CloseHandle(timer_thread);
    905 			timer_thread = NULL;
    906 		}
    907 		for (i = 0; i < 2; i++) {
    908 			if (timer_request[i]) {
    909 				CloseHandle(timer_request[i]);
    910 				timer_request[i] = NULL;
    911 			}
    912 		}
    913 		if (timer_response) {
    914 			CloseHandle(timer_response);
    915 			timer_response = NULL;
    916 		}
    917 		if (timer_mutex) {
    918 			CloseHandle(timer_mutex);
    919 			timer_mutex = NULL;
    920 		}
    921 		htab_destroy();
    922 	}
    923 
    924 	if (r != LIBUSB_SUCCESS)
    925 		--concurrent_usage; // Not expected to call libusb_exit if we failed.
    926 
    927 	ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
    928 	CloseHandle(semaphore);
    929 	return r;
    930 }
    931 
    932 /*
    933  * HCD (root) hubs need to have their device descriptor manually populated
    934  *
    935  * Note that, like Microsoft does in the device manager, we populate the
    936  * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
    937  */
    938 static int force_hcd_device_descriptor(struct libusb_device *dev)
    939 {
    940 	struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
    941 	struct libusb_context *ctx = DEVICE_CTX(dev);
    942 	int vid, pid;
    943 
    944 	dev->num_configurations = 1;
    945 	priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
    946 	priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
    947 	priv->dev_descriptor.bNumConfigurations = 1;
    948 	priv->active_config = 1;
    949 
    950 	if (priv->parent_dev == NULL) {
    951 		usbi_err(ctx, "program assertion failed - HCD hub has no parent");
    952 		return LIBUSB_ERROR_NO_DEVICE;
    953 	}
    954 	parent_priv = _device_priv(priv->parent_dev);
    955 	if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
    956 		priv->dev_descriptor.idVendor = (uint16_t)vid;
    957 		priv->dev_descriptor.idProduct = (uint16_t)pid;
    958 	} else {
    959 		usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
    960 		priv->dev_descriptor.idVendor = 0x1d6b;		// Linux Foundation root hub
    961 		priv->dev_descriptor.idProduct = 1;
    962 	}
    963 	return LIBUSB_SUCCESS;
    964 }
    965 
    966 /*
    967  * fetch and cache all the config descriptors through I/O
    968  */
    969 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
    970 {
    971 	DWORD size, ret_size;
    972 	struct libusb_context *ctx = DEVICE_CTX(dev);
    973 	struct windows_device_priv *priv = _device_priv(dev);
    974 	int r;
    975 	uint8_t i;
    976 
    977 	USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short;    // dummy request
    978 	PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL;       // actual request
    979 	PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
    980 
    981 	if (dev->num_configurations == 0)
    982 		return LIBUSB_ERROR_INVALID_PARAM;
    983 
    984 	priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(unsigned char*));
    985 	if (priv->config_descriptor == NULL)
    986 		return LIBUSB_ERROR_NO_MEM;
    987 	for (i=0; i<dev->num_configurations; i++)
    988 		priv->config_descriptor[i] = NULL;
    989 
    990 	for (i=0, r=LIBUSB_SUCCESS; ; i++)
    991 	{
    992 		// safe loop: release all dynamic resources
    993 		safe_free(cd_buf_actual);
    994 
    995 		// safe loop: end of loop condition
    996 		if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
    997 			break;
    998 
    999 		size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
   1000 		memset(&cd_buf_short, 0, size);
   1001 
   1002 		cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
   1003 		cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
   1004 		cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
   1005 		cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
   1006 		cd_buf_short.req.SetupPacket.wIndex = i;
   1007 		cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
   1008 
   1009 		// Dummy call to get the required data size. Initial failures are reported as info rather
   1010 		// than error as they can occur for non-penalizing situations, such as with some hubs.
   1011 		if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
   1012 			&cd_buf_short, size, &ret_size, NULL)) {
   1013 			usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
   1014 			LOOP_BREAK(LIBUSB_ERROR_IO);
   1015 		}
   1016 
   1017 		if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
   1018 			usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
   1019 			LOOP_BREAK(LIBUSB_ERROR_IO);
   1020 		}
   1021 
   1022 		size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
   1023 		if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
   1024 			usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
   1025 			LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1026 		}
   1027 		memset(cd_buf_actual, 0, size);
   1028 
   1029 		// Actual call
   1030 		cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
   1031 		cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
   1032 		cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
   1033 		cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
   1034 		cd_buf_actual->SetupPacket.wIndex = i;
   1035 		cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
   1036 
   1037 		if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
   1038 			cd_buf_actual, size, &ret_size, NULL)) {
   1039 			usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
   1040 			LOOP_BREAK(LIBUSB_ERROR_IO);
   1041 		}
   1042 
   1043 		cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
   1044 
   1045 		if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
   1046 			usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
   1047 			LOOP_BREAK(LIBUSB_ERROR_IO);
   1048 		}
   1049 
   1050 		if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
   1051 			usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
   1052 			LOOP_BREAK(LIBUSB_ERROR_IO);
   1053 		}
   1054 
   1055 		usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
   1056 			i, cd_data->bConfigurationValue, cd_data->wTotalLength);
   1057 
   1058 		// Cache the descriptor
   1059 		priv->config_descriptor[i] = (unsigned char*) malloc(cd_data->wTotalLength);
   1060 		if (priv->config_descriptor[i] == NULL)
   1061 			return LIBUSB_ERROR_NO_MEM;
   1062 		memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
   1063 	}
   1064 	return LIBUSB_SUCCESS;
   1065 }
   1066 
   1067 /*
   1068  * Populate a libusbx device structure
   1069  */
   1070 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
   1071 					   uint8_t port_number, char* device_id, DWORD devinst)
   1072 {
   1073 	HANDLE handle;
   1074 	DWORD size;
   1075 	USB_NODE_CONNECTION_INFORMATION_EX conn_info;
   1076 	struct windows_device_priv *priv, *parent_priv;
   1077 	struct libusb_context *ctx = DEVICE_CTX(dev);
   1078 	struct libusb_device* tmp_dev;
   1079 	unsigned i;
   1080 
   1081 	if ((dev == NULL) || (parent_dev == NULL)) {
   1082 		return LIBUSB_ERROR_NOT_FOUND;
   1083 	}
   1084 	priv = _device_priv(dev);
   1085 	parent_priv = _device_priv(parent_dev);
   1086 	if (parent_priv->apib->id != USB_API_HUB) {
   1087 		usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
   1088 		return LIBUSB_ERROR_NOT_FOUND;
   1089 	}
   1090 
   1091 	// It is possible for the parent hub not to have been initialized yet
   1092 	// If that's the case, lookup the ancestors to set the bus number
   1093 	if (parent_dev->bus_number == 0) {
   1094 		for (i=2; ; i++) {
   1095 			tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
   1096 			if (tmp_dev == NULL) break;
   1097 			if (tmp_dev->bus_number != 0) {
   1098 				usbi_dbg("got bus number from ancestor #%d", i);
   1099 				parent_dev->bus_number = tmp_dev->bus_number;
   1100 				break;
   1101 			}
   1102 		}
   1103 	}
   1104 	if (parent_dev->bus_number == 0) {
   1105 		usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
   1106 		return LIBUSB_ERROR_NOT_FOUND;
   1107 	}
   1108 	dev->bus_number = parent_dev->bus_number;
   1109 	priv->port = port_number;
   1110 	dev->port_number = port_number;
   1111 	priv->depth = parent_priv->depth + 1;
   1112 	priv->parent_dev = parent_dev;
   1113 	dev->parent_dev = libusb_ref_device(parent_dev);
   1114 
   1115 	// If the device address is already set, we can stop here
   1116 	if (dev->device_address != 0) {
   1117 		return LIBUSB_SUCCESS;
   1118 	}
   1119 	memset(&conn_info, 0, sizeof(conn_info));
   1120 	if (priv->depth != 0) {	// Not a HCD hub
   1121 		handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
   1122 			FILE_FLAG_OVERLAPPED, NULL);
   1123 		if (handle == INVALID_HANDLE_VALUE) {
   1124 			usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
   1125 			return LIBUSB_ERROR_ACCESS;
   1126 		}
   1127 		size = sizeof(conn_info);
   1128 		conn_info.ConnectionIndex = (ULONG)port_number;
   1129 		if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
   1130 			&conn_info, size, &size, NULL)) {
   1131 			usbi_warn(ctx, "could not get node connection information for device '%s': %s",
   1132 				device_id, windows_error_str(0));
   1133 			safe_closehandle(handle);
   1134 			return LIBUSB_ERROR_NO_DEVICE;
   1135 		}
   1136 		if (conn_info.ConnectionStatus == NoDeviceConnected) {
   1137 			usbi_err(ctx, "device '%s' is no longer connected!", device_id);
   1138 			safe_closehandle(handle);
   1139 			return LIBUSB_ERROR_NO_DEVICE;
   1140 		}
   1141 		memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
   1142 		dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
   1143 		priv->active_config = conn_info.CurrentConfigurationValue;
   1144 		usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
   1145 		// If we can't read the config descriptors, just set the number of confs to zero
   1146 		if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
   1147 			dev->num_configurations = 0;
   1148 			priv->dev_descriptor.bNumConfigurations = 0;
   1149 		}
   1150 		safe_closehandle(handle);
   1151 
   1152 		if (conn_info.DeviceAddress > UINT8_MAX) {
   1153 			usbi_err(ctx, "program assertion failed: device address overflow");
   1154 		}
   1155 		dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
   1156 		if (dev->device_address == 1) {
   1157 			usbi_err(ctx, "program assertion failed: device address collision with root hub");
   1158 		}
   1159 		switch (conn_info.Speed) {
   1160 		case 0: dev->speed = LIBUSB_SPEED_LOW; break;
   1161 		case 1: dev->speed = LIBUSB_SPEED_FULL; break;
   1162 		case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
   1163 		case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
   1164 		default:
   1165 			usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
   1166 			break;
   1167 		}
   1168 	} else {
   1169 		dev->device_address = 1;	// root hubs are set to use device number 1
   1170 		force_hcd_device_descriptor(dev);
   1171 	}
   1172 
   1173 	usbi_sanitize_device(dev);
   1174 
   1175 	usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
   1176 		dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
   1177 
   1178 	return LIBUSB_SUCCESS;
   1179 }
   1180 
   1181 // Returns the api type, or 0 if not found/unsupported
   1182 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
   1183 	SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
   1184 {
   1185 	// Precedence for filter drivers vs driver is in the order of this array
   1186 	struct driver_lookup lookup[3] = {
   1187 		{"\0\0", SPDRP_SERVICE, "driver"},
   1188 		{"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
   1189 		{"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
   1190 	};
   1191 	DWORD size, reg_type;
   1192 	unsigned k, l;
   1193 	int i, j;
   1194 
   1195 	*api = USB_API_UNSUPPORTED;
   1196 	*sub_api = SUB_API_NOTSET;
   1197 	// Check the service & filter names to know the API we should use
   1198 	for (k=0; k<3; k++) {
   1199 		if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
   1200 			&reg_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
   1201 			// Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
   1202 			if (lookup[k].reg_prop == SPDRP_SERVICE) {
   1203 				// our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
   1204 				lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
   1205 			}
   1206 			// MULTI_SZ is a pain to work with. Turn it into something much more manageable
   1207 			// NB: none of the driver names we check against contain LIST_SEPARATOR,
   1208 			// (currently ';'), so even if an unsuported one does, it's not an issue
   1209 			for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
   1210 				if (lookup[k].list[l] == 0) {
   1211 					lookup[k].list[l] = LIST_SEPARATOR;
   1212 				}
   1213 			}
   1214 			usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
   1215 		} else {
   1216 			if (GetLastError() != ERROR_INVALID_DATA) {
   1217 				usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
   1218 			}
   1219 			lookup[k].list[0] = 0;
   1220 		}
   1221 	}
   1222 
   1223 	for (i=1; i<USB_API_MAX; i++) {
   1224 		for (k=0; k<3; k++) {
   1225 			j = get_sub_api(lookup[k].list, i);
   1226 			if (j >= 0) {
   1227 				usbi_dbg("matched %s name against %s API",
   1228 					lookup[k].designation, (i!=USB_API_WINUSBX)?usb_api_backend[i].designation:sub_api_name[j]);
   1229 				*api = i;
   1230 				*sub_api = j;
   1231 				return;
   1232 			}
   1233 		}
   1234 	}
   1235 }
   1236 
   1237 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
   1238 							char* dev_interface_path, char* device_id, int api, int sub_api)
   1239 {
   1240 	unsigned i;
   1241 	struct windows_device_priv *priv = _device_priv(dev);
   1242 	int interface_number;
   1243 
   1244 	if (priv->apib->id != USB_API_COMPOSITE) {
   1245 		usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
   1246 		return LIBUSB_ERROR_NO_DEVICE;
   1247 	}
   1248 
   1249 	// Because MI_## are not necessarily in sequential order (some composite
   1250 	// devices will have only MI_00 & MI_03 for instance), we retrieve the actual
   1251 	// interface number from the path's MI value
   1252 	interface_number = 0;
   1253 	for (i=0; device_id[i] != 0; ) {
   1254 		if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
   1255 		  && (device_id[i++] == '_') ) {
   1256 			interface_number = (device_id[i++] - '0')*10;
   1257 			interface_number += device_id[i] - '0';
   1258 			break;
   1259 		}
   1260 	}
   1261 
   1262 	if (device_id[i] == 0) {
   1263 		usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
   1264 			device_id, interface_number);
   1265 	}
   1266 
   1267 	if (priv->usb_interface[interface_number].path != NULL) {
   1268 		if (api == USB_API_HID) {
   1269 			// HID devices can have multiple collections (COL##) for each MI_## interface
   1270 			usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
   1271 				interface_number, device_id);
   1272 			return LIBUSB_ERROR_ACCESS;
   1273 		}
   1274 		// In other cases, just use the latest data
   1275 		safe_free(priv->usb_interface[interface_number].path);
   1276 	}
   1277 
   1278 	usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
   1279 	priv->usb_interface[interface_number].path = dev_interface_path;
   1280 	priv->usb_interface[interface_number].apib = &usb_api_backend[api];
   1281 	priv->usb_interface[interface_number].sub_api = sub_api;
   1282 	if ((api == USB_API_HID) && (priv->hid == NULL)) {
   1283 		priv->hid = (struct hid_device_priv*) calloc(1, sizeof(struct hid_device_priv));
   1284 		if (priv->hid == NULL)
   1285 			return LIBUSB_ERROR_NO_MEM;
   1286 	}
   1287 
   1288 	return LIBUSB_SUCCESS;
   1289 }
   1290 
   1291 static int set_hid_interface(struct libusb_context* ctx, struct libusb_device* dev,
   1292 							char* dev_interface_path)
   1293 {
   1294 	int i;
   1295 	struct windows_device_priv *priv = _device_priv(dev);
   1296 
   1297 	if (priv->hid == NULL) {
   1298 		usbi_err(ctx, "program assertion failed: parent is not HID");
   1299 		return LIBUSB_ERROR_NO_DEVICE;
   1300 	}
   1301 	if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
   1302 		usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
   1303 		return LIBUSB_ERROR_NO_DEVICE;
   1304 	}
   1305 	for (i=0; i<priv->hid->nb_interfaces; i++) {
   1306 		if (safe_strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
   1307 			usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
   1308 			return LIBUSB_SUCCESS;
   1309 		}
   1310 	}
   1311 
   1312 	priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
   1313 	priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
   1314 	usbi_dbg("interface[%d] = %s", priv->hid->nb_interfaces, dev_interface_path);
   1315 	priv->hid->nb_interfaces++;
   1316 	return LIBUSB_SUCCESS;
   1317 }
   1318 
   1319 /*
   1320  * get_device_list: libusbx backend device enumeration function
   1321  */
   1322 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
   1323 {
   1324 	struct discovered_devs *discdevs;
   1325 	HDEVINFO dev_info = { 0 };
   1326 	const char* usb_class[] = {"USB", "NUSB3", "IUSB3"};
   1327 	SP_DEVINFO_DATA dev_info_data = { 0 };
   1328 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
   1329 	GUID hid_guid;
   1330 #define MAX_ENUM_GUIDS 64
   1331 	const GUID* guid[MAX_ENUM_GUIDS];
   1332 #define HCD_PASS 0
   1333 #define HUB_PASS 1
   1334 #define GEN_PASS 2
   1335 #define DEV_PASS 3
   1336 #define HID_PASS 4
   1337 	int r = LIBUSB_SUCCESS;
   1338 	int api, sub_api;
   1339 	size_t class_index = 0;
   1340 	unsigned int nb_guids, pass, i, j, ancestor;
   1341 	char path[MAX_PATH_LENGTH];
   1342 	char strbuf[MAX_PATH_LENGTH];
   1343 	struct libusb_device *dev, *parent_dev;
   1344 	struct windows_device_priv *priv, *parent_priv;
   1345 	char* dev_interface_path = NULL;
   1346 	char* dev_id_path = NULL;
   1347 	unsigned long session_id;
   1348 	DWORD size, reg_type, port_nr, install_state;
   1349 	HKEY key;
   1350 	WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
   1351 	GUID* if_guid;
   1352 	LONG s;
   1353 	// Keep a list of newly allocated devs to unref
   1354 	libusb_device** unref_list;
   1355 	unsigned int unref_size = 64;
   1356 	unsigned int unref_cur = 0;
   1357 
   1358 	// PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
   1359 	// PASS 2 : (re)enumerate HUBS
   1360 	// PASS 3 : (re)enumerate generic USB devices (including driverless)
   1361 	//           and list additional USB device interface GUIDs to explore
   1362 	// PASS 4 : (re)enumerate master USB devices that have a device interface
   1363 	// PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
   1364 	//           set the device interfaces.
   1365 
   1366 	// Init the GUID table
   1367 	guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
   1368 	guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
   1369 	guid[GEN_PASS] = NULL;
   1370 	guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
   1371 	HidD_GetHidGuid(&hid_guid);
   1372 	guid[HID_PASS] = &hid_guid;
   1373 	nb_guids = HID_PASS+1;
   1374 
   1375 	unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
   1376 	if (unref_list == NULL) {
   1377 		return LIBUSB_ERROR_NO_MEM;
   1378 	}
   1379 
   1380 	for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
   1381 //#define ENUM_DEBUG
   1382 #ifdef ENUM_DEBUG
   1383 		const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
   1384 		usbi_dbg("\n#### PROCESSING %ss %s", passname[(pass<=HID_PASS)?pass:HID_PASS+1],
   1385 			(pass!=GEN_PASS)?guid_to_string(guid[pass]):"");
   1386 #endif
   1387 		for (i = 0; ; i++) {
   1388 			// safe loop: free up any (unprotected) dynamic resource
   1389 			// NB: this is always executed before breaking the loop
   1390 			safe_free(dev_interface_details);
   1391 			safe_free(dev_interface_path);
   1392 			safe_free(dev_id_path);
   1393 			priv = parent_priv = NULL;
   1394 			dev = parent_dev = NULL;
   1395 
   1396 			// Safe loop: end of loop conditions
   1397 			if (r != LIBUSB_SUCCESS) {
   1398 				break;
   1399 			}
   1400 			if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
   1401 				usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
   1402 				break;
   1403 			}
   1404 			if (pass != GEN_PASS) {
   1405 				// Except for GEN, all passes deal with device interfaces
   1406 				dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
   1407 				if (dev_interface_details == NULL) {
   1408 					break;
   1409 				} else {
   1410 					dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
   1411 					if (dev_interface_path == NULL) {
   1412 						usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
   1413 						continue;
   1414 					}
   1415 				}
   1416 			} else {
   1417 				// Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
   1418 				// being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
   1419 				// The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
   1420 				for (; class_index < ARRAYSIZE(usb_class); class_index++) {
   1421 					if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
   1422 						break;
   1423 					i = 0;
   1424 				}
   1425 				if (class_index >= ARRAYSIZE(usb_class))
   1426 					break;
   1427 			}
   1428 
   1429 			// Read the Device ID path. This is what we'll use as UID
   1430 			// Note that if the device is plugged in a different port or hub, the Device ID changes
   1431 			if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
   1432 				usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
   1433 					dev_info_data.DevInst);
   1434 				continue;
   1435 			}
   1436 			dev_id_path = sanitize_path(path);
   1437 			if (dev_id_path == NULL) {
   1438 				usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
   1439 					dev_info_data.DevInst);
   1440 				continue;
   1441 			}
   1442 #ifdef ENUM_DEBUG
   1443 			usbi_dbg("PRO: %s", dev_id_path);
   1444 #endif
   1445 
   1446 			// The SPDRP_ADDRESS for USB devices is the device port number on the hub
   1447 			port_nr = 0;
   1448 			if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
   1449 				if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
   1450 					&reg_type, (BYTE*)&port_nr, 4, &size))
   1451 				  || (size != 4) ) {
   1452 					usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
   1453 						dev_id_path, windows_error_str(0));
   1454 					continue;
   1455 				}
   1456 			}
   1457 
   1458 			// Set API to use or get additional data from generic pass
   1459 			api = USB_API_UNSUPPORTED;
   1460 			sub_api = SUB_API_NOTSET;
   1461 			switch (pass) {
   1462 			case HCD_PASS:
   1463 				break;
   1464 			case GEN_PASS:
   1465 				// We use the GEN pass to detect driverless devices...
   1466 				size = sizeof(strbuf);
   1467 				if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
   1468 					&reg_type, (BYTE*)strbuf, size, &size)) {
   1469 						usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
   1470 						usbi_info(ctx, "libusbx will not be able to access it.");
   1471 				}
   1472 				// ...and to add the additional device interface GUIDs
   1473 				key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
   1474 				if (key != INVALID_HANDLE_VALUE) {
   1475 					size = sizeof(guid_string_w);
   1476 					s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &reg_type,
   1477 						(BYTE*)guid_string_w, &size);
   1478 					pRegCloseKey(key);
   1479 					if (s == ERROR_SUCCESS) {
   1480 						if (nb_guids >= MAX_ENUM_GUIDS) {
   1481 							// If this assert is ever reported, grow a GUID table dynamically
   1482 							usbi_err(ctx, "program assertion failed: too many GUIDs");
   1483 							LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
   1484 						}
   1485 						if_guid = (GUID*) calloc(1, sizeof(GUID));
   1486 						pCLSIDFromString(guid_string_w, if_guid);
   1487 						guid[nb_guids++] = if_guid;
   1488 						usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
   1489 					}
   1490 				}
   1491 				break;
   1492 			case HID_PASS:
   1493 				api = USB_API_HID;
   1494 				break;
   1495 			default:
   1496 				// Get the API type (after checking that the driver installation is OK)
   1497 				if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
   1498 					&reg_type, (BYTE*)&install_state, 4, &size))
   1499 				  || (size != 4) ){
   1500 					usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
   1501 						dev_id_path, windows_error_str(0));
   1502 				} else if (install_state != 0) {
   1503 					usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
   1504 						dev_id_path, install_state);
   1505 					continue;
   1506 				}
   1507 				get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
   1508 				break;
   1509 			}
   1510 
   1511 			// Find parent device (for the passes that need it)
   1512 			switch (pass) {
   1513 			case HCD_PASS:
   1514 			case DEV_PASS:
   1515 			case HUB_PASS:
   1516 				break;
   1517 			default:
   1518 				// Go through the ancestors until we see a face we recognize
   1519 				parent_dev = NULL;
   1520 				for (ancestor = 1; parent_dev == NULL; ancestor++) {
   1521 					session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
   1522 					if (session_id == 0) {
   1523 						break;
   1524 					}
   1525 					parent_dev = usbi_get_device_by_session_id(ctx, session_id);
   1526 				}
   1527 				if (parent_dev == NULL) {
   1528 					usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
   1529 					continue;
   1530 				}
   1531 				parent_priv = _device_priv(parent_dev);
   1532 				// virtual USB devices are also listed during GEN - don't process these yet
   1533 				if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
   1534 					continue;
   1535 				}
   1536 				break;
   1537 			}
   1538 
   1539 			// Create new or match existing device, using the (hashed) device_id as session id
   1540 			if (pass <= DEV_PASS) {	// For subsequent passes, we'll lookup the parent
   1541 				// These are the passes that create "new" devices
   1542 				session_id = htab_hash(dev_id_path);
   1543 				dev = usbi_get_device_by_session_id(ctx, session_id);
   1544 				if (dev == NULL) {
   1545 					if (pass == DEV_PASS) {
   1546 						// This can occur if the OS only reports a newly plugged device after we started enum
   1547 						usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
   1548 							" - ignoring", dev_id_path);
   1549 						continue;
   1550 					}
   1551 					usbi_dbg("allocating new device for session [%X]", session_id);
   1552 					if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
   1553 						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1554 					}
   1555 					windows_device_priv_init(dev);
   1556 					// Keep track of devices that need unref
   1557 					unref_list[unref_cur++] = dev;
   1558 					if (unref_cur >= unref_size) {
   1559 						unref_size += 64;
   1560 						unref_list = usbi_reallocf(unref_list, unref_size*sizeof(libusb_device*));
   1561 						if (unref_list == NULL) {
   1562 							usbi_err(ctx, "could not realloc list for unref - aborting.");
   1563 							LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1564 						}
   1565 					}
   1566 				} else {
   1567 					usbi_dbg("found existing device for session [%X] (%d.%d)",
   1568 						session_id, dev->bus_number, dev->device_address);
   1569 				}
   1570 				priv = _device_priv(dev);
   1571 			}
   1572 
   1573 			// Setup device
   1574 			switch (pass) {
   1575 			case HCD_PASS:
   1576 				dev->bus_number = (uint8_t)(i + 1);	// bus 0 is reserved for disconnected
   1577 				dev->device_address = 0;
   1578 				dev->num_configurations = 0;
   1579 				priv->apib = &usb_api_backend[USB_API_HUB];
   1580 				priv->sub_api = SUB_API_NOTSET;
   1581 				priv->depth = UINT8_MAX;	// Overflow to 0 for HCD Hubs
   1582 				priv->path = dev_interface_path; dev_interface_path = NULL;
   1583 				break;
   1584 			case HUB_PASS:
   1585 			case DEV_PASS:
   1586 				// If the device has already been setup, don't do it again
   1587 				if (priv->path != NULL)
   1588 					break;
   1589 				// Take care of API initialization
   1590 				priv->path = dev_interface_path; dev_interface_path = NULL;
   1591 				priv->apib = &usb_api_backend[api];
   1592 				priv->sub_api = sub_api;
   1593 				switch(api) {
   1594 				case USB_API_COMPOSITE:
   1595 				case USB_API_HUB:
   1596 					break;
   1597 				case USB_API_HID:
   1598 					priv->hid = calloc(1, sizeof(struct hid_device_priv));
   1599 					if (priv->hid == NULL) {
   1600 						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1601 					}
   1602 					priv->hid->nb_interfaces = 0;
   1603 					break;
   1604 				default:
   1605 					// For other devices, the first interface is the same as the device
   1606 					priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
   1607 					if (priv->usb_interface[0].path != NULL) {
   1608 						safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
   1609 					} else {
   1610 						usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
   1611 					}
   1612 					// The following is needed if we want API calls to work for both simple
   1613 					// and composite devices.
   1614 					for(j=0; j<USB_MAXINTERFACES; j++) {
   1615 						priv->usb_interface[j].apib = &usb_api_backend[api];
   1616 					}
   1617 					break;
   1618 				}
   1619 				break;
   1620 			case GEN_PASS:
   1621 				r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
   1622 				if (r == LIBUSB_SUCCESS) {
   1623 					// Append device to the list of discovered devices
   1624 					discdevs = discovered_devs_append(*_discdevs, dev);
   1625 					if (!discdevs) {
   1626 						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1627 					}
   1628 					*_discdevs = discdevs;
   1629 				} else if (r == LIBUSB_ERROR_NO_DEVICE) {
   1630 					// This can occur if the device was disconnected but Windows hasn't
   1631 					// refreshed its enumeration yet - in that case, we ignore the device
   1632 					r = LIBUSB_SUCCESS;
   1633 				}
   1634 				break;
   1635 			default:	// HID_PASS and later
   1636 				if (parent_priv->apib->id == USB_API_HID) {
   1637 					usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
   1638 					r = set_hid_interface(ctx, parent_dev, dev_interface_path);
   1639 					if (r != LIBUSB_SUCCESS) LOOP_BREAK(r);
   1640 					dev_interface_path = NULL;
   1641 				} else if (parent_priv->apib->id == USB_API_COMPOSITE) {
   1642 					usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
   1643 					switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api)) {
   1644 					case LIBUSB_SUCCESS:
   1645 						dev_interface_path = NULL;
   1646 						break;
   1647 					case LIBUSB_ERROR_ACCESS:
   1648 						// interface has already been set => make sure dev_interface_path is freed then
   1649 						break;
   1650 					default:
   1651 						LOOP_BREAK(r);
   1652 						break;
   1653 					}
   1654 				}
   1655 				break;
   1656 			}
   1657 		}
   1658 	}
   1659 
   1660 	// Free any additional GUIDs
   1661 	for (pass = HID_PASS+1; pass < nb_guids; pass++) {
   1662 		safe_free(guid[pass]);
   1663 	}
   1664 
   1665 	// Unref newly allocated devs
   1666 	for (i=0; i<unref_cur; i++) {
   1667 		safe_unref_device(unref_list[i]);
   1668 	}
   1669 	safe_free(unref_list);
   1670 
   1671 	return r;
   1672 }
   1673 
   1674 /*
   1675  * exit: libusbx backend deinitialization function
   1676  */
   1677 static void windows_exit(void)
   1678 {
   1679 	int i;
   1680 	HANDLE semaphore;
   1681 	char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
   1682 
   1683 	sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
   1684 	semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
   1685 	if (semaphore == NULL) {
   1686 		return;
   1687 	}
   1688 
   1689 	// A successful wait brings our semaphore count to 0 (unsignaled)
   1690 	// => any concurent wait stalls until the semaphore release
   1691 	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
   1692 		CloseHandle(semaphore);
   1693 		return;
   1694 	}
   1695 
   1696 	// Only works if exits and inits are balanced exactly
   1697 	if (--concurrent_usage < 0) {	// Last exit
   1698 		for (i=0; i<USB_API_MAX; i++) {
   1699 			usb_api_backend[i].exit(SUB_API_NOTSET);
   1700 		}
   1701 		exit_polling();
   1702 
   1703 		if (timer_thread) {
   1704 			SetEvent(timer_request[1]); // actually the signal to quit the thread.
   1705 			if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
   1706 				usbi_dbg("could not wait for timer thread to quit");
   1707 				TerminateThread(timer_thread, 1);
   1708 			}
   1709 			CloseHandle(timer_thread);
   1710 			timer_thread = NULL;
   1711 		}
   1712 		for (i = 0; i < 2; i++) {
   1713 			if (timer_request[i]) {
   1714 				CloseHandle(timer_request[i]);
   1715 				timer_request[i] = NULL;
   1716 			}
   1717 		}
   1718 		if (timer_response) {
   1719 			CloseHandle(timer_response);
   1720 			timer_response = NULL;
   1721 		}
   1722 		if (timer_mutex) {
   1723 			CloseHandle(timer_mutex);
   1724 			timer_mutex = NULL;
   1725 		}
   1726 		htab_destroy();
   1727 	}
   1728 
   1729 	ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
   1730 	CloseHandle(semaphore);
   1731 }
   1732 
   1733 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
   1734 {
   1735 	struct windows_device_priv *priv = _device_priv(dev);
   1736 
   1737 	memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
   1738 	*host_endian = 0;
   1739 
   1740 	return LIBUSB_SUCCESS;
   1741 }
   1742 
   1743 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
   1744 {
   1745 	struct windows_device_priv *priv = _device_priv(dev);
   1746 	PUSB_CONFIGURATION_DESCRIPTOR config_header;
   1747 	size_t size;
   1748 
   1749 	// config index is zero based
   1750 	if (config_index >= dev->num_configurations)
   1751 		return LIBUSB_ERROR_INVALID_PARAM;
   1752 
   1753 	if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
   1754 		return LIBUSB_ERROR_NOT_FOUND;
   1755 
   1756 	config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
   1757 
   1758 	size = min(config_header->wTotalLength, len);
   1759 	memcpy(buffer, priv->config_descriptor[config_index], size);
   1760 	*host_endian = 0;
   1761 
   1762 	return size;
   1763 }
   1764 
   1765 /*
   1766  * return the cached copy of the active config descriptor
   1767  */
   1768 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
   1769 {
   1770 	struct windows_device_priv *priv = _device_priv(dev);
   1771 
   1772 	if (priv->active_config == 0)
   1773 		return LIBUSB_ERROR_NOT_FOUND;
   1774 
   1775 	// config index is zero based
   1776 	return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
   1777 }
   1778 
   1779 static int windows_open(struct libusb_device_handle *dev_handle)
   1780 {
   1781 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1782 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   1783 
   1784 	if (priv->apib == NULL) {
   1785 		usbi_err(ctx, "program assertion failed - device is not initialized");
   1786 		return LIBUSB_ERROR_NO_DEVICE;
   1787 	}
   1788 
   1789 	return priv->apib->open(SUB_API_NOTSET, dev_handle);
   1790 }
   1791 
   1792 static void windows_close(struct libusb_device_handle *dev_handle)
   1793 {
   1794 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1795 
   1796 	priv->apib->close(SUB_API_NOTSET, dev_handle);
   1797 }
   1798 
   1799 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
   1800 {
   1801 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1802 
   1803 	if (priv->active_config == 0) {
   1804 		*config = 0;
   1805 		return LIBUSB_ERROR_NOT_FOUND;
   1806 	}
   1807 
   1808 	*config = priv->active_config;
   1809 	return LIBUSB_SUCCESS;
   1810 }
   1811 
   1812 /*
   1813  * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
   1814  * does not currently expose a service that allows higher-level drivers to set
   1815  * the configuration."
   1816  */
   1817 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
   1818 {
   1819 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1820 	int r = LIBUSB_SUCCESS;
   1821 
   1822 	if (config >= USB_MAXCONFIG)
   1823 		return LIBUSB_ERROR_INVALID_PARAM;
   1824 
   1825 	r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
   1826 		LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
   1827 		LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
   1828 		0, NULL, 0, 1000);
   1829 
   1830 	if (r == LIBUSB_SUCCESS) {
   1831 		priv->active_config = (uint8_t)config;
   1832 	}
   1833 	return r;
   1834 }
   1835 
   1836 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
   1837 {
   1838 	int r = LIBUSB_SUCCESS;
   1839 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1840 
   1841 	if (iface >= USB_MAXINTERFACES)
   1842 		return LIBUSB_ERROR_INVALID_PARAM;
   1843 
   1844 	safe_free(priv->usb_interface[iface].endpoint);
   1845 	priv->usb_interface[iface].nb_endpoints= 0;
   1846 
   1847 	r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
   1848 
   1849 	if (r == LIBUSB_SUCCESS) {
   1850 		r = windows_assign_endpoints(dev_handle, iface, 0);
   1851 	}
   1852 
   1853 	return r;
   1854 }
   1855 
   1856 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
   1857 {
   1858 	int r = LIBUSB_SUCCESS;
   1859 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1860 
   1861 	safe_free(priv->usb_interface[iface].endpoint);
   1862 	priv->usb_interface[iface].nb_endpoints= 0;
   1863 
   1864 	r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
   1865 
   1866 	if (r == LIBUSB_SUCCESS) {
   1867 		r = windows_assign_endpoints(dev_handle, iface, altsetting);
   1868 	}
   1869 
   1870 	return r;
   1871 }
   1872 
   1873 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
   1874 {
   1875 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1876 
   1877 	return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
   1878 }
   1879 
   1880 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
   1881 {
   1882 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1883 	return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
   1884 }
   1885 
   1886 static int windows_reset_device(struct libusb_device_handle *dev_handle)
   1887 {
   1888 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1889 	return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
   1890 }
   1891 
   1892 // The 3 functions below are unlikely to ever get supported on Windows
   1893 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
   1894 {
   1895 	return LIBUSB_ERROR_NOT_SUPPORTED;
   1896 }
   1897 
   1898 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
   1899 {
   1900 	return LIBUSB_ERROR_NOT_SUPPORTED;
   1901 }
   1902 
   1903 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
   1904 {
   1905 	return LIBUSB_ERROR_NOT_SUPPORTED;
   1906 }
   1907 
   1908 static void windows_destroy_device(struct libusb_device *dev)
   1909 {
   1910 	windows_device_priv_release(dev);
   1911 }
   1912 
   1913 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
   1914 {
   1915 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1916 
   1917 	usbi_free_fd(&transfer_priv->pollable_fd);
   1918 	safe_free(transfer_priv->hid_buffer);
   1919 	// When auto claim is in use, attempt to release the auto-claimed interface
   1920 	auto_release(itransfer);
   1921 }
   1922 
   1923 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
   1924 {
   1925 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1926 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   1927 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1928 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1929 	int r;
   1930 
   1931 	r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
   1932 	if (r != LIBUSB_SUCCESS) {
   1933 		return r;
   1934 	}
   1935 
   1936 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
   1937 		(short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
   1938 
   1939 	itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
   1940 	return LIBUSB_SUCCESS;
   1941 }
   1942 
   1943 static int submit_iso_transfer(struct usbi_transfer *itransfer)
   1944 {
   1945 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1946 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   1947 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1948 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1949 	int r;
   1950 
   1951 	r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
   1952 	if (r != LIBUSB_SUCCESS) {
   1953 		return r;
   1954 	}
   1955 
   1956 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
   1957 		(short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
   1958 
   1959 	itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
   1960 	return LIBUSB_SUCCESS;
   1961 }
   1962 
   1963 static int submit_control_transfer(struct usbi_transfer *itransfer)
   1964 {
   1965 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1966 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   1967 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1968 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1969 	int r;
   1970 
   1971 	r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
   1972 	if (r != LIBUSB_SUCCESS) {
   1973 		return r;
   1974 	}
   1975 
   1976 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
   1977 
   1978 	itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
   1979 	return LIBUSB_SUCCESS;
   1980 
   1981 }
   1982 
   1983 static int windows_submit_transfer(struct usbi_transfer *itransfer)
   1984 {
   1985 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1986 
   1987 	switch (transfer->type) {
   1988 	case LIBUSB_TRANSFER_TYPE_CONTROL:
   1989 		return submit_control_transfer(itransfer);
   1990 	case LIBUSB_TRANSFER_TYPE_BULK:
   1991 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   1992 		if (IS_XFEROUT(transfer) &&
   1993 		    transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
   1994 			return LIBUSB_ERROR_NOT_SUPPORTED;
   1995 		return submit_bulk_transfer(itransfer);
   1996 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   1997 		return submit_iso_transfer(itransfer);
   1998 	default:
   1999 		usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
   2000 		return LIBUSB_ERROR_INVALID_PARAM;
   2001 	}
   2002 }
   2003 
   2004 static int windows_abort_control(struct usbi_transfer *itransfer)
   2005 {
   2006 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2007 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2008 
   2009 	return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
   2010 }
   2011 
   2012 static int windows_abort_transfers(struct usbi_transfer *itransfer)
   2013 {
   2014 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2015 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2016 
   2017 	return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
   2018 }
   2019 
   2020 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
   2021 {
   2022 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2023 
   2024 	switch (transfer->type) {
   2025 	case LIBUSB_TRANSFER_TYPE_CONTROL:
   2026 		return windows_abort_control(itransfer);
   2027 	case LIBUSB_TRANSFER_TYPE_BULK:
   2028 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   2029 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   2030 		return windows_abort_transfers(itransfer);
   2031 	default:
   2032 		usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
   2033 		return LIBUSB_ERROR_INVALID_PARAM;
   2034 	}
   2035 }
   2036 
   2037 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
   2038 {
   2039 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2040 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2041 	int status, istatus;
   2042 
   2043 	usbi_dbg("handling I/O completion with errcode %d, size %d", io_result, io_size);
   2044 
   2045 	switch(io_result) {
   2046 	case NO_ERROR:
   2047 		status = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
   2048 		break;
   2049 	case ERROR_GEN_FAILURE:
   2050 		usbi_dbg("detected endpoint stall");
   2051 		status = LIBUSB_TRANSFER_STALL;
   2052 		break;
   2053 	case ERROR_SEM_TIMEOUT:
   2054 		usbi_dbg("detected semaphore timeout");
   2055 		status = LIBUSB_TRANSFER_TIMED_OUT;
   2056 		break;
   2057 	case ERROR_OPERATION_ABORTED:
   2058 		istatus = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
   2059 		if (istatus != LIBUSB_TRANSFER_COMPLETED) {
   2060 			usbi_dbg("Failed to copy partial data in aborted operation: %d", istatus);
   2061 		}
   2062 		if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
   2063 			usbi_dbg("detected timeout");
   2064 			status = LIBUSB_TRANSFER_TIMED_OUT;
   2065 		} else {
   2066 			usbi_dbg("detected operation aborted");
   2067 			status = LIBUSB_TRANSFER_CANCELLED;
   2068 		}
   2069 		break;
   2070 	default:
   2071 		usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error %d: %s", io_result, windows_error_str(0));
   2072 		status = LIBUSB_TRANSFER_ERROR;
   2073 		break;
   2074 	}
   2075 	windows_clear_transfer_priv(itransfer);	// Cancel polling
   2076 	usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
   2077 }
   2078 
   2079 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
   2080 {
   2081 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2082 
   2083 	switch (transfer->type) {
   2084 	case LIBUSB_TRANSFER_TYPE_CONTROL:
   2085 	case LIBUSB_TRANSFER_TYPE_BULK:
   2086 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   2087 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   2088 		windows_transfer_callback (itransfer, io_result, io_size);
   2089 		break;
   2090 	default:
   2091 		usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
   2092 	}
   2093 }
   2094 
   2095 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
   2096 {
   2097 	struct windows_transfer_priv* transfer_priv = NULL;
   2098 	POLL_NFDS_TYPE i = 0;
   2099 	bool found = false;
   2100 	struct usbi_transfer *transfer;
   2101 	DWORD io_size, io_result;
   2102 
   2103 	usbi_mutex_lock(&ctx->open_devs_lock);
   2104 	for (i = 0; i < nfds && num_ready > 0; i++) {
   2105 
   2106 		usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
   2107 
   2108 		if (!fds[i].revents) {
   2109 			continue;
   2110 		}
   2111 
   2112 		num_ready--;
   2113 
   2114 		// Because a Windows OVERLAPPED is used for poll emulation,
   2115 		// a pollable fd is created and stored with each transfer
   2116 		usbi_mutex_lock(&ctx->flying_transfers_lock);
   2117 		list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
   2118 			transfer_priv = usbi_transfer_get_os_priv(transfer);
   2119 			if (transfer_priv->pollable_fd.fd == fds[i].fd) {
   2120 				found = true;
   2121 				break;
   2122 			}
   2123 		}
   2124 		usbi_mutex_unlock(&ctx->flying_transfers_lock);
   2125 
   2126 		if (found) {
   2127 			// Handle async requests that completed synchronously first
   2128 			if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
   2129 				io_result = NO_ERROR;
   2130 				io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
   2131 			// Regular async overlapped
   2132 			} else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
   2133 				transfer_priv->pollable_fd.overlapped, &io_size, false)) {
   2134 				io_result = NO_ERROR;
   2135 			} else {
   2136 				io_result = GetLastError();
   2137 			}
   2138 			usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
   2139 			// let handle_callback free the event using the transfer wfd
   2140 			// If you don't use the transfer wfd, you run a risk of trying to free a
   2141 			// newly allocated wfd that took the place of the one from the transfer.
   2142 			windows_handle_callback(transfer, io_result, io_size);
   2143 		} else {
   2144 			usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
   2145 			usbi_mutex_unlock(&ctx->open_devs_lock);
   2146 			return LIBUSB_ERROR_NOT_FOUND;
   2147 		}
   2148 	}
   2149 
   2150 	usbi_mutex_unlock(&ctx->open_devs_lock);
   2151 	return LIBUSB_SUCCESS;
   2152 }
   2153 
   2154 /*
   2155  * Monotonic and real time functions
   2156  */
   2157 unsigned __stdcall windows_clock_gettime_threaded(void* param)
   2158 {
   2159 	LARGE_INTEGER hires_counter, li_frequency;
   2160 	LONG nb_responses;
   2161 	int timer_index;
   2162 
   2163 	// Init - find out if we have access to a monotonic (hires) timer
   2164 	if (!QueryPerformanceFrequency(&li_frequency)) {
   2165 		usbi_dbg("no hires timer available on this platform");
   2166 		hires_frequency = 0;
   2167 		hires_ticks_to_ps = UINT64_C(0);
   2168 	} else {
   2169 		hires_frequency = li_frequency.QuadPart;
   2170 		// The hires frequency can go as high as 4 GHz, so we'll use a conversion
   2171 		// to picoseconds to compute the tv_nsecs part in clock_gettime
   2172 		hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
   2173 		usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
   2174 	}
   2175 
   2176 	// Main loop - wait for requests
   2177 	while (1) {
   2178 		timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
   2179 		if ( (timer_index != 0) && (timer_index != 1) ) {
   2180 			usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
   2181 			continue;
   2182 		}
   2183 		if (request_count[timer_index] == 0) {
   2184 			// Request already handled
   2185 			ResetEvent(timer_request[timer_index]);
   2186 			// There's still a possiblity that a thread sends a request between the
   2187 			// time we test request_count[] == 0 and we reset the event, in which case
   2188 			// the request would be ignored. The simple solution to that is to test
   2189 			// request_count again and process requests if non zero.
   2190 			if (request_count[timer_index] == 0)
   2191 				continue;
   2192 		}
   2193 		switch (timer_index) {
   2194 		case 0:
   2195 			WaitForSingleObject(timer_mutex, INFINITE);
   2196 			// Requests to this thread are for hires always
   2197 			if (QueryPerformanceCounter(&hires_counter) != 0) {
   2198 				timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
   2199 				timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
   2200 			} else {
   2201 				// Fallback to real-time if we can't get monotonic value
   2202 				// Note that real-time clock does not wait on the mutex or this thread.
   2203 				windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
   2204 			}
   2205 			ReleaseMutex(timer_mutex);
   2206 
   2207 			nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
   2208 			if ( (nb_responses)
   2209 			  && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
   2210 				usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
   2211 			}
   2212 			continue;
   2213 		case 1: // time to quit
   2214 			usbi_dbg("timer thread quitting");
   2215 			return 0;
   2216 		}
   2217 	}
   2218 }
   2219 
   2220 static int windows_clock_gettime(int clk_id, struct timespec *tp)
   2221 {
   2222 	FILETIME filetime;
   2223 	ULARGE_INTEGER rtime;
   2224 	DWORD r;
   2225 	switch(clk_id) {
   2226 	case USBI_CLOCK_MONOTONIC:
   2227 		if (hires_frequency != 0) {
   2228 			while (1) {
   2229 				InterlockedIncrement((LONG*)&request_count[0]);
   2230 				SetEvent(timer_request[0]);
   2231 				r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
   2232 				switch(r) {
   2233 				case WAIT_OBJECT_0:
   2234 					WaitForSingleObject(timer_mutex, INFINITE);
   2235 					*tp = timer_tp;
   2236 					ReleaseMutex(timer_mutex);
   2237 					return LIBUSB_SUCCESS;
   2238 				case WAIT_TIMEOUT:
   2239 					usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
   2240 					break; // Retry until successful
   2241 				default:
   2242 					usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
   2243 					return LIBUSB_ERROR_OTHER;
   2244 				}
   2245 			}
   2246 		}
   2247 		// Fall through and return real-time if monotonic was not detected @ timer init
   2248 	case USBI_CLOCK_REALTIME:
   2249 		// We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
   2250 		// with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
   2251 		// Note however that our resolution is bounded by the Windows system time
   2252 		// functions and is at best of the order of 1 ms (or, usually, worse)
   2253 		GetSystemTimeAsFileTime(&filetime);
   2254 		rtime.LowPart = filetime.dwLowDateTime;
   2255 		rtime.HighPart = filetime.dwHighDateTime;
   2256 		rtime.QuadPart -= epoch_time;
   2257 		tp->tv_sec = (long)(rtime.QuadPart / 10000000);
   2258 		tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
   2259 		return LIBUSB_SUCCESS;
   2260 	default:
   2261 		return LIBUSB_ERROR_INVALID_PARAM;
   2262 	}
   2263 }
   2264 
   2265 
   2266 // NB: MSVC6 does not support named initializers.
   2267 const struct usbi_os_backend windows_backend = {
   2268 	"Windows",
   2269 	USBI_CAP_HAS_HID_ACCESS,
   2270 	windows_init,
   2271 	windows_exit,
   2272 
   2273 	windows_get_device_list,
   2274 	NULL,				/* hotplug_poll */
   2275 	windows_open,
   2276 	windows_close,
   2277 
   2278 	windows_get_device_descriptor,
   2279 	windows_get_active_config_descriptor,
   2280 	windows_get_config_descriptor,
   2281 	NULL,				/* get_config_descriptor_by_value() */
   2282 
   2283 	windows_get_configuration,
   2284 	windows_set_configuration,
   2285 	windows_claim_interface,
   2286 	windows_release_interface,
   2287 
   2288 	windows_set_interface_altsetting,
   2289 	windows_clear_halt,
   2290 	windows_reset_device,
   2291 
   2292 	windows_kernel_driver_active,
   2293 	windows_detach_kernel_driver,
   2294 	windows_attach_kernel_driver,
   2295 
   2296 	windows_destroy_device,
   2297 
   2298 	windows_submit_transfer,
   2299 	windows_cancel_transfer,
   2300 	windows_clear_transfer_priv,
   2301 
   2302 	windows_handle_events,
   2303 
   2304 	windows_clock_gettime,
   2305 #if defined(USBI_TIMERFD_AVAILABLE)
   2306 	NULL,
   2307 #endif
   2308 	sizeof(struct windows_device_priv),
   2309 	sizeof(struct windows_device_handle_priv),
   2310 	sizeof(struct windows_transfer_priv),
   2311 	0,
   2312 };
   2313 
   2314 
   2315 /*
   2316  * USB API backends
   2317  */
   2318 static int unsupported_init(int sub_api, struct libusb_context *ctx) {
   2319 	return LIBUSB_SUCCESS;
   2320 }
   2321 static int unsupported_exit(int sub_api) {
   2322 	return LIBUSB_SUCCESS;
   2323 }
   2324 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle) {
   2325 	PRINT_UNSUPPORTED_API(open);
   2326 }
   2327 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle) {
   2328 	usbi_dbg("unsupported API call for 'close'");
   2329 }
   2330 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
   2331 	PRINT_UNSUPPORTED_API(configure_endpoints);
   2332 }
   2333 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
   2334 	PRINT_UNSUPPORTED_API(claim_interface);
   2335 }
   2336 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) {
   2337 	PRINT_UNSUPPORTED_API(set_interface_altsetting);
   2338 }
   2339 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
   2340 	PRINT_UNSUPPORTED_API(release_interface);
   2341 }
   2342 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) {
   2343 	PRINT_UNSUPPORTED_API(clear_halt);
   2344 }
   2345 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle) {
   2346 	PRINT_UNSUPPORTED_API(reset_device);
   2347 }
   2348 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
   2349 	PRINT_UNSUPPORTED_API(submit_bulk_transfer);
   2350 }
   2351 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
   2352 	PRINT_UNSUPPORTED_API(submit_iso_transfer);
   2353 }
   2354 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) {
   2355 	PRINT_UNSUPPORTED_API(submit_control_transfer);
   2356 }
   2357 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer) {
   2358 	PRINT_UNSUPPORTED_API(abort_control);
   2359 }
   2360 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer) {
   2361 	PRINT_UNSUPPORTED_API(abort_transfers);
   2362 }
   2363 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
   2364 	PRINT_UNSUPPORTED_API(copy_transfer_data);
   2365 }
   2366 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
   2367 	return LIBUSB_SUCCESS;
   2368 }
   2369 // These names must be uppercase
   2370 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB"};
   2371 const char* composite_driver_names[] = {"USBCCGP"};
   2372 const char* winusbx_driver_names[] = WINUSBX_DRV_NAMES;
   2373 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
   2374 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
   2375 	{
   2376 		USB_API_UNSUPPORTED,
   2377 		"Unsupported API",
   2378 		NULL,
   2379 		0,
   2380 		unsupported_init,
   2381 		unsupported_exit,
   2382 		unsupported_open,
   2383 		unsupported_close,
   2384 		unsupported_configure_endpoints,
   2385 		unsupported_claim_interface,
   2386 		unsupported_set_interface_altsetting,
   2387 		unsupported_release_interface,
   2388 		unsupported_clear_halt,
   2389 		unsupported_reset_device,
   2390 		unsupported_submit_bulk_transfer,
   2391 		unsupported_submit_iso_transfer,
   2392 		unsupported_submit_control_transfer,
   2393 		unsupported_abort_control,
   2394 		unsupported_abort_transfers,
   2395 		unsupported_copy_transfer_data,
   2396 	}, {
   2397 		USB_API_HUB,
   2398 		"HUB API",
   2399 		hub_driver_names,
   2400 		ARRAYSIZE(hub_driver_names),
   2401 		unsupported_init,
   2402 		unsupported_exit,
   2403 		unsupported_open,
   2404 		unsupported_close,
   2405 		unsupported_configure_endpoints,
   2406 		unsupported_claim_interface,
   2407 		unsupported_set_interface_altsetting,
   2408 		unsupported_release_interface,
   2409 		unsupported_clear_halt,
   2410 		unsupported_reset_device,
   2411 		unsupported_submit_bulk_transfer,
   2412 		unsupported_submit_iso_transfer,
   2413 		unsupported_submit_control_transfer,
   2414 		unsupported_abort_control,
   2415 		unsupported_abort_transfers,
   2416 		unsupported_copy_transfer_data,
   2417 	}, {
   2418 		USB_API_COMPOSITE,
   2419 		"Composite API",
   2420 		composite_driver_names,
   2421 		ARRAYSIZE(composite_driver_names),
   2422 		composite_init,
   2423 		composite_exit,
   2424 		composite_open,
   2425 		composite_close,
   2426 		common_configure_endpoints,
   2427 		composite_claim_interface,
   2428 		composite_set_interface_altsetting,
   2429 		composite_release_interface,
   2430 		composite_clear_halt,
   2431 		composite_reset_device,
   2432 		composite_submit_bulk_transfer,
   2433 		composite_submit_iso_transfer,
   2434 		composite_submit_control_transfer,
   2435 		composite_abort_control,
   2436 		composite_abort_transfers,
   2437 		composite_copy_transfer_data,
   2438 	}, {
   2439 		USB_API_WINUSBX,
   2440 		"WinUSB-like APIs",
   2441 		winusbx_driver_names,
   2442 		ARRAYSIZE(winusbx_driver_names),
   2443 		winusbx_init,
   2444 		winusbx_exit,
   2445 		winusbx_open,
   2446 		winusbx_close,
   2447 		winusbx_configure_endpoints,
   2448 		winusbx_claim_interface,
   2449 		winusbx_set_interface_altsetting,
   2450 		winusbx_release_interface,
   2451 		winusbx_clear_halt,
   2452 		winusbx_reset_device,
   2453 		winusbx_submit_bulk_transfer,
   2454 		unsupported_submit_iso_transfer,
   2455 		winusbx_submit_control_transfer,
   2456 		winusbx_abort_control,
   2457 		winusbx_abort_transfers,
   2458 		winusbx_copy_transfer_data,
   2459 	}, {
   2460 		USB_API_HID,
   2461 		"HID API",
   2462 		hid_driver_names,
   2463 		ARRAYSIZE(hid_driver_names),
   2464 		hid_init,
   2465 		hid_exit,
   2466 		hid_open,
   2467 		hid_close,
   2468 		common_configure_endpoints,
   2469 		hid_claim_interface,
   2470 		hid_set_interface_altsetting,
   2471 		hid_release_interface,
   2472 		hid_clear_halt,
   2473 		hid_reset_device,
   2474 		hid_submit_bulk_transfer,
   2475 		unsupported_submit_iso_transfer,
   2476 		hid_submit_control_transfer,
   2477 		hid_abort_transfers,
   2478 		hid_abort_transfers,
   2479 		hid_copy_transfer_data,
   2480 	},
   2481 };
   2482 
   2483 
   2484 /*
   2485  * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
   2486  */
   2487 #define WinUSBX_Set(fn) do { if (native_winusb) WinUSBX[i].fn = (WinUsb_##fn##_t) GetProcAddress(h, "WinUsb_" #fn); \
   2488 	else pLibK_GetProcAddress((PVOID*)&WinUSBX[i].fn, i, KUSB_FNID_##fn); } while (0)
   2489 
   2490 static int winusbx_init(int sub_api, struct libusb_context *ctx)
   2491 {
   2492 	HMODULE h = NULL;
   2493 	bool native_winusb = false;
   2494 	int i;
   2495 	KLIB_VERSION LibK_Version;
   2496 	LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
   2497 	LibK_GetVersion_t pLibK_GetVersion = NULL;
   2498 
   2499 	h = GetModuleHandleA("libusbK");
   2500 	if (h == NULL) {
   2501 		h = LoadLibraryA("libusbK");
   2502 	}
   2503 	if (h == NULL) {
   2504 		usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
   2505 		h = GetModuleHandleA("WinUSB");
   2506 		if (h == NULL) {
   2507 			h = LoadLibraryA("WinUSB");
   2508 		}		if (h == NULL) {
   2509 			usbi_warn(ctx, "WinUSB DLL is not available either,\n"
   2510 				"you will not be able to access devices outside of enumeration");
   2511 			return LIBUSB_ERROR_NOT_FOUND;
   2512 		}
   2513 	} else {
   2514 		usbi_dbg("using libusbK DLL for universal access");
   2515 		pLibK_GetVersion = (LibK_GetVersion_t) GetProcAddress(h, "LibK_GetVersion");
   2516 		if (pLibK_GetVersion != NULL) {
   2517 			pLibK_GetVersion(&LibK_Version);
   2518 			usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
   2519 				LibK_Version.Micro, LibK_Version.Nano);
   2520 		}
   2521 		pLibK_GetProcAddress = (LibK_GetProcAddress_t) GetProcAddress(h, "LibK_GetProcAddress");
   2522 		if (pLibK_GetProcAddress == NULL) {
   2523 			usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
   2524 			return LIBUSB_ERROR_NOT_FOUND;
   2525 		}
   2526 	}
   2527 	native_winusb = (pLibK_GetProcAddress == NULL);
   2528 	for (i=SUB_API_LIBUSBK; i<SUB_API_MAX; i++) {
   2529 		WinUSBX_Set(AbortPipe);
   2530 		WinUSBX_Set(ControlTransfer);
   2531 		WinUSBX_Set(FlushPipe);
   2532 		WinUSBX_Set(Free);
   2533 		WinUSBX_Set(GetAssociatedInterface);
   2534 		WinUSBX_Set(GetCurrentAlternateSetting);
   2535 		WinUSBX_Set(GetDescriptor);
   2536 		WinUSBX_Set(GetOverlappedResult);
   2537 		WinUSBX_Set(GetPipePolicy);
   2538 		WinUSBX_Set(GetPowerPolicy);
   2539 		WinUSBX_Set(Initialize);
   2540 		WinUSBX_Set(QueryDeviceInformation);
   2541 		WinUSBX_Set(QueryInterfaceSettings);
   2542 		WinUSBX_Set(QueryPipe);
   2543 		WinUSBX_Set(ReadPipe);
   2544 		WinUSBX_Set(ResetPipe);
   2545 		WinUSBX_Set(SetCurrentAlternateSetting);
   2546 		WinUSBX_Set(SetPipePolicy);
   2547 		WinUSBX_Set(SetPowerPolicy);
   2548 		WinUSBX_Set(WritePipe);
   2549 		if (!native_winusb) {
   2550 			WinUSBX_Set(ResetDevice);
   2551 		}
   2552 		if (WinUSBX[i].Initialize != NULL) {
   2553 			WinUSBX[i].initialized = true;
   2554 			usbi_dbg("initalized sub API %s", sub_api_name[i]);
   2555 		} else {
   2556 			usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
   2557 			WinUSBX[i].initialized = false;
   2558 		}
   2559 	}
   2560 	return LIBUSB_SUCCESS;
   2561 }
   2562 
   2563 static int winusbx_exit(int sub_api)
   2564 {
   2565 	return LIBUSB_SUCCESS;
   2566 }
   2567 
   2568 // NB: open and close must ensure that they only handle interface of
   2569 // the right API type, as these functions can be called wholesale from
   2570 // composite_open(), with interfaces belonging to different APIs
   2571 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
   2572 {
   2573 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2574 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2575 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2576 
   2577 	HANDLE file_handle;
   2578 	int i;
   2579 
   2580 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2581 
   2582 	// WinUSB requires a seperate handle for each interface
   2583 	for (i = 0; i < USB_MAXINTERFACES; i++) {
   2584 		if ( (priv->usb_interface[i].path != NULL)
   2585 		  && (priv->usb_interface[i].apib->id == USB_API_WINUSBX) ) {
   2586 			file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
   2587 				NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
   2588 			if (file_handle == INVALID_HANDLE_VALUE) {
   2589 				usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
   2590 				switch(GetLastError()) {
   2591 				case ERROR_FILE_NOT_FOUND:	// The device was disconnected
   2592 					return LIBUSB_ERROR_NO_DEVICE;
   2593 				case ERROR_ACCESS_DENIED:
   2594 					return LIBUSB_ERROR_ACCESS;
   2595 				default:
   2596 					return LIBUSB_ERROR_IO;
   2597 				}
   2598 			}
   2599 			handle_priv->interface_handle[i].dev_handle = file_handle;
   2600 		}
   2601 	}
   2602 
   2603 	return LIBUSB_SUCCESS;
   2604 }
   2605 
   2606 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
   2607 {
   2608 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2609 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2610 	HANDLE file_handle;
   2611 	int i;
   2612 
   2613 	if (sub_api == SUB_API_NOTSET)
   2614 		sub_api = priv->sub_api;
   2615 	if (!WinUSBX[sub_api].initialized)
   2616 		return;
   2617 
   2618 	for (i = 0; i < USB_MAXINTERFACES; i++) {
   2619 		if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
   2620 			file_handle = handle_priv->interface_handle[i].dev_handle;
   2621 			if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
   2622 				CloseHandle(file_handle);
   2623 			}
   2624 		}
   2625 	}
   2626 }
   2627 
   2628 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   2629 {
   2630 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2631 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2632 	HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
   2633 	UCHAR policy;
   2634 	ULONG timeout = 0;
   2635 	uint8_t endpoint_address;
   2636 	int i;
   2637 
   2638 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2639 
   2640 	// With handle and enpoints set (in parent), we can setup the default pipe properties
   2641 	// see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
   2642 	for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
   2643 		endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
   2644 		if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
   2645 			PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
   2646 			usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
   2647 		}
   2648 		if ((i == -1) || (sub_api == SUB_API_LIBUSB0)) {
   2649 			continue;	// Other policies don't apply to control endpoint or libusb0
   2650 		}
   2651 		policy = false;
   2652 		if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
   2653 			SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
   2654 			usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
   2655 		}
   2656 		if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
   2657 			IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
   2658 			usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
   2659 		}
   2660 		policy = true;
   2661 		/* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
   2662 		   https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
   2663 		if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
   2664 			ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
   2665 			usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
   2666 		}
   2667 		if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
   2668 			AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
   2669 			usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
   2670 		}
   2671 	}
   2672 
   2673 	return LIBUSB_SUCCESS;
   2674 }
   2675 
   2676 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   2677 {
   2678 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2679 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2680 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2681 	bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
   2682 	HANDLE file_handle, winusb_handle;
   2683 	DWORD err;
   2684 	int i;
   2685 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
   2686 	HDEVINFO dev_info = INVALID_HANDLE_VALUE;
   2687 	SP_DEVINFO_DATA dev_info_data;
   2688 	char* dev_path_no_guid = NULL;
   2689 	char filter_path[] = "\\\\.\\libusb0-0000";
   2690 	bool found_filter = false;
   2691 
   2692 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2693 
   2694 	// If the device is composite, but using the default Windows composite parent driver (usbccgp)
   2695 	// or if it's the first WinUSB-like interface, we get a handle through Initialize().
   2696 	if ((is_using_usbccgp) || (iface == 0)) {
   2697 		// composite device (independent interfaces) or interface 0
   2698 		file_handle = handle_priv->interface_handle[iface].dev_handle;
   2699 		if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
   2700 			return LIBUSB_ERROR_NOT_FOUND;
   2701 		}
   2702 
   2703 		if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
   2704 			handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
   2705 			err = GetLastError();
   2706 			switch(err) {
   2707 			case ERROR_BAD_COMMAND:
   2708 				// The device was disconnected
   2709 				usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
   2710 				return LIBUSB_ERROR_NO_DEVICE;
   2711 			default:
   2712 				// it may be that we're using the libusb0 filter driver.
   2713 				// TODO: can we move this whole business into the K/0 DLL?
   2714 				for (i = 0; ; i++) {
   2715 					safe_free(dev_interface_details);
   2716 					safe_free(dev_path_no_guid);
   2717 					dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
   2718 					if ((found_filter) || (dev_interface_details == NULL)) {
   2719 						break;
   2720 					}
   2721 					// ignore GUID part
   2722 					dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
   2723 					if (safe_strncmp(dev_path_no_guid, priv->usb_interface[iface].path, safe_strlen(dev_path_no_guid)) == 0) {
   2724 						file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
   2725 							NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
   2726 						if (file_handle == INVALID_HANDLE_VALUE) {
   2727 							usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
   2728 						} else {
   2729 							WinUSBX[sub_api].Free(winusb_handle);
   2730 							if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
   2731 								continue;
   2732 							}
   2733 							found_filter = true;
   2734 							break;
   2735 						}
   2736 					}
   2737 				}
   2738 				if (!found_filter) {
   2739 					usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
   2740 					return LIBUSB_ERROR_ACCESS;
   2741 				}
   2742 			}
   2743 		}
   2744 		handle_priv->interface_handle[iface].api_handle = winusb_handle;
   2745 	} else {
   2746 		// For all other interfaces, use GetAssociatedInterface()
   2747 		winusb_handle = handle_priv->interface_handle[0].api_handle;
   2748 		// It is a requirement for multiple interface devices on Windows that, to you
   2749 		// must first claim the first interface before you claim the others
   2750 		if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
   2751 			file_handle = handle_priv->interface_handle[0].dev_handle;
   2752 			if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
   2753 				handle_priv->interface_handle[0].api_handle = winusb_handle;
   2754 				usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
   2755 			} else {
   2756 				usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
   2757 				return LIBUSB_ERROR_ACCESS;
   2758 			}
   2759 		}
   2760 		if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
   2761 			&handle_priv->interface_handle[iface].api_handle)) {
   2762 			handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
   2763 			switch(GetLastError()) {
   2764 			case ERROR_NO_MORE_ITEMS:   // invalid iface
   2765 				return LIBUSB_ERROR_NOT_FOUND;
   2766 			case ERROR_BAD_COMMAND:     // The device was disconnected
   2767 				return LIBUSB_ERROR_NO_DEVICE;
   2768 			case ERROR_ALREADY_EXISTS:  // already claimed
   2769 				return LIBUSB_ERROR_BUSY;
   2770 			default:
   2771 				usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
   2772 				return LIBUSB_ERROR_ACCESS;
   2773 			}
   2774 		}
   2775 	}
   2776 	usbi_dbg("claimed interface %d", iface);
   2777 	handle_priv->active_interface = iface;
   2778 
   2779 	return LIBUSB_SUCCESS;
   2780 }
   2781 
   2782 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   2783 {
   2784 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2785 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2786 	HANDLE winusb_handle;
   2787 
   2788 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2789 
   2790 	winusb_handle = handle_priv->interface_handle[iface].api_handle;
   2791 	if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
   2792 		return LIBUSB_ERROR_NOT_FOUND;
   2793 	}
   2794 
   2795 	WinUSBX[sub_api].Free(winusb_handle);
   2796 	handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
   2797 
   2798 	return LIBUSB_SUCCESS;
   2799 }
   2800 
   2801 /*
   2802  * Return the first valid interface (of the same API type), for control transfers
   2803  */
   2804 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
   2805 {
   2806 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2807 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2808 	int i;
   2809 
   2810 	if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
   2811 		usbi_dbg("unsupported API ID");
   2812 		return -1;
   2813 	}
   2814 
   2815 	for (i=0; i<USB_MAXINTERFACES; i++) {
   2816 		if ( (handle_priv->interface_handle[i].dev_handle != 0)
   2817 		  && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
   2818 		  && (handle_priv->interface_handle[i].api_handle != 0)
   2819 		  && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
   2820 		  && (priv->usb_interface[i].apib->id == api_id) ) {
   2821 			return i;
   2822 		}
   2823 	}
   2824 	return -1;
   2825 }
   2826 
   2827 /*
   2828  * Lookup interface by endpoint address. -1 if not found
   2829  */
   2830 static int interface_by_endpoint(struct windows_device_priv *priv,
   2831 	struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
   2832 {
   2833 	int i, j;
   2834 	for (i=0; i<USB_MAXINTERFACES; i++) {
   2835 		if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
   2836 			continue;
   2837 		if (handle_priv->interface_handle[i].api_handle == 0)
   2838 			continue;
   2839 		if (priv->usb_interface[i].endpoint == NULL)
   2840 			continue;
   2841 		for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
   2842 			if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
   2843 				return i;
   2844 			}
   2845 		}
   2846 	}
   2847 	return -1;
   2848 }
   2849 
   2850 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
   2851 {
   2852 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2853 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2854 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2855 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   2856 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(
   2857 		transfer->dev_handle);
   2858 	WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
   2859 	ULONG size;
   2860 	HANDLE winusb_handle;
   2861 	int current_interface;
   2862 	struct winfd wfd;
   2863 
   2864 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2865 
   2866 	transfer_priv->pollable_fd = INVALID_WINFD;
   2867 	size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
   2868 
   2869 	if (size > MAX_CTRL_BUFFER_LENGTH)
   2870 		return LIBUSB_ERROR_INVALID_PARAM;
   2871 
   2872 	current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
   2873 	if (current_interface < 0) {
   2874 		if (auto_claim(transfer, &current_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS) {
   2875 			return LIBUSB_ERROR_NOT_FOUND;
   2876 		}
   2877 	}
   2878 
   2879 	usbi_dbg("will use interface %d", current_interface);
   2880 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   2881 
   2882 	wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
   2883 	// Always use the handle returned from usbi_create_fd (wfd.handle)
   2884 	if (wfd.fd < 0) {
   2885 		return LIBUSB_ERROR_NO_MEM;
   2886 	}
   2887 
   2888 	// Sending of set configuration control requests from WinUSB creates issues
   2889 	if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
   2890 	  && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
   2891 		if (setup->value != priv->active_config) {
   2892 			usbi_warn(ctx, "cannot set configuration other than the default one");
   2893 			usbi_free_fd(&wfd);
   2894 			return LIBUSB_ERROR_INVALID_PARAM;
   2895 		}
   2896 		wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   2897 		wfd.overlapped->InternalHigh = 0;
   2898 	} else {
   2899 		if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
   2900 			if(GetLastError() != ERROR_IO_PENDING) {
   2901 				usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
   2902 				usbi_free_fd(&wfd);
   2903 				return LIBUSB_ERROR_IO;
   2904 			}
   2905 		} else {
   2906 			wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   2907 			wfd.overlapped->InternalHigh = (DWORD)size;
   2908 		}
   2909 	}
   2910 
   2911 	// Use priv_transfer to store data needed for async polling
   2912 	transfer_priv->pollable_fd = wfd;
   2913 	transfer_priv->interface_number = (uint8_t)current_interface;
   2914 
   2915 	return LIBUSB_SUCCESS;
   2916 }
   2917 
   2918 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
   2919 {
   2920 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2921 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2922 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2923 	HANDLE winusb_handle;
   2924 
   2925 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2926 
   2927 	if (altsetting > 255) {
   2928 		return LIBUSB_ERROR_INVALID_PARAM;
   2929 	}
   2930 
   2931 	winusb_handle = handle_priv->interface_handle[iface].api_handle;
   2932 	if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
   2933 		usbi_err(ctx, "interface must be claimed first");
   2934 		return LIBUSB_ERROR_NOT_FOUND;
   2935 	}
   2936 
   2937 	if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
   2938 		usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
   2939 		return LIBUSB_ERROR_IO;
   2940 	}
   2941 
   2942 	return LIBUSB_SUCCESS;
   2943 }
   2944 
   2945 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
   2946 {
   2947 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2948 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2949 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   2950 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   2951 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2952 	HANDLE winusb_handle;
   2953 	bool ret;
   2954 	int current_interface;
   2955 	struct winfd wfd;
   2956 
   2957 	CHECK_WINUSBX_AVAILABLE(sub_api);
   2958 
   2959 	transfer_priv->pollable_fd = INVALID_WINFD;
   2960 
   2961 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   2962 	if (current_interface < 0) {
   2963 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   2964 		return LIBUSB_ERROR_NOT_FOUND;
   2965 	}
   2966 
   2967 	usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
   2968 
   2969 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   2970 
   2971 	wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
   2972 	// Always use the handle returned from usbi_create_fd (wfd.handle)
   2973 	if (wfd.fd < 0) {
   2974 		return LIBUSB_ERROR_NO_MEM;
   2975 	}
   2976 
   2977 	if (IS_XFERIN(transfer)) {
   2978 		usbi_dbg("reading %d bytes", transfer->length);
   2979 		ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
   2980 	} else {
   2981 		usbi_dbg("writing %d bytes", transfer->length);
   2982 		ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
   2983 	}
   2984 	if (!ret) {
   2985 		if(GetLastError() != ERROR_IO_PENDING) {
   2986 			usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
   2987 			usbi_free_fd(&wfd);
   2988 			return LIBUSB_ERROR_IO;
   2989 		}
   2990 	} else {
   2991 		wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   2992 		wfd.overlapped->InternalHigh = (DWORD)transfer->length;
   2993 	}
   2994 
   2995 	transfer_priv->pollable_fd = wfd;
   2996 	transfer_priv->interface_number = (uint8_t)current_interface;
   2997 
   2998 	return LIBUSB_SUCCESS;
   2999 }
   3000 
   3001 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
   3002 {
   3003 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   3004 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   3005 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   3006 	HANDLE winusb_handle;
   3007 	int current_interface;
   3008 
   3009 	CHECK_WINUSBX_AVAILABLE(sub_api);
   3010 
   3011 	current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
   3012 	if (current_interface < 0) {
   3013 		usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
   3014 		return LIBUSB_ERROR_NOT_FOUND;
   3015 	}
   3016 
   3017 	usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
   3018 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   3019 
   3020 	if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
   3021 		usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
   3022 		return LIBUSB_ERROR_NO_DEVICE;
   3023 	}
   3024 
   3025 	return LIBUSB_SUCCESS;
   3026 }
   3027 
   3028 /*
   3029  * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
   3030  * through testing as well):
   3031  * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
   3032  * the control transfer using CancelIo"
   3033  */
   3034 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
   3035 {
   3036 	// Cancelling of the I/O is done in the parent
   3037 	return LIBUSB_SUCCESS;
   3038 }
   3039 
   3040 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
   3041 {
   3042 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   3043 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   3044 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   3045 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   3046 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   3047 	HANDLE winusb_handle;
   3048 	int current_interface;
   3049 
   3050 	CHECK_WINUSBX_AVAILABLE(sub_api);
   3051 
   3052 	current_interface = transfer_priv->interface_number;
   3053 	if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
   3054 		usbi_err(ctx, "program assertion failed: invalid interface_number");
   3055 		return LIBUSB_ERROR_NOT_FOUND;
   3056 	}
   3057 	usbi_dbg("will use interface %d", current_interface);
   3058 
   3059 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   3060 
   3061 	if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
   3062 		usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
   3063 		return LIBUSB_ERROR_NO_DEVICE;
   3064 	}
   3065 
   3066 	return LIBUSB_SUCCESS;
   3067 }
   3068 
   3069 /*
   3070  * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
   3071  * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
   3072  * "WinUSB does not support host-initiated reset port and cycle port operations" and
   3073  * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
   3074  * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
   3075  * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
   3076  */
   3077 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
   3078 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
   3079 {
   3080 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   3081 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   3082 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   3083 	struct winfd wfd;
   3084 	HANDLE winusb_handle;
   3085 	int i, j;
   3086 
   3087 	CHECK_WINUSBX_AVAILABLE(sub_api);
   3088 
   3089 	// Reset any available pipe (except control)
   3090 	for (i=0; i<USB_MAXINTERFACES; i++) {
   3091 		winusb_handle = handle_priv->interface_handle[i].api_handle;
   3092 		for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
   3093 		{
   3094 			// Cancel any pollable I/O
   3095 			usbi_remove_pollfd(ctx, wfd.fd);
   3096 			usbi_free_fd(&wfd);
   3097 			wfd = handle_to_winfd(winusb_handle);
   3098 		}
   3099 
   3100 		if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
   3101 			for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
   3102 				usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
   3103 				if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
   3104 					usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
   3105 						priv->usb_interface[i].endpoint[j], windows_error_str(0));
   3106 				}
   3107 				// FlushPipe seems to fail on OUT pipes
   3108 				if (IS_EPIN(priv->usb_interface[i].endpoint[j])
   3109 				  && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
   3110 					usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
   3111 						priv->usb_interface[i].endpoint[j], windows_error_str(0));
   3112 				}
   3113 				if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
   3114 					usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
   3115 						priv->usb_interface[i].endpoint[j], windows_error_str(0));
   3116 				}
   3117 			}
   3118 		}
   3119 	}
   3120 
   3121 	// libusbK & libusb0 have the ability to issue an actual device reset
   3122 	if (WinUSBX[sub_api].ResetDevice != NULL) {
   3123 		winusb_handle = handle_priv->interface_handle[0].api_handle;
   3124 		if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
   3125 			WinUSBX[sub_api].ResetDevice(winusb_handle);
   3126 		}
   3127 	}
   3128 	return LIBUSB_SUCCESS;
   3129 }
   3130 
   3131 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
   3132 {
   3133 	itransfer->transferred += io_size;
   3134 	return LIBUSB_TRANSFER_COMPLETED;
   3135 }
   3136 
   3137 /*
   3138  * Internal HID Support functions (from libusb-win32)
   3139  * Note that functions that complete data transfer synchronously must return
   3140  * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
   3141  */
   3142 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
   3143 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
   3144 
   3145 static int _hid_wcslen(WCHAR *str)
   3146 {
   3147 	int i = 0;
   3148 	while (str[i] && (str[i] != 0x409)) {
   3149 		i++;
   3150 	}
   3151 	return i;
   3152 }
   3153 
   3154 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
   3155 {
   3156 	struct libusb_device_descriptor d;
   3157 
   3158 	d.bLength = LIBUSB_DT_DEVICE_SIZE;
   3159 	d.bDescriptorType = LIBUSB_DT_DEVICE;
   3160 	d.bcdUSB = 0x0200; /* 2.00 */
   3161 	d.bDeviceClass = 0;
   3162 	d.bDeviceSubClass = 0;
   3163 	d.bDeviceProtocol = 0;
   3164 	d.bMaxPacketSize0 = 64; /* fix this! */
   3165 	d.idVendor = (uint16_t)dev->vid;
   3166 	d.idProduct = (uint16_t)dev->pid;
   3167 	d.bcdDevice = 0x0100;
   3168 	d.iManufacturer = dev->string_index[0];
   3169 	d.iProduct = dev->string_index[1];
   3170 	d.iSerialNumber = dev->string_index[2];
   3171 	d.bNumConfigurations = 1;
   3172 
   3173 	if (*size > LIBUSB_DT_DEVICE_SIZE)
   3174 		*size = LIBUSB_DT_DEVICE_SIZE;
   3175 	memcpy(data, &d, *size);
   3176 	return LIBUSB_COMPLETED;
   3177 }
   3178 
   3179 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
   3180 {
   3181 	char num_endpoints = 0;
   3182 	size_t config_total_len = 0;
   3183 	char tmp[HID_MAX_CONFIG_DESC_SIZE];
   3184 	struct libusb_config_descriptor *cd;
   3185 	struct libusb_interface_descriptor *id;
   3186 	struct libusb_hid_descriptor *hd;
   3187 	struct libusb_endpoint_descriptor *ed;
   3188 	size_t tmp_size;
   3189 
   3190 	if (dev->input_report_size)
   3191 		num_endpoints++;
   3192 	if (dev->output_report_size)
   3193 		num_endpoints++;
   3194 
   3195 	config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
   3196 		+ LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
   3197 
   3198 
   3199 	cd = (struct libusb_config_descriptor *)tmp;
   3200 	id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
   3201 	hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
   3202 		+ LIBUSB_DT_INTERFACE_SIZE);
   3203 	ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
   3204 		+ LIBUSB_DT_INTERFACE_SIZE
   3205 		+ LIBUSB_DT_HID_SIZE);
   3206 
   3207 	cd->bLength = LIBUSB_DT_CONFIG_SIZE;
   3208 	cd->bDescriptorType = LIBUSB_DT_CONFIG;
   3209 	cd->wTotalLength = (uint16_t) config_total_len;
   3210 	cd->bNumInterfaces = 1;
   3211 	cd->bConfigurationValue = 1;
   3212 	cd->iConfiguration = 0;
   3213 	cd->bmAttributes = 1 << 7; /* bus powered */
   3214 	cd->MaxPower = 50;
   3215 
   3216 	id->bLength = LIBUSB_DT_INTERFACE_SIZE;
   3217 	id->bDescriptorType = LIBUSB_DT_INTERFACE;
   3218 	id->bInterfaceNumber = 0;
   3219 	id->bAlternateSetting = 0;
   3220 	id->bNumEndpoints = num_endpoints;
   3221 	id->bInterfaceClass = 3;
   3222 	id->bInterfaceSubClass = 0;
   3223 	id->bInterfaceProtocol = 0;
   3224 	id->iInterface = 0;
   3225 
   3226 	tmp_size = LIBUSB_DT_HID_SIZE;
   3227 	_hid_get_hid_descriptor(dev, hd, &tmp_size);
   3228 
   3229 	if (dev->input_report_size) {
   3230 		ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
   3231 		ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
   3232 		ed->bEndpointAddress = HID_IN_EP;
   3233 		ed->bmAttributes = 3;
   3234 		ed->wMaxPacketSize = dev->input_report_size - 1;
   3235 		ed->bInterval = 10;
   3236 		ed = (struct libusb_endpoint_descriptor *)((char*)ed + LIBUSB_DT_ENDPOINT_SIZE);
   3237 	}
   3238 
   3239 	if (dev->output_report_size) {
   3240 		ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
   3241 		ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
   3242 		ed->bEndpointAddress = HID_OUT_EP;
   3243 		ed->bmAttributes = 3;
   3244 		ed->wMaxPacketSize = dev->output_report_size - 1;
   3245 		ed->bInterval = 10;
   3246 	}
   3247 
   3248 	if (*size > config_total_len)
   3249 		*size = config_total_len;
   3250 	memcpy(data, tmp, *size);
   3251 	return LIBUSB_COMPLETED;
   3252 }
   3253 
   3254 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int _index,
   3255 									  void *data, size_t *size)
   3256 {
   3257 	void *tmp = NULL;
   3258 	size_t tmp_size = 0;
   3259 	int i;
   3260 
   3261 	/* language ID, EN-US */
   3262 	char string_langid[] = {
   3263 		0x09,
   3264 		0x04
   3265 	};
   3266 
   3267 	if ((*size < 2) || (*size > 255)) {
   3268 		return LIBUSB_ERROR_OVERFLOW;
   3269 	}
   3270 
   3271 	if (_index == 0) {
   3272 		tmp = string_langid;
   3273 		tmp_size = sizeof(string_langid)+2;
   3274 	} else {
   3275 		for (i=0; i<3; i++) {
   3276 			if (_index == (dev->string_index[i])) {
   3277 				tmp = dev->string[i];
   3278 				tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
   3279 				break;
   3280 			}
   3281 		}
   3282 		if (i == 3) {	// not found
   3283 			return LIBUSB_ERROR_INVALID_PARAM;
   3284 		}
   3285 	}
   3286 
   3287 	if(!tmp_size) {
   3288 		return LIBUSB_ERROR_INVALID_PARAM;
   3289 	}
   3290 
   3291 	if (tmp_size < *size) {
   3292 		*size = tmp_size;
   3293 	}
   3294 	// 2 byte header
   3295 	((uint8_t*)data)[0] = (uint8_t)*size;
   3296 	((uint8_t*)data)[1] = LIBUSB_DT_STRING;
   3297 	memcpy((uint8_t*)data+2, tmp, *size-2);
   3298 	return LIBUSB_COMPLETED;
   3299 }
   3300 
   3301 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
   3302 {
   3303 	struct libusb_hid_descriptor d;
   3304 	uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
   3305 	size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
   3306 
   3307 	_hid_get_report_descriptor(dev, tmp, &report_len);
   3308 
   3309 	d.bLength = LIBUSB_DT_HID_SIZE;
   3310 	d.bDescriptorType = LIBUSB_DT_HID;
   3311 	d.bcdHID = 0x0110; /* 1.10 */
   3312 	d.bCountryCode = 0;
   3313 	d.bNumDescriptors = 1;
   3314 	d.bClassDescriptorType = LIBUSB_DT_REPORT;
   3315 	d.wClassDescriptorLength = (uint16_t)report_len;
   3316 
   3317 	if (*size > LIBUSB_DT_HID_SIZE)
   3318 		*size = LIBUSB_DT_HID_SIZE;
   3319 	memcpy(data, &d, *size);
   3320 	return LIBUSB_COMPLETED;
   3321 }
   3322 
   3323 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
   3324 {
   3325 	uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
   3326 	size_t i = 0;
   3327 
   3328 	/* usage page (0xFFA0 == vendor defined) */
   3329 	d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
   3330 	/* usage (vendor defined) */
   3331 	d[i++] = 0x09; d[i++] = 0x01;
   3332 	/* start collection (application) */
   3333 	d[i++] = 0xA1; d[i++] = 0x01;
   3334 	/* input report */
   3335 	if (dev->input_report_size) {
   3336 		/* usage (vendor defined) */
   3337 		d[i++] = 0x09; d[i++] = 0x01;
   3338 		/* logical minimum (0) */
   3339 		d[i++] = 0x15; d[i++] = 0x00;
   3340 		/* logical maximum (255) */
   3341 		d[i++] = 0x25; d[i++] = 0xFF;
   3342 		/* report size (8 bits) */
   3343 		d[i++] = 0x75; d[i++] = 0x08;
   3344 		/* report count */
   3345 		d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
   3346 		/* input (data, variable, absolute) */
   3347 		d[i++] = 0x81; d[i++] = 0x00;
   3348 	}
   3349 	/* output report */
   3350 	if (dev->output_report_size) {
   3351 		/* usage (vendor defined) */
   3352 		d[i++] = 0x09; d[i++] = 0x02;
   3353 		/* logical minimum (0) */
   3354 		d[i++] = 0x15; d[i++] = 0x00;
   3355 		/* logical maximum (255) */
   3356 		d[i++] = 0x25; d[i++] = 0xFF;
   3357 		/* report size (8 bits) */
   3358 		d[i++] = 0x75; d[i++] = 0x08;
   3359 		/* report count */
   3360 		d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
   3361 		/* output (data, variable, absolute) */
   3362 		d[i++] = 0x91; d[i++] = 0x00;
   3363 	}
   3364 	/* feature report */
   3365 	if (dev->feature_report_size) {
   3366 		/* usage (vendor defined) */
   3367 		d[i++] = 0x09; d[i++] = 0x03;
   3368 		/* logical minimum (0) */
   3369 		d[i++] = 0x15; d[i++] = 0x00;
   3370 		/* logical maximum (255) */
   3371 		d[i++] = 0x25; d[i++] = 0xFF;
   3372 		/* report size (8 bits) */
   3373 		d[i++] = 0x75; d[i++] = 0x08;
   3374 		/* report count */
   3375 		d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
   3376 		/* feature (data, variable, absolute) */
   3377 		d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
   3378 	}
   3379 
   3380 	/* end collection */
   3381 	d[i++] = 0xC0;
   3382 
   3383 	if (*size > i)
   3384 		*size = i;
   3385 	memcpy(data, d, *size);
   3386 	return LIBUSB_COMPLETED;
   3387 }
   3388 
   3389 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
   3390 							   int type, int _index, void *data, size_t *size)
   3391 {
   3392 	switch(type) {
   3393 	case LIBUSB_DT_DEVICE:
   3394 		usbi_dbg("LIBUSB_DT_DEVICE");
   3395 		return _hid_get_device_descriptor(dev, data, size);
   3396 	case LIBUSB_DT_CONFIG:
   3397 		usbi_dbg("LIBUSB_DT_CONFIG");
   3398 		if (!_index)
   3399 			return _hid_get_config_descriptor(dev, data, size);
   3400 		return LIBUSB_ERROR_INVALID_PARAM;
   3401 	case LIBUSB_DT_STRING:
   3402 		usbi_dbg("LIBUSB_DT_STRING");
   3403 		return _hid_get_string_descriptor(dev, _index, data, size);
   3404 	case LIBUSB_DT_HID:
   3405 		usbi_dbg("LIBUSB_DT_HID");
   3406 		if (!_index)
   3407 			return _hid_get_hid_descriptor(dev, data, size);
   3408 		return LIBUSB_ERROR_INVALID_PARAM;
   3409 	case LIBUSB_DT_REPORT:
   3410 		usbi_dbg("LIBUSB_DT_REPORT");
   3411 		if (!_index)
   3412 			return _hid_get_report_descriptor(dev, data, size);
   3413 		return LIBUSB_ERROR_INVALID_PARAM;
   3414 	case LIBUSB_DT_PHYSICAL:
   3415 		usbi_dbg("LIBUSB_DT_PHYSICAL");
   3416 		if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
   3417 			return LIBUSB_COMPLETED;
   3418 		return LIBUSB_ERROR_OTHER;
   3419 	}
   3420 	usbi_dbg("unsupported");
   3421 	return LIBUSB_ERROR_INVALID_PARAM;
   3422 }
   3423 
   3424 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
   3425 						   struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
   3426 						   int report_type)
   3427 {
   3428 	uint8_t *buf;
   3429 	DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
   3430 	int r = LIBUSB_SUCCESS;
   3431 
   3432 	if (tp->hid_buffer != NULL) {
   3433 		usbi_dbg("program assertion failed: hid_buffer is not NULL");
   3434 	}
   3435 
   3436 	if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
   3437 		usbi_dbg("invalid size (%d)", *size);
   3438 		return LIBUSB_ERROR_INVALID_PARAM;
   3439 	}
   3440 
   3441 	switch (report_type) {
   3442 		case HID_REPORT_TYPE_INPUT:
   3443 			ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
   3444 			break;
   3445 		case HID_REPORT_TYPE_FEATURE:
   3446 			ioctl_code = IOCTL_HID_GET_FEATURE;
   3447 			break;
   3448 		default:
   3449 			usbi_dbg("unknown HID report type %d", report_type);
   3450 			return LIBUSB_ERROR_INVALID_PARAM;
   3451 	}
   3452 
   3453 	// Add a trailing byte to detect overflows
   3454 	buf = (uint8_t*)calloc(expected_size+1, 1);
   3455 	if (buf == NULL) {
   3456 		return LIBUSB_ERROR_NO_MEM;
   3457 	}
   3458 	buf[0] = (uint8_t)id;	// Must be set always
   3459 	usbi_dbg("report ID: 0x%02X", buf[0]);
   3460 
   3461 	tp->hid_expected_size = expected_size;
   3462 	read_size = expected_size;
   3463 
   3464 	// NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
   3465 	if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
   3466 		buf, expected_size+1, &read_size, overlapped)) {
   3467 		if (GetLastError() != ERROR_IO_PENDING) {
   3468 			usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
   3469 			safe_free(buf);
   3470 			return LIBUSB_ERROR_IO;
   3471 		}
   3472 		// Asynchronous wait
   3473 		tp->hid_buffer = buf;
   3474 		tp->hid_dest = (uint8_t*)data; // copy dest, as not necessarily the start of the transfer buffer
   3475 		return LIBUSB_SUCCESS;
   3476 	}
   3477 
   3478 	// Transfer completed synchronously => copy and discard extra buffer
   3479 	if (read_size == 0) {
   3480 		usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
   3481 		*size = 0;
   3482 	} else {
   3483 		if (buf[0] != id) {
   3484 			usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
   3485 		}
   3486 		if ((size_t)read_size > expected_size) {
   3487 			r = LIBUSB_ERROR_OVERFLOW;
   3488 			usbi_dbg("OVERFLOW!");
   3489 		} else {
   3490 			r = LIBUSB_COMPLETED;
   3491 		}
   3492 
   3493 		*size = MIN((size_t)read_size, *size);
   3494 		if (id == 0) {
   3495 			// Discard report ID
   3496 			memcpy(data, buf+1, *size);
   3497 		} else {
   3498 			memcpy(data, buf, *size);
   3499 		}
   3500 	}
   3501 	safe_free(buf);
   3502 	return r;
   3503 }
   3504 
   3505 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
   3506 						   struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
   3507 						   int report_type)
   3508 {
   3509 	uint8_t *buf = NULL;
   3510 	DWORD ioctl_code, write_size= (DWORD)*size;
   3511 
   3512 	if (tp->hid_buffer != NULL) {
   3513 		usbi_dbg("program assertion failed: hid_buffer is not NULL");
   3514 	}
   3515 
   3516 	if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
   3517 		usbi_dbg("invalid size (%d)", *size);
   3518 		return LIBUSB_ERROR_INVALID_PARAM;
   3519 	}
   3520 
   3521 	switch (report_type) {
   3522 		case HID_REPORT_TYPE_OUTPUT:
   3523 			ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
   3524 			break;
   3525 		case HID_REPORT_TYPE_FEATURE:
   3526 			ioctl_code = IOCTL_HID_SET_FEATURE;
   3527 			break;
   3528 		default:
   3529 			usbi_dbg("unknown HID report type %d", report_type);
   3530 			return LIBUSB_ERROR_INVALID_PARAM;
   3531 	}
   3532 
   3533 	usbi_dbg("report ID: 0x%02X", id);
   3534 	// When report IDs are not used (i.e. when id == 0), we must add
   3535 	// a null report ID. Otherwise, we just use original data buffer
   3536 	if (id == 0) {
   3537 		write_size++;
   3538 	}
   3539 	buf = (uint8_t*) malloc(write_size);
   3540 	if (buf == NULL) {
   3541 		return LIBUSB_ERROR_NO_MEM;
   3542 	}
   3543 	if (id == 0) {
   3544 		buf[0] = 0;
   3545 		memcpy(buf + 1, data, *size);
   3546 	} else {
   3547 		// This seems like a waste, but if we don't duplicate the
   3548 		// data, we'll get issues when freeing hid_buffer
   3549 		memcpy(buf, data, *size);
   3550 		if (buf[0] != id) {
   3551 			usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
   3552 		}
   3553 	}
   3554 
   3555 	// NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
   3556 	if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
   3557 		buf, write_size, &write_size, overlapped)) {
   3558 		if (GetLastError() != ERROR_IO_PENDING) {
   3559 			usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
   3560 			safe_free(buf);
   3561 			return LIBUSB_ERROR_IO;
   3562 		}
   3563 		tp->hid_buffer = buf;
   3564 		tp->hid_dest = NULL;
   3565 		return LIBUSB_SUCCESS;
   3566 	}
   3567 
   3568 	// Transfer completed synchronously
   3569 	*size = write_size;
   3570 	if (write_size == 0) {
   3571 		usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
   3572 	}
   3573 	safe_free(buf);
   3574 	return LIBUSB_COMPLETED;
   3575 }
   3576 
   3577 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
   3578 							  int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
   3579 							  size_t *size, OVERLAPPED* overlapped)
   3580 {
   3581 	int report_type = (value >> 8) & 0xFF;
   3582 	int report_id = value & 0xFF;
   3583 
   3584 	if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
   3585 	  && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
   3586 		return LIBUSB_ERROR_INVALID_PARAM;
   3587 
   3588 	if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
   3589 		return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
   3590 
   3591 	if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
   3592 		return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
   3593 
   3594 	return LIBUSB_ERROR_INVALID_PARAM;
   3595 }
   3596 
   3597 
   3598 /*
   3599  * HID API functions
   3600  */
   3601 static int hid_init(int sub_api, struct libusb_context *ctx)
   3602 {
   3603 	DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
   3604 	DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
   3605 	DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
   3606 	DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
   3607 	DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
   3608 	DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
   3609 	DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
   3610 	DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
   3611 	DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
   3612 	DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
   3613 	DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
   3614 	DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
   3615 	DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
   3616 	DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
   3617 	DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
   3618 	DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
   3619 
   3620 	api_hid_available = true;
   3621 	return LIBUSB_SUCCESS;
   3622 }
   3623 
   3624 static int hid_exit(int sub_api)
   3625 {
   3626 	return LIBUSB_SUCCESS;
   3627 }
   3628 
   3629 // NB: open and close must ensure that they only handle interface of
   3630 // the right API type, as these functions can be called wholesale from
   3631 // composite_open(), with interfaces belonging to different APIs
   3632 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
   3633 {
   3634 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   3635 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   3636 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   3637 
   3638 	HIDD_ATTRIBUTES hid_attributes;
   3639 	PHIDP_PREPARSED_DATA preparsed_data = NULL;
   3640 	HIDP_CAPS capabilities;
   3641 	HIDP_VALUE_CAPS *value_caps;
   3642 
   3643 	HANDLE hid_handle = INVALID_HANDLE_VALUE;
   3644 	int i, j;
   3645 	// report IDs handling
   3646 	ULONG size[3];
   3647 	const char* type[3] = {"input", "output", "feature"};
   3648 	int nb_ids[2];	// zero and nonzero report IDs
   3649 
   3650 	CHECK_HID_AVAILABLE;
   3651 	if (priv->hid == NULL) {
   3652 		usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
   3653 		return LIBUSB_ERROR_NOT_FOUND;
   3654 	}
   3655 
   3656 	for (i = 0; i < USB_MAXINTERFACES; i++) {
   3657 		if ( (priv->usb_interface[i].path != NULL)
   3658 		  && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
   3659 			hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
   3660 				NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
   3661 			/*
   3662 			 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
   3663 			 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
   3664 			 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
   3665 			 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
   3666 			 * HidD_GetFeature (if the device supports Feature reports)."
   3667 			 */
   3668 			if (hid_handle == INVALID_HANDLE_VALUE) {
   3669 				usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
   3670 				hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
   3671 					NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
   3672 				if (hid_handle == INVALID_HANDLE_VALUE) {
   3673 					usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
   3674 					switch(GetLastError()) {
   3675 					case ERROR_FILE_NOT_FOUND:	// The device was disconnected
   3676 						return LIBUSB_ERROR_NO_DEVICE;
   3677 					case ERROR_ACCESS_DENIED:
   3678 						return LIBUSB_ERROR_ACCESS;
   3679 					default:
   3680 						return LIBUSB_ERROR_IO;
   3681 					}
   3682 				}
   3683 				priv->usb_interface[i].restricted_functionality = true;
   3684 			}
   3685 			handle_priv->interface_handle[i].api_handle = hid_handle;
   3686 		}
   3687 	}
   3688 
   3689 	hid_attributes.Size = sizeof(hid_attributes);
   3690 	do {
   3691 		if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
   3692 			usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
   3693 			break;
   3694 		}
   3695 
   3696 		priv->hid->vid = hid_attributes.VendorID;
   3697 		priv->hid->pid = hid_attributes.ProductID;
   3698 
   3699 		// Set the maximum available input buffer size
   3700 		for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
   3701 		usbi_dbg("set maximum input buffer size to %d", i/2);
   3702 
   3703 		// Get the maximum input and output report size
   3704 		if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
   3705 			usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
   3706 			break;
   3707 		}
   3708 		if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
   3709 			usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
   3710 			break;
   3711 		}
   3712 
   3713 		// Find out if interrupt will need report IDs
   3714 		size[0] = capabilities.NumberInputValueCaps;
   3715 		size[1] = capabilities.NumberOutputValueCaps;
   3716 		size[2] = capabilities.NumberFeatureValueCaps;
   3717 		for (j=HidP_Input; j<=HidP_Feature; j++) {
   3718 			usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
   3719 			priv->hid->uses_report_ids[j] = false;
   3720 			if (size[j] > 0) {
   3721 				value_caps = (HIDP_VALUE_CAPS*) calloc(size[j], sizeof(HIDP_VALUE_CAPS));
   3722 				if ( (value_caps != NULL)
   3723 				  && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
   3724 				  && (size[j] >= 1) ) {
   3725 					nb_ids[0] = 0;
   3726 					nb_ids[1] = 0;
   3727 					for (i=0; i<(int)size[j]; i++) {
   3728 						usbi_dbg("  Report ID: 0x%02X", value_caps[i].ReportID);
   3729 						if (value_caps[i].ReportID != 0) {
   3730 							nb_ids[1]++;
   3731 						} else {
   3732 							nb_ids[0]++;
   3733 						}
   3734 					}
   3735 					if (nb_ids[1] != 0) {
   3736 						if (nb_ids[0] != 0) {
   3737 							usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
   3738 								type[j]);
   3739 						}
   3740 						priv->hid->uses_report_ids[j] = true;
   3741 					}
   3742 				} else {
   3743 					usbi_warn(ctx, "  could not process %s report IDs", type[j]);
   3744 				}
   3745 				safe_free(value_caps);
   3746 			}
   3747 		}
   3748 
   3749 		// Set the report sizes
   3750 		priv->hid->input_report_size = capabilities.InputReportByteLength;
   3751 		priv->hid->output_report_size = capabilities.OutputReportByteLength;
   3752 		priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
   3753 
   3754 		// Fetch string descriptors
   3755 		priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
   3756 		if (priv->hid->string_index[0] != 0) {
   3757 			HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
   3758 				sizeof(priv->hid->string[0]));
   3759 		} else {
   3760 			priv->hid->string[0][0] = 0;
   3761 		}
   3762 		priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
   3763 		if (priv->hid->string_index[1] != 0) {
   3764 			HidD_GetProductString(hid_handle, priv->hid->string[1],
   3765 				sizeof(priv->hid->string[1]));
   3766 		} else {
   3767 			priv->hid->string[1][0] = 0;
   3768 		}
   3769 		priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
   3770 		if (priv->hid->string_index[2] != 0) {
   3771 			HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
   3772 				sizeof(priv->hid->string[2]));
   3773 		} else {
   3774 			priv->hid->string[2][0] = 0;
   3775 		}
   3776 	} while(0);
   3777 
   3778 	if (preparsed_data) {
   3779 		HidD_FreePreparsedData(preparsed_data);
   3780 	}
   3781 
   3782 	return LIBUSB_SUCCESS;
   3783 }
   3784 
   3785 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
   3786 {
   3787 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   3788 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   3789 	HANDLE file_handle;
   3790 	int i;
   3791 
   3792 	if (!api_hid_available)
   3793 		return;
   3794 
   3795 	for (i = 0; i < USB_MAXINTERFACES; i++) {
   3796 		if (priv->usb_interface[i].apib->id == USB_API_HID) {
   3797 			file_handle = handle_priv->interface_handle[i].api_handle;
   3798 			if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
   3799 				CloseHandle(file_handle);
   3800 			}
   3801 		}
   3802 	}
   3803 }
   3804 
   3805 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   3806 {
   3807 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   3808 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   3809 
   3810 	CHECK_HID_AVAILABLE;
   3811 
   3812 	// NB: Disconnection detection is not possible in this function
   3813 	if (priv->usb_interface[iface].path == NULL) {
   3814 		return LIBUSB_ERROR_NOT_FOUND;	// invalid iface
   3815 	}
   3816 
   3817 	// We use dev_handle as a flag for interface claimed
   3818 	if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
   3819 		return LIBUSB_ERROR_BUSY;	// already claimed
   3820 	}
   3821 
   3822 	handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
   3823 
   3824 	usbi_dbg("claimed interface %d", iface);
   3825 	handle_priv->active_interface = iface;
   3826 
   3827 	return LIBUSB_SUCCESS;
   3828 }
   3829 
   3830 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   3831 {
   3832 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   3833 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   3834 
   3835 	CHECK_HID_AVAILABLE;
   3836 
   3837 	if (priv->usb_interface[iface].path == NULL) {
   3838 		return LIBUSB_ERROR_NOT_FOUND;	// invalid iface
   3839 	}
   3840 
   3841 	if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
   3842 		return LIBUSB_ERROR_NOT_FOUND;	// invalid iface
   3843 	}
   3844 
   3845 	handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
   3846 
   3847 	return LIBUSB_SUCCESS;
   3848 }
   3849 
   3850 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
   3851 {
   3852 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   3853 
   3854 	CHECK_HID_AVAILABLE;
   3855 
   3856 	if (altsetting > 255) {
   3857 		return LIBUSB_ERROR_INVALID_PARAM;
   3858 	}
   3859 
   3860 	if (altsetting != 0) {
   3861 		usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
   3862 		return LIBUSB_ERROR_NOT_SUPPORTED;
   3863 	}
   3864 
   3865 	return LIBUSB_SUCCESS;
   3866 }
   3867 
   3868 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
   3869 {
   3870 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   3871 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   3872 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   3873 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   3874 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   3875 	WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
   3876 	HANDLE hid_handle;
   3877 	struct winfd wfd;
   3878 	int current_interface, config;
   3879 	size_t size;
   3880 	int r = LIBUSB_ERROR_INVALID_PARAM;
   3881 
   3882 	CHECK_HID_AVAILABLE;
   3883 
   3884 	transfer_priv->pollable_fd = INVALID_WINFD;
   3885 	safe_free(transfer_priv->hid_buffer);
   3886 	transfer_priv->hid_dest = NULL;
   3887 	size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
   3888 
   3889 	if (size > MAX_CTRL_BUFFER_LENGTH) {
   3890 		return LIBUSB_ERROR_INVALID_PARAM;
   3891 	}
   3892 
   3893 	current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
   3894 	if (current_interface < 0) {
   3895 		if (auto_claim(transfer, &current_interface, USB_API_HID) != LIBUSB_SUCCESS) {
   3896 			return LIBUSB_ERROR_NOT_FOUND;
   3897 		}
   3898 	}
   3899 
   3900 	usbi_dbg("will use interface %d", current_interface);
   3901 	hid_handle = handle_priv->interface_handle[current_interface].api_handle;
   3902 	// Always use the handle returned from usbi_create_fd (wfd.handle)
   3903 	wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
   3904 	if (wfd.fd < 0) {
   3905 		return LIBUSB_ERROR_NOT_FOUND;
   3906 	}
   3907 
   3908 	switch(LIBUSB_REQ_TYPE(setup->request_type)) {
   3909 	case LIBUSB_REQUEST_TYPE_STANDARD:
   3910 		switch(setup->request) {
   3911 		case LIBUSB_REQUEST_GET_DESCRIPTOR:
   3912 			r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
   3913 				(setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
   3914 			break;
   3915 		case LIBUSB_REQUEST_GET_CONFIGURATION:
   3916 			r = windows_get_configuration(transfer->dev_handle, &config);
   3917 			if (r == LIBUSB_SUCCESS) {
   3918 				size = 1;
   3919 				((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
   3920 				r = LIBUSB_COMPLETED;
   3921 			}
   3922 			break;
   3923 		case LIBUSB_REQUEST_SET_CONFIGURATION:
   3924 			if (setup->value == priv->active_config) {
   3925 				r = LIBUSB_COMPLETED;
   3926 			} else {
   3927 				usbi_warn(ctx, "cannot set configuration other than the default one");
   3928 				r = LIBUSB_ERROR_INVALID_PARAM;
   3929 			}
   3930 			break;
   3931 		case LIBUSB_REQUEST_GET_INTERFACE:
   3932 			size = 1;
   3933 			((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
   3934 			r = LIBUSB_COMPLETED;
   3935 			break;
   3936 		case LIBUSB_REQUEST_SET_INTERFACE:
   3937 			r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->index, setup->value);
   3938 			if (r == LIBUSB_SUCCESS) {
   3939 				r = LIBUSB_COMPLETED;
   3940 			}
   3941 			break;
   3942 		default:
   3943 			usbi_warn(ctx, "unsupported HID control request");
   3944 			r = LIBUSB_ERROR_INVALID_PARAM;
   3945 			break;
   3946 		}
   3947 		break;
   3948 	case LIBUSB_REQUEST_TYPE_CLASS:
   3949 		r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
   3950 			setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
   3951 			&size, wfd.overlapped);
   3952 		break;
   3953 	default:
   3954 		usbi_warn(ctx, "unsupported HID control request");
   3955 		r = LIBUSB_ERROR_INVALID_PARAM;
   3956 		break;
   3957 	}
   3958 
   3959 	if (r == LIBUSB_COMPLETED) {
   3960 		// Force request to be completed synchronously. Transferred size has been set by previous call
   3961 		wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   3962 		// http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
   3963 		// set InternalHigh to the number of bytes transferred
   3964 		wfd.overlapped->InternalHigh = (DWORD)size;
   3965 		r = LIBUSB_SUCCESS;
   3966 	}
   3967 
   3968 	if (r == LIBUSB_SUCCESS) {
   3969 		// Use priv_transfer to store data needed for async polling
   3970 		transfer_priv->pollable_fd = wfd;
   3971 		transfer_priv->interface_number = (uint8_t)current_interface;
   3972 	} else {
   3973 		usbi_free_fd(&wfd);
   3974 	}
   3975 
   3976 	return r;
   3977 }
   3978 
   3979 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
   3980 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   3981 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   3982 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   3983 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   3984 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   3985 	struct winfd wfd;
   3986 	HANDLE hid_handle;
   3987 	bool direction_in, ret;
   3988 	int current_interface, length;
   3989 	DWORD size;
   3990 	int r = LIBUSB_SUCCESS;
   3991 
   3992 	CHECK_HID_AVAILABLE;
   3993 
   3994 	transfer_priv->pollable_fd = INVALID_WINFD;
   3995 	transfer_priv->hid_dest = NULL;
   3996 	safe_free(transfer_priv->hid_buffer);
   3997 
   3998 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   3999 	if (current_interface < 0) {
   4000 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   4001 		return LIBUSB_ERROR_NOT_FOUND;
   4002 	}
   4003 
   4004 	usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
   4005 
   4006 	hid_handle = handle_priv->interface_handle[current_interface].api_handle;
   4007 	direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
   4008 
   4009 	wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
   4010 	// Always use the handle returned from usbi_create_fd (wfd.handle)
   4011 	if (wfd.fd < 0) {
   4012 		return LIBUSB_ERROR_NO_MEM;
   4013 	}
   4014 
   4015 	// If report IDs are not in use, an extra prefix byte must be added
   4016 	if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
   4017 	  || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
   4018 		length = transfer->length+1;
   4019 	} else {
   4020 		length = transfer->length;
   4021 	}
   4022 	// Add a trailing byte to detect overflows on input
   4023 	transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
   4024 	if (transfer_priv->hid_buffer == NULL) {
   4025 		return LIBUSB_ERROR_NO_MEM;
   4026 	}
   4027 	transfer_priv->hid_expected_size = length;
   4028 
   4029 	if (direction_in) {
   4030 		transfer_priv->hid_dest = transfer->buffer;
   4031 		usbi_dbg("reading %d bytes (report ID: 0x00)", length);
   4032 		ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
   4033 	} else {
   4034 		if (!priv->hid->uses_report_ids[1]) {
   4035 			memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
   4036 		} else {
   4037 			// We could actually do without the calloc and memcpy in this case
   4038 			memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
   4039 		}
   4040 		usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
   4041 		ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
   4042 	}
   4043 	if (!ret) {
   4044 		if (GetLastError() != ERROR_IO_PENDING) {
   4045 			usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
   4046 			usbi_free_fd(&wfd);
   4047 			safe_free(transfer_priv->hid_buffer);
   4048 			return LIBUSB_ERROR_IO;
   4049 		}
   4050 	} else {
   4051 		// Only write operations that completed synchronously need to free up
   4052 		// hid_buffer. For reads, copy_transfer_data() handles that process.
   4053 		if (!direction_in) {
   4054 			safe_free(transfer_priv->hid_buffer);
   4055 		}
   4056 		if (size == 0) {
   4057 			usbi_err(ctx, "program assertion failed - no data was transferred");
   4058 			size = 1;
   4059 		}
   4060 		if (size > (size_t)length) {
   4061 			usbi_err(ctx, "OVERFLOW!");
   4062 			r = LIBUSB_ERROR_OVERFLOW;
   4063 		}
   4064 		wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   4065 		wfd.overlapped->InternalHigh = size;
   4066 	}
   4067 
   4068 	transfer_priv->pollable_fd = wfd;
   4069 	transfer_priv->interface_number = (uint8_t)current_interface;
   4070 
   4071 	return r;
   4072 }
   4073 
   4074 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
   4075 {
   4076 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4077 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   4078 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   4079 	HANDLE hid_handle;
   4080 	int current_interface;
   4081 
   4082 	CHECK_HID_AVAILABLE;
   4083 
   4084 	current_interface = transfer_priv->interface_number;
   4085 	hid_handle = handle_priv->interface_handle[current_interface].api_handle;
   4086 	CancelIo(hid_handle);
   4087 
   4088 	return LIBUSB_SUCCESS;
   4089 }
   4090 
   4091 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
   4092 {
   4093 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   4094 	HANDLE hid_handle;
   4095 	int current_interface;
   4096 
   4097 	CHECK_HID_AVAILABLE;
   4098 
   4099 	// Flushing the queues on all interfaces is the best we can achieve
   4100 	for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
   4101 		hid_handle = handle_priv->interface_handle[current_interface].api_handle;
   4102 		if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
   4103 			HidD_FlushQueue(hid_handle);
   4104 		}
   4105 	}
   4106 	return LIBUSB_SUCCESS;
   4107 }
   4108 
   4109 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
   4110 {
   4111 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   4112 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   4113 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4114 	HANDLE hid_handle;
   4115 	int current_interface;
   4116 
   4117 	CHECK_HID_AVAILABLE;
   4118 
   4119 	current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
   4120 	if (current_interface < 0) {
   4121 		usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
   4122 		return LIBUSB_ERROR_NOT_FOUND;
   4123 	}
   4124 
   4125 	usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
   4126 	hid_handle = handle_priv->interface_handle[current_interface].api_handle;
   4127 
   4128 	// No endpoint selection with Microsoft's implementation, so we try to flush the
   4129 	// whole interface. Should be OK for most case scenarios
   4130 	if (!HidD_FlushQueue(hid_handle)) {
   4131 		usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
   4132 		// Device was probably disconnected
   4133 		return LIBUSB_ERROR_NO_DEVICE;
   4134 	}
   4135 
   4136 	return LIBUSB_SUCCESS;
   4137 }
   4138 
   4139 // This extra function is only needed for HID
   4140 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
   4141 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4142 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   4143 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   4144 	int r = LIBUSB_TRANSFER_COMPLETED;
   4145 	uint32_t corrected_size = io_size;
   4146 
   4147 	if (transfer_priv->hid_buffer != NULL) {
   4148 		// If we have a valid hid_buffer, it means the transfer was async
   4149 		if (transfer_priv->hid_dest != NULL) {	// Data readout
   4150 			// First, check for overflow
   4151 			if (corrected_size > transfer_priv->hid_expected_size) {
   4152 				usbi_err(ctx, "OVERFLOW!");
   4153 				corrected_size = (uint32_t)transfer_priv->hid_expected_size;
   4154 				r = LIBUSB_TRANSFER_OVERFLOW;
   4155 			}
   4156 
   4157 			if (transfer_priv->hid_buffer[0] == 0) {
   4158 				// Discard the 1 byte report ID prefix
   4159 				corrected_size--;
   4160 				memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
   4161 			} else {
   4162 				memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
   4163 			}
   4164 			transfer_priv->hid_dest = NULL;
   4165 		}
   4166 		// For write, we just need to free the hid buffer
   4167 		safe_free(transfer_priv->hid_buffer);
   4168 	}
   4169 	itransfer->transferred += corrected_size;
   4170 	return r;
   4171 }
   4172 
   4173 
   4174 /*
   4175  * Composite API functions
   4176  */
   4177 static int composite_init(int sub_api, struct libusb_context *ctx)
   4178 {
   4179 	return LIBUSB_SUCCESS;
   4180 }
   4181 
   4182 static int composite_exit(int sub_api)
   4183 {
   4184 	return LIBUSB_SUCCESS;
   4185 }
   4186 
   4187 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
   4188 {
   4189 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4190 	int r = LIBUSB_ERROR_NOT_FOUND;
   4191 	uint8_t i;
   4192 	// SUB_API_MAX+1 as the SUB_API_MAX pos is used to indicate availability of HID
   4193 	bool available[SUB_API_MAX+1] = {0};
   4194 
   4195 	for (i=0; i<USB_MAXINTERFACES; i++) {
   4196 		switch (priv->usb_interface[i].apib->id) {
   4197 		case USB_API_WINUSBX:
   4198 			if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
   4199 				available[priv->usb_interface[i].sub_api] = true;
   4200 			break;
   4201 		case USB_API_HID:
   4202 			available[SUB_API_MAX] = true;
   4203 			break;
   4204 		default:
   4205 			break;
   4206 		}
   4207 	}
   4208 
   4209 	for (i=0; i<SUB_API_MAX; i++) {	// WinUSB-like drivers
   4210 		if (available[i]) {
   4211 			r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
   4212 			if (r != LIBUSB_SUCCESS) {
   4213 				return r;
   4214 			}
   4215 		}
   4216 	}
   4217 	if (available[SUB_API_MAX]) {	// HID driver
   4218 		r = hid_open(SUB_API_NOTSET, dev_handle);
   4219 	}
   4220 	return r;
   4221 }
   4222 
   4223 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
   4224 {
   4225 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4226 	uint8_t i;
   4227 	bool available[SUB_API_MAX];
   4228 
   4229 	for (i = 0; i<SUB_API_MAX; i++) {
   4230 		available[i] = false;
   4231 	}
   4232 
   4233 	for (i=0; i<USB_MAXINTERFACES; i++) {
   4234 		if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
   4235 		  && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
   4236 			available[priv->usb_interface[i].sub_api] = true;
   4237 		}
   4238 	}
   4239 
   4240 	for (i=0; i<SUB_API_MAX; i++) {
   4241 		if (available[i]) {
   4242 			usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
   4243 		}
   4244 	}
   4245 }
   4246 
   4247 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   4248 {
   4249 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4250 	return priv->usb_interface[iface].apib->
   4251 		claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
   4252 }
   4253 
   4254 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
   4255 {
   4256 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4257 	return priv->usb_interface[iface].apib->
   4258 		set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
   4259 }
   4260 
   4261 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
   4262 {
   4263 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4264 	return priv->usb_interface[iface].apib->
   4265 		release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
   4266 }
   4267 
   4268 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
   4269 {
   4270 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4271 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   4272 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   4273 	int i, pass;
   4274 
   4275 	// Interface shouldn't matter for control, but it does in practice, with Windows'
   4276 	// restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
   4277 	for (pass = 0; pass < 2; pass++) {
   4278 		for (i=0; i<USB_MAXINTERFACES; i++) {
   4279 			if (priv->usb_interface[i].path != NULL) {
   4280 				if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
   4281 					usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
   4282 					continue;
   4283 				}
   4284 				usbi_dbg("using interface %d", i);
   4285 				return priv->usb_interface[i].apib->submit_control_transfer(priv->usb_interface[i].sub_api, itransfer);
   4286 			}
   4287 		}
   4288 	}
   4289 
   4290 	usbi_err(ctx, "no libusbx supported interfaces to complete request");
   4291 	return LIBUSB_ERROR_NOT_FOUND;
   4292 }
   4293 
   4294 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
   4295 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4296 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   4297 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   4298 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   4299 	int current_interface;
   4300 
   4301 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   4302 	if (current_interface < 0) {
   4303 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   4304 		return LIBUSB_ERROR_NOT_FOUND;
   4305 	}
   4306 
   4307 	return priv->usb_interface[current_interface].apib->
   4308 		submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
   4309 
   4310 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
   4311 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4312 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   4313 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   4314 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   4315 	int current_interface;
   4316 
   4317 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   4318 	if (current_interface < 0) {
   4319 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   4320 		return LIBUSB_ERROR_NOT_FOUND;
   4321 	}
   4322 
   4323 	return priv->usb_interface[current_interface].apib->
   4324 		submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
   4325 
   4326 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
   4327 {
   4328 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   4329 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   4330 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4331 	int current_interface;
   4332 
   4333 	current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
   4334 	if (current_interface < 0) {
   4335 		usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
   4336 		return LIBUSB_ERROR_NOT_FOUND;
   4337 	}
   4338 
   4339 	return priv->usb_interface[current_interface].apib->
   4340 		clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);}
   4341 
   4342 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
   4343 {
   4344 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4345 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   4346 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   4347 
   4348 	return priv->usb_interface[transfer_priv->interface_number].apib->
   4349 		abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
   4350 
   4351 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
   4352 {
   4353 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4354 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   4355 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   4356 
   4357 	return priv->usb_interface[transfer_priv->interface_number].apib->
   4358 		abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
   4359 
   4360 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
   4361 {
   4362 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   4363 	int r;
   4364 	uint8_t i;
   4365 	bool available[SUB_API_MAX];
   4366 	for (i = 0; i<SUB_API_MAX; i++) {
   4367 		available[i] = false;
   4368 	}
   4369 	for (i=0; i<USB_MAXINTERFACES; i++) {
   4370 		if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
   4371 		  && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
   4372 			available[priv->usb_interface[i].sub_api] = true;
   4373 		}
   4374 	}
   4375 	for (i=0; i<SUB_API_MAX; i++) {
   4376 		if (available[i]) {
   4377 			r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
   4378 			if (r != LIBUSB_SUCCESS) {
   4379 				return r;
   4380 			}
   4381 		}
   4382 	}
   4383 	return LIBUSB_SUCCESS;
   4384 }
   4385 
   4386 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
   4387 {
   4388 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   4389 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   4390 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   4391 
   4392 	return priv->usb_interface[transfer_priv->interface_number].apib->
   4393 		copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
   4394 }
   4395