2 * windows backend for libusb 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
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.
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.
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
38 #include "poll_windows.h"
39 #include "windows_usb.h"
41 // The 2 macros below are used in conjunction with safe loops.
42 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
43 #define LOOP_BREAK(err) { r=err; continue; }
46 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
47 static int windows_clock_gettime(int clk_id, struct timespec *tp);
48 unsigned __stdcall windows_clock_gettime_threaded(void* param);
50 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
52 // WinUSB-like API prototypes
53 static int winusbx_init(int sub_api, struct libusb_context *ctx);
54 static int winusbx_exit(int sub_api);
55 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
56 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
57 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
58 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
59 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
60 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
61 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
62 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
63 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
64 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
65 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
66 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
67 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
69 static int hid_init(int sub_api, struct libusb_context *ctx);
70 static int hid_exit(int sub_api);
71 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
72 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
73 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
74 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
75 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
76 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
77 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
78 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
79 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
80 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
81 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
82 // Composite API prototypes
83 static int composite_init(int sub_api, struct libusb_context *ctx);
84 static int composite_exit(int sub_api);
85 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
86 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
87 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
88 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
89 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
90 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
91 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
92 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
93 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
94 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
95 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
96 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
97 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
101 uint64_t hires_frequency, hires_ticks_to_ps;
102 const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
103 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
105 static int concurrent_usage = -1;
106 usbi_mutex_t autoclaim_lock;
108 // NB: index 0 is for monotonic and 1 is for the thread exit event
109 HANDLE timer_thread = NULL;
110 HANDLE timer_mutex = NULL;
111 struct timespec timer_tp;
112 volatile LONG request_count[2] = {0, 1}; // last one must be > 0
113 HANDLE timer_request[2] = { NULL, NULL };
114 HANDLE timer_response = NULL;
116 #define CHECK_WINUSBX_AVAILABLE(sub_api) do { if (sub_api == SUB_API_NOTSET) sub_api = priv->sub_api; \
117 if (!WinUSBX[sub_api].initialized) return LIBUSB_ERROR_ACCESS; } while(0)
118 static struct winusb_interface WinUSBX[SUB_API_MAX];
119 const char* sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
120 bool api_hid_available = false;
121 #define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
123 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
124 if ((guid1 != NULL) && (guid2 != NULL)) {
125 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
130 #if defined(ENABLE_LOGGING)
131 static char* guid_to_string(const GUID* guid)
133 static char guid_string[MAX_GUID_STRING_LENGTH];
135 if (guid == NULL) return NULL;
136 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
137 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
138 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
139 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
145 * Converts a windows error to human readable string
146 * uses retval as errorcode, or, if 0, use GetLastError()
148 #if defined(ENABLE_LOGGING)
149 static char *windows_error_str(uint32_t retval)
151 static char err_string[ERR_BUFFER_SIZE];
155 uint32_t error_code, format_error;
157 error_code = retval?retval:GetLastError();
159 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%u] ", error_code);
161 // Translate codes returned by SetupAPI. The ones we are dealing with are either
162 // in 0x0000xxxx or 0xE000xxxx and can be distinguished from standard error codes.
163 // See http://msdn.microsoft.com/en-us/library/windows/hardware/ff545011.aspx
164 switch (error_code & 0xE0000000) {
166 error_code = HRESULT_FROM_WIN32(error_code); // Still leaves ERROR_SUCCESS unmodified
169 error_code = 0x80000000 | (FACILITY_SETUPAPI << 16) | (error_code & 0x0000FFFF);
175 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
176 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
177 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
179 format_error = GetLastError();
181 safe_sprintf(err_string, ERR_BUFFER_SIZE,
182 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
184 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
186 // Remove CR/LF terminators
187 for (i=safe_strlen(err_string)-1; (i>=0) && ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
196 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
197 * Return an allocated sanitized string or NULL on error.
199 static char* sanitize_path(const char* path)
201 const char root_prefix[] = "\\\\.\\";
202 size_t j, size, root_size;
203 char* ret_path = NULL;
209 size = safe_strlen(path)+1;
210 root_size = sizeof(root_prefix)-1;
212 // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
213 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
214 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
215 add_root = root_size;
219 if ((ret_path = (char*) calloc(size, 1)) == NULL)
222 safe_strcpy(&ret_path[add_root], size-add_root, path);
224 // Ensure consistancy with root prefix
225 for (j=0; j<root_size; j++)
226 ret_path[j] = root_prefix[j];
228 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
229 for(j=root_size; j<size; j++) {
230 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
231 if (ret_path[j] == '\\')
239 * Cfgmgr32, OLE32 and SetupAPI DLL functions
241 static int init_dlls(void)
243 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
244 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
245 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
246 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
247 // Prefixed to avoid conflict with header files
248 DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
249 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
250 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
251 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
252 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
253 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
254 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
255 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
256 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
257 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
258 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
259 return LIBUSB_SUCCESS;
263 * enumerate interfaces for the whole USB class
266 * dev_info: a pointer to a dev_info list
267 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
268 * usb_class: the generic USB class for which to retrieve interface details
269 * index: zero based index of the interface in the device info list
271 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
272 * structure returned and call this function repeatedly using the same guid (with an
273 * incremented index starting at zero) until all interfaces have been returned.
275 static bool get_devinfo_data(struct libusb_context *ctx,
276 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char* usb_class, unsigned _index)
279 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
280 if (*dev_info == INVALID_HANDLE_VALUE) {
285 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
286 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
287 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
288 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
289 _index, windows_error_str(0));
291 pSetupDiDestroyDeviceInfoList(*dev_info);
292 *dev_info = INVALID_HANDLE_VALUE;
299 * enumerate interfaces for a specific GUID
302 * dev_info: a pointer to a dev_info list
303 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
304 * guid: the GUID for which to retrieve interface details
305 * index: zero based index of the interface in the device info list
307 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
308 * structure returned and call this function repeatedly using the same guid (with an
309 * incremented index starting at zero) until all interfaces have been returned.
311 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
312 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
314 SP_DEVICE_INTERFACE_DATA dev_interface_data;
315 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
319 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
322 if (dev_info_data != NULL) {
323 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
324 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
325 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
326 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
327 _index, windows_error_str(0));
329 pSetupDiDestroyDeviceInfoList(*dev_info);
330 *dev_info = INVALID_HANDLE_VALUE;
335 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
336 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
337 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
338 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
339 _index, windows_error_str(0));
341 pSetupDiDestroyDeviceInfoList(*dev_info);
342 *dev_info = INVALID_HANDLE_VALUE;
346 // Read interface data (dummy + actual) to access the device path
347 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
348 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
349 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
350 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
351 _index, windows_error_str(0));
355 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
359 if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
360 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
364 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
365 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
366 dev_interface_details, size, &size, NULL)) {
367 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
368 _index, windows_error_str(0));
371 return dev_interface_details;
374 pSetupDiDestroyDeviceInfoList(*dev_info);
375 *dev_info = INVALID_HANDLE_VALUE;
379 /* For libusb0 filter */
380 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
381 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index, char* filter_path){
382 SP_DEVICE_INTERFACE_DATA dev_interface_data;
383 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
386 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
388 if (dev_info_data != NULL) {
389 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
390 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
391 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
392 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
393 _index, windows_error_str(0));
395 pSetupDiDestroyDeviceInfoList(*dev_info);
396 *dev_info = INVALID_HANDLE_VALUE;
400 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
401 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
402 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
403 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
404 _index, windows_error_str(0));
406 pSetupDiDestroyDeviceInfoList(*dev_info);
407 *dev_info = INVALID_HANDLE_VALUE;
410 // Read interface data (dummy + actual) to access the device path
411 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
412 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
413 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
414 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
415 _index, windows_error_str(0));
419 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
422 if ((dev_interface_details = malloc(size)) == NULL) {
423 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
426 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
427 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
428 dev_interface_details, size, &size, NULL)) {
429 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
430 _index, windows_error_str(0));
432 // [trobinso] lookup the libusb0 symbolic index.
433 if (dev_interface_details) {
434 HKEY hkey_device_interface=pSetupDiOpenDeviceInterfaceRegKey(*dev_info,&dev_interface_data,0,KEY_READ);
435 if (hkey_device_interface != INVALID_HANDLE_VALUE) {
436 DWORD libusb0_symboliclink_index=0;
437 DWORD value_length=sizeof(DWORD);
440 status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
441 (LPBYTE) &libusb0_symboliclink_index, &value_length);
442 if (status == ERROR_SUCCESS) {
443 if (libusb0_symboliclink_index < 256) {
444 // libusb0.sys is connected to this device instance.
445 // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
446 safe_sprintf(filter_path, sizeof("\\\\.\\libusb0-0000"), "\\\\.\\libusb0-%04d", libusb0_symboliclink_index);
447 usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
449 // libusb0.sys was connected to this device instance at one time; but not anymore.
452 pRegCloseKey(hkey_device_interface);
455 return dev_interface_details;
457 pSetupDiDestroyDeviceInfoList(*dev_info);
458 *dev_info = INVALID_HANDLE_VALUE;
461 /* Hash table functions - modified From glibc 2.3.2:
462 [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
463 [Knuth] The Art of Computer Programming, part 3 (6.4) */
464 typedef struct htab_entry {
468 htab_entry* htab_table = NULL;
469 usbi_mutex_t htab_write_mutex = NULL;
470 unsigned long htab_size, htab_filled;
472 /* For the used double hash method the table size has to be a prime. To
473 correct the user given table size we need a prime test. This trivial
474 algorithm is adequate because the code is called only during init and
475 the number is likely to be small */
476 static int isprime(unsigned long number)
478 // no even number will be passed
479 unsigned int divider = 3;
481 while((divider * divider < number) && (number % divider != 0))
484 return (number % divider != 0);
487 /* Before using the hash table we must allocate memory for it.
488 We allocate one element more as the found prime number says.
489 This is done for more effective indexing as explained in the
490 comment for the hash function. */
491 static int htab_create(struct libusb_context *ctx, unsigned long nel)
493 if (htab_table != NULL) {
494 usbi_err(ctx, "hash table already allocated");
498 usbi_mutex_init(&htab_write_mutex, NULL);
500 // Change nel to the first prime number not smaller as nel.
506 usbi_dbg("using %d entries hash table", nel);
509 // allocate memory and zero out.
510 htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
511 if (htab_table == NULL) {
512 usbi_err(ctx, "could not allocate space for hash table");
519 /* After using the hash table it has to be destroyed. */
520 static void htab_destroy(void)
523 if (htab_table == NULL) {
527 for (i=0; i<htab_size; i++) {
528 if (htab_table[i].used) {
529 safe_free(htab_table[i].str);
532 usbi_mutex_destroy(&htab_write_mutex);
533 safe_free(htab_table);
536 /* This is the search function. It uses double hashing with open addressing.
537 We use an trick to speed up the lookup. The table is created with one
538 more element available. This enables us to use the index zero special.
539 This index will never be used because we store the first hash index in
540 the field used where zero means not used. Every other value means used.
541 The used field can be used as a first fast comparison for equality of
542 the stored and the parameter value. This helps to prevent unnecessary
543 expensive calls of strcmp. */
544 static unsigned long htab_hash(char* str)
546 unsigned long hval, hval2;
548 unsigned long r = 5381;
555 // Compute main hash value (algorithm suggested by Nokia)
556 while ((c = *sz++) != 0)
557 r = ((r << 5) + r) + c;
561 // compute table hash: simply take the modulus
562 hval = r % htab_size;
566 // Try the first index
569 if (htab_table[idx].used) {
570 if ( (htab_table[idx].used == hval)
571 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
575 usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
577 // Second hash function, as suggested in [Knuth]
578 hval2 = 1 + hval % (htab_size - 2);
581 // Because size is prime this guarantees to step through all available indexes
583 idx = htab_size + idx - hval2;
588 // If we visited all entries leave the loop unsuccessfully
593 // If entry is found use it.
594 if ( (htab_table[idx].used == hval)
595 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
599 while (htab_table[idx].used);
602 // Not found => New entry
604 // If the table is full return an error
605 if (htab_filled >= htab_size) {
606 usbi_err(NULL, "hash table is full (%d entries)", htab_size);
610 // Concurrent threads might be storing the same entry at the same time
611 // (eg. "simultaneous" enums from different threads) => use a mutex
612 usbi_mutex_lock(&htab_write_mutex);
613 // Just free any previously allocated string (which should be the same as
614 // new one). The possibility of concurrent threads storing a collision
615 // string (same hash, different string) at the same time is extremely low
616 safe_free(htab_table[idx].str);
617 htab_table[idx].used = hval;
618 htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
619 if (htab_table[idx].str == NULL) {
620 usbi_err(NULL, "could not duplicate string for hash table");
621 usbi_mutex_unlock(&htab_write_mutex);
624 memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
626 usbi_mutex_unlock(&htab_write_mutex);
632 * Returns the session ID of a device's nth level ancestor
633 * If there's no device at the nth level, return 0
635 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
637 DWORD parent_devinst;
638 unsigned long session_id = 0;
639 char* sanitized_path = NULL;
640 char path[MAX_PATH_LENGTH];
643 if (level < 1) return 0;
644 for (i = 0; i<level; i++) {
645 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
648 devinst = parent_devinst;
650 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
653 // TODO: (post hotplug): try without sanitizing
654 sanitized_path = sanitize_path(path);
655 if (sanitized_path == NULL) {
658 session_id = htab_hash(sanitized_path);
659 safe_free(sanitized_path);
664 * Populate the endpoints addresses of the device_priv interface helper structs
666 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
669 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
670 struct libusb_config_descriptor *conf_desc;
671 const struct libusb_interface_descriptor *if_desc;
672 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
674 r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
675 if (r != LIBUSB_SUCCESS) {
676 usbi_warn(ctx, "could not read config descriptor: error %d", r);
680 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
681 safe_free(priv->usb_interface[iface].endpoint);
683 if (if_desc->bNumEndpoints == 0) {
684 usbi_dbg("no endpoints found for interface %d", iface);
685 return LIBUSB_SUCCESS;
688 priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
689 if (priv->usb_interface[iface].endpoint == NULL) {
690 return LIBUSB_ERROR_NO_MEM;
693 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
694 for (i=0; i<if_desc->bNumEndpoints; i++) {
695 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
696 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
698 libusb_free_config_descriptor(conf_desc);
700 // Extra init may be required to configure endpoints
701 return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
704 // Lookup for a match in the list of API driver names
705 // return -1 if not found, driver match number otherwise
706 static int get_sub_api(char* driver, int api){
708 const char sep_str[2] = {LIST_SEPARATOR, 0};
710 size_t len = safe_strlen(driver);
712 if (len == 0) return SUB_API_NOTSET;
713 tmp_str = (char*) calloc(len+1, 1);
714 if (tmp_str == NULL) return SUB_API_NOTSET;
715 memcpy(tmp_str, driver, len+1);
716 tok = strtok(tmp_str, sep_str);
717 while (tok != NULL) {
718 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
719 if (safe_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
724 tok = strtok(NULL, sep_str);
727 return SUB_API_NOTSET;
731 * auto-claiming and auto-release helper functions
733 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
735 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
736 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
737 transfer->dev_handle);
738 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
739 int current_interface = *interface_number;
740 int r = LIBUSB_SUCCESS;
743 case USB_API_WINUSBX:
747 return LIBUSB_ERROR_INVALID_PARAM;
750 usbi_mutex_lock(&autoclaim_lock);
751 if (current_interface < 0) // No serviceable interface was found
753 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
754 // Must claim an interface of the same API type
755 if ( (priv->usb_interface[current_interface].apib->id == api_type)
756 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
757 usbi_dbg("auto-claimed interface %d for control request", current_interface);
758 if (handle_priv->autoclaim_count[current_interface] != 0) {
759 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
761 handle_priv->autoclaim_count[current_interface]++;
765 if (current_interface == USB_MAXINTERFACES) {
766 usbi_err(ctx, "could not auto-claim any interface");
767 r = LIBUSB_ERROR_NOT_FOUND;
770 // If we have a valid interface that was autoclaimed, we must increment
771 // its autoclaim count so that we can prevent an early release.
772 if (handle_priv->autoclaim_count[current_interface] != 0) {
773 handle_priv->autoclaim_count[current_interface]++;
776 usbi_mutex_unlock(&autoclaim_lock);
778 *interface_number = current_interface;
783 static void auto_release(struct usbi_transfer *itransfer)
785 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
786 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
787 libusb_device_handle *dev_handle = transfer->dev_handle;
788 struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
791 usbi_mutex_lock(&autoclaim_lock);
792 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
793 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
794 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
795 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
796 if (r == LIBUSB_SUCCESS) {
797 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
799 usbi_dbg("failed to auto-release interface %d (%s)",
800 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
804 usbi_mutex_unlock(&autoclaim_lock);
808 * init: libusb backend init function
810 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
811 * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed.
812 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
814 static int windows_init(struct libusb_context *ctx)
816 int i, r = LIBUSB_ERROR_OTHER;
817 OSVERSIONINFO os_version;
819 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
821 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
822 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
823 if (semaphore == NULL) {
824 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
825 return LIBUSB_ERROR_NO_MEM;
828 // A successful wait brings our semaphore count to 0 (unsignaled)
829 // => any concurent wait stalls until the semaphore's release
830 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
831 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
832 CloseHandle(semaphore);
833 return LIBUSB_ERROR_NO_MEM;
836 // NB: concurrent usage supposes that init calls are equally balanced with
837 // exit calls. If init is called more than exit, we will not exit properly
838 if ( ++concurrent_usage == 0 ) { // First init?
840 memset(&os_version, 0, sizeof(OSVERSIONINFO));
841 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
842 windows_version = WINDOWS_UNSUPPORTED;
843 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
844 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
845 windows_version = WINDOWS_XP;
846 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
847 windows_version = WINDOWS_2003; // also includes XP 64
848 } else if (os_version.dwMajorVersion >= 6) {
849 windows_version = WINDOWS_VISTA_AND_LATER;
852 if (windows_version == WINDOWS_UNSUPPORTED) {
853 usbi_err(ctx, "This version of Windows is NOT supported");
854 r = LIBUSB_ERROR_NOT_SUPPORTED;
858 // We need a lock for proper auto-release
859 usbi_mutex_init(&autoclaim_lock, NULL);
861 // Initialize pollable file descriptors
865 if (init_dlls() != LIBUSB_SUCCESS) {
866 usbi_err(ctx, "could not resolve DLL functions");
867 return LIBUSB_ERROR_NOT_FOUND;
870 // Initialize the low level APIs (we don't care about errors at this stage)
871 for (i=0; i<USB_API_MAX; i++) {
872 usb_api_backend[i].init(SUB_API_NOTSET, ctx);
875 // Because QueryPerformanceCounter might report different values when
876 // running on different cores, we create a separate thread for the timer
877 // calls, which we glue to the first core always to prevent timing discrepancies.
878 r = LIBUSB_ERROR_NO_MEM;
879 for (i = 0; i < 2; i++) {
880 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
881 if (timer_request[i] == NULL) {
882 usbi_err(ctx, "could not create timer request event %d - aborting", i);
886 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
887 if (timer_response == NULL) {
888 usbi_err(ctx, "could not create timer response semaphore - aborting");
891 timer_mutex = CreateMutex(NULL, FALSE, NULL);
892 if (timer_mutex == NULL) {
893 usbi_err(ctx, "could not create timer mutex - aborting");
896 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
897 if (timer_thread == NULL) {
898 usbi_err(ctx, "Unable to create timer thread - aborting");
901 SetThreadAffinityMask(timer_thread, 0);
903 // Wait for timer thread to init before continuing.
904 if (WaitForSingleObject(timer_response, INFINITE) != WAIT_OBJECT_0) {
905 usbi_err(ctx, "Failed to wait for timer thread to become ready - aborting");
909 // Create a hash table to store session ids. Second parameter is better if prime
910 htab_create(ctx, HTAB_SIZE);
912 // At this stage, either we went through full init successfully, or didn't need to
915 init_exit: // Holds semaphore here.
916 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
918 SetEvent(timer_request[1]); // actually the signal to quit the thread.
919 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
920 usbi_warn(ctx, "could not wait for timer thread to quit");
921 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
922 // all objects it might have held anyway.
924 CloseHandle(timer_thread);
927 for (i = 0; i < 2; i++) {
928 if (timer_request[i]) {
929 CloseHandle(timer_request[i]);
930 timer_request[i] = NULL;
933 if (timer_response) {
934 CloseHandle(timer_response);
935 timer_response = NULL;
938 CloseHandle(timer_mutex);
944 if (r != LIBUSB_SUCCESS)
945 --concurrent_usage; // Not expected to call libusb_exit if we failed.
947 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
948 CloseHandle(semaphore);
953 * HCD (root) hubs need to have their device descriptor manually populated
955 * Note that, like Microsoft does in the device manager, we populate the
956 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
958 static int force_hcd_device_descriptor(struct libusb_device *dev)
960 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
961 struct libusb_context *ctx = DEVICE_CTX(dev);
964 dev->num_configurations = 1;
965 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
966 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
967 priv->dev_descriptor.bNumConfigurations = 1;
968 priv->active_config = 1;
970 if (priv->parent_dev == NULL) {
971 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
972 return LIBUSB_ERROR_NO_DEVICE;
974 parent_priv = _device_priv(priv->parent_dev);
975 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
976 priv->dev_descriptor.idVendor = (uint16_t)vid;
977 priv->dev_descriptor.idProduct = (uint16_t)pid;
979 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
980 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
981 priv->dev_descriptor.idProduct = 1;
983 return LIBUSB_SUCCESS;
987 * fetch and cache all the config descriptors through I/O
989 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
991 DWORD size, ret_size;
992 struct libusb_context *ctx = DEVICE_CTX(dev);
993 struct windows_device_priv *priv = _device_priv(dev);
997 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
998 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
999 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
1001 if (dev->num_configurations == 0)
1002 return LIBUSB_ERROR_INVALID_PARAM;
1004 priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(unsigned char*));
1005 if (priv->config_descriptor == NULL)
1006 return LIBUSB_ERROR_NO_MEM;
1007 for (i=0; i<dev->num_configurations; i++)
1008 priv->config_descriptor[i] = NULL;
1010 for (i=0, r=LIBUSB_SUCCESS; ; i++)
1012 // safe loop: release all dynamic resources
1013 safe_free(cd_buf_actual);
1015 // safe loop: end of loop condition
1016 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
1019 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
1020 memset(&cd_buf_short, 0, size);
1022 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
1023 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
1024 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
1025 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
1026 cd_buf_short.req.SetupPacket.wIndex = i;
1027 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
1029 // Dummy call to get the required data size. Initial failures are reported as info rather
1030 // than error as they can occur for non-penalizing situations, such as with some hubs.
1031 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
1032 &cd_buf_short, size, &ret_size, NULL)) {
1033 usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
1034 LOOP_BREAK(LIBUSB_ERROR_IO);
1037 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
1038 usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
1039 LOOP_BREAK(LIBUSB_ERROR_IO);
1042 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
1043 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
1044 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
1045 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1047 memset(cd_buf_actual, 0, size);
1050 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
1051 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
1052 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
1053 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
1054 cd_buf_actual->SetupPacket.wIndex = i;
1055 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
1057 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
1058 cd_buf_actual, size, &ret_size, NULL)) {
1059 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
1060 LOOP_BREAK(LIBUSB_ERROR_IO);
1063 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
1065 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
1066 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
1067 LOOP_BREAK(LIBUSB_ERROR_IO);
1070 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
1071 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
1072 LOOP_BREAK(LIBUSB_ERROR_IO);
1075 usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
1076 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
1078 // Cache the descriptor
1079 priv->config_descriptor[i] = (unsigned char*) malloc(cd_data->wTotalLength);
1080 if (priv->config_descriptor[i] == NULL)
1081 return LIBUSB_ERROR_NO_MEM;
1082 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
1084 return LIBUSB_SUCCESS;
1088 * Populate a libusb device structure
1090 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
1091 uint8_t port_number, char* device_id, DWORD devinst)
1095 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
1096 struct windows_device_priv *priv, *parent_priv;
1097 struct libusb_context *ctx = DEVICE_CTX(dev);
1098 struct libusb_device* tmp_dev;
1101 if ((dev == NULL) || (parent_dev == NULL)) {
1102 return LIBUSB_ERROR_NOT_FOUND;
1104 priv = _device_priv(dev);
1105 parent_priv = _device_priv(parent_dev);
1106 if (parent_priv->apib->id != USB_API_HUB) {
1107 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1108 return LIBUSB_ERROR_NOT_FOUND;
1111 // It is possible for the parent hub not to have been initialized yet
1112 // If that's the case, lookup the ancestors to set the bus number
1113 if (parent_dev->bus_number == 0) {
1115 tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
1116 if (tmp_dev == NULL) break;
1117 if (tmp_dev->bus_number != 0) {
1118 usbi_dbg("got bus number from ancestor #%d", i);
1119 parent_dev->bus_number = tmp_dev->bus_number;
1120 libusb_unref_device(tmp_dev);
1123 libusb_unref_device(tmp_dev);
1126 if (parent_dev->bus_number == 0) {
1127 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1128 return LIBUSB_ERROR_NOT_FOUND;
1130 dev->bus_number = parent_dev->bus_number;
1131 priv->port = port_number;
1132 dev->port_number = port_number;
1133 priv->depth = parent_priv->depth + 1;
1134 priv->parent_dev = parent_dev;
1135 dev->parent_dev = parent_dev;
1137 // If the device address is already set, we can stop here
1138 if (dev->device_address != 0) {
1139 return LIBUSB_SUCCESS;
1141 memset(&conn_info, 0, sizeof(conn_info));
1142 if (priv->depth != 0) { // Not a HCD hub
1143 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1144 FILE_FLAG_OVERLAPPED, NULL);
1145 if (handle == INVALID_HANDLE_VALUE) {
1146 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1147 return LIBUSB_ERROR_ACCESS;
1149 size = sizeof(conn_info);
1150 conn_info.ConnectionIndex = (ULONG)port_number;
1151 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1152 &conn_info, size, &size, NULL)) {
1153 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1154 device_id, windows_error_str(0));
1155 safe_closehandle(handle);
1156 return LIBUSB_ERROR_NO_DEVICE;
1158 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1159 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1160 safe_closehandle(handle);
1161 return LIBUSB_ERROR_NO_DEVICE;
1163 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1164 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1165 priv->active_config = conn_info.CurrentConfigurationValue;
1166 usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
1167 // If we can't read the config descriptors, just set the number of confs to zero
1168 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1169 dev->num_configurations = 0;
1170 priv->dev_descriptor.bNumConfigurations = 0;
1172 safe_closehandle(handle);
1174 if (conn_info.DeviceAddress > UINT8_MAX) {
1175 usbi_err(ctx, "program assertion failed: device address overflow");
1177 dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
1178 if (dev->device_address == 1) {
1179 usbi_err(ctx, "program assertion failed: device address collision with root hub");
1181 switch (conn_info.Speed) {
1182 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1183 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1184 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1185 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1187 usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1191 dev->device_address = 1; // root hubs are set to use device number 1
1192 force_hcd_device_descriptor(dev);
1195 usbi_sanitize_device(dev);
1197 usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1198 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1200 return LIBUSB_SUCCESS;
1203 // Returns the api type, or 0 if not found/unsupported
1204 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
1205 SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
1207 // Precedence for filter drivers vs driver is in the order of this array
1208 struct driver_lookup lookup[3] = {
1209 {"\0\0", SPDRP_SERVICE, "driver"},
1210 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1211 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1213 DWORD size, reg_type;
1217 *api = USB_API_UNSUPPORTED;
1218 *sub_api = SUB_API_NOTSET;
1219 // Check the service & filter names to know the API we should use
1220 for (k=0; k<3; k++) {
1221 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1222 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1223 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1224 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1225 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1226 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1228 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1229 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1230 // (currently ';'), so even if an unsuported one does, it's not an issue
1231 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1232 if (lookup[k].list[l] == 0) {
1233 lookup[k].list[l] = LIST_SEPARATOR;
1236 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1238 if (GetLastError() != ERROR_INVALID_DATA) {
1239 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1241 lookup[k].list[0] = 0;
1245 for (i=1; i<USB_API_MAX; i++) {
1246 for (k=0; k<3; k++) {
1247 j = get_sub_api(lookup[k].list, i);
1249 usbi_dbg("matched %s name against %s",
1250 lookup[k].designation, (i!=USB_API_WINUSBX)?usb_api_backend[i].designation:sub_api_name[j]);
1259 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1260 char* dev_interface_path, char* device_id, int api, int sub_api)
1263 struct windows_device_priv *priv = _device_priv(dev);
1264 int interface_number;
1266 if (priv->apib->id != USB_API_COMPOSITE) {
1267 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1268 return LIBUSB_ERROR_NO_DEVICE;
1271 // Because MI_## are not necessarily in sequential order (some composite
1272 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1273 // interface number from the path's MI value
1274 interface_number = 0;
1275 for (i=0; device_id[i] != 0; ) {
1276 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1277 && (device_id[i++] == '_') ) {
1278 interface_number = (device_id[i++] - '0')*10;
1279 interface_number += device_id[i] - '0';
1284 if (device_id[i] == 0) {
1285 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1286 device_id, interface_number);
1289 if (priv->usb_interface[interface_number].path != NULL) {
1290 if (api == USB_API_HID) {
1291 // HID devices can have multiple collections (COL##) for each MI_## interface
1292 usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1293 interface_number, device_id);
1294 return LIBUSB_ERROR_ACCESS;
1296 // In other cases, just use the latest data
1297 safe_free(priv->usb_interface[interface_number].path);
1300 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1301 priv->usb_interface[interface_number].path = dev_interface_path;
1302 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1303 priv->usb_interface[interface_number].sub_api = sub_api;
1304 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1305 priv->hid = (struct hid_device_priv*) calloc(1, sizeof(struct hid_device_priv));
1306 if (priv->hid == NULL)
1307 return LIBUSB_ERROR_NO_MEM;
1310 return LIBUSB_SUCCESS;
1313 static int set_hid_interface(struct libusb_context* ctx, struct libusb_device* dev,
1314 char* dev_interface_path)
1317 struct windows_device_priv *priv = _device_priv(dev);
1319 if (priv->hid == NULL) {
1320 usbi_err(ctx, "program assertion failed: parent is not HID");
1321 return LIBUSB_ERROR_NO_DEVICE;
1323 if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1324 usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
1325 return LIBUSB_ERROR_NO_DEVICE;
1327 for (i=0; i<priv->hid->nb_interfaces; i++) {
1328 if (safe_strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1329 usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
1330 return LIBUSB_SUCCESS;
1334 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1335 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1336 usbi_dbg("interface[%d] = %s", priv->hid->nb_interfaces, dev_interface_path);
1337 priv->hid->nb_interfaces++;
1338 return LIBUSB_SUCCESS;
1342 * get_device_list: libusb backend device enumeration function
1344 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1346 struct discovered_devs *discdevs;
1347 HDEVINFO dev_info = { 0 };
1348 const char* usb_class[] = {"USB", "NUSB3", "IUSB3"};
1349 SP_DEVINFO_DATA dev_info_data = { 0 };
1350 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1352 #define MAX_ENUM_GUIDS 64
1353 const GUID* guid[MAX_ENUM_GUIDS];
1359 int r = LIBUSB_SUCCESS;
1361 size_t class_index = 0;
1362 unsigned int nb_guids, pass, i, j, ancestor;
1363 char path[MAX_PATH_LENGTH];
1364 char strbuf[MAX_PATH_LENGTH];
1365 struct libusb_device *dev, *parent_dev;
1366 struct windows_device_priv *priv, *parent_priv;
1367 char* dev_interface_path = NULL;
1368 char* dev_id_path = NULL;
1369 unsigned long session_id;
1370 DWORD size, reg_type, port_nr, install_state;
1372 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1375 // Keep a list of newly allocated devs to unref
1376 libusb_device** unref_list;
1377 unsigned int unref_size = 64;
1378 unsigned int unref_cur = 0;
1380 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1381 // PASS 2 : (re)enumerate HUBS
1382 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1383 // and list additional USB device interface GUIDs to explore
1384 // PASS 4 : (re)enumerate master USB devices that have a device interface
1385 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1386 // set the device interfaces.
1388 // Init the GUID table
1389 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1390 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1391 guid[GEN_PASS] = NULL;
1392 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1393 HidD_GetHidGuid(&hid_guid);
1394 guid[HID_PASS] = &hid_guid;
1395 nb_guids = HID_PASS+1;
1397 unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
1398 if (unref_list == NULL) {
1399 return LIBUSB_ERROR_NO_MEM;
1402 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1403 //#define ENUM_DEBUG
1405 const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
1406 usbi_dbg("\n#### PROCESSING %ss %s", passname[(pass<=HID_PASS)?pass:HID_PASS+1],
1407 (pass!=GEN_PASS)?guid_to_string(guid[pass]):"");
1409 for (i = 0; ; i++) {
1410 // safe loop: free up any (unprotected) dynamic resource
1411 // NB: this is always executed before breaking the loop
1412 safe_free(dev_interface_details);
1413 safe_free(dev_interface_path);
1414 safe_free(dev_id_path);
1415 priv = parent_priv = NULL;
1416 dev = parent_dev = NULL;
1418 // Safe loop: end of loop conditions
1419 if (r != LIBUSB_SUCCESS) {
1422 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1423 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1426 if (pass != GEN_PASS) {
1427 // Except for GEN, all passes deal with device interfaces
1428 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1429 if (dev_interface_details == NULL) {
1432 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1433 if (dev_interface_path == NULL) {
1434 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1439 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1440 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1441 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1442 for (; class_index < ARRAYSIZE(usb_class); class_index++) {
1443 if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
1447 if (class_index >= ARRAYSIZE(usb_class))
1451 // Read the Device ID path. This is what we'll use as UID
1452 // Note that if the device is plugged in a different port or hub, the Device ID changes
1453 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1454 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1455 dev_info_data.DevInst);
1458 dev_id_path = sanitize_path(path);
1459 if (dev_id_path == NULL) {
1460 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1461 dev_info_data.DevInst);
1465 usbi_dbg("PRO: %s", dev_id_path);
1468 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1470 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1471 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1472 ®_type, (BYTE*)&port_nr, 4, &size))
1474 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1475 dev_id_path, windows_error_str(0));
1480 // Set API to use or get additional data from generic pass
1481 api = USB_API_UNSUPPORTED;
1482 sub_api = SUB_API_NOTSET;
1487 // We use the GEN pass to detect driverless devices...
1488 size = sizeof(strbuf);
1489 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1490 ®_type, (BYTE*)strbuf, size, &size)) {
1491 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1492 usbi_info(ctx, "libusb will not be able to access it.");
1494 // ...and to add the additional device interface GUIDs
1495 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1496 if (key != INVALID_HANDLE_VALUE) {
1497 size = sizeof(guid_string_w);
1498 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1499 (BYTE*)guid_string_w, &size);
1501 if (s == ERROR_SUCCESS) {
1502 if (nb_guids >= MAX_ENUM_GUIDS) {
1503 // If this assert is ever reported, grow a GUID table dynamically
1504 usbi_err(ctx, "program assertion failed: too many GUIDs");
1505 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1507 if_guid = (GUID*) calloc(1, sizeof(GUID));
1508 pCLSIDFromString(guid_string_w, if_guid);
1509 guid[nb_guids++] = if_guid;
1510 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1518 // Get the API type (after checking that the driver installation is OK)
1519 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1520 ®_type, (BYTE*)&install_state, 4, &size))
1522 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1523 dev_id_path, windows_error_str(0));
1524 } else if (install_state != 0) {
1525 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1526 dev_id_path, install_state);
1529 get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
1533 // Find parent device (for the passes that need it)
1540 // Go through the ancestors until we see a face we recognize
1542 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1543 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1544 if (session_id == 0) {
1547 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1549 if (parent_dev == NULL) {
1550 usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1553 parent_priv = _device_priv(parent_dev);
1554 // virtual USB devices are also listed during GEN - don't process these yet
1555 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1556 libusb_unref_device(parent_dev);
1562 // Create new or match existing device, using the (hashed) device_id as session id
1563 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1564 // These are the passes that create "new" devices
1565 session_id = htab_hash(dev_id_path);
1566 dev = usbi_get_device_by_session_id(ctx, session_id);
1568 if (pass == DEV_PASS) {
1569 // This can occur if the OS only reports a newly plugged device after we started enum
1570 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1571 " - ignoring", dev_id_path);
1574 usbi_dbg("allocating new device for session [%X]", session_id);
1575 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1576 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1578 windows_device_priv_init(dev);
1580 usbi_dbg("found existing device for session [%X] (%d.%d)",
1581 session_id, dev->bus_number, dev->device_address);
1583 // Keep track of devices that need unref
1584 unref_list[unref_cur++] = dev;
1585 if (unref_cur >= unref_size) {
1587 unref_list = usbi_reallocf(unref_list, unref_size*sizeof(libusb_device*));
1588 if (unref_list == NULL) {
1589 usbi_err(ctx, "could not realloc list for unref - aborting.");
1590 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1593 priv = _device_priv(dev);
1599 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1600 dev->device_address = 0;
1601 dev->num_configurations = 0;
1602 priv->apib = &usb_api_backend[USB_API_HUB];
1603 priv->sub_api = SUB_API_NOTSET;
1604 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1605 priv->path = dev_interface_path; dev_interface_path = NULL;
1609 // If the device has already been setup, don't do it again
1610 if (priv->path != NULL)
1612 // Take care of API initialization
1613 priv->path = dev_interface_path; dev_interface_path = NULL;
1614 priv->apib = &usb_api_backend[api];
1615 priv->sub_api = sub_api;
1617 case USB_API_COMPOSITE:
1621 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1622 if (priv->hid == NULL) {
1623 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1625 priv->hid->nb_interfaces = 0;
1628 // For other devices, the first interface is the same as the device
1629 priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
1630 if (priv->usb_interface[0].path != NULL) {
1631 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1633 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1635 // The following is needed if we want API calls to work for both simple
1636 // and composite devices.
1637 for(j=0; j<USB_MAXINTERFACES; j++) {
1638 priv->usb_interface[j].apib = &usb_api_backend[api];
1644 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1645 if (r == LIBUSB_SUCCESS) {
1646 // Append device to the list of discovered devices
1647 discdevs = discovered_devs_append(*_discdevs, dev);
1649 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1651 *_discdevs = discdevs;
1652 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1653 // This can occur if the device was disconnected but Windows hasn't
1654 // refreshed its enumeration yet - in that case, we ignore the device
1658 default: // HID_PASS and later
1659 if (parent_priv->apib->id == USB_API_HID) {
1660 usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1661 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1662 if (r != LIBUSB_SUCCESS) LOOP_BREAK(r);
1663 dev_interface_path = NULL;
1664 } else if (parent_priv->apib->id == USB_API_COMPOSITE) {
1665 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1666 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api)) {
1667 case LIBUSB_SUCCESS:
1668 dev_interface_path = NULL;
1670 case LIBUSB_ERROR_ACCESS:
1671 // interface has already been set => make sure dev_interface_path is freed then
1678 libusb_unref_device(parent_dev);
1684 // Free any additional GUIDs
1685 for (pass = HID_PASS+1; pass < nb_guids; pass++) {
1686 safe_free(guid[pass]);
1689 // Unref newly allocated devs
1690 for (i=0; i<unref_cur; i++) {
1691 safe_unref_device(unref_list[i]);
1693 safe_free(unref_list);
1699 * exit: libusb backend deinitialization function
1701 static void windows_exit(void)
1705 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1707 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1708 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1709 if (semaphore == NULL) {
1713 // A successful wait brings our semaphore count to 0 (unsignaled)
1714 // => any concurent wait stalls until the semaphore release
1715 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1716 CloseHandle(semaphore);
1720 // Only works if exits and inits are balanced exactly
1721 if (--concurrent_usage < 0) { // Last exit
1722 for (i=0; i<USB_API_MAX; i++) {
1723 usb_api_backend[i].exit(SUB_API_NOTSET);
1728 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1729 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1730 usbi_dbg("could not wait for timer thread to quit");
1731 TerminateThread(timer_thread, 1);
1733 CloseHandle(timer_thread);
1734 timer_thread = NULL;
1736 for (i = 0; i < 2; i++) {
1737 if (timer_request[i]) {
1738 CloseHandle(timer_request[i]);
1739 timer_request[i] = NULL;
1742 if (timer_response) {
1743 CloseHandle(timer_response);
1744 timer_response = NULL;
1747 CloseHandle(timer_mutex);
1753 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1754 CloseHandle(semaphore);
1757 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1759 struct windows_device_priv *priv = _device_priv(dev);
1761 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1764 return LIBUSB_SUCCESS;
1767 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1769 struct windows_device_priv *priv = _device_priv(dev);
1770 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1773 // config index is zero based
1774 if (config_index >= dev->num_configurations)
1775 return LIBUSB_ERROR_INVALID_PARAM;
1777 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1778 return LIBUSB_ERROR_NOT_FOUND;
1780 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1782 size = min(config_header->wTotalLength, len);
1783 memcpy(buffer, priv->config_descriptor[config_index], size);
1790 * return the cached copy of the active config descriptor
1792 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1794 struct windows_device_priv *priv = _device_priv(dev);
1796 if (priv->active_config == 0)
1797 return LIBUSB_ERROR_NOT_FOUND;
1799 // config index is zero based
1800 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1803 static int windows_open(struct libusb_device_handle *dev_handle)
1805 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1806 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1808 if (priv->apib == NULL) {
1809 usbi_err(ctx, "program assertion failed - device is not initialized");
1810 return LIBUSB_ERROR_NO_DEVICE;
1813 return priv->apib->open(SUB_API_NOTSET, dev_handle);
1816 static void windows_close(struct libusb_device_handle *dev_handle)
1818 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1820 priv->apib->close(SUB_API_NOTSET, dev_handle);
1823 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1825 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1827 if (priv->active_config == 0) {
1829 return LIBUSB_ERROR_NOT_FOUND;
1832 *config = priv->active_config;
1833 return LIBUSB_SUCCESS;
1837 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1838 * does not currently expose a service that allows higher-level drivers to set
1839 * the configuration."
1841 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1843 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1844 int r = LIBUSB_SUCCESS;
1846 if (config >= USB_MAXCONFIG)
1847 return LIBUSB_ERROR_INVALID_PARAM;
1849 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1850 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1851 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1854 if (r == LIBUSB_SUCCESS) {
1855 priv->active_config = (uint8_t)config;
1860 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1862 int r = LIBUSB_SUCCESS;
1863 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1865 if (iface >= USB_MAXINTERFACES)
1866 return LIBUSB_ERROR_INVALID_PARAM;
1868 safe_free(priv->usb_interface[iface].endpoint);
1869 priv->usb_interface[iface].nb_endpoints= 0;
1871 r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
1873 if (r == LIBUSB_SUCCESS) {
1874 r = windows_assign_endpoints(dev_handle, iface, 0);
1880 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1882 int r = LIBUSB_SUCCESS;
1883 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1885 safe_free(priv->usb_interface[iface].endpoint);
1886 priv->usb_interface[iface].nb_endpoints= 0;
1888 r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
1890 if (r == LIBUSB_SUCCESS) {
1891 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1897 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1899 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1901 return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
1904 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1906 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1907 return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
1910 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1912 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1913 return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
1916 // The 3 functions below are unlikely to ever get supported on Windows
1917 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1919 return LIBUSB_ERROR_NOT_SUPPORTED;
1922 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1924 return LIBUSB_ERROR_NOT_SUPPORTED;
1927 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1929 return LIBUSB_ERROR_NOT_SUPPORTED;
1932 static void windows_destroy_device(struct libusb_device *dev)
1934 windows_device_priv_release(dev);
1937 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1939 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1941 usbi_free_fd(&transfer_priv->pollable_fd);
1942 safe_free(transfer_priv->hid_buffer);
1943 // When auto claim is in use, attempt to release the auto-claimed interface
1944 auto_release(itransfer);
1947 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1949 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1950 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1951 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1952 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1955 r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
1956 if (r != LIBUSB_SUCCESS) {
1960 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1961 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1963 itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
1964 return LIBUSB_SUCCESS;
1967 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1969 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1970 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1971 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1972 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1975 r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
1976 if (r != LIBUSB_SUCCESS) {
1980 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1981 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1983 itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
1984 return LIBUSB_SUCCESS;
1987 static int submit_control_transfer(struct usbi_transfer *itransfer)
1989 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1990 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1991 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1992 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1995 r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
1996 if (r != LIBUSB_SUCCESS) {
2000 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
2002 itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
2003 return LIBUSB_SUCCESS;
2007 static int windows_submit_transfer(struct usbi_transfer *itransfer)
2009 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2011 switch (transfer->type) {
2012 case LIBUSB_TRANSFER_TYPE_CONTROL:
2013 return submit_control_transfer(itransfer);
2014 case LIBUSB_TRANSFER_TYPE_BULK:
2015 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2016 if (IS_XFEROUT(transfer) &&
2017 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2018 return LIBUSB_ERROR_NOT_SUPPORTED;
2019 return submit_bulk_transfer(itransfer);
2020 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2021 return submit_iso_transfer(itransfer);
2022 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2023 return LIBUSB_ERROR_NOT_SUPPORTED;
2025 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2026 return LIBUSB_ERROR_INVALID_PARAM;
2030 static int windows_abort_control(struct usbi_transfer *itransfer)
2032 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2033 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2035 return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
2038 static int windows_abort_transfers(struct usbi_transfer *itransfer)
2040 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2041 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2043 return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
2046 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
2048 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2050 switch (transfer->type) {
2051 case LIBUSB_TRANSFER_TYPE_CONTROL:
2052 return windows_abort_control(itransfer);
2053 case LIBUSB_TRANSFER_TYPE_BULK:
2054 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2055 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2056 return windows_abort_transfers(itransfer);
2057 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2058 return LIBUSB_ERROR_NOT_SUPPORTED;
2060 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2061 return LIBUSB_ERROR_INVALID_PARAM;
2065 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2067 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2068 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2069 int status, istatus;
2071 usbi_dbg("handling I/O completion with errcode %d, size %d", io_result, io_size);
2075 status = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2077 case ERROR_GEN_FAILURE:
2078 usbi_dbg("detected endpoint stall");
2079 status = LIBUSB_TRANSFER_STALL;
2081 case ERROR_SEM_TIMEOUT:
2082 usbi_dbg("detected semaphore timeout");
2083 status = LIBUSB_TRANSFER_TIMED_OUT;
2085 case ERROR_OPERATION_ABORTED:
2086 istatus = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2087 if (istatus != LIBUSB_TRANSFER_COMPLETED) {
2088 usbi_dbg("Failed to copy partial data in aborted operation: %d", istatus);
2090 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
2091 usbi_dbg("detected timeout");
2092 status = LIBUSB_TRANSFER_TIMED_OUT;
2094 usbi_dbg("detected operation aborted");
2095 status = LIBUSB_TRANSFER_CANCELLED;
2099 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error %d: %s", io_result, windows_error_str(io_result));
2100 status = LIBUSB_TRANSFER_ERROR;
2103 windows_clear_transfer_priv(itransfer); // Cancel polling
2104 usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
2107 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2109 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2111 switch (transfer->type) {
2112 case LIBUSB_TRANSFER_TYPE_CONTROL:
2113 case LIBUSB_TRANSFER_TYPE_BULK:
2114 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2115 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2116 windows_transfer_callback (itransfer, io_result, io_size);
2118 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2119 return LIBUSB_ERROR_NOT_SUPPORTED;
2121 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2125 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2127 struct windows_transfer_priv* transfer_priv = NULL;
2128 POLL_NFDS_TYPE i = 0;
2130 struct usbi_transfer *transfer;
2131 DWORD io_size, io_result;
2133 usbi_mutex_lock(&ctx->open_devs_lock);
2134 for (i = 0; i < nfds && num_ready > 0; i++) {
2136 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2138 if (!fds[i].revents) {
2144 // Because a Windows OVERLAPPED is used for poll emulation,
2145 // a pollable fd is created and stored with each transfer
2146 usbi_mutex_lock(&ctx->flying_transfers_lock);
2147 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2148 transfer_priv = usbi_transfer_get_os_priv(transfer);
2149 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2154 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2157 // Handle async requests that completed synchronously first
2158 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2159 io_result = NO_ERROR;
2160 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2161 // Regular async overlapped
2162 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2163 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2164 io_result = NO_ERROR;
2166 io_result = GetLastError();
2168 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2169 // let handle_callback free the event using the transfer wfd
2170 // If you don't use the transfer wfd, you run a risk of trying to free a
2171 // newly allocated wfd that took the place of the one from the transfer.
2172 windows_handle_callback(transfer, io_result, io_size);
2174 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2175 return LIBUSB_ERROR_NOT_FOUND;
2179 usbi_mutex_unlock(&ctx->open_devs_lock);
2180 return LIBUSB_SUCCESS;
2184 * Monotonic and real time functions
2186 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2188 LARGE_INTEGER hires_counter, li_frequency;
2192 // Init - find out if we have access to a monotonic (hires) timer
2193 if (!QueryPerformanceFrequency(&li_frequency)) {
2194 usbi_dbg("no hires timer available on this platform");
2195 hires_frequency = 0;
2196 hires_ticks_to_ps = UINT64_C(0);
2198 hires_frequency = li_frequency.QuadPart;
2199 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2200 // to picoseconds to compute the tv_nsecs part in clock_gettime
2201 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2202 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2205 // Signal windows_init() that we're ready to service requests
2206 if (ReleaseSemaphore(timer_response, 1, NULL) == 0) {
2207 usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
2210 // Main loop - wait for requests
2212 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2213 if ( (timer_index != 0) && (timer_index != 1) ) {
2214 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2217 if (request_count[timer_index] == 0) {
2218 // Request already handled
2219 ResetEvent(timer_request[timer_index]);
2220 // There's still a possiblity that a thread sends a request between the
2221 // time we test request_count[] == 0 and we reset the event, in which case
2222 // the request would be ignored. The simple solution to that is to test
2223 // request_count again and process requests if non zero.
2224 if (request_count[timer_index] == 0)
2227 switch (timer_index) {
2229 WaitForSingleObject(timer_mutex, INFINITE);
2230 // Requests to this thread are for hires always
2231 if (QueryPerformanceCounter(&hires_counter) != 0) {
2232 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2233 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2235 // Fallback to real-time if we can't get monotonic value
2236 // Note that real-time clock does not wait on the mutex or this thread.
2237 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2239 ReleaseMutex(timer_mutex);
2241 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2243 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2244 usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
2247 case 1: // time to quit
2248 usbi_dbg("timer thread quitting");
2254 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2257 ULARGE_INTEGER rtime;
2260 case USBI_CLOCK_MONOTONIC:
2261 if (hires_frequency != 0) {
2263 InterlockedIncrement((LONG*)&request_count[0]);
2264 SetEvent(timer_request[0]);
2265 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2268 WaitForSingleObject(timer_mutex, INFINITE);
2270 ReleaseMutex(timer_mutex);
2271 return LIBUSB_SUCCESS;
2273 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2274 break; // Retry until successful
2276 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2277 return LIBUSB_ERROR_OTHER;
2281 // Fall through and return real-time if monotonic was not detected @ timer init
2282 case USBI_CLOCK_REALTIME:
2283 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2284 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2285 // Note however that our resolution is bounded by the Windows system time
2286 // functions and is at best of the order of 1 ms (or, usually, worse)
2287 GetSystemTimeAsFileTime(&filetime);
2288 rtime.LowPart = filetime.dwLowDateTime;
2289 rtime.HighPart = filetime.dwHighDateTime;
2290 rtime.QuadPart -= epoch_time;
2291 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2292 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2293 return LIBUSB_SUCCESS;
2295 return LIBUSB_ERROR_INVALID_PARAM;
2300 // NB: MSVC6 does not support named initializers.
2301 const struct usbi_os_backend windows_backend = {
2303 USBI_CAP_HAS_HID_ACCESS,
2307 windows_get_device_list,
2308 NULL, /* hotplug_poll */
2312 windows_get_device_descriptor,
2313 windows_get_active_config_descriptor,
2314 windows_get_config_descriptor,
2315 NULL, /* get_config_descriptor_by_value() */
2317 windows_get_configuration,
2318 windows_set_configuration,
2319 windows_claim_interface,
2320 windows_release_interface,
2322 windows_set_interface_altsetting,
2324 windows_reset_device,
2326 NULL, /* alloc_streams */
2327 NULL, /* free_streams */
2329 windows_kernel_driver_active,
2330 windows_detach_kernel_driver,
2331 windows_attach_kernel_driver,
2333 windows_destroy_device,
2335 windows_submit_transfer,
2336 windows_cancel_transfer,
2337 windows_clear_transfer_priv,
2339 windows_handle_events,
2341 windows_clock_gettime,
2342 #if defined(USBI_TIMERFD_AVAILABLE)
2345 sizeof(struct windows_device_priv),
2346 sizeof(struct windows_device_handle_priv),
2347 sizeof(struct windows_transfer_priv),
2355 static int unsupported_init(int sub_api, struct libusb_context *ctx) {
2356 return LIBUSB_SUCCESS;
2358 static int unsupported_exit(int sub_api) {
2359 return LIBUSB_SUCCESS;
2361 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle) {
2362 PRINT_UNSUPPORTED_API(open);
2364 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle) {
2365 usbi_dbg("unsupported API call for 'close'");
2367 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2368 PRINT_UNSUPPORTED_API(configure_endpoints);
2370 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2371 PRINT_UNSUPPORTED_API(claim_interface);
2373 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2374 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2376 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2377 PRINT_UNSUPPORTED_API(release_interface);
2379 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2380 PRINT_UNSUPPORTED_API(clear_halt);
2382 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle) {
2383 PRINT_UNSUPPORTED_API(reset_device);
2385 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
2386 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2388 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
2389 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2391 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) {
2392 PRINT_UNSUPPORTED_API(submit_control_transfer);
2394 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer) {
2395 PRINT_UNSUPPORTED_API(abort_control);
2397 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer) {
2398 PRINT_UNSUPPORTED_API(abort_transfers);
2400 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
2401 PRINT_UNSUPPORTED_API(copy_transfer_data);
2403 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2404 return LIBUSB_SUCCESS;
2406 // These names must be uppercase
2407 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30"};
2408 const char* composite_driver_names[] = {"USBCCGP"};
2409 const char* winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2410 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2411 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2413 USB_API_UNSUPPORTED,
2421 unsupported_configure_endpoints,
2422 unsupported_claim_interface,
2423 unsupported_set_interface_altsetting,
2424 unsupported_release_interface,
2425 unsupported_clear_halt,
2426 unsupported_reset_device,
2427 unsupported_submit_bulk_transfer,
2428 unsupported_submit_iso_transfer,
2429 unsupported_submit_control_transfer,
2430 unsupported_abort_control,
2431 unsupported_abort_transfers,
2432 unsupported_copy_transfer_data,
2437 ARRAYSIZE(hub_driver_names),
2442 unsupported_configure_endpoints,
2443 unsupported_claim_interface,
2444 unsupported_set_interface_altsetting,
2445 unsupported_release_interface,
2446 unsupported_clear_halt,
2447 unsupported_reset_device,
2448 unsupported_submit_bulk_transfer,
2449 unsupported_submit_iso_transfer,
2450 unsupported_submit_control_transfer,
2451 unsupported_abort_control,
2452 unsupported_abort_transfers,
2453 unsupported_copy_transfer_data,
2457 composite_driver_names,
2458 ARRAYSIZE(composite_driver_names),
2463 common_configure_endpoints,
2464 composite_claim_interface,
2465 composite_set_interface_altsetting,
2466 composite_release_interface,
2467 composite_clear_halt,
2468 composite_reset_device,
2469 composite_submit_bulk_transfer,
2470 composite_submit_iso_transfer,
2471 composite_submit_control_transfer,
2472 composite_abort_control,
2473 composite_abort_transfers,
2474 composite_copy_transfer_data,
2478 winusbx_driver_names,
2479 ARRAYSIZE(winusbx_driver_names),
2484 winusbx_configure_endpoints,
2485 winusbx_claim_interface,
2486 winusbx_set_interface_altsetting,
2487 winusbx_release_interface,
2489 winusbx_reset_device,
2490 winusbx_submit_bulk_transfer,
2491 unsupported_submit_iso_transfer,
2492 winusbx_submit_control_transfer,
2493 winusbx_abort_control,
2494 winusbx_abort_transfers,
2495 winusbx_copy_transfer_data,
2500 ARRAYSIZE(hid_driver_names),
2505 common_configure_endpoints,
2506 hid_claim_interface,
2507 hid_set_interface_altsetting,
2508 hid_release_interface,
2511 hid_submit_bulk_transfer,
2512 unsupported_submit_iso_transfer,
2513 hid_submit_control_transfer,
2514 hid_abort_transfers,
2515 hid_abort_transfers,
2516 hid_copy_transfer_data,
2522 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2524 #define WinUSBX_Set(fn) do { if (native_winusb) WinUSBX[i].fn = (WinUsb_##fn##_t) GetProcAddress(h, "WinUsb_" #fn); \
2525 else pLibK_GetProcAddress((PVOID*)&WinUSBX[i].fn, i, KUSB_FNID_##fn); } while (0)
2527 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2530 bool native_winusb = false;
2532 KLIB_VERSION LibK_Version;
2533 LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2534 LibK_GetVersion_t pLibK_GetVersion = NULL;
2536 h = GetModuleHandleA("libusbK");
2538 h = LoadLibraryA("libusbK");
2541 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2542 h = GetModuleHandleA("WinUSB");
2544 h = LoadLibraryA("WinUSB");
2546 usbi_warn(ctx, "WinUSB DLL is not available either,\n"
2547 "you will not be able to access devices outside of enumeration");
2548 return LIBUSB_ERROR_NOT_FOUND;
2551 usbi_dbg("using libusbK DLL for universal access");
2552 pLibK_GetVersion = (LibK_GetVersion_t) GetProcAddress(h, "LibK_GetVersion");
2553 if (pLibK_GetVersion != NULL) {
2554 pLibK_GetVersion(&LibK_Version);
2555 usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2556 LibK_Version.Micro, LibK_Version.Nano);
2558 pLibK_GetProcAddress = (LibK_GetProcAddress_t) GetProcAddress(h, "LibK_GetProcAddress");
2559 if (pLibK_GetProcAddress == NULL) {
2560 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2561 return LIBUSB_ERROR_NOT_FOUND;
2564 native_winusb = (pLibK_GetProcAddress == NULL);
2565 for (i=SUB_API_LIBUSBK; i<SUB_API_MAX; i++) {
2566 WinUSBX_Set(AbortPipe);
2567 WinUSBX_Set(ControlTransfer);
2568 WinUSBX_Set(FlushPipe);
2570 WinUSBX_Set(GetAssociatedInterface);
2571 WinUSBX_Set(GetCurrentAlternateSetting);
2572 WinUSBX_Set(GetDescriptor);
2573 WinUSBX_Set(GetOverlappedResult);
2574 WinUSBX_Set(GetPipePolicy);
2575 WinUSBX_Set(GetPowerPolicy);
2576 WinUSBX_Set(Initialize);
2577 WinUSBX_Set(QueryDeviceInformation);
2578 WinUSBX_Set(QueryInterfaceSettings);
2579 WinUSBX_Set(QueryPipe);
2580 WinUSBX_Set(ReadPipe);
2581 WinUSBX_Set(ResetPipe);
2582 WinUSBX_Set(SetCurrentAlternateSetting);
2583 WinUSBX_Set(SetPipePolicy);
2584 WinUSBX_Set(SetPowerPolicy);
2585 WinUSBX_Set(WritePipe);
2586 if (!native_winusb) {
2587 WinUSBX_Set(ResetDevice);
2589 if (WinUSBX[i].Initialize != NULL) {
2590 WinUSBX[i].initialized = true;
2591 usbi_dbg("initalized sub API %s", sub_api_name[i]);
2593 usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2594 WinUSBX[i].initialized = false;
2597 return LIBUSB_SUCCESS;
2600 static int winusbx_exit(int sub_api)
2602 return LIBUSB_SUCCESS;
2605 // NB: open and close must ensure that they only handle interface of
2606 // the right API type, as these functions can be called wholesale from
2607 // composite_open(), with interfaces belonging to different APIs
2608 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2610 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2611 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2612 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2617 CHECK_WINUSBX_AVAILABLE(sub_api);
2619 // WinUSB requires a seperate handle for each interface
2620 for (i = 0; i < USB_MAXINTERFACES; i++) {
2621 if ( (priv->usb_interface[i].path != NULL)
2622 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX) ) {
2623 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2624 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2625 if (file_handle == INVALID_HANDLE_VALUE) {
2626 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2627 switch(GetLastError()) {
2628 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2629 return LIBUSB_ERROR_NO_DEVICE;
2630 case ERROR_ACCESS_DENIED:
2631 return LIBUSB_ERROR_ACCESS;
2633 return LIBUSB_ERROR_IO;
2636 handle_priv->interface_handle[i].dev_handle = file_handle;
2640 return LIBUSB_SUCCESS;
2643 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2645 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2646 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2650 if (sub_api == SUB_API_NOTSET)
2651 sub_api = priv->sub_api;
2652 if (!WinUSBX[sub_api].initialized)
2655 for (i = 0; i < USB_MAXINTERFACES; i++) {
2656 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2657 file_handle = handle_priv->interface_handle[i].dev_handle;
2658 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2659 CloseHandle(file_handle);
2665 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2667 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2668 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2669 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2672 uint8_t endpoint_address;
2675 CHECK_WINUSBX_AVAILABLE(sub_api);
2677 // With handle and enpoints set (in parent), we can setup the default pipe properties
2678 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2679 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2680 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2681 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2682 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2683 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2685 if ((i == -1) || (sub_api == SUB_API_LIBUSB0)) {
2686 continue; // Other policies don't apply to control endpoint or libusb0
2689 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2690 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2691 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2693 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2694 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2695 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2698 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2699 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2700 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2701 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2702 usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2704 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2705 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2706 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2710 return LIBUSB_SUCCESS;
2713 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2715 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2716 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2717 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2718 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2719 HANDLE file_handle, winusb_handle;
2722 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2723 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2724 SP_DEVINFO_DATA dev_info_data;
2725 char* dev_path_no_guid = NULL;
2726 char filter_path[] = "\\\\.\\libusb0-0000";
2727 bool found_filter = false;
2729 CHECK_WINUSBX_AVAILABLE(sub_api);
2731 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2732 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2733 if ((is_using_usbccgp) || (iface == 0)) {
2734 // composite device (independent interfaces) or interface 0
2735 file_handle = handle_priv->interface_handle[iface].dev_handle;
2736 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2737 return LIBUSB_ERROR_NOT_FOUND;
2740 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2741 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2742 err = GetLastError();
2744 case ERROR_BAD_COMMAND:
2745 // The device was disconnected
2746 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2747 return LIBUSB_ERROR_NO_DEVICE;
2749 // it may be that we're using the libusb0 filter driver.
2750 // TODO: can we move this whole business into the K/0 DLL?
2751 for (i = 0; ; i++) {
2752 safe_free(dev_interface_details);
2753 safe_free(dev_path_no_guid);
2754 dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2755 if ((found_filter) || (dev_interface_details == NULL)) {
2759 dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2760 if (safe_strncmp(dev_path_no_guid, priv->usb_interface[iface].path, safe_strlen(dev_path_no_guid)) == 0) {
2761 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2762 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2763 if (file_handle == INVALID_HANDLE_VALUE) {
2764 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2766 WinUSBX[sub_api].Free(winusb_handle);
2767 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2770 found_filter = true;
2775 if (!found_filter) {
2776 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2777 return LIBUSB_ERROR_ACCESS;
2781 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2783 // For all other interfaces, use GetAssociatedInterface()
2784 winusb_handle = handle_priv->interface_handle[0].api_handle;
2785 // It is a requirement for multiple interface devices on Windows that, to you
2786 // must first claim the first interface before you claim the others
2787 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2788 file_handle = handle_priv->interface_handle[0].dev_handle;
2789 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2790 handle_priv->interface_handle[0].api_handle = winusb_handle;
2791 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2793 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2794 return LIBUSB_ERROR_ACCESS;
2797 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2798 &handle_priv->interface_handle[iface].api_handle)) {
2799 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2800 switch(GetLastError()) {
2801 case ERROR_NO_MORE_ITEMS: // invalid iface
2802 return LIBUSB_ERROR_NOT_FOUND;
2803 case ERROR_BAD_COMMAND: // The device was disconnected
2804 return LIBUSB_ERROR_NO_DEVICE;
2805 case ERROR_ALREADY_EXISTS: // already claimed
2806 return LIBUSB_ERROR_BUSY;
2808 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2809 return LIBUSB_ERROR_ACCESS;
2813 usbi_dbg("claimed interface %d", iface);
2814 handle_priv->active_interface = iface;
2816 return LIBUSB_SUCCESS;
2819 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2821 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2822 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2823 HANDLE winusb_handle;
2825 CHECK_WINUSBX_AVAILABLE(sub_api);
2827 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2828 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2829 return LIBUSB_ERROR_NOT_FOUND;
2832 WinUSBX[sub_api].Free(winusb_handle);
2833 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2835 return LIBUSB_SUCCESS;
2839 * Return the first valid interface (of the same API type), for control transfers
2841 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2843 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2844 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2847 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2848 usbi_dbg("unsupported API ID");
2852 for (i=0; i<USB_MAXINTERFACES; i++) {
2853 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2854 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2855 && (handle_priv->interface_handle[i].api_handle != 0)
2856 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2857 && (priv->usb_interface[i].apib->id == api_id) ) {
2865 * Lookup interface by endpoint address. -1 if not found
2867 static int interface_by_endpoint(struct windows_device_priv *priv,
2868 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2871 for (i=0; i<USB_MAXINTERFACES; i++) {
2872 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2874 if (handle_priv->interface_handle[i].api_handle == 0)
2876 if (priv->usb_interface[i].endpoint == NULL)
2878 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2879 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2887 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2889 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2890 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2891 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2892 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2893 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2894 transfer->dev_handle);
2895 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2897 HANDLE winusb_handle;
2898 int current_interface;
2901 CHECK_WINUSBX_AVAILABLE(sub_api);
2903 transfer_priv->pollable_fd = INVALID_WINFD;
2904 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2906 if (size > MAX_CTRL_BUFFER_LENGTH)
2907 return LIBUSB_ERROR_INVALID_PARAM;
2909 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2910 if (current_interface < 0) {
2911 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS) {
2912 return LIBUSB_ERROR_NOT_FOUND;
2916 usbi_dbg("will use interface %d", current_interface);
2917 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2919 wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
2920 // Always use the handle returned from usbi_create_fd (wfd.handle)
2922 return LIBUSB_ERROR_NO_MEM;
2925 // Sending of set configuration control requests from WinUSB creates issues
2926 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2927 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2928 if (setup->value != priv->active_config) {
2929 usbi_warn(ctx, "cannot set configuration other than the default one");
2931 return LIBUSB_ERROR_INVALID_PARAM;
2933 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2934 wfd.overlapped->InternalHigh = 0;
2936 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2937 if(GetLastError() != ERROR_IO_PENDING) {
2938 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
2940 return LIBUSB_ERROR_IO;
2943 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2944 wfd.overlapped->InternalHigh = (DWORD)size;
2948 // Use priv_transfer to store data needed for async polling
2949 transfer_priv->pollable_fd = wfd;
2950 transfer_priv->interface_number = (uint8_t)current_interface;
2952 return LIBUSB_SUCCESS;
2955 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2957 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2958 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2959 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2960 HANDLE winusb_handle;
2962 CHECK_WINUSBX_AVAILABLE(sub_api);
2964 if (altsetting > 255) {
2965 return LIBUSB_ERROR_INVALID_PARAM;
2968 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2969 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2970 usbi_err(ctx, "interface must be claimed first");
2971 return LIBUSB_ERROR_NOT_FOUND;
2974 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2975 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2976 return LIBUSB_ERROR_IO;
2979 return LIBUSB_SUCCESS;
2982 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2984 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2985 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2986 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2987 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2988 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2989 HANDLE winusb_handle;
2991 int current_interface;
2994 CHECK_WINUSBX_AVAILABLE(sub_api);
2996 transfer_priv->pollable_fd = INVALID_WINFD;
2998 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2999 if (current_interface < 0) {
3000 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3001 return LIBUSB_ERROR_NOT_FOUND;
3004 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3006 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3008 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
3009 // Always use the handle returned from usbi_create_fd (wfd.handle)
3011 return LIBUSB_ERROR_NO_MEM;
3014 if (IS_XFERIN(transfer)) {
3015 usbi_dbg("reading %d bytes", transfer->length);
3016 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
3018 usbi_dbg("writing %d bytes", transfer->length);
3019 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
3022 if(GetLastError() != ERROR_IO_PENDING) {
3023 usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
3025 return LIBUSB_ERROR_IO;
3028 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3029 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
3032 transfer_priv->pollable_fd = wfd;
3033 transfer_priv->interface_number = (uint8_t)current_interface;
3035 return LIBUSB_SUCCESS;
3038 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3040 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3041 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3042 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3043 HANDLE winusb_handle;
3044 int current_interface;
3046 CHECK_WINUSBX_AVAILABLE(sub_api);
3048 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3049 if (current_interface < 0) {
3050 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3051 return LIBUSB_ERROR_NOT_FOUND;
3054 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3055 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3057 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
3058 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
3059 return LIBUSB_ERROR_NO_DEVICE;
3062 return LIBUSB_SUCCESS;
3066 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
3067 * through testing as well):
3068 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
3069 * the control transfer using CancelIo"
3071 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
3073 // Cancelling of the I/O is done in the parent
3074 return LIBUSB_SUCCESS;
3077 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3079 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3080 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3081 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3082 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3083 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3084 HANDLE winusb_handle;
3085 int current_interface;
3087 CHECK_WINUSBX_AVAILABLE(sub_api);
3089 current_interface = transfer_priv->interface_number;
3090 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
3091 usbi_err(ctx, "program assertion failed: invalid interface_number");
3092 return LIBUSB_ERROR_NOT_FOUND;
3094 usbi_dbg("will use interface %d", current_interface);
3096 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3098 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
3099 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
3100 return LIBUSB_ERROR_NO_DEVICE;
3103 return LIBUSB_SUCCESS;
3107 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
3108 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
3109 * "WinUSB does not support host-initiated reset port and cycle port operations" and
3110 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
3111 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
3112 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
3114 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
3115 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3117 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3118 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3119 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3121 HANDLE winusb_handle;
3124 CHECK_WINUSBX_AVAILABLE(sub_api);
3126 // Reset any available pipe (except control)
3127 for (i=0; i<USB_MAXINTERFACES; i++) {
3128 winusb_handle = handle_priv->interface_handle[i].api_handle;
3129 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
3131 // Cancel any pollable I/O
3132 usbi_remove_pollfd(ctx, wfd.fd);
3134 wfd = handle_to_winfd(winusb_handle);
3137 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
3138 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
3139 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
3140 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
3141 usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
3142 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3144 // FlushPipe seems to fail on OUT pipes
3145 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
3146 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
3147 usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
3148 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3150 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
3151 usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
3152 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3158 // libusbK & libusb0 have the ability to issue an actual device reset
3159 if (WinUSBX[sub_api].ResetDevice != NULL) {
3160 winusb_handle = handle_priv->interface_handle[0].api_handle;
3161 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
3162 WinUSBX[sub_api].ResetDevice(winusb_handle);
3165 return LIBUSB_SUCCESS;
3168 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3170 itransfer->transferred += io_size;
3171 return LIBUSB_TRANSFER_COMPLETED;
3175 * Internal HID Support functions (from libusb-win32)
3176 * Note that functions that complete data transfer synchronously must return
3177 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3179 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
3180 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
3182 static int _hid_wcslen(WCHAR *str)
3185 while (str[i] && (str[i] != 0x409)) {
3191 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3193 struct libusb_device_descriptor d;
3195 d.bLength = LIBUSB_DT_DEVICE_SIZE;
3196 d.bDescriptorType = LIBUSB_DT_DEVICE;
3197 d.bcdUSB = 0x0200; /* 2.00 */
3199 d.bDeviceSubClass = 0;
3200 d.bDeviceProtocol = 0;
3201 d.bMaxPacketSize0 = 64; /* fix this! */
3202 d.idVendor = (uint16_t)dev->vid;
3203 d.idProduct = (uint16_t)dev->pid;
3204 d.bcdDevice = 0x0100;
3205 d.iManufacturer = dev->string_index[0];
3206 d.iProduct = dev->string_index[1];
3207 d.iSerialNumber = dev->string_index[2];
3208 d.bNumConfigurations = 1;
3210 if (*size > LIBUSB_DT_DEVICE_SIZE)
3211 *size = LIBUSB_DT_DEVICE_SIZE;
3212 memcpy(data, &d, *size);
3213 return LIBUSB_COMPLETED;
3216 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3218 char num_endpoints = 0;
3219 size_t config_total_len = 0;
3220 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3221 struct libusb_config_descriptor *cd;
3222 struct libusb_interface_descriptor *id;
3223 struct libusb_hid_descriptor *hd;
3224 struct libusb_endpoint_descriptor *ed;
3227 if (dev->input_report_size)
3229 if (dev->output_report_size)
3232 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3233 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3236 cd = (struct libusb_config_descriptor *)tmp;
3237 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3238 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3239 + LIBUSB_DT_INTERFACE_SIZE);
3240 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3241 + LIBUSB_DT_INTERFACE_SIZE
3242 + LIBUSB_DT_HID_SIZE);
3244 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3245 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3246 cd->wTotalLength = (uint16_t) config_total_len;
3247 cd->bNumInterfaces = 1;
3248 cd->bConfigurationValue = 1;
3249 cd->iConfiguration = 0;
3250 cd->bmAttributes = 1 << 7; /* bus powered */
3253 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3254 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3255 id->bInterfaceNumber = 0;
3256 id->bAlternateSetting = 0;
3257 id->bNumEndpoints = num_endpoints;
3258 id->bInterfaceClass = 3;
3259 id->bInterfaceSubClass = 0;
3260 id->bInterfaceProtocol = 0;
3263 tmp_size = LIBUSB_DT_HID_SIZE;
3264 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3266 if (dev->input_report_size) {
3267 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3268 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3269 ed->bEndpointAddress = HID_IN_EP;
3270 ed->bmAttributes = 3;
3271 ed->wMaxPacketSize = dev->input_report_size - 1;
3273 ed = (struct libusb_endpoint_descriptor *)((char*)ed + LIBUSB_DT_ENDPOINT_SIZE);
3276 if (dev->output_report_size) {
3277 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3278 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3279 ed->bEndpointAddress = HID_OUT_EP;
3280 ed->bmAttributes = 3;
3281 ed->wMaxPacketSize = dev->output_report_size - 1;
3285 if (*size > config_total_len)
3286 *size = config_total_len;
3287 memcpy(data, tmp, *size);
3288 return LIBUSB_COMPLETED;
3291 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int _index,
3292 void *data, size_t *size)
3295 size_t tmp_size = 0;
3298 /* language ID, EN-US */
3299 char string_langid[] = {
3304 if ((*size < 2) || (*size > 255)) {
3305 return LIBUSB_ERROR_OVERFLOW;
3309 tmp = string_langid;
3310 tmp_size = sizeof(string_langid)+2;
3312 for (i=0; i<3; i++) {
3313 if (_index == (dev->string_index[i])) {
3314 tmp = dev->string[i];
3315 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3319 if (i == 3) { // not found
3320 return LIBUSB_ERROR_INVALID_PARAM;
3325 return LIBUSB_ERROR_INVALID_PARAM;
3328 if (tmp_size < *size) {
3332 ((uint8_t*)data)[0] = (uint8_t)*size;
3333 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3334 memcpy((uint8_t*)data+2, tmp, *size-2);
3335 return LIBUSB_COMPLETED;
3338 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3340 struct libusb_hid_descriptor d;
3341 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3342 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3344 _hid_get_report_descriptor(dev, tmp, &report_len);
3346 d.bLength = LIBUSB_DT_HID_SIZE;
3347 d.bDescriptorType = LIBUSB_DT_HID;
3348 d.bcdHID = 0x0110; /* 1.10 */
3350 d.bNumDescriptors = 1;
3351 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3352 d.wClassDescriptorLength = (uint16_t)report_len;
3354 if (*size > LIBUSB_DT_HID_SIZE)
3355 *size = LIBUSB_DT_HID_SIZE;
3356 memcpy(data, &d, *size);
3357 return LIBUSB_COMPLETED;
3360 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3362 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3365 /* usage page (0xFFA0 == vendor defined) */
3366 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3367 /* usage (vendor defined) */
3368 d[i++] = 0x09; d[i++] = 0x01;
3369 /* start collection (application) */
3370 d[i++] = 0xA1; d[i++] = 0x01;
3372 if (dev->input_report_size) {
3373 /* usage (vendor defined) */
3374 d[i++] = 0x09; d[i++] = 0x01;
3375 /* logical minimum (0) */
3376 d[i++] = 0x15; d[i++] = 0x00;
3377 /* logical maximum (255) */
3378 d[i++] = 0x25; d[i++] = 0xFF;
3379 /* report size (8 bits) */
3380 d[i++] = 0x75; d[i++] = 0x08;
3382 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3383 /* input (data, variable, absolute) */
3384 d[i++] = 0x81; d[i++] = 0x00;
3387 if (dev->output_report_size) {
3388 /* usage (vendor defined) */
3389 d[i++] = 0x09; d[i++] = 0x02;
3390 /* logical minimum (0) */
3391 d[i++] = 0x15; d[i++] = 0x00;
3392 /* logical maximum (255) */
3393 d[i++] = 0x25; d[i++] = 0xFF;
3394 /* report size (8 bits) */
3395 d[i++] = 0x75; d[i++] = 0x08;
3397 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3398 /* output (data, variable, absolute) */
3399 d[i++] = 0x91; d[i++] = 0x00;
3401 /* feature report */
3402 if (dev->feature_report_size) {
3403 /* usage (vendor defined) */
3404 d[i++] = 0x09; d[i++] = 0x03;
3405 /* logical minimum (0) */
3406 d[i++] = 0x15; d[i++] = 0x00;
3407 /* logical maximum (255) */
3408 d[i++] = 0x25; d[i++] = 0xFF;
3409 /* report size (8 bits) */
3410 d[i++] = 0x75; d[i++] = 0x08;
3412 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3413 /* feature (data, variable, absolute) */
3414 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3417 /* end collection */
3422 memcpy(data, d, *size);
3423 return LIBUSB_COMPLETED;
3426 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3427 int type, int _index, void *data, size_t *size)
3430 case LIBUSB_DT_DEVICE:
3431 usbi_dbg("LIBUSB_DT_DEVICE");
3432 return _hid_get_device_descriptor(dev, data, size);
3433 case LIBUSB_DT_CONFIG:
3434 usbi_dbg("LIBUSB_DT_CONFIG");
3436 return _hid_get_config_descriptor(dev, data, size);
3437 return LIBUSB_ERROR_INVALID_PARAM;
3438 case LIBUSB_DT_STRING:
3439 usbi_dbg("LIBUSB_DT_STRING");
3440 return _hid_get_string_descriptor(dev, _index, data, size);
3442 usbi_dbg("LIBUSB_DT_HID");
3444 return _hid_get_hid_descriptor(dev, data, size);
3445 return LIBUSB_ERROR_INVALID_PARAM;
3446 case LIBUSB_DT_REPORT:
3447 usbi_dbg("LIBUSB_DT_REPORT");
3449 return _hid_get_report_descriptor(dev, data, size);
3450 return LIBUSB_ERROR_INVALID_PARAM;
3451 case LIBUSB_DT_PHYSICAL:
3452 usbi_dbg("LIBUSB_DT_PHYSICAL");
3453 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3454 return LIBUSB_COMPLETED;
3455 return LIBUSB_ERROR_OTHER;
3457 usbi_dbg("unsupported");
3458 return LIBUSB_ERROR_INVALID_PARAM;
3461 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3462 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3466 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3467 int r = LIBUSB_SUCCESS;
3469 if (tp->hid_buffer != NULL) {
3470 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3473 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3474 usbi_dbg("invalid size (%d)", *size);
3475 return LIBUSB_ERROR_INVALID_PARAM;
3478 switch (report_type) {
3479 case HID_REPORT_TYPE_INPUT:
3480 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3482 case HID_REPORT_TYPE_FEATURE:
3483 ioctl_code = IOCTL_HID_GET_FEATURE;
3486 usbi_dbg("unknown HID report type %d", report_type);
3487 return LIBUSB_ERROR_INVALID_PARAM;
3490 // Add a trailing byte to detect overflows
3491 buf = (uint8_t*)calloc(expected_size+1, 1);
3493 return LIBUSB_ERROR_NO_MEM;
3495 buf[0] = (uint8_t)id; // Must be set always
3496 usbi_dbg("report ID: 0x%02X", buf[0]);
3498 tp->hid_expected_size = expected_size;
3499 read_size = expected_size;
3501 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3502 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3503 buf, expected_size+1, &read_size, overlapped)) {
3504 if (GetLastError() != ERROR_IO_PENDING) {
3505 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3507 return LIBUSB_ERROR_IO;
3509 // Asynchronous wait
3510 tp->hid_buffer = buf;
3511 tp->hid_dest = (uint8_t*)data; // copy dest, as not necessarily the start of the transfer buffer
3512 return LIBUSB_SUCCESS;
3515 // Transfer completed synchronously => copy and discard extra buffer
3516 if (read_size == 0) {
3517 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3521 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3523 if ((size_t)read_size > expected_size) {
3524 r = LIBUSB_ERROR_OVERFLOW;
3525 usbi_dbg("OVERFLOW!");
3527 r = LIBUSB_COMPLETED;
3530 *size = MIN((size_t)read_size, *size);
3532 // Discard report ID
3533 memcpy(data, buf+1, *size);
3535 memcpy(data, buf, *size);
3542 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3543 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3546 uint8_t *buf = NULL;
3547 DWORD ioctl_code, write_size= (DWORD)*size;
3549 if (tp->hid_buffer != NULL) {
3550 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3553 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3554 usbi_dbg("invalid size (%d)", *size);
3555 return LIBUSB_ERROR_INVALID_PARAM;
3558 switch (report_type) {
3559 case HID_REPORT_TYPE_OUTPUT:
3560 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3562 case HID_REPORT_TYPE_FEATURE:
3563 ioctl_code = IOCTL_HID_SET_FEATURE;
3566 usbi_dbg("unknown HID report type %d", report_type);
3567 return LIBUSB_ERROR_INVALID_PARAM;
3570 usbi_dbg("report ID: 0x%02X", id);
3571 // When report IDs are not used (i.e. when id == 0), we must add
3572 // a null report ID. Otherwise, we just use original data buffer
3576 buf = (uint8_t*) malloc(write_size);
3578 return LIBUSB_ERROR_NO_MEM;
3582 memcpy(buf + 1, data, *size);
3584 // This seems like a waste, but if we don't duplicate the
3585 // data, we'll get issues when freeing hid_buffer
3586 memcpy(buf, data, *size);
3588 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3592 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3593 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3594 buf, write_size, &write_size, overlapped)) {
3595 if (GetLastError() != ERROR_IO_PENDING) {
3596 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3598 return LIBUSB_ERROR_IO;
3600 tp->hid_buffer = buf;
3601 tp->hid_dest = NULL;
3602 return LIBUSB_SUCCESS;
3605 // Transfer completed synchronously
3607 if (write_size == 0) {
3608 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3611 return LIBUSB_COMPLETED;
3614 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3615 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3616 size_t *size, OVERLAPPED* overlapped)
3618 int report_type = (value >> 8) & 0xFF;
3619 int report_id = value & 0xFF;
3621 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3622 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3623 return LIBUSB_ERROR_INVALID_PARAM;
3625 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3626 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3628 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3629 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3631 return LIBUSB_ERROR_INVALID_PARAM;
3638 static int hid_init(int sub_api, struct libusb_context *ctx)
3640 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3641 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3642 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3643 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3644 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3645 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3646 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3647 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3648 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3649 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3650 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3651 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3652 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3653 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3654 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3655 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3657 api_hid_available = true;
3658 return LIBUSB_SUCCESS;
3661 static int hid_exit(int sub_api)
3663 return LIBUSB_SUCCESS;
3666 // NB: open and close must ensure that they only handle interface of
3667 // the right API type, as these functions can be called wholesale from
3668 // composite_open(), with interfaces belonging to different APIs
3669 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3671 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3672 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3673 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3675 HIDD_ATTRIBUTES hid_attributes;
3676 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3677 HIDP_CAPS capabilities;
3678 HIDP_VALUE_CAPS *value_caps;
3680 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3682 // report IDs handling
3684 const char* type[3] = {"input", "output", "feature"};
3685 int nb_ids[2]; // zero and nonzero report IDs
3687 CHECK_HID_AVAILABLE;
3688 if (priv->hid == NULL) {
3689 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3690 return LIBUSB_ERROR_NOT_FOUND;
3693 for (i = 0; i < USB_MAXINTERFACES; i++) {
3694 if ( (priv->usb_interface[i].path != NULL)
3695 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3696 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3697 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3699 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3700 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3701 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3702 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3703 * HidD_GetFeature (if the device supports Feature reports)."
3705 if (hid_handle == INVALID_HANDLE_VALUE) {
3706 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3707 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3708 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3709 if (hid_handle == INVALID_HANDLE_VALUE) {
3710 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3711 switch(GetLastError()) {
3712 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3713 return LIBUSB_ERROR_NO_DEVICE;
3714 case ERROR_ACCESS_DENIED:
3715 return LIBUSB_ERROR_ACCESS;
3717 return LIBUSB_ERROR_IO;
3720 priv->usb_interface[i].restricted_functionality = true;
3722 handle_priv->interface_handle[i].api_handle = hid_handle;
3726 hid_attributes.Size = sizeof(hid_attributes);
3728 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3729 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3733 priv->hid->vid = hid_attributes.VendorID;
3734 priv->hid->pid = hid_attributes.ProductID;
3736 // Set the maximum available input buffer size
3737 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3738 usbi_dbg("set maximum input buffer size to %d", i/2);
3740 // Get the maximum input and output report size
3741 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3742 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3745 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3746 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3750 // Find out if interrupt will need report IDs
3751 size[0] = capabilities.NumberInputValueCaps;
3752 size[1] = capabilities.NumberOutputValueCaps;
3753 size[2] = capabilities.NumberFeatureValueCaps;
3754 for (j=HidP_Input; j<=HidP_Feature; j++) {
3755 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3756 priv->hid->uses_report_ids[j] = false;
3758 value_caps = (HIDP_VALUE_CAPS*) calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3759 if ( (value_caps != NULL)
3760 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3761 && (size[j] >= 1) ) {
3764 for (i=0; i<(int)size[j]; i++) {
3765 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3766 if (value_caps[i].ReportID != 0) {
3772 if (nb_ids[1] != 0) {
3773 if (nb_ids[0] != 0) {
3774 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3777 priv->hid->uses_report_ids[j] = true;
3780 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3782 safe_free(value_caps);
3786 // Set the report sizes
3787 priv->hid->input_report_size = capabilities.InputReportByteLength;
3788 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3789 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3791 // Fetch string descriptors
3792 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3793 if (priv->hid->string_index[0] != 0) {
3794 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3795 sizeof(priv->hid->string[0]));
3797 priv->hid->string[0][0] = 0;
3799 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3800 if (priv->hid->string_index[1] != 0) {
3801 HidD_GetProductString(hid_handle, priv->hid->string[1],
3802 sizeof(priv->hid->string[1]));
3804 priv->hid->string[1][0] = 0;
3806 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3807 if (priv->hid->string_index[2] != 0) {
3808 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3809 sizeof(priv->hid->string[2]));
3811 priv->hid->string[2][0] = 0;
3815 if (preparsed_data) {
3816 HidD_FreePreparsedData(preparsed_data);
3819 return LIBUSB_SUCCESS;
3822 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3824 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3825 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3829 if (!api_hid_available)
3832 for (i = 0; i < USB_MAXINTERFACES; i++) {
3833 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3834 file_handle = handle_priv->interface_handle[i].api_handle;
3835 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3836 CloseHandle(file_handle);
3842 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3844 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3845 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3847 CHECK_HID_AVAILABLE;
3849 // NB: Disconnection detection is not possible in this function
3850 if (priv->usb_interface[iface].path == NULL) {
3851 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3854 // We use dev_handle as a flag for interface claimed
3855 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3856 return LIBUSB_ERROR_BUSY; // already claimed
3859 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3861 usbi_dbg("claimed interface %d", iface);
3862 handle_priv->active_interface = iface;
3864 return LIBUSB_SUCCESS;
3867 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3869 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3870 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3872 CHECK_HID_AVAILABLE;
3874 if (priv->usb_interface[iface].path == NULL) {
3875 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3878 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
3879 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3882 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3884 return LIBUSB_SUCCESS;
3887 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3889 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3891 CHECK_HID_AVAILABLE;
3893 if (altsetting > 255) {
3894 return LIBUSB_ERROR_INVALID_PARAM;
3897 if (altsetting != 0) {
3898 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3899 return LIBUSB_ERROR_NOT_SUPPORTED;
3902 return LIBUSB_SUCCESS;
3905 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3907 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3908 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3909 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3910 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3911 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3912 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3915 int current_interface, config;
3917 int r = LIBUSB_ERROR_INVALID_PARAM;
3919 CHECK_HID_AVAILABLE;
3921 transfer_priv->pollable_fd = INVALID_WINFD;
3922 safe_free(transfer_priv->hid_buffer);
3923 transfer_priv->hid_dest = NULL;
3924 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3926 if (size > MAX_CTRL_BUFFER_LENGTH) {
3927 return LIBUSB_ERROR_INVALID_PARAM;
3930 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3931 if (current_interface < 0) {
3932 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) {
3933 return LIBUSB_ERROR_NOT_FOUND;
3937 usbi_dbg("will use interface %d", current_interface);
3938 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3939 // Always use the handle returned from usbi_create_fd (wfd.handle)
3940 wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
3942 return LIBUSB_ERROR_NOT_FOUND;
3945 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3946 case LIBUSB_REQUEST_TYPE_STANDARD:
3947 switch(setup->request) {
3948 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3949 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3950 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3952 case LIBUSB_REQUEST_GET_CONFIGURATION:
3953 r = windows_get_configuration(transfer->dev_handle, &config);
3954 if (r == LIBUSB_SUCCESS) {
3956 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3957 r = LIBUSB_COMPLETED;
3960 case LIBUSB_REQUEST_SET_CONFIGURATION:
3961 if (setup->value == priv->active_config) {
3962 r = LIBUSB_COMPLETED;
3964 usbi_warn(ctx, "cannot set configuration other than the default one");
3965 r = LIBUSB_ERROR_INVALID_PARAM;
3968 case LIBUSB_REQUEST_GET_INTERFACE:
3970 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3971 r = LIBUSB_COMPLETED;
3973 case LIBUSB_REQUEST_SET_INTERFACE:
3974 r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->index, setup->value);
3975 if (r == LIBUSB_SUCCESS) {
3976 r = LIBUSB_COMPLETED;
3980 usbi_warn(ctx, "unsupported HID control request");
3981 r = LIBUSB_ERROR_INVALID_PARAM;
3985 case LIBUSB_REQUEST_TYPE_CLASS:
3986 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3987 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3988 &size, wfd.overlapped);
3991 usbi_warn(ctx, "unsupported HID control request");
3992 r = LIBUSB_ERROR_INVALID_PARAM;
3996 if (r == LIBUSB_COMPLETED) {
3997 // Force request to be completed synchronously. Transferred size has been set by previous call
3998 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3999 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
4000 // set InternalHigh to the number of bytes transferred
4001 wfd.overlapped->InternalHigh = (DWORD)size;
4005 if (r == LIBUSB_SUCCESS) {
4006 // Use priv_transfer to store data needed for async polling
4007 transfer_priv->pollable_fd = wfd;
4008 transfer_priv->interface_number = (uint8_t)current_interface;
4016 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4017 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4018 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4019 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4020 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4021 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4024 bool direction_in, ret;
4025 int current_interface, length;
4027 int r = LIBUSB_SUCCESS;
4029 CHECK_HID_AVAILABLE;
4031 transfer_priv->pollable_fd = INVALID_WINFD;
4032 transfer_priv->hid_dest = NULL;
4033 safe_free(transfer_priv->hid_buffer);
4035 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4036 if (current_interface < 0) {
4037 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4038 return LIBUSB_ERROR_NOT_FOUND;
4041 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
4043 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4044 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
4046 wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
4047 // Always use the handle returned from usbi_create_fd (wfd.handle)
4049 return LIBUSB_ERROR_NO_MEM;
4052 // If report IDs are not in use, an extra prefix byte must be added
4053 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
4054 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
4055 length = transfer->length+1;
4057 length = transfer->length;
4059 // Add a trailing byte to detect overflows on input
4060 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
4061 if (transfer_priv->hid_buffer == NULL) {
4062 return LIBUSB_ERROR_NO_MEM;
4064 transfer_priv->hid_expected_size = length;
4067 transfer_priv->hid_dest = transfer->buffer;
4068 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
4069 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
4071 if (!priv->hid->uses_report_ids[1]) {
4072 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
4074 // We could actually do without the calloc and memcpy in this case
4075 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
4077 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
4078 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
4081 if (GetLastError() != ERROR_IO_PENDING) {
4082 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
4084 safe_free(transfer_priv->hid_buffer);
4085 return LIBUSB_ERROR_IO;
4088 // Only write operations that completed synchronously need to free up
4089 // hid_buffer. For reads, copy_transfer_data() handles that process.
4090 if (!direction_in) {
4091 safe_free(transfer_priv->hid_buffer);
4094 usbi_err(ctx, "program assertion failed - no data was transferred");
4097 if (size > (size_t)length) {
4098 usbi_err(ctx, "OVERFLOW!");
4099 r = LIBUSB_ERROR_OVERFLOW;
4101 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
4102 wfd.overlapped->InternalHigh = size;
4105 transfer_priv->pollable_fd = wfd;
4106 transfer_priv->interface_number = (uint8_t)current_interface;
4111 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4113 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4114 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4115 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4117 int current_interface;
4119 CHECK_HID_AVAILABLE;
4121 current_interface = transfer_priv->interface_number;
4122 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4123 CancelIo(hid_handle);
4125 return LIBUSB_SUCCESS;
4128 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4130 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4132 int current_interface;
4134 CHECK_HID_AVAILABLE;
4136 // Flushing the queues on all interfaces is the best we can achieve
4137 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
4138 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4139 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
4140 HidD_FlushQueue(hid_handle);
4143 return LIBUSB_SUCCESS;
4146 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4148 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4149 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4150 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4152 int current_interface;
4154 CHECK_HID_AVAILABLE;
4156 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4157 if (current_interface < 0) {
4158 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4159 return LIBUSB_ERROR_NOT_FOUND;
4162 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
4163 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4165 // No endpoint selection with Microsoft's implementation, so we try to flush the
4166 // whole interface. Should be OK for most case scenarios
4167 if (!HidD_FlushQueue(hid_handle)) {
4168 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
4169 // Device was probably disconnected
4170 return LIBUSB_ERROR_NO_DEVICE;
4173 return LIBUSB_SUCCESS;
4176 // This extra function is only needed for HID
4177 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
4178 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4179 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4180 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4181 int r = LIBUSB_TRANSFER_COMPLETED;
4182 uint32_t corrected_size = io_size;
4184 if (transfer_priv->hid_buffer != NULL) {
4185 // If we have a valid hid_buffer, it means the transfer was async
4186 if (transfer_priv->hid_dest != NULL) { // Data readout
4187 if (corrected_size > 0) {
4188 // First, check for overflow
4189 if (corrected_size > transfer_priv->hid_expected_size) {
4190 usbi_err(ctx, "OVERFLOW!");
4191 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4192 r = LIBUSB_TRANSFER_OVERFLOW;
4195 if (transfer_priv->hid_buffer[0] == 0) {
4196 // Discard the 1 byte report ID prefix
4198 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
4200 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4203 transfer_priv->hid_dest = NULL;
4205 // For write, we just need to free the hid buffer
4206 safe_free(transfer_priv->hid_buffer);
4208 itransfer->transferred += corrected_size;
4214 * Composite API functions
4216 static int composite_init(int sub_api, struct libusb_context *ctx)
4218 return LIBUSB_SUCCESS;
4221 static int composite_exit(int sub_api)
4223 return LIBUSB_SUCCESS;
4226 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4228 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4229 int r = LIBUSB_ERROR_NOT_FOUND;
4231 // SUB_API_MAX+1 as the SUB_API_MAX pos is used to indicate availability of HID
4232 bool available[SUB_API_MAX+1] = {0};
4234 for (i=0; i<USB_MAXINTERFACES; i++) {
4235 switch (priv->usb_interface[i].apib->id) {
4236 case USB_API_WINUSBX:
4237 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4238 available[priv->usb_interface[i].sub_api] = true;
4241 available[SUB_API_MAX] = true;
4248 for (i=0; i<SUB_API_MAX; i++) { // WinUSB-like drivers
4250 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4251 if (r != LIBUSB_SUCCESS) {
4256 if (available[SUB_API_MAX]) { // HID driver
4257 r = hid_open(SUB_API_NOTSET, dev_handle);
4262 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4264 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4266 bool available[SUB_API_MAX];
4268 for (i = 0; i<SUB_API_MAX; i++) {
4269 available[i] = false;
4272 for (i=0; i<USB_MAXINTERFACES; i++) {
4273 if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4274 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
4275 available[priv->usb_interface[i].sub_api] = true;
4279 for (i=0; i<SUB_API_MAX; i++) {
4281 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4286 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4288 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4289 return priv->usb_interface[iface].apib->
4290 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4293 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4295 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4296 return priv->usb_interface[iface].apib->
4297 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4300 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4302 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4303 return priv->usb_interface[iface].apib->
4304 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4307 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4309 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4310 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4311 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4314 // Interface shouldn't matter for control, but it does in practice, with Windows'
4315 // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4316 for (pass = 0; pass < 2; pass++) {
4317 for (i=0; i<USB_MAXINTERFACES; i++) {
4318 if (priv->usb_interface[i].path != NULL) {
4319 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4320 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4323 usbi_dbg("using interface %d", i);
4324 return priv->usb_interface[i].apib->submit_control_transfer(priv->usb_interface[i].sub_api, itransfer);
4329 usbi_err(ctx, "no libusb supported interfaces to complete request");
4330 return LIBUSB_ERROR_NOT_FOUND;
4333 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4334 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4335 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4336 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4337 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4338 int current_interface;
4340 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4341 if (current_interface < 0) {
4342 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4343 return LIBUSB_ERROR_NOT_FOUND;
4346 return priv->usb_interface[current_interface].apib->
4347 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
4349 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4350 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4351 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4352 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4353 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4354 int current_interface;
4356 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4357 if (current_interface < 0) {
4358 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4359 return LIBUSB_ERROR_NOT_FOUND;
4362 return priv->usb_interface[current_interface].apib->
4363 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
4365 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4367 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4368 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4369 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4370 int current_interface;
4372 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4373 if (current_interface < 0) {
4374 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4375 return LIBUSB_ERROR_NOT_FOUND;
4378 return priv->usb_interface[current_interface].apib->
4379 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);}
4381 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4383 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4384 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4385 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4387 return priv->usb_interface[transfer_priv->interface_number].apib->
4388 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
4390 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4392 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4393 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4394 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4396 return priv->usb_interface[transfer_priv->interface_number].apib->
4397 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
4399 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4401 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4404 bool available[SUB_API_MAX];
4405 for (i = 0; i<SUB_API_MAX; i++) {
4406 available[i] = false;
4408 for (i=0; i<USB_MAXINTERFACES; i++) {
4409 if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4410 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
4411 available[priv->usb_interface[i].sub_api] = true;
4414 for (i=0; i<SUB_API_MAX; i++) {
4416 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4417 if (r != LIBUSB_SUCCESS) {
4422 return LIBUSB_SUCCESS;
4425 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4427 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4428 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4429 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4431 return priv->usb_interface[transfer_priv->interface_number].apib->
4432 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);