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
39 #include "poll_windows.h"
40 #include "windows_usb.h"
42 // The 2 macros below are used in conjunction with safe loops.
43 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
44 #define LOOP_BREAK(err) { r=err; continue; }
47 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
48 static int windows_clock_gettime(int clk_id, struct timespec *tp);
49 unsigned __stdcall windows_clock_gettime_threaded(void* param);
51 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
53 // WinUSB-like API prototypes
54 static int winusbx_init(int sub_api, struct libusb_context *ctx);
55 static int winusbx_exit(int sub_api);
56 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
57 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
58 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
59 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
60 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
61 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
62 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
63 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
64 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
65 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
66 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
67 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
68 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
70 static int hid_init(int sub_api, struct libusb_context *ctx);
71 static int hid_exit(int sub_api);
72 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
73 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
74 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
75 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
76 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
77 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
78 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
79 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
80 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
81 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
82 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
83 // Composite API prototypes
84 static int composite_init(int sub_api, struct libusb_context *ctx);
85 static int composite_exit(int sub_api);
86 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
87 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
88 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
89 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
90 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
91 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
92 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
93 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
94 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
95 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
96 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
97 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
98 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
102 uint64_t hires_frequency, hires_ticks_to_ps;
103 const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
104 int windows_version = WINDOWS_UNDEFINED;
105 static char windows_version_str[128] = "Windows Undefined";
107 static int concurrent_usage = -1;
108 usbi_mutex_t autoclaim_lock;
110 HANDLE timer_thread = NULL;
111 DWORD timer_thread_id = 0;
113 #define CHECK_WINUSBX_AVAILABLE(sub_api) do { if (sub_api == SUB_API_NOTSET) sub_api = priv->sub_api; \
114 if (!WinUSBX[sub_api].initialized) return LIBUSB_ERROR_ACCESS; } while(0)
115 static struct winusb_interface WinUSBX[SUB_API_MAX];
116 const char* sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
117 bool api_hid_available = false;
118 #define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
120 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
121 if ((guid1 != NULL) && (guid2 != NULL)) {
122 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
127 #if defined(ENABLE_LOGGING)
128 static char* guid_to_string(const GUID* guid)
130 static char guid_string[MAX_GUID_STRING_LENGTH];
132 if (guid == NULL) return NULL;
133 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
134 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
135 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
136 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
142 * Converts a windows error to human readable string
143 * uses retval as errorcode, or, if 0, use GetLastError()
145 #if defined(ENABLE_LOGGING)
146 static char *windows_error_str(uint32_t retval)
148 static char err_string[ERR_BUFFER_SIZE];
152 uint32_t error_code, format_error;
154 error_code = retval?retval:GetLastError();
156 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%u] ", error_code);
158 // Translate codes returned by SetupAPI. The ones we are dealing with are either
159 // in 0x0000xxxx or 0xE000xxxx and can be distinguished from standard error codes.
160 // See http://msdn.microsoft.com/en-us/library/windows/hardware/ff545011.aspx
161 switch (error_code & 0xE0000000) {
163 error_code = HRESULT_FROM_WIN32(error_code); // Still leaves ERROR_SUCCESS unmodified
166 error_code = 0x80000000 | (FACILITY_SETUPAPI << 16) | (error_code & 0x0000FFFF);
172 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
173 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
174 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
176 format_error = GetLastError();
178 safe_sprintf(err_string, ERR_BUFFER_SIZE,
179 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
181 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
183 // Remove CR/LF terminators
184 for (i=safe_strlen(err_string)-1; (i>=0) && ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
193 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
194 * Return an allocated sanitized string or NULL on error.
196 static char* sanitize_path(const char* path)
198 const char root_prefix[] = "\\\\.\\";
199 size_t j, size, root_size;
200 char* ret_path = NULL;
206 size = safe_strlen(path)+1;
207 root_size = sizeof(root_prefix)-1;
209 // Microsoft indiscriminately uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
210 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
211 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
212 add_root = root_size;
216 if ((ret_path = (char*) calloc(size, 1)) == NULL)
219 safe_strcpy(&ret_path[add_root], size-add_root, path);
221 // Ensure consistency with root prefix
222 for (j=0; j<root_size; j++)
223 ret_path[j] = root_prefix[j];
225 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
226 for(j=root_size; j<size; j++) {
227 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
228 if (ret_path[j] == '\\')
236 * Cfgmgr32, OLE32 and SetupAPI DLL functions
238 static int init_dlls(void)
240 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
241 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
242 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
243 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
244 // Prefixed to avoid conflict with header files
245 DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
246 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
247 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
248 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
249 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
250 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
251 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
252 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
253 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
254 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
255 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
256 return LIBUSB_SUCCESS;
260 * enumerate interfaces for the whole USB class
263 * dev_info: a pointer to a dev_info list
264 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
265 * usb_class: the generic USB class for which to retrieve interface details
266 * index: zero based index of the interface in the device info list
268 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
269 * structure returned and call this function repeatedly using the same guid (with an
270 * incremented index starting at zero) until all interfaces have been returned.
272 static bool get_devinfo_data(struct libusb_context *ctx,
273 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char* usb_class, unsigned _index)
276 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
277 if (*dev_info == INVALID_HANDLE_VALUE) {
282 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
283 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
284 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
285 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
286 _index, windows_error_str(0));
288 pSetupDiDestroyDeviceInfoList(*dev_info);
289 *dev_info = INVALID_HANDLE_VALUE;
296 * enumerate interfaces for a specific GUID
299 * dev_info: a pointer to a dev_info list
300 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
301 * guid: the GUID for which to retrieve interface details
302 * index: zero based index of the interface in the device info list
304 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
305 * structure returned and call this function repeatedly using the same guid (with an
306 * incremented index starting at zero) until all interfaces have been returned.
308 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
309 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
311 SP_DEVICE_INTERFACE_DATA dev_interface_data;
312 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
316 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
319 if (dev_info_data != NULL) {
320 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
321 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
322 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
323 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
324 _index, windows_error_str(0));
326 pSetupDiDestroyDeviceInfoList(*dev_info);
327 *dev_info = INVALID_HANDLE_VALUE;
332 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
333 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
334 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
335 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
336 _index, windows_error_str(0));
338 pSetupDiDestroyDeviceInfoList(*dev_info);
339 *dev_info = INVALID_HANDLE_VALUE;
343 // Read interface data (dummy + actual) to access the device path
344 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
345 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
346 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
347 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
348 _index, windows_error_str(0));
352 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
356 if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
357 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
361 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
362 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
363 dev_interface_details, size, &size, NULL)) {
364 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
365 _index, windows_error_str(0));
368 return dev_interface_details;
371 pSetupDiDestroyDeviceInfoList(*dev_info);
372 *dev_info = INVALID_HANDLE_VALUE;
376 /* For libusb0 filter */
377 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
378 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index, char* filter_path){
379 SP_DEVICE_INTERFACE_DATA dev_interface_data;
380 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
383 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
385 if (dev_info_data != NULL) {
386 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
387 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
388 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
389 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
390 _index, windows_error_str(0));
392 pSetupDiDestroyDeviceInfoList(*dev_info);
393 *dev_info = INVALID_HANDLE_VALUE;
397 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
398 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
399 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
400 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
401 _index, windows_error_str(0));
403 pSetupDiDestroyDeviceInfoList(*dev_info);
404 *dev_info = INVALID_HANDLE_VALUE;
407 // Read interface data (dummy + actual) to access the device path
408 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
409 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
410 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
411 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
412 _index, windows_error_str(0));
416 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
419 if ((dev_interface_details = malloc(size)) == NULL) {
420 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
423 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
424 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
425 dev_interface_details, size, &size, NULL)) {
426 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
427 _index, windows_error_str(0));
429 // [trobinso] lookup the libusb0 symbolic index.
430 if (dev_interface_details) {
431 HKEY hkey_device_interface=pSetupDiOpenDeviceInterfaceRegKey(*dev_info,&dev_interface_data,0,KEY_READ);
432 if (hkey_device_interface != INVALID_HANDLE_VALUE) {
433 DWORD libusb0_symboliclink_index=0;
434 DWORD value_length=sizeof(DWORD);
437 status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
438 (LPBYTE) &libusb0_symboliclink_index, &value_length);
439 if (status == ERROR_SUCCESS) {
440 if (libusb0_symboliclink_index < 256) {
441 // libusb0.sys is connected to this device instance.
442 // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
443 safe_sprintf(filter_path, sizeof("\\\\.\\libusb0-0000"), "\\\\.\\libusb0-%04d", libusb0_symboliclink_index);
444 usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
446 // libusb0.sys was connected to this device instance at one time; but not anymore.
449 pRegCloseKey(hkey_device_interface);
452 return dev_interface_details;
454 pSetupDiDestroyDeviceInfoList(*dev_info);
455 *dev_info = INVALID_HANDLE_VALUE;
458 /* Hash table functions - modified From glibc 2.3.2:
459 [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
460 [Knuth] The Art of Computer Programming, part 3 (6.4) */
461 typedef struct htab_entry {
465 htab_entry* htab_table = NULL;
466 usbi_mutex_t htab_write_mutex = NULL;
467 unsigned long htab_size, htab_filled;
469 /* For the used double hash method the table size has to be a prime. To
470 correct the user given table size we need a prime test. This trivial
471 algorithm is adequate because the code is called only during init and
472 the number is likely to be small */
473 static int isprime(unsigned long number)
475 // no even number will be passed
476 unsigned int divider = 3;
478 while((divider * divider < number) && (number % divider != 0))
481 return (number % divider != 0);
484 /* Before using the hash table we must allocate memory for it.
485 We allocate one element more as the found prime number says.
486 This is done for more effective indexing as explained in the
487 comment for the hash function. */
488 static int htab_create(struct libusb_context *ctx, unsigned long nel)
490 if (htab_table != NULL) {
491 usbi_err(ctx, "hash table already allocated");
495 usbi_mutex_init(&htab_write_mutex, NULL);
497 // Change nel to the first prime number not smaller as nel.
503 usbi_dbg("using %d entries hash table", nel);
506 // allocate memory and zero out.
507 htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
508 if (htab_table == NULL) {
509 usbi_err(ctx, "could not allocate space for hash table");
516 /* After using the hash table it has to be destroyed. */
517 static void htab_destroy(void)
520 if (htab_table == NULL) {
524 for (i=0; i<htab_size; i++) {
525 if (htab_table[i].used) {
526 safe_free(htab_table[i].str);
529 usbi_mutex_destroy(&htab_write_mutex);
530 safe_free(htab_table);
533 /* This is the search function. It uses double hashing with open addressing.
534 We use an trick to speed up the lookup. The table is created with one
535 more element available. This enables us to use the index zero special.
536 This index will never be used because we store the first hash index in
537 the field used where zero means not used. Every other value means used.
538 The used field can be used as a first fast comparison for equality of
539 the stored and the parameter value. This helps to prevent unnecessary
540 expensive calls of strcmp. */
541 static unsigned long htab_hash(char* str)
543 unsigned long hval, hval2;
545 unsigned long r = 5381;
552 // Compute main hash value (algorithm suggested by Nokia)
553 while ((c = *sz++) != 0)
554 r = ((r << 5) + r) + c;
558 // compute table hash: simply take the modulus
559 hval = r % htab_size;
563 // Try the first index
566 if (htab_table[idx].used) {
567 if ( (htab_table[idx].used == hval)
568 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
572 usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
574 // Second hash function, as suggested in [Knuth]
575 hval2 = 1 + hval % (htab_size - 2);
578 // Because size is prime this guarantees to step through all available indexes
580 idx = htab_size + idx - hval2;
585 // If we visited all entries leave the loop unsuccessfully
590 // If entry is found use it.
591 if ( (htab_table[idx].used == hval)
592 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
596 while (htab_table[idx].used);
599 // Not found => New entry
601 // If the table is full return an error
602 if (htab_filled >= htab_size) {
603 usbi_err(NULL, "hash table is full (%d entries)", htab_size);
607 // Concurrent threads might be storing the same entry at the same time
608 // (eg. "simultaneous" enums from different threads) => use a mutex
609 usbi_mutex_lock(&htab_write_mutex);
610 // Just free any previously allocated string (which should be the same as
611 // new one). The possibility of concurrent threads storing a collision
612 // string (same hash, different string) at the same time is extremely low
613 safe_free(htab_table[idx].str);
614 htab_table[idx].used = hval;
615 htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
616 if (htab_table[idx].str == NULL) {
617 usbi_err(NULL, "could not duplicate string for hash table");
618 usbi_mutex_unlock(&htab_write_mutex);
621 memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
623 usbi_mutex_unlock(&htab_write_mutex);
629 * Returns the session ID of a device's nth level ancestor
630 * If there's no device at the nth level, return 0
632 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
634 DWORD parent_devinst;
635 unsigned long session_id = 0;
636 char* sanitized_path = NULL;
637 char path[MAX_PATH_LENGTH];
640 if (level < 1) return 0;
641 for (i = 0; i<level; i++) {
642 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
645 devinst = parent_devinst;
647 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
650 // TODO: (post hotplug): try without sanitizing
651 sanitized_path = sanitize_path(path);
652 if (sanitized_path == NULL) {
655 session_id = htab_hash(sanitized_path);
656 safe_free(sanitized_path);
661 * Determine which interface the given endpoint address belongs to
663 static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep)
665 const struct libusb_interface *intf;
666 const struct libusb_interface_descriptor *intf_desc;
669 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
670 intf = &conf_desc->interface[i];
671 for (j = 0; j < intf->num_altsetting; j++) {
672 intf_desc = &intf->altsetting[j];
673 for (k = 0; k < intf_desc->bNumEndpoints; k++) {
674 if (intf_desc->endpoint[k].bEndpointAddress == ep) {
675 usbi_dbg("found endpoint %02X on interface %d", intf_desc->bInterfaceNumber);
676 return intf_desc->bInterfaceNumber;
682 usbi_dbg("endpoint %02X not found on any interface", ep);
683 return LIBUSB_ERROR_NOT_FOUND;
687 * Populate the endpoints addresses of the device_priv interface helper structs
689 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
692 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
693 struct libusb_config_descriptor *conf_desc;
694 const struct libusb_interface_descriptor *if_desc;
695 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
697 r = libusb_get_config_descriptor(dev_handle->dev, (uint8_t)(priv->active_config-1), &conf_desc);
698 if (r != LIBUSB_SUCCESS) {
699 usbi_warn(ctx, "could not read config descriptor: error %d", r);
703 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
704 safe_free(priv->usb_interface[iface].endpoint);
706 if (if_desc->bNumEndpoints == 0) {
707 usbi_dbg("no endpoints found for interface %d", iface);
708 return LIBUSB_SUCCESS;
711 priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
712 if (priv->usb_interface[iface].endpoint == NULL) {
713 return LIBUSB_ERROR_NO_MEM;
716 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
717 for (i=0; i<if_desc->bNumEndpoints; i++) {
718 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
719 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
721 libusb_free_config_descriptor(conf_desc);
723 // Extra init may be required to configure endpoints
724 return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
727 // Lookup for a match in the list of API driver names
728 // return -1 if not found, driver match number otherwise
729 static int get_sub_api(char* driver, int api){
731 const char sep_str[2] = {LIST_SEPARATOR, 0};
733 size_t len = safe_strlen(driver);
735 if (len == 0) return SUB_API_NOTSET;
736 tmp_str = (char*) calloc(len+1, 1);
737 if (tmp_str == NULL) return SUB_API_NOTSET;
738 memcpy(tmp_str, driver, len+1);
739 tok = strtok(tmp_str, sep_str);
740 while (tok != NULL) {
741 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
742 if (safe_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
747 tok = strtok(NULL, sep_str);
750 return SUB_API_NOTSET;
754 * auto-claiming and auto-release helper functions
756 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
758 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
759 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
760 transfer->dev_handle);
761 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
762 int current_interface = *interface_number;
763 int r = LIBUSB_SUCCESS;
766 case USB_API_WINUSBX:
770 return LIBUSB_ERROR_INVALID_PARAM;
773 usbi_mutex_lock(&autoclaim_lock);
774 if (current_interface < 0) // No serviceable interface was found
776 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
777 // Must claim an interface of the same API type
778 if ( (priv->usb_interface[current_interface].apib->id == api_type)
779 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
780 usbi_dbg("auto-claimed interface %d for control request", current_interface);
781 if (handle_priv->autoclaim_count[current_interface] != 0) {
782 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
784 handle_priv->autoclaim_count[current_interface]++;
788 if (current_interface == USB_MAXINTERFACES) {
789 usbi_err(ctx, "could not auto-claim any interface");
790 r = LIBUSB_ERROR_NOT_FOUND;
793 // If we have a valid interface that was autoclaimed, we must increment
794 // its autoclaim count so that we can prevent an early release.
795 if (handle_priv->autoclaim_count[current_interface] != 0) {
796 handle_priv->autoclaim_count[current_interface]++;
799 usbi_mutex_unlock(&autoclaim_lock);
801 *interface_number = current_interface;
806 static void auto_release(struct usbi_transfer *itransfer)
808 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
809 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
810 libusb_device_handle *dev_handle = transfer->dev_handle;
811 struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
814 usbi_mutex_lock(&autoclaim_lock);
815 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
816 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
817 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
818 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
819 if (r == LIBUSB_SUCCESS) {
820 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
822 usbi_dbg("failed to auto-release interface %d (%s)",
823 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
827 usbi_mutex_unlock(&autoclaim_lock);
830 /* Windows version dtection */
831 static BOOL is_x64(void)
834 // Detect if we're running a 32 or 64 bit system
835 if (sizeof(uintptr_t) < 8) {
836 DLL_LOAD_PREFIXED(Kernel32.dll, p, IsWow64Process, FALSE);
837 if (pIsWow64Process != NULL) {
838 (*pIsWow64Process)(GetCurrentProcess(), &ret);
846 static void get_windows_version(void)
848 OSVERSIONINFOEXA vi, vi2;
850 const char* w64 = "32 bit";
853 unsigned major, minor;
854 ULONGLONG major_equal, minor_equal;
857 memset(&vi, 0, sizeof(vi));
858 vi.dwOSVersionInfoSize = sizeof(vi);
859 if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
860 memset(&vi, 0, sizeof(vi));
861 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
862 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
866 if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
868 if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) {
869 // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
870 // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
872 major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
873 for (major = vi.dwMajorVersion; major <= 9; major++) {
874 memset(&vi2, 0, sizeof(vi2));
875 vi2.dwOSVersionInfoSize = sizeof(vi2); vi2.dwMajorVersion = major;
876 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
878 if (vi.dwMajorVersion < major) {
879 vi.dwMajorVersion = major; vi.dwMinorVersion = 0;
882 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
883 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
884 memset(&vi2, 0, sizeof(vi2)); vi2.dwOSVersionInfoSize = sizeof(vi2);
885 vi2.dwMinorVersion = minor;
886 if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
888 vi.dwMinorVersion = minor;
896 if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) {
897 ws = (vi.wProductType <= VER_NT_WORKSTATION);
898 windows_version = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
899 switch (windows_version) {
900 case 0x50: w = "2000";
904 case 0x52: w = ("2003");
906 case 0x60: w = (ws?"Vista":"2008");
908 case 0x61: w = (ws?"7":"2008_R2");
910 case 0x62: w = (ws?"8":"2012");
912 case 0x63: w = (ws?"8.1":"2012_R2");
914 case 0x64: w = (ws?"10":"2015");
917 if (windows_version < 0x50)
918 windows_version = WINDOWS_UNSUPPORTED;
929 vptr = &windows_version_str[sizeof("Windows ") - 1];
930 vlen = sizeof(windows_version_str) - sizeof("Windows ") - 1;
932 safe_sprintf(vptr, vlen, "%s %u.%u %s", (vi.dwPlatformId==VER_PLATFORM_WIN32_NT?"NT":"??"),
933 (unsigned)vi.dwMajorVersion, (unsigned)vi.dwMinorVersion, w64);
934 else if (vi.wServicePackMinor)
935 safe_sprintf(vptr, vlen, "%s SP%u.%u %s", w, vi.wServicePackMajor, vi.wServicePackMinor, w64);
936 else if (vi.wServicePackMajor)
937 safe_sprintf(vptr, vlen, "%s SP%u %s", w, vi.wServicePackMajor, w64);
939 safe_sprintf(vptr, vlen, "%s %s", w, w64);
943 * init: libusb backend init function
945 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
946 * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed.
947 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
949 static int windows_init(struct libusb_context *ctx)
951 int i, r = LIBUSB_ERROR_OTHER;
952 DWORD_PTR affinity, dummy;
955 LARGE_INTEGER li_frequency;
956 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
958 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
959 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
960 if (semaphore == NULL) {
961 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
962 return LIBUSB_ERROR_NO_MEM;
965 // A successful wait brings our semaphore count to 0 (unsignaled)
966 // => any concurent wait stalls until the semaphore's release
967 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
968 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
969 CloseHandle(semaphore);
970 return LIBUSB_ERROR_NO_MEM;
973 // NB: concurrent usage supposes that init calls are equally balanced with
974 // exit calls. If init is called more than exit, we will not exit properly
975 if ( ++concurrent_usage == 0 ) { // First init?
976 get_windows_version();
977 usbi_dbg(windows_version_str);
978 if (windows_version == WINDOWS_UNSUPPORTED) {
979 usbi_err(ctx, "This version of Windows is NOT supported");
980 r = LIBUSB_ERROR_NOT_SUPPORTED;
984 // We need a lock for proper auto-release
985 usbi_mutex_init(&autoclaim_lock, NULL);
987 // Initialize pollable file descriptors
991 if (init_dlls() != LIBUSB_SUCCESS) {
992 usbi_err(ctx, "could not resolve DLL functions");
996 // Initialize the low level APIs (we don't care about errors at this stage)
997 for (i=0; i<USB_API_MAX; i++) {
998 usb_api_backend[i].init(SUB_API_NOTSET, ctx);
1001 if (QueryPerformanceFrequency(&li_frequency)) {
1002 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
1003 // to picoseconds to compute the tv_nsecs part in clock_gettime
1004 hires_frequency = li_frequency.QuadPart;
1005 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
1006 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
1008 // Because QueryPerformanceCounter might report different values when
1009 // running on different cores, we create a separate thread for the timer
1010 // calls, which we glue to the first available core always to prevent timing discrepancies.
1011 if (!GetProcessAffinityMask(GetCurrentProcess(), &affinity, &dummy) || (affinity == 0)) {
1012 usbi_err(ctx, "could not get process affinity: %s", windows_error_str(0));
1015 // The process affinity mask is a bitmask where each set bit represents a core on
1016 // which this process is allowed to run, so we find the first set bit
1017 for (i = 0; !(affinity & (1 << i)); i++);
1018 affinity = (1 << i);
1020 usbi_dbg("timer thread will run on core #%d", i);
1022 r = LIBUSB_ERROR_NO_MEM;
1023 event = CreateEvent(NULL, FALSE, FALSE, NULL);
1024 if (event == NULL) {
1025 usbi_err(ctx, "could not create event: %s", windows_error_str(0));
1028 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, (void *)event,
1029 0, (unsigned int *)&timer_thread_id);
1030 if (timer_thread == NULL) {
1031 usbi_err(ctx, "unable to create timer thread - aborting");
1034 if (!SetThreadAffinityMask(timer_thread, affinity)) {
1035 usbi_warn(ctx, "unable to set timer thread affinity, timer discrepancies may arise");
1038 // Wait for timer thread to init before continuing.
1039 if (WaitForSingleObject(event, INFINITE) != WAIT_OBJECT_0) {
1040 usbi_err(ctx, "failed to wait for timer thread to become ready - aborting");
1045 usbi_dbg("no hires timer available on this platform");
1046 hires_frequency = 0;
1047 hires_ticks_to_ps = UINT64_C(0);
1050 // Create a hash table to store session ids. Second parameter is better if prime
1051 htab_create(ctx, HTAB_SIZE);
1053 // At this stage, either we went through full init successfully, or didn't need to
1056 init_exit: // Holds semaphore here.
1057 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
1059 // actually the signal to quit the thread.
1060 if (!PostThreadMessage(timer_thread_id, WM_TIMER_EXIT, 0, 0) ||
1061 (WaitForSingleObject(timer_thread, INFINITE) != WAIT_OBJECT_0)) {
1062 usbi_warn(ctx, "could not wait for timer thread to quit");
1063 TerminateThread(timer_thread, 1);
1064 // shouldn't happen, but we're destroying
1065 // all objects it might have held anyway.
1067 CloseHandle(timer_thread);
1068 timer_thread = NULL;
1069 timer_thread_id = 0;
1074 if (r != LIBUSB_SUCCESS)
1075 --concurrent_usage; // Not expected to call libusb_exit if we failed.
1079 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1080 CloseHandle(semaphore);
1085 * HCD (root) hubs need to have their device descriptor manually populated
1087 * Note that, like Microsoft does in the device manager, we populate the
1088 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
1090 static int force_hcd_device_descriptor(struct libusb_device *dev)
1092 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
1093 struct libusb_context *ctx = DEVICE_CTX(dev);
1096 dev->num_configurations = 1;
1097 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
1098 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
1099 priv->dev_descriptor.bNumConfigurations = 1;
1100 priv->active_config = 1;
1102 if (priv->parent_dev == NULL) {
1103 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
1104 return LIBUSB_ERROR_NO_DEVICE;
1106 parent_priv = _device_priv(priv->parent_dev);
1107 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
1108 priv->dev_descriptor.idVendor = (uint16_t)vid;
1109 priv->dev_descriptor.idProduct = (uint16_t)pid;
1111 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
1112 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
1113 priv->dev_descriptor.idProduct = 1;
1115 return LIBUSB_SUCCESS;
1119 * fetch and cache all the config descriptors through I/O
1121 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
1123 DWORD size, ret_size;
1124 struct libusb_context *ctx = DEVICE_CTX(dev);
1125 struct windows_device_priv *priv = _device_priv(dev);
1129 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
1130 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
1131 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
1133 if (dev->num_configurations == 0)
1134 return LIBUSB_ERROR_INVALID_PARAM;
1136 priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(unsigned char*));
1137 if (priv->config_descriptor == NULL)
1138 return LIBUSB_ERROR_NO_MEM;
1139 for (i=0; i<dev->num_configurations; i++)
1140 priv->config_descriptor[i] = NULL;
1142 for (i=0, r=LIBUSB_SUCCESS; ; i++)
1144 // safe loop: release all dynamic resources
1145 safe_free(cd_buf_actual);
1147 // safe loop: end of loop condition
1148 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
1151 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
1152 memset(&cd_buf_short, 0, size);
1154 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
1155 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
1156 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
1157 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
1158 cd_buf_short.req.SetupPacket.wIndex = 0;
1159 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
1161 // Dummy call to get the required data size. Initial failures are reported as info rather
1162 // than error as they can occur for non-penalizing situations, such as with some hubs.
1163 // coverity[tainted_data_argument]
1164 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
1165 &cd_buf_short, size, &ret_size, NULL)) {
1166 usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
1167 LOOP_BREAK(LIBUSB_ERROR_IO);
1170 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
1171 usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
1172 LOOP_BREAK(LIBUSB_ERROR_IO);
1175 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
1176 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
1177 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
1178 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1180 memset(cd_buf_actual, 0, size);
1183 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
1184 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
1185 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
1186 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
1187 cd_buf_actual->SetupPacket.wIndex = 0;
1188 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
1190 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
1191 cd_buf_actual, size, &ret_size, NULL)) {
1192 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
1193 LOOP_BREAK(LIBUSB_ERROR_IO);
1196 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
1198 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
1199 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
1200 LOOP_BREAK(LIBUSB_ERROR_IO);
1203 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
1204 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
1205 LOOP_BREAK(LIBUSB_ERROR_IO);
1208 usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
1209 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
1211 // Cache the descriptor
1212 priv->config_descriptor[i] = (unsigned char*) malloc(cd_data->wTotalLength);
1213 if (priv->config_descriptor[i] == NULL)
1214 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1215 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
1217 return LIBUSB_SUCCESS;
1221 * Populate a libusb device structure
1223 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
1224 uint8_t port_number, char* device_id, DWORD devinst)
1228 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
1229 USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
1230 struct windows_device_priv *priv, *parent_priv;
1231 struct libusb_context *ctx;
1232 struct libusb_device* tmp_dev;
1233 unsigned long tmp_id;
1236 if ((dev == NULL) || (parent_dev == NULL)) {
1237 return LIBUSB_ERROR_NOT_FOUND;
1239 ctx = DEVICE_CTX(dev);
1240 priv = _device_priv(dev);
1241 parent_priv = _device_priv(parent_dev);
1242 if (parent_priv->apib->id != USB_API_HUB) {
1243 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1244 return LIBUSB_ERROR_NOT_FOUND;
1247 // It is possible for the parent hub not to have been initialized yet
1248 // If that's the case, lookup the ancestors to set the bus number
1249 if (parent_dev->bus_number == 0) {
1251 tmp_id = get_ancestor_session_id(devinst, i);
1252 if (tmp_id == 0) break;
1253 tmp_dev = usbi_get_device_by_session_id(ctx, tmp_id);
1254 if (tmp_dev == NULL) continue;
1255 if (tmp_dev->bus_number != 0) {
1256 usbi_dbg("got bus number from ancestor #%d", i);
1257 parent_dev->bus_number = tmp_dev->bus_number;
1258 libusb_unref_device(tmp_dev);
1261 libusb_unref_device(tmp_dev);
1264 if (parent_dev->bus_number == 0) {
1265 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1266 return LIBUSB_ERROR_NOT_FOUND;
1268 dev->bus_number = parent_dev->bus_number;
1269 priv->port = port_number;
1270 dev->port_number = port_number;
1271 priv->depth = parent_priv->depth + 1;
1272 priv->parent_dev = parent_dev;
1273 dev->parent_dev = parent_dev;
1275 // If the device address is already set, we can stop here
1276 if (dev->device_address != 0) {
1277 return LIBUSB_SUCCESS;
1279 memset(&conn_info, 0, sizeof(conn_info));
1280 if (priv->depth != 0) { // Not a HCD hub
1281 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1282 FILE_FLAG_OVERLAPPED, NULL);
1283 if (handle == INVALID_HANDLE_VALUE) {
1284 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1285 return LIBUSB_ERROR_ACCESS;
1287 size = sizeof(conn_info);
1288 conn_info.ConnectionIndex = (ULONG)port_number;
1289 // coverity[tainted_data_argument]
1290 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1291 &conn_info, size, &size, NULL)) {
1292 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1293 device_id, windows_error_str(0));
1294 safe_closehandle(handle);
1295 return LIBUSB_ERROR_NO_DEVICE;
1297 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1298 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1299 safe_closehandle(handle);
1300 return LIBUSB_ERROR_NO_DEVICE;
1302 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1303 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1304 priv->active_config = conn_info.CurrentConfigurationValue;
1305 usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
1306 // If we can't read the config descriptors, just set the number of confs to zero
1307 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1308 dev->num_configurations = 0;
1309 priv->dev_descriptor.bNumConfigurations = 0;
1312 // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
1313 if (windows_version >= WINDOWS_8) {
1314 memset(&conn_info_v2, 0, sizeof(conn_info_v2));
1315 size = sizeof(conn_info_v2);
1316 conn_info_v2.ConnectionIndex = (ULONG)port_number;
1317 conn_info_v2.Length = size;
1318 conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
1319 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
1320 &conn_info_v2, size, &conn_info_v2, size, &size, NULL)) {
1321 usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
1322 device_id, windows_error_str(0));
1323 } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
1324 conn_info.Speed = 3;
1328 safe_closehandle(handle);
1330 if (conn_info.DeviceAddress > UINT8_MAX) {
1331 usbi_err(ctx, "program assertion failed: device address overflow");
1333 dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
1334 if (dev->device_address == 1) {
1335 usbi_err(ctx, "program assertion failed: device address collision with root hub");
1337 switch (conn_info.Speed) {
1338 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1339 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1340 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1341 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1343 usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1347 dev->device_address = 1; // root hubs are set to use device number 1
1348 force_hcd_device_descriptor(dev);
1351 usbi_sanitize_device(dev);
1353 usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1354 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1356 return LIBUSB_SUCCESS;
1359 // Returns the api type, or 0 if not found/unsupported
1360 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
1361 SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
1363 // Precedence for filter drivers vs driver is in the order of this array
1364 struct driver_lookup lookup[3] = {
1365 {"\0\0", SPDRP_SERVICE, "driver"},
1366 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1367 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1369 DWORD size, reg_type;
1373 *api = USB_API_UNSUPPORTED;
1374 *sub_api = SUB_API_NOTSET;
1375 // Check the service & filter names to know the API we should use
1376 for (k=0; k<3; k++) {
1377 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1378 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1379 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1380 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1381 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1382 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1384 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1385 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1386 // (currently ';'), so even if an unsuported one does, it's not an issue
1387 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1388 if (lookup[k].list[l] == 0) {
1389 lookup[k].list[l] = LIST_SEPARATOR;
1392 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1394 if (GetLastError() != ERROR_INVALID_DATA) {
1395 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1397 lookup[k].list[0] = 0;
1401 for (i=1; i<USB_API_MAX; i++) {
1402 for (k=0; k<3; k++) {
1403 j = get_sub_api(lookup[k].list, i);
1405 usbi_dbg("matched %s name against %s",
1406 lookup[k].designation, (i!=USB_API_WINUSBX)?usb_api_backend[i].designation:sub_api_name[j]);
1415 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1416 char* dev_interface_path, char* device_id, int api, int sub_api)
1419 struct windows_device_priv *priv = _device_priv(dev);
1420 int interface_number;
1422 if (priv->apib->id != USB_API_COMPOSITE) {
1423 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1424 return LIBUSB_ERROR_NO_DEVICE;
1427 // Because MI_## are not necessarily in sequential order (some composite
1428 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1429 // interface number from the path's MI value
1430 interface_number = 0;
1431 for (i=0; device_id[i] != 0; ) {
1432 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1433 && (device_id[i++] == '_') ) {
1434 interface_number = (device_id[i++] - '0')*10;
1435 interface_number += device_id[i] - '0';
1440 if (device_id[i] == 0) {
1441 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1442 device_id, interface_number);
1445 if (priv->usb_interface[interface_number].path != NULL) {
1446 if (api == USB_API_HID) {
1447 // HID devices can have multiple collections (COL##) for each MI_## interface
1448 usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1449 interface_number, device_id);
1450 return LIBUSB_ERROR_ACCESS;
1452 // In other cases, just use the latest data
1453 safe_free(priv->usb_interface[interface_number].path);
1456 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1457 priv->usb_interface[interface_number].path = dev_interface_path;
1458 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1459 priv->usb_interface[interface_number].sub_api = sub_api;
1460 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1461 priv->hid = (struct hid_device_priv*) calloc(1, sizeof(struct hid_device_priv));
1462 if (priv->hid == NULL)
1463 return LIBUSB_ERROR_NO_MEM;
1466 return LIBUSB_SUCCESS;
1469 static int set_hid_interface(struct libusb_context* ctx, struct libusb_device* dev,
1470 char* dev_interface_path)
1473 struct windows_device_priv *priv = _device_priv(dev);
1475 if (priv->hid == NULL) {
1476 usbi_err(ctx, "program assertion failed: parent is not HID");
1477 return LIBUSB_ERROR_NO_DEVICE;
1479 if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1480 usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
1481 return LIBUSB_ERROR_NO_DEVICE;
1483 for (i=0; i<priv->hid->nb_interfaces; i++) {
1484 if (safe_strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1485 usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
1486 return LIBUSB_SUCCESS;
1490 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1491 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1492 usbi_dbg("interface[%d] = %s", priv->hid->nb_interfaces, dev_interface_path);
1493 priv->hid->nb_interfaces++;
1494 return LIBUSB_SUCCESS;
1498 * get_device_list: libusb backend device enumeration function
1500 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1502 struct discovered_devs *discdevs;
1503 HDEVINFO dev_info = { 0 };
1504 const char* usb_class[] = {"USB", "NUSB3", "IUSB3"};
1505 SP_DEVINFO_DATA dev_info_data = { 0 };
1506 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1508 #define MAX_ENUM_GUIDS 64
1509 const GUID* guid[MAX_ENUM_GUIDS];
1515 int r = LIBUSB_SUCCESS;
1517 size_t class_index = 0;
1518 unsigned int nb_guids, pass, i, j, ancestor;
1519 char path[MAX_PATH_LENGTH];
1520 char strbuf[MAX_PATH_LENGTH];
1521 struct libusb_device *dev, *parent_dev;
1522 struct windows_device_priv *priv, *parent_priv;
1523 char* dev_interface_path = NULL;
1524 char* dev_id_path = NULL;
1525 unsigned long session_id;
1526 DWORD size, reg_type, port_nr, install_state;
1528 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1531 // Keep a list of newly allocated devs to unref
1532 libusb_device** unref_list;
1533 unsigned int unref_size = 64;
1534 unsigned int unref_cur = 0;
1536 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1537 // PASS 2 : (re)enumerate HUBS
1538 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1539 // and list additional USB device interface GUIDs to explore
1540 // PASS 4 : (re)enumerate master USB devices that have a device interface
1541 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1542 // set the device interfaces.
1544 // Init the GUID table
1545 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1546 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1547 guid[GEN_PASS] = NULL;
1548 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1549 HidD_GetHidGuid(&hid_guid);
1550 guid[HID_PASS] = &hid_guid;
1551 nb_guids = HID_PASS+1;
1553 unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
1554 if (unref_list == NULL) {
1555 return LIBUSB_ERROR_NO_MEM;
1558 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1559 //#define ENUM_DEBUG
1561 const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
1562 usbi_dbg("#### PROCESSING %ss %s", passname[(pass<=HID_PASS)?pass:HID_PASS+1],
1563 (pass!=GEN_PASS)?guid_to_string(guid[pass]):"");
1565 for (i = 0; ; i++) {
1566 // safe loop: free up any (unprotected) dynamic resource
1567 // NB: this is always executed before breaking the loop
1568 safe_free(dev_interface_details);
1569 safe_free(dev_interface_path);
1570 safe_free(dev_id_path);
1571 priv = parent_priv = NULL;
1572 dev = parent_dev = NULL;
1574 // Safe loop: end of loop conditions
1575 if (r != LIBUSB_SUCCESS) {
1578 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1579 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1582 if (pass != GEN_PASS) {
1583 // Except for GEN, all passes deal with device interfaces
1584 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1585 if (dev_interface_details == NULL) {
1588 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1589 if (dev_interface_path == NULL) {
1590 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1595 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1596 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1597 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1598 for (; class_index < ARRAYSIZE(usb_class); class_index++) {
1599 if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
1603 if (class_index >= ARRAYSIZE(usb_class))
1607 // Read the Device ID path. This is what we'll use as UID
1608 // Note that if the device is plugged in a different port or hub, the Device ID changes
1609 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1610 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1611 dev_info_data.DevInst);
1614 dev_id_path = sanitize_path(path);
1615 if (dev_id_path == NULL) {
1616 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1617 dev_info_data.DevInst);
1621 usbi_dbg("PRO: %s", dev_id_path);
1624 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1626 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1627 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1628 ®_type, (BYTE*)&port_nr, 4, &size))
1630 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1631 dev_id_path, windows_error_str(0));
1636 // Set API to use or get additional data from generic pass
1637 api = USB_API_UNSUPPORTED;
1638 sub_api = SUB_API_NOTSET;
1643 // We use the GEN pass to detect driverless devices...
1644 size = sizeof(strbuf);
1645 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1646 ®_type, (BYTE*)strbuf, size, &size)) {
1647 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1648 usbi_info(ctx, "libusb will not be able to access it.");
1650 // ...and to add the additional device interface GUIDs
1651 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1652 if (key != INVALID_HANDLE_VALUE) {
1653 size = sizeof(guid_string_w);
1654 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1655 (BYTE*)guid_string_w, &size);
1657 if (s == ERROR_SUCCESS) {
1658 if (nb_guids >= MAX_ENUM_GUIDS) {
1659 // If this assert is ever reported, grow a GUID table dynamically
1660 usbi_err(ctx, "program assertion failed: too many GUIDs");
1661 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1663 if_guid = (GUID*) calloc(1, sizeof(GUID));
1664 pCLSIDFromString(guid_string_w, if_guid);
1665 guid[nb_guids++] = if_guid;
1666 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1674 // Get the API type (after checking that the driver installation is OK)
1675 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1676 ®_type, (BYTE*)&install_state, 4, &size))
1678 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1679 dev_id_path, windows_error_str(0));
1680 } else if (install_state != 0) {
1681 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1682 dev_id_path, install_state);
1685 get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
1689 // Find parent device (for the passes that need it)
1696 // Go through the ancestors until we see a face we recognize
1698 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1699 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1700 if (session_id == 0) {
1703 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1705 if (parent_dev == NULL) {
1706 usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1709 parent_priv = _device_priv(parent_dev);
1710 // virtual USB devices are also listed during GEN - don't process these yet
1711 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1712 libusb_unref_device(parent_dev);
1718 // Create new or match existing device, using the (hashed) device_id as session id
1719 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1720 // These are the passes that create "new" devices
1721 session_id = htab_hash(dev_id_path);
1722 dev = usbi_get_device_by_session_id(ctx, session_id);
1724 if (pass == DEV_PASS) {
1725 // This can occur if the OS only reports a newly plugged device after we started enum
1726 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1727 " - ignoring", dev_id_path);
1730 usbi_dbg("allocating new device for session [%X]", session_id);
1731 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1732 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1734 windows_device_priv_init(dev);
1736 usbi_dbg("found existing device for session [%X] (%d.%d)",
1737 session_id, dev->bus_number, dev->device_address);
1739 // Keep track of devices that need unref
1740 unref_list[unref_cur++] = dev;
1741 if (unref_cur >= unref_size) {
1743 unref_list = usbi_reallocf(unref_list, unref_size*sizeof(libusb_device*));
1744 if (unref_list == NULL) {
1745 usbi_err(ctx, "could not realloc list for unref - aborting.");
1746 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1749 priv = _device_priv(dev);
1755 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1756 dev->device_address = 0;
1757 dev->num_configurations = 0;
1758 priv->apib = &usb_api_backend[USB_API_HUB];
1759 priv->sub_api = SUB_API_NOTSET;
1760 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1761 priv->path = dev_interface_path; dev_interface_path = NULL;
1765 // If the device has already been setup, don't do it again
1766 if (priv->path != NULL)
1768 // Take care of API initialization
1769 priv->path = dev_interface_path; dev_interface_path = NULL;
1770 priv->apib = &usb_api_backend[api];
1771 priv->sub_api = sub_api;
1773 case USB_API_COMPOSITE:
1777 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1778 if (priv->hid == NULL) {
1779 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1781 priv->hid->nb_interfaces = 0;
1784 // For other devices, the first interface is the same as the device
1785 priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
1786 if (priv->usb_interface[0].path != NULL) {
1787 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1789 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1791 // The following is needed if we want API calls to work for both simple
1792 // and composite devices.
1793 for(j=0; j<USB_MAXINTERFACES; j++) {
1794 priv->usb_interface[j].apib = &usb_api_backend[api];
1800 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1801 if (r == LIBUSB_SUCCESS) {
1802 // Append device to the list of discovered devices
1803 discdevs = discovered_devs_append(*_discdevs, dev);
1805 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1807 *_discdevs = discdevs;
1808 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1809 // This can occur if the device was disconnected but Windows hasn't
1810 // refreshed its enumeration yet - in that case, we ignore the device
1814 default: // HID_PASS and later
1815 if (parent_priv->apib->id == USB_API_HID) {
1816 usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1817 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1818 if (r != LIBUSB_SUCCESS) LOOP_BREAK(r);
1819 dev_interface_path = NULL;
1820 } else if (parent_priv->apib->id == USB_API_COMPOSITE) {
1821 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1822 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api)) {
1823 case LIBUSB_SUCCESS:
1824 dev_interface_path = NULL;
1826 case LIBUSB_ERROR_ACCESS:
1827 // interface has already been set => make sure dev_interface_path is freed then
1834 libusb_unref_device(parent_dev);
1840 // Free any additional GUIDs
1841 for (pass = HID_PASS+1; pass < nb_guids; pass++) {
1842 safe_free(guid[pass]);
1845 // Unref newly allocated devs
1846 if (unref_list != NULL) {
1847 for (i=0; i<unref_cur; i++) {
1848 safe_unref_device(unref_list[i]);
1857 * exit: libusb backend deinitialization function
1859 static void windows_exit(void)
1863 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1865 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1866 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1867 if (semaphore == NULL) {
1871 // A successful wait brings our semaphore count to 0 (unsignaled)
1872 // => any concurent wait stalls until the semaphore release
1873 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1874 CloseHandle(semaphore);
1878 // Only works if exits and inits are balanced exactly
1879 if (--concurrent_usage < 0) { // Last exit
1880 for (i=0; i<USB_API_MAX; i++) {
1881 usb_api_backend[i].exit(SUB_API_NOTSET);
1886 // actually the signal to quit the thread.
1887 if (!PostThreadMessage(timer_thread_id, WM_TIMER_EXIT, 0, 0) ||
1888 (WaitForSingleObject(timer_thread, INFINITE) != WAIT_OBJECT_0)) {
1889 usbi_dbg("could not wait for timer thread to quit");
1890 TerminateThread(timer_thread, 1);
1892 CloseHandle(timer_thread);
1893 timer_thread = NULL;
1894 timer_thread_id = 0;
1899 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1900 CloseHandle(semaphore);
1903 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1905 struct windows_device_priv *priv = _device_priv(dev);
1907 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1910 return LIBUSB_SUCCESS;
1913 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1915 struct windows_device_priv *priv = _device_priv(dev);
1916 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1919 // config index is zero based
1920 if (config_index >= dev->num_configurations)
1921 return LIBUSB_ERROR_INVALID_PARAM;
1923 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1924 return LIBUSB_ERROR_NOT_FOUND;
1926 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1928 size = min(config_header->wTotalLength, len);
1929 memcpy(buffer, priv->config_descriptor[config_index], size);
1936 * return the cached copy of the active config descriptor
1938 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1940 struct windows_device_priv *priv = _device_priv(dev);
1942 if (priv->active_config == 0)
1943 return LIBUSB_ERROR_NOT_FOUND;
1945 // config index is zero based
1946 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1949 static int windows_open(struct libusb_device_handle *dev_handle)
1951 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1952 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1954 if (priv->apib == NULL) {
1955 usbi_err(ctx, "program assertion failed - device is not initialized");
1956 return LIBUSB_ERROR_NO_DEVICE;
1959 return priv->apib->open(SUB_API_NOTSET, dev_handle);
1962 static void windows_close(struct libusb_device_handle *dev_handle)
1964 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1966 priv->apib->close(SUB_API_NOTSET, dev_handle);
1969 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1971 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1973 if (priv->active_config == 0) {
1975 return LIBUSB_ERROR_NOT_FOUND;
1978 *config = priv->active_config;
1979 return LIBUSB_SUCCESS;
1983 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1984 * does not currently expose a service that allows higher-level drivers to set
1985 * the configuration."
1987 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1989 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1990 int r = LIBUSB_SUCCESS;
1992 if (config >= USB_MAXCONFIG)
1993 return LIBUSB_ERROR_INVALID_PARAM;
1995 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1996 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1997 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
2000 if (r == LIBUSB_SUCCESS) {
2001 priv->active_config = (uint8_t)config;
2006 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2008 int r = LIBUSB_SUCCESS;
2009 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2011 if (iface >= USB_MAXINTERFACES)
2012 return LIBUSB_ERROR_INVALID_PARAM;
2014 safe_free(priv->usb_interface[iface].endpoint);
2015 priv->usb_interface[iface].nb_endpoints= 0;
2017 r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
2019 if (r == LIBUSB_SUCCESS) {
2020 r = windows_assign_endpoints(dev_handle, iface, 0);
2026 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2028 int r = LIBUSB_SUCCESS;
2029 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2031 safe_free(priv->usb_interface[iface].endpoint);
2032 priv->usb_interface[iface].nb_endpoints= 0;
2034 r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
2036 if (r == LIBUSB_SUCCESS) {
2037 r = windows_assign_endpoints(dev_handle, iface, altsetting);
2043 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
2045 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2047 return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
2050 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2052 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2053 return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
2056 static int windows_reset_device(struct libusb_device_handle *dev_handle)
2058 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2059 return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
2062 // The 3 functions below are unlikely to ever get supported on Windows
2063 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
2065 return LIBUSB_ERROR_NOT_SUPPORTED;
2068 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
2070 return LIBUSB_ERROR_NOT_SUPPORTED;
2073 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
2075 return LIBUSB_ERROR_NOT_SUPPORTED;
2078 static void windows_destroy_device(struct libusb_device *dev)
2080 windows_device_priv_release(dev);
2083 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
2085 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2087 usbi_free_fd(&transfer_priv->pollable_fd);
2088 safe_free(transfer_priv->hid_buffer);
2089 // When auto claim is in use, attempt to release the auto-claimed interface
2090 auto_release(itransfer);
2093 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
2095 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2096 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2097 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2098 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2101 r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
2102 if (r != LIBUSB_SUCCESS) {
2106 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
2107 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
2109 return LIBUSB_SUCCESS;
2112 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2114 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2115 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2116 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2117 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2120 r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
2121 if (r != LIBUSB_SUCCESS) {
2125 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
2126 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
2128 return LIBUSB_SUCCESS;
2131 static int submit_control_transfer(struct usbi_transfer *itransfer)
2133 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2134 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2135 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2136 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2139 r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
2140 if (r != LIBUSB_SUCCESS) {
2144 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
2146 return LIBUSB_SUCCESS;
2150 static int windows_submit_transfer(struct usbi_transfer *itransfer)
2152 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2154 switch (transfer->type) {
2155 case LIBUSB_TRANSFER_TYPE_CONTROL:
2156 return submit_control_transfer(itransfer);
2157 case LIBUSB_TRANSFER_TYPE_BULK:
2158 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2159 if (IS_XFEROUT(transfer) &&
2160 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
2161 return LIBUSB_ERROR_NOT_SUPPORTED;
2162 return submit_bulk_transfer(itransfer);
2163 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2164 return submit_iso_transfer(itransfer);
2165 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2166 return LIBUSB_ERROR_NOT_SUPPORTED;
2168 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2169 return LIBUSB_ERROR_INVALID_PARAM;
2173 static int windows_abort_control(struct usbi_transfer *itransfer)
2175 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2176 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2178 return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
2181 static int windows_abort_transfers(struct usbi_transfer *itransfer)
2183 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2184 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2186 return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
2189 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
2191 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2193 switch (transfer->type) {
2194 case LIBUSB_TRANSFER_TYPE_CONTROL:
2195 return windows_abort_control(itransfer);
2196 case LIBUSB_TRANSFER_TYPE_BULK:
2197 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2198 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2199 return windows_abort_transfers(itransfer);
2200 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2201 return LIBUSB_ERROR_NOT_SUPPORTED;
2203 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2204 return LIBUSB_ERROR_INVALID_PARAM;
2208 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2210 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2211 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2212 int status, istatus;
2214 usbi_dbg("handling I/O completion with errcode %d, size %d", io_result, io_size);
2218 status = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2220 case ERROR_GEN_FAILURE:
2221 usbi_dbg("detected endpoint stall");
2222 status = LIBUSB_TRANSFER_STALL;
2224 case ERROR_SEM_TIMEOUT:
2225 usbi_dbg("detected semaphore timeout");
2226 status = LIBUSB_TRANSFER_TIMED_OUT;
2228 case ERROR_OPERATION_ABORTED:
2229 istatus = priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2230 if (istatus != LIBUSB_TRANSFER_COMPLETED) {
2231 usbi_dbg("Failed to copy partial data in aborted operation: %d", istatus);
2233 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
2234 usbi_dbg("detected timeout");
2235 status = LIBUSB_TRANSFER_TIMED_OUT;
2237 usbi_dbg("detected operation aborted");
2238 status = LIBUSB_TRANSFER_CANCELLED;
2242 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error %d: %s", io_result, windows_error_str(io_result));
2243 status = LIBUSB_TRANSFER_ERROR;
2246 windows_clear_transfer_priv(itransfer); // Cancel polling
2247 usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
2250 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2252 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2254 switch (transfer->type) {
2255 case LIBUSB_TRANSFER_TYPE_CONTROL:
2256 case LIBUSB_TRANSFER_TYPE_BULK:
2257 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2258 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2259 windows_transfer_callback (itransfer, io_result, io_size);
2261 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2262 usbi_warn(ITRANSFER_CTX(itransfer), "bulk stream transfers are not yet supported on this platform");
2265 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2269 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2271 struct windows_transfer_priv* transfer_priv = NULL;
2272 POLL_NFDS_TYPE i = 0;
2274 struct usbi_transfer *transfer;
2275 DWORD io_size, io_result;
2277 usbi_mutex_lock(&ctx->open_devs_lock);
2278 for (i = 0; i < nfds && num_ready > 0; i++) {
2280 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2282 if (!fds[i].revents) {
2288 // Because a Windows OVERLAPPED is used for poll emulation,
2289 // a pollable fd is created and stored with each transfer
2290 usbi_mutex_lock(&ctx->flying_transfers_lock);
2292 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2293 transfer_priv = usbi_transfer_get_os_priv(transfer);
2294 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2299 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2302 // Handle async requests that completed synchronously first
2303 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2304 io_result = NO_ERROR;
2305 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2306 // Regular async overlapped
2307 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2308 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2309 io_result = NO_ERROR;
2311 io_result = GetLastError();
2313 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2314 // let handle_callback free the event using the transfer wfd
2315 // If you don't use the transfer wfd, you run a risk of trying to free a
2316 // newly allocated wfd that took the place of the one from the transfer.
2317 windows_handle_callback(transfer, io_result, io_size);
2319 usbi_mutex_unlock(&ctx->open_devs_lock);
2320 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2321 return LIBUSB_ERROR_NOT_FOUND;
2325 usbi_mutex_unlock(&ctx->open_devs_lock);
2326 return LIBUSB_SUCCESS;
2330 * Monotonic and real time functions
2332 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2334 struct timer_request *request;
2335 LARGE_INTEGER hires_counter;
2338 // The following call will create this thread's message queue
2339 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms644946.aspx
2340 PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
2342 // Signal windows_init() that we're ready to service requests
2343 if (!SetEvent((HANDLE)param)) {
2344 usbi_dbg("SetEvent failed for timer init event: %s", windows_error_str(0));
2348 // Main loop - wait for requests
2350 if (GetMessage(&msg, NULL, WM_TIMER_REQUEST, WM_TIMER_EXIT) == -1) {
2351 usbi_err(NULL, "GetMessage failed for timer thread: %s", windows_error_str(0));
2355 switch (msg.message) {
2356 case WM_TIMER_REQUEST:
2357 // Requests to this thread are for hires always
2358 // Microsoft says that this function always succeeds on XP and later
2359 // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms644904.aspx
2360 request = (struct timer_request *)msg.lParam;
2361 QueryPerformanceCounter(&hires_counter);
2362 request->tp->tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2363 request->tp->tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency) / 1000) * hires_ticks_to_ps);
2364 if (!SetEvent(request->event)) {
2365 usbi_err(NULL, "SetEvent failed for timer request: %s", windows_error_str(0));
2370 usbi_dbg("timer thread quitting");
2376 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2378 struct timer_request request;
2380 ULARGE_INTEGER rtime;
2383 case USBI_CLOCK_MONOTONIC:
2386 request.event = CreateEvent(NULL, FALSE, FALSE, NULL);
2387 if (request.event == NULL) {
2388 return LIBUSB_ERROR_NO_MEM;
2391 if (!PostThreadMessage(timer_thread_id, WM_TIMER_REQUEST, 0, (LPARAM)&request)) {
2392 usbi_err(NULL, "PostThreadMessage failed for timer thread: %s", windows_error_str(0));
2393 CloseHandle(request.event);
2394 return LIBUSB_ERROR_OTHER;
2398 r = WaitForSingleObject(request.event, TIMER_REQUEST_RETRY_MS);
2399 if (r == WAIT_TIMEOUT) {
2400 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2402 else if (r == WAIT_FAILED) {
2403 usbi_err(NULL, "WaitForSingleObject failed: %s", windows_error_str(0));
2405 } while (r == WAIT_TIMEOUT);
2406 CloseHandle(request.event);
2408 if (r == WAIT_OBJECT_0) {
2409 return LIBUSB_SUCCESS;
2412 return LIBUSB_ERROR_OTHER;
2415 // Fall through and return real-time if monotonic was not detected @ timer init
2416 case USBI_CLOCK_REALTIME:
2417 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2418 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2419 // Note however that our resolution is bounded by the Windows system time
2420 // functions and is at best of the order of 1 ms (or, usually, worse)
2421 GetSystemTimeAsFileTime(&filetime);
2422 rtime.LowPart = filetime.dwLowDateTime;
2423 rtime.HighPart = filetime.dwHighDateTime;
2424 rtime.QuadPart -= epoch_time;
2425 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2426 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2427 return LIBUSB_SUCCESS;
2429 return LIBUSB_ERROR_INVALID_PARAM;
2434 // NB: MSVC6 does not support named initializers.
2435 const struct usbi_os_backend windows_backend = {
2437 USBI_CAP_HAS_HID_ACCESS,
2441 windows_get_device_list,
2442 NULL, /* hotplug_poll */
2446 windows_get_device_descriptor,
2447 windows_get_active_config_descriptor,
2448 windows_get_config_descriptor,
2449 NULL, /* get_config_descriptor_by_value() */
2451 windows_get_configuration,
2452 windows_set_configuration,
2453 windows_claim_interface,
2454 windows_release_interface,
2456 windows_set_interface_altsetting,
2458 windows_reset_device,
2460 NULL, /* alloc_streams */
2461 NULL, /* free_streams */
2463 windows_kernel_driver_active,
2464 windows_detach_kernel_driver,
2465 windows_attach_kernel_driver,
2467 windows_destroy_device,
2469 windows_submit_transfer,
2470 windows_cancel_transfer,
2471 windows_clear_transfer_priv,
2473 windows_handle_events,
2474 NULL, /* handle_transfer_completion() */
2476 windows_clock_gettime,
2477 #if defined(USBI_TIMERFD_AVAILABLE)
2480 sizeof(struct windows_device_priv),
2481 sizeof(struct windows_device_handle_priv),
2482 sizeof(struct windows_transfer_priv),
2490 static int unsupported_init(int sub_api, struct libusb_context *ctx) {
2491 return LIBUSB_SUCCESS;
2493 static int unsupported_exit(int sub_api) {
2494 return LIBUSB_SUCCESS;
2496 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle) {
2497 PRINT_UNSUPPORTED_API(open);
2499 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle) {
2500 usbi_dbg("unsupported API call for 'close'");
2502 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2503 PRINT_UNSUPPORTED_API(configure_endpoints);
2505 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2506 PRINT_UNSUPPORTED_API(claim_interface);
2508 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2509 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2511 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2512 PRINT_UNSUPPORTED_API(release_interface);
2514 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2515 PRINT_UNSUPPORTED_API(clear_halt);
2517 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle) {
2518 PRINT_UNSUPPORTED_API(reset_device);
2520 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
2521 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2523 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
2524 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2526 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) {
2527 PRINT_UNSUPPORTED_API(submit_control_transfer);
2529 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer) {
2530 PRINT_UNSUPPORTED_API(abort_control);
2532 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer) {
2533 PRINT_UNSUPPORTED_API(abort_transfers);
2535 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
2536 PRINT_UNSUPPORTED_API(copy_transfer_data);
2538 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) {
2539 return LIBUSB_SUCCESS;
2541 // These names must be uppercase
2542 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30"};
2543 const char* composite_driver_names[] = {"USBCCGP"};
2544 const char* winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2545 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2546 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2548 USB_API_UNSUPPORTED,
2556 unsupported_configure_endpoints,
2557 unsupported_claim_interface,
2558 unsupported_set_interface_altsetting,
2559 unsupported_release_interface,
2560 unsupported_clear_halt,
2561 unsupported_reset_device,
2562 unsupported_submit_bulk_transfer,
2563 unsupported_submit_iso_transfer,
2564 unsupported_submit_control_transfer,
2565 unsupported_abort_control,
2566 unsupported_abort_transfers,
2567 unsupported_copy_transfer_data,
2572 ARRAYSIZE(hub_driver_names),
2577 unsupported_configure_endpoints,
2578 unsupported_claim_interface,
2579 unsupported_set_interface_altsetting,
2580 unsupported_release_interface,
2581 unsupported_clear_halt,
2582 unsupported_reset_device,
2583 unsupported_submit_bulk_transfer,
2584 unsupported_submit_iso_transfer,
2585 unsupported_submit_control_transfer,
2586 unsupported_abort_control,
2587 unsupported_abort_transfers,
2588 unsupported_copy_transfer_data,
2592 composite_driver_names,
2593 ARRAYSIZE(composite_driver_names),
2598 common_configure_endpoints,
2599 composite_claim_interface,
2600 composite_set_interface_altsetting,
2601 composite_release_interface,
2602 composite_clear_halt,
2603 composite_reset_device,
2604 composite_submit_bulk_transfer,
2605 composite_submit_iso_transfer,
2606 composite_submit_control_transfer,
2607 composite_abort_control,
2608 composite_abort_transfers,
2609 composite_copy_transfer_data,
2613 winusbx_driver_names,
2614 ARRAYSIZE(winusbx_driver_names),
2619 winusbx_configure_endpoints,
2620 winusbx_claim_interface,
2621 winusbx_set_interface_altsetting,
2622 winusbx_release_interface,
2624 winusbx_reset_device,
2625 winusbx_submit_bulk_transfer,
2626 unsupported_submit_iso_transfer,
2627 winusbx_submit_control_transfer,
2628 winusbx_abort_control,
2629 winusbx_abort_transfers,
2630 winusbx_copy_transfer_data,
2635 ARRAYSIZE(hid_driver_names),
2640 common_configure_endpoints,
2641 hid_claim_interface,
2642 hid_set_interface_altsetting,
2643 hid_release_interface,
2646 hid_submit_bulk_transfer,
2647 unsupported_submit_iso_transfer,
2648 hid_submit_control_transfer,
2649 hid_abort_transfers,
2650 hid_abort_transfers,
2651 hid_copy_transfer_data,
2657 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2659 #define WinUSBX_Set(fn) do { if (native_winusb) WinUSBX[i].fn = (WinUsb_##fn##_t) GetProcAddress(h, "WinUsb_" #fn); \
2660 else pLibK_GetProcAddress((PVOID*)&WinUSBX[i].fn, i, KUSB_FNID_##fn); } while (0)
2662 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2665 bool native_winusb = false;
2667 KLIB_VERSION LibK_Version;
2668 LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2669 LibK_GetVersion_t pLibK_GetVersion = NULL;
2671 h = GetModuleHandleA("libusbK");
2673 h = LoadLibraryA("libusbK");
2676 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2677 h = GetModuleHandleA("WinUSB");
2679 h = LoadLibraryA("WinUSB");
2681 usbi_warn(ctx, "WinUSB DLL is not available either, "
2682 "you will not be able to access devices outside of enumeration");
2683 return LIBUSB_ERROR_NOT_FOUND;
2686 usbi_dbg("using libusbK DLL for universal access");
2687 pLibK_GetVersion = (LibK_GetVersion_t) GetProcAddress(h, "LibK_GetVersion");
2688 if (pLibK_GetVersion != NULL) {
2689 pLibK_GetVersion(&LibK_Version);
2690 usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2691 LibK_Version.Micro, LibK_Version.Nano);
2693 pLibK_GetProcAddress = (LibK_GetProcAddress_t) GetProcAddress(h, "LibK_GetProcAddress");
2694 if (pLibK_GetProcAddress == NULL) {
2695 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2696 return LIBUSB_ERROR_NOT_FOUND;
2699 native_winusb = (pLibK_GetProcAddress == NULL);
2700 for (i=SUB_API_LIBUSBK; i<SUB_API_MAX; i++) {
2701 WinUSBX_Set(AbortPipe);
2702 WinUSBX_Set(ControlTransfer);
2703 WinUSBX_Set(FlushPipe);
2705 WinUSBX_Set(GetAssociatedInterface);
2706 WinUSBX_Set(GetCurrentAlternateSetting);
2707 WinUSBX_Set(GetDescriptor);
2708 WinUSBX_Set(GetOverlappedResult);
2709 WinUSBX_Set(GetPipePolicy);
2710 WinUSBX_Set(GetPowerPolicy);
2711 WinUSBX_Set(Initialize);
2712 WinUSBX_Set(QueryDeviceInformation);
2713 WinUSBX_Set(QueryInterfaceSettings);
2714 WinUSBX_Set(QueryPipe);
2715 WinUSBX_Set(ReadPipe);
2716 WinUSBX_Set(ResetPipe);
2717 WinUSBX_Set(SetCurrentAlternateSetting);
2718 WinUSBX_Set(SetPipePolicy);
2719 WinUSBX_Set(SetPowerPolicy);
2720 WinUSBX_Set(WritePipe);
2721 if (!native_winusb) {
2722 WinUSBX_Set(ResetDevice);
2724 if (WinUSBX[i].Initialize != NULL) {
2725 WinUSBX[i].initialized = true;
2726 usbi_dbg("initalized sub API %s", sub_api_name[i]);
2728 usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2729 WinUSBX[i].initialized = false;
2732 return LIBUSB_SUCCESS;
2735 static int winusbx_exit(int sub_api)
2737 return LIBUSB_SUCCESS;
2740 // NB: open and close must ensure that they only handle interface of
2741 // the right API type, as these functions can be called wholesale from
2742 // composite_open(), with interfaces belonging to different APIs
2743 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2745 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2746 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2747 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2752 CHECK_WINUSBX_AVAILABLE(sub_api);
2754 // WinUSB requires a seperate handle for each interface
2755 for (i = 0; i < USB_MAXINTERFACES; i++) {
2756 if ( (priv->usb_interface[i].path != NULL)
2757 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX) ) {
2758 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2759 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2760 if (file_handle == INVALID_HANDLE_VALUE) {
2761 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2762 switch(GetLastError()) {
2763 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2764 return LIBUSB_ERROR_NO_DEVICE;
2765 case ERROR_ACCESS_DENIED:
2766 return LIBUSB_ERROR_ACCESS;
2768 return LIBUSB_ERROR_IO;
2771 handle_priv->interface_handle[i].dev_handle = file_handle;
2775 return LIBUSB_SUCCESS;
2778 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2780 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2781 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2785 if (sub_api == SUB_API_NOTSET)
2786 sub_api = priv->sub_api;
2787 if (!WinUSBX[sub_api].initialized)
2790 if (priv->apib->id == USB_API_COMPOSITE) {
2791 // If this is a composite device, just free and close all WinUSB-like
2792 // interfaces directly (each is independent and not associated with another)
2793 for (i = 0; i < USB_MAXINTERFACES; i++) {
2794 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2795 handle = handle_priv->interface_handle[i].api_handle;
2796 if ((handle != 0) && (handle != INVALID_HANDLE_VALUE)) {
2797 WinUSBX[sub_api].Free(handle);
2799 handle = handle_priv->interface_handle[i].dev_handle;
2800 if ((handle != 0) && (handle != INVALID_HANDLE_VALUE)) {
2801 CloseHandle(handle);
2807 // If this is a WinUSB device, free all interfaces above interface 0,
2808 // then free and close interface 0 last
2809 for (i = 1; i < USB_MAXINTERFACES; i++) {
2810 handle = handle_priv->interface_handle[i].api_handle;
2811 if ((handle != 0) && (handle != INVALID_HANDLE_VALUE)) {
2812 WinUSBX[sub_api].Free(handle);
2815 handle = handle_priv->interface_handle[0].api_handle;
2816 if ((handle != 0) && (handle != INVALID_HANDLE_VALUE)) {
2817 WinUSBX[sub_api].Free(handle);
2819 handle = handle_priv->interface_handle[0].dev_handle;
2820 if ((handle != 0) && (handle != INVALID_HANDLE_VALUE)) {
2821 CloseHandle(handle);
2826 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2828 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2829 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2830 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2833 uint8_t endpoint_address;
2836 CHECK_WINUSBX_AVAILABLE(sub_api);
2838 // With handle and enpoints set (in parent), we can setup the default pipe properties
2839 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2840 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2841 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2842 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2843 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2844 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2846 if ((i == -1) || (sub_api == SUB_API_LIBUSB0)) {
2847 continue; // Other policies don't apply to control endpoint or libusb0
2850 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2851 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2852 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2854 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2855 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2856 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2859 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2860 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2861 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2862 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2863 usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2865 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2866 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2867 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2871 return LIBUSB_SUCCESS;
2874 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2876 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2877 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2878 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2879 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2880 HANDLE file_handle, winusb_handle;
2883 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2884 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2885 SP_DEVINFO_DATA dev_info_data;
2886 char* dev_path_no_guid = NULL;
2887 char filter_path[] = "\\\\.\\libusb0-0000";
2888 bool found_filter = false;
2890 CHECK_WINUSBX_AVAILABLE(sub_api);
2892 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2893 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2894 if ((is_using_usbccgp) || (iface == 0)) {
2895 // composite device (independent interfaces) or interface 0
2896 file_handle = handle_priv->interface_handle[iface].dev_handle;
2897 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2898 return LIBUSB_ERROR_NOT_FOUND;
2901 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2902 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2903 err = GetLastError();
2905 case ERROR_BAD_COMMAND:
2906 // The device was disconnected
2907 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2908 return LIBUSB_ERROR_NO_DEVICE;
2910 // it may be that we're using the libusb0 filter driver.
2911 // TODO: can we move this whole business into the K/0 DLL?
2912 for (i = 0; ; i++) {
2913 safe_free(dev_interface_details);
2914 safe_free(dev_path_no_guid);
2915 dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2916 if ((found_filter) || (dev_interface_details == NULL)) {
2920 dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2921 if (safe_strncmp(dev_path_no_guid, priv->usb_interface[iface].path, safe_strlen(dev_path_no_guid)) == 0) {
2922 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2923 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2924 if (file_handle == INVALID_HANDLE_VALUE) {
2925 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2927 WinUSBX[sub_api].Free(winusb_handle);
2928 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle))
2929 found_filter = true;
2931 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2935 if (!found_filter) {
2936 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2937 return LIBUSB_ERROR_ACCESS;
2941 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2943 // For all other interfaces, use GetAssociatedInterface()
2944 winusb_handle = handle_priv->interface_handle[0].api_handle;
2945 // It is a requirement for multiple interface devices on Windows that, to you
2946 // must first claim the first interface before you claim the others
2947 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2948 file_handle = handle_priv->interface_handle[0].dev_handle;
2949 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2950 handle_priv->interface_handle[0].api_handle = winusb_handle;
2951 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2953 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2954 return LIBUSB_ERROR_ACCESS;
2957 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2958 &handle_priv->interface_handle[iface].api_handle)) {
2959 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2960 switch(GetLastError()) {
2961 case ERROR_NO_MORE_ITEMS: // invalid iface
2962 return LIBUSB_ERROR_NOT_FOUND;
2963 case ERROR_BAD_COMMAND: // The device was disconnected
2964 return LIBUSB_ERROR_NO_DEVICE;
2965 case ERROR_ALREADY_EXISTS: // already claimed
2966 return LIBUSB_ERROR_BUSY;
2968 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2969 return LIBUSB_ERROR_ACCESS;
2973 usbi_dbg("claimed interface %d", iface);
2974 handle_priv->active_interface = iface;
2976 return LIBUSB_SUCCESS;
2979 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2981 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2982 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2983 HANDLE winusb_handle;
2985 CHECK_WINUSBX_AVAILABLE(sub_api);
2987 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2988 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2989 return LIBUSB_ERROR_NOT_FOUND;
2992 WinUSBX[sub_api].Free(winusb_handle);
2993 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2995 return LIBUSB_SUCCESS;
2999 * Return the first valid interface (of the same API type), for control transfers
3001 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
3003 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3004 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3007 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
3008 usbi_dbg("unsupported API ID");
3012 for (i=0; i<USB_MAXINTERFACES; i++) {
3013 if ( (handle_priv->interface_handle[i].dev_handle != 0)
3014 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
3015 && (handle_priv->interface_handle[i].api_handle != 0)
3016 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
3017 && (priv->usb_interface[i].apib->id == api_id) ) {
3025 * Lookup interface by endpoint address. -1 if not found
3027 static int interface_by_endpoint(struct windows_device_priv *priv,
3028 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
3031 for (i=0; i<USB_MAXINTERFACES; i++) {
3032 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
3034 if (handle_priv->interface_handle[i].api_handle == 0)
3036 if (priv->usb_interface[i].endpoint == NULL)
3038 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
3039 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
3047 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3049 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3050 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3051 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3052 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3053 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
3054 transfer->dev_handle);
3055 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3057 HANDLE winusb_handle;
3058 int current_interface;
3061 CHECK_WINUSBX_AVAILABLE(sub_api);
3063 transfer_priv->pollable_fd = INVALID_WINFD;
3064 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3066 if (size > MAX_CTRL_BUFFER_LENGTH)
3067 return LIBUSB_ERROR_INVALID_PARAM;
3069 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
3070 if (current_interface < 0) {
3071 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS) {
3072 return LIBUSB_ERROR_NOT_FOUND;
3076 usbi_dbg("will use interface %d", current_interface);
3077 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3079 wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
3080 // Always use the handle returned from usbi_create_fd (wfd.handle)
3082 return LIBUSB_ERROR_NO_MEM;
3085 // Sending of set configuration control requests from WinUSB creates issues
3086 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
3087 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
3088 if (setup->value != priv->active_config) {
3089 usbi_warn(ctx, "cannot set configuration other than the default one");
3091 return LIBUSB_ERROR_INVALID_PARAM;
3093 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3094 wfd.overlapped->InternalHigh = 0;
3096 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
3097 if(GetLastError() != ERROR_IO_PENDING) {
3098 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
3100 return LIBUSB_ERROR_IO;
3103 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3104 wfd.overlapped->InternalHigh = (DWORD)size;
3108 // Use priv_transfer to store data needed for async polling
3109 transfer_priv->pollable_fd = wfd;
3110 transfer_priv->interface_number = (uint8_t)current_interface;
3112 return LIBUSB_SUCCESS;
3115 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
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);
3120 HANDLE winusb_handle;
3122 CHECK_WINUSBX_AVAILABLE(sub_api);
3124 if (altsetting > 255) {
3125 return LIBUSB_ERROR_INVALID_PARAM;
3128 winusb_handle = handle_priv->interface_handle[iface].api_handle;
3129 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
3130 usbi_err(ctx, "interface must be claimed first");
3131 return LIBUSB_ERROR_NOT_FOUND;
3134 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
3135 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
3136 return LIBUSB_ERROR_IO;
3139 return LIBUSB_SUCCESS;
3142 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3144 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3145 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3146 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3147 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3148 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3149 HANDLE winusb_handle;
3151 int current_interface;
3154 CHECK_WINUSBX_AVAILABLE(sub_api);
3156 transfer_priv->pollable_fd = INVALID_WINFD;
3158 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3159 if (current_interface < 0) {
3160 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3161 return LIBUSB_ERROR_NOT_FOUND;
3164 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3166 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3168 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
3169 // Always use the handle returned from usbi_create_fd (wfd.handle)
3171 return LIBUSB_ERROR_NO_MEM;
3174 if (IS_XFERIN(transfer)) {
3175 usbi_dbg("reading %d bytes", transfer->length);
3176 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
3178 usbi_dbg("writing %d bytes", transfer->length);
3179 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
3182 if(GetLastError() != ERROR_IO_PENDING) {
3183 usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
3185 return LIBUSB_ERROR_IO;
3188 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3189 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
3192 transfer_priv->pollable_fd = wfd;
3193 transfer_priv->interface_number = (uint8_t)current_interface;
3195 return LIBUSB_SUCCESS;
3198 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3200 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3201 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3202 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3203 HANDLE winusb_handle;
3204 int current_interface;
3206 CHECK_WINUSBX_AVAILABLE(sub_api);
3208 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3209 if (current_interface < 0) {
3210 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3211 return LIBUSB_ERROR_NOT_FOUND;
3214 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3215 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3217 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
3218 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
3219 return LIBUSB_ERROR_NO_DEVICE;
3222 return LIBUSB_SUCCESS;
3226 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
3227 * through testing as well):
3228 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
3229 * the control transfer using CancelIo"
3231 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
3233 // Cancelling of the I/O is done in the parent
3234 return LIBUSB_SUCCESS;
3237 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3239 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3240 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3241 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3242 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3243 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3244 HANDLE winusb_handle;
3245 int current_interface;
3247 CHECK_WINUSBX_AVAILABLE(sub_api);
3249 current_interface = transfer_priv->interface_number;
3250 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
3251 usbi_err(ctx, "program assertion failed: invalid interface_number");
3252 return LIBUSB_ERROR_NOT_FOUND;
3254 usbi_dbg("will use interface %d", current_interface);
3256 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3258 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
3259 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
3260 return LIBUSB_ERROR_NO_DEVICE;
3263 return LIBUSB_SUCCESS;
3267 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
3268 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
3269 * "WinUSB does not support host-initiated reset port and cycle port operations" and
3270 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
3271 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
3272 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
3274 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
3275 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3277 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3278 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3279 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3281 HANDLE winusb_handle;
3284 CHECK_WINUSBX_AVAILABLE(sub_api);
3286 // Reset any available pipe (except control)
3287 for (i=0; i<USB_MAXINTERFACES; i++) {
3288 winusb_handle = handle_priv->interface_handle[i].api_handle;
3289 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
3291 // Cancel any pollable I/O
3292 usbi_remove_pollfd(ctx, wfd.fd);
3294 wfd = handle_to_winfd(winusb_handle);
3297 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
3298 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
3299 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
3300 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
3301 usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
3302 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3304 // FlushPipe seems to fail on OUT pipes
3305 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
3306 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
3307 usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
3308 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3310 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
3311 usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
3312 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3318 // libusbK & libusb0 have the ability to issue an actual device reset
3319 if (WinUSBX[sub_api].ResetDevice != NULL) {
3320 winusb_handle = handle_priv->interface_handle[0].api_handle;
3321 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
3322 WinUSBX[sub_api].ResetDevice(winusb_handle);
3325 return LIBUSB_SUCCESS;
3328 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3330 itransfer->transferred += io_size;
3331 return LIBUSB_TRANSFER_COMPLETED;
3335 * Internal HID Support functions (from libusb-win32)
3336 * Note that functions that complete data transfer synchronously must return
3337 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3339 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
3340 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
3342 static int _hid_wcslen(WCHAR *str)
3345 while (str[i] && (str[i] != 0x409)) {
3351 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3353 struct libusb_device_descriptor d;
3355 d.bLength = LIBUSB_DT_DEVICE_SIZE;
3356 d.bDescriptorType = LIBUSB_DT_DEVICE;
3357 d.bcdUSB = 0x0200; /* 2.00 */
3359 d.bDeviceSubClass = 0;
3360 d.bDeviceProtocol = 0;
3361 d.bMaxPacketSize0 = 64; /* fix this! */
3362 d.idVendor = (uint16_t)dev->vid;
3363 d.idProduct = (uint16_t)dev->pid;
3364 d.bcdDevice = 0x0100;
3365 d.iManufacturer = dev->string_index[0];
3366 d.iProduct = dev->string_index[1];
3367 d.iSerialNumber = dev->string_index[2];
3368 d.bNumConfigurations = 1;
3370 if (*size > LIBUSB_DT_DEVICE_SIZE)
3371 *size = LIBUSB_DT_DEVICE_SIZE;
3372 memcpy(data, &d, *size);
3373 return LIBUSB_COMPLETED;
3376 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3378 char num_endpoints = 0;
3379 size_t config_total_len = 0;
3380 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3381 struct libusb_config_descriptor *cd;
3382 struct libusb_interface_descriptor *id;
3383 struct libusb_hid_descriptor *hd;
3384 struct libusb_endpoint_descriptor *ed;
3387 if (dev->input_report_size)
3389 if (dev->output_report_size)
3392 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3393 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3396 cd = (struct libusb_config_descriptor *)tmp;
3397 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3398 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3399 + LIBUSB_DT_INTERFACE_SIZE);
3400 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3401 + LIBUSB_DT_INTERFACE_SIZE
3402 + LIBUSB_DT_HID_SIZE);
3404 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3405 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3406 cd->wTotalLength = (uint16_t) config_total_len;
3407 cd->bNumInterfaces = 1;
3408 cd->bConfigurationValue = 1;
3409 cd->iConfiguration = 0;
3410 cd->bmAttributes = 1 << 7; /* bus powered */
3413 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3414 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3415 id->bInterfaceNumber = 0;
3416 id->bAlternateSetting = 0;
3417 id->bNumEndpoints = num_endpoints;
3418 id->bInterfaceClass = 3;
3419 id->bInterfaceSubClass = 0;
3420 id->bInterfaceProtocol = 0;
3423 tmp_size = LIBUSB_DT_HID_SIZE;
3424 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3426 if (dev->input_report_size) {
3427 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3428 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3429 ed->bEndpointAddress = HID_IN_EP;
3430 ed->bmAttributes = 3;
3431 ed->wMaxPacketSize = dev->input_report_size - 1;
3433 ed = (struct libusb_endpoint_descriptor *)((char*)ed + LIBUSB_DT_ENDPOINT_SIZE);
3436 if (dev->output_report_size) {
3437 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3438 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3439 ed->bEndpointAddress = HID_OUT_EP;
3440 ed->bmAttributes = 3;
3441 ed->wMaxPacketSize = dev->output_report_size - 1;
3445 if (*size > config_total_len)
3446 *size = config_total_len;
3447 memcpy(data, tmp, *size);
3448 return LIBUSB_COMPLETED;
3451 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int _index,
3452 void *data, size_t *size)
3455 size_t tmp_size = 0;
3458 /* language ID, EN-US */
3459 char string_langid[] = {
3464 if ((*size < 2) || (*size > 255)) {
3465 return LIBUSB_ERROR_OVERFLOW;
3469 tmp = string_langid;
3470 tmp_size = sizeof(string_langid)+2;
3472 for (i=0; i<3; i++) {
3473 if (_index == (dev->string_index[i])) {
3474 tmp = dev->string[i];
3475 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3479 if (i == 3) { // not found
3480 return LIBUSB_ERROR_INVALID_PARAM;
3485 return LIBUSB_ERROR_INVALID_PARAM;
3488 if (tmp_size < *size) {
3492 ((uint8_t*)data)[0] = (uint8_t)*size;
3493 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3494 memcpy((uint8_t*)data+2, tmp, *size-2);
3495 return LIBUSB_COMPLETED;
3498 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3500 struct libusb_hid_descriptor d;
3501 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3502 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3504 _hid_get_report_descriptor(dev, tmp, &report_len);
3506 d.bLength = LIBUSB_DT_HID_SIZE;
3507 d.bDescriptorType = LIBUSB_DT_HID;
3508 d.bcdHID = 0x0110; /* 1.10 */
3510 d.bNumDescriptors = 1;
3511 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3512 d.wClassDescriptorLength = (uint16_t)report_len;
3514 if (*size > LIBUSB_DT_HID_SIZE)
3515 *size = LIBUSB_DT_HID_SIZE;
3516 memcpy(data, &d, *size);
3517 return LIBUSB_COMPLETED;
3520 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3522 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3525 /* usage page (0xFFA0 == vendor defined) */
3526 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3527 /* usage (vendor defined) */
3528 d[i++] = 0x09; d[i++] = 0x01;
3529 /* start collection (application) */
3530 d[i++] = 0xA1; d[i++] = 0x01;
3532 if (dev->input_report_size) {
3533 /* usage (vendor defined) */
3534 d[i++] = 0x09; d[i++] = 0x01;
3535 /* logical minimum (0) */
3536 d[i++] = 0x15; d[i++] = 0x00;
3537 /* logical maximum (255) */
3538 d[i++] = 0x25; d[i++] = 0xFF;
3539 /* report size (8 bits) */
3540 d[i++] = 0x75; d[i++] = 0x08;
3542 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3543 /* input (data, variable, absolute) */
3544 d[i++] = 0x81; d[i++] = 0x00;
3547 if (dev->output_report_size) {
3548 /* usage (vendor defined) */
3549 d[i++] = 0x09; d[i++] = 0x02;
3550 /* logical minimum (0) */
3551 d[i++] = 0x15; d[i++] = 0x00;
3552 /* logical maximum (255) */
3553 d[i++] = 0x25; d[i++] = 0xFF;
3554 /* report size (8 bits) */
3555 d[i++] = 0x75; d[i++] = 0x08;
3557 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3558 /* output (data, variable, absolute) */
3559 d[i++] = 0x91; d[i++] = 0x00;
3561 /* feature report */
3562 if (dev->feature_report_size) {
3563 /* usage (vendor defined) */
3564 d[i++] = 0x09; d[i++] = 0x03;
3565 /* logical minimum (0) */
3566 d[i++] = 0x15; d[i++] = 0x00;
3567 /* logical maximum (255) */
3568 d[i++] = 0x25; d[i++] = 0xFF;
3569 /* report size (8 bits) */
3570 d[i++] = 0x75; d[i++] = 0x08;
3572 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3573 /* feature (data, variable, absolute) */
3574 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3577 /* end collection */
3582 memcpy(data, d, *size);
3583 return LIBUSB_COMPLETED;
3586 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3587 int type, int _index, void *data, size_t *size)
3590 case LIBUSB_DT_DEVICE:
3591 usbi_dbg("LIBUSB_DT_DEVICE");
3592 return _hid_get_device_descriptor(dev, data, size);
3593 case LIBUSB_DT_CONFIG:
3594 usbi_dbg("LIBUSB_DT_CONFIG");
3596 return _hid_get_config_descriptor(dev, data, size);
3597 return LIBUSB_ERROR_INVALID_PARAM;
3598 case LIBUSB_DT_STRING:
3599 usbi_dbg("LIBUSB_DT_STRING");
3600 return _hid_get_string_descriptor(dev, _index, data, size);
3602 usbi_dbg("LIBUSB_DT_HID");
3604 return _hid_get_hid_descriptor(dev, data, size);
3605 return LIBUSB_ERROR_INVALID_PARAM;
3606 case LIBUSB_DT_REPORT:
3607 usbi_dbg("LIBUSB_DT_REPORT");
3609 return _hid_get_report_descriptor(dev, data, size);
3610 return LIBUSB_ERROR_INVALID_PARAM;
3611 case LIBUSB_DT_PHYSICAL:
3612 usbi_dbg("LIBUSB_DT_PHYSICAL");
3613 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3614 return LIBUSB_COMPLETED;
3615 return LIBUSB_ERROR_OTHER;
3617 usbi_dbg("unsupported");
3618 return LIBUSB_ERROR_NOT_SUPPORTED;
3621 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3622 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3626 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3627 int r = LIBUSB_SUCCESS;
3629 if (tp->hid_buffer != NULL) {
3630 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3633 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3634 usbi_dbg("invalid size (%d)", *size);
3635 return LIBUSB_ERROR_INVALID_PARAM;
3638 switch (report_type) {
3639 case HID_REPORT_TYPE_INPUT:
3640 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3642 case HID_REPORT_TYPE_FEATURE:
3643 ioctl_code = IOCTL_HID_GET_FEATURE;
3646 usbi_dbg("unknown HID report type %d", report_type);
3647 return LIBUSB_ERROR_INVALID_PARAM;
3650 // Add a trailing byte to detect overflows
3651 buf = (uint8_t*)calloc(expected_size+1, 1);
3653 return LIBUSB_ERROR_NO_MEM;
3655 buf[0] = (uint8_t)id; // Must be set always
3656 usbi_dbg("report ID: 0x%02X", buf[0]);
3658 tp->hid_expected_size = expected_size;
3659 read_size = expected_size;
3661 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3662 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3663 buf, expected_size+1, &read_size, overlapped)) {
3664 if (GetLastError() != ERROR_IO_PENDING) {
3665 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3667 return LIBUSB_ERROR_IO;
3669 // Asynchronous wait
3670 tp->hid_buffer = buf;
3671 tp->hid_dest = (uint8_t*)data; // copy dest, as not necessarily the start of the transfer buffer
3672 return LIBUSB_SUCCESS;
3675 // Transfer completed synchronously => copy and discard extra buffer
3676 if (read_size == 0) {
3677 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3681 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3683 if ((size_t)read_size > expected_size) {
3684 r = LIBUSB_ERROR_OVERFLOW;
3685 usbi_dbg("OVERFLOW!");
3687 r = LIBUSB_COMPLETED;
3690 *size = MIN((size_t)read_size, *size);
3692 // Discard report ID
3693 memcpy(data, buf+1, *size);
3695 memcpy(data, buf, *size);
3702 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3703 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3706 uint8_t *buf = NULL;
3707 DWORD ioctl_code, write_size= (DWORD)*size;
3709 if (tp->hid_buffer != NULL) {
3710 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3713 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3714 usbi_dbg("invalid size (%d)", *size);
3715 return LIBUSB_ERROR_INVALID_PARAM;
3718 switch (report_type) {
3719 case HID_REPORT_TYPE_OUTPUT:
3720 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3722 case HID_REPORT_TYPE_FEATURE:
3723 ioctl_code = IOCTL_HID_SET_FEATURE;
3726 usbi_dbg("unknown HID report type %d", report_type);
3727 return LIBUSB_ERROR_INVALID_PARAM;
3730 usbi_dbg("report ID: 0x%02X", id);
3731 // When report IDs are not used (i.e. when id == 0), we must add
3732 // a null report ID. Otherwise, we just use original data buffer
3736 buf = (uint8_t*) malloc(write_size);
3738 return LIBUSB_ERROR_NO_MEM;
3742 memcpy(buf + 1, data, *size);
3744 // This seems like a waste, but if we don't duplicate the
3745 // data, we'll get issues when freeing hid_buffer
3746 memcpy(buf, data, *size);
3748 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3752 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3753 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3754 buf, write_size, &write_size, overlapped)) {
3755 if (GetLastError() != ERROR_IO_PENDING) {
3756 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3758 return LIBUSB_ERROR_IO;
3760 tp->hid_buffer = buf;
3761 tp->hid_dest = NULL;
3762 return LIBUSB_SUCCESS;
3765 // Transfer completed synchronously
3767 if (write_size == 0) {
3768 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3771 return LIBUSB_COMPLETED;
3774 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3775 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3776 size_t *size, OVERLAPPED* overlapped)
3778 int report_type = (value >> 8) & 0xFF;
3779 int report_id = value & 0xFF;
3781 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3782 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3783 return LIBUSB_ERROR_INVALID_PARAM;
3785 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3786 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3788 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3789 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3791 return LIBUSB_ERROR_INVALID_PARAM;
3798 static int hid_init(int sub_api, struct libusb_context *ctx)
3800 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3801 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3802 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3803 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3804 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3805 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3806 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3807 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3808 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3809 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3810 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3811 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3812 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3813 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3814 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3815 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3817 api_hid_available = true;
3818 return LIBUSB_SUCCESS;
3821 static int hid_exit(int sub_api)
3823 return LIBUSB_SUCCESS;
3826 // NB: open and close must ensure that they only handle interface of
3827 // the right API type, as these functions can be called wholesale from
3828 // composite_open(), with interfaces belonging to different APIs
3829 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3831 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3832 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3833 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3835 HIDD_ATTRIBUTES hid_attributes;
3836 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3837 HIDP_CAPS capabilities;
3838 HIDP_VALUE_CAPS *value_caps;
3840 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3842 // report IDs handling
3844 const char* type[3] = {"input", "output", "feature"};
3845 int nb_ids[2]; // zero and nonzero report IDs
3847 CHECK_HID_AVAILABLE;
3848 if (priv->hid == NULL) {
3849 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3850 return LIBUSB_ERROR_NOT_FOUND;
3853 for (i = 0; i < USB_MAXINTERFACES; i++) {
3854 if ( (priv->usb_interface[i].path != NULL)
3855 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3856 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3857 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3859 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3860 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3861 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3862 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3863 * HidD_GetFeature (if the device supports Feature reports)."
3865 if (hid_handle == INVALID_HANDLE_VALUE) {
3866 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3867 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3868 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3869 if (hid_handle == INVALID_HANDLE_VALUE) {
3870 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3871 switch(GetLastError()) {
3872 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3873 return LIBUSB_ERROR_NO_DEVICE;
3874 case ERROR_ACCESS_DENIED:
3875 return LIBUSB_ERROR_ACCESS;
3877 return LIBUSB_ERROR_IO;
3880 priv->usb_interface[i].restricted_functionality = true;
3882 handle_priv->interface_handle[i].api_handle = hid_handle;
3886 hid_attributes.Size = sizeof(hid_attributes);
3888 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3889 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3893 priv->hid->vid = hid_attributes.VendorID;
3894 priv->hid->pid = hid_attributes.ProductID;
3896 // Set the maximum available input buffer size
3897 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3898 usbi_dbg("set maximum input buffer size to %d", i/2);
3900 // Get the maximum input and output report size
3901 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3902 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3905 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3906 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3910 // Find out if interrupt will need report IDs
3911 size[0] = capabilities.NumberInputValueCaps;
3912 size[1] = capabilities.NumberOutputValueCaps;
3913 size[2] = capabilities.NumberFeatureValueCaps;
3914 for (j=HidP_Input; j<=HidP_Feature; j++) {
3915 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3916 priv->hid->uses_report_ids[j] = false;
3918 value_caps = (HIDP_VALUE_CAPS*) calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3919 if ( (value_caps != NULL)
3920 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3921 && (size[j] >= 1) ) {
3924 for (i=0; i<(int)size[j]; i++) {
3925 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3926 if (value_caps[i].ReportID != 0) {
3932 if (nb_ids[1] != 0) {
3933 if (nb_ids[0] != 0) {
3934 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3937 priv->hid->uses_report_ids[j] = true;
3940 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3942 safe_free(value_caps);
3946 // Set the report sizes
3947 priv->hid->input_report_size = capabilities.InputReportByteLength;
3948 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3949 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3951 // Fetch string descriptors
3952 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3953 if (priv->hid->string_index[0] != 0) {
3954 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3955 sizeof(priv->hid->string[0]));
3957 priv->hid->string[0][0] = 0;
3959 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3960 if (priv->hid->string_index[1] != 0) {
3961 HidD_GetProductString(hid_handle, priv->hid->string[1],
3962 sizeof(priv->hid->string[1]));
3964 priv->hid->string[1][0] = 0;
3966 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3967 if (priv->hid->string_index[2] != 0) {
3968 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3969 sizeof(priv->hid->string[2]));
3971 priv->hid->string[2][0] = 0;
3975 if (preparsed_data) {
3976 HidD_FreePreparsedData(preparsed_data);
3979 return LIBUSB_SUCCESS;
3982 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3984 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3985 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3989 if (!api_hid_available)
3992 for (i = 0; i < USB_MAXINTERFACES; i++) {
3993 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3994 file_handle = handle_priv->interface_handle[i].api_handle;
3995 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3996 CloseHandle(file_handle);
4002 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4004 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4005 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4007 CHECK_HID_AVAILABLE;
4009 // NB: Disconnection detection is not possible in this function
4010 if (priv->usb_interface[iface].path == NULL) {
4011 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
4014 // We use dev_handle as a flag for interface claimed
4015 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
4016 return LIBUSB_ERROR_BUSY; // already claimed
4019 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
4021 usbi_dbg("claimed interface %d", iface);
4022 handle_priv->active_interface = iface;
4024 return LIBUSB_SUCCESS;
4027 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4029 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4030 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4032 CHECK_HID_AVAILABLE;
4034 if (priv->usb_interface[iface].path == NULL) {
4035 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
4038 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
4039 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
4042 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
4044 return LIBUSB_SUCCESS;
4047 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4049 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4051 CHECK_HID_AVAILABLE;
4053 if (altsetting > 255) {
4054 return LIBUSB_ERROR_INVALID_PARAM;
4057 if (altsetting != 0) {
4058 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
4059 return LIBUSB_ERROR_NOT_SUPPORTED;
4062 return LIBUSB_SUCCESS;
4065 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4067 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4068 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4069 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4070 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4071 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4072 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
4075 int current_interface, config;
4077 int r = LIBUSB_ERROR_INVALID_PARAM;
4079 CHECK_HID_AVAILABLE;
4081 transfer_priv->pollable_fd = INVALID_WINFD;
4082 safe_free(transfer_priv->hid_buffer);
4083 transfer_priv->hid_dest = NULL;
4084 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
4086 if (size > MAX_CTRL_BUFFER_LENGTH) {
4087 return LIBUSB_ERROR_INVALID_PARAM;
4090 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
4091 if (current_interface < 0) {
4092 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) {
4093 return LIBUSB_ERROR_NOT_FOUND;
4097 usbi_dbg("will use interface %d", current_interface);
4098 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4099 // Always use the handle returned from usbi_create_fd (wfd.handle)
4100 wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
4102 return LIBUSB_ERROR_NOT_FOUND;
4105 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
4106 case LIBUSB_REQUEST_TYPE_STANDARD:
4107 switch(setup->request) {
4108 case LIBUSB_REQUEST_GET_DESCRIPTOR:
4109 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
4110 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
4112 case LIBUSB_REQUEST_GET_CONFIGURATION:
4113 r = windows_get_configuration(transfer->dev_handle, &config);
4114 if (r == LIBUSB_SUCCESS) {
4116 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
4117 r = LIBUSB_COMPLETED;
4120 case LIBUSB_REQUEST_SET_CONFIGURATION:
4121 if (setup->value == priv->active_config) {
4122 r = LIBUSB_COMPLETED;
4124 usbi_warn(ctx, "cannot set configuration other than the default one");
4125 r = LIBUSB_ERROR_NOT_SUPPORTED;
4128 case LIBUSB_REQUEST_GET_INTERFACE:
4130 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
4131 r = LIBUSB_COMPLETED;
4133 case LIBUSB_REQUEST_SET_INTERFACE:
4134 r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->index, setup->value);
4135 if (r == LIBUSB_SUCCESS) {
4136 r = LIBUSB_COMPLETED;
4140 usbi_warn(ctx, "unsupported HID control request");
4141 r = LIBUSB_ERROR_NOT_SUPPORTED;
4145 case LIBUSB_REQUEST_TYPE_CLASS:
4146 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
4147 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
4148 &size, wfd.overlapped);
4151 usbi_warn(ctx, "unsupported HID control request");
4152 r = LIBUSB_ERROR_NOT_SUPPORTED;
4156 if (r == LIBUSB_COMPLETED) {
4157 // Force request to be completed synchronously. Transferred size has been set by previous call
4158 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
4159 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
4160 // set InternalHigh to the number of bytes transferred
4161 wfd.overlapped->InternalHigh = (DWORD)size;
4165 if (r == LIBUSB_SUCCESS) {
4166 // Use priv_transfer to store data needed for async polling
4167 transfer_priv->pollable_fd = wfd;
4168 transfer_priv->interface_number = (uint8_t)current_interface;
4176 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4177 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4178 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4179 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4180 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4181 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4184 bool direction_in, ret;
4185 int current_interface, length;
4187 int r = LIBUSB_SUCCESS;
4189 CHECK_HID_AVAILABLE;
4191 transfer_priv->pollable_fd = INVALID_WINFD;
4192 transfer_priv->hid_dest = NULL;
4193 safe_free(transfer_priv->hid_buffer);
4195 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4196 if (current_interface < 0) {
4197 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4198 return LIBUSB_ERROR_NOT_FOUND;
4201 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
4203 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4204 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
4206 wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
4207 // Always use the handle returned from usbi_create_fd (wfd.handle)
4209 return LIBUSB_ERROR_NO_MEM;
4212 // If report IDs are not in use, an extra prefix byte must be added
4213 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
4214 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
4215 length = transfer->length+1;
4217 length = transfer->length;
4219 // Add a trailing byte to detect overflows on input
4220 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
4221 if (transfer_priv->hid_buffer == NULL) {
4222 return LIBUSB_ERROR_NO_MEM;
4224 transfer_priv->hid_expected_size = length;
4227 transfer_priv->hid_dest = transfer->buffer;
4228 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
4229 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
4231 if (!priv->hid->uses_report_ids[1]) {
4232 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
4234 // We could actually do without the calloc and memcpy in this case
4235 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
4237 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
4238 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
4241 if (GetLastError() != ERROR_IO_PENDING) {
4242 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
4244 safe_free(transfer_priv->hid_buffer);
4245 return LIBUSB_ERROR_IO;
4248 // Only write operations that completed synchronously need to free up
4249 // hid_buffer. For reads, copy_transfer_data() handles that process.
4250 if (!direction_in) {
4251 safe_free(transfer_priv->hid_buffer);
4254 usbi_err(ctx, "program assertion failed - no data was transferred");
4257 if (size > (size_t)length) {
4258 usbi_err(ctx, "OVERFLOW!");
4259 r = LIBUSB_ERROR_OVERFLOW;
4261 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
4262 wfd.overlapped->InternalHigh = size;
4265 transfer_priv->pollable_fd = wfd;
4266 transfer_priv->interface_number = (uint8_t)current_interface;
4271 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4273 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4274 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
4275 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4277 int current_interface;
4279 CHECK_HID_AVAILABLE;
4281 current_interface = transfer_priv->interface_number;
4282 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4283 CancelIo(hid_handle);
4285 return LIBUSB_SUCCESS;
4288 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4290 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4292 int current_interface;
4294 CHECK_HID_AVAILABLE;
4296 // Flushing the queues on all interfaces is the best we can achieve
4297 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
4298 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4299 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
4300 HidD_FlushQueue(hid_handle);
4303 return LIBUSB_SUCCESS;
4306 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4308 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4309 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4310 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4312 int current_interface;
4314 CHECK_HID_AVAILABLE;
4316 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4317 if (current_interface < 0) {
4318 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4319 return LIBUSB_ERROR_NOT_FOUND;
4322 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
4323 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4325 // No endpoint selection with Microsoft's implementation, so we try to flush the
4326 // whole interface. Should be OK for most case scenarios
4327 if (!HidD_FlushQueue(hid_handle)) {
4328 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
4329 // Device was probably disconnected
4330 return LIBUSB_ERROR_NO_DEVICE;
4333 return LIBUSB_SUCCESS;
4336 // This extra function is only needed for HID
4337 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) {
4338 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4339 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4340 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4341 int r = LIBUSB_TRANSFER_COMPLETED;
4342 uint32_t corrected_size = io_size;
4344 if (transfer_priv->hid_buffer != NULL) {
4345 // If we have a valid hid_buffer, it means the transfer was async
4346 if (transfer_priv->hid_dest != NULL) { // Data readout
4347 if (corrected_size > 0) {
4348 // First, check for overflow
4349 if (corrected_size > transfer_priv->hid_expected_size) {
4350 usbi_err(ctx, "OVERFLOW!");
4351 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4352 r = LIBUSB_TRANSFER_OVERFLOW;
4355 if (transfer_priv->hid_buffer[0] == 0) {
4356 // Discard the 1 byte report ID prefix
4358 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
4360 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4363 transfer_priv->hid_dest = NULL;
4365 // For write, we just need to free the hid buffer
4366 safe_free(transfer_priv->hid_buffer);
4368 itransfer->transferred += corrected_size;
4374 * Composite API functions
4376 static int composite_init(int sub_api, struct libusb_context *ctx)
4378 return LIBUSB_SUCCESS;
4381 static int composite_exit(int sub_api)
4383 return LIBUSB_SUCCESS;
4386 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4388 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4389 int r = LIBUSB_ERROR_NOT_FOUND;
4391 // SUB_API_MAX+1 as the SUB_API_MAX pos is used to indicate availability of HID
4392 bool available[SUB_API_MAX+1] = {0};
4394 for (i=0; i<USB_MAXINTERFACES; i++) {
4395 switch (priv->usb_interface[i].apib->id) {
4396 case USB_API_WINUSBX:
4397 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4398 available[priv->usb_interface[i].sub_api] = true;
4401 available[SUB_API_MAX] = true;
4408 for (i=0; i<SUB_API_MAX; i++) { // WinUSB-like drivers
4410 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4411 if (r != LIBUSB_SUCCESS) {
4416 if (available[SUB_API_MAX]) { // HID driver
4417 r = hid_open(SUB_API_NOTSET, dev_handle);
4422 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4424 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4426 bool available[SUB_API_MAX];
4428 for (i = 0; i<SUB_API_MAX; i++) {
4429 available[i] = false;
4432 for (i=0; i<USB_MAXINTERFACES; i++) {
4433 if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4434 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
4435 available[priv->usb_interface[i].sub_api] = true;
4439 for (i=0; i<SUB_API_MAX; i++) {
4441 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4446 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4448 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4449 return priv->usb_interface[iface].apib->
4450 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4453 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4455 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4456 return priv->usb_interface[iface].apib->
4457 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4460 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4462 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4463 return priv->usb_interface[iface].apib->
4464 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4467 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4469 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4470 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4471 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4472 struct libusb_config_descriptor *conf_desc;
4473 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
4476 // Interface shouldn't matter for control, but it does in practice, with Windows'
4477 // restrictions with regards to accessing HID keyboards and mice. Try to target
4478 // a specific interface first, if possible.
4479 switch (LIBUSB_REQ_RECIPIENT(setup->request_type)) {
4480 case LIBUSB_RECIPIENT_INTERFACE:
4481 iface = setup->index & 0xFF;
4483 case LIBUSB_RECIPIENT_ENDPOINT:
4484 r = libusb_get_config_descriptor(transfer->dev_handle->dev, (uint8_t)(priv->active_config-1), &conf_desc);
4485 if (r == LIBUSB_SUCCESS) {
4486 iface = get_interface_by_endpoint(conf_desc, (setup->index & 0xFF));
4487 libusb_free_config_descriptor(conf_desc);
4490 // Fall through if not able to determine interface
4496 // Try and target a specific interface if the control setup indicates such
4497 if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4498 usbi_dbg("attempting control transfer targeted to interface %d", iface);
4499 if (priv->usb_interface[iface].path != NULL) {
4500 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4501 if (r == LIBUSB_SUCCESS) {
4507 // Either not targeted to a specific interface or no luck in doing so.
4508 // Try a 2 pass approach with all interfaces.
4509 for (pass = 0; pass < 2; pass++) {
4510 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4511 if (priv->usb_interface[iface].path != NULL) {
4512 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4513 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4516 usbi_dbg("using interface %d", iface);
4517 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4518 // If not supported on this API, it may be supported on another, so don't give up yet!!
4519 if (r == LIBUSB_ERROR_NOT_SUPPORTED) {
4527 usbi_err(ctx, "no libusb supported interfaces to complete request");
4528 return LIBUSB_ERROR_NOT_FOUND;
4531 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4532 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4533 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4534 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4535 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4536 int current_interface;
4538 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4539 if (current_interface < 0) {
4540 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4541 return LIBUSB_ERROR_NOT_FOUND;
4544 return priv->usb_interface[current_interface].apib->
4545 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
4547 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4548 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4549 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4550 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4551 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4552 int current_interface;
4554 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4555 if (current_interface < 0) {
4556 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4557 return LIBUSB_ERROR_NOT_FOUND;
4560 return priv->usb_interface[current_interface].apib->
4561 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);}
4563 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4565 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4566 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4567 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4568 int current_interface;
4570 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4571 if (current_interface < 0) {
4572 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4573 return LIBUSB_ERROR_NOT_FOUND;
4576 return priv->usb_interface[current_interface].apib->
4577 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);}
4579 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4581 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4582 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4583 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4585 return priv->usb_interface[transfer_priv->interface_number].apib->
4586 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
4588 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4590 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4591 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4592 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4594 return priv->usb_interface[transfer_priv->interface_number].apib->
4595 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);}
4597 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4599 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4602 bool available[SUB_API_MAX];
4603 for (i = 0; i<SUB_API_MAX; i++) {
4604 available[i] = false;
4606 for (i=0; i<USB_MAXINTERFACES; i++) {
4607 if ( (priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4608 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET) ) {
4609 available[priv->usb_interface[i].sub_api] = true;
4612 for (i=0; i<SUB_API_MAX; i++) {
4614 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4615 if (r != LIBUSB_SUCCESS) {
4620 return LIBUSB_SUCCESS;
4623 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4625 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4626 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4627 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4629 return priv->usb_interface[transfer_priv->interface_number].apib->
4630 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);