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, "[%d] ", 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(PUSB_CONFIGURATION_DESCRIPTOR));
905 if (priv->config_descriptor == NULL)
906 return LIBUSB_ERROR_NO_MEM;
907 for (i=0; i<dev->num_configurations; i++)
908 priv->config_descriptor[i] = NULL;
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 = realloc(unref_list, unref_size*sizeof(libusb_device*));
1475 if (unref_list == NULL) {
1476 usbi_err(ctx, "could not realloc list for unref - aborting.");
1477 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
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");
2124 usbi_dbg("ERROR: broken timer thread");
2128 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2131 ULARGE_INTEGER rtime;
2134 case USBI_CLOCK_MONOTONIC:
2135 if (hires_frequency != 0) {
2137 InterlockedIncrement((LONG*)&request_count[0]);
2138 SetEvent(timer_request[0]);
2139 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2142 WaitForSingleObject(timer_mutex, INFINITE);
2144 ReleaseMutex(timer_mutex);
2145 return LIBUSB_SUCCESS;
2147 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2148 break; // Retry until successful
2150 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2151 return LIBUSB_ERROR_OTHER;
2155 // Fall through and return real-time if monotonic was not detected @ timer init
2156 case USBI_CLOCK_REALTIME:
2157 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2158 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2159 // Note however that our resolution is bounded by the Windows system time
2160 // functions and is at best of the order of 1 ms (or, usually, worse)
2161 GetSystemTimeAsFileTime(&filetime);
2162 rtime.LowPart = filetime.dwLowDateTime;
2163 rtime.HighPart = filetime.dwHighDateTime;
2164 rtime.QuadPart -= epoch_time;
2165 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2166 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2167 return LIBUSB_SUCCESS;
2169 return LIBUSB_ERROR_INVALID_PARAM;
2174 // NB: MSVC6 does not support named initializers.
2175 const struct usbi_os_backend windows_backend = {
2180 windows_get_device_list,
2184 windows_get_device_descriptor,
2185 windows_get_active_config_descriptor,
2186 windows_get_config_descriptor,
2188 windows_get_configuration,
2189 windows_set_configuration,
2190 windows_claim_interface,
2191 windows_release_interface,
2193 windows_set_interface_altsetting,
2195 windows_reset_device,
2197 windows_kernel_driver_active,
2198 windows_detach_kernel_driver,
2199 windows_attach_kernel_driver,
2201 windows_destroy_device,
2203 windows_submit_transfer,
2204 windows_cancel_transfer,
2205 windows_clear_transfer_priv,
2207 windows_handle_events,
2209 windows_clock_gettime,
2210 #if defined(USBI_TIMERFD_AVAILABLE)
2213 sizeof(struct windows_device_priv),
2214 sizeof(struct windows_device_handle_priv),
2215 sizeof(struct windows_transfer_priv),
2223 static int unsupported_init(struct libusb_context *ctx) {
2224 return LIBUSB_SUCCESS;
2226 static int unsupported_exit(void) {
2227 return LIBUSB_SUCCESS;
2229 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2230 PRINT_UNSUPPORTED_API(open);
2232 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2233 usbi_dbg("unsupported API call for 'close'");
2235 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2236 PRINT_UNSUPPORTED_API(claim_interface);
2238 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2239 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2241 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2242 PRINT_UNSUPPORTED_API(release_interface);
2244 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2245 PRINT_UNSUPPORTED_API(clear_halt);
2247 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2248 PRINT_UNSUPPORTED_API(reset_device);
2250 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2251 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2253 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2254 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2256 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2257 PRINT_UNSUPPORTED_API(submit_control_transfer);
2259 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2260 PRINT_UNSUPPORTED_API(abort_control);
2262 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2263 PRINT_UNSUPPORTED_API(abort_transfers);
2265 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2266 PRINT_UNSUPPORTED_API(copy_transfer_data);
2269 // These names must be uppercase
2270 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
2271 const char* composite_driver_names[] = {"USBCCGP"};
2272 const char* winusb_driver_names[] = {"WINUSB"};
2273 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2274 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2276 USB_API_UNSUPPORTED,
2278 &CLASS_GUID_UNSUPPORTED,
2285 unsupported_claim_interface,
2286 unsupported_set_interface_altsetting,
2287 unsupported_release_interface,
2288 unsupported_clear_halt,
2289 unsupported_reset_device,
2290 unsupported_submit_bulk_transfer,
2291 unsupported_submit_iso_transfer,
2292 unsupported_submit_control_transfer,
2293 unsupported_abort_control,
2294 unsupported_abort_transfers,
2295 unsupported_copy_transfer_data,
2299 &CLASS_GUID_UNSUPPORTED,
2301 sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
2306 unsupported_claim_interface,
2307 unsupported_set_interface_altsetting,
2308 unsupported_release_interface,
2309 unsupported_clear_halt,
2310 unsupported_reset_device,
2311 unsupported_submit_bulk_transfer,
2312 unsupported_submit_iso_transfer,
2313 unsupported_submit_control_transfer,
2314 unsupported_abort_control,
2315 unsupported_abort_transfers,
2316 unsupported_copy_transfer_data,
2320 &CLASS_GUID_COMPOSITE,
2321 composite_driver_names,
2322 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2327 composite_claim_interface,
2328 composite_set_interface_altsetting,
2329 composite_release_interface,
2330 composite_clear_halt,
2331 composite_reset_device,
2332 composite_submit_bulk_transfer,
2333 composite_submit_iso_transfer,
2334 composite_submit_control_transfer,
2335 composite_abort_control,
2336 composite_abort_transfers,
2337 composite_copy_transfer_data,
2341 &CLASS_GUID_LIBUSB_WINUSB,
2342 winusb_driver_names,
2343 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2348 winusb_claim_interface,
2349 winusb_set_interface_altsetting,
2350 winusb_release_interface,
2352 winusb_reset_device,
2353 winusb_submit_bulk_transfer,
2354 unsupported_submit_iso_transfer,
2355 winusb_submit_control_transfer,
2356 winusb_abort_control,
2357 winusb_abort_transfers,
2358 winusb_copy_transfer_data,
2364 sizeof(hid_driver_names)/sizeof(hid_driver_names[0]),
2369 hid_claim_interface,
2370 hid_set_interface_altsetting,
2371 hid_release_interface,
2374 hid_submit_bulk_transfer,
2375 unsupported_submit_iso_transfer,
2376 hid_submit_control_transfer,
2377 hid_abort_transfers,
2378 hid_abort_transfers,
2379 hid_copy_transfer_data,
2385 * WinUSB API functions
2387 static int winusb_init(struct libusb_context *ctx)
2389 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2390 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2391 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2392 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2393 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2394 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2395 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2396 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2397 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2398 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2399 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2400 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2401 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2402 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2403 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2404 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2405 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2407 api_winusb_available = true;
2408 return LIBUSB_SUCCESS;
2411 static int winusb_exit(void)
2413 return LIBUSB_SUCCESS;
2416 // NB: open and close must ensure that they only handle interface of
2417 // the right API type, as these functions can be called wholesale from
2418 // composite_open(), with interfaces belonging to different APIs
2419 static int winusb_open(struct libusb_device_handle *dev_handle)
2421 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2422 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2423 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2428 CHECK_WINUSB_AVAILABLE;
2430 // WinUSB requires a seperate handle for each interface
2431 for (i = 0; i < USB_MAXINTERFACES; i++) {
2432 if ( (priv->usb_interface[i].path != NULL)
2433 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2434 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2435 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2436 if (file_handle == INVALID_HANDLE_VALUE) {
2437 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2438 switch(GetLastError()) {
2439 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2440 return LIBUSB_ERROR_NO_DEVICE;
2441 case ERROR_ACCESS_DENIED:
2442 return LIBUSB_ERROR_ACCESS;
2444 return LIBUSB_ERROR_IO;
2447 handle_priv->interface_handle[i].dev_handle = file_handle;
2451 return LIBUSB_SUCCESS;
2454 static void winusb_close(struct libusb_device_handle *dev_handle)
2456 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2457 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2461 if (!api_winusb_available)
2464 for (i = 0; i < USB_MAXINTERFACES; i++) {
2465 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2466 file_handle = handle_priv->interface_handle[i].dev_handle;
2467 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2468 CloseHandle(file_handle);
2474 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
2476 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2477 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2478 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2481 uint8_t endpoint_address;
2484 CHECK_WINUSB_AVAILABLE;
2486 // With handle and enpoints set (in parent), we can setup the default pipe properties
2487 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2488 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2489 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2490 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2491 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2492 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2494 if (i == -1) continue; // Other policies don't apply to control endpoint
2496 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2497 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2498 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2500 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2501 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2502 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2504 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2505 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2506 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2509 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2510 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2511 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2515 return LIBUSB_SUCCESS;
2518 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2520 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2521 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2522 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2523 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2524 HANDLE file_handle, winusb_handle;
2526 CHECK_WINUSB_AVAILABLE;
2528 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2529 // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
2530 if ((is_using_usbccgp) || (iface == 0)) {
2531 // composite device (independent interfaces) or interface 0
2532 file_handle = handle_priv->interface_handle[iface].dev_handle;
2533 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2534 return LIBUSB_ERROR_NOT_FOUND;
2537 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2538 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2539 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2541 switch(GetLastError()) {
2542 case ERROR_BAD_COMMAND: // The device was disconnected
2543 return LIBUSB_ERROR_NO_DEVICE;
2545 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2546 return LIBUSB_ERROR_ACCESS;
2549 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2551 // For all other interfaces, use WinUsb_GetAssociatedInterface()
2552 winusb_handle = handle_priv->interface_handle[0].api_handle;
2553 // It is a requirement for multiple interface devices using WinUSB that you
2554 // must first claim the first interface before you claim any other
2555 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2556 file_handle = handle_priv->interface_handle[0].dev_handle;
2557 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2558 handle_priv->interface_handle[0].api_handle = winusb_handle;
2559 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2561 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2562 return LIBUSB_ERROR_ACCESS;
2565 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2566 &handle_priv->interface_handle[iface].api_handle)) {
2567 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2568 switch(GetLastError()) {
2569 case ERROR_NO_MORE_ITEMS: // invalid iface
2570 return LIBUSB_ERROR_NOT_FOUND;
2571 case ERROR_BAD_COMMAND: // The device was disconnected
2572 return LIBUSB_ERROR_NO_DEVICE;
2573 case ERROR_ALREADY_EXISTS: // already claimed
2574 return LIBUSB_ERROR_BUSY;
2576 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2577 return LIBUSB_ERROR_ACCESS;
2581 usbi_dbg("claimed interface %d", iface);
2582 handle_priv->active_interface = iface;
2584 return LIBUSB_SUCCESS;
2587 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2589 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2590 HANDLE winusb_handle;
2592 CHECK_WINUSB_AVAILABLE;
2594 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2595 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2596 return LIBUSB_ERROR_NOT_FOUND;
2599 WinUsb_Free(winusb_handle);
2600 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2602 return LIBUSB_SUCCESS;
2606 * Return the first valid interface (of the same API type), for control transfers
2608 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2610 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2611 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2614 if ((api_id < USB_API_WINUSB) || (api_id > USB_API_HID)) {
2615 usbi_dbg("unsupported API ID");
2619 for (i=0; i<USB_MAXINTERFACES; i++) {
2620 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2621 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2622 && (handle_priv->interface_handle[i].api_handle != 0)
2623 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2624 && (priv->usb_interface[i].apib->id == api_id) ) {
2632 * Lookup interface by endpoint address. -1 if not found
2634 static int interface_by_endpoint(struct windows_device_priv *priv,
2635 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2638 for (i=0; i<USB_MAXINTERFACES; i++) {
2639 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2641 if (handle_priv->interface_handle[i].api_handle == 0)
2643 if (priv->usb_interface[i].endpoint == NULL)
2645 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2646 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2654 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2656 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2657 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2658 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2659 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2660 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2661 transfer->dev_handle);
2662 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2664 HANDLE winusb_handle;
2665 int current_interface;
2668 CHECK_WINUSB_AVAILABLE;
2670 transfer_priv->pollable_fd = INVALID_WINFD;
2671 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2673 if (size > MAX_CTRL_BUFFER_LENGTH)
2674 return LIBUSB_ERROR_INVALID_PARAM;
2676 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSB);
2677 if (current_interface < 0) {
2678 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2679 return LIBUSB_ERROR_NOT_FOUND;
2683 usbi_dbg("will use interface %d", current_interface);
2684 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2686 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2687 // Always use the handle returned from usbi_create_fd (wfd.handle)
2689 return LIBUSB_ERROR_NO_MEM;
2692 // Sending of set configuration control requests from WinUSB creates issues
2693 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2694 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2695 if (setup->value != priv->active_config) {
2696 usbi_warn(ctx, "cannot set configuration other than the default one");
2697 usbi_free_fd(wfd.fd);
2698 return LIBUSB_ERROR_INVALID_PARAM;
2700 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2701 wfd.overlapped->InternalHigh = 0;
2703 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2704 if(GetLastError() != ERROR_IO_PENDING) {
2705 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2706 usbi_free_fd(wfd.fd);
2707 return LIBUSB_ERROR_IO;
2710 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2711 wfd.overlapped->InternalHigh = (DWORD)size;
2715 // Use priv_transfer to store data needed for async polling
2716 transfer_priv->pollable_fd = wfd;
2717 transfer_priv->interface_number = (uint8_t)current_interface;
2719 return LIBUSB_SUCCESS;
2722 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2724 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2725 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2726 HANDLE winusb_handle;
2728 CHECK_WINUSB_AVAILABLE;
2730 if (altsetting > 255) {
2731 return LIBUSB_ERROR_INVALID_PARAM;
2734 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2735 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2736 usbi_err(ctx, "interface must be claimed first");
2737 return LIBUSB_ERROR_NOT_FOUND;
2740 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2741 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2742 return LIBUSB_ERROR_IO;
2745 return LIBUSB_SUCCESS;
2748 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2750 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2751 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2752 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2753 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2754 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2755 HANDLE winusb_handle;
2757 int current_interface;
2760 CHECK_WINUSB_AVAILABLE;
2762 transfer_priv->pollable_fd = INVALID_WINFD;
2764 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2765 if (current_interface < 0) {
2766 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2767 return LIBUSB_ERROR_NOT_FOUND;
2770 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2772 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2774 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? _O_RDONLY : _O_WRONLY);
2775 // Always use the handle returned from usbi_create_fd (wfd.handle)
2777 return LIBUSB_ERROR_NO_MEM;
2780 if (IS_XFERIN(transfer)) {
2781 usbi_dbg("reading %d bytes", transfer->length);
2782 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2784 usbi_dbg("writing %d bytes", transfer->length);
2785 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2788 if(GetLastError() != ERROR_IO_PENDING) {
2789 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2790 usbi_free_fd(wfd.fd);
2791 return LIBUSB_ERROR_IO;
2794 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2795 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2798 transfer_priv->pollable_fd = wfd;
2799 transfer_priv->interface_number = (uint8_t)current_interface;
2801 return LIBUSB_SUCCESS;
2804 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2806 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2807 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2808 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2809 HANDLE winusb_handle;
2810 int current_interface;
2812 CHECK_WINUSB_AVAILABLE;
2814 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2815 if (current_interface < 0) {
2816 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2817 return LIBUSB_ERROR_NOT_FOUND;
2820 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2821 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2823 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2824 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2825 return LIBUSB_ERROR_NO_DEVICE;
2828 return LIBUSB_SUCCESS;
2832 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2833 * through testing as well):
2834 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2835 * the control transfer using CancelIo"
2837 static int winusb_abort_control(struct usbi_transfer *itransfer)
2839 // Cancelling of the I/O is done in the parent
2840 return LIBUSB_SUCCESS;
2843 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2845 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2846 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2847 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2848 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2849 HANDLE winusb_handle;
2850 int current_interface;
2852 CHECK_WINUSB_AVAILABLE;
2854 current_interface = transfer_priv->interface_number;
2855 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2856 usbi_err(ctx, "program assertion failed: invalid interface_number");
2857 return LIBUSB_ERROR_NOT_FOUND;
2859 usbi_dbg("will use interface %d", current_interface);
2861 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2863 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2864 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2865 return LIBUSB_ERROR_NO_DEVICE;
2868 return LIBUSB_SUCCESS;
2872 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2873 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2874 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2875 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2876 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2877 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2879 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2880 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2882 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2883 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2884 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2886 HANDLE winusb_handle;
2889 CHECK_WINUSB_AVAILABLE;
2891 // Reset any available pipe (except control)
2892 for (i=0; i<USB_MAXINTERFACES; i++) {
2893 winusb_handle = handle_priv->interface_handle[i].api_handle;
2894 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2896 // Cancel any pollable I/O
2897 usbi_remove_pollfd(ctx, wfd.fd);
2898 usbi_free_fd(wfd.fd);
2899 wfd = handle_to_winfd(winusb_handle);
2902 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2903 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2904 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2905 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2906 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2907 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2909 // FlushPipe seems to fail on OUT pipes
2910 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2911 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2912 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2913 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2915 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2916 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2917 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2923 return LIBUSB_SUCCESS;
2926 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2928 itransfer->transferred += io_size;
2929 return LIBUSB_TRANSFER_COMPLETED;
2933 * Internal HID Support functions (from libusb-win32)
2934 * Note that functions that complete data transfer synchronously must return
2935 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
2937 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2938 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2940 static int _hid_wcslen(WCHAR *str)
2943 while (str[i] && (str[i] != 0x409)) {
2949 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2951 struct libusb_device_descriptor d;
2953 d.bLength = LIBUSB_DT_DEVICE_SIZE;
2954 d.bDescriptorType = LIBUSB_DT_DEVICE;
2955 d.bcdUSB = 0x0200; /* 2.00 */
2957 d.bDeviceSubClass = 0;
2958 d.bDeviceProtocol = 0;
2959 d.bMaxPacketSize0 = 64; /* fix this! */
2960 d.idVendor = (uint16_t)dev->vid;
2961 d.idProduct = (uint16_t)dev->pid;
2962 d.bcdDevice = 0x0100;
2963 d.iManufacturer = dev->string_index[0];
2964 d.iProduct = dev->string_index[1];
2965 d.iSerialNumber = dev->string_index[2];
2966 d.bNumConfigurations = 1;
2968 if (*size > LIBUSB_DT_DEVICE_SIZE)
2969 *size = LIBUSB_DT_DEVICE_SIZE;
2970 memcpy(data, &d, *size);
2971 return LIBUSB_COMPLETED;
2974 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2976 char num_endpoints = 0;
2977 size_t config_total_len = 0;
2978 char tmp[HID_MAX_CONFIG_DESC_SIZE];
2979 struct libusb_config_descriptor *cd;
2980 struct libusb_interface_descriptor *id;
2981 struct libusb_hid_descriptor *hd;
2982 struct libusb_endpoint_descriptor *ed;
2985 if (dev->input_report_size)
2987 if (dev->output_report_size)
2990 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
2991 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
2994 cd = (struct libusb_config_descriptor *)tmp;
2995 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
2996 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
2997 + LIBUSB_DT_INTERFACE_SIZE);
2998 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
2999 + LIBUSB_DT_INTERFACE_SIZE
3000 + LIBUSB_DT_HID_SIZE);
3002 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3003 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3004 cd->wTotalLength = (uint16_t) config_total_len;
3005 cd->bNumInterfaces = 1;
3006 cd->bConfigurationValue = 1;
3007 cd->iConfiguration = 0;
3008 cd->bmAttributes = 1 << 7; /* bus powered */
3011 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3012 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3013 id->bInterfaceNumber = 0;
3014 id->bAlternateSetting = 0;
3015 id->bNumEndpoints = num_endpoints;
3016 id->bInterfaceClass = 3;
3017 id->bInterfaceSubClass = 0;
3018 id->bInterfaceProtocol = 0;
3021 tmp_size = LIBUSB_DT_HID_SIZE;
3022 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3024 if (dev->input_report_size) {
3025 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3026 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3027 ed->bEndpointAddress = HID_IN_EP;
3028 ed->bmAttributes = 3;
3029 ed->wMaxPacketSize = dev->input_report_size - 1;
3035 if (dev->output_report_size) {
3036 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3037 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3038 ed->bEndpointAddress = HID_OUT_EP;
3039 ed->bmAttributes = 3;
3040 ed->wMaxPacketSize = dev->output_report_size - 1;
3044 if (*size > config_total_len)
3045 *size = config_total_len;
3046 memcpy(data, tmp, *size);
3047 return LIBUSB_COMPLETED;
3050 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int _index,
3051 void *data, size_t *size)
3054 size_t tmp_size = 0;
3057 /* language ID, EN-US */
3058 char string_langid[] = {
3063 if ((*size < 2) || (*size > 255)) {
3064 return LIBUSB_ERROR_OVERFLOW;
3068 tmp = string_langid;
3069 tmp_size = sizeof(string_langid)+2;
3071 for (i=0; i<3; i++) {
3072 if (_index == (dev->string_index[i])) {
3073 tmp = dev->string[i];
3074 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3078 if (i == 3) { // not found
3079 return LIBUSB_ERROR_INVALID_PARAM;
3084 return LIBUSB_ERROR_INVALID_PARAM;
3087 if (tmp_size < *size) {
3091 ((uint8_t*)data)[0] = (uint8_t)*size;
3092 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3093 memcpy((uint8_t*)data+2, tmp, *size-2);
3094 return LIBUSB_COMPLETED;
3097 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3099 struct libusb_hid_descriptor d;
3100 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3101 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3103 _hid_get_report_descriptor(dev, tmp, &report_len);
3105 d.bLength = LIBUSB_DT_HID_SIZE;
3106 d.bDescriptorType = LIBUSB_DT_HID;
3107 d.bcdHID = 0x0110; /* 1.10 */
3109 d.bNumDescriptors = 1;
3110 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3111 d.wClassDescriptorLength = (uint16_t)report_len;
3113 if (*size > LIBUSB_DT_HID_SIZE)
3114 *size = LIBUSB_DT_HID_SIZE;
3115 memcpy(data, &d, *size);
3116 return LIBUSB_COMPLETED;
3119 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3121 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3124 /* usage page (0xFFA0 == vendor defined) */
3125 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3126 /* usage (vendor defined) */
3127 d[i++] = 0x09; d[i++] = 0x01;
3128 /* start collection (application) */
3129 d[i++] = 0xA1; d[i++] = 0x01;
3131 if (dev->input_report_size) {
3132 /* usage (vendor defined) */
3133 d[i++] = 0x09; d[i++] = 0x01;
3134 /* logical minimum (0) */
3135 d[i++] = 0x15; d[i++] = 0x00;
3136 /* logical maximum (255) */
3137 d[i++] = 0x25; d[i++] = 0xFF;
3138 /* report size (8 bits) */
3139 d[i++] = 0x75; d[i++] = 0x08;
3141 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3142 /* input (data, variable, absolute) */
3143 d[i++] = 0x81; d[i++] = 0x00;
3146 if (dev->output_report_size) {
3147 /* usage (vendor defined) */
3148 d[i++] = 0x09; d[i++] = 0x02;
3149 /* logical minimum (0) */
3150 d[i++] = 0x15; d[i++] = 0x00;
3151 /* logical maximum (255) */
3152 d[i++] = 0x25; d[i++] = 0xFF;
3153 /* report size (8 bits) */
3154 d[i++] = 0x75; d[i++] = 0x08;
3156 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3157 /* output (data, variable, absolute) */
3158 d[i++] = 0x91; d[i++] = 0x00;
3160 /* feature report */
3161 if (dev->feature_report_size) {
3162 /* usage (vendor defined) */
3163 d[i++] = 0x09; d[i++] = 0x03;
3164 /* logical minimum (0) */
3165 d[i++] = 0x15; d[i++] = 0x00;
3166 /* logical maximum (255) */
3167 d[i++] = 0x25; d[i++] = 0xFF;
3168 /* report size (8 bits) */
3169 d[i++] = 0x75; d[i++] = 0x08;
3171 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3172 /* feature (data, variable, absolute) */
3173 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3176 /* end collection */
3181 memcpy(data, d, *size);
3182 return LIBUSB_COMPLETED;
3185 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3186 int type, int _index, void *data, size_t *size)
3189 case LIBUSB_DT_DEVICE:
3190 usbi_dbg("LIBUSB_DT_DEVICE");
3191 return _hid_get_device_descriptor(dev, data, size);
3192 case LIBUSB_DT_CONFIG:
3193 usbi_dbg("LIBUSB_DT_CONFIG");
3195 return _hid_get_config_descriptor(dev, data, size);
3196 return LIBUSB_ERROR_INVALID_PARAM;
3197 case LIBUSB_DT_STRING:
3198 usbi_dbg("LIBUSB_DT_STRING");
3199 return _hid_get_string_descriptor(dev, _index, data, size);
3201 usbi_dbg("LIBUSB_DT_HID");
3203 return _hid_get_hid_descriptor(dev, data, size);
3204 return LIBUSB_ERROR_INVALID_PARAM;
3205 case LIBUSB_DT_REPORT:
3206 usbi_dbg("LIBUSB_DT_REPORT");
3208 return _hid_get_report_descriptor(dev, data, size);
3209 return LIBUSB_ERROR_INVALID_PARAM;
3210 case LIBUSB_DT_PHYSICAL:
3211 usbi_dbg("LIBUSB_DT_PHYSICAL");
3212 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3213 return LIBUSB_COMPLETED;
3214 return LIBUSB_ERROR_OTHER;
3216 usbi_dbg("unsupported");
3217 return LIBUSB_ERROR_INVALID_PARAM;
3220 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3221 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3225 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3226 int r = LIBUSB_SUCCESS;
3228 if (tp->hid_buffer != NULL) {
3229 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3232 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3233 usbi_dbg("invalid size (%d)", *size);
3234 return LIBUSB_ERROR_INVALID_PARAM;
3237 switch (report_type) {
3238 case HID_REPORT_TYPE_INPUT:
3239 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3241 case HID_REPORT_TYPE_FEATURE:
3242 ioctl_code = IOCTL_HID_GET_FEATURE;
3245 usbi_dbg("unknown HID report type %d", report_type);
3246 return LIBUSB_ERROR_INVALID_PARAM;
3249 // Add a trailing byte to detect overflows
3250 buf = (uint8_t*)calloc(expected_size+1, 1);
3252 return LIBUSB_ERROR_NO_MEM;
3254 buf[0] = (uint8_t)id; // Must be set always
3255 usbi_dbg("report ID: 0x%02X", buf[0]);
3257 tp->hid_expected_size = expected_size;
3258 read_size = expected_size;
3260 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3261 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3262 buf, expected_size+1, &read_size, overlapped)) {
3263 if (GetLastError() != ERROR_IO_PENDING) {
3264 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3266 return LIBUSB_ERROR_IO;
3268 // Asynchronous wait
3269 tp->hid_buffer = buf;
3270 tp->hid_dest = (uint8_t*)data; // copy dest, as not necessarily the start of the transfer buffer
3271 return LIBUSB_SUCCESS;
3274 // Transfer completed synchronously => copy and discard extra buffer
3275 if (read_size == 0) {
3276 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3280 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3282 if ((size_t)read_size > expected_size) {
3283 r = LIBUSB_ERROR_OVERFLOW;
3284 usbi_dbg("OVERFLOW!");
3286 r = LIBUSB_COMPLETED;
3289 *size = MIN((size_t)read_size, *size);
3291 // Discard report ID
3292 memcpy(data, buf+1, *size);
3294 memcpy(data, buf, *size);
3301 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3302 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3305 uint8_t *buf = NULL;
3306 DWORD ioctl_code, write_size= (DWORD)*size;
3308 if (tp->hid_buffer != NULL) {
3309 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3312 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3313 usbi_dbg("invalid size (%d)", *size);
3314 return LIBUSB_ERROR_INVALID_PARAM;
3317 switch (report_type) {
3318 case HID_REPORT_TYPE_OUTPUT:
3319 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3321 case HID_REPORT_TYPE_FEATURE:
3322 ioctl_code = IOCTL_HID_SET_FEATURE;
3325 usbi_dbg("unknown HID report type %d", report_type);
3326 return LIBUSB_ERROR_INVALID_PARAM;
3329 usbi_dbg("report ID: 0x%02X", id);
3330 // When report IDs are not used (i.e. when id == 0), we must add
3331 // a null report ID. Otherwise, we just use original data buffer
3335 buf = (uint8_t*) malloc(write_size);
3337 return LIBUSB_ERROR_NO_MEM;
3341 memcpy(buf + 1, data, *size);
3343 // This seems like a waste, but if we don't duplicate the
3344 // data, we'll get issues when freeing hid_buffer
3345 memcpy(buf, data, *size);
3347 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3351 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3352 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3353 buf, write_size, &write_size, overlapped)) {
3354 if (GetLastError() != ERROR_IO_PENDING) {
3355 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3357 return LIBUSB_ERROR_IO;
3359 tp->hid_buffer = buf;
3360 tp->hid_dest = NULL;
3361 return LIBUSB_SUCCESS;
3364 // Transfer completed synchronously
3366 if (write_size == 0) {
3367 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3370 return LIBUSB_COMPLETED;
3373 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3374 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3375 size_t *size, OVERLAPPED* overlapped)
3377 int report_type = (value >> 8) & 0xFF;
3378 int report_id = value & 0xFF;
3380 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3381 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3382 return LIBUSB_ERROR_INVALID_PARAM;
3384 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3385 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3387 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3388 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3390 return LIBUSB_ERROR_INVALID_PARAM;
3397 static int hid_init(struct libusb_context *ctx)
3399 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3400 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3401 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3402 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3403 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3404 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3405 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3406 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3407 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3408 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3409 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3410 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3411 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3412 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3413 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3414 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3416 api_hid_available = true;
3417 return LIBUSB_SUCCESS;
3420 static int hid_exit(void)
3422 return LIBUSB_SUCCESS;
3425 // NB: open and close must ensure that they only handle interface of
3426 // the right API type, as these functions can be called wholesale from
3427 // composite_open(), with interfaces belonging to different APIs
3428 static int hid_open(struct libusb_device_handle *dev_handle)
3430 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3431 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3432 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3434 HIDD_ATTRIBUTES hid_attributes;
3435 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3436 HIDP_CAPS capabilities;
3437 HIDP_VALUE_CAPS *value_caps;
3439 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3441 // report IDs handling
3443 char* type[3] = {"input", "output", "feature"};
3444 int nb_ids[2]; // zero and nonzero report IDs
3446 CHECK_HID_AVAILABLE;
3447 if (priv->hid == NULL) {
3448 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3449 return LIBUSB_ERROR_NOT_FOUND;
3452 for (i = 0; i < USB_MAXINTERFACES; i++) {
3453 if ( (priv->usb_interface[i].path != NULL)
3454 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3455 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3456 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3458 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3459 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3460 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3461 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3462 * HidD_GetFeature (if the device supports Feature reports)."
3464 if (hid_handle == INVALID_HANDLE_VALUE) {
3465 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3466 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3467 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3468 if (hid_handle == INVALID_HANDLE_VALUE) {
3469 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3470 switch(GetLastError()) {
3471 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3472 return LIBUSB_ERROR_NO_DEVICE;
3473 case ERROR_ACCESS_DENIED:
3474 return LIBUSB_ERROR_ACCESS;
3476 return LIBUSB_ERROR_IO;
3479 priv->usb_interface[i].restricted_functionality = true;
3481 handle_priv->interface_handle[i].api_handle = hid_handle;
3485 hid_attributes.Size = sizeof(hid_attributes);
3487 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3488 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3492 priv->hid->vid = hid_attributes.VendorID;
3493 priv->hid->pid = hid_attributes.ProductID;
3495 // Set the maximum available input buffer size
3496 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3497 usbi_dbg("set maximum input buffer size to %d", i/2);
3499 // Get the maximum input and output report size
3500 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3501 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3504 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3505 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3509 // Find out if interrupt will need report IDs
3510 size[0] = capabilities.NumberInputValueCaps;
3511 size[1] = capabilities.NumberOutputValueCaps;
3512 size[2] = capabilities.NumberFeatureValueCaps;
3513 for (j=0; j<3; j++) {
3514 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3515 priv->hid->uses_report_ids[j] = false;
3517 value_caps = (HIDP_VALUE_CAPS*) calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3518 if ( (value_caps != NULL)
3519 && (HidP_GetValueCaps(j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3520 && (size[j] >= 1) ) {
3523 for (i=0; i<(int)size[j]; i++) {
3524 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3525 if (value_caps[i].ReportID != 0) {
3531 if (nb_ids[1] != 0) {
3532 if (nb_ids[0] != 0) {
3533 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3536 priv->hid->uses_report_ids[j] = true;
3539 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3541 safe_free(value_caps);
3545 // Set the report sizes
3546 priv->hid->input_report_size = capabilities.InputReportByteLength;
3547 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3548 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3550 // Fetch string descriptors
3551 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3552 if (priv->hid->string_index[0] != 0) {
3553 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3554 sizeof(priv->hid->string[0]));
3556 priv->hid->string[0][0] = 0;
3558 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3559 if (priv->hid->string_index[1] != 0) {
3560 HidD_GetProductString(hid_handle, priv->hid->string[1],
3561 sizeof(priv->hid->string[1]));
3563 priv->hid->string[1][0] = 0;
3565 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3566 if (priv->hid->string_index[2] != 0) {
3567 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3568 sizeof(priv->hid->string[2]));
3570 priv->hid->string[2][0] = 0;
3574 if (preparsed_data) {
3575 HidD_FreePreparsedData(preparsed_data);
3578 return LIBUSB_SUCCESS;
3581 static void hid_close(struct libusb_device_handle *dev_handle)
3583 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3584 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3588 if (!api_hid_available)
3591 for (i = 0; i < USB_MAXINTERFACES; i++) {
3592 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3593 file_handle = handle_priv->interface_handle[i].api_handle;
3594 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3595 CloseHandle(file_handle);
3601 static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface)
3603 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3604 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3606 CHECK_HID_AVAILABLE;
3608 // NB: Disconnection detection is not possible in this function
3609 if (priv->usb_interface[iface].path == NULL) {
3610 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3613 // We use dev_handle as a flag for interface claimed
3614 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3615 return LIBUSB_ERROR_BUSY; // already claimed
3618 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3620 usbi_dbg("claimed interface %d", iface);
3621 handle_priv->active_interface = iface;
3623 return LIBUSB_SUCCESS;
3626 static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface)
3628 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3629 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3631 CHECK_HID_AVAILABLE;
3633 if (priv->usb_interface[iface].path == NULL) {
3634 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3637 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
3638 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3641 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3643 return LIBUSB_SUCCESS;
3646 static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
3648 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3650 CHECK_HID_AVAILABLE;
3652 if (altsetting > 255) {
3653 return LIBUSB_ERROR_INVALID_PARAM;
3656 if (altsetting != 0) {
3657 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3658 return LIBUSB_ERROR_NOT_SUPPORTED;
3661 return LIBUSB_SUCCESS;
3664 static int hid_submit_control_transfer(struct usbi_transfer *itransfer)
3666 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3667 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3668 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3669 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3670 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3671 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3674 int current_interface, config;
3676 int r = LIBUSB_ERROR_INVALID_PARAM;
3678 CHECK_HID_AVAILABLE;
3680 transfer_priv->pollable_fd = INVALID_WINFD;
3681 safe_free(transfer_priv->hid_buffer);
3682 transfer_priv->hid_dest = NULL;
3683 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3685 if (size > MAX_CTRL_BUFFER_LENGTH) {
3686 return LIBUSB_ERROR_INVALID_PARAM;
3689 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3690 if (current_interface < 0) {
3691 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) {
3692 return LIBUSB_ERROR_NOT_FOUND;
3696 usbi_dbg("will use interface %d", current_interface);
3697 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3698 // Always use the handle returned from usbi_create_fd (wfd.handle)
3699 wfd = usbi_create_fd(hid_handle, _O_RDONLY);
3701 return LIBUSB_ERROR_NO_MEM;
3704 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3705 case LIBUSB_REQUEST_TYPE_STANDARD:
3706 switch(setup->request) {
3707 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3708 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3709 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3711 case LIBUSB_REQUEST_GET_CONFIGURATION:
3712 r = windows_get_configuration(transfer->dev_handle, &config);
3713 if (r == LIBUSB_SUCCESS) {
3715 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3716 r = LIBUSB_COMPLETED;
3719 case LIBUSB_REQUEST_SET_CONFIGURATION:
3720 if (setup->value == priv->active_config) {
3721 r = LIBUSB_COMPLETED;
3723 usbi_warn(ctx, "cannot set configuration other than the default one");
3724 r = LIBUSB_ERROR_INVALID_PARAM;
3727 case LIBUSB_REQUEST_GET_INTERFACE:
3729 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3730 r = LIBUSB_COMPLETED;
3732 case LIBUSB_REQUEST_SET_INTERFACE:
3733 r = hid_set_interface_altsetting(transfer->dev_handle, setup->index, setup->value);
3734 if (r == LIBUSB_SUCCESS) {
3735 r = LIBUSB_COMPLETED;
3739 usbi_warn(ctx, "unsupported HID control request");
3740 r = LIBUSB_ERROR_INVALID_PARAM;
3744 case LIBUSB_REQUEST_TYPE_CLASS:
3745 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3746 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3747 &size, wfd.overlapped);
3750 usbi_warn(ctx, "unsupported HID control request");
3751 r = LIBUSB_ERROR_INVALID_PARAM;
3755 if (r == LIBUSB_COMPLETED) {
3756 // Force request to be completed synchronously. Transferred size has been set by previous call
3757 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3758 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3759 // set InternalHigh to the number of bytes transferred
3760 wfd.overlapped->InternalHigh = (DWORD)size;
3764 if (r == LIBUSB_SUCCESS) {
3765 // Use priv_transfer to store data needed for async polling
3766 transfer_priv->pollable_fd = wfd;
3767 transfer_priv->interface_number = (uint8_t)current_interface;
3769 usbi_free_fd(wfd.fd);
3775 static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer) {
3776 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3777 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3778 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3779 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3780 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3783 bool direction_in, ret;
3784 int current_interface, length;
3786 int r = LIBUSB_SUCCESS;
3788 CHECK_HID_AVAILABLE;
3790 transfer_priv->pollable_fd = INVALID_WINFD;
3791 transfer_priv->hid_dest = NULL;
3792 safe_free(transfer_priv->hid_buffer);
3794 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3795 if (current_interface < 0) {
3796 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3797 return LIBUSB_ERROR_NOT_FOUND;
3800 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3802 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3803 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3805 wfd = usbi_create_fd(hid_handle, direction_in?_O_RDONLY:_O_WRONLY);
3806 // Always use the handle returned from usbi_create_fd (wfd.handle)
3808 return LIBUSB_ERROR_NO_MEM;
3811 // If report IDs are not in use, an extra prefix byte must be added
3812 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
3813 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
3814 length = transfer->length+1;
3816 length = transfer->length;
3818 // Add a trailing byte to detect overflows on input
3819 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
3820 if (transfer_priv->hid_buffer == NULL) {
3821 return LIBUSB_ERROR_NO_MEM;
3823 transfer_priv->hid_expected_size = length;
3826 transfer_priv->hid_dest = transfer->buffer;
3827 usbi_dbg("reading %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3828 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
3830 if (!priv->hid->uses_report_ids[1]) {
3831 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
3833 // We could actually do without the calloc and memcpy in this case
3834 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3836 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3837 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3840 if (GetLastError() != ERROR_IO_PENDING) {
3841 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3842 usbi_free_fd(wfd.fd);
3843 safe_free(transfer_priv->hid_buffer);
3844 return LIBUSB_ERROR_IO;
3847 // Only write operations that completed synchronously need to free up
3848 // hid_buffer. For reads, copy_transfer_data() handles that process.
3849 if (!direction_in) {
3850 safe_free(transfer_priv->hid_buffer);
3853 usbi_err(ctx, "program assertion failed - no data was transferred");
3856 if (size > (size_t)length) {
3857 usbi_err(ctx, "OVERFLOW!");
3858 r = LIBUSB_ERROR_OVERFLOW;
3860 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3861 wfd.overlapped->InternalHigh = size;
3864 transfer_priv->pollable_fd = wfd;
3865 transfer_priv->interface_number = (uint8_t)current_interface;
3870 static int hid_abort_transfers(struct usbi_transfer *itransfer)
3872 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3873 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
3874 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3876 int current_interface;
3878 CHECK_HID_AVAILABLE;
3880 current_interface = transfer_priv->interface_number;
3881 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3882 CancelIo(hid_handle);
3884 return LIBUSB_SUCCESS;
3887 static int hid_reset_device(struct libusb_device_handle *dev_handle)
3889 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3891 int current_interface;
3893 CHECK_HID_AVAILABLE;
3895 // Flushing the queues on all interfaces is the best we can achieve
3896 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3897 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3898 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
3899 HidD_FlushQueue(hid_handle);
3902 return LIBUSB_SUCCESS;
3905 static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
3907 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3908 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3909 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3911 int current_interface;
3913 CHECK_HID_AVAILABLE;
3915 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3916 if (current_interface < 0) {
3917 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3918 return LIBUSB_ERROR_NOT_FOUND;
3921 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3922 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3924 // No endpoint selection with Microsoft's implementation, so we try to flush the
3925 // whole interface. Should be OK for most case scenarios
3926 if (!HidD_FlushQueue(hid_handle)) {
3927 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3928 // Device was probably disconnected
3929 return LIBUSB_ERROR_NO_DEVICE;
3932 return LIBUSB_SUCCESS;
3935 // This extra function is only needed for HID
3936 static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
3937 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3938 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3939 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3940 int r = LIBUSB_TRANSFER_COMPLETED;
3941 uint32_t corrected_size = io_size;
3943 if (transfer_priv->hid_buffer != NULL) {
3944 // If we have a valid hid_buffer, it means the transfer was async
3945 if (transfer_priv->hid_dest != NULL) { // Data readout
3946 // First, check for overflow
3947 if (corrected_size > transfer_priv->hid_expected_size) {
3948 usbi_err(ctx, "OVERFLOW!");
3949 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
3950 r = LIBUSB_TRANSFER_OVERFLOW;
3953 if (transfer_priv->hid_buffer[0] == 0) {
3954 // Discard the 1 byte report ID prefix
3956 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
3958 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
3960 transfer_priv->hid_dest = NULL;
3962 // For write, we just need to free the hid buffer
3963 safe_free(transfer_priv->hid_buffer);
3965 itransfer->transferred += corrected_size;
3971 * Composite API functions
3973 static int composite_init(struct libusb_context *ctx)
3975 return LIBUSB_SUCCESS;
3978 static int composite_exit(void)
3980 return LIBUSB_SUCCESS;
3983 static int composite_open(struct libusb_device_handle *dev_handle)
3985 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3988 uint8_t flag = 1<<USB_API_WINUSB;
3990 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3991 if (priv->composite_api_flags & flag) {
3992 r = usb_api_backend[api].open(dev_handle);
3993 if (r != LIBUSB_SUCCESS) {
3999 return LIBUSB_SUCCESS;
4002 static void composite_close(struct libusb_device_handle *dev_handle)
4004 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4006 uint8_t flag = 1<<USB_API_WINUSB;
4008 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4009 if (priv->composite_api_flags & flag) {
4010 usb_api_backend[api].close(dev_handle);
4016 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
4018 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4019 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
4022 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
4024 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4025 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
4028 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
4030 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4031 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
4034 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
4036 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4037 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4038 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4041 // Interface shouldn't matter for control, but it does in practice, with Windows'
4042 // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4043 for (pass = 0; pass < 2; pass++) {
4044 for (i=0; i<USB_MAXINTERFACES; i++) {
4045 if (priv->usb_interface[i].path != NULL) {
4046 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4047 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4050 usbi_dbg("using interface %d", i);
4051 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
4056 usbi_err(ctx, "no libusbx supported interfaces to complete request");
4057 return LIBUSB_ERROR_NOT_FOUND;
4060 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
4061 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4062 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4063 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4064 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4065 int current_interface;
4067 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4068 if (current_interface < 0) {
4069 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4070 return LIBUSB_ERROR_NOT_FOUND;
4073 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
4076 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
4077 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4078 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4079 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4080 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4081 int current_interface;
4083 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4084 if (current_interface < 0) {
4085 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4086 return LIBUSB_ERROR_NOT_FOUND;
4089 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
4092 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
4094 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4095 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4096 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4097 int current_interface;
4099 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4100 if (current_interface < 0) {
4101 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4102 return LIBUSB_ERROR_NOT_FOUND;
4105 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
4108 static int composite_abort_control(struct usbi_transfer *itransfer)
4110 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4111 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4112 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4114 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
4117 static int composite_abort_transfers(struct usbi_transfer *itransfer)
4119 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4120 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4121 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4123 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
4126 static int composite_reset_device(struct libusb_device_handle *dev_handle)
4128 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4131 uint8_t flag = 1<<USB_API_WINUSB;
4133 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4134 if (priv->composite_api_flags & flag) {
4135 r = usb_api_backend[api].reset_device(dev_handle);
4136 if (r != LIBUSB_SUCCESS) {
4142 return LIBUSB_SUCCESS;
4145 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
4147 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4148 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4149 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4151 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);