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