Windows: do not set altsetting 0 as part of libusb_release_interface()
[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)
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                 default:
1069                         usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1070                         break;
1071                 }
1072         } else {
1073                 dev->device_address = UINT8_MAX;        // Hubs from HCD have a devaddr of 255
1074                 force_hcd_device_descriptor(dev);
1075         }
1076
1077         usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1078                 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1079
1080         return LIBUSB_SUCCESS;
1081 }
1082
1083 // Returns the api type, or 0 if not found/unsupported
1084 static uint8_t get_api_type(struct libusb_context *ctx,
1085                                                 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
1086 {
1087         // Precedence for filter drivers vs driver is in the order of this array
1088         struct driver_lookup lookup[3] = {
1089                 {"\0\0", SPDRP_SERVICE, "driver"},
1090                 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1091                 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1092         };
1093         DWORD size, reg_type;
1094         unsigned k, l;
1095         uint8_t api;
1096
1097         // Check the service & filter names to know the API we should use
1098         for (k=0; k<3; k++) {
1099                 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1100                         &reg_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1101                         // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1102                         if (lookup[k].reg_prop == SPDRP_SERVICE) {
1103                                 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1104                                 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1105                         }
1106                         // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1107                         // NB: none of the driver names we check against contain LIST_SEPARATOR,
1108                         // (currently ';'), so even if an unsuported one does, it's not an issue
1109                         for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1110                                 if (lookup[k].list[l] == 0) {
1111                                         lookup[k].list[l] = LIST_SEPARATOR;
1112                                 }
1113                         }
1114                         upperize(lookup[k].list);
1115                         usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1116                 } else {
1117                         if (GetLastError() != ERROR_INVALID_DATA) {
1118                                 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1119                         }
1120                         lookup[k].list[0] = 0;
1121                 }
1122         }
1123
1124         for (api=1; api<USB_API_MAX; api++) {
1125                 for (k=0; k<3; k++) {
1126                         if (is_api_driver(lookup[k].list, api)) {
1127                                 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1128                                 break;
1129                         }
1130                 }
1131                 if (k >= 3) continue;
1132                 return api;
1133         }
1134         return 0;
1135 }
1136
1137 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1138                                                         char* dev_interface_path, char* device_id, uint8_t api)
1139 {
1140         unsigned i;
1141         struct windows_device_priv *priv = _device_priv(dev);
1142         int interface_number;
1143
1144         if (priv->apib->id != USB_API_COMPOSITE) {
1145                 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1146                 return LIBUSB_ERROR_NO_DEVICE;
1147         }
1148
1149         // Because MI_## are not necessarily in sequential order (some composite
1150         // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1151         // interface number from the path's MI value
1152         interface_number = 0;
1153         for (i=0; device_id[i] != 0; ) {
1154                 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1155                   && (device_id[i++] == '_') ) {
1156                         interface_number = (device_id[i++] - '0')*10;
1157                         interface_number += device_id[i] - '0';
1158                         break;
1159                 }
1160         }
1161
1162         if (device_id[i] == 0) {
1163                 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1164                         device_id, interface_number);
1165         }
1166
1167         if (priv->usb_interface[interface_number].path != NULL) {
1168                 usbi_warn(ctx, "interface[%d] already set - ignoring: %s", interface_number, device_id);
1169                 return LIBUSB_ERROR_ACCESS;
1170         }
1171
1172         usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1173         priv->usb_interface[interface_number].path = dev_interface_path;
1174         priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1175         priv->composite_api_flags |= 1<<api;
1176
1177         return LIBUSB_SUCCESS;
1178 }
1179
1180 /*
1181  * get_device_list: libusb backend device enumeration function
1182  */
1183 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1184 {
1185         struct discovered_devs *discdevs = *_discdevs;
1186         HDEVINFO dev_info = { 0 };
1187         char* usb_class[2] = {"USB", "NUSB3"};
1188         SP_DEVINFO_DATA dev_info_data;
1189         SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1190 #define MAX_ENUM_GUIDS 64
1191         const GUID* guid[MAX_ENUM_GUIDS];
1192 #define HCD_PASS 0
1193 #define HUB_PASS 1
1194 #define GEN_PASS 2
1195 #define DEV_PASS 3
1196         int r = LIBUSB_SUCCESS;
1197         int class_index = 0;
1198         unsigned int nb_guids, pass, i, j, ancestor;
1199         char path[MAX_PATH_LENGTH];
1200         char strbuf[MAX_PATH_LENGTH];
1201         struct libusb_device *dev, *parent_dev;
1202         struct windows_device_priv *priv, *parent_priv;
1203         char* dev_interface_path = NULL;
1204         char* dev_id_path = NULL;
1205         unsigned long session_id;
1206         DWORD size, reg_type, port_nr, install_state;
1207         BOOL b = FALSE;
1208         HKEY key;
1209         WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1210         GUID* if_guid;
1211         LONG s;
1212         uint8_t api;
1213         // Keep a list of newly allocated devs to unref
1214         libusb_device** unref_list;
1215         unsigned int unref_size = 64;
1216         unsigned int unref_cur = 0;
1217
1218         // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1219         // PASS 2 : (re)enumerate HUBS
1220         // PASS 3 : (re)enumerate generic USB devices (including driverless)
1221         //           and list additional USB device interface GUIDs to explore
1222         // PASS 4 : (re)enumerate master USB devices that have a device interface
1223         // PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.
1224
1225         // Init the GUID table
1226         guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1227         guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1228         guid[GEN_PASS] = NULL;
1229         guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1230         nb_guids = DEV_PASS+1;
1231
1232         unref_list = malloc(unref_size*sizeof(libusb_device*));
1233         if (unref_list == NULL) {
1234                 return LIBUSB_ERROR_NO_MEM;
1235         }
1236
1237         for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1238 //#define ENUM_DEBUG
1239 #ifdef ENUM_DEBUG
1240                 switch(pass) {
1241                 case HCD_PASS:
1242                         usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
1243                         break;
1244                 case HUB_PASS:
1245                         usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
1246                         break;
1247                 case DEV_PASS:
1248                         usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
1249                         break;
1250                 case GEN_PASS:
1251                         usbi_dbg("PROCESSING GENs");
1252                         break;
1253                 default:
1254                         usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
1255                         break;
1256                 }
1257 #endif
1258                 for (i = 0; ; i++) {
1259                         // safe loop: free up any (unprotected) dynamic resource
1260                         // NB: this is always executed before breaking the loop
1261                         safe_free(dev_interface_details);
1262                         safe_free(dev_interface_path);
1263                         safe_free(dev_id_path);
1264                         session_id = 0;
1265                         priv = parent_priv = NULL;
1266                         dev = parent_dev = NULL;
1267
1268                         // Safe loop: end of loop conditions
1269                         if (r != LIBUSB_SUCCESS) {
1270                                 break;
1271                         }
1272                         if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1273                                 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1274                                 break;
1275                         }
1276                         if (pass != GEN_PASS) {
1277                                 // Except for GEN, all passes deal with device interfaces
1278                                 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1279                                 if (dev_interface_details == NULL) {
1280                                         break;
1281                                 } else {
1282                                         dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1283                                         if (dev_interface_path == NULL) {
1284                                                 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1285                                                 continue;
1286                                         }
1287                                 }
1288                         } else {
1289                                 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1290                                 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
1291                                 while ( (class_index < 2) &&
1292                                             (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
1293                                                 class_index++;
1294                                                 i = 0;
1295                                 }
1296                                 if (!b) break;
1297                         }
1298
1299                         // Read the Device ID path. This is what we'll use as UID
1300                         // Note that if the device is plugged in a different port or hub, the Device ID changes
1301                         if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1302                                 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1303                                         dev_info_data.DevInst);
1304                                 continue;
1305                         }
1306                         dev_id_path = sanitize_path(path);
1307                         if (dev_id_path == NULL) {
1308                                 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1309                                         dev_info_data.DevInst);
1310                                 continue;
1311                         }
1312 #ifdef ENUM_DEBUG
1313                         usbi_dbg("PRO: %s", dev_id_path);
1314 #endif
1315
1316                         // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1317                         port_nr = 0;
1318                         if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1319                                 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1320                                         &reg_type, (BYTE*)&port_nr, 4, &size))
1321                                   || (size != 4) ) {
1322                                         usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1323                                                 dev_id_path, windows_error_str(0));
1324                                         continue;
1325                                 }
1326                         }
1327
1328                         // Set API to use or get additional data from generic pass
1329                         api = USB_API_UNSUPPORTED;
1330                         switch (pass) {
1331                         case HCD_PASS:
1332                                 break;
1333                         case GEN_PASS:
1334                                 // We use the GEN pass to detect driverless devices...
1335                                 size = sizeof(strbuf);
1336                                 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1337                                         &reg_type, (BYTE*)strbuf, size, &size)) {
1338                                                 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1339                                                 usbi_info(ctx, "libusb will not be able to access it.");
1340                                 }
1341                                 // ...and to add the additional device interface GUIDs
1342                                 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1343                                 if (key != INVALID_HANDLE_VALUE) {
1344                                         size = sizeof(guid_string_w);
1345                                         s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &reg_type,
1346                                                 (BYTE*)guid_string_w, &size);
1347                                         pRegCloseKey(key);
1348                                         if (s == ERROR_SUCCESS) {
1349                                                 if (nb_guids >= MAX_ENUM_GUIDS) {
1350                                                         // If this assert is ever reported, grow a GUID table dynamically
1351                                                         usbi_err(ctx, "program assertion failed: too many GUIDs");
1352                                                         LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1353                                                 }
1354                                                 if_guid = calloc(1, sizeof(GUID));
1355                                                 pCLSIDFromString(guid_string_w, if_guid);
1356                                                 guid[nb_guids++] = if_guid;
1357                                                 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1358                                         }
1359                                 }
1360                                 break;
1361                         default:
1362                                 // Get the API type (after checking that the driver installation is OK)
1363                                 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1364                                         &reg_type, (BYTE*)&install_state, 4, &size))
1365                                   || (size != 4) ){
1366                                         usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1367                                                 dev_id_path, windows_error_str(0));
1368                                 } else if (install_state != 0) {
1369                                         usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1370                                                 dev_id_path, install_state);
1371                                         continue;
1372                                 }
1373                                 api = get_api_type(ctx, &dev_info, &dev_info_data);
1374                                 break;
1375                         }
1376
1377                         // Find parent device (for the passes that need it)
1378                         switch (pass) {
1379                         case HCD_PASS:
1380                         case DEV_PASS:
1381                         case HUB_PASS:
1382                                 break;
1383                         default:
1384                                 // Go through the ancestors until we see a face we recognize
1385                                 parent_dev = NULL;
1386                                 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1387                                         session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1388                                         if (session_id == 0) {
1389                                                 break;
1390                                         }
1391                                         parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1392                                 }
1393                                 if (parent_dev == NULL) {
1394                                         usbi_dbg("unlisted ancestor for '%s' (newly connected, etc.) - ignoring", dev_id_path);
1395                                         continue;
1396                                 }
1397                                 parent_priv = _device_priv(parent_dev);
1398                                 // virtual USB devices are also listed during GEN - don't process these yet
1399                                 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1400                                         continue;
1401                                 }
1402                                 break;
1403                         }
1404
1405                         // Create new or match existing device, using the (hashed) device_id as session id
1406                         if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1407                                 // These are the passes that create "new" devices
1408                                 session_id = htab_hash(dev_id_path);
1409                                 dev = usbi_get_device_by_session_id(ctx, session_id);
1410                                 if (dev == NULL) {
1411                                         if (pass == DEV_PASS) {
1412                                                 // This can occur if the OS only reports a newly plugged device after we started enum
1413                                                 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1414                                                         " - ignoring", dev_id_path);
1415                                                 continue;
1416                                         }
1417                                         usbi_dbg("allocating new device for session [%X]", session_id);
1418                                         if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1419                                                 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1420                                         }
1421                                         windows_device_priv_init(dev);
1422                                         // Keep track of devices that need unref
1423                                         unref_list[unref_cur++] = dev;
1424                                         if (unref_cur > unref_size) {
1425                                                 unref_size += 64;
1426                                                 unref_list = realloc(unref_list, unref_size*sizeof(libusb_device*));
1427                                                 if (unref_list == NULL) {
1428                                                         usbi_err(ctx, "could not realloc list for unref - aborting.");
1429                                                         LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1430                                                 }
1431                                         }
1432                                 } else {
1433                                         usbi_dbg("found existing device for session [%X] (%d.%d)",
1434                                                 session_id, dev->bus_number, dev->device_address);
1435                                 }
1436                                 priv = _device_priv(dev);
1437                         }
1438
1439                         // Setup device
1440                         switch (pass) {
1441                         case HCD_PASS:
1442                                 dev->bus_number = (uint8_t)(i + 1);     // bus 0 is reserved for disconnected
1443                                 dev->device_address = 0;
1444                                 dev->num_configurations = 0;
1445                                 priv->apib = &usb_api_backend[USB_API_HUB];
1446                                 priv->depth = UINT8_MAX;        // Overflow to 0 for HCD Hubs
1447                                 priv->path = dev_interface_path; dev_interface_path = NULL;
1448                                 break;
1449                         case HUB_PASS:
1450                         case DEV_PASS:
1451                                 // If the device has already been setup, don't do it again
1452                                 if (priv->path != NULL)
1453                                         break;
1454                                 // Take care of API initialization
1455                                 priv->path = dev_interface_path; dev_interface_path = NULL;
1456                                 priv->apib = &usb_api_backend[api];
1457                                 switch(api) {
1458                                 case USB_API_COMPOSITE:
1459                                 case USB_API_HUB:
1460                                         break;
1461                                 default:
1462                                         // For other devices, the first interface is the same as the device
1463                                         priv->usb_interface[0].path = malloc(safe_strlen(priv->path)+1);
1464                                         if (priv->usb_interface[0].path != NULL) {
1465                                                 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1466                                         }
1467                                         // The following is needed if we want API calls to work for both simple
1468                                         // and composite devices.
1469                                         for(j=0; j<USB_MAXINTERFACES; j++) {
1470                                                 priv->usb_interface[j].apib = &usb_api_backend[api];
1471                                         }
1472                                         break;
1473                                 }
1474                                 break;
1475                         case GEN_PASS:
1476                                 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1477                                 if (r == LIBUSB_SUCCESS) {
1478                                         // Append device to the list of discovered devices
1479                                         discdevs = discovered_devs_append(*_discdevs, dev);
1480                                         if (!discdevs) {
1481                                                 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1482                                         }
1483                                         *_discdevs = discdevs;
1484                                 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1485                                         // This can occur if the device was disconnected but Windows hasn't
1486                                         // refreshed its enumeration yet - in that case, we ignore the device
1487                                         r = LIBUSB_SUCCESS;
1488                                 }
1489                                 break;
1490                         default:        // later passes
1491                                 if (parent_priv->apib->id == USB_API_COMPOSITE) {
1492                                         usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1493                                         switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
1494                                         case LIBUSB_SUCCESS:
1495                                                 dev_interface_path = NULL;
1496                                                 break;
1497                                         case LIBUSB_ERROR_ACCESS:
1498                                                 // interface has already been set => make sure dev_interface_path is freed then
1499                                                 break;
1500                                         default:
1501                                                 LOOP_BREAK(r);
1502                                                 break;
1503                                         }
1504                                 }
1505                                 break;
1506                         }
1507                 }
1508         }
1509
1510         // Free any additional GUIDs
1511         for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
1512                 safe_free(guid[pass]);
1513         }
1514
1515         // Unref newly allocated devs
1516         for (i=0; i<unref_cur; i++) {
1517                 safe_unref_device(unref_list[i]);
1518         }
1519         safe_free(unref_list);
1520
1521         return r;
1522 }
1523
1524 /*
1525  * exit: libusb backend deinitialization function
1526  */
1527 static void windows_exit(void)
1528 {
1529         int i;
1530         HANDLE semaphore;
1531         char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1532
1533         sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1534         semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1535         if (semaphore == NULL) {
1536                 return;
1537         }
1538
1539         // A successful wait brings our semaphore count to 0 (unsignaled)
1540         // => any concurent wait stalls until the semaphore release
1541         if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1542                 CloseHandle(semaphore);
1543                 return;
1544         }
1545
1546         // Only works if exits and inits are balanced exactly
1547         if (--concurrent_usage < 0) {   // Last exit
1548                 for (i=0; i<USB_API_MAX; i++) {
1549                         usb_api_backend[i].exit();
1550                 }
1551                 exit_polling();
1552
1553                 if (timer_thread) {
1554                         SetEvent(timer_request[1]); // actually the signal to quit the thread.
1555                         if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1556                                 usbi_dbg("could not wait for timer thread to quit");
1557                                 TerminateThread(timer_thread, 1);
1558                         }
1559                         CloseHandle(timer_thread);
1560                         timer_thread = NULL;
1561                 }
1562                 for (i = 0; i < 2; i++) {
1563                         if (timer_request[i]) {
1564                                 CloseHandle(timer_request[i]);
1565                                 timer_request[i] = NULL;
1566                         }
1567                 }
1568                 if (timer_response) {
1569                         CloseHandle(timer_response);
1570                         timer_response = NULL;
1571                 }
1572                 if (timer_mutex) {
1573                         CloseHandle(timer_mutex);
1574                         timer_mutex = NULL;
1575                 }
1576                 htab_destroy();
1577         }
1578
1579         ReleaseSemaphore(semaphore, 1, NULL);   // increase count back to 1
1580         CloseHandle(semaphore);
1581 }
1582
1583 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1584 {
1585         struct windows_device_priv *priv = _device_priv(dev);
1586
1587         memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1588         *host_endian = 0;
1589
1590         return LIBUSB_SUCCESS;
1591 }
1592
1593 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1594 {
1595         struct windows_device_priv *priv = _device_priv(dev);
1596         PUSB_CONFIGURATION_DESCRIPTOR config_header;
1597         size_t size;
1598
1599         // config index is zero based
1600         if (config_index >= dev->num_configurations)
1601                 return LIBUSB_ERROR_INVALID_PARAM;
1602
1603         if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1604                 return LIBUSB_ERROR_NOT_FOUND;
1605
1606         config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1607
1608         size = min(config_header->wTotalLength, len);
1609         memcpy(buffer, priv->config_descriptor[config_index], size);
1610
1611         return LIBUSB_SUCCESS;
1612 }
1613
1614 /*
1615  * return the cached copy of the active config descriptor
1616  */
1617 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1618 {
1619         struct windows_device_priv *priv = _device_priv(dev);
1620
1621         if (priv->active_config == 0)
1622                 return LIBUSB_ERROR_NOT_FOUND;
1623
1624         // config index is zero based
1625         return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1626 }
1627
1628 static int windows_open(struct libusb_device_handle *dev_handle)
1629 {
1630         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1631         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1632
1633         if (priv->apib == NULL) {
1634                 usbi_err(ctx, "program assertion failed - device is not initialized");
1635                 return LIBUSB_ERROR_NO_DEVICE;
1636         }
1637
1638         return priv->apib->open(dev_handle);
1639 }
1640
1641 static void windows_close(struct libusb_device_handle *dev_handle)
1642 {
1643         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1644
1645         priv->apib->close(dev_handle);
1646 }
1647
1648 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1649 {
1650         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1651
1652         if (priv->active_config == 0) {
1653                 *config = 0;
1654                 return LIBUSB_ERROR_NOT_FOUND;
1655         }
1656
1657         *config = priv->active_config;
1658         return LIBUSB_SUCCESS;
1659 }
1660
1661 /*
1662  * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1663  * does not currently expose a service that allows higher-level drivers to set
1664  * the configuration."
1665  */
1666 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1667 {
1668         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1669         int r = LIBUSB_SUCCESS;
1670
1671         if (config >= USB_MAXCONFIG)
1672                 return LIBUSB_ERROR_INVALID_PARAM;
1673
1674         r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1675                 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1676                 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1677                 0, NULL, 0, 1000);
1678
1679         if (r == LIBUSB_SUCCESS) {
1680                 priv->active_config = (uint8_t)config;
1681         }
1682         return r;
1683 }
1684
1685 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1686 {
1687         int r = LIBUSB_SUCCESS;
1688         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1689
1690         if (iface >= USB_MAXINTERFACES)
1691                 return LIBUSB_ERROR_INVALID_PARAM;
1692
1693         safe_free(priv->usb_interface[iface].endpoint);
1694         priv->usb_interface[iface].nb_endpoints= 0;
1695
1696         r = priv->apib->claim_interface(dev_handle, iface);
1697
1698         if (r == LIBUSB_SUCCESS) {
1699                 r = windows_assign_endpoints(dev_handle, iface, 0);
1700         }
1701
1702         return r;
1703 }
1704
1705 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1706 {
1707         int r = LIBUSB_SUCCESS;
1708         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1709
1710         safe_free(priv->usb_interface[iface].endpoint);
1711         priv->usb_interface[iface].nb_endpoints= 0;
1712
1713         r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1714
1715         if (r == LIBUSB_SUCCESS) {
1716                 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1717         }
1718
1719         return r;
1720 }
1721
1722 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1723 {
1724         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1725
1726         return priv->apib->release_interface(dev_handle, iface);
1727 }
1728
1729 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1730 {
1731         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1732         return priv->apib->clear_halt(dev_handle, endpoint);
1733 }
1734
1735 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1736 {
1737         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1738         return priv->apib->reset_device(dev_handle);
1739 }
1740
1741 // The 3 functions below are unlikely to ever get supported on Windows
1742 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1743 {
1744         return LIBUSB_ERROR_NOT_SUPPORTED;
1745 }
1746
1747 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1748 {
1749         return LIBUSB_ERROR_NOT_SUPPORTED;
1750 }
1751
1752 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1753 {
1754         return LIBUSB_ERROR_NOT_SUPPORTED;
1755 }
1756
1757 static void windows_destroy_device(struct libusb_device *dev)
1758 {
1759         windows_device_priv_release(dev);
1760 }
1761
1762 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1763 {
1764         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1765
1766         usbi_free_fd(transfer_priv->pollable_fd.fd);
1767 #if defined(AUTO_CLAIM)
1768         // When auto claim is in use, attempt to release the auto-claimed interface
1769         auto_release(itransfer);
1770 #endif
1771 }
1772
1773 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1774 {
1775         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1776         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1777         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1778         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1779         int r;
1780
1781         r = priv->apib->submit_bulk_transfer(itransfer);
1782         if (r != LIBUSB_SUCCESS) {
1783                 return r;
1784         }
1785
1786         usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1787                 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1788 #if !defined(DYNAMIC_FDS)
1789         usbi_fd_notification(ctx);
1790 #endif
1791
1792         return LIBUSB_SUCCESS;
1793 }
1794
1795 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1796 {
1797         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1798         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1799         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1800         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1801         int r;
1802
1803         r = priv->apib->submit_iso_transfer(itransfer);
1804         if (r != LIBUSB_SUCCESS) {
1805                 return r;
1806         }
1807
1808         usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1809                 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1810 #if !defined(DYNAMIC_FDS)
1811         usbi_fd_notification(ctx);
1812 #endif
1813
1814         return LIBUSB_SUCCESS;
1815 }
1816
1817 static int submit_control_transfer(struct usbi_transfer *itransfer)
1818 {
1819         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1820         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1821         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1822         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1823         int r;
1824
1825         r = priv->apib->submit_control_transfer(itransfer);
1826         if (r != LIBUSB_SUCCESS) {
1827                 return r;
1828         }
1829
1830         usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1831 #if !defined(DYNAMIC_FDS)
1832         usbi_fd_notification(ctx);
1833 #endif
1834
1835         return LIBUSB_SUCCESS;
1836
1837 }
1838
1839 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1840 {
1841         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1842
1843         switch (transfer->type) {
1844         case LIBUSB_TRANSFER_TYPE_CONTROL:
1845                 return submit_control_transfer(itransfer);
1846         case LIBUSB_TRANSFER_TYPE_BULK:
1847         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1848                 return submit_bulk_transfer(itransfer);
1849         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1850                 return submit_iso_transfer(itransfer);
1851         default:
1852                 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1853                 return LIBUSB_ERROR_INVALID_PARAM;
1854         }
1855 }
1856
1857 static int windows_abort_control(struct usbi_transfer *itransfer)
1858 {
1859         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1860         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1861
1862         return priv->apib->abort_control(itransfer);
1863 }
1864
1865 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1866 {
1867         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1868         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1869
1870         return priv->apib->abort_transfers(itransfer);
1871 }
1872
1873 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1874 {
1875         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1876 #if defined(FORCE_INSTANT_TIMEOUTS)
1877         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1878
1879         // Forces instant overlapped completion on timeouts - use at your own risks
1880         if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1881                 transfer_priv->pollable_fd.overlapped->Internal &= ~STATUS_PENDING;
1882         }
1883 #endif
1884         switch (transfer->type) {
1885         case LIBUSB_TRANSFER_TYPE_CONTROL:
1886                 return windows_abort_control(itransfer);
1887         case LIBUSB_TRANSFER_TYPE_BULK:
1888         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1889         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1890                 return windows_abort_transfers(itransfer);
1891         default:
1892                 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1893                 return LIBUSB_ERROR_INVALID_PARAM;
1894         }
1895 }
1896
1897 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1898 {
1899         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1900         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1901         int status;
1902
1903         usbi_dbg("handling I/O completion with errcode %d", io_result);
1904
1905         switch(io_result) {
1906         case NO_ERROR:
1907                 status = priv->apib->copy_transfer_data(itransfer, io_size);
1908                 break;
1909         case ERROR_GEN_FAILURE:
1910                 usbi_dbg("detected endpoint stall");
1911                 status = LIBUSB_TRANSFER_STALL;
1912                 break;
1913         case ERROR_SEM_TIMEOUT:
1914                 usbi_dbg("detected semaphore timeout");
1915                 status = LIBUSB_TRANSFER_TIMED_OUT;
1916                 break;
1917         case ERROR_OPERATION_ABORTED:
1918                 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1919                         usbi_dbg("detected timeout");
1920                         status = LIBUSB_TRANSFER_TIMED_OUT;
1921                 } else {
1922                         usbi_dbg("detected operation aborted");
1923                         status = LIBUSB_TRANSFER_CANCELLED;
1924                 }
1925                 break;
1926         default:
1927                 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
1928                 status = LIBUSB_TRANSFER_ERROR;
1929                 break;
1930         }
1931         windows_clear_transfer_priv(itransfer); // Cancel polling
1932         usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
1933 }
1934
1935 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1936 {
1937         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1938
1939         switch (transfer->type) {
1940         case LIBUSB_TRANSFER_TYPE_CONTROL:
1941         case LIBUSB_TRANSFER_TYPE_BULK:
1942         case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1943         case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1944                 windows_transfer_callback (itransfer, io_result, io_size);
1945                 break;
1946         default:
1947                 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1948         }
1949 }
1950
1951 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
1952 {
1953         struct windows_transfer_priv* transfer_priv = NULL;
1954         POLL_NFDS_TYPE i = 0;
1955         bool found = false;
1956         struct usbi_transfer *transfer;
1957         DWORD io_size, io_result;
1958
1959         usbi_mutex_lock(&ctx->open_devs_lock);
1960         for (i = 0; i < nfds && num_ready > 0; i++) {
1961
1962                 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
1963
1964                 if (!fds[i].revents) {
1965                         continue;
1966                 }
1967
1968                 num_ready--;
1969
1970                 // Because a Windows OVERLAPPED is used for poll emulation,
1971                 // a pollable fd is created and stored with each transfer
1972                 usbi_mutex_lock(&ctx->flying_transfers_lock);
1973                 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
1974                         transfer_priv = usbi_transfer_get_os_priv(transfer);
1975                         if (transfer_priv->pollable_fd.fd == fds[i].fd) {
1976                                 found = true;
1977                                 break;
1978                         }
1979                 }
1980                 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1981
1982                 if (found) {
1983                         // Handle async requests that completed synchronously first
1984                         if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
1985                                 io_result = NO_ERROR;
1986                                 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
1987                         // Regular async overlapped
1988                         } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
1989                                 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
1990                                 io_result = NO_ERROR;
1991                         } else {
1992                                 io_result = GetLastError();
1993                         }
1994                         usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
1995                         // let handle_callback free the event using the transfer wfd
1996                         // If you don't use the transfer wfd, you run a risk of trying to free a
1997                         // newly allocated wfd that took the place of the one from the transfer.
1998                         windows_handle_callback(transfer, io_result, io_size);
1999                 } else {
2000                         usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2001                         return LIBUSB_ERROR_NOT_FOUND;
2002                 }
2003         }
2004
2005         usbi_mutex_unlock(&ctx->open_devs_lock);
2006         return LIBUSB_SUCCESS;
2007 }
2008
2009 /*
2010  * Monotonic and real time functions
2011  */
2012 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2013 {
2014         LARGE_INTEGER hires_counter, li_frequency;
2015         LONG nb_responses;
2016         int timer_index;
2017
2018         // Init - find out if we have access to a monotonic (hires) timer
2019         if (!QueryPerformanceFrequency(&li_frequency)) {
2020                 usbi_dbg("no hires timer available on this platform");
2021                 hires_frequency = 0;
2022                 hires_ticks_to_ps = UINT64_C(0);
2023         } else {
2024                 hires_frequency = li_frequency.QuadPart;
2025                 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2026                 // to picoseconds to compute the tv_nsecs part in clock_gettime
2027                 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2028                 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2029         }
2030
2031         // Main loop - wait for requests
2032         while (1) {
2033                 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2034                 if ( (timer_index != 0) && (timer_index != 1) ) {
2035                         usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2036                         continue;
2037                 }
2038                 if (request_count[timer_index] == 0) {
2039                         // Request already handled
2040                         ResetEvent(timer_request[timer_index]);
2041                         // There's still a possiblity that a thread sends a request between the
2042                         // time we test request_count[] == 0 and we reset the event, in which case
2043                         // the request would be ignored. The simple solution to that is to test
2044                         // request_count again and process requests if non zero.
2045                         if (request_count[timer_index] == 0)
2046                                 continue;
2047                 }
2048                 switch (timer_index) {
2049                 case 0:
2050                         WaitForSingleObject(timer_mutex, INFINITE);
2051                         // Requests to this thread are for hires always
2052                         if (QueryPerformanceCounter(&hires_counter) != 0) {
2053                                 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2054                                 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2055                         } else {
2056                                 // Fallback to real-time if we can't get monotonic value
2057                                 // Note that real-time clock does not wait on the mutex or this thread.
2058                                 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2059                         }
2060                         ReleaseMutex(timer_mutex);
2061
2062                         nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2063                         if ( (nb_responses)
2064                           && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2065                                 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2066                         }
2067                         continue;
2068                 case 1: // time to quit
2069                         usbi_dbg("timer thread quitting");
2070                         return 0;
2071                 }
2072         }
2073         usbi_dbg("ERROR: broken timer thread");
2074         return 1;
2075 }
2076
2077 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2078 {
2079         FILETIME filetime;
2080         ULARGE_INTEGER rtime;
2081         DWORD r;
2082         switch(clk_id) {
2083         case USBI_CLOCK_MONOTONIC:
2084                 if (hires_frequency != 0) {
2085                         while (1) {
2086                                 InterlockedIncrement((LONG*)&request_count[0]);
2087                                 SetEvent(timer_request[0]);
2088                                 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2089                                 switch(r) {
2090                                 case WAIT_OBJECT_0:
2091                                         WaitForSingleObject(timer_mutex, INFINITE);
2092                                         *tp = timer_tp;
2093                                         ReleaseMutex(timer_mutex);
2094                                         return LIBUSB_SUCCESS;
2095                                 case WAIT_TIMEOUT:
2096                                         usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2097                                         break; // Retry until successful
2098                                 default:
2099                                         usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2100                                         return LIBUSB_ERROR_OTHER;
2101                                 }
2102                         }
2103                 }
2104                 // Fall through and return real-time if monotonic was not detected @ timer init
2105         case USBI_CLOCK_REALTIME:
2106                 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2107                 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2108                 // Note however that our resolution is bounded by the Windows system time
2109                 // functions and is at best of the order of 1 ms (or, usually, worse)
2110                 GetSystemTimeAsFileTime(&filetime);
2111                 rtime.LowPart = filetime.dwLowDateTime;
2112                 rtime.HighPart = filetime.dwHighDateTime;
2113                 rtime.QuadPart -= epoch_time;
2114                 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2115                 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2116                 return LIBUSB_SUCCESS;
2117         default:
2118                 return LIBUSB_ERROR_INVALID_PARAM;
2119         }
2120 }
2121
2122
2123 // NB: MSVC6 does not support named initializers.
2124 const struct usbi_os_backend windows_backend = {
2125         "Windows",
2126         windows_init,
2127         windows_exit,
2128
2129         windows_get_device_list,
2130         windows_open,
2131         windows_close,
2132
2133         windows_get_device_descriptor,
2134         windows_get_active_config_descriptor,
2135         windows_get_config_descriptor,
2136
2137         windows_get_configuration,
2138         windows_set_configuration,
2139         windows_claim_interface,
2140         windows_release_interface,
2141
2142         windows_set_interface_altsetting,
2143         windows_clear_halt,
2144         windows_reset_device,
2145
2146         windows_kernel_driver_active,
2147         windows_detach_kernel_driver,
2148         windows_attach_kernel_driver,
2149
2150         windows_destroy_device,
2151
2152         windows_submit_transfer,
2153         windows_cancel_transfer,
2154         windows_clear_transfer_priv,
2155
2156         windows_handle_events,
2157
2158         windows_clock_gettime,
2159 #if defined(USBI_TIMERFD_AVAILABLE)
2160         NULL,
2161 #endif
2162         sizeof(struct windows_device_priv),
2163         sizeof(struct windows_device_handle_priv),
2164         sizeof(struct windows_transfer_priv),
2165         0,
2166 };
2167
2168
2169 /*
2170  * USB API backends
2171  */
2172 static int unsupported_init(struct libusb_context *ctx) {
2173         return LIBUSB_SUCCESS;
2174 }
2175 static int unsupported_exit(void) {
2176         return LIBUSB_SUCCESS;
2177 }
2178 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2179         PRINT_UNSUPPORTED_API(open);
2180 }
2181 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2182         usbi_dbg("unsupported API call for 'close'");
2183 }
2184 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2185         PRINT_UNSUPPORTED_API(claim_interface);
2186 }
2187 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2188         PRINT_UNSUPPORTED_API(set_interface_altsetting);
2189 }
2190 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2191         PRINT_UNSUPPORTED_API(release_interface);
2192 }
2193 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2194         PRINT_UNSUPPORTED_API(clear_halt);
2195 }
2196 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2197         PRINT_UNSUPPORTED_API(reset_device);
2198 }
2199 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2200         PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2201 }
2202 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2203         PRINT_UNSUPPORTED_API(submit_iso_transfer);
2204 }
2205 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2206         PRINT_UNSUPPORTED_API(submit_control_transfer);
2207 }
2208 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2209         PRINT_UNSUPPORTED_API(abort_control);
2210 }
2211 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2212         PRINT_UNSUPPORTED_API(abort_transfers);
2213 }
2214 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2215         PRINT_UNSUPPORTED_API(copy_transfer_data);
2216 }
2217
2218 // These names must be uppercase
2219 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
2220 const char* composite_driver_names[] = {"USBCCGP"};
2221 const char* winusb_driver_names[] = {"WINUSB"};
2222 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2223         {
2224                 USB_API_UNSUPPORTED,
2225                 "Unsupported API",
2226                 &CLASS_GUID_UNSUPPORTED,
2227                 NULL,
2228                 0,
2229                 unsupported_init,
2230                 unsupported_exit,
2231                 unsupported_open,
2232                 unsupported_close,
2233                 unsupported_claim_interface,
2234                 unsupported_set_interface_altsetting,
2235                 unsupported_release_interface,
2236                 unsupported_clear_halt,
2237                 unsupported_reset_device,
2238                 unsupported_submit_bulk_transfer,
2239                 unsupported_submit_iso_transfer,
2240                 unsupported_submit_control_transfer,
2241                 unsupported_abort_control,
2242                 unsupported_abort_transfers,
2243                 unsupported_copy_transfer_data,
2244         }, {
2245                 USB_API_HUB,
2246                 "HUB API",
2247                 &CLASS_GUID_UNSUPPORTED,
2248                 hub_driver_names,
2249                 sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
2250                 unsupported_init,
2251                 unsupported_exit,
2252                 unsupported_open,
2253                 unsupported_close,
2254                 unsupported_claim_interface,
2255                 unsupported_set_interface_altsetting,
2256                 unsupported_release_interface,
2257                 unsupported_clear_halt,
2258                 unsupported_reset_device,
2259                 unsupported_submit_bulk_transfer,
2260                 unsupported_submit_iso_transfer,
2261                 unsupported_submit_control_transfer,
2262                 unsupported_abort_control,
2263                 unsupported_abort_transfers,
2264                 unsupported_copy_transfer_data,
2265         }, {
2266                 USB_API_COMPOSITE,
2267                 "Composite API",
2268                 &CLASS_GUID_COMPOSITE,
2269                 composite_driver_names,
2270                 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2271                 composite_init,
2272                 composite_exit,
2273                 composite_open,
2274                 composite_close,
2275                 composite_claim_interface,
2276                 composite_set_interface_altsetting,
2277                 composite_release_interface,
2278                 composite_clear_halt,
2279                 composite_reset_device,
2280                 composite_submit_bulk_transfer,
2281                 composite_submit_iso_transfer,
2282                 composite_submit_control_transfer,
2283                 composite_abort_control,
2284                 composite_abort_transfers,
2285                 composite_copy_transfer_data,
2286         }, {
2287                 USB_API_WINUSB,
2288                 "WinUSB API",
2289                 &CLASS_GUID_LIBUSB_WINUSB,
2290                 winusb_driver_names,
2291                 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2292                 winusb_init,
2293                 winusb_exit,
2294                 winusb_open,
2295                 winusb_close,
2296                 winusb_claim_interface,
2297                 winusb_set_interface_altsetting,
2298                 winusb_release_interface,
2299                 winusb_clear_halt,
2300                 winusb_reset_device,
2301                 winusb_submit_bulk_transfer,
2302                 unsupported_submit_iso_transfer,
2303                 winusb_submit_control_transfer,
2304                 winusb_abort_control,
2305                 winusb_abort_transfers,
2306                 winusb_copy_transfer_data,
2307         },
2308 };
2309
2310
2311 /*
2312  * WinUSB API functions
2313  */
2314 static int winusb_init(struct libusb_context *ctx)
2315 {
2316         DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2317         DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2318         DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2319         DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2320         DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2321         DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2322         DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2323         DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2324         DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2325         DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2326         DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2327         DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2328         DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2329         DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2330         DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2331         DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2332         DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2333
2334         api_winusb_available = true;
2335         return LIBUSB_SUCCESS;
2336 }
2337
2338 static int winusb_exit(void)
2339 {
2340         return LIBUSB_SUCCESS;
2341 }
2342
2343 // NB: open and close must ensure that they only handle interface of
2344 // the right API type, as these functions can be called wholesale from
2345 // composite_open(), with interfaces belonging to different APIs
2346 static int winusb_open(struct libusb_device_handle *dev_handle)
2347 {
2348         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2349         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2350         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2351
2352         HANDLE file_handle;
2353         int i;
2354
2355         CHECK_WINUSB_AVAILABLE;
2356
2357         // WinUSB requires a seperate handle for each interface
2358         for (i = 0; i < USB_MAXINTERFACES; i++) {
2359                 if ( (priv->usb_interface[i].path != NULL)
2360                   && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2361                         file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2362                                 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2363                         if (file_handle == INVALID_HANDLE_VALUE) {
2364                                 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2365                                 switch(GetLastError()) {
2366                                 case ERROR_FILE_NOT_FOUND:      // The device was disconnected
2367                                         return LIBUSB_ERROR_NO_DEVICE;
2368                                 case ERROR_ACCESS_DENIED:
2369                                         return LIBUSB_ERROR_ACCESS;
2370                                 default:
2371                                         return LIBUSB_ERROR_IO;
2372                                 }
2373                         }
2374                         handle_priv->interface_handle[i].dev_handle = file_handle;
2375                 }
2376         }
2377
2378         return LIBUSB_SUCCESS;
2379 }
2380
2381 static void winusb_close(struct libusb_device_handle *dev_handle)
2382 {
2383         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2384         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2385         HANDLE file_handle;
2386         int i;
2387
2388         if (!api_winusb_available)
2389                 return;
2390
2391         for (i = 0; i < USB_MAXINTERFACES; i++) {
2392                 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2393                         file_handle = handle_priv->interface_handle[i].dev_handle;
2394                         if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2395                                 CloseHandle(file_handle);
2396                         }
2397                 }
2398         }
2399 }
2400
2401 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
2402 {
2403         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2404         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2405         HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2406         UCHAR policy;
2407         ULONG timeout = 0;
2408         uint8_t endpoint_address;
2409         int i;
2410
2411         CHECK_WINUSB_AVAILABLE;
2412
2413         // With handle and enpoints set (in parent), we can setup the default pipe properties
2414         // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2415         for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2416                 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2417                 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2418                         PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2419                         usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2420                 }
2421                 if (i == -1) continue;  // Other policies don't apply to control endpoint
2422                 policy = false;
2423                 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2424                         SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2425                         usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2426                 }
2427                 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2428                         IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2429                         usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2430                 }
2431                 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2432                         ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2433                         usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2434                 }
2435                 policy = true;
2436                 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2437                         AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2438                         usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2439                 }
2440         }
2441
2442         return LIBUSB_SUCCESS;
2443 }
2444
2445 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2446 {
2447         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2448         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2449         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2450         bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2451         HANDLE file_handle, winusb_handle;
2452
2453         CHECK_WINUSB_AVAILABLE;
2454
2455         // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2456         // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
2457         if ((is_using_usbccgp) || (iface == 0)) {
2458                 // composite device (independent interfaces) or interface 0
2459                 file_handle = handle_priv->interface_handle[iface].dev_handle;
2460                 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2461                         return LIBUSB_ERROR_NOT_FOUND;
2462                 }
2463
2464                 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2465                         usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2466                         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2467
2468                         switch(GetLastError()) {
2469                         case ERROR_BAD_COMMAND: // The device was disconnected
2470                                 return LIBUSB_ERROR_NO_DEVICE;
2471                         default:
2472                                 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2473                                 return LIBUSB_ERROR_ACCESS;
2474                         }
2475                 }
2476                 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2477         } else {
2478                 // For all other interfaces, use WinUsb_GetAssociatedInterface()
2479                 winusb_handle = handle_priv->interface_handle[0].api_handle;
2480                 // It is a requirement for multiple interface devices using WinUSB that you
2481                 // must first claim the first interface before you claim any other
2482                 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2483 #if defined(AUTO_CLAIM)
2484                         file_handle = handle_priv->interface_handle[0].dev_handle;
2485                         if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2486                                 handle_priv->interface_handle[0].api_handle = winusb_handle;
2487                                 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2488                         } else {
2489                                 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2490                                 return LIBUSB_ERROR_ACCESS;
2491                         }
2492 #else
2493                         usbi_warn(ctx, "you must claim interface 0 before you can claim %d with WinUSB", iface);
2494                         return LIBUSB_ERROR_ACCESS;
2495 #endif
2496                 }
2497                 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2498                         &handle_priv->interface_handle[iface].api_handle)) {
2499                         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2500                         switch(GetLastError()) {
2501                         case ERROR_NO_MORE_ITEMS:   // invalid iface
2502                                 return LIBUSB_ERROR_NOT_FOUND;
2503                         case ERROR_BAD_COMMAND:     // The device was disconnected
2504                                 return LIBUSB_ERROR_NO_DEVICE;
2505                         case ERROR_ALREADY_EXISTS:  // already claimed
2506                                 return LIBUSB_ERROR_BUSY;
2507                         default:
2508                                 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2509                                 return LIBUSB_ERROR_ACCESS;
2510                         }
2511                 }
2512         }
2513         usbi_dbg("claimed interface %d", iface);
2514         handle_priv->active_interface = iface;
2515
2516         return LIBUSB_SUCCESS;
2517 }
2518
2519 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2520 {
2521         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2522         HANDLE winusb_handle;
2523
2524         CHECK_WINUSB_AVAILABLE;
2525
2526         winusb_handle = handle_priv->interface_handle[iface].api_handle;
2527         if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2528                 return LIBUSB_ERROR_NOT_FOUND;
2529         }
2530
2531         WinUsb_Free(winusb_handle);
2532         handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2533
2534         return LIBUSB_SUCCESS;
2535 }
2536
2537 /*
2538  * Return the first valid interface (of the same API type), for control transfers
2539  */
2540 static int winusb_get_valid_interface(struct libusb_device_handle *dev_handle)
2541 {
2542         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2543         int i;
2544
2545         for (i=0; i<USB_MAXINTERFACES; i++) {
2546                 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2547                   && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2548                   && (handle_priv->interface_handle[i].api_handle != 0)
2549                   && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE) ) {
2550                         return i;
2551                 }
2552         }
2553         return -1;
2554 }
2555
2556 /*
2557  * Lookup interface by endpoint address. -1 if not found
2558  */
2559 static int interface_by_endpoint(struct windows_device_priv *priv,
2560         struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2561 {
2562         int i, j;
2563         for (i=0; i<USB_MAXINTERFACES; i++) {
2564                 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2565                         continue;
2566                 if (handle_priv->interface_handle[i].api_handle == 0)
2567                         continue;
2568                 if (priv->usb_interface[i].endpoint == NULL)
2569                         continue;
2570                 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2571                         if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2572                                 return i;
2573                         }
2574                 }
2575         }
2576         return -1;
2577 }
2578
2579 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2580 {
2581         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2582         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2583         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2584         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2585         struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2586                 transfer->dev_handle);
2587         WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2588         ULONG size;
2589         HANDLE winusb_handle;
2590         int current_interface;
2591         struct winfd wfd;
2592
2593         CHECK_WINUSB_AVAILABLE;
2594
2595         transfer_priv->pollable_fd = INVALID_WINFD;
2596         size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2597
2598         if (size > MAX_CTRL_BUFFER_LENGTH)
2599                 return LIBUSB_ERROR_INVALID_PARAM;
2600
2601         current_interface = winusb_get_valid_interface(transfer->dev_handle);
2602         if (current_interface < 0) {
2603 #if defined(AUTO_CLAIM)
2604                 if (auto_claim(transfer, &current_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2605                         return LIBUSB_ERROR_NOT_FOUND;
2606                 }
2607 #else
2608                 usbi_warn(ctx, "no interface available for control transfer");
2609                 return LIBUSB_ERROR_NOT_FOUND;
2610 #endif
2611         }
2612
2613         usbi_dbg("will use interface %d", current_interface);
2614         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2615
2616         wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2617         // Always use the handle returned from usbi_create_fd (wfd.handle)
2618         if (wfd.fd < 0) {
2619                 return LIBUSB_ERROR_NO_MEM;
2620         }
2621
2622         // Sending of set configuration control requests from WinUSB creates issues
2623         if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2624           && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2625                 if (setup->value != priv->active_config) {
2626                         usbi_warn(ctx, "cannot set configuration other than the default one");
2627                         usbi_free_fd(wfd.fd);
2628                         return LIBUSB_ERROR_INVALID_PARAM;
2629                 }
2630                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2631                 wfd.overlapped->InternalHigh = 0;
2632         } else {
2633                 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2634                         if(GetLastError() != ERROR_IO_PENDING) {
2635                                 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2636                                 usbi_free_fd(wfd.fd);
2637                                 return LIBUSB_ERROR_IO;
2638                         }
2639                 } else {
2640                         wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2641                         wfd.overlapped->InternalHigh = (DWORD)size;
2642                 }
2643         }
2644
2645         // Use priv_transfer to store data needed for async polling
2646         transfer_priv->pollable_fd = wfd;
2647         transfer_priv->interface_number = (uint8_t)current_interface;
2648
2649         return LIBUSB_SUCCESS;
2650 }
2651
2652 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2653 {
2654         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2655         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2656         HANDLE winusb_handle;
2657
2658         CHECK_WINUSB_AVAILABLE;
2659
2660         if (altsetting > 255) {
2661                 return LIBUSB_ERROR_INVALID_PARAM;
2662         }
2663
2664         winusb_handle = handle_priv->interface_handle[iface].api_handle;
2665         if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2666                 usbi_err(ctx, "interface must be claimed first");
2667                 return LIBUSB_ERROR_NOT_FOUND;
2668         }
2669
2670         if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2671                 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2672                 return LIBUSB_ERROR_IO;
2673         }
2674
2675         return LIBUSB_SUCCESS;
2676 }
2677
2678 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2679 {
2680         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2681         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2682         struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2683         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2684         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2685         HANDLE winusb_handle;
2686         bool direction_in, ret;
2687         int current_interface;
2688         struct winfd wfd;
2689
2690         CHECK_WINUSB_AVAILABLE;
2691
2692         transfer_priv->pollable_fd = INVALID_WINFD;
2693
2694         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2695         if (current_interface < 0) {
2696                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2697                 return LIBUSB_ERROR_NOT_FOUND;
2698         }
2699
2700         usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2701
2702         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2703         direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
2704
2705         wfd = usbi_create_fd(winusb_handle, direction_in?_O_RDONLY:_O_WRONLY);
2706         // Always use the handle returned from usbi_create_fd (wfd.handle)
2707         if (wfd.fd < 0) {
2708                 return LIBUSB_ERROR_NO_MEM;
2709         }
2710
2711         if (direction_in) {
2712                 usbi_dbg("reading %d bytes", transfer->length);
2713                 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2714         } else {
2715                 usbi_dbg("writing %d bytes", transfer->length);
2716                 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2717         }
2718         if (!ret) {
2719                 if(GetLastError() != ERROR_IO_PENDING) {
2720                         usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2721                         usbi_free_fd(wfd.fd);
2722                         return LIBUSB_ERROR_IO;
2723                 }
2724         } else {
2725                 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2726                 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2727         }
2728
2729         transfer_priv->pollable_fd = wfd;
2730         transfer_priv->interface_number = (uint8_t)current_interface;
2731
2732         return LIBUSB_SUCCESS;
2733 }
2734
2735 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2736 {
2737         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2738         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2739         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2740         HANDLE winusb_handle;
2741         int current_interface;
2742
2743         CHECK_WINUSB_AVAILABLE;
2744
2745         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2746         if (current_interface < 0) {
2747                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2748                 return LIBUSB_ERROR_NOT_FOUND;
2749         }
2750
2751         usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2752         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2753
2754         if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2755                 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2756                 return LIBUSB_ERROR_NO_DEVICE;
2757         }
2758
2759         return LIBUSB_SUCCESS;
2760 }
2761
2762 /*
2763  * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2764  * through testing as well):
2765  * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2766  * the control transfer using CancelIo"
2767  */
2768 static int winusb_abort_control(struct usbi_transfer *itransfer)
2769 {
2770         // Cancelling of the I/O is done in the parent
2771         return LIBUSB_SUCCESS;
2772 }
2773
2774 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2775 {
2776         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2777         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2778         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2779         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2780         HANDLE winusb_handle;
2781         int current_interface;
2782
2783         CHECK_WINUSB_AVAILABLE;
2784
2785         current_interface = transfer_priv->interface_number;
2786         if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2787                 usbi_err(ctx, "program assertion failed: invalid interface_number");
2788                 return LIBUSB_ERROR_NOT_FOUND;
2789         }
2790         usbi_dbg("will use interface %d", current_interface);
2791
2792         winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2793
2794         if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2795                 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2796                 return LIBUSB_ERROR_NO_DEVICE;
2797         }
2798
2799         return LIBUSB_SUCCESS;
2800 }
2801
2802 /*
2803  * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2804  * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2805  * "WinUSB does not support host-initiated reset port and cycle port operations" and
2806  * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2807  * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2808  * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2809  */
2810 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2811 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2812 {
2813         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2814         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2815         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2816         struct winfd wfd;
2817         HANDLE winusb_handle;
2818         int i, j;
2819
2820         CHECK_WINUSB_AVAILABLE;
2821
2822         // Reset any available pipe (except control)
2823         for (i=0; i<USB_MAXINTERFACES; i++) {
2824                 winusb_handle = handle_priv->interface_handle[i].api_handle;
2825                 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2826                 {
2827                         // Cancel any pollable I/O
2828                         usbi_remove_pollfd(ctx, wfd.fd);
2829                         usbi_free_fd(wfd.fd);
2830                         wfd = handle_to_winfd(winusb_handle);
2831                 }
2832
2833                 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2834                         for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2835                                 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2836                                 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2837                                         usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2838                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2839                                 }
2840                                 // FlushPipe seems to fail on OUT pipes
2841                                 if ( (priv->usb_interface[i].endpoint[j] & LIBUSB_ENDPOINT_IN)
2842                                   && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2843                                         usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2844                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2845                                 }
2846                                 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2847                                         usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2848                                                 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2849                                 }
2850                         }
2851                 }
2852         }
2853
2854         return LIBUSB_SUCCESS;
2855 }
2856
2857 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2858 {
2859         itransfer->transferred += io_size;
2860         return LIBUSB_TRANSFER_COMPLETED;
2861 }
2862
2863
2864 /*
2865  * Composite API functions
2866  */
2867 static int composite_init(struct libusb_context *ctx)
2868 {
2869         return LIBUSB_SUCCESS;
2870 }
2871
2872 static int composite_exit(void)
2873 {
2874         return LIBUSB_SUCCESS;
2875 }
2876
2877 static int composite_open(struct libusb_device_handle *dev_handle)
2878 {
2879         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2880         unsigned api;
2881         int r;
2882         uint8_t flag = 1<<USB_API_WINUSB;
2883
2884         for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2885                 if (priv->composite_api_flags & flag) {
2886                         r = usb_api_backend[api].open(dev_handle);
2887                         if (r != LIBUSB_SUCCESS) {
2888                                 return r;
2889                         }
2890                 }
2891                 flag <<= 1;
2892         }
2893         return LIBUSB_SUCCESS;
2894 }
2895
2896 static void composite_close(struct libusb_device_handle *dev_handle)
2897 {
2898         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2899         unsigned api;
2900         uint8_t flag = 1<<USB_API_WINUSB;
2901
2902         for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2903                 if (priv->composite_api_flags & flag) {
2904                         usb_api_backend[api].close(dev_handle);
2905                 }
2906                 flag <<= 1;
2907         }
2908 }
2909
2910 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2911 {
2912         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2913         return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
2914 }
2915
2916 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2917 {
2918         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2919         return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
2920 }
2921
2922 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
2923 {
2924         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2925         return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
2926 }
2927
2928 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
2929 {
2930         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2931         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2932         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2933         int i;
2934
2935         for (i=0; i<USB_MAXINTERFACES; i++) {
2936                 if (priv->usb_interface[i].path != NULL) {
2937                         usbi_dbg("using interface %d", i);
2938                         return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
2939                 }
2940         }
2941
2942         usbi_err(ctx, "no libusb supported interfaces to complete request");
2943         return LIBUSB_ERROR_NOT_FOUND;
2944 }
2945
2946 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2947         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2948         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2949         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2950         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2951         int current_interface;
2952
2953         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2954         if (current_interface < 0) {
2955                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2956                 return LIBUSB_ERROR_NOT_FOUND;
2957         }
2958
2959         return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
2960 }
2961
2962 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
2963         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2964         struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2965         struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2966         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2967         int current_interface;
2968
2969         current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2970         if (current_interface < 0) {
2971                 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2972                 return LIBUSB_ERROR_NOT_FOUND;
2973         }
2974
2975         return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
2976 }
2977
2978 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2979 {
2980         struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2981         struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2982         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2983         int current_interface;
2984
2985         current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2986         if (current_interface < 0) {
2987                 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2988                 return LIBUSB_ERROR_NOT_FOUND;
2989         }
2990
2991         return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
2992 }
2993
2994 static int composite_abort_control(struct usbi_transfer *itransfer)
2995 {
2996         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2997         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2998         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2999
3000         return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
3001 }
3002
3003 static int composite_abort_transfers(struct usbi_transfer *itransfer)
3004 {
3005         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3006         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3007         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3008
3009         return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
3010 }
3011
3012 static int composite_reset_device(struct libusb_device_handle *dev_handle)
3013 {
3014         struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3015         unsigned api;
3016         int r;
3017         uint8_t flag = 1<<USB_API_WINUSB;
3018
3019         for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3020                 if (priv->composite_api_flags & flag) {
3021                         r = usb_api_backend[api].reset_device(dev_handle);
3022                         if (r != LIBUSB_SUCCESS) {
3023                                 return r;
3024                         }
3025                 }
3026                 flag <<= 1;
3027         }
3028         return LIBUSB_SUCCESS;
3029 }
3030
3031 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
3032 {
3033         struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3034         struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3035         struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3036
3037         return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);
3038 }