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