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