2 * windows backend for libusbx 1.0
3 * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7 * Hash table functions adapted from glibc, by Ulrich Drepper et al.
8 * Major code testing contribution by Xiaofan Chen
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
38 #include "poll_windows.h"
39 #include "windows_usb.h"
41 // The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
42 #if defined(_PREFAST_)
43 #pragma warning(disable:28719)
46 // The 2 macros below are used in conjunction with safe loops.
47 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
48 #define LOOP_BREAK(err) { r=err; continue; }
50 extern void usbi_fd_notification(struct libusb_context *ctx);
53 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
54 static int windows_clock_gettime(int clk_id, struct timespec *tp);
55 unsigned __stdcall windows_clock_gettime_threaded(void* param);
56 // WinUSB API prototypes
57 static int winusb_init(struct libusb_context *ctx);
58 static int winusb_exit(void);
59 static int winusb_open(struct libusb_device_handle *dev_handle);
60 static void winusb_close(struct libusb_device_handle *dev_handle);
61 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface);
62 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
63 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
64 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
65 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
66 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
67 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
68 static int winusb_abort_transfers(struct usbi_transfer *itransfer);
69 static int winusb_abort_control(struct usbi_transfer *itransfer);
70 static int winusb_reset_device(struct libusb_device_handle *dev_handle);
71 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
73 static int hid_init(struct libusb_context *ctx);
74 static int hid_exit(void);
75 static int hid_open(struct libusb_device_handle *dev_handle);
76 static void hid_close(struct libusb_device_handle *dev_handle);
77 static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface);
78 static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface);
79 static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
80 static int hid_submit_control_transfer(struct usbi_transfer *itransfer);
81 static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer);
82 static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
83 static int hid_abort_transfers(struct usbi_transfer *itransfer);
84 static int hid_reset_device(struct libusb_device_handle *dev_handle);
85 static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
86 // Composite API prototypes
87 static int composite_init(struct libusb_context *ctx);
88 static int composite_exit(void);
89 static int composite_open(struct libusb_device_handle *dev_handle);
90 static void composite_close(struct libusb_device_handle *dev_handle);
91 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
92 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
93 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
94 static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
95 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
96 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
97 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
98 static int composite_abort_transfers(struct usbi_transfer *itransfer);
99 static int composite_abort_control(struct usbi_transfer *itransfer);
100 static int composite_reset_device(struct libusb_device_handle *dev_handle);
101 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
105 uint64_t hires_frequency, hires_ticks_to_ps;
106 const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
107 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
109 static int concurrent_usage = -1;
110 usbi_mutex_t autoclaim_lock;
112 // NB: index 0 is for monotonic and 1 is for the thread exit event
113 HANDLE timer_thread = NULL;
114 HANDLE timer_mutex = NULL;
115 struct timespec timer_tp;
116 volatile LONG request_count[2] = {0, 1}; // last one must be > 0
117 HANDLE timer_request[2] = { NULL, NULL };
118 HANDLE timer_response = NULL;
120 bool api_winusb_available = false;
121 #define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
122 bool api_hid_available = false;
123 #define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
125 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
126 if ((guid1 != NULL) && (guid2 != NULL)) {
127 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
132 #if defined(ENABLE_LOGGING)
133 static char* guid_to_string(const GUID* guid)
135 static char guid_string[MAX_GUID_STRING_LENGTH];
137 if (guid == NULL) return NULL;
138 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
139 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
140 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
141 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
147 * Converts a windows error to human readable string
148 * uses retval as errorcode, or, if 0, use GetLastError()
150 #if defined(ENABLE_LOGGING)
151 static char *windows_error_str(uint32_t retval)
153 static char err_string[ERR_BUFFER_SIZE];
157 uint32_t error_code, format_error;
159 error_code = retval?retval:GetLastError();
161 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%u] ", error_code);
163 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
164 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
165 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
167 format_error = GetLastError();
169 safe_sprintf(err_string, ERR_BUFFER_SIZE,
170 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
172 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
174 // Remove CR/LF terminators
175 for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
184 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
185 * Return an allocated sanitized string or NULL on error.
187 static char* sanitize_path(const char* path)
189 const char root_prefix[] = "\\\\.\\";
190 size_t j, size, root_size;
191 char* ret_path = NULL;
197 size = safe_strlen(path)+1;
198 root_size = sizeof(root_prefix)-1;
200 // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
201 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
202 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
203 add_root = root_size;
207 if ((ret_path = (char*) calloc(size, 1)) == NULL)
210 safe_strcpy(&ret_path[add_root], size-add_root, path);
212 // Ensure consistancy with root prefix
213 for (j=0; j<root_size; j++)
214 ret_path[j] = root_prefix[j];
216 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
217 for(j=root_size; j<size; j++) {
218 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
219 if (ret_path[j] == '\\')
227 * Cfgmgr32, OLE32 and SetupAPI DLL functions
229 static int init_dlls(void)
231 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
232 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
233 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
234 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
235 // Prefixed to avoid conflict with header files
236 DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
237 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
238 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
239 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
240 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
241 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
242 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
243 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
244 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
245 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
246 return LIBUSB_SUCCESS;
250 * enumerate interfaces for the whole USB class
253 * dev_info: a pointer to a dev_info list
254 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
255 * usb_class: the generic USB class for which to retrieve interface details
256 * index: zero based index of the interface in the device info list
258 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
259 * structure returned and call this function repeatedly using the same guid (with an
260 * incremented index starting at zero) until all interfaces have been returned.
262 static bool get_devinfo_data(struct libusb_context *ctx,
263 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, char* usb_class, unsigned _index)
266 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
267 if (*dev_info == INVALID_HANDLE_VALUE) {
272 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
273 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
274 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
275 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
276 _index, windows_error_str(0));
278 pSetupDiDestroyDeviceInfoList(*dev_info);
279 *dev_info = INVALID_HANDLE_VALUE;
286 * enumerate interfaces for a specific GUID
289 * dev_info: a pointer to a dev_info list
290 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
291 * guid: the GUID for which to retrieve interface details
292 * index: zero based index of the interface in the device info list
294 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
295 * structure returned and call this function repeatedly using the same guid (with an
296 * incremented index starting at zero) until all interfaces have been returned.
298 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
299 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
301 SP_DEVICE_INTERFACE_DATA dev_interface_data;
302 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
306 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
309 if (dev_info_data != NULL) {
310 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
311 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
312 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
313 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
314 _index, windows_error_str(0));
316 pSetupDiDestroyDeviceInfoList(*dev_info);
317 *dev_info = INVALID_HANDLE_VALUE;
322 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
323 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
324 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
325 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
326 _index, windows_error_str(0));
328 pSetupDiDestroyDeviceInfoList(*dev_info);
329 *dev_info = INVALID_HANDLE_VALUE;
333 // Read interface data (dummy + actual) to access the device path
334 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
335 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
336 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
337 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
338 _index, windows_error_str(0));
342 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
346 if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
347 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
351 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
352 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
353 dev_interface_details, size, &size, NULL)) {
354 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
355 _index, windows_error_str(0));
358 return dev_interface_details;
361 pSetupDiDestroyDeviceInfoList(*dev_info);
362 *dev_info = INVALID_HANDLE_VALUE;
366 /* Hash table functions - modified From glibc 2.3.2:
367 [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
368 [Knuth] The Art of Computer Programming, part 3 (6.4) */
369 typedef struct htab_entry {
373 htab_entry* htab_table = NULL;
374 usbi_mutex_t htab_write_mutex = NULL;
375 unsigned long htab_size, htab_filled;
377 /* For the used double hash method the table size has to be a prime. To
378 correct the user given table size we need a prime test. This trivial
379 algorithm is adequate because the code is called only during init and
380 the number is likely to be small */
381 static int isprime(unsigned long number)
383 // no even number will be passed
384 unsigned int divider = 3;
386 while((divider * divider < number) && (number % divider != 0))
389 return (number % divider != 0);
392 /* Before using the hash table we must allocate memory for it.
393 We allocate one element more as the found prime number says.
394 This is done for more effective indexing as explained in the
395 comment for the hash function. */
396 static int htab_create(struct libusb_context *ctx, unsigned long nel)
398 if (htab_table != NULL) {
399 usbi_err(ctx, "hash table already allocated");
403 usbi_mutex_init(&htab_write_mutex, NULL);
405 // Change nel to the first prime number not smaller as nel.
411 usbi_dbg("using %d entries hash table", nel);
414 // allocate memory and zero out.
415 htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
416 if (htab_table == NULL) {
417 usbi_err(ctx, "could not allocate space for hash table");
424 /* After using the hash table it has to be destroyed. */
425 static void htab_destroy(void)
428 if (htab_table == NULL) {
432 for (i=0; i<htab_size; i++) {
433 if (htab_table[i].used) {
434 safe_free(htab_table[i].str);
437 usbi_mutex_destroy(&htab_write_mutex);
438 safe_free(htab_table);
441 /* This is the search function. It uses double hashing with open addressing.
442 We use an trick to speed up the lookup. The table is created with one
443 more element available. This enables us to use the index zero special.
444 This index will never be used because we store the first hash index in
445 the field used where zero means not used. Every other value means used.
446 The used field can be used as a first fast comparison for equality of
447 the stored and the parameter value. This helps to prevent unnecessary
448 expensive calls of strcmp. */
449 static unsigned long htab_hash(char* str)
451 unsigned long hval, hval2;
453 unsigned long r = 5381;
457 // Compute main hash value (algorithm suggested by Nokia)
459 r = ((r << 5) + r) + c;
463 // compute table hash: simply take the modulus
464 hval = r % htab_size;
468 // Try the first index
471 if (htab_table[idx].used) {
472 if ( (htab_table[idx].used == hval)
473 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
477 usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
479 // Second hash function, as suggested in [Knuth]
480 hval2 = 1 + hval % (htab_size - 2);
483 // Because size is prime this guarantees to step through all available indexes
485 idx = htab_size + idx - hval2;
490 // If we visited all entries leave the loop unsuccessfully
495 // If entry is found use it.
496 if ( (htab_table[idx].used == hval)
497 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
501 while (htab_table[idx].used);
504 // Not found => New entry
506 // If the table is full return an error
507 if (htab_filled >= htab_size) {
508 usbi_err(NULL, "hash table is full (%d entries)", htab_size);
512 // Concurrent threads might be storing the same entry at the same time
513 // (eg. "simultaneous" enums from different threads) => use a mutex
514 usbi_mutex_lock(&htab_write_mutex);
515 // Just free any previously allocated string (which should be the same as
516 // new one). The possibility of concurrent threads storing a collision
517 // string (same hash, different string) at the same time is extremely low
518 safe_free(htab_table[idx].str);
519 htab_table[idx].used = hval;
520 htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
521 if (htab_table[idx].str == NULL) {
522 usbi_err(NULL, "could not duplicate string for hash table");
523 usbi_mutex_unlock(&htab_write_mutex);
526 memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
528 usbi_mutex_unlock(&htab_write_mutex);
534 * Returns the session ID of a device's nth level ancestor
535 * If there's no device at the nth level, return 0
537 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
539 DWORD parent_devinst;
540 unsigned long session_id = 0;
541 char* sanitized_path = NULL;
542 char path[MAX_PATH_LENGTH];
545 if (level < 1) return 0;
546 for (i = 0; i<level; i++) {
547 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
550 devinst = parent_devinst;
552 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
555 // TODO (post hotplug): try without sanitizing
556 sanitized_path = sanitize_path(path);
557 if (sanitized_path == NULL) {
560 session_id = htab_hash(sanitized_path);
561 safe_free(sanitized_path);
566 * Populate the endpoints addresses of the device_priv interface helper structs
568 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
571 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
572 struct libusb_config_descriptor *conf_desc;
573 const struct libusb_interface_descriptor *if_desc;
574 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
576 r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
577 if (r != LIBUSB_SUCCESS) {
578 usbi_warn(ctx, "could not read config descriptor: error %d", r);
582 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
583 safe_free(priv->usb_interface[iface].endpoint);
585 if (if_desc->bNumEndpoints == 0) {
586 usbi_dbg("no endpoints found for interface %d", iface);
587 return LIBUSB_SUCCESS;
590 priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
591 if (priv->usb_interface[iface].endpoint == NULL) {
592 return LIBUSB_ERROR_NO_MEM;
595 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
596 for (i=0; i<if_desc->bNumEndpoints; i++) {
597 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
598 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
600 libusb_free_config_descriptor(conf_desc);
602 // Extra init is required for WinUSB endpoints
603 if (priv->apib->id == USB_API_WINUSB) {
604 return winusb_configure_endpoints(dev_handle, iface);
607 return LIBUSB_SUCCESS;
610 // Lookup for a match in the list of API driver names
611 static bool is_api_driver(char* driver, uint8_t api)
614 const char sep_str[2] = {LIST_SEPARATOR, 0};
616 size_t len = safe_strlen(driver);
618 if (len == 0) return false;
619 tmp_str = (char*) calloc(len+1, 1);
620 if (tmp_str == NULL) return false;
621 memcpy(tmp_str, driver, len+1);
622 tok = strtok(tmp_str, sep_str);
623 while (tok != NULL) {
624 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
625 if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
630 tok = strtok(NULL, sep_str);
637 * auto-claiming and auto-release helper functions
639 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
641 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
642 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
643 transfer->dev_handle);
644 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
645 int current_interface = *interface_number;
646 int r = LIBUSB_SUCCESS;
653 return LIBUSB_ERROR_INVALID_PARAM;
656 usbi_mutex_lock(&autoclaim_lock);
657 if (current_interface < 0) // No serviceable interface was found
659 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
660 // Must claim an interface of the same API type
661 if ( (priv->usb_interface[current_interface].apib->id == api_type)
662 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
663 usbi_dbg("auto-claimed interface %d for control request", current_interface);
664 if (handle_priv->autoclaim_count[current_interface] != 0) {
665 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
667 handle_priv->autoclaim_count[current_interface]++;
671 if (current_interface == USB_MAXINTERFACES) {
672 usbi_err(ctx, "could not auto-claim any interface");
673 r = LIBUSB_ERROR_NOT_FOUND;
676 // If we have a valid interface that was autoclaimed, we must increment
677 // its autoclaim count so that we can prevent an early release.
678 if (handle_priv->autoclaim_count[current_interface] != 0) {
679 handle_priv->autoclaim_count[current_interface]++;
682 usbi_mutex_unlock(&autoclaim_lock);
684 *interface_number = current_interface;
689 static void auto_release(struct usbi_transfer *itransfer)
691 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
692 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
693 libusb_device_handle *dev_handle = transfer->dev_handle;
694 struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
697 usbi_mutex_lock(&autoclaim_lock);
698 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
699 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
700 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
701 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
702 if (r == LIBUSB_SUCCESS) {
703 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
705 usbi_dbg("failed to auto-release interface %d (%s)",
706 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
710 usbi_mutex_unlock(&autoclaim_lock);
714 * init: libusbx backend init function
716 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
717 * In our implementation, we equate Windows' "HCD" to libusbx's "bus". Note that bus is zero indexed.
718 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
720 static int windows_init(struct libusb_context *ctx)
722 int i, r = LIBUSB_ERROR_OTHER;
723 OSVERSIONINFO os_version;
725 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
727 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
728 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
729 if (semaphore == NULL) {
730 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
731 return LIBUSB_ERROR_NO_MEM;
734 // A successful wait brings our semaphore count to 0 (unsignaled)
735 // => any concurent wait stalls until the semaphore's release
736 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
737 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
738 CloseHandle(semaphore);
739 return LIBUSB_ERROR_NO_MEM;
742 // NB: concurrent usage supposes that init calls are equally balanced with
743 // exit calls. If init is called more than exit, we will not exit properly
744 if ( ++concurrent_usage == 0 ) { // First init?
746 memset(&os_version, 0, sizeof(OSVERSIONINFO));
747 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
748 windows_version = WINDOWS_UNSUPPORTED;
749 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
750 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
751 windows_version = WINDOWS_XP;
752 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
753 windows_version = WINDOWS_2003; // also includes XP 64
754 } else if (os_version.dwMajorVersion >= 6) {
755 windows_version = WINDOWS_VISTA_AND_LATER;
758 if (windows_version == WINDOWS_UNSUPPORTED) {
759 usbi_err(ctx, "This version of Windows is NOT supported");
760 r = LIBUSB_ERROR_NOT_SUPPORTED;
764 // We need a lock for proper auto-release
765 usbi_mutex_init(&autoclaim_lock, NULL);
767 // Initialize pollable file descriptors
771 if (init_dlls() != LIBUSB_SUCCESS) {
772 usbi_err(ctx, "could not resolve DLL functions");
773 return LIBUSB_ERROR_NOT_FOUND;
776 // Initialize the low level APIs (we don't care about errors at this stage)
777 for (i=0; i<USB_API_MAX; i++) {
778 usb_api_backend[i].init(ctx);
781 // Because QueryPerformanceCounter might report different values when
782 // running on different cores, we create a separate thread for the timer
783 // calls, which we glue to the first core always to prevent timing discrepancies.
784 r = LIBUSB_ERROR_NO_MEM;
785 for (i = 0; i < 2; i++) {
786 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
787 if (timer_request[i] == NULL) {
788 usbi_err(ctx, "could not create timer request event %d - aborting", i);
792 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
793 if (timer_response == NULL) {
794 usbi_err(ctx, "could not create timer response semaphore - aborting");
797 timer_mutex = CreateMutex(NULL, FALSE, NULL);
798 if (timer_mutex == NULL) {
799 usbi_err(ctx, "could not create timer mutex - aborting");
802 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
803 if (timer_thread == NULL) {
804 usbi_err(ctx, "Unable to create timer thread - aborting");
807 SetThreadAffinityMask(timer_thread, 0);
809 // Create a hash table to store session ids. Second parameter is better if prime
810 htab_create(ctx, HTAB_SIZE);
812 // At this stage, either we went through full init successfully, or didn't need to
815 init_exit: // Holds semaphore here.
816 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
818 SetEvent(timer_request[1]); // actually the signal to quit the thread.
819 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
820 usbi_warn(ctx, "could not wait for timer thread to quit");
821 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
822 // all objects it might have held anyway.
824 CloseHandle(timer_thread);
827 for (i = 0; i < 2; i++) {
828 if (timer_request[i]) {
829 CloseHandle(timer_request[i]);
830 timer_request[i] = NULL;
833 if (timer_response) {
834 CloseHandle(timer_response);
835 timer_response = NULL;
838 CloseHandle(timer_mutex);
844 if (r != LIBUSB_SUCCESS)
845 --concurrent_usage; // Not expected to call libusb_exit if we failed.
847 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
848 CloseHandle(semaphore);
853 * HCD (root) hubs need to have their device descriptor manually populated
855 * Note that, like Microsoft does in the device manager, we populate the
856 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
858 static int force_hcd_device_descriptor(struct libusb_device *dev)
860 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
861 struct libusb_context *ctx = DEVICE_CTX(dev);
864 dev->num_configurations = 1;
865 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
866 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
867 priv->dev_descriptor.bNumConfigurations = 1;
868 priv->active_config = 1;
870 if (priv->parent_dev == NULL) {
871 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
872 return LIBUSB_ERROR_NO_DEVICE;
874 parent_priv = _device_priv(priv->parent_dev);
875 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
876 priv->dev_descriptor.idVendor = (uint16_t)vid;
877 priv->dev_descriptor.idProduct = (uint16_t)pid;
879 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
880 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
881 priv->dev_descriptor.idProduct = 1;
883 return LIBUSB_SUCCESS;
887 * fetch and cache all the config descriptors through I/O
889 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
891 DWORD size, ret_size;
892 struct libusb_context *ctx = DEVICE_CTX(dev);
893 struct windows_device_priv *priv = _device_priv(dev);
897 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
898 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
899 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
901 if (dev->num_configurations == 0)
902 return LIBUSB_ERROR_INVALID_PARAM;
904 priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(unsigned char*));
905 if (priv->config_descriptor == NULL)
906 return LIBUSB_ERROR_NO_MEM;
907 for (i=0; i<dev->num_configurations; i++)
908 priv->config_descriptor[i] = NULL;
910 for (i=0, r=LIBUSB_SUCCESS; ; i++)
912 // safe loop: release all dynamic resources
913 safe_free(cd_buf_actual);
915 // safe loop: end of loop condition
916 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
919 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
920 memset(&cd_buf_short, 0, size);
922 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
923 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
924 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
925 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
926 cd_buf_short.req.SetupPacket.wIndex = i;
927 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
929 // Dummy call to get the required data size. Initial failures are reported as info rather
930 // than error as they can occur for non-penalizing situations, such as with some hubs.
931 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
932 &cd_buf_short, size, &ret_size, NULL)) {
933 usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
934 LOOP_BREAK(LIBUSB_ERROR_IO);
937 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
938 usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
939 LOOP_BREAK(LIBUSB_ERROR_IO);
942 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
943 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
944 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
945 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
947 memset(cd_buf_actual, 0, size);
950 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
951 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
952 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
953 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
954 cd_buf_actual->SetupPacket.wIndex = i;
955 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
957 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
958 cd_buf_actual, size, &ret_size, NULL)) {
959 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
960 LOOP_BREAK(LIBUSB_ERROR_IO);
963 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
965 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
966 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
967 LOOP_BREAK(LIBUSB_ERROR_IO);
970 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
971 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
972 LOOP_BREAK(LIBUSB_ERROR_IO);
975 usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
976 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
978 // Cache the descriptor
979 priv->config_descriptor[i] = (unsigned char*) malloc(cd_data->wTotalLength);
980 if (priv->config_descriptor[i] == NULL)
981 return LIBUSB_ERROR_NO_MEM;
982 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
984 return LIBUSB_SUCCESS;
988 * Populate a libusbx device structure
990 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
991 uint8_t port_number, char* device_id, DWORD devinst)
995 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
996 struct windows_device_priv *priv, *parent_priv;
997 struct libusb_context *ctx = DEVICE_CTX(dev);
998 struct libusb_device* tmp_dev;
1001 if ((dev == NULL) || (parent_dev == NULL)) {
1002 return LIBUSB_ERROR_NOT_FOUND;
1004 priv = _device_priv(dev);
1005 parent_priv = _device_priv(parent_dev);
1006 if (parent_priv->apib->id != USB_API_HUB) {
1007 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1008 return LIBUSB_ERROR_NOT_FOUND;
1011 // It is possible for the parent hub not to have been initialized yet
1012 // If that's the case, lookup the ancestors to set the bus number
1013 if (parent_dev->bus_number == 0) {
1015 tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
1016 if (tmp_dev == NULL) break;
1017 if (tmp_dev->bus_number != 0) {
1018 usbi_dbg("got bus number from ancestor #%d", i);
1019 parent_dev->bus_number = tmp_dev->bus_number;
1024 if (parent_dev->bus_number == 0) {
1025 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1026 return LIBUSB_ERROR_NOT_FOUND;
1028 dev->bus_number = parent_dev->bus_number;
1029 priv->port = port_number;
1030 dev->port_number = port_number;
1031 priv->depth = parent_priv->depth + 1;
1032 priv->parent_dev = parent_dev;
1033 dev->parent_dev = parent_dev;
1035 // If the device address is already set, we can stop here
1036 if (dev->device_address != 0) {
1037 return LIBUSB_SUCCESS;
1039 memset(&conn_info, 0, sizeof(conn_info));
1040 if (priv->depth != 0) { // Not a HCD hub
1041 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1042 FILE_FLAG_OVERLAPPED, NULL);
1043 if (handle == INVALID_HANDLE_VALUE) {
1044 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1045 return LIBUSB_ERROR_ACCESS;
1047 size = sizeof(conn_info);
1048 conn_info.ConnectionIndex = (ULONG)port_number;
1049 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1050 &conn_info, size, &size, NULL)) {
1051 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1052 device_id, windows_error_str(0));
1053 safe_closehandle(handle);
1054 return LIBUSB_ERROR_NO_DEVICE;
1056 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1057 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1058 safe_closehandle(handle);
1059 return LIBUSB_ERROR_NO_DEVICE;
1061 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1062 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1063 priv->active_config = conn_info.CurrentConfigurationValue;
1064 usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
1065 // If we can't read the config descriptors, just set the number of confs to zero
1066 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1067 dev->num_configurations = 0;
1068 priv->dev_descriptor.bNumConfigurations = 0;
1070 safe_closehandle(handle);
1072 if (conn_info.DeviceAddress > UINT8_MAX) {
1073 usbi_err(ctx, "program assertion failed: device address overflow");
1075 dev->device_address = (uint8_t)conn_info.DeviceAddress;
1076 switch (conn_info.Speed) {
1077 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1078 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1079 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1080 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1082 usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1086 dev->device_address = UINT8_MAX; // Hubs from HCD have a devaddr of 255
1087 force_hcd_device_descriptor(dev);
1090 usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1091 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1093 return LIBUSB_SUCCESS;
1096 // Returns the api type, or 0 if not found/unsupported
1097 static uint8_t get_api_type(struct libusb_context *ctx,
1098 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
1100 // Precedence for filter drivers vs driver is in the order of this array
1101 struct driver_lookup lookup[3] = {
1102 {"\0\0", SPDRP_SERVICE, "driver"},
1103 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1104 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1106 DWORD size, reg_type;
1110 // Check the service & filter names to know the API we should use
1111 for (k=0; k<3; k++) {
1112 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1113 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1114 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1115 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1116 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1117 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1119 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1120 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1121 // (currently ';'), so even if an unsuported one does, it's not an issue
1122 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1123 if (lookup[k].list[l] == 0) {
1124 lookup[k].list[l] = LIST_SEPARATOR;
1127 upperize(lookup[k].list);
1128 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1130 if (GetLastError() != ERROR_INVALID_DATA) {
1131 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1133 lookup[k].list[0] = 0;
1137 for (api=1; api<USB_API_MAX; api++) {
1138 for (k=0; k<3; k++) {
1139 if (is_api_driver(lookup[k].list, api)) {
1140 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1144 if (k >= 3) continue;
1150 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1151 char* dev_interface_path, char* device_id, uint8_t api)
1154 struct windows_device_priv *priv = _device_priv(dev);
1155 int interface_number;
1157 if (priv->apib->id != USB_API_COMPOSITE) {
1158 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1159 return LIBUSB_ERROR_NO_DEVICE;
1162 // Because MI_## are not necessarily in sequential order (some composite
1163 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1164 // interface number from the path's MI value
1165 interface_number = 0;
1166 for (i=0; device_id[i] != 0; ) {
1167 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1168 && (device_id[i++] == '_') ) {
1169 interface_number = (device_id[i++] - '0')*10;
1170 interface_number += device_id[i] - '0';
1175 if (device_id[i] == 0) {
1176 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1177 device_id, interface_number);
1180 // HID devices can have multiple collections (COL##) for each MI_## interface
1181 if (priv->usb_interface[interface_number].path != NULL) {
1182 if (api != USB_API_HID) {
1183 usbi_warn(ctx, "program assertion failed %s is not an USB HID collection", device_id);
1184 return LIBUSB_ERROR_OTHER;
1186 usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1187 interface_number, device_id);
1188 return LIBUSB_ERROR_ACCESS;
1191 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1192 priv->usb_interface[interface_number].path = dev_interface_path;
1193 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1194 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1195 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1197 priv->composite_api_flags |= 1<<api;
1199 return LIBUSB_SUCCESS;
1202 static int set_hid_interface(struct libusb_context* ctx, struct libusb_device* dev,
1203 char* dev_interface_path)
1205 struct windows_device_priv *priv = _device_priv(dev);
1207 if (priv->hid == NULL) {
1208 usbi_err(ctx, "program assertion failed: parent is not HID");
1209 return LIBUSB_ERROR_NO_DEVICE;
1211 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1212 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1213 usbi_dbg("interface[%d] = %s", priv->hid->nb_interfaces, dev_interface_path);
1214 priv->hid->nb_interfaces++;
1215 return LIBUSB_SUCCESS;
1219 * get_device_list: libusbx backend device enumeration function
1221 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1223 struct discovered_devs *discdevs;
1224 HDEVINFO dev_info = { 0 };
1225 char* usb_class[2] = {"USB", "NUSB3"};
1226 SP_DEVINFO_DATA dev_info_data;
1227 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1229 #define MAX_ENUM_GUIDS 64
1230 const GUID* guid[MAX_ENUM_GUIDS];
1236 int r = LIBUSB_SUCCESS;
1237 int class_index = 0;
1238 unsigned int nb_guids, pass, i, j, ancestor;
1239 char path[MAX_PATH_LENGTH];
1240 char strbuf[MAX_PATH_LENGTH];
1241 struct libusb_device *dev, *parent_dev;
1242 struct windows_device_priv *priv, *parent_priv;
1243 char* dev_interface_path = NULL;
1244 char* dev_id_path = NULL;
1245 unsigned long session_id;
1246 DWORD size, reg_type, port_nr, install_state;
1249 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1253 // Keep a list of newly allocated devs to unref
1254 libusb_device** unref_list;
1255 unsigned int unref_size = 64;
1256 unsigned int unref_cur = 0;
1258 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1259 // PASS 2 : (re)enumerate HUBS
1260 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1261 // and list additional USB device interface GUIDs to explore
1262 // PASS 4 : (re)enumerate master USB devices that have a device interface
1263 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1264 // set the device interfaces.
1266 // Init the GUID table
1267 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1268 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1269 guid[GEN_PASS] = NULL;
1270 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1271 HidD_GetHidGuid(&hid_guid);
1272 guid[HID_PASS] = &hid_guid;
1273 nb_guids = HID_PASS+1;
1275 unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
1276 if (unref_list == NULL) {
1277 return LIBUSB_ERROR_NO_MEM;
1280 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1281 //#define ENUM_DEBUG
1285 usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
1288 usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
1291 usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
1294 usbi_dbg("PROCESSING GENs");
1297 usbi_dbg("PROCESSING HIDs %s", guid_to_string(guid[pass]));
1300 usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
1304 for (i = 0; ; i++) {
1305 // safe loop: free up any (unprotected) dynamic resource
1306 // NB: this is always executed before breaking the loop
1307 safe_free(dev_interface_details);
1308 safe_free(dev_interface_path);
1309 safe_free(dev_id_path);
1310 priv = parent_priv = NULL;
1311 dev = parent_dev = NULL;
1313 // Safe loop: end of loop conditions
1314 if (r != LIBUSB_SUCCESS) {
1317 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1318 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1321 if (pass != GEN_PASS) {
1322 // Except for GEN, all passes deal with device interfaces
1323 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1324 if (dev_interface_details == NULL) {
1327 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1328 if (dev_interface_path == NULL) {
1329 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1334 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1335 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
1336 while ( (class_index < 2) &&
1337 (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
1344 // Read the Device ID path. This is what we'll use as UID
1345 // Note that if the device is plugged in a different port or hub, the Device ID changes
1346 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1347 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1348 dev_info_data.DevInst);
1351 dev_id_path = sanitize_path(path);
1352 if (dev_id_path == NULL) {
1353 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1354 dev_info_data.DevInst);
1358 usbi_dbg("PRO: %s", dev_id_path);
1361 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1363 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1364 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1365 ®_type, (BYTE*)&port_nr, 4, &size))
1367 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1368 dev_id_path, windows_error_str(0));
1373 // Set API to use or get additional data from generic pass
1374 api = USB_API_UNSUPPORTED;
1379 // We use the GEN pass to detect driverless devices...
1380 size = sizeof(strbuf);
1381 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1382 ®_type, (BYTE*)strbuf, size, &size)) {
1383 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1384 usbi_info(ctx, "libusbx will not be able to access it.");
1386 // ...and to add the additional device interface GUIDs
1387 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1388 if (key != INVALID_HANDLE_VALUE) {
1389 size = sizeof(guid_string_w);
1390 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1391 (BYTE*)guid_string_w, &size);
1393 if (s == ERROR_SUCCESS) {
1394 if (nb_guids >= MAX_ENUM_GUIDS) {
1395 // If this assert is ever reported, grow a GUID table dynamically
1396 usbi_err(ctx, "program assertion failed: too many GUIDs");
1397 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1399 if_guid = (GUID*) calloc(1, sizeof(GUID));
1400 pCLSIDFromString(guid_string_w, if_guid);
1401 guid[nb_guids++] = if_guid;
1402 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1410 // Get the API type (after checking that the driver installation is OK)
1411 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1412 ®_type, (BYTE*)&install_state, 4, &size))
1414 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1415 dev_id_path, windows_error_str(0));
1416 } else if (install_state != 0) {
1417 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1418 dev_id_path, install_state);
1421 api = get_api_type(ctx, &dev_info, &dev_info_data);
1425 // Find parent device (for the passes that need it)
1432 // Go through the ancestors until we see a face we recognize
1434 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1435 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1436 if (session_id == 0) {
1439 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1441 if (parent_dev == NULL) {
1442 usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1445 parent_priv = _device_priv(parent_dev);
1446 // virtual USB devices are also listed during GEN - don't process these yet
1447 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1453 // Create new or match existing device, using the (hashed) device_id as session id
1454 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1455 // These are the passes that create "new" devices
1456 session_id = htab_hash(dev_id_path);
1457 dev = usbi_get_device_by_session_id(ctx, session_id);
1459 if (pass == DEV_PASS) {
1460 // This can occur if the OS only reports a newly plugged device after we started enum
1461 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1462 " - ignoring", dev_id_path);
1465 usbi_dbg("allocating new device for session [%X]", session_id);
1466 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1467 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1469 windows_device_priv_init(dev);
1470 // Keep track of devices that need unref
1471 unref_list[unref_cur++] = dev;
1472 if (unref_cur >= unref_size) {
1474 unref_list = usbi_reallocf(unref_list, unref_size*sizeof(libusb_device*));
1475 if (unref_list == NULL) {
1476 usbi_err(ctx, "could not realloc list for unref - aborting.");
1477 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1481 usbi_dbg("found existing device for session [%X] (%d.%d)",
1482 session_id, dev->bus_number, dev->device_address);
1484 priv = _device_priv(dev);
1490 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1491 dev->device_address = 0;
1492 dev->num_configurations = 0;
1493 priv->apib = &usb_api_backend[USB_API_HUB];
1494 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1495 priv->path = dev_interface_path; dev_interface_path = NULL;
1499 // If the device has already been setup, don't do it again
1500 if (priv->path != NULL)
1502 // Take care of API initialization
1503 priv->path = dev_interface_path; dev_interface_path = NULL;
1504 priv->apib = &usb_api_backend[api];
1506 case USB_API_COMPOSITE:
1510 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1511 if (priv->hid == NULL) {
1512 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1514 priv->hid->nb_interfaces = 0;
1517 // For other devices, the first interface is the same as the device
1518 priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
1519 if (priv->usb_interface[0].path != NULL) {
1520 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1522 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1524 // The following is needed if we want API calls to work for both simple
1525 // and composite devices.
1526 for(j=0; j<USB_MAXINTERFACES; j++) {
1527 priv->usb_interface[j].apib = &usb_api_backend[api];
1533 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1534 if (r == LIBUSB_SUCCESS) {
1535 // Append device to the list of discovered devices
1536 discdevs = discovered_devs_append(*_discdevs, dev);
1538 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1540 *_discdevs = discdevs;
1541 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1542 // This can occur if the device was disconnected but Windows hasn't
1543 // refreshed its enumeration yet - in that case, we ignore the device
1547 default: // HID_PASS and later
1548 if (parent_priv->apib->id == USB_API_HID) {
1549 usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1550 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1551 if (r != LIBUSB_SUCCESS) LOOP_BREAK(r);
1552 dev_interface_path = NULL;
1553 } else if (parent_priv->apib->id == USB_API_COMPOSITE) {
1554 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1555 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
1556 case LIBUSB_SUCCESS:
1557 dev_interface_path = NULL;
1559 case LIBUSB_ERROR_ACCESS:
1560 // interface has already been set => make sure dev_interface_path is freed then
1572 // Free any additional GUIDs
1573 for (pass = HID_PASS+1; pass < nb_guids; pass++) {
1574 safe_free(guid[pass]);
1577 // Unref newly allocated devs
1578 for (i=0; i<unref_cur; i++) {
1579 safe_unref_device(unref_list[i]);
1581 safe_free(unref_list);
1587 * exit: libusbx backend deinitialization function
1589 static void windows_exit(void)
1593 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1595 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1596 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1597 if (semaphore == NULL) {
1601 // A successful wait brings our semaphore count to 0 (unsignaled)
1602 // => any concurent wait stalls until the semaphore release
1603 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1604 CloseHandle(semaphore);
1608 // Only works if exits and inits are balanced exactly
1609 if (--concurrent_usage < 0) { // Last exit
1610 for (i=0; i<USB_API_MAX; i++) {
1611 usb_api_backend[i].exit();
1616 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1617 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1618 usbi_dbg("could not wait for timer thread to quit");
1619 TerminateThread(timer_thread, 1);
1621 CloseHandle(timer_thread);
1622 timer_thread = NULL;
1624 for (i = 0; i < 2; i++) {
1625 if (timer_request[i]) {
1626 CloseHandle(timer_request[i]);
1627 timer_request[i] = NULL;
1630 if (timer_response) {
1631 CloseHandle(timer_response);
1632 timer_response = NULL;
1635 CloseHandle(timer_mutex);
1641 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1642 CloseHandle(semaphore);
1645 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1647 struct windows_device_priv *priv = _device_priv(dev);
1649 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1652 return LIBUSB_SUCCESS;
1655 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1657 struct windows_device_priv *priv = _device_priv(dev);
1658 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1661 // config index is zero based
1662 if (config_index >= dev->num_configurations)
1663 return LIBUSB_ERROR_INVALID_PARAM;
1665 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1666 return LIBUSB_ERROR_NOT_FOUND;
1668 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1670 size = min(config_header->wTotalLength, len);
1671 memcpy(buffer, priv->config_descriptor[config_index], size);
1673 return LIBUSB_SUCCESS;
1677 * return the cached copy of the active config descriptor
1679 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1681 struct windows_device_priv *priv = _device_priv(dev);
1683 if (priv->active_config == 0)
1684 return LIBUSB_ERROR_NOT_FOUND;
1686 // config index is zero based
1687 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1690 static int windows_open(struct libusb_device_handle *dev_handle)
1692 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1693 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1695 if (priv->apib == NULL) {
1696 usbi_err(ctx, "program assertion failed - device is not initialized");
1697 return LIBUSB_ERROR_NO_DEVICE;
1700 return priv->apib->open(dev_handle);
1703 static void windows_close(struct libusb_device_handle *dev_handle)
1705 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1707 priv->apib->close(dev_handle);
1710 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1712 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1714 if (priv->active_config == 0) {
1716 return LIBUSB_ERROR_NOT_FOUND;
1719 *config = priv->active_config;
1720 return LIBUSB_SUCCESS;
1724 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1725 * does not currently expose a service that allows higher-level drivers to set
1726 * the configuration."
1728 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1730 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1731 int r = LIBUSB_SUCCESS;
1733 if (config >= USB_MAXCONFIG)
1734 return LIBUSB_ERROR_INVALID_PARAM;
1736 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1737 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1738 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1741 if (r == LIBUSB_SUCCESS) {
1742 priv->active_config = (uint8_t)config;
1747 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1749 int r = LIBUSB_SUCCESS;
1750 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1752 if (iface >= USB_MAXINTERFACES)
1753 return LIBUSB_ERROR_INVALID_PARAM;
1755 safe_free(priv->usb_interface[iface].endpoint);
1756 priv->usb_interface[iface].nb_endpoints= 0;
1758 r = priv->apib->claim_interface(dev_handle, iface);
1760 if (r == LIBUSB_SUCCESS) {
1761 r = windows_assign_endpoints(dev_handle, iface, 0);
1767 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1769 int r = LIBUSB_SUCCESS;
1770 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1772 safe_free(priv->usb_interface[iface].endpoint);
1773 priv->usb_interface[iface].nb_endpoints= 0;
1775 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1777 if (r == LIBUSB_SUCCESS) {
1778 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1784 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1786 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1788 return priv->apib->release_interface(dev_handle, iface);
1791 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1793 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1794 return priv->apib->clear_halt(dev_handle, endpoint);
1797 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1799 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1800 return priv->apib->reset_device(dev_handle);
1803 // The 3 functions below are unlikely to ever get supported on Windows
1804 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1806 return LIBUSB_ERROR_NOT_SUPPORTED;
1809 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1811 return LIBUSB_ERROR_NOT_SUPPORTED;
1814 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1816 return LIBUSB_ERROR_NOT_SUPPORTED;
1819 static void windows_destroy_device(struct libusb_device *dev)
1821 windows_device_priv_release(dev);
1824 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1826 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1828 usbi_free_fd(transfer_priv->pollable_fd.fd);
1829 safe_free(transfer_priv->hid_buffer);
1830 // When auto claim is in use, attempt to release the auto-claimed interface
1831 auto_release(itransfer);
1834 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1836 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1837 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1838 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1839 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1842 r = priv->apib->submit_bulk_transfer(itransfer);
1843 if (r != LIBUSB_SUCCESS) {
1847 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1848 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1850 itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
1851 return LIBUSB_SUCCESS;
1854 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1856 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1857 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1858 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1859 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1862 r = priv->apib->submit_iso_transfer(itransfer);
1863 if (r != LIBUSB_SUCCESS) {
1867 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1868 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1870 itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
1871 return LIBUSB_SUCCESS;
1874 static int submit_control_transfer(struct usbi_transfer *itransfer)
1876 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1877 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1878 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1879 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1882 r = priv->apib->submit_control_transfer(itransfer);
1883 if (r != LIBUSB_SUCCESS) {
1887 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1889 itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
1890 return LIBUSB_SUCCESS;
1894 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1896 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1898 switch (transfer->type) {
1899 case LIBUSB_TRANSFER_TYPE_CONTROL:
1900 return submit_control_transfer(itransfer);
1901 case LIBUSB_TRANSFER_TYPE_BULK:
1902 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1903 if (IS_XFEROUT(transfer) &&
1904 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1905 return LIBUSB_ERROR_NOT_SUPPORTED;
1906 return submit_bulk_transfer(itransfer);
1907 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1908 return submit_iso_transfer(itransfer);
1910 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1911 return LIBUSB_ERROR_INVALID_PARAM;
1915 static int windows_abort_control(struct usbi_transfer *itransfer)
1917 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1918 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1920 return priv->apib->abort_control(itransfer);
1923 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1925 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1926 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1928 return priv->apib->abort_transfers(itransfer);
1931 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1933 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1935 switch (transfer->type) {
1936 case LIBUSB_TRANSFER_TYPE_CONTROL:
1937 return windows_abort_control(itransfer);
1938 case LIBUSB_TRANSFER_TYPE_BULK:
1939 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1940 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1941 return windows_abort_transfers(itransfer);
1943 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1944 return LIBUSB_ERROR_INVALID_PARAM;
1948 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1950 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1951 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1954 usbi_dbg("handling I/O completion with errcode %d", io_result);
1958 status = priv->apib->copy_transfer_data(itransfer, io_size);
1960 case ERROR_GEN_FAILURE:
1961 usbi_dbg("detected endpoint stall");
1962 status = LIBUSB_TRANSFER_STALL;
1964 case ERROR_SEM_TIMEOUT:
1965 usbi_dbg("detected semaphore timeout");
1966 status = LIBUSB_TRANSFER_TIMED_OUT;
1968 case ERROR_OPERATION_ABORTED:
1969 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1970 usbi_dbg("detected timeout");
1971 status = LIBUSB_TRANSFER_TIMED_OUT;
1973 usbi_dbg("detected operation aborted");
1974 status = LIBUSB_TRANSFER_CANCELLED;
1978 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
1979 status = LIBUSB_TRANSFER_ERROR;
1982 windows_clear_transfer_priv(itransfer); // Cancel polling
1983 usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
1986 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1988 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1990 switch (transfer->type) {
1991 case LIBUSB_TRANSFER_TYPE_CONTROL:
1992 case LIBUSB_TRANSFER_TYPE_BULK:
1993 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1994 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1995 windows_transfer_callback (itransfer, io_result, io_size);
1998 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2002 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2004 struct windows_transfer_priv* transfer_priv = NULL;
2005 POLL_NFDS_TYPE i = 0;
2007 struct usbi_transfer *transfer;
2008 DWORD io_size, io_result;
2010 usbi_mutex_lock(&ctx->open_devs_lock);
2011 for (i = 0; i < nfds && num_ready > 0; i++) {
2013 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2015 if (!fds[i].revents) {
2021 // Because a Windows OVERLAPPED is used for poll emulation,
2022 // a pollable fd is created and stored with each transfer
2023 usbi_mutex_lock(&ctx->flying_transfers_lock);
2024 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2025 transfer_priv = usbi_transfer_get_os_priv(transfer);
2026 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2031 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2034 // Handle async requests that completed synchronously first
2035 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2036 io_result = NO_ERROR;
2037 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2038 // Regular async overlapped
2039 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2040 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2041 io_result = NO_ERROR;
2043 io_result = GetLastError();
2045 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2046 // let handle_callback free the event using the transfer wfd
2047 // If you don't use the transfer wfd, you run a risk of trying to free a
2048 // newly allocated wfd that took the place of the one from the transfer.
2049 windows_handle_callback(transfer, io_result, io_size);
2051 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2052 return LIBUSB_ERROR_NOT_FOUND;
2056 usbi_mutex_unlock(&ctx->open_devs_lock);
2057 return LIBUSB_SUCCESS;
2061 * Monotonic and real time functions
2063 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2065 LARGE_INTEGER hires_counter, li_frequency;
2069 // Init - find out if we have access to a monotonic (hires) timer
2070 if (!QueryPerformanceFrequency(&li_frequency)) {
2071 usbi_dbg("no hires timer available on this platform");
2072 hires_frequency = 0;
2073 hires_ticks_to_ps = UINT64_C(0);
2075 hires_frequency = li_frequency.QuadPart;
2076 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2077 // to picoseconds to compute the tv_nsecs part in clock_gettime
2078 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2079 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2082 // Main loop - wait for requests
2084 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2085 if ( (timer_index != 0) && (timer_index != 1) ) {
2086 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2089 if (request_count[timer_index] == 0) {
2090 // Request already handled
2091 ResetEvent(timer_request[timer_index]);
2092 // There's still a possiblity that a thread sends a request between the
2093 // time we test request_count[] == 0 and we reset the event, in which case
2094 // the request would be ignored. The simple solution to that is to test
2095 // request_count again and process requests if non zero.
2096 if (request_count[timer_index] == 0)
2099 switch (timer_index) {
2101 WaitForSingleObject(timer_mutex, INFINITE);
2102 // Requests to this thread are for hires always
2103 if (QueryPerformanceCounter(&hires_counter) != 0) {
2104 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2105 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2107 // Fallback to real-time if we can't get monotonic value
2108 // Note that real-time clock does not wait on the mutex or this thread.
2109 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2111 ReleaseMutex(timer_mutex);
2113 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2115 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2116 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2119 case 1: // time to quit
2120 usbi_dbg("timer thread quitting");
2126 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2129 ULARGE_INTEGER rtime;
2132 case USBI_CLOCK_MONOTONIC:
2133 if (hires_frequency != 0) {
2135 InterlockedIncrement((LONG*)&request_count[0]);
2136 SetEvent(timer_request[0]);
2137 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2140 WaitForSingleObject(timer_mutex, INFINITE);
2142 ReleaseMutex(timer_mutex);
2143 return LIBUSB_SUCCESS;
2145 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2146 break; // Retry until successful
2148 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2149 return LIBUSB_ERROR_OTHER;
2153 // Fall through and return real-time if monotonic was not detected @ timer init
2154 case USBI_CLOCK_REALTIME:
2155 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2156 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2157 // Note however that our resolution is bounded by the Windows system time
2158 // functions and is at best of the order of 1 ms (or, usually, worse)
2159 GetSystemTimeAsFileTime(&filetime);
2160 rtime.LowPart = filetime.dwLowDateTime;
2161 rtime.HighPart = filetime.dwHighDateTime;
2162 rtime.QuadPart -= epoch_time;
2163 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2164 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2165 return LIBUSB_SUCCESS;
2167 return LIBUSB_ERROR_INVALID_PARAM;
2172 // NB: MSVC6 does not support named initializers.
2173 const struct usbi_os_backend windows_backend = {
2178 windows_get_device_list,
2182 windows_get_device_descriptor,
2183 windows_get_active_config_descriptor,
2184 windows_get_config_descriptor,
2186 windows_get_configuration,
2187 windows_set_configuration,
2188 windows_claim_interface,
2189 windows_release_interface,
2191 windows_set_interface_altsetting,
2193 windows_reset_device,
2195 windows_kernel_driver_active,
2196 windows_detach_kernel_driver,
2197 windows_attach_kernel_driver,
2199 windows_destroy_device,
2201 windows_submit_transfer,
2202 windows_cancel_transfer,
2203 windows_clear_transfer_priv,
2205 windows_handle_events,
2207 windows_clock_gettime,
2208 #if defined(USBI_TIMERFD_AVAILABLE)
2211 sizeof(struct windows_device_priv),
2212 sizeof(struct windows_device_handle_priv),
2213 sizeof(struct windows_transfer_priv),
2221 static int unsupported_init(struct libusb_context *ctx) {
2222 return LIBUSB_SUCCESS;
2224 static int unsupported_exit(void) {
2225 return LIBUSB_SUCCESS;
2227 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2228 PRINT_UNSUPPORTED_API(open);
2230 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2231 usbi_dbg("unsupported API call for 'close'");
2233 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2234 PRINT_UNSUPPORTED_API(claim_interface);
2236 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2237 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2239 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2240 PRINT_UNSUPPORTED_API(release_interface);
2242 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2243 PRINT_UNSUPPORTED_API(clear_halt);
2245 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2246 PRINT_UNSUPPORTED_API(reset_device);
2248 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2249 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2251 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2252 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2254 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2255 PRINT_UNSUPPORTED_API(submit_control_transfer);
2257 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2258 PRINT_UNSUPPORTED_API(abort_control);
2260 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2261 PRINT_UNSUPPORTED_API(abort_transfers);
2263 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2264 PRINT_UNSUPPORTED_API(copy_transfer_data);
2267 // These names must be uppercase
2268 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
2269 const char* composite_driver_names[] = {"USBCCGP"};
2270 const char* winusb_driver_names[] = {"WINUSB"};
2271 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2272 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2274 USB_API_UNSUPPORTED,
2276 &CLASS_GUID_UNSUPPORTED,
2283 unsupported_claim_interface,
2284 unsupported_set_interface_altsetting,
2285 unsupported_release_interface,
2286 unsupported_clear_halt,
2287 unsupported_reset_device,
2288 unsupported_submit_bulk_transfer,
2289 unsupported_submit_iso_transfer,
2290 unsupported_submit_control_transfer,
2291 unsupported_abort_control,
2292 unsupported_abort_transfers,
2293 unsupported_copy_transfer_data,
2297 &CLASS_GUID_UNSUPPORTED,
2299 sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
2304 unsupported_claim_interface,
2305 unsupported_set_interface_altsetting,
2306 unsupported_release_interface,
2307 unsupported_clear_halt,
2308 unsupported_reset_device,
2309 unsupported_submit_bulk_transfer,
2310 unsupported_submit_iso_transfer,
2311 unsupported_submit_control_transfer,
2312 unsupported_abort_control,
2313 unsupported_abort_transfers,
2314 unsupported_copy_transfer_data,
2318 &CLASS_GUID_COMPOSITE,
2319 composite_driver_names,
2320 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2325 composite_claim_interface,
2326 composite_set_interface_altsetting,
2327 composite_release_interface,
2328 composite_clear_halt,
2329 composite_reset_device,
2330 composite_submit_bulk_transfer,
2331 composite_submit_iso_transfer,
2332 composite_submit_control_transfer,
2333 composite_abort_control,
2334 composite_abort_transfers,
2335 composite_copy_transfer_data,
2339 &CLASS_GUID_LIBUSB_WINUSB,
2340 winusb_driver_names,
2341 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2346 winusb_claim_interface,
2347 winusb_set_interface_altsetting,
2348 winusb_release_interface,
2350 winusb_reset_device,
2351 winusb_submit_bulk_transfer,
2352 unsupported_submit_iso_transfer,
2353 winusb_submit_control_transfer,
2354 winusb_abort_control,
2355 winusb_abort_transfers,
2356 winusb_copy_transfer_data,
2362 sizeof(hid_driver_names)/sizeof(hid_driver_names[0]),
2367 hid_claim_interface,
2368 hid_set_interface_altsetting,
2369 hid_release_interface,
2372 hid_submit_bulk_transfer,
2373 unsupported_submit_iso_transfer,
2374 hid_submit_control_transfer,
2375 hid_abort_transfers,
2376 hid_abort_transfers,
2377 hid_copy_transfer_data,
2383 * WinUSB API functions
2385 static int winusb_init(struct libusb_context *ctx)
2387 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2388 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2389 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2390 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2391 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2392 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2393 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2394 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2395 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2396 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2397 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2398 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2399 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2400 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2401 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2402 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2403 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2405 api_winusb_available = true;
2406 return LIBUSB_SUCCESS;
2409 static int winusb_exit(void)
2411 return LIBUSB_SUCCESS;
2414 // NB: open and close must ensure that they only handle interface of
2415 // the right API type, as these functions can be called wholesale from
2416 // composite_open(), with interfaces belonging to different APIs
2417 static int winusb_open(struct libusb_device_handle *dev_handle)
2419 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2420 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2421 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2426 CHECK_WINUSB_AVAILABLE;
2428 // WinUSB requires a seperate handle for each interface
2429 for (i = 0; i < USB_MAXINTERFACES; i++) {
2430 if ( (priv->usb_interface[i].path != NULL)
2431 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2432 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2433 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2434 if (file_handle == INVALID_HANDLE_VALUE) {
2435 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2436 switch(GetLastError()) {
2437 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2438 return LIBUSB_ERROR_NO_DEVICE;
2439 case ERROR_ACCESS_DENIED:
2440 return LIBUSB_ERROR_ACCESS;
2442 return LIBUSB_ERROR_IO;
2445 handle_priv->interface_handle[i].dev_handle = file_handle;
2449 return LIBUSB_SUCCESS;
2452 static void winusb_close(struct libusb_device_handle *dev_handle)
2454 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2455 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2459 if (!api_winusb_available)
2462 for (i = 0; i < USB_MAXINTERFACES; i++) {
2463 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2464 file_handle = handle_priv->interface_handle[i].dev_handle;
2465 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2466 CloseHandle(file_handle);
2472 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
2474 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2475 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2476 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2479 uint8_t endpoint_address;
2482 CHECK_WINUSB_AVAILABLE;
2484 // With handle and enpoints set (in parent), we can setup the default pipe properties
2485 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2486 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2487 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2488 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2489 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2490 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2492 if (i == -1) continue; // Other policies don't apply to control endpoint
2494 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2495 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2496 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2498 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2499 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2500 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2502 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2503 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2504 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2507 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2508 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2509 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2513 return LIBUSB_SUCCESS;
2516 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2518 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2519 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2520 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2521 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2522 HANDLE file_handle, winusb_handle;
2524 CHECK_WINUSB_AVAILABLE;
2526 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2527 // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
2528 if ((is_using_usbccgp) || (iface == 0)) {
2529 // composite device (independent interfaces) or interface 0
2530 file_handle = handle_priv->interface_handle[iface].dev_handle;
2531 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2532 return LIBUSB_ERROR_NOT_FOUND;
2535 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2536 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2537 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2539 switch(GetLastError()) {
2540 case ERROR_BAD_COMMAND: // The device was disconnected
2541 return LIBUSB_ERROR_NO_DEVICE;
2543 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2544 return LIBUSB_ERROR_ACCESS;
2547 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2549 // For all other interfaces, use WinUsb_GetAssociatedInterface()
2550 winusb_handle = handle_priv->interface_handle[0].api_handle;
2551 // It is a requirement for multiple interface devices using WinUSB that you
2552 // must first claim the first interface before you claim any other
2553 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2554 file_handle = handle_priv->interface_handle[0].dev_handle;
2555 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2556 handle_priv->interface_handle[0].api_handle = winusb_handle;
2557 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2559 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2560 return LIBUSB_ERROR_ACCESS;
2563 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2564 &handle_priv->interface_handle[iface].api_handle)) {
2565 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2566 switch(GetLastError()) {
2567 case ERROR_NO_MORE_ITEMS: // invalid iface
2568 return LIBUSB_ERROR_NOT_FOUND;
2569 case ERROR_BAD_COMMAND: // The device was disconnected
2570 return LIBUSB_ERROR_NO_DEVICE;
2571 case ERROR_ALREADY_EXISTS: // already claimed
2572 return LIBUSB_ERROR_BUSY;
2574 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2575 return LIBUSB_ERROR_ACCESS;
2579 usbi_dbg("claimed interface %d", iface);
2580 handle_priv->active_interface = iface;
2582 return LIBUSB_SUCCESS;
2585 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2587 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2588 HANDLE winusb_handle;
2590 CHECK_WINUSB_AVAILABLE;
2592 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2593 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2594 return LIBUSB_ERROR_NOT_FOUND;
2597 WinUsb_Free(winusb_handle);
2598 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2600 return LIBUSB_SUCCESS;
2604 * Return the first valid interface (of the same API type), for control transfers
2606 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2608 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2609 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2612 if ((api_id < USB_API_WINUSB) || (api_id > USB_API_HID)) {
2613 usbi_dbg("unsupported API ID");
2617 for (i=0; i<USB_MAXINTERFACES; i++) {
2618 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2619 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2620 && (handle_priv->interface_handle[i].api_handle != 0)
2621 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2622 && (priv->usb_interface[i].apib->id == api_id) ) {
2630 * Lookup interface by endpoint address. -1 if not found
2632 static int interface_by_endpoint(struct windows_device_priv *priv,
2633 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2636 for (i=0; i<USB_MAXINTERFACES; i++) {
2637 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2639 if (handle_priv->interface_handle[i].api_handle == 0)
2641 if (priv->usb_interface[i].endpoint == NULL)
2643 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2644 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2652 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2654 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2655 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2656 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2657 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2658 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2659 transfer->dev_handle);
2660 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2662 HANDLE winusb_handle;
2663 int current_interface;
2666 CHECK_WINUSB_AVAILABLE;
2668 transfer_priv->pollable_fd = INVALID_WINFD;
2669 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2671 if (size > MAX_CTRL_BUFFER_LENGTH)
2672 return LIBUSB_ERROR_INVALID_PARAM;
2674 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSB);
2675 if (current_interface < 0) {
2676 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2677 return LIBUSB_ERROR_NOT_FOUND;
2681 usbi_dbg("will use interface %d", current_interface);
2682 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2684 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2685 // Always use the handle returned from usbi_create_fd (wfd.handle)
2687 return LIBUSB_ERROR_NO_MEM;
2690 // Sending of set configuration control requests from WinUSB creates issues
2691 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2692 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2693 if (setup->value != priv->active_config) {
2694 usbi_warn(ctx, "cannot set configuration other than the default one");
2695 usbi_free_fd(wfd.fd);
2696 return LIBUSB_ERROR_INVALID_PARAM;
2698 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2699 wfd.overlapped->InternalHigh = 0;
2701 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2702 if(GetLastError() != ERROR_IO_PENDING) {
2703 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2704 usbi_free_fd(wfd.fd);
2705 return LIBUSB_ERROR_IO;
2708 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2709 wfd.overlapped->InternalHigh = (DWORD)size;
2713 // Use priv_transfer to store data needed for async polling
2714 transfer_priv->pollable_fd = wfd;
2715 transfer_priv->interface_number = (uint8_t)current_interface;
2717 return LIBUSB_SUCCESS;
2720 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2722 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2723 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2724 HANDLE winusb_handle;
2726 CHECK_WINUSB_AVAILABLE;
2728 if (altsetting > 255) {
2729 return LIBUSB_ERROR_INVALID_PARAM;
2732 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2733 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2734 usbi_err(ctx, "interface must be claimed first");
2735 return LIBUSB_ERROR_NOT_FOUND;
2738 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2739 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2740 return LIBUSB_ERROR_IO;
2743 return LIBUSB_SUCCESS;
2746 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2748 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2749 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2750 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2751 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2752 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2753 HANDLE winusb_handle;
2755 int current_interface;
2758 CHECK_WINUSB_AVAILABLE;
2760 transfer_priv->pollable_fd = INVALID_WINFD;
2762 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2763 if (current_interface < 0) {
2764 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2765 return LIBUSB_ERROR_NOT_FOUND;
2768 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2770 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2772 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? _O_RDONLY : _O_WRONLY);
2773 // Always use the handle returned from usbi_create_fd (wfd.handle)
2775 return LIBUSB_ERROR_NO_MEM;
2778 if (IS_XFERIN(transfer)) {
2779 usbi_dbg("reading %d bytes", transfer->length);
2780 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2782 usbi_dbg("writing %d bytes", transfer->length);
2783 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2786 if(GetLastError() != ERROR_IO_PENDING) {
2787 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2788 usbi_free_fd(wfd.fd);
2789 return LIBUSB_ERROR_IO;
2792 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2793 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2796 transfer_priv->pollable_fd = wfd;
2797 transfer_priv->interface_number = (uint8_t)current_interface;
2799 return LIBUSB_SUCCESS;
2802 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2804 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2805 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2806 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2807 HANDLE winusb_handle;
2808 int current_interface;
2810 CHECK_WINUSB_AVAILABLE;
2812 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2813 if (current_interface < 0) {
2814 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2815 return LIBUSB_ERROR_NOT_FOUND;
2818 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2819 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2821 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2822 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2823 return LIBUSB_ERROR_NO_DEVICE;
2826 return LIBUSB_SUCCESS;
2830 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2831 * through testing as well):
2832 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2833 * the control transfer using CancelIo"
2835 static int winusb_abort_control(struct usbi_transfer *itransfer)
2837 // Cancelling of the I/O is done in the parent
2838 return LIBUSB_SUCCESS;
2841 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2843 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2844 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2845 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2846 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2847 HANDLE winusb_handle;
2848 int current_interface;
2850 CHECK_WINUSB_AVAILABLE;
2852 current_interface = transfer_priv->interface_number;
2853 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2854 usbi_err(ctx, "program assertion failed: invalid interface_number");
2855 return LIBUSB_ERROR_NOT_FOUND;
2857 usbi_dbg("will use interface %d", current_interface);
2859 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2861 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2862 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2863 return LIBUSB_ERROR_NO_DEVICE;
2866 return LIBUSB_SUCCESS;
2870 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2871 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2872 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2873 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2874 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2875 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2877 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2878 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2880 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2881 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2882 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2884 HANDLE winusb_handle;
2887 CHECK_WINUSB_AVAILABLE;
2889 // Reset any available pipe (except control)
2890 for (i=0; i<USB_MAXINTERFACES; i++) {
2891 winusb_handle = handle_priv->interface_handle[i].api_handle;
2892 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2894 // Cancel any pollable I/O
2895 usbi_remove_pollfd(ctx, wfd.fd);
2896 usbi_free_fd(wfd.fd);
2897 wfd = handle_to_winfd(winusb_handle);
2900 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2901 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2902 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2903 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2904 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2905 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2907 // FlushPipe seems to fail on OUT pipes
2908 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2909 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2910 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2911 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2913 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2914 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2915 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2921 return LIBUSB_SUCCESS;
2924 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2926 itransfer->transferred += io_size;
2927 return LIBUSB_TRANSFER_COMPLETED;
2931 * Internal HID Support functions (from libusb-win32)
2932 * Note that functions that complete data transfer synchronously must return
2933 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
2935 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2936 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2938 static int _hid_wcslen(WCHAR *str)
2941 while (str[i] && (str[i] != 0x409)) {
2947 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2949 struct libusb_device_descriptor d;
2951 d.bLength = LIBUSB_DT_DEVICE_SIZE;
2952 d.bDescriptorType = LIBUSB_DT_DEVICE;
2953 d.bcdUSB = 0x0200; /* 2.00 */
2955 d.bDeviceSubClass = 0;
2956 d.bDeviceProtocol = 0;
2957 d.bMaxPacketSize0 = 64; /* fix this! */
2958 d.idVendor = (uint16_t)dev->vid;
2959 d.idProduct = (uint16_t)dev->pid;
2960 d.bcdDevice = 0x0100;
2961 d.iManufacturer = dev->string_index[0];
2962 d.iProduct = dev->string_index[1];
2963 d.iSerialNumber = dev->string_index[2];
2964 d.bNumConfigurations = 1;
2966 if (*size > LIBUSB_DT_DEVICE_SIZE)
2967 *size = LIBUSB_DT_DEVICE_SIZE;
2968 memcpy(data, &d, *size);
2969 return LIBUSB_COMPLETED;
2972 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2974 char num_endpoints = 0;
2975 size_t config_total_len = 0;
2976 char tmp[HID_MAX_CONFIG_DESC_SIZE];
2977 struct libusb_config_descriptor *cd;
2978 struct libusb_interface_descriptor *id;
2979 struct libusb_hid_descriptor *hd;
2980 struct libusb_endpoint_descriptor *ed;
2983 if (dev->input_report_size)
2985 if (dev->output_report_size)
2988 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
2989 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
2992 cd = (struct libusb_config_descriptor *)tmp;
2993 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
2994 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
2995 + LIBUSB_DT_INTERFACE_SIZE);
2996 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
2997 + LIBUSB_DT_INTERFACE_SIZE
2998 + LIBUSB_DT_HID_SIZE);
3000 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3001 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3002 cd->wTotalLength = (uint16_t) config_total_len;
3003 cd->bNumInterfaces = 1;
3004 cd->bConfigurationValue = 1;
3005 cd->iConfiguration = 0;
3006 cd->bmAttributes = 1 << 7; /* bus powered */
3009 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3010 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3011 id->bInterfaceNumber = 0;
3012 id->bAlternateSetting = 0;
3013 id->bNumEndpoints = num_endpoints;
3014 id->bInterfaceClass = 3;
3015 id->bInterfaceSubClass = 0;
3016 id->bInterfaceProtocol = 0;
3019 tmp_size = LIBUSB_DT_HID_SIZE;
3020 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3022 if (dev->input_report_size) {
3023 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3024 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3025 ed->bEndpointAddress = HID_IN_EP;
3026 ed->bmAttributes = 3;
3027 ed->wMaxPacketSize = dev->input_report_size - 1;
3033 if (dev->output_report_size) {
3034 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3035 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3036 ed->bEndpointAddress = HID_OUT_EP;
3037 ed->bmAttributes = 3;
3038 ed->wMaxPacketSize = dev->output_report_size - 1;
3042 if (*size > config_total_len)
3043 *size = config_total_len;
3044 memcpy(data, tmp, *size);
3045 return LIBUSB_COMPLETED;
3048 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int _index,
3049 void *data, size_t *size)
3052 size_t tmp_size = 0;
3055 /* language ID, EN-US */
3056 char string_langid[] = {
3061 if ((*size < 2) || (*size > 255)) {
3062 return LIBUSB_ERROR_OVERFLOW;
3066 tmp = string_langid;
3067 tmp_size = sizeof(string_langid)+2;
3069 for (i=0; i<3; i++) {
3070 if (_index == (dev->string_index[i])) {
3071 tmp = dev->string[i];
3072 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3076 if (i == 3) { // not found
3077 return LIBUSB_ERROR_INVALID_PARAM;
3082 return LIBUSB_ERROR_INVALID_PARAM;
3085 if (tmp_size < *size) {
3089 ((uint8_t*)data)[0] = (uint8_t)*size;
3090 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3091 memcpy((uint8_t*)data+2, tmp, *size-2);
3092 return LIBUSB_COMPLETED;
3095 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3097 struct libusb_hid_descriptor d;
3098 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3099 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3101 _hid_get_report_descriptor(dev, tmp, &report_len);
3103 d.bLength = LIBUSB_DT_HID_SIZE;
3104 d.bDescriptorType = LIBUSB_DT_HID;
3105 d.bcdHID = 0x0110; /* 1.10 */
3107 d.bNumDescriptors = 1;
3108 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3109 d.wClassDescriptorLength = (uint16_t)report_len;
3111 if (*size > LIBUSB_DT_HID_SIZE)
3112 *size = LIBUSB_DT_HID_SIZE;
3113 memcpy(data, &d, *size);
3114 return LIBUSB_COMPLETED;
3117 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3119 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3122 /* usage page (0xFFA0 == vendor defined) */
3123 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3124 /* usage (vendor defined) */
3125 d[i++] = 0x09; d[i++] = 0x01;
3126 /* start collection (application) */
3127 d[i++] = 0xA1; d[i++] = 0x01;
3129 if (dev->input_report_size) {
3130 /* usage (vendor defined) */
3131 d[i++] = 0x09; d[i++] = 0x01;
3132 /* logical minimum (0) */
3133 d[i++] = 0x15; d[i++] = 0x00;
3134 /* logical maximum (255) */
3135 d[i++] = 0x25; d[i++] = 0xFF;
3136 /* report size (8 bits) */
3137 d[i++] = 0x75; d[i++] = 0x08;
3139 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3140 /* input (data, variable, absolute) */
3141 d[i++] = 0x81; d[i++] = 0x00;
3144 if (dev->output_report_size) {
3145 /* usage (vendor defined) */
3146 d[i++] = 0x09; d[i++] = 0x02;
3147 /* logical minimum (0) */
3148 d[i++] = 0x15; d[i++] = 0x00;
3149 /* logical maximum (255) */
3150 d[i++] = 0x25; d[i++] = 0xFF;
3151 /* report size (8 bits) */
3152 d[i++] = 0x75; d[i++] = 0x08;
3154 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3155 /* output (data, variable, absolute) */
3156 d[i++] = 0x91; d[i++] = 0x00;
3158 /* feature report */
3159 if (dev->feature_report_size) {
3160 /* usage (vendor defined) */
3161 d[i++] = 0x09; d[i++] = 0x03;
3162 /* logical minimum (0) */
3163 d[i++] = 0x15; d[i++] = 0x00;
3164 /* logical maximum (255) */
3165 d[i++] = 0x25; d[i++] = 0xFF;
3166 /* report size (8 bits) */
3167 d[i++] = 0x75; d[i++] = 0x08;
3169 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3170 /* feature (data, variable, absolute) */
3171 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3174 /* end collection */
3179 memcpy(data, d, *size);
3180 return LIBUSB_COMPLETED;
3183 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3184 int type, int _index, void *data, size_t *size)
3187 case LIBUSB_DT_DEVICE:
3188 usbi_dbg("LIBUSB_DT_DEVICE");
3189 return _hid_get_device_descriptor(dev, data, size);
3190 case LIBUSB_DT_CONFIG:
3191 usbi_dbg("LIBUSB_DT_CONFIG");
3193 return _hid_get_config_descriptor(dev, data, size);
3194 return LIBUSB_ERROR_INVALID_PARAM;
3195 case LIBUSB_DT_STRING:
3196 usbi_dbg("LIBUSB_DT_STRING");
3197 return _hid_get_string_descriptor(dev, _index, data, size);
3199 usbi_dbg("LIBUSB_DT_HID");
3201 return _hid_get_hid_descriptor(dev, data, size);
3202 return LIBUSB_ERROR_INVALID_PARAM;
3203 case LIBUSB_DT_REPORT:
3204 usbi_dbg("LIBUSB_DT_REPORT");
3206 return _hid_get_report_descriptor(dev, data, size);
3207 return LIBUSB_ERROR_INVALID_PARAM;
3208 case LIBUSB_DT_PHYSICAL:
3209 usbi_dbg("LIBUSB_DT_PHYSICAL");
3210 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3211 return LIBUSB_COMPLETED;
3212 return LIBUSB_ERROR_OTHER;
3214 usbi_dbg("unsupported");
3215 return LIBUSB_ERROR_INVALID_PARAM;
3218 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3219 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3223 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3224 int r = LIBUSB_SUCCESS;
3226 if (tp->hid_buffer != NULL) {
3227 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3230 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3231 usbi_dbg("invalid size (%d)", *size);
3232 return LIBUSB_ERROR_INVALID_PARAM;
3235 switch (report_type) {
3236 case HID_REPORT_TYPE_INPUT:
3237 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3239 case HID_REPORT_TYPE_FEATURE:
3240 ioctl_code = IOCTL_HID_GET_FEATURE;
3243 usbi_dbg("unknown HID report type %d", report_type);
3244 return LIBUSB_ERROR_INVALID_PARAM;
3247 // Add a trailing byte to detect overflows
3248 buf = (uint8_t*)calloc(expected_size+1, 1);
3250 return LIBUSB_ERROR_NO_MEM;
3252 buf[0] = (uint8_t)id; // Must be set always
3253 usbi_dbg("report ID: 0x%02X", buf[0]);
3255 tp->hid_expected_size = expected_size;
3256 read_size = expected_size;
3258 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3259 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3260 buf, expected_size+1, &read_size, overlapped)) {
3261 if (GetLastError() != ERROR_IO_PENDING) {
3262 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3264 return LIBUSB_ERROR_IO;
3266 // Asynchronous wait
3267 tp->hid_buffer = buf;
3268 tp->hid_dest = (uint8_t*)data; // copy dest, as not necessarily the start of the transfer buffer
3269 return LIBUSB_SUCCESS;
3272 // Transfer completed synchronously => copy and discard extra buffer
3273 if (read_size == 0) {
3274 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3278 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3280 if ((size_t)read_size > expected_size) {
3281 r = LIBUSB_ERROR_OVERFLOW;
3282 usbi_dbg("OVERFLOW!");
3284 r = LIBUSB_COMPLETED;
3287 *size = MIN((size_t)read_size, *size);
3289 // Discard report ID
3290 memcpy(data, buf+1, *size);
3292 memcpy(data, buf, *size);
3299 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3300 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3303 uint8_t *buf = NULL;
3304 DWORD ioctl_code, write_size= (DWORD)*size;
3306 if (tp->hid_buffer != NULL) {
3307 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3310 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3311 usbi_dbg("invalid size (%d)", *size);
3312 return LIBUSB_ERROR_INVALID_PARAM;
3315 switch (report_type) {
3316 case HID_REPORT_TYPE_OUTPUT:
3317 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3319 case HID_REPORT_TYPE_FEATURE:
3320 ioctl_code = IOCTL_HID_SET_FEATURE;
3323 usbi_dbg("unknown HID report type %d", report_type);
3324 return LIBUSB_ERROR_INVALID_PARAM;
3327 usbi_dbg("report ID: 0x%02X", id);
3328 // When report IDs are not used (i.e. when id == 0), we must add
3329 // a null report ID. Otherwise, we just use original data buffer
3333 buf = (uint8_t*) malloc(write_size);
3335 return LIBUSB_ERROR_NO_MEM;
3339 memcpy(buf + 1, data, *size);
3341 // This seems like a waste, but if we don't duplicate the
3342 // data, we'll get issues when freeing hid_buffer
3343 memcpy(buf, data, *size);
3345 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3349 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3350 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3351 buf, write_size, &write_size, overlapped)) {
3352 if (GetLastError() != ERROR_IO_PENDING) {
3353 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3355 return LIBUSB_ERROR_IO;
3357 tp->hid_buffer = buf;
3358 tp->hid_dest = NULL;
3359 return LIBUSB_SUCCESS;
3362 // Transfer completed synchronously
3364 if (write_size == 0) {
3365 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3368 return LIBUSB_COMPLETED;
3371 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3372 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3373 size_t *size, OVERLAPPED* overlapped)
3375 int report_type = (value >> 8) & 0xFF;
3376 int report_id = value & 0xFF;
3378 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3379 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3380 return LIBUSB_ERROR_INVALID_PARAM;
3382 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3383 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3385 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3386 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3388 return LIBUSB_ERROR_INVALID_PARAM;
3395 static int hid_init(struct libusb_context *ctx)
3397 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3398 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3399 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3400 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3401 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3402 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3403 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3404 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3405 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3406 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3407 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3408 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3409 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3410 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3411 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3412 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3414 api_hid_available = true;
3415 return LIBUSB_SUCCESS;
3418 static int hid_exit(void)
3420 return LIBUSB_SUCCESS;
3423 // NB: open and close must ensure that they only handle interface of
3424 // the right API type, as these functions can be called wholesale from
3425 // composite_open(), with interfaces belonging to different APIs
3426 static int hid_open(struct libusb_device_handle *dev_handle)
3428 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3429 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3430 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3432 HIDD_ATTRIBUTES hid_attributes;
3433 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3434 HIDP_CAPS capabilities;
3435 HIDP_VALUE_CAPS *value_caps;
3437 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3439 // report IDs handling
3441 char* type[3] = {"input", "output", "feature"};
3442 int nb_ids[2]; // zero and nonzero report IDs
3444 CHECK_HID_AVAILABLE;
3445 if (priv->hid == NULL) {
3446 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3447 return LIBUSB_ERROR_NOT_FOUND;
3450 for (i = 0; i < USB_MAXINTERFACES; i++) {
3451 if ( (priv->usb_interface[i].path != NULL)
3452 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3453 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3454 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3456 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3457 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3458 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3459 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3460 * HidD_GetFeature (if the device supports Feature reports)."
3462 if (hid_handle == INVALID_HANDLE_VALUE) {
3463 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3464 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3465 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3466 if (hid_handle == INVALID_HANDLE_VALUE) {
3467 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3468 switch(GetLastError()) {
3469 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3470 return LIBUSB_ERROR_NO_DEVICE;
3471 case ERROR_ACCESS_DENIED:
3472 return LIBUSB_ERROR_ACCESS;
3474 return LIBUSB_ERROR_IO;
3477 priv->usb_interface[i].restricted_functionality = true;
3479 handle_priv->interface_handle[i].api_handle = hid_handle;
3483 hid_attributes.Size = sizeof(hid_attributes);
3485 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3486 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3490 priv->hid->vid = hid_attributes.VendorID;
3491 priv->hid->pid = hid_attributes.ProductID;
3493 // Set the maximum available input buffer size
3494 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3495 usbi_dbg("set maximum input buffer size to %d", i/2);
3497 // Get the maximum input and output report size
3498 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3499 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3502 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3503 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3507 // Find out if interrupt will need report IDs
3508 size[0] = capabilities.NumberInputValueCaps;
3509 size[1] = capabilities.NumberOutputValueCaps;
3510 size[2] = capabilities.NumberFeatureValueCaps;
3511 for (j=HidP_Input; j<=HidP_Feature; j++) {
3512 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3513 priv->hid->uses_report_ids[j] = false;
3515 value_caps = (HIDP_VALUE_CAPS*) calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3516 if ( (value_caps != NULL)
3517 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3518 && (size[j] >= 1) ) {
3521 for (i=0; i<(int)size[j]; i++) {
3522 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3523 if (value_caps[i].ReportID != 0) {
3529 if (nb_ids[1] != 0) {
3530 if (nb_ids[0] != 0) {
3531 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3534 priv->hid->uses_report_ids[j] = true;
3537 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3539 safe_free(value_caps);
3543 // Set the report sizes
3544 priv->hid->input_report_size = capabilities.InputReportByteLength;
3545 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3546 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3548 // Fetch string descriptors
3549 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3550 if (priv->hid->string_index[0] != 0) {
3551 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3552 sizeof(priv->hid->string[0]));
3554 priv->hid->string[0][0] = 0;
3556 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3557 if (priv->hid->string_index[1] != 0) {
3558 HidD_GetProductString(hid_handle, priv->hid->string[1],
3559 sizeof(priv->hid->string[1]));
3561 priv->hid->string[1][0] = 0;
3563 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3564 if (priv->hid->string_index[2] != 0) {
3565 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3566 sizeof(priv->hid->string[2]));
3568 priv->hid->string[2][0] = 0;
3572 if (preparsed_data) {
3573 HidD_FreePreparsedData(preparsed_data);
3576 return LIBUSB_SUCCESS;
3579 static void hid_close(struct libusb_device_handle *dev_handle)
3581 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3582 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3586 if (!api_hid_available)
3589 for (i = 0; i < USB_MAXINTERFACES; i++) {
3590 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3591 file_handle = handle_priv->interface_handle[i].api_handle;
3592 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3593 CloseHandle(file_handle);
3599 static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface)
3601 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3602 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3604 CHECK_HID_AVAILABLE;
3606 // NB: Disconnection detection is not possible in this function
3607 if (priv->usb_interface[iface].path == NULL) {
3608 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3611 // We use dev_handle as a flag for interface claimed
3612 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3613 return LIBUSB_ERROR_BUSY; // already claimed
3616 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3618 usbi_dbg("claimed interface %d", iface);
3619 handle_priv->active_interface = iface;
3621 return LIBUSB_SUCCESS;
3624 static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface)
3626 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3627 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3629 CHECK_HID_AVAILABLE;
3631 if (priv->usb_interface[iface].path == NULL) {
3632 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3635 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
3636 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3639 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3641 return LIBUSB_SUCCESS;
3644 static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
3646 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3648 CHECK_HID_AVAILABLE;
3650 if (altsetting > 255) {
3651 return LIBUSB_ERROR_INVALID_PARAM;
3654 if (altsetting != 0) {
3655 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3656 return LIBUSB_ERROR_NOT_SUPPORTED;
3659 return LIBUSB_SUCCESS;
3662 static int hid_submit_control_transfer(struct usbi_transfer *itransfer)
3664 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3665 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3666 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3667 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3668 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3669 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3672 int current_interface, config;
3674 int r = LIBUSB_ERROR_INVALID_PARAM;
3676 CHECK_HID_AVAILABLE;
3678 transfer_priv->pollable_fd = INVALID_WINFD;
3679 safe_free(transfer_priv->hid_buffer);
3680 transfer_priv->hid_dest = NULL;
3681 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3683 if (size > MAX_CTRL_BUFFER_LENGTH) {
3684 return LIBUSB_ERROR_INVALID_PARAM;
3687 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3688 if (current_interface < 0) {
3689 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) {
3690 return LIBUSB_ERROR_NOT_FOUND;
3694 usbi_dbg("will use interface %d", current_interface);
3695 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3696 // Always use the handle returned from usbi_create_fd (wfd.handle)
3697 wfd = usbi_create_fd(hid_handle, _O_RDONLY);
3699 return LIBUSB_ERROR_NO_MEM;
3702 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3703 case LIBUSB_REQUEST_TYPE_STANDARD:
3704 switch(setup->request) {
3705 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3706 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3707 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3709 case LIBUSB_REQUEST_GET_CONFIGURATION:
3710 r = windows_get_configuration(transfer->dev_handle, &config);
3711 if (r == LIBUSB_SUCCESS) {
3713 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3714 r = LIBUSB_COMPLETED;
3717 case LIBUSB_REQUEST_SET_CONFIGURATION:
3718 if (setup->value == priv->active_config) {
3719 r = LIBUSB_COMPLETED;
3721 usbi_warn(ctx, "cannot set configuration other than the default one");
3722 r = LIBUSB_ERROR_INVALID_PARAM;
3725 case LIBUSB_REQUEST_GET_INTERFACE:
3727 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3728 r = LIBUSB_COMPLETED;
3730 case LIBUSB_REQUEST_SET_INTERFACE:
3731 r = hid_set_interface_altsetting(transfer->dev_handle, setup->index, setup->value);
3732 if (r == LIBUSB_SUCCESS) {
3733 r = LIBUSB_COMPLETED;
3737 usbi_warn(ctx, "unsupported HID control request");
3738 r = LIBUSB_ERROR_INVALID_PARAM;
3742 case LIBUSB_REQUEST_TYPE_CLASS:
3743 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3744 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3745 &size, wfd.overlapped);
3748 usbi_warn(ctx, "unsupported HID control request");
3749 r = LIBUSB_ERROR_INVALID_PARAM;
3753 if (r == LIBUSB_COMPLETED) {
3754 // Force request to be completed synchronously. Transferred size has been set by previous call
3755 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3756 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3757 // set InternalHigh to the number of bytes transferred
3758 wfd.overlapped->InternalHigh = (DWORD)size;
3762 if (r == LIBUSB_SUCCESS) {
3763 // Use priv_transfer to store data needed for async polling
3764 transfer_priv->pollable_fd = wfd;
3765 transfer_priv->interface_number = (uint8_t)current_interface;
3767 usbi_free_fd(wfd.fd);
3773 static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer) {
3774 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3775 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3776 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3777 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3778 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3781 bool direction_in, ret;
3782 int current_interface, length;
3784 int r = LIBUSB_SUCCESS;
3786 CHECK_HID_AVAILABLE;
3788 transfer_priv->pollable_fd = INVALID_WINFD;
3789 transfer_priv->hid_dest = NULL;
3790 safe_free(transfer_priv->hid_buffer);
3792 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3793 if (current_interface < 0) {
3794 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3795 return LIBUSB_ERROR_NOT_FOUND;
3798 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3800 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3801 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3803 wfd = usbi_create_fd(hid_handle, direction_in?_O_RDONLY:_O_WRONLY);
3804 // Always use the handle returned from usbi_create_fd (wfd.handle)
3806 return LIBUSB_ERROR_NO_MEM;
3809 // If report IDs are not in use, an extra prefix byte must be added
3810 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
3811 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
3812 length = transfer->length+1;
3814 length = transfer->length;
3816 // Add a trailing byte to detect overflows on input
3817 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
3818 if (transfer_priv->hid_buffer == NULL) {
3819 return LIBUSB_ERROR_NO_MEM;
3821 transfer_priv->hid_expected_size = length;
3824 transfer_priv->hid_dest = transfer->buffer;
3825 usbi_dbg("reading %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3826 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
3828 if (!priv->hid->uses_report_ids[1]) {
3829 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
3831 // We could actually do without the calloc and memcpy in this case
3832 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3834 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3835 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3838 if (GetLastError() != ERROR_IO_PENDING) {
3839 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3840 usbi_free_fd(wfd.fd);
3841 safe_free(transfer_priv->hid_buffer);
3842 return LIBUSB_ERROR_IO;
3845 // Only write operations that completed synchronously need to free up
3846 // hid_buffer. For reads, copy_transfer_data() handles that process.
3847 if (!direction_in) {
3848 safe_free(transfer_priv->hid_buffer);
3851 usbi_err(ctx, "program assertion failed - no data was transferred");
3854 if (size > (size_t)length) {
3855 usbi_err(ctx, "OVERFLOW!");
3856 r = LIBUSB_ERROR_OVERFLOW;
3858 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3859 wfd.overlapped->InternalHigh = size;
3862 transfer_priv->pollable_fd = wfd;
3863 transfer_priv->interface_number = (uint8_t)current_interface;
3868 static int hid_abort_transfers(struct usbi_transfer *itransfer)
3870 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3871 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3872 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3874 int current_interface;
3876 CHECK_HID_AVAILABLE;
3878 current_interface = transfer_priv->interface_number;
3879 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3880 CancelIo(hid_handle);
3882 return LIBUSB_SUCCESS;
3885 static int hid_reset_device(struct libusb_device_handle *dev_handle)
3887 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3889 int current_interface;
3891 CHECK_HID_AVAILABLE;
3893 // Flushing the queues on all interfaces is the best we can achieve
3894 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3895 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3896 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
3897 HidD_FlushQueue(hid_handle);
3900 return LIBUSB_SUCCESS;
3903 static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
3905 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3906 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3907 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3909 int current_interface;
3911 CHECK_HID_AVAILABLE;
3913 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3914 if (current_interface < 0) {
3915 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3916 return LIBUSB_ERROR_NOT_FOUND;
3919 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3920 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3922 // No endpoint selection with Microsoft's implementation, so we try to flush the
3923 // whole interface. Should be OK for most case scenarios
3924 if (!HidD_FlushQueue(hid_handle)) {
3925 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3926 // Device was probably disconnected
3927 return LIBUSB_ERROR_NO_DEVICE;
3930 return LIBUSB_SUCCESS;
3933 // This extra function is only needed for HID
3934 static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
3935 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3936 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3937 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3938 int r = LIBUSB_TRANSFER_COMPLETED;
3939 uint32_t corrected_size = io_size;
3941 if (transfer_priv->hid_buffer != NULL) {
3942 // If we have a valid hid_buffer, it means the transfer was async
3943 if (transfer_priv->hid_dest != NULL) { // Data readout
3944 // First, check for overflow
3945 if (corrected_size > transfer_priv->hid_expected_size) {
3946 usbi_err(ctx, "OVERFLOW!");
3947 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
3948 r = LIBUSB_TRANSFER_OVERFLOW;
3951 if (transfer_priv->hid_buffer[0] == 0) {
3952 // Discard the 1 byte report ID prefix
3954 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
3956 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
3958 transfer_priv->hid_dest = NULL;
3960 // For write, we just need to free the hid buffer
3961 safe_free(transfer_priv->hid_buffer);
3963 itransfer->transferred += corrected_size;
3969 * Composite API functions
3971 static int composite_init(struct libusb_context *ctx)
3973 return LIBUSB_SUCCESS;
3976 static int composite_exit(void)
3978 return LIBUSB_SUCCESS;
3981 static int composite_open(struct libusb_device_handle *dev_handle)
3983 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3986 uint8_t flag = 1<<USB_API_WINUSB;
3988 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3989 if (priv->composite_api_flags & flag) {
3990 r = usb_api_backend[api].open(dev_handle);
3991 if (r != LIBUSB_SUCCESS) {
3997 return LIBUSB_SUCCESS;
4000 static void composite_close(struct libusb_device_handle *dev_handle)
4002 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4004 uint8_t flag = 1<<USB_API_WINUSB;
4006 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4007 if (priv->composite_api_flags & flag) {
4008 usb_api_backend[api].close(dev_handle);
4014 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
4016 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4017 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
4020 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
4022 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4023 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
4026 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
4028 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4029 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
4032 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
4034 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4035 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4036 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4039 // Interface shouldn't matter for control, but it does in practice, with Windows'
4040 // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4041 for (pass = 0; pass < 2; pass++) {
4042 for (i=0; i<USB_MAXINTERFACES; i++) {
4043 if (priv->usb_interface[i].path != NULL) {
4044 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4045 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4048 usbi_dbg("using interface %d", i);
4049 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
4054 usbi_err(ctx, "no libusbx supported interfaces to complete request");
4055 return LIBUSB_ERROR_NOT_FOUND;
4058 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
4059 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4060 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4061 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4062 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4063 int current_interface;
4065 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4066 if (current_interface < 0) {
4067 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4068 return LIBUSB_ERROR_NOT_FOUND;
4071 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
4074 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
4075 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4076 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4077 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4078 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4079 int current_interface;
4081 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4082 if (current_interface < 0) {
4083 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4084 return LIBUSB_ERROR_NOT_FOUND;
4087 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
4090 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
4092 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4093 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4094 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4095 int current_interface;
4097 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4098 if (current_interface < 0) {
4099 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4100 return LIBUSB_ERROR_NOT_FOUND;
4103 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
4106 static int composite_abort_control(struct usbi_transfer *itransfer)
4108 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4109 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4110 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4112 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
4115 static int composite_abort_transfers(struct usbi_transfer *itransfer)
4117 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4118 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4119 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4121 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
4124 static int composite_reset_device(struct libusb_device_handle *dev_handle)
4126 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4129 uint8_t flag = 1<<USB_API_WINUSB;
4131 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4132 if (priv->composite_api_flags & flag) {
4133 r = usb_api_backend[api].reset_device(dev_handle);
4134 if (r != LIBUSB_SUCCESS) {
4140 return LIBUSB_SUCCESS;
4143 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
4145 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4146 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4147 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4149 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);