Home | History | Annotate | Download | only in os
      1 /*
      2  * windows backend for libusb 1.0
      3  * Copyright (c) 2009-2010 Pete Batard <pbatard (at) gmail.com>
      4  * With contributions from Michael Plante, Orin Eman et al.
      5  * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
      6  * Hash table functions adapted from glibc, by Ulrich Drepper et al.
      7  * Major code testing contribution by Xiaofan Chen
      8  *
      9  * This library is free software; you can redistribute it and/or
     10  * modify it under the terms of the GNU Lesser General Public
     11  * License as published by the Free Software Foundation; either
     12  * version 2.1 of the License, or (at your option) any later version.
     13  *
     14  * This library is distributed in the hope that it will be useful,
     15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     17  * Lesser General Public License for more details.
     18  *
     19  * You should have received a copy of the GNU Lesser General Public
     20  * License along with this library; if not, write to the Free Software
     21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
     22  */
     23 
     24 #include <config.h>
     25 #include <windows.h>
     26 #include <setupapi.h>
     27 #include <ctype.h>
     28 #include <errno.h>
     29 #include <fcntl.h>
     30 #include <process.h>
     31 #include <stdio.h>
     32 #include <inttypes.h>
     33 #include <objbase.h>
     34 #include <winioctl.h>
     35 
     36 #include <libusbi.h>
     37 #include "poll_windows.h"
     38 #include "windows_usb.h"
     39 
     40 // The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
     41 #if defined(_PREFAST_)
     42 #pragma warning(disable:28719)
     43 #endif
     44 
     45 // The 2 macros below are used in conjunction with safe loops.
     46 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
     47 #define LOOP_BREAK(err) { r=err; continue; }
     48 
     49 extern void usbi_fd_notification(struct libusb_context *ctx);
     50 
     51 // Helper prototypes
     52 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
     53 static int windows_clock_gettime(int clk_id, struct timespec *tp);
     54 unsigned __stdcall windows_clock_gettime_threaded(void* param);
     55 // WinUSB API prototypes
     56 static int winusb_init(struct libusb_context *ctx);
     57 static int winusb_exit(void);
     58 static int winusb_open(struct libusb_device_handle *dev_handle);
     59 static void winusb_close(struct libusb_device_handle *dev_handle);
     60 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface);
     61 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
     62 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
     63 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
     64 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
     65 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
     66 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
     67 static int winusb_abort_transfers(struct usbi_transfer *itransfer);
     68 static int winusb_abort_control(struct usbi_transfer *itransfer);
     69 static int winusb_reset_device(struct libusb_device_handle *dev_handle);
     70 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
     71 // Composite API prototypes
     72 static int composite_init(struct libusb_context *ctx);
     73 static int composite_exit(void);
     74 static int composite_open(struct libusb_device_handle *dev_handle);
     75 static void composite_close(struct libusb_device_handle *dev_handle);
     76 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
     77 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
     78 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
     79 static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
     80 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
     81 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
     82 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
     83 static int composite_abort_transfers(struct usbi_transfer *itransfer);
     84 static int composite_abort_control(struct usbi_transfer *itransfer);
     85 static int composite_reset_device(struct libusb_device_handle *dev_handle);
     86 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
     87 
     88 
     89 // Global variables
     90 uint64_t hires_frequency, hires_ticks_to_ps;
     91 const uint64_t epoch_time = UINT64_C(116444736000000000);	// 1970.01.01 00:00:000 in MS Filetime
     92 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
     93 // Concurrency
     94 static int concurrent_usage = -1;
     95 usbi_mutex_t autoclaim_lock;
     96 // Timer thread
     97 // NB: index 0 is for monotonic and 1 is for the thread exit event
     98 HANDLE timer_thread = NULL;
     99 HANDLE timer_mutex = NULL;
    100 struct timespec timer_tp;
    101 volatile LONG request_count[2] = {0, 1};	// last one must be > 0
    102 HANDLE timer_request[2] = { NULL, NULL };
    103 HANDLE timer_response = NULL;
    104 // API globals
    105 bool api_winusb_available = false;
    106 #define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
    107 
    108 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
    109 	if ((guid1 != NULL) && (guid2 != NULL)) {
    110 		return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
    111 	}
    112 	return false;
    113 }
    114 
    115 #if defined(ENABLE_DEBUG_LOGGING) || (defined(_MSC_VER) && _MSC_VER < 1400)
    116 static char* guid_to_string(const GUID* guid)
    117 {
    118 	static char guid_string[MAX_GUID_STRING_LENGTH];
    119 
    120 	if (guid == NULL) return NULL;
    121 	sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
    122 		(unsigned int)guid->Data1, guid->Data2, guid->Data3,
    123 		guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
    124 		guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
    125 	return guid_string;
    126 }
    127 #endif
    128 
    129 /*
    130  * Converts a windows error to human readable string
    131  * uses retval as errorcode, or, if 0, use GetLastError()
    132  */
    133 static char *windows_error_str(uint32_t retval)
    134 {
    135 static char err_string[ERR_BUFFER_SIZE];
    136 
    137 	DWORD size;
    138 	size_t i;
    139 	uint32_t error_code, format_error;
    140 
    141 	error_code = retval?retval:GetLastError();
    142 
    143 	safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%d] ", error_code);
    144 
    145 	size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
    146 		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
    147 		ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
    148 	if (size == 0) {
    149 		format_error = GetLastError();
    150 		if (format_error)
    151 			safe_sprintf(err_string, ERR_BUFFER_SIZE,
    152 				"Windows error code %u (FormatMessage error code %u)", error_code, format_error);
    153 		else
    154 			safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
    155 	} else {
    156 		// Remove CR/LF terminators
    157 		for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
    158 			err_string[i] = 0;
    159 		}
    160 	}
    161 	return err_string;
    162 }
    163 
    164 /*
    165  * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
    166  * Return an allocated sanitized string or NULL on error.
    167  */
    168 static char* sanitize_path(const char* path)
    169 {
    170 	const char root_prefix[] = "\\\\.\\";
    171 	size_t j, size, root_size;
    172 	char* ret_path = NULL;
    173 	size_t add_root = 0;
    174 
    175 	if (path == NULL)
    176 		return NULL;
    177 
    178 	size = safe_strlen(path)+1;
    179 	root_size = sizeof(root_prefix)-1;
    180 
    181 	// Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
    182 	if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
    183 		((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
    184 		add_root = root_size;
    185 		size += add_root;
    186 	}
    187 
    188 	if ((ret_path = (char*)calloc(size, 1)) == NULL)
    189 		return NULL;
    190 
    191 	safe_strcpy(&ret_path[add_root], size-add_root, path);
    192 
    193 	// Ensure consistancy with root prefix
    194 	for (j=0; j<root_size; j++)
    195 		ret_path[j] = root_prefix[j];
    196 
    197 	// Same goes for '\' and '#' after the root prefix. Ensure '#' is used
    198 	for(j=root_size; j<size; j++) {
    199 		ret_path[j] = (char)toupper((int)ret_path[j]);	// Fix case too
    200 		if (ret_path[j] == '\\')
    201 			ret_path[j] = '#';
    202 	}
    203 
    204 	return ret_path;
    205 }
    206 
    207 /*
    208  * Cfgmgr32, OLE32 and SetupAPI DLL functions
    209  */
    210 static int init_dlls(void)
    211 {
    212 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
    213 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
    214 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
    215 	DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
    216 	// Prefixed to avoid conflict with header files
    217 	DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
    218 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
    219 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
    220 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
    221 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
    222 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
    223 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
    224 	DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
    225 	DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
    226 	DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
    227 	return LIBUSB_SUCCESS;
    228 }
    229 
    230 /*
    231  * enumerate interfaces for the whole USB class
    232  *
    233  * Parameters:
    234  * dev_info: a pointer to a dev_info list
    235  * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
    236  * usb_class: the generic USB class for which to retrieve interface details
    237  * index: zero based index of the interface in the device info list
    238  *
    239  * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
    240  * structure returned and call this function repeatedly using the same guid (with an
    241  * incremented index starting at zero) until all interfaces have been returned.
    242  */
    243 static bool get_devinfo_data(struct libusb_context *ctx,
    244 	HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, char* usb_class, unsigned _index)
    245 {
    246 	if (_index <= 0) {
    247 		*dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
    248 		if (*dev_info == INVALID_HANDLE_VALUE) {
    249 			return false;
    250 		}
    251 	}
    252 
    253 	dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
    254 	if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
    255 		if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    256 			usbi_err(ctx, "Could not obtain device info data for index %u: %s",
    257 				_index, windows_error_str(0));
    258 		}
    259 		pSetupDiDestroyDeviceInfoList(*dev_info);
    260 		*dev_info = INVALID_HANDLE_VALUE;
    261 		return false;
    262 	}
    263 	return true;
    264 }
    265 
    266 /*
    267  * enumerate interfaces for a specific GUID
    268  *
    269  * Parameters:
    270  * dev_info: a pointer to a dev_info list
    271  * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
    272  * guid: the GUID for which to retrieve interface details
    273  * index: zero based index of the interface in the device info list
    274  *
    275  * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
    276  * structure returned and call this function repeatedly using the same guid (with an
    277  * incremented index starting at zero) until all interfaces have been returned.
    278  */
    279 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
    280 	HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
    281 {
    282 	SP_DEVICE_INTERFACE_DATA dev_interface_data;
    283 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
    284 	DWORD size;
    285 
    286 	if (_index <= 0) {
    287 		*dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
    288 	}
    289 
    290 	if (dev_info_data != NULL) {
    291 		dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
    292 		if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
    293 			if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    294 				usbi_err(ctx, "Could not obtain device info data for index %u: %s",
    295 					_index, windows_error_str(0));
    296 			}
    297 			pSetupDiDestroyDeviceInfoList(*dev_info);
    298 			*dev_info = INVALID_HANDLE_VALUE;
    299 			return NULL;
    300 		}
    301 	}
    302 
    303 	dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
    304 	if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
    305 		if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    306 			usbi_err(ctx, "Could not obtain interface data for index %u: %s",
    307 				_index, windows_error_str(0));
    308 		}
    309 		pSetupDiDestroyDeviceInfoList(*dev_info);
    310 		*dev_info = INVALID_HANDLE_VALUE;
    311 		return NULL;
    312 	}
    313 
    314 	// Read interface data (dummy + actual) to access the device path
    315 	if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
    316 		// The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
    317 		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
    318 			usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
    319 				_index, windows_error_str(0));
    320 			goto err_exit;
    321 		}
    322 	} else {
    323 		usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
    324 		goto err_exit;
    325 	}
    326 
    327 	if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
    328 		usbi_err(ctx, "could not allocate interface data for index %u.", _index);
    329 		goto err_exit;
    330 	}
    331 
    332 	dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
    333 	if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
    334 		dev_interface_details, size, &size, NULL)) {
    335 		usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
    336 			_index, windows_error_str(0));
    337 	}
    338 
    339 	return dev_interface_details;
    340 
    341 err_exit:
    342 	pSetupDiDestroyDeviceInfoList(*dev_info);
    343 	*dev_info = INVALID_HANDLE_VALUE;
    344 	return NULL;
    345 }
    346 
    347 /* Hash table functions - modified From glibc 2.3.2:
    348    [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
    349    [Knuth]            The Art of Computer Programming, part 3 (6.4)  */
    350 typedef struct htab_entry {
    351 	unsigned long used;
    352 	char* str;
    353 } htab_entry;
    354 htab_entry* htab_table = NULL;
    355 usbi_mutex_t htab_write_mutex = NULL;
    356 unsigned long htab_size, htab_filled;
    357 
    358 /* For the used double hash method the table size has to be a prime. To
    359    correct the user given table size we need a prime test.  This trivial
    360    algorithm is adequate because the code is called only during init and
    361    the number is likely to be small  */
    362 static int isprime(unsigned long number)
    363 {
    364 	// no even number will be passed
    365 	unsigned int divider = 3;
    366 
    367 	while((divider * divider < number) && (number % divider != 0))
    368 		divider += 2;
    369 
    370 	return (number % divider != 0);
    371 }
    372 
    373 /* Before using the hash table we must allocate memory for it.
    374    We allocate one element more as the found prime number says.
    375    This is done for more effective indexing as explained in the
    376    comment for the hash function.  */
    377 static int htab_create(struct libusb_context *ctx, unsigned long nel)
    378 {
    379 	if (htab_table != NULL) {
    380 		usbi_err(ctx, "hash table already allocated");
    381 	}
    382 
    383 	// Create a mutex
    384 	usbi_mutex_init(&htab_write_mutex, NULL);
    385 
    386 	// Change nel to the first prime number not smaller as nel.
    387 	nel |= 1;
    388 	while(!isprime(nel))
    389 		nel += 2;
    390 
    391 	htab_size = nel;
    392 	usbi_dbg("using %d entries hash table", nel);
    393 	htab_filled = 0;
    394 
    395 	// allocate memory and zero out.
    396 	htab_table = (htab_entry*)calloc(htab_size + 1, sizeof(htab_entry));
    397 	if (htab_table == NULL) {
    398 		usbi_err(ctx, "could not allocate space for hash table");
    399 		return 0;
    400 	}
    401 
    402 	return 1;
    403 }
    404 
    405 /* After using the hash table it has to be destroyed.  */
    406 static void htab_destroy(void)
    407 {
    408 	size_t i;
    409 	if (htab_table == NULL) {
    410 		return;
    411 	}
    412 
    413 	for (i=0; i<htab_size; i++) {
    414 		if (htab_table[i].used) {
    415 			safe_free(htab_table[i].str);
    416 		}
    417 	}
    418 	usbi_mutex_destroy(&htab_write_mutex);
    419 	safe_free(htab_table);
    420 }
    421 
    422 /* This is the search function. It uses double hashing with open addressing.
    423    We use an trick to speed up the lookup. The table is created with one
    424    more element available. This enables us to use the index zero special.
    425    This index will never be used because we store the first hash index in
    426    the field used where zero means not used. Every other value means used.
    427    The used field can be used as a first fast comparison for equality of
    428    the stored and the parameter value. This helps to prevent unnecessary
    429    expensive calls of strcmp.  */
    430 static unsigned long htab_hash(char* str)
    431 {
    432 	unsigned long hval, hval2;
    433 	unsigned long idx;
    434 	unsigned long r = 5381;
    435 	int c;
    436 	char* sz = str;
    437 
    438 	// Compute main hash value (algorithm suggested by Nokia)
    439 	while ((c = *sz++))
    440 		r = ((r << 5) + r) + c;
    441 	if (r == 0)
    442 		++r;
    443 
    444 	// compute table hash: simply take the modulus
    445 	hval = r % htab_size;
    446 	if (hval == 0)
    447 		++hval;
    448 
    449 	// Try the first index
    450 	idx = hval;
    451 
    452 	if (htab_table[idx].used) {
    453 		if ( (htab_table[idx].used == hval)
    454 		  && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
    455 			// existing hash
    456 			return idx;
    457 		}
    458 		usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
    459 
    460 		// Second hash function, as suggested in [Knuth]
    461 		hval2 = 1 + hval % (htab_size - 2);
    462 
    463 		do {
    464 			// Because size is prime this guarantees to step through all available indexes
    465 			if (idx <= hval2) {
    466 				idx = htab_size + idx - hval2;
    467 			} else {
    468 				idx -= hval2;
    469 			}
    470 
    471 			// If we visited all entries leave the loop unsuccessfully
    472 			if (idx == hval) {
    473 				break;
    474 			}
    475 
    476 			// If entry is found use it.
    477 			if ( (htab_table[idx].used == hval)
    478 			  && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
    479 				return idx;
    480 			}
    481 		}
    482 		while (htab_table[idx].used);
    483 	}
    484 
    485 	// Not found => New entry
    486 
    487 	// If the table is full return an error
    488 	if (htab_filled >= htab_size) {
    489 		usbi_err(NULL, "hash table is full (%d entries)", htab_size);
    490 		return 0;
    491 	}
    492 
    493 	// Concurrent threads might be storing the same entry at the same time
    494 	// (eg. "simultaneous" enums from different threads) => use a mutex
    495 	usbi_mutex_lock(&htab_write_mutex);
    496 	// Just free any previously allocated string (which should be the same as
    497 	// new one). The possibility of concurrent threads storing a collision
    498 	// string (same hash, different string) at the same time is extremely low
    499 	safe_free(htab_table[idx].str);
    500 	htab_table[idx].used = hval;
    501 	htab_table[idx].str = (char*) calloc(1, safe_strlen(str)+1);
    502 	if (htab_table[idx].str == NULL) {
    503 		usbi_err(NULL, "could not duplicate string for hash table");
    504 		usbi_mutex_unlock(&htab_write_mutex);
    505 		return 0;
    506 	}
    507 	memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
    508 	++htab_filled;
    509 	usbi_mutex_unlock(&htab_write_mutex);
    510 
    511 	return idx;
    512 }
    513 
    514 /*
    515  * Returns the session ID of a device's nth level ancestor
    516  * If there's no device at the nth level, return 0
    517  */
    518 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
    519 {
    520 	DWORD parent_devinst;
    521 	unsigned long session_id = 0;
    522 	char* sanitized_path = NULL;
    523 	char path[MAX_PATH_LENGTH];
    524 	unsigned i;
    525 
    526 	if (level < 1) return 0;
    527 	for (i = 0; i<level; i++) {
    528 		if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
    529 			return 0;
    530 		}
    531 		devinst = parent_devinst;
    532 	}
    533 	if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
    534 		return 0;
    535 	}
    536 	// TODO (post hotplug): try without sanitizing
    537 	sanitized_path = sanitize_path(path);
    538 	if (sanitized_path == NULL) {
    539 		return 0;
    540 	}
    541 	session_id = htab_hash(sanitized_path);
    542 	safe_free(sanitized_path);
    543 	return session_id;
    544 }
    545 
    546 /*
    547  * Populate the endpoints addresses of the device_priv interface helper structs
    548  */
    549 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
    550 {
    551 	int i, r;
    552 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
    553 	struct libusb_config_descriptor *conf_desc;
    554 	const struct libusb_interface_descriptor *if_desc;
    555 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
    556 
    557 	r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
    558 	if (r != LIBUSB_SUCCESS) {
    559 		usbi_warn(ctx, "could not read config descriptor: error %d", r);
    560 		return r;
    561 	}
    562 
    563 	if_desc = &conf_desc->interface[iface].altsetting[altsetting];
    564 	safe_free(priv->usb_interface[iface].endpoint);
    565 
    566 	if (if_desc->bNumEndpoints == 0) {
    567 		usbi_dbg("no endpoints found for interface %d", iface);
    568 		return LIBUSB_SUCCESS;
    569 	}
    570 
    571 	priv->usb_interface[iface].endpoint = (uint8_t*) calloc(1, if_desc->bNumEndpoints);
    572 	if (priv->usb_interface[iface].endpoint == NULL) {
    573 		return LIBUSB_ERROR_NO_MEM;
    574 	}
    575 
    576 	priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
    577 	for (i=0; i<if_desc->bNumEndpoints; i++) {
    578 		priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
    579 		usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
    580 	}
    581 	libusb_free_config_descriptor(conf_desc);
    582 
    583 	// Extra init is required for WinUSB endpoints
    584 	if (priv->apib->id == USB_API_WINUSB) {
    585 		return winusb_configure_endpoints(dev_handle, iface);
    586 	}
    587 
    588 	return LIBUSB_SUCCESS;
    589 }
    590 
    591 // Lookup for a match in the list of API driver names
    592 static bool is_api_driver(char* driver, uint8_t api)
    593 {
    594 	uint8_t i;
    595 	const char sep_str[2] = {LIST_SEPARATOR, 0};
    596 	char *tok, *tmp_str;
    597 	size_t len = safe_strlen(driver);
    598 
    599 	if (len == 0) return false;
    600 	tmp_str = (char*) calloc(1, len+1);
    601 	if (tmp_str == NULL) return false;
    602 	memcpy(tmp_str, driver, len+1);
    603 	tok = strtok(tmp_str, sep_str);
    604 	while (tok != NULL) {
    605 		for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
    606 			if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
    607 				free(tmp_str);
    608 				return true;
    609 			}
    610 		}
    611 		tok = strtok(NULL, sep_str);
    612 	}
    613 	free (tmp_str);
    614 	return false;
    615 }
    616 
    617 /*
    618  * auto-claiming and auto-release helper functions
    619  */
    620 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
    621 {
    622 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
    623 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(
    624 		transfer->dev_handle);
    625 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
    626 	int current_interface = *interface_number;
    627 	int r = LIBUSB_SUCCESS;
    628 
    629 	usbi_mutex_lock(&autoclaim_lock);
    630 	if (current_interface < 0)	// No serviceable interface was found
    631 	{
    632 		for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
    633 			// Must claim an interface of the same API type
    634 			if ( (priv->usb_interface[current_interface].apib->id == api_type)
    635 			  && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
    636 				usbi_dbg("auto-claimed interface %d for control request", current_interface);
    637 				if (handle_priv->autoclaim_count[current_interface] != 0) {
    638 					usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
    639 				}
    640 				handle_priv->autoclaim_count[current_interface]++;
    641 				break;
    642 			}
    643 		}
    644 		if (current_interface == USB_MAXINTERFACES) {
    645 			usbi_err(ctx, "could not auto-claim any interface");
    646 			r = LIBUSB_ERROR_NOT_FOUND;
    647 		}
    648 	} else {
    649 		// If we have a valid interface that was autoclaimed, we must increment
    650 		// its autoclaim count so that we can prevent an early release.
    651 		if (handle_priv->autoclaim_count[current_interface] != 0) {
    652 			handle_priv->autoclaim_count[current_interface]++;
    653 		}
    654 	}
    655 	usbi_mutex_unlock(&autoclaim_lock);
    656 
    657 	*interface_number = current_interface;
    658 	return r;
    659 
    660 }
    661 
    662 static void auto_release(struct usbi_transfer *itransfer)
    663 {
    664 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
    665 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    666 	libusb_device_handle *dev_handle = transfer->dev_handle;
    667 	struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
    668 	int r;
    669 
    670 	usbi_mutex_lock(&autoclaim_lock);
    671 	if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
    672 		handle_priv->autoclaim_count[transfer_priv->interface_number]--;
    673 		if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
    674 			r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
    675 			if (r == LIBUSB_SUCCESS) {
    676 				usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
    677 			} else {
    678 				usbi_dbg("failed to auto-release interface %d (%s)",
    679 					transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
    680 			}
    681 		}
    682 	}
    683 	usbi_mutex_unlock(&autoclaim_lock);
    684 }
    685 
    686 /*
    687  * init: libusb backend init function
    688  *
    689  * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
    690  * In our implementation, we equate Windows' "HCD" to LibUSB's "bus". Note that bus is zero indexed.
    691  * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
    692  */
    693 static int windows_init(struct libusb_context *ctx)
    694 {
    695 	int i, r = LIBUSB_ERROR_OTHER;
    696 	OSVERSIONINFO os_version;
    697 	HANDLE semaphore;
    698 	char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
    699 
    700 	sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
    701 	semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
    702 	if (semaphore == NULL) {
    703 		usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
    704 		return LIBUSB_ERROR_NO_MEM;
    705 	}
    706 
    707 	// A successful wait brings our semaphore count to 0 (unsignaled)
    708 	// => any concurent wait stalls until the semaphore's release
    709 	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
    710 		usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
    711 		CloseHandle(semaphore);
    712 		return LIBUSB_ERROR_NO_MEM;
    713 	}
    714 
    715 	// NB: concurrent usage supposes that init calls are equally balanced with
    716 	// exit calls. If init is called more than exit, we will not exit properly
    717 	if ( ++concurrent_usage == 0 ) {	// First init?
    718 		// Detect OS version
    719 		memset(&os_version, 0, sizeof(OSVERSIONINFO));
    720 		os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    721 		windows_version = WINDOWS_UNSUPPORTED;
    722 		if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
    723 			if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
    724 				windows_version = WINDOWS_XP;
    725 			} else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
    726 				windows_version = WINDOWS_2003;	// also includes XP 64
    727 			} else if (os_version.dwMajorVersion >= 6) {
    728 				windows_version = WINDOWS_VISTA_AND_LATER;
    729 			}
    730 		}
    731 		if (windows_version == WINDOWS_UNSUPPORTED) {
    732 			usbi_err(ctx, "This version of Windows is NOT supported");
    733 			r = LIBUSB_ERROR_NOT_SUPPORTED;
    734 			goto init_exit;
    735 		}
    736 
    737 		// We need a lock for proper auto-release
    738 		usbi_mutex_init(&autoclaim_lock, NULL);
    739 
    740 		// Initialize pollable file descriptors
    741 		init_polling();
    742 
    743 		// Load DLL imports
    744 		if (init_dlls() != LIBUSB_SUCCESS) {
    745 			usbi_err(ctx, "could not resolve DLL functions");
    746 			return LIBUSB_ERROR_NOT_FOUND;
    747 		}
    748 
    749 		// Initialize the low level APIs (we don't care about errors at this stage)
    750 		for (i=0; i<USB_API_MAX; i++) {
    751 			usb_api_backend[i].init(ctx);
    752 		}
    753 
    754 		// Because QueryPerformanceCounter might report different values when
    755 		// running on different cores, we create a separate thread for the timer
    756 		// calls, which we glue to the first core always to prevent timing discrepancies.
    757 		r = LIBUSB_ERROR_NO_MEM;
    758 		for (i = 0; i < 2; i++) {
    759 			timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    760 			if (timer_request[i] == NULL) {
    761 				usbi_err(ctx, "could not create timer request event %d - aborting", i);
    762 				goto init_exit;
    763 			}
    764 		}
    765 		timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
    766 		if (timer_response == NULL) {
    767 			usbi_err(ctx, "could not create timer response semaphore - aborting");
    768 			goto init_exit;
    769 		}
    770 		timer_mutex = CreateMutex(NULL, FALSE, NULL);
    771 		if (timer_mutex == NULL) {
    772 			usbi_err(ctx, "could not create timer mutex - aborting");
    773 			goto init_exit;
    774 		}
    775 		timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
    776 		if (timer_thread == NULL) {
    777 			usbi_err(ctx, "Unable to create timer thread - aborting");
    778 			goto init_exit;
    779 		}
    780 		SetThreadAffinityMask(timer_thread, 0);
    781 
    782 		// Create a hash table to store session ids. Second parameter is better if prime
    783 		htab_create(ctx, HTAB_SIZE);
    784 	}
    785 	// At this stage, either we went through full init successfully, or didn't need to
    786 	r = LIBUSB_SUCCESS;
    787 
    788 init_exit: // Holds semaphore here.
    789 	if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
    790 		if (timer_thread) {
    791 			SetEvent(timer_request[1]); // actually the signal to quit the thread.
    792 			if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
    793 				usbi_warn(ctx, "could not wait for timer thread to quit");
    794 				TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
    795 												  // all objects it might have held anyway.
    796 			}
    797 			CloseHandle(timer_thread);
    798 			timer_thread = NULL;
    799 		}
    800 		for (i = 0; i < 2; i++) {
    801 			if (timer_request[i]) {
    802 				CloseHandle(timer_request[i]);
    803 				timer_request[i] = NULL;
    804 			}
    805 		}
    806 		if (timer_response) {
    807 			CloseHandle(timer_response);
    808 			timer_response = NULL;
    809 		}
    810 		if (timer_mutex) {
    811 			CloseHandle(timer_mutex);
    812 			timer_mutex = NULL;
    813 		}
    814 		htab_destroy();
    815 	}
    816 
    817 	if (r != LIBUSB_SUCCESS)
    818 		--concurrent_usage; // Not expected to call libusb_exit if we failed.
    819 
    820 	ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
    821 	CloseHandle(semaphore);
    822 	return r;
    823 }
    824 
    825 /*
    826  * HCD (root) hubs need to have their device descriptor manually populated
    827  *
    828  * Note that, like Microsoft does in the device manager, we populate the
    829  * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
    830  */
    831 static int force_hcd_device_descriptor(struct libusb_device *dev)
    832 {
    833 	struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
    834 	struct libusb_context *ctx = DEVICE_CTX(dev);
    835 	int vid, pid;
    836 
    837 	dev->num_configurations = 1;
    838 	priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
    839 	priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
    840 	priv->dev_descriptor.bNumConfigurations = 1;
    841 	priv->active_config = 1;
    842 
    843 	if (priv->parent_dev == NULL) {
    844 		usbi_err(ctx, "program assertion failed - HCD hub has no parent");
    845 		return LIBUSB_ERROR_NO_DEVICE;
    846 	}
    847 	parent_priv = _device_priv(priv->parent_dev);
    848 	if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
    849 		priv->dev_descriptor.idVendor = (uint16_t)vid;
    850 		priv->dev_descriptor.idProduct = (uint16_t)pid;
    851 	} else {
    852 		usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
    853 		priv->dev_descriptor.idVendor = 0x1d6b;		// Linux Foundation root hub
    854 		priv->dev_descriptor.idProduct = 1;
    855 	}
    856 	return LIBUSB_SUCCESS;
    857 }
    858 
    859 /*
    860  * fetch and cache all the config descriptors through I/O
    861  */
    862 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
    863 {
    864 	DWORD size, ret_size;
    865 	struct libusb_context *ctx = DEVICE_CTX(dev);
    866 	struct windows_device_priv *priv = _device_priv(dev);
    867 	int r;
    868 	uint8_t i;
    869 
    870 	USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short;    // dummy request
    871 	PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL;       // actual request
    872 	PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
    873 
    874 	if (dev->num_configurations == 0)
    875 		return LIBUSB_ERROR_INVALID_PARAM;
    876 
    877 	priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
    878 	if (priv->config_descriptor == NULL)
    879 		return LIBUSB_ERROR_NO_MEM;
    880 	for (i=0; i<dev->num_configurations; i++)
    881 		priv->config_descriptor[i] = NULL;
    882 
    883 	for (i=0, r=LIBUSB_SUCCESS; ; i++)
    884 	{
    885 		// safe loop: release all dynamic resources
    886 		safe_free(cd_buf_actual);
    887 
    888 		// safe loop: end of loop condition
    889 		if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
    890 			break;
    891 
    892 		size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
    893 		memset(&cd_buf_short, 0, size);
    894 
    895 		cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
    896 		cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
    897 		cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
    898 		cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
    899 		cd_buf_short.req.SetupPacket.wIndex = i;
    900 		cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
    901 
    902 		// Dummy call to get the required data size
    903 		if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
    904 			&cd_buf_short, size, &ret_size, NULL)) {
    905 			usbi_err(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
    906 			LOOP_BREAK(LIBUSB_ERROR_IO);
    907 		}
    908 
    909 		if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
    910 			usbi_err(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
    911 			LOOP_BREAK(LIBUSB_ERROR_IO);
    912 		}
    913 
    914 		size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
    915 		if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
    916 			usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
    917 			LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
    918 		}
    919 		memset(cd_buf_actual, 0, size);
    920 
    921 		// Actual call
    922 		cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
    923 		cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
    924 		cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
    925 		cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
    926 		cd_buf_actual->SetupPacket.wIndex = i;
    927 		cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
    928 
    929 		if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
    930 			cd_buf_actual, size, &ret_size, NULL)) {
    931 			usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
    932 			LOOP_BREAK(LIBUSB_ERROR_IO);
    933 		}
    934 
    935 		cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
    936 
    937 		if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
    938 			usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
    939 			LOOP_BREAK(LIBUSB_ERROR_IO);
    940 		}
    941 
    942 		if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
    943 			usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
    944 			LOOP_BREAK(LIBUSB_ERROR_IO);
    945 		}
    946 
    947 		usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
    948 			i, cd_data->bConfigurationValue, cd_data->wTotalLength);
    949 
    950 		// Cache the descriptor
    951 		priv->config_descriptor[i] = (unsigned char*) calloc(1, cd_data->wTotalLength);
    952 		if (priv->config_descriptor[i] == NULL)
    953 			return LIBUSB_ERROR_NO_MEM;
    954 		memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
    955 	}
    956 	return LIBUSB_SUCCESS;
    957 }
    958 
    959 /*
    960  * Populate a libusb device structure
    961  */
    962 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
    963 					   uint8_t port_number, char* device_id, DWORD devinst)
    964 {
    965 	HANDLE handle;
    966 	DWORD size;
    967 	USB_NODE_CONNECTION_INFORMATION_EX conn_info;
    968 	struct windows_device_priv *priv, *parent_priv;
    969 	struct libusb_context *ctx = DEVICE_CTX(dev);
    970 	struct libusb_device* tmp_dev;
    971 	unsigned i;
    972 
    973 	if ((dev == NULL) || (parent_dev == NULL)) {
    974 		return LIBUSB_ERROR_NOT_FOUND;
    975 	}
    976 	priv = _device_priv(dev);
    977 	parent_priv = _device_priv(parent_dev);
    978 	if (parent_priv->apib->id != USB_API_HUB) {
    979 		usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
    980 		return LIBUSB_ERROR_NOT_FOUND;
    981 	}
    982 
    983 	// It is possible for the parent hub not to have been initialized yet
    984 	// If that's the case, lookup the ancestors to set the bus number
    985 	if (parent_dev->bus_number == 0) {
    986 		for (i=2; ; i++) {
    987 			tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
    988 			if (tmp_dev == NULL) break;
    989 			if (tmp_dev->bus_number != 0) {
    990 				usbi_dbg("got bus number from ancestor #%d", i);
    991 				parent_dev->bus_number = tmp_dev->bus_number;
    992 				break;
    993 			}
    994 		}
    995 	}
    996 	if (parent_dev->bus_number == 0) {
    997 		usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
    998 		return LIBUSB_ERROR_NOT_FOUND;
    999 	}
   1000 	dev->bus_number = parent_dev->bus_number;
   1001 	priv->port = port_number;
   1002 	priv->depth = parent_priv->depth + 1;
   1003 	priv->parent_dev = parent_dev;
   1004 
   1005 	// If the device address is already set, we can stop here
   1006 	if (dev->device_address != 0) {
   1007 		return LIBUSB_SUCCESS;
   1008 	}
   1009 	memset(&conn_info, 0, sizeof(conn_info));
   1010 	if (priv->depth != 0) {	// Not a HCD hub
   1011 		handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
   1012 			FILE_FLAG_OVERLAPPED, NULL);
   1013 		if (handle == INVALID_HANDLE_VALUE) {
   1014 			usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
   1015 			return LIBUSB_ERROR_ACCESS;
   1016 		}
   1017 		size = sizeof(conn_info);
   1018 		conn_info.ConnectionIndex = (ULONG)port_number;
   1019 		if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
   1020 			&conn_info, size, &size, NULL)) {
   1021 			usbi_warn(ctx, "could not get node connection information for device '%s': %s",
   1022 				device_id, windows_error_str(0));
   1023 			safe_closehandle(handle);
   1024 			return LIBUSB_ERROR_NO_DEVICE;
   1025 		}
   1026 		if (conn_info.ConnectionStatus == NoDeviceConnected) {
   1027 			usbi_err(ctx, "device '%s' is no longer connected!", device_id);
   1028 			safe_closehandle(handle);
   1029 			return LIBUSB_ERROR_NO_DEVICE;
   1030 		}
   1031 		memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
   1032 		dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
   1033 		priv->active_config = conn_info.CurrentConfigurationValue;
   1034 		usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
   1035 		// If we can't read the config descriptors, just set the number of confs to zero
   1036 		if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
   1037 			dev->num_configurations = 0;
   1038 			priv->dev_descriptor.bNumConfigurations = 0;
   1039 		}
   1040 		safe_closehandle(handle);
   1041 
   1042 		if (conn_info.DeviceAddress > UINT8_MAX) {
   1043 			usbi_err(ctx, "program assertion failed: device address overflow");
   1044 		}
   1045 		dev->device_address = (uint8_t)conn_info.DeviceAddress;
   1046 		switch (conn_info.Speed) {
   1047 		case 0: dev->speed = LIBUSB_SPEED_LOW; break;
   1048 		case 1: dev->speed = LIBUSB_SPEED_FULL; break;
   1049 		case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
   1050 		case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
   1051 		default:
   1052 			usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
   1053 			break;
   1054 		}
   1055 	} else {
   1056 		dev->device_address = UINT8_MAX;	// Hubs from HCD have a devaddr of 255
   1057 		force_hcd_device_descriptor(dev);
   1058 	}
   1059 
   1060 	usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
   1061 		dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
   1062 
   1063 	return LIBUSB_SUCCESS;
   1064 }
   1065 
   1066 // Returns the api type, or 0 if not found/unsupported
   1067 static uint8_t get_api_type(struct libusb_context *ctx,
   1068 						HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
   1069 {
   1070 	// Precedence for filter drivers vs driver is in the order of this array
   1071 	struct driver_lookup lookup[3] = {
   1072 		{"\0\0", SPDRP_SERVICE, "driver"},
   1073 		{"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
   1074 		{"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
   1075 	};
   1076 	DWORD size, reg_type;
   1077 	unsigned k, l;
   1078 	uint8_t api;
   1079 
   1080 	// Check the service & filter names to know the API we should use
   1081 	for (k=0; k<3; k++) {
   1082 		if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
   1083 			&reg_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
   1084 			// Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
   1085 			if (lookup[k].reg_prop == SPDRP_SERVICE) {
   1086 				// our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
   1087 				lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
   1088 			}
   1089 			// MULTI_SZ is a pain to work with. Turn it into something much more manageable
   1090 			// NB: none of the driver names we check against contain LIST_SEPARATOR,
   1091 			// (currently ';'), so even if an unsuported one does, it's not an issue
   1092 			for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
   1093 				if (lookup[k].list[l] == 0) {
   1094 					lookup[k].list[l] = LIST_SEPARATOR;
   1095 				}
   1096 			}
   1097 			upperize(lookup[k].list);
   1098 			usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
   1099 		} else {
   1100 			if (GetLastError() != ERROR_INVALID_DATA) {
   1101 				usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
   1102 			}
   1103 			lookup[k].list[0] = 0;
   1104 		}
   1105 	}
   1106 
   1107 	for (api=1; api<USB_API_MAX; api++) {
   1108 		for (k=0; k<3; k++) {
   1109 			if (is_api_driver(lookup[k].list, api)) {
   1110 				usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
   1111 				break;
   1112 			}
   1113 		}
   1114 		if (k >= 3) continue;
   1115 		return api;
   1116 	}
   1117 	return 0;
   1118 }
   1119 
   1120 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
   1121 							char* dev_interface_path, char* device_id, uint8_t api)
   1122 {
   1123 	unsigned i;
   1124 	struct windows_device_priv *priv = _device_priv(dev);
   1125 	int interface_number;
   1126 
   1127 	if (priv->apib->id != USB_API_COMPOSITE) {
   1128 		usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
   1129 		return LIBUSB_ERROR_NO_DEVICE;
   1130 	}
   1131 
   1132 	// Because MI_## are not necessarily in sequential order (some composite
   1133 	// devices will have only MI_00 & MI_03 for instance), we retrieve the actual
   1134 	// interface number from the path's MI value
   1135 	interface_number = 0;
   1136 	for (i=0; device_id[i] != 0; ) {
   1137 		if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
   1138 		  && (device_id[i++] == '_') ) {
   1139 			interface_number = (device_id[i++] - '0')*10;
   1140 			interface_number += device_id[i] - '0';
   1141 			break;
   1142 		}
   1143 	}
   1144 
   1145 	if (device_id[i] == 0) {
   1146 		usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
   1147 			device_id, interface_number);
   1148 	}
   1149 
   1150 	if (priv->usb_interface[interface_number].path != NULL) {
   1151 		usbi_warn(ctx, "interface[%d] already set - ignoring: %s", interface_number, device_id);
   1152 		return LIBUSB_ERROR_ACCESS;
   1153 	}
   1154 
   1155 	usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
   1156 	priv->usb_interface[interface_number].path = dev_interface_path;
   1157 	priv->usb_interface[interface_number].apib = &usb_api_backend[api];
   1158 	priv->composite_api_flags |= 1<<api;
   1159 
   1160 	return LIBUSB_SUCCESS;
   1161 }
   1162 
   1163 /*
   1164  * get_device_list: libusb backend device enumeration function
   1165  */
   1166 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
   1167 {
   1168 	struct discovered_devs *discdevs;
   1169 	HDEVINFO dev_info = { 0 };
   1170 	char* usb_class[2] = {"USB", "NUSB3"};
   1171 	SP_DEVINFO_DATA dev_info_data;
   1172 	SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
   1173 #define MAX_ENUM_GUIDS 64
   1174 	const GUID* guid[MAX_ENUM_GUIDS];
   1175 #define HCD_PASS 0
   1176 #define HUB_PASS 1
   1177 #define GEN_PASS 2
   1178 #define DEV_PASS 3
   1179 	int r = LIBUSB_SUCCESS;
   1180 	int class_index = 0;
   1181 	unsigned int nb_guids, pass, i, j, ancestor;
   1182 	char path[MAX_PATH_LENGTH];
   1183 	char strbuf[MAX_PATH_LENGTH];
   1184 	struct libusb_device *dev, *parent_dev;
   1185 	struct windows_device_priv *priv, *parent_priv;
   1186 	char* dev_interface_path = NULL;
   1187 	char* dev_id_path = NULL;
   1188 	unsigned long session_id;
   1189 	DWORD size, reg_type, port_nr, install_state;
   1190 	BOOL b = FALSE;
   1191 	HKEY key;
   1192 	WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
   1193 	GUID* if_guid;
   1194 	LONG s;
   1195 	uint8_t api;
   1196 	// Keep a list of newly allocated devs to unref
   1197 	libusb_device** unref_list;
   1198 	unsigned int unref_size = 64;
   1199 	unsigned int unref_cur = 0;
   1200 
   1201 	// PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
   1202 	// PASS 2 : (re)enumerate HUBS
   1203 	// PASS 3 : (re)enumerate generic USB devices (including driverless)
   1204 	//           and list additional USB device interface GUIDs to explore
   1205 	// PASS 4 : (re)enumerate master USB devices that have a device interface
   1206 	// PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.
   1207 
   1208 	// Init the GUID table
   1209 	guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
   1210 	guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
   1211 	guid[GEN_PASS] = NULL;
   1212 	guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
   1213 	nb_guids = DEV_PASS+1;
   1214 
   1215 	unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
   1216 	if (unref_list == NULL) {
   1217 		return LIBUSB_ERROR_NO_MEM;
   1218 	}
   1219 
   1220 	for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
   1221 //#define ENUM_DEBUG
   1222 #ifdef ENUM_DEBUG
   1223 		switch(pass) {
   1224 		case HCD_PASS:
   1225 			usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
   1226 			break;
   1227 		case HUB_PASS:
   1228 			usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
   1229 			break;
   1230 		case DEV_PASS:
   1231 			usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
   1232 			break;
   1233 		case GEN_PASS:
   1234 			usbi_dbg("PROCESSING GENs");
   1235 			break;
   1236 		default:
   1237 			usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
   1238 			break;
   1239 		}
   1240 #endif
   1241 		for (i = 0; ; i++) {
   1242 			// safe loop: free up any (unprotected) dynamic resource
   1243 			// NB: this is always executed before breaking the loop
   1244 			safe_free(dev_interface_details);
   1245 			safe_free(dev_interface_path);
   1246 			safe_free(dev_id_path);
   1247 			priv = parent_priv = NULL;
   1248 			dev = parent_dev = NULL;
   1249 
   1250 			// Safe loop: end of loop conditions
   1251 			if (r != LIBUSB_SUCCESS) {
   1252 				break;
   1253 			}
   1254 			if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
   1255 				usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
   1256 				break;
   1257 			}
   1258 			if (pass != GEN_PASS) {
   1259 				// Except for GEN, all passes deal with device interfaces
   1260 				dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
   1261 				if (dev_interface_details == NULL) {
   1262 					break;
   1263 				} else {
   1264 					dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
   1265 					if (dev_interface_path == NULL) {
   1266 						usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
   1267 						continue;
   1268 					}
   1269 				}
   1270 			} else {
   1271 				// Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
   1272 				// being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
   1273 				while ( (class_index < 2) &&
   1274 					    (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
   1275 						class_index++;
   1276 						i = 0;
   1277 				}
   1278 				if (!b) break;
   1279 			}
   1280 
   1281 			// Read the Device ID path. This is what we'll use as UID
   1282 			// Note that if the device is plugged in a different port or hub, the Device ID changes
   1283 			if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
   1284 				usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
   1285 					dev_info_data.DevInst);
   1286 				continue;
   1287 			}
   1288 			dev_id_path = sanitize_path(path);
   1289 			if (dev_id_path == NULL) {
   1290 				usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
   1291 					dev_info_data.DevInst);
   1292 				continue;
   1293 			}
   1294 #ifdef ENUM_DEBUG
   1295 			usbi_dbg("PRO: %s", dev_id_path);
   1296 #endif
   1297 
   1298 			// The SPDRP_ADDRESS for USB devices is the device port number on the hub
   1299 			port_nr = 0;
   1300 			if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
   1301 				if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
   1302 					&reg_type, (BYTE*)&port_nr, 4, &size))
   1303 				  || (size != 4) ) {
   1304 					usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
   1305 						dev_id_path, windows_error_str(0));
   1306 					continue;
   1307 				}
   1308 			}
   1309 
   1310 			// Set API to use or get additional data from generic pass
   1311 			api = USB_API_UNSUPPORTED;
   1312 			switch (pass) {
   1313 			case HCD_PASS:
   1314 				break;
   1315 			case GEN_PASS:
   1316 				// We use the GEN pass to detect driverless devices...
   1317 				size = sizeof(strbuf);
   1318 				if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
   1319 					&reg_type, (BYTE*)strbuf, size, &size)) {
   1320 						usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
   1321 						usbi_info(ctx, "libusb will not be able to access it.");
   1322 				}
   1323 				// ...and to add the additional device interface GUIDs
   1324 				key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
   1325 				if (key != INVALID_HANDLE_VALUE) {
   1326 					size = sizeof(guid_string_w);
   1327 					s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &reg_type,
   1328 						(BYTE*)guid_string_w, &size);
   1329 					pRegCloseKey(key);
   1330 					if (s == ERROR_SUCCESS) {
   1331 						if (nb_guids >= MAX_ENUM_GUIDS) {
   1332 							// If this assert is ever reported, grow a GUID table dynamically
   1333 							usbi_err(ctx, "program assertion failed: too many GUIDs");
   1334 							LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
   1335 						}
   1336 						if_guid = (GUID*) calloc(1, sizeof(GUID));
   1337 						pCLSIDFromString(guid_string_w, if_guid);
   1338 						guid[nb_guids++] = if_guid;
   1339 						usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
   1340 					}
   1341 				}
   1342 				break;
   1343 			default:
   1344 				// Get the API type (after checking that the driver installation is OK)
   1345 				if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
   1346 					&reg_type, (BYTE*)&install_state, 4, &size))
   1347 				  || (size != 4) ){
   1348 					usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
   1349 						dev_id_path, windows_error_str(0));
   1350 				} else if (install_state != 0) {
   1351 					usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
   1352 						dev_id_path, install_state);
   1353 					continue;
   1354 				}
   1355 				api = get_api_type(ctx, &dev_info, &dev_info_data);
   1356 				break;
   1357 			}
   1358 
   1359 			// Find parent device (for the passes that need it)
   1360 			switch (pass) {
   1361 			case HCD_PASS:
   1362 			case DEV_PASS:
   1363 			case HUB_PASS:
   1364 				break;
   1365 			default:
   1366 				// Go through the ancestors until we see a face we recognize
   1367 				parent_dev = NULL;
   1368 				for (ancestor = 1; parent_dev == NULL; ancestor++) {
   1369 					session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
   1370 					if (session_id == 0) {
   1371 						break;
   1372 					}
   1373 					parent_dev = usbi_get_device_by_session_id(ctx, session_id);
   1374 				}
   1375 				if (parent_dev == NULL) {
   1376 					usbi_dbg("unlisted ancestor for '%s' (newly connected, etc.) - ignoring", dev_id_path);
   1377 					continue;
   1378 				}
   1379 				parent_priv = _device_priv(parent_dev);
   1380 				// virtual USB devices are also listed during GEN - don't process these yet
   1381 				if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
   1382 					continue;
   1383 				}
   1384 				break;
   1385 			}
   1386 
   1387 			// Create new or match existing device, using the (hashed) device_id as session id
   1388 			if (pass <= DEV_PASS) {	// For subsequent passes, we'll lookup the parent
   1389 				// These are the passes that create "new" devices
   1390 				session_id = htab_hash(dev_id_path);
   1391 				dev = usbi_get_device_by_session_id(ctx, session_id);
   1392 				if (dev == NULL) {
   1393 					if (pass == DEV_PASS) {
   1394 						// This can occur if the OS only reports a newly plugged device after we started enum
   1395 						usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
   1396 							" - ignoring", dev_id_path);
   1397 						continue;
   1398 					}
   1399 					usbi_dbg("allocating new device for session [%X]", session_id);
   1400 					if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
   1401 						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1402 					}
   1403 					windows_device_priv_init(dev);
   1404 					// Keep track of devices that need unref
   1405 					unref_list[unref_cur++] = dev;
   1406 					if (unref_cur >= unref_size) {
   1407 						unref_size += 64;
   1408 						unref_list = realloc(unref_list, unref_size*sizeof(libusb_device*));
   1409 						if (unref_list == NULL) {
   1410 							usbi_err(ctx, "could not realloc list for unref - aborting.");
   1411 							LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1412 						}
   1413 					}
   1414 				} else {
   1415 					usbi_dbg("found existing device for session [%X] (%d.%d)",
   1416 						session_id, dev->bus_number, dev->device_address);
   1417 				}
   1418 				priv = _device_priv(dev);
   1419 			}
   1420 
   1421 			// Setup device
   1422 			switch (pass) {
   1423 			case HCD_PASS:
   1424 				dev->bus_number = (uint8_t)(i + 1);	// bus 0 is reserved for disconnected
   1425 				dev->device_address = 0;
   1426 				dev->num_configurations = 0;
   1427 				priv->apib = &usb_api_backend[USB_API_HUB];
   1428 				priv->depth = UINT8_MAX;	// Overflow to 0 for HCD Hubs
   1429 				priv->path = dev_interface_path; dev_interface_path = NULL;
   1430 				break;
   1431 			case HUB_PASS:
   1432 			case DEV_PASS:
   1433 				// If the device has already been setup, don't do it again
   1434 				if (priv->path != NULL)
   1435 					break;
   1436 				// Take care of API initialization
   1437 				priv->path = dev_interface_path; dev_interface_path = NULL;
   1438 				priv->apib = &usb_api_backend[api];
   1439 				switch(api) {
   1440 				case USB_API_COMPOSITE:
   1441 				case USB_API_HUB:
   1442 					break;
   1443 				default:
   1444 					// For other devices, the first interface is the same as the device
   1445 					priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
   1446 					if (priv->usb_interface[0].path != NULL) {
   1447 						safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
   1448 					} else {
   1449 						usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
   1450 					}
   1451 					// The following is needed if we want API calls to work for both simple
   1452 					// and composite devices.
   1453 					for(j=0; j<USB_MAXINTERFACES; j++) {
   1454 						priv->usb_interface[j].apib = &usb_api_backend[api];
   1455 					}
   1456 					break;
   1457 				}
   1458 				break;
   1459 			case GEN_PASS:
   1460 				r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
   1461 				if (r == LIBUSB_SUCCESS) {
   1462 					// Append device to the list of discovered devices
   1463 					discdevs = discovered_devs_append(*_discdevs, dev);
   1464 					if (!discdevs) {
   1465 						LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
   1466 					}
   1467 					*_discdevs = discdevs;
   1468 				} else if (r == LIBUSB_ERROR_NO_DEVICE) {
   1469 					// This can occur if the device was disconnected but Windows hasn't
   1470 					// refreshed its enumeration yet - in that case, we ignore the device
   1471 					r = LIBUSB_SUCCESS;
   1472 				}
   1473 				break;
   1474 			default:	// later passes
   1475 				if (parent_priv->apib->id == USB_API_COMPOSITE) {
   1476 					usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
   1477 					switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
   1478 					case LIBUSB_SUCCESS:
   1479 						dev_interface_path = NULL;
   1480 						break;
   1481 					case LIBUSB_ERROR_ACCESS:
   1482 						// interface has already been set => make sure dev_interface_path is freed then
   1483 						break;
   1484 					default:
   1485 						LOOP_BREAK(r);
   1486 						break;
   1487 					}
   1488 				}
   1489 				break;
   1490 			}
   1491 		}
   1492 	}
   1493 
   1494 	// Free any additional GUIDs
   1495 	for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
   1496 		safe_free(guid[pass]);
   1497 	}
   1498 
   1499 	// Unref newly allocated devs
   1500 	for (i=0; i<unref_cur; i++) {
   1501 		safe_unref_device(unref_list[i]);
   1502 	}
   1503 	safe_free(unref_list);
   1504 
   1505 	return r;
   1506 }
   1507 
   1508 /*
   1509  * exit: libusb backend deinitialization function
   1510  */
   1511 static void windows_exit(void)
   1512 {
   1513 	int i;
   1514 	HANDLE semaphore;
   1515 	char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
   1516 
   1517 	sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
   1518 	semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
   1519 	if (semaphore == NULL) {
   1520 		return;
   1521 	}
   1522 
   1523 	// A successful wait brings our semaphore count to 0 (unsignaled)
   1524 	// => any concurent wait stalls until the semaphore release
   1525 	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
   1526 		CloseHandle(semaphore);
   1527 		return;
   1528 	}
   1529 
   1530 	// Only works if exits and inits are balanced exactly
   1531 	if (--concurrent_usage < 0) {	// Last exit
   1532 		for (i=0; i<USB_API_MAX; i++) {
   1533 			usb_api_backend[i].exit();
   1534 		}
   1535 		exit_polling();
   1536 
   1537 		if (timer_thread) {
   1538 			SetEvent(timer_request[1]); // actually the signal to quit the thread.
   1539 			if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
   1540 				usbi_dbg("could not wait for timer thread to quit");
   1541 				TerminateThread(timer_thread, 1);
   1542 			}
   1543 			CloseHandle(timer_thread);
   1544 			timer_thread = NULL;
   1545 		}
   1546 		for (i = 0; i < 2; i++) {
   1547 			if (timer_request[i]) {
   1548 				CloseHandle(timer_request[i]);
   1549 				timer_request[i] = NULL;
   1550 			}
   1551 		}
   1552 		if (timer_response) {
   1553 			CloseHandle(timer_response);
   1554 			timer_response = NULL;
   1555 		}
   1556 		if (timer_mutex) {
   1557 			CloseHandle(timer_mutex);
   1558 			timer_mutex = NULL;
   1559 		}
   1560 		htab_destroy();
   1561 	}
   1562 
   1563 	ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
   1564 	CloseHandle(semaphore);
   1565 }
   1566 
   1567 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
   1568 {
   1569 	struct windows_device_priv *priv = _device_priv(dev);
   1570 
   1571 	memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
   1572 	*host_endian = 0;
   1573 
   1574 	return LIBUSB_SUCCESS;
   1575 }
   1576 
   1577 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
   1578 {
   1579 	struct windows_device_priv *priv = _device_priv(dev);
   1580 	PUSB_CONFIGURATION_DESCRIPTOR config_header;
   1581 	size_t size;
   1582 
   1583 	// config index is zero based
   1584 	if (config_index >= dev->num_configurations)
   1585 		return LIBUSB_ERROR_INVALID_PARAM;
   1586 
   1587 	if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
   1588 		return LIBUSB_ERROR_NOT_FOUND;
   1589 
   1590 	config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
   1591 
   1592 	size = min(config_header->wTotalLength, len);
   1593 	memcpy(buffer, priv->config_descriptor[config_index], size);
   1594 
   1595 	return LIBUSB_SUCCESS;
   1596 }
   1597 
   1598 /*
   1599  * return the cached copy of the active config descriptor
   1600  */
   1601 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
   1602 {
   1603 	struct windows_device_priv *priv = _device_priv(dev);
   1604 
   1605 	if (priv->active_config == 0)
   1606 		return LIBUSB_ERROR_NOT_FOUND;
   1607 
   1608 	// config index is zero based
   1609 	return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
   1610 }
   1611 
   1612 static int windows_open(struct libusb_device_handle *dev_handle)
   1613 {
   1614 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1615 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   1616 
   1617 	if (priv->apib == NULL) {
   1618 		usbi_err(ctx, "program assertion failed - device is not initialized");
   1619 		return LIBUSB_ERROR_NO_DEVICE;
   1620 	}
   1621 
   1622 	return priv->apib->open(dev_handle);
   1623 }
   1624 
   1625 static void windows_close(struct libusb_device_handle *dev_handle)
   1626 {
   1627 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1628 
   1629 	priv->apib->close(dev_handle);
   1630 }
   1631 
   1632 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
   1633 {
   1634 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1635 
   1636 	if (priv->active_config == 0) {
   1637 		*config = 0;
   1638 		return LIBUSB_ERROR_NOT_FOUND;
   1639 	}
   1640 
   1641 	*config = priv->active_config;
   1642 	return LIBUSB_SUCCESS;
   1643 }
   1644 
   1645 /*
   1646  * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
   1647  * does not currently expose a service that allows higher-level drivers to set
   1648  * the configuration."
   1649  */
   1650 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
   1651 {
   1652 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1653 	int r = LIBUSB_SUCCESS;
   1654 
   1655 	if (config >= USB_MAXCONFIG)
   1656 		return LIBUSB_ERROR_INVALID_PARAM;
   1657 
   1658 	r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
   1659 		LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
   1660 		LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
   1661 		0, NULL, 0, 1000);
   1662 
   1663 	if (r == LIBUSB_SUCCESS) {
   1664 		priv->active_config = (uint8_t)config;
   1665 	}
   1666 	return r;
   1667 }
   1668 
   1669 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
   1670 {
   1671 	int r = LIBUSB_SUCCESS;
   1672 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1673 
   1674 	if (iface >= USB_MAXINTERFACES)
   1675 		return LIBUSB_ERROR_INVALID_PARAM;
   1676 
   1677 	safe_free(priv->usb_interface[iface].endpoint);
   1678 	priv->usb_interface[iface].nb_endpoints= 0;
   1679 
   1680 	r = priv->apib->claim_interface(dev_handle, iface);
   1681 
   1682 	if (r == LIBUSB_SUCCESS) {
   1683 		r = windows_assign_endpoints(dev_handle, iface, 0);
   1684 	}
   1685 
   1686 	return r;
   1687 }
   1688 
   1689 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
   1690 {
   1691 	int r = LIBUSB_SUCCESS;
   1692 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1693 
   1694 	safe_free(priv->usb_interface[iface].endpoint);
   1695 	priv->usb_interface[iface].nb_endpoints= 0;
   1696 
   1697 	r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
   1698 
   1699 	if (r == LIBUSB_SUCCESS) {
   1700 		r = windows_assign_endpoints(dev_handle, iface, altsetting);
   1701 	}
   1702 
   1703 	return r;
   1704 }
   1705 
   1706 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
   1707 {
   1708 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1709 
   1710 	return priv->apib->release_interface(dev_handle, iface);
   1711 }
   1712 
   1713 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
   1714 {
   1715 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1716 	return priv->apib->clear_halt(dev_handle, endpoint);
   1717 }
   1718 
   1719 static int windows_reset_device(struct libusb_device_handle *dev_handle)
   1720 {
   1721 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   1722 	return priv->apib->reset_device(dev_handle);
   1723 }
   1724 
   1725 // The 3 functions below are unlikely to ever get supported on Windows
   1726 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
   1727 {
   1728 	return LIBUSB_ERROR_NOT_SUPPORTED;
   1729 }
   1730 
   1731 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
   1732 {
   1733 	return LIBUSB_ERROR_NOT_SUPPORTED;
   1734 }
   1735 
   1736 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
   1737 {
   1738 	return LIBUSB_ERROR_NOT_SUPPORTED;
   1739 }
   1740 
   1741 static void windows_destroy_device(struct libusb_device *dev)
   1742 {
   1743 	windows_device_priv_release(dev);
   1744 }
   1745 
   1746 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
   1747 {
   1748 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1749 
   1750 	usbi_free_fd(transfer_priv->pollable_fd.fd);
   1751 	// When auto claim is in use, attempt to release the auto-claimed interface
   1752 	auto_release(itransfer);
   1753 }
   1754 
   1755 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
   1756 {
   1757 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1758 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   1759 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1760 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1761 	int r;
   1762 
   1763 	r = priv->apib->submit_bulk_transfer(itransfer);
   1764 	if (r != LIBUSB_SUCCESS) {
   1765 		return r;
   1766 	}
   1767 
   1768 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
   1769 		(short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
   1770 
   1771 	return LIBUSB_SUCCESS;
   1772 }
   1773 
   1774 static int submit_iso_transfer(struct usbi_transfer *itransfer)
   1775 {
   1776 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1777 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   1778 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1779 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1780 	int r;
   1781 
   1782 	r = priv->apib->submit_iso_transfer(itransfer);
   1783 	if (r != LIBUSB_SUCCESS) {
   1784 		return r;
   1785 	}
   1786 
   1787 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
   1788 		(short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
   1789 
   1790 	return LIBUSB_SUCCESS;
   1791 }
   1792 
   1793 static int submit_control_transfer(struct usbi_transfer *itransfer)
   1794 {
   1795 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1796 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   1797 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   1798 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1799 	int r;
   1800 
   1801 	r = priv->apib->submit_control_transfer(itransfer);
   1802 	if (r != LIBUSB_SUCCESS) {
   1803 		return r;
   1804 	}
   1805 
   1806 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
   1807 
   1808 	return LIBUSB_SUCCESS;
   1809 
   1810 }
   1811 
   1812 static int windows_submit_transfer(struct usbi_transfer *itransfer)
   1813 {
   1814 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1815 
   1816 	switch (transfer->type) {
   1817 	case LIBUSB_TRANSFER_TYPE_CONTROL:
   1818 		return submit_control_transfer(itransfer);
   1819 	case LIBUSB_TRANSFER_TYPE_BULK:
   1820 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   1821 		if (IS_XFEROUT(transfer) &&
   1822 		    transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
   1823 			return LIBUSB_ERROR_NOT_SUPPORTED;
   1824 		return submit_bulk_transfer(itransfer);
   1825 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   1826 		return submit_iso_transfer(itransfer);
   1827 	default:
   1828 		usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
   1829 		return LIBUSB_ERROR_INVALID_PARAM;
   1830 	}
   1831 }
   1832 
   1833 static int windows_abort_control(struct usbi_transfer *itransfer)
   1834 {
   1835 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1836 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1837 
   1838 	return priv->apib->abort_control(itransfer);
   1839 }
   1840 
   1841 static int windows_abort_transfers(struct usbi_transfer *itransfer)
   1842 {
   1843 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1844 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1845 
   1846 	return priv->apib->abort_transfers(itransfer);
   1847 }
   1848 
   1849 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
   1850 {
   1851 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1852 
   1853 	switch (transfer->type) {
   1854 	case LIBUSB_TRANSFER_TYPE_CONTROL:
   1855 		return windows_abort_control(itransfer);
   1856 	case LIBUSB_TRANSFER_TYPE_BULK:
   1857 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   1858 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   1859 		return windows_abort_transfers(itransfer);
   1860 	default:
   1861 		usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
   1862 		return LIBUSB_ERROR_INVALID_PARAM;
   1863 	}
   1864 }
   1865 
   1866 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
   1867 {
   1868 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1869 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   1870 	int status;
   1871 
   1872 	usbi_dbg("handling I/O completion with errcode %d", io_result);
   1873 
   1874 	switch(io_result) {
   1875 	case NO_ERROR:
   1876 		status = priv->apib->copy_transfer_data(itransfer, io_size);
   1877 		break;
   1878 	case ERROR_GEN_FAILURE:
   1879 		usbi_dbg("detected endpoint stall");
   1880 		status = LIBUSB_TRANSFER_STALL;
   1881 		break;
   1882 	case ERROR_SEM_TIMEOUT:
   1883 		usbi_dbg("detected semaphore timeout");
   1884 		status = LIBUSB_TRANSFER_TIMED_OUT;
   1885 		break;
   1886 	case ERROR_OPERATION_ABORTED:
   1887 		if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
   1888 			usbi_dbg("detected timeout");
   1889 			status = LIBUSB_TRANSFER_TIMED_OUT;
   1890 		} else {
   1891 			usbi_dbg("detected operation aborted");
   1892 			status = LIBUSB_TRANSFER_CANCELLED;
   1893 		}
   1894 		break;
   1895 	default:
   1896 		usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
   1897 		status = LIBUSB_TRANSFER_ERROR;
   1898 		break;
   1899 	}
   1900 	windows_clear_transfer_priv(itransfer);	// Cancel polling
   1901 	usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
   1902 }
   1903 
   1904 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
   1905 {
   1906 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   1907 
   1908 	switch (transfer->type) {
   1909 	case LIBUSB_TRANSFER_TYPE_CONTROL:
   1910 	case LIBUSB_TRANSFER_TYPE_BULK:
   1911 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
   1912 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
   1913 		windows_transfer_callback (itransfer, io_result, io_size);
   1914 		break;
   1915 	default:
   1916 		usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
   1917 	}
   1918 }
   1919 
   1920 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
   1921 {
   1922 	struct windows_transfer_priv* transfer_priv = NULL;
   1923 	POLL_NFDS_TYPE i = 0;
   1924 	bool found = false;
   1925 	struct usbi_transfer *transfer;
   1926 	DWORD io_size, io_result;
   1927 
   1928 	usbi_mutex_lock(&ctx->open_devs_lock);
   1929 	for (i = 0; i < nfds && num_ready > 0; i++) {
   1930 
   1931 		usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
   1932 
   1933 		if (!fds[i].revents) {
   1934 			continue;
   1935 		}
   1936 
   1937 		num_ready--;
   1938 
   1939 		// Because a Windows OVERLAPPED is used for poll emulation,
   1940 		// a pollable fd is created and stored with each transfer
   1941 		usbi_mutex_lock(&ctx->flying_transfers_lock);
   1942 		list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
   1943 			transfer_priv = usbi_transfer_get_os_priv(transfer);
   1944 			if (transfer_priv->pollable_fd.fd == fds[i].fd) {
   1945 				found = true;
   1946 				break;
   1947 			}
   1948 		}
   1949 		usbi_mutex_unlock(&ctx->flying_transfers_lock);
   1950 
   1951 		if (found) {
   1952 			// Handle async requests that completed synchronously first
   1953 			if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
   1954 				io_result = NO_ERROR;
   1955 				io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
   1956 			// Regular async overlapped
   1957 			} else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
   1958 				transfer_priv->pollable_fd.overlapped, &io_size, false)) {
   1959 				io_result = NO_ERROR;
   1960 			} else {
   1961 				io_result = GetLastError();
   1962 			}
   1963 			usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
   1964 			// let handle_callback free the event using the transfer wfd
   1965 			// If you don't use the transfer wfd, you run a risk of trying to free a
   1966 			// newly allocated wfd that took the place of the one from the transfer.
   1967 			windows_handle_callback(transfer, io_result, io_size);
   1968 		} else {
   1969 			usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
   1970 			return LIBUSB_ERROR_NOT_FOUND;
   1971 		}
   1972 	}
   1973 
   1974 	usbi_mutex_unlock(&ctx->open_devs_lock);
   1975 	return LIBUSB_SUCCESS;
   1976 }
   1977 
   1978 /*
   1979  * Monotonic and real time functions
   1980  */
   1981 unsigned __stdcall windows_clock_gettime_threaded(void* param)
   1982 {
   1983 	LARGE_INTEGER hires_counter, li_frequency;
   1984 	LONG nb_responses;
   1985 	int timer_index;
   1986 
   1987 	// Init - find out if we have access to a monotonic (hires) timer
   1988 	if (!QueryPerformanceFrequency(&li_frequency)) {
   1989 		usbi_dbg("no hires timer available on this platform");
   1990 		hires_frequency = 0;
   1991 		hires_ticks_to_ps = UINT64_C(0);
   1992 	} else {
   1993 		hires_frequency = li_frequency.QuadPart;
   1994 		// The hires frequency can go as high as 4 GHz, so we'll use a conversion
   1995 		// to picoseconds to compute the tv_nsecs part in clock_gettime
   1996 		hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
   1997 		usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
   1998 	}
   1999 
   2000 	// Main loop - wait for requests
   2001 	while (1) {
   2002 		timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
   2003 		if ( (timer_index != 0) && (timer_index != 1) ) {
   2004 			usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
   2005 			continue;
   2006 		}
   2007 		if (request_count[timer_index] == 0) {
   2008 			// Request already handled
   2009 			ResetEvent(timer_request[timer_index]);
   2010 			// There's still a possiblity that a thread sends a request between the
   2011 			// time we test request_count[] == 0 and we reset the event, in which case
   2012 			// the request would be ignored. The simple solution to that is to test
   2013 			// request_count again and process requests if non zero.
   2014 			if (request_count[timer_index] == 0)
   2015 				continue;
   2016 		}
   2017 		switch (timer_index) {
   2018 		case 0:
   2019 			WaitForSingleObject(timer_mutex, INFINITE);
   2020 			// Requests to this thread are for hires always
   2021 			if (QueryPerformanceCounter(&hires_counter) != 0) {
   2022 				timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
   2023 				timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
   2024 			} else {
   2025 				// Fallback to real-time if we can't get monotonic value
   2026 				// Note that real-time clock does not wait on the mutex or this thread.
   2027 				windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
   2028 			}
   2029 			ReleaseMutex(timer_mutex);
   2030 
   2031 			nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
   2032 			if ( (nb_responses)
   2033 			  && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
   2034 				usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
   2035 			}
   2036 			continue;
   2037 		case 1: // time to quit
   2038 			usbi_dbg("timer thread quitting");
   2039 			return 0;
   2040 		}
   2041 	}
   2042 	usbi_dbg("ERROR: broken timer thread");
   2043 	return 1;
   2044 }
   2045 
   2046 static int windows_clock_gettime(int clk_id, struct timespec *tp)
   2047 {
   2048 	FILETIME filetime;
   2049 	ULARGE_INTEGER rtime;
   2050 	DWORD r;
   2051 	switch(clk_id) {
   2052 	case USBI_CLOCK_MONOTONIC:
   2053 		if (hires_frequency != 0) {
   2054 			while (1) {
   2055 				InterlockedIncrement((LONG*)&request_count[0]);
   2056 				SetEvent(timer_request[0]);
   2057 				r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
   2058 				switch(r) {
   2059 				case WAIT_OBJECT_0:
   2060 					WaitForSingleObject(timer_mutex, INFINITE);
   2061 					*tp = timer_tp;
   2062 					ReleaseMutex(timer_mutex);
   2063 					return LIBUSB_SUCCESS;
   2064 				case WAIT_TIMEOUT:
   2065 					usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
   2066 					break; // Retry until successful
   2067 				default:
   2068 					usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
   2069 					return LIBUSB_ERROR_OTHER;
   2070 				}
   2071 			}
   2072 		}
   2073 		// Fall through and return real-time if monotonic was not detected @ timer init
   2074 	case USBI_CLOCK_REALTIME:
   2075 		// We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
   2076 		// with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
   2077 		// Note however that our resolution is bounded by the Windows system time
   2078 		// functions and is at best of the order of 1 ms (or, usually, worse)
   2079 		GetSystemTimeAsFileTime(&filetime);
   2080 		rtime.LowPart = filetime.dwLowDateTime;
   2081 		rtime.HighPart = filetime.dwHighDateTime;
   2082 		rtime.QuadPart -= epoch_time;
   2083 		tp->tv_sec = (long)(rtime.QuadPart / 10000000);
   2084 		tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
   2085 		return LIBUSB_SUCCESS;
   2086 	default:
   2087 		return LIBUSB_ERROR_INVALID_PARAM;
   2088 	}
   2089 }
   2090 
   2091 
   2092 // NB: MSVC6 does not support named initializers.
   2093 const struct usbi_os_backend windows_backend = {
   2094 	"Windows",
   2095 	windows_init,
   2096 	windows_exit,
   2097 
   2098 	windows_get_device_list,
   2099 	windows_open,
   2100 	windows_close,
   2101 
   2102 	windows_get_device_descriptor,
   2103 	windows_get_active_config_descriptor,
   2104 	windows_get_config_descriptor,
   2105 
   2106 	windows_get_configuration,
   2107 	windows_set_configuration,
   2108 	windows_claim_interface,
   2109 	windows_release_interface,
   2110 
   2111 	windows_set_interface_altsetting,
   2112 	windows_clear_halt,
   2113 	windows_reset_device,
   2114 
   2115 	windows_kernel_driver_active,
   2116 	windows_detach_kernel_driver,
   2117 	windows_attach_kernel_driver,
   2118 
   2119 	windows_destroy_device,
   2120 
   2121 	windows_submit_transfer,
   2122 	windows_cancel_transfer,
   2123 	windows_clear_transfer_priv,
   2124 
   2125 	windows_handle_events,
   2126 
   2127 	windows_clock_gettime,
   2128 #if defined(USBI_TIMERFD_AVAILABLE)
   2129 	NULL,
   2130 #endif
   2131 	sizeof(struct windows_device_priv),
   2132 	sizeof(struct windows_device_handle_priv),
   2133 	sizeof(struct windows_transfer_priv),
   2134 	0,
   2135 };
   2136 
   2137 
   2138 /*
   2139  * USB API backends
   2140  */
   2141 static int unsupported_init(struct libusb_context *ctx) {
   2142 	return LIBUSB_SUCCESS;
   2143 }
   2144 static int unsupported_exit(void) {
   2145 	return LIBUSB_SUCCESS;
   2146 }
   2147 static int unsupported_open(struct libusb_device_handle *dev_handle) {
   2148 	PRINT_UNSUPPORTED_API(open);
   2149 }
   2150 static void unsupported_close(struct libusb_device_handle *dev_handle) {
   2151 	usbi_dbg("unsupported API call for 'close'");
   2152 }
   2153 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
   2154 	PRINT_UNSUPPORTED_API(claim_interface);
   2155 }
   2156 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
   2157 	PRINT_UNSUPPORTED_API(set_interface_altsetting);
   2158 }
   2159 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
   2160 	PRINT_UNSUPPORTED_API(release_interface);
   2161 }
   2162 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
   2163 	PRINT_UNSUPPORTED_API(clear_halt);
   2164 }
   2165 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
   2166 	PRINT_UNSUPPORTED_API(reset_device);
   2167 }
   2168 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
   2169 	PRINT_UNSUPPORTED_API(submit_bulk_transfer);
   2170 }
   2171 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
   2172 	PRINT_UNSUPPORTED_API(submit_iso_transfer);
   2173 }
   2174 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
   2175 	PRINT_UNSUPPORTED_API(submit_control_transfer);
   2176 }
   2177 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
   2178 	PRINT_UNSUPPORTED_API(abort_control);
   2179 }
   2180 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
   2181 	PRINT_UNSUPPORTED_API(abort_transfers);
   2182 }
   2183 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
   2184 	PRINT_UNSUPPORTED_API(copy_transfer_data);
   2185 }
   2186 
   2187 // These names must be uppercase
   2188 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
   2189 const char* composite_driver_names[] = {"USBCCGP"};
   2190 const char* winusb_driver_names[] = {"WINUSB"};
   2191 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
   2192 	{
   2193 		USB_API_UNSUPPORTED,
   2194 		"Unsupported API",
   2195 		&CLASS_GUID_UNSUPPORTED,
   2196 		NULL,
   2197 		0,
   2198 		unsupported_init,
   2199 		unsupported_exit,
   2200 		unsupported_open,
   2201 		unsupported_close,
   2202 		unsupported_claim_interface,
   2203 		unsupported_set_interface_altsetting,
   2204 		unsupported_release_interface,
   2205 		unsupported_clear_halt,
   2206 		unsupported_reset_device,
   2207 		unsupported_submit_bulk_transfer,
   2208 		unsupported_submit_iso_transfer,
   2209 		unsupported_submit_control_transfer,
   2210 		unsupported_abort_control,
   2211 		unsupported_abort_transfers,
   2212 		unsupported_copy_transfer_data,
   2213 	}, {
   2214 		USB_API_HUB,
   2215 		"HUB API",
   2216 		&CLASS_GUID_UNSUPPORTED,
   2217 		hub_driver_names,
   2218 		sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
   2219 		unsupported_init,
   2220 		unsupported_exit,
   2221 		unsupported_open,
   2222 		unsupported_close,
   2223 		unsupported_claim_interface,
   2224 		unsupported_set_interface_altsetting,
   2225 		unsupported_release_interface,
   2226 		unsupported_clear_halt,
   2227 		unsupported_reset_device,
   2228 		unsupported_submit_bulk_transfer,
   2229 		unsupported_submit_iso_transfer,
   2230 		unsupported_submit_control_transfer,
   2231 		unsupported_abort_control,
   2232 		unsupported_abort_transfers,
   2233 		unsupported_copy_transfer_data,
   2234 	}, {
   2235 		USB_API_COMPOSITE,
   2236 		"Composite API",
   2237 		&CLASS_GUID_COMPOSITE,
   2238 		composite_driver_names,
   2239 		sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
   2240 		composite_init,
   2241 		composite_exit,
   2242 		composite_open,
   2243 		composite_close,
   2244 		composite_claim_interface,
   2245 		composite_set_interface_altsetting,
   2246 		composite_release_interface,
   2247 		composite_clear_halt,
   2248 		composite_reset_device,
   2249 		composite_submit_bulk_transfer,
   2250 		composite_submit_iso_transfer,
   2251 		composite_submit_control_transfer,
   2252 		composite_abort_control,
   2253 		composite_abort_transfers,
   2254 		composite_copy_transfer_data,
   2255 	}, {
   2256 		USB_API_WINUSB,
   2257 		"WinUSB API",
   2258 		&CLASS_GUID_LIBUSB_WINUSB,
   2259 		winusb_driver_names,
   2260 		sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
   2261 		winusb_init,
   2262 		winusb_exit,
   2263 		winusb_open,
   2264 		winusb_close,
   2265 		winusb_claim_interface,
   2266 		winusb_set_interface_altsetting,
   2267 		winusb_release_interface,
   2268 		winusb_clear_halt,
   2269 		winusb_reset_device,
   2270 		winusb_submit_bulk_transfer,
   2271 		unsupported_submit_iso_transfer,
   2272 		winusb_submit_control_transfer,
   2273 		winusb_abort_control,
   2274 		winusb_abort_transfers,
   2275 		winusb_copy_transfer_data,
   2276 	},
   2277 };
   2278 
   2279 
   2280 /*
   2281  * WinUSB API functions
   2282  */
   2283 static int winusb_init(struct libusb_context *ctx)
   2284 {
   2285 	DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
   2286 	DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
   2287 	DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
   2288 	DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
   2289 	DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
   2290 	DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
   2291 	DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
   2292 	DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
   2293 	DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
   2294 	DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
   2295 	DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
   2296 	DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
   2297 	DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
   2298 	DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
   2299 	DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
   2300 	DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
   2301 	DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
   2302 
   2303 	api_winusb_available = true;
   2304 	return LIBUSB_SUCCESS;
   2305 }
   2306 
   2307 static int winusb_exit(void)
   2308 {
   2309 	return LIBUSB_SUCCESS;
   2310 }
   2311 
   2312 // NB: open and close must ensure that they only handle interface of
   2313 // the right API type, as these functions can be called wholesale from
   2314 // composite_open(), with interfaces belonging to different APIs
   2315 static int winusb_open(struct libusb_device_handle *dev_handle)
   2316 {
   2317 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2318 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2319 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2320 
   2321 	HANDLE file_handle;
   2322 	int i;
   2323 
   2324 	CHECK_WINUSB_AVAILABLE;
   2325 
   2326 	// WinUSB requires a seperate handle for each interface
   2327 	for (i = 0; i < USB_MAXINTERFACES; i++) {
   2328 		if ( (priv->usb_interface[i].path != NULL)
   2329 		  && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
   2330 			file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
   2331 				NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
   2332 			if (file_handle == INVALID_HANDLE_VALUE) {
   2333 				usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
   2334 				switch(GetLastError()) {
   2335 				case ERROR_FILE_NOT_FOUND:	// The device was disconnected
   2336 					return LIBUSB_ERROR_NO_DEVICE;
   2337 				case ERROR_ACCESS_DENIED:
   2338 					return LIBUSB_ERROR_ACCESS;
   2339 				default:
   2340 					return LIBUSB_ERROR_IO;
   2341 				}
   2342 			}
   2343 			handle_priv->interface_handle[i].dev_handle = file_handle;
   2344 		}
   2345 	}
   2346 
   2347 	return LIBUSB_SUCCESS;
   2348 }
   2349 
   2350 static void winusb_close(struct libusb_device_handle *dev_handle)
   2351 {
   2352 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2353 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2354 	HANDLE file_handle;
   2355 	int i;
   2356 
   2357 	if (!api_winusb_available)
   2358 		return;
   2359 
   2360 	for (i = 0; i < USB_MAXINTERFACES; i++) {
   2361 		if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
   2362 			file_handle = handle_priv->interface_handle[i].dev_handle;
   2363 			if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
   2364 				CloseHandle(file_handle);
   2365 			}
   2366 		}
   2367 	}
   2368 }
   2369 
   2370 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
   2371 {
   2372 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2373 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2374 	HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
   2375 	UCHAR policy;
   2376 	ULONG timeout = 0;
   2377 	uint8_t endpoint_address;
   2378 	int i;
   2379 
   2380 	CHECK_WINUSB_AVAILABLE;
   2381 
   2382 	// With handle and enpoints set (in parent), we can setup the default pipe properties
   2383 	// see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
   2384 	for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
   2385 		endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
   2386 		if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
   2387 			PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
   2388 			usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
   2389 		}
   2390 		if (i == -1) continue;	// Other policies don't apply to control endpoint
   2391 		policy = false;
   2392 		if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
   2393 			SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
   2394 			usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
   2395 		}
   2396 		if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
   2397 			IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
   2398 			usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
   2399 		}
   2400 		if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
   2401 			ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
   2402 			usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
   2403 		}
   2404 		policy = true;
   2405 		if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
   2406 			AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
   2407 			usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
   2408 		}
   2409 	}
   2410 
   2411 	return LIBUSB_SUCCESS;
   2412 }
   2413 
   2414 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
   2415 {
   2416 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2417 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2418 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2419 	bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
   2420 	HANDLE file_handle, winusb_handle;
   2421 
   2422 	CHECK_WINUSB_AVAILABLE;
   2423 
   2424 	// If the device is composite, but using the default Windows composite parent driver (usbccgp)
   2425 	// or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
   2426 	if ((is_using_usbccgp) || (iface == 0)) {
   2427 		// composite device (independent interfaces) or interface 0
   2428 		file_handle = handle_priv->interface_handle[iface].dev_handle;
   2429 		if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
   2430 			return LIBUSB_ERROR_NOT_FOUND;
   2431 		}
   2432 
   2433 		if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
   2434 			usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
   2435 			handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
   2436 
   2437 			switch(GetLastError()) {
   2438 			case ERROR_BAD_COMMAND:	// The device was disconnected
   2439 				return LIBUSB_ERROR_NO_DEVICE;
   2440 			default:
   2441 				usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
   2442 				return LIBUSB_ERROR_ACCESS;
   2443 			}
   2444 		}
   2445 		handle_priv->interface_handle[iface].api_handle = winusb_handle;
   2446 	} else {
   2447 		// For all other interfaces, use WinUsb_GetAssociatedInterface()
   2448 		winusb_handle = handle_priv->interface_handle[0].api_handle;
   2449 		// It is a requirement for multiple interface devices using WinUSB that you
   2450 		// must first claim the first interface before you claim any other
   2451 		if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
   2452 			file_handle = handle_priv->interface_handle[0].dev_handle;
   2453 			if (WinUsb_Initialize(file_handle, &winusb_handle)) {
   2454 				handle_priv->interface_handle[0].api_handle = winusb_handle;
   2455 				usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
   2456 			} else {
   2457 				usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
   2458 				return LIBUSB_ERROR_ACCESS;
   2459 			}
   2460 		}
   2461 		if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
   2462 			&handle_priv->interface_handle[iface].api_handle)) {
   2463 			handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
   2464 			switch(GetLastError()) {
   2465 			case ERROR_NO_MORE_ITEMS:   // invalid iface
   2466 				return LIBUSB_ERROR_NOT_FOUND;
   2467 			case ERROR_BAD_COMMAND:     // The device was disconnected
   2468 				return LIBUSB_ERROR_NO_DEVICE;
   2469 			case ERROR_ALREADY_EXISTS:  // already claimed
   2470 				return LIBUSB_ERROR_BUSY;
   2471 			default:
   2472 				usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
   2473 				return LIBUSB_ERROR_ACCESS;
   2474 			}
   2475 		}
   2476 	}
   2477 	usbi_dbg("claimed interface %d", iface);
   2478 	handle_priv->active_interface = iface;
   2479 
   2480 	return LIBUSB_SUCCESS;
   2481 }
   2482 
   2483 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
   2484 {
   2485 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2486 	HANDLE winusb_handle;
   2487 
   2488 	CHECK_WINUSB_AVAILABLE;
   2489 
   2490 	winusb_handle = handle_priv->interface_handle[iface].api_handle;
   2491 	if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
   2492 		return LIBUSB_ERROR_NOT_FOUND;
   2493 	}
   2494 
   2495 	WinUsb_Free(winusb_handle);
   2496 	handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
   2497 
   2498 	return LIBUSB_SUCCESS;
   2499 }
   2500 
   2501 /*
   2502  * Return the first valid interface (of the same API type), for control transfers
   2503  */
   2504 static int winusb_get_valid_interface(struct libusb_device_handle *dev_handle)
   2505 {
   2506 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2507 	int i;
   2508 
   2509 	for (i=0; i<USB_MAXINTERFACES; i++) {
   2510 		if ( (handle_priv->interface_handle[i].dev_handle != 0)
   2511 		  && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
   2512 		  && (handle_priv->interface_handle[i].api_handle != 0)
   2513 		  && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE) ) {
   2514 			return i;
   2515 		}
   2516 	}
   2517 	return -1;
   2518 }
   2519 
   2520 /*
   2521  * Lookup interface by endpoint address. -1 if not found
   2522  */
   2523 static int interface_by_endpoint(struct windows_device_priv *priv,
   2524 	struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
   2525 {
   2526 	int i, j;
   2527 	for (i=0; i<USB_MAXINTERFACES; i++) {
   2528 		if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
   2529 			continue;
   2530 		if (handle_priv->interface_handle[i].api_handle == 0)
   2531 			continue;
   2532 		if (priv->usb_interface[i].endpoint == NULL)
   2533 			continue;
   2534 		for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
   2535 			if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
   2536 				return i;
   2537 			}
   2538 		}
   2539 	}
   2540 	return -1;
   2541 }
   2542 
   2543 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
   2544 {
   2545 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2546 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2547 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2548 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   2549 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(
   2550 		transfer->dev_handle);
   2551 	WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
   2552 	ULONG size;
   2553 	HANDLE winusb_handle;
   2554 	int current_interface;
   2555 	struct winfd wfd;
   2556 
   2557 	CHECK_WINUSB_AVAILABLE;
   2558 
   2559 	transfer_priv->pollable_fd = INVALID_WINFD;
   2560 	size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
   2561 
   2562 	if (size > MAX_CTRL_BUFFER_LENGTH)
   2563 		return LIBUSB_ERROR_INVALID_PARAM;
   2564 
   2565 	current_interface = winusb_get_valid_interface(transfer->dev_handle);
   2566 	if (current_interface < 0) {
   2567 		if (auto_claim(transfer, &current_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
   2568 			return LIBUSB_ERROR_NOT_FOUND;
   2569 		}
   2570 	}
   2571 
   2572 	usbi_dbg("will use interface %d", current_interface);
   2573 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   2574 
   2575 	wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
   2576 	// Always use the handle returned from usbi_create_fd (wfd.handle)
   2577 	if (wfd.fd < 0) {
   2578 		return LIBUSB_ERROR_NO_MEM;
   2579 	}
   2580 
   2581 	// Sending of set configuration control requests from WinUSB creates issues
   2582 	if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
   2583 	  && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
   2584 		if (setup->value != priv->active_config) {
   2585 			usbi_warn(ctx, "cannot set configuration other than the default one");
   2586 			usbi_free_fd(wfd.fd);
   2587 			return LIBUSB_ERROR_INVALID_PARAM;
   2588 		}
   2589 		wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   2590 		wfd.overlapped->InternalHigh = 0;
   2591 	} else {
   2592 		if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
   2593 			if(GetLastError() != ERROR_IO_PENDING) {
   2594 				usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
   2595 				usbi_free_fd(wfd.fd);
   2596 				return LIBUSB_ERROR_IO;
   2597 			}
   2598 		} else {
   2599 			wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   2600 			wfd.overlapped->InternalHigh = (DWORD)size;
   2601 		}
   2602 	}
   2603 
   2604 	// Use priv_transfer to store data needed for async polling
   2605 	transfer_priv->pollable_fd = wfd;
   2606 	transfer_priv->interface_number = (uint8_t)current_interface;
   2607 
   2608 	return LIBUSB_SUCCESS;
   2609 }
   2610 
   2611 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
   2612 {
   2613 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2614 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2615 	HANDLE winusb_handle;
   2616 
   2617 	CHECK_WINUSB_AVAILABLE;
   2618 
   2619 	if (altsetting > 255) {
   2620 		return LIBUSB_ERROR_INVALID_PARAM;
   2621 	}
   2622 
   2623 	winusb_handle = handle_priv->interface_handle[iface].api_handle;
   2624 	if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
   2625 		usbi_err(ctx, "interface must be claimed first");
   2626 		return LIBUSB_ERROR_NOT_FOUND;
   2627 	}
   2628 
   2629 	if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
   2630 		usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
   2631 		return LIBUSB_ERROR_IO;
   2632 	}
   2633 
   2634 	return LIBUSB_SUCCESS;
   2635 }
   2636 
   2637 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
   2638 {
   2639 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2640 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2641 	struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
   2642 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   2643 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2644 	HANDLE winusb_handle;
   2645 	bool ret;
   2646 	int current_interface;
   2647 	struct winfd wfd;
   2648 
   2649 	CHECK_WINUSB_AVAILABLE;
   2650 
   2651 	transfer_priv->pollable_fd = INVALID_WINFD;
   2652 
   2653 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   2654 	if (current_interface < 0) {
   2655 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   2656 		return LIBUSB_ERROR_NOT_FOUND;
   2657 	}
   2658 
   2659 	usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
   2660 
   2661 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   2662 
   2663 	wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? _O_RDONLY : _O_WRONLY);
   2664 	// Always use the handle returned from usbi_create_fd (wfd.handle)
   2665 	if (wfd.fd < 0) {
   2666 		return LIBUSB_ERROR_NO_MEM;
   2667 	}
   2668 
   2669 	if (IS_XFERIN(transfer)) {
   2670 		usbi_dbg("reading %d bytes", transfer->length);
   2671 		ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
   2672 	} else {
   2673 		usbi_dbg("writing %d bytes", transfer->length);
   2674 		ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
   2675 	}
   2676 	if (!ret) {
   2677 		if(GetLastError() != ERROR_IO_PENDING) {
   2678 			usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
   2679 			usbi_free_fd(wfd.fd);
   2680 			return LIBUSB_ERROR_IO;
   2681 		}
   2682 	} else {
   2683 		wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
   2684 		wfd.overlapped->InternalHigh = (DWORD)transfer->length;
   2685 	}
   2686 
   2687 	transfer_priv->pollable_fd = wfd;
   2688 	transfer_priv->interface_number = (uint8_t)current_interface;
   2689 
   2690 	return LIBUSB_SUCCESS;
   2691 }
   2692 
   2693 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
   2694 {
   2695 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2696 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2697 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2698 	HANDLE winusb_handle;
   2699 	int current_interface;
   2700 
   2701 	CHECK_WINUSB_AVAILABLE;
   2702 
   2703 	current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
   2704 	if (current_interface < 0) {
   2705 		usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
   2706 		return LIBUSB_ERROR_NOT_FOUND;
   2707 	}
   2708 
   2709 	usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
   2710 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   2711 
   2712 	if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
   2713 		usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
   2714 		return LIBUSB_ERROR_NO_DEVICE;
   2715 	}
   2716 
   2717 	return LIBUSB_SUCCESS;
   2718 }
   2719 
   2720 /*
   2721  * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
   2722  * through testing as well):
   2723  * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
   2724  * the control transfer using CancelIo"
   2725  */
   2726 static int winusb_abort_control(struct usbi_transfer *itransfer)
   2727 {
   2728 	// Cancelling of the I/O is done in the parent
   2729 	return LIBUSB_SUCCESS;
   2730 }
   2731 
   2732 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
   2733 {
   2734 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2735 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2736 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   2737 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   2738 	HANDLE winusb_handle;
   2739 	int current_interface;
   2740 
   2741 	CHECK_WINUSB_AVAILABLE;
   2742 
   2743 	current_interface = transfer_priv->interface_number;
   2744 	if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
   2745 		usbi_err(ctx, "program assertion failed: invalid interface_number");
   2746 		return LIBUSB_ERROR_NOT_FOUND;
   2747 	}
   2748 	usbi_dbg("will use interface %d", current_interface);
   2749 
   2750 	winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
   2751 
   2752 	if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
   2753 		usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
   2754 		return LIBUSB_ERROR_NO_DEVICE;
   2755 	}
   2756 
   2757 	return LIBUSB_SUCCESS;
   2758 }
   2759 
   2760 /*
   2761  * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
   2762  * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
   2763  * "WinUSB does not support host-initiated reset port and cycle port operations" and
   2764  * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
   2765  * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
   2766  * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
   2767  */
   2768 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
   2769 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
   2770 {
   2771 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2772 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2773 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2774 	struct winfd wfd;
   2775 	HANDLE winusb_handle;
   2776 	int i, j;
   2777 
   2778 	CHECK_WINUSB_AVAILABLE;
   2779 
   2780 	// Reset any available pipe (except control)
   2781 	for (i=0; i<USB_MAXINTERFACES; i++) {
   2782 		winusb_handle = handle_priv->interface_handle[i].api_handle;
   2783 		for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
   2784 		{
   2785 			// Cancel any pollable I/O
   2786 			usbi_remove_pollfd(ctx, wfd.fd);
   2787 			usbi_free_fd(wfd.fd);
   2788 			wfd = handle_to_winfd(winusb_handle);
   2789 		}
   2790 
   2791 		if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
   2792 			for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
   2793 				usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
   2794 				if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
   2795 					usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
   2796 						priv->usb_interface[i].endpoint[j], windows_error_str(0));
   2797 				}
   2798 				// FlushPipe seems to fail on OUT pipes
   2799 				if (IS_EPIN(priv->usb_interface[i].endpoint[j])
   2800 				  && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
   2801 					usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
   2802 						priv->usb_interface[i].endpoint[j], windows_error_str(0));
   2803 				}
   2804 				if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
   2805 					usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
   2806 						priv->usb_interface[i].endpoint[j], windows_error_str(0));
   2807 				}
   2808 			}
   2809 		}
   2810 	}
   2811 
   2812 	return LIBUSB_SUCCESS;
   2813 }
   2814 
   2815 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
   2816 {
   2817 	itransfer->transferred += io_size;
   2818 	return LIBUSB_TRANSFER_COMPLETED;
   2819 }
   2820 
   2821 
   2822 /*
   2823  * Composite API functions
   2824  */
   2825 static int composite_init(struct libusb_context *ctx)
   2826 {
   2827 	return LIBUSB_SUCCESS;
   2828 }
   2829 
   2830 static int composite_exit(void)
   2831 {
   2832 	return LIBUSB_SUCCESS;
   2833 }
   2834 
   2835 static int composite_open(struct libusb_device_handle *dev_handle)
   2836 {
   2837 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2838 	unsigned api;
   2839 	int r;
   2840 	uint8_t flag = 1<<USB_API_WINUSB;
   2841 
   2842 	for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
   2843 		if (priv->composite_api_flags & flag) {
   2844 			r = usb_api_backend[api].open(dev_handle);
   2845 			if (r != LIBUSB_SUCCESS) {
   2846 				return r;
   2847 			}
   2848 		}
   2849 		flag <<= 1;
   2850 	}
   2851 	return LIBUSB_SUCCESS;
   2852 }
   2853 
   2854 static void composite_close(struct libusb_device_handle *dev_handle)
   2855 {
   2856 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2857 	unsigned api;
   2858 	uint8_t flag = 1<<USB_API_WINUSB;
   2859 
   2860 	for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
   2861 		if (priv->composite_api_flags & flag) {
   2862 			usb_api_backend[api].close(dev_handle);
   2863 		}
   2864 		flag <<= 1;
   2865 	}
   2866 }
   2867 
   2868 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
   2869 {
   2870 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2871 	return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
   2872 }
   2873 
   2874 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
   2875 {
   2876 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2877 	return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
   2878 }
   2879 
   2880 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
   2881 {
   2882 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2883 	return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
   2884 }
   2885 
   2886 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
   2887 {
   2888 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2889 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2890 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2891 	int i;
   2892 
   2893 	for (i=0; i<USB_MAXINTERFACES; i++) {
   2894 		if (priv->usb_interface[i].path != NULL) {
   2895 			usbi_dbg("using interface %d", i);
   2896 			return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
   2897 		}
   2898 	}
   2899 
   2900 	usbi_err(ctx, "no libusb supported interfaces to complete request");
   2901 	return LIBUSB_ERROR_NOT_FOUND;
   2902 }
   2903 
   2904 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
   2905 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2906 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2907 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   2908 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2909 	int current_interface;
   2910 
   2911 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   2912 	if (current_interface < 0) {
   2913 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   2914 		return LIBUSB_ERROR_NOT_FOUND;
   2915 	}
   2916 
   2917 	return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
   2918 }
   2919 
   2920 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
   2921 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2922 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
   2923 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
   2924 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2925 	int current_interface;
   2926 
   2927 	current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
   2928 	if (current_interface < 0) {
   2929 		usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
   2930 		return LIBUSB_ERROR_NOT_FOUND;
   2931 	}
   2932 
   2933 	return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
   2934 }
   2935 
   2936 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
   2937 {
   2938 	struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
   2939 	struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
   2940 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2941 	int current_interface;
   2942 
   2943 	current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
   2944 	if (current_interface < 0) {
   2945 		usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
   2946 		return LIBUSB_ERROR_NOT_FOUND;
   2947 	}
   2948 
   2949 	return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
   2950 }
   2951 
   2952 static int composite_abort_control(struct usbi_transfer *itransfer)
   2953 {
   2954 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2955 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   2956 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2957 
   2958 	return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
   2959 }
   2960 
   2961 static int composite_abort_transfers(struct usbi_transfer *itransfer)
   2962 {
   2963 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2964 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   2965 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2966 
   2967 	return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
   2968 }
   2969 
   2970 static int composite_reset_device(struct libusb_device_handle *dev_handle)
   2971 {
   2972 	struct windows_device_priv *priv = _device_priv(dev_handle->dev);
   2973 	unsigned api;
   2974 	int r;
   2975 	uint8_t flag = 1<<USB_API_WINUSB;
   2976 
   2977 	for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
   2978 		if (priv->composite_api_flags & flag) {
   2979 			r = usb_api_backend[api].reset_device(dev_handle);
   2980 			if (r != LIBUSB_SUCCESS) {
   2981 				return r;
   2982 			}
   2983 		}
   2984 		flag <<= 1;
   2985 	}
   2986 	return LIBUSB_SUCCESS;
   2987 }
   2988 
   2989 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
   2990 {
   2991 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
   2992 	struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
   2993 	struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
   2994 
   2995 	return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);
   2996 }
   2997