2 * windows backend for libusb 1.0
3 * Copyright (c) 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * Hash table functions adapted from glibc, by Ulrich Drepper et al.
7 * Major code testing contribution by Xiaofan Chen
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 // COMPILATION OPTIONS:
25 // - Should libusb automatically claim (and release) the interfaces it requires?
27 // - Forces instant overlapped completion on timeouts: can prevents extensive
28 // wait in poll, after a timeout, but might affect subsequent API calls.
29 // ***USE AT YOUR OWN RISKS***
30 //#define FORCE_INSTANT_TIMEOUTS
45 #include "poll_windows.h"
46 #include "windows_usb.h"
48 // The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
49 #if defined(_PREFAST_)
50 #pragma warning(disable:28719)
53 // The 2 macros below are used in conjunction with safe loops.
54 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
55 #define LOOP_BREAK(err) { r=err; continue; }
57 extern void usbi_fd_notification(struct libusb_context *ctx);
60 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
61 static int windows_clock_gettime(int clk_id, struct timespec *tp);
62 unsigned __stdcall windows_clock_gettime_threaded(void* param);
63 // WinUSB API prototypes
64 static int winusb_init(struct libusb_context *ctx);
65 static int winusb_exit(void);
66 static int winusb_open(struct libusb_device_handle *dev_handle);
67 static void winusb_close(struct libusb_device_handle *dev_handle);
68 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface);
69 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
70 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
71 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
72 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
73 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
74 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
75 static int winusb_abort_transfers(struct usbi_transfer *itransfer);
76 static int winusb_abort_control(struct usbi_transfer *itransfer);
77 static int winusb_reset_device(struct libusb_device_handle *dev_handle);
78 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
79 // Composite API prototypes
80 static int composite_init(struct libusb_context *ctx);
81 static int composite_exit(void);
82 static int composite_open(struct libusb_device_handle *dev_handle);
83 static void composite_close(struct libusb_device_handle *dev_handle);
84 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
85 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
86 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
87 static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
88 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
89 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
90 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
91 static int composite_abort_transfers(struct usbi_transfer *itransfer);
92 static int composite_abort_control(struct usbi_transfer *itransfer);
93 static int composite_reset_device(struct libusb_device_handle *dev_handle);
94 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
98 uint64_t hires_frequency, hires_ticks_to_ps;
99 const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
100 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
102 static int concurrent_usage = -1;
103 #if defined(AUTO_CLAIM)
104 usbi_mutex_t autoclaim_lock;
107 // NB: index 0 is for monotonic and 1 is for the thread exit event
108 HANDLE timer_thread = NULL;
109 HANDLE timer_mutex = NULL;
110 struct timespec timer_tp;
111 volatile LONG request_count[2] = {0, 1}; // last one must be > 0
112 HANDLE timer_request[2] = { NULL, NULL };
113 HANDLE timer_response = NULL;
115 bool api_winusb_available = false;
116 #define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
118 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
119 if ((guid1 != NULL) && (guid2 != NULL)) {
120 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
125 #if defined(ENABLE_DEBUG_LOGGING) || (defined(_MSC_VER) && _MSC_VER <= 1200)
126 static char* guid_to_string(const GUID* guid)
128 static char guid_string[MAX_GUID_STRING_LENGTH];
130 if (guid == NULL) return NULL;
131 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
132 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
133 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
134 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
140 * Converts a windows error to human readable string
141 * uses retval as errorcode, or, if 0, use GetLastError()
143 #if defined(ENABLE_LOGGING)
144 static char *windows_error_str(uint32_t retval)
146 static char err_string[ERR_BUFFER_SIZE];
150 uint32_t error_code, format_error;
152 error_code = retval?retval:GetLastError();
154 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%d] ", error_code);
156 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
157 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
158 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
160 format_error = GetLastError();
162 safe_sprintf(err_string, ERR_BUFFER_SIZE,
163 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
165 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
167 // Remove CR/LF terminators
168 for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
177 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
178 * Return an allocated sanitized string or NULL on error.
180 static char* sanitize_path(const char* path)
182 const char root_prefix[] = "\\\\.\\";
183 size_t j, size, root_size;
184 char* ret_path = NULL;
190 size = safe_strlen(path)+1;
191 root_size = sizeof(root_prefix)-1;
193 // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
194 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
195 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
196 add_root = root_size;
200 if ((ret_path = (char*)calloc(size, 1)) == NULL)
203 safe_strcpy(&ret_path[add_root], size-add_root, path);
205 // Ensure consistancy with root prefix
206 for (j=0; j<root_size; j++)
207 ret_path[j] = root_prefix[j];
209 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
210 for(j=root_size; j<size; j++) {
211 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
212 if (ret_path[j] == '\\')
220 * Cfgmgr32, OLE32 and SetupAPI DLL functions
222 static int init_dlls(void)
224 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
225 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
226 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
227 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
228 // Prefixed to avoid conflict with header files
229 DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
230 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
231 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
232 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
233 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
234 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
235 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
236 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
237 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
238 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
239 return LIBUSB_SUCCESS;
243 * enumerate interfaces for the whole USB class
246 * dev_info: a pointer to a dev_info list
247 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
248 * usb_class: the generic USB class for which to retrieve interface details
249 * index: zero based index of the interface in the device info list
251 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
252 * structure returned and call this function repeatedly using the same guid (with an
253 * incremented index starting at zero) until all interfaces have been returned.
255 static bool get_devinfo_data(struct libusb_context *ctx,
256 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, char* usb_class, unsigned _index)
259 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
260 if (*dev_info == INVALID_HANDLE_VALUE) {
265 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
266 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
267 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
268 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
269 _index, windows_error_str(0));
271 pSetupDiDestroyDeviceInfoList(*dev_info);
272 *dev_info = INVALID_HANDLE_VALUE;
279 * enumerate interfaces for a specific GUID
282 * dev_info: a pointer to a dev_info list
283 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
284 * guid: the GUID for which to retrieve interface details
285 * index: zero based index of the interface in the device info list
287 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
288 * structure returned and call this function repeatedly using the same guid (with an
289 * incremented index starting at zero) until all interfaces have been returned.
291 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
292 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
294 SP_DEVICE_INTERFACE_DATA dev_interface_data;
295 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
299 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
302 if (dev_info_data != NULL) {
303 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
304 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
305 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
306 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
307 _index, windows_error_str(0));
309 pSetupDiDestroyDeviceInfoList(*dev_info);
310 *dev_info = INVALID_HANDLE_VALUE;
315 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
316 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
317 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
318 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
319 _index, windows_error_str(0));
321 pSetupDiDestroyDeviceInfoList(*dev_info);
322 *dev_info = INVALID_HANDLE_VALUE;
326 // Read interface data (dummy + actual) to access the device path
327 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
328 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
329 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
330 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
331 _index, windows_error_str(0));
335 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
339 if ((dev_interface_details = malloc(size)) == NULL) {
340 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
344 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
345 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
346 dev_interface_details, size, &size, NULL)) {
347 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
348 _index, windows_error_str(0));
351 return dev_interface_details;
354 pSetupDiDestroyDeviceInfoList(*dev_info);
355 *dev_info = INVALID_HANDLE_VALUE;
359 /* Hash table functions - modified From glibc 2.3.2:
360 [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
361 [Knuth] The Art of Computer Programming, part 3 (6.4) */
362 typedef struct htab_entry {
366 htab_entry* htab_table = NULL;
367 usbi_mutex_t htab_write_mutex = NULL;
368 unsigned long htab_size, htab_filled;
370 /* For the used double hash method the table size has to be a prime. To
371 correct the user given table size we need a prime test. This trivial
372 algorithm is adequate because the code is called only during init and
373 the number is likely to be small */
374 static int isprime(unsigned long number)
376 // no even number will be passed
377 unsigned int divider = 3;
379 while((divider * divider < number) && (number % divider != 0))
382 return (number % divider != 0);
385 /* Before using the hash table we must allocate memory for it.
386 We allocate one element more as the found prime number says.
387 This is done for more effective indexing as explained in the
388 comment for the hash function. */
389 static int htab_create(struct libusb_context *ctx, unsigned long nel)
391 if (htab_table != NULL) {
392 usbi_err(ctx, "hash table already allocated");
396 usbi_mutex_init(&htab_write_mutex, NULL);
398 // Change nel to the first prime number not smaller as nel.
404 usbi_dbg("using %d entries hash table", nel);
407 // allocate memory and zero out.
408 htab_table = (htab_entry*)calloc(htab_size + 1, sizeof(htab_entry));
409 if (htab_table == NULL) {
410 usbi_err(ctx, "could not allocate space for hash table");
417 /* After using the hash table it has to be destroyed. */
418 static void htab_destroy(void)
421 if (htab_table == NULL) {
425 for (i=0; i<htab_size; i++) {
426 if (htab_table[i].used) {
427 safe_free(htab_table[i].str);
430 usbi_mutex_destroy(&htab_write_mutex);
431 safe_free(htab_table);
434 /* This is the search function. It uses double hashing with open addressing.
435 We use an trick to speed up the lookup. The table is created with one
436 more element available. This enables us to use the index zero special.
437 This index will never be used because we store the first hash index in
438 the field used where zero means not used. Every other value means used.
439 The used field can be used as a first fast comparison for equality of
440 the stored and the parameter value. This helps to prevent unnecessary
441 expensive calls of strcmp. */
442 static unsigned long htab_hash(char* str)
444 unsigned long hval, hval2;
446 unsigned long r = 5381;
450 // Compute main hash value (algorithm suggested by Nokia)
452 r = ((r << 5) + r) + c;
456 // compute table hash: simply take the modulus
457 hval = r % htab_size;
461 // Try the first index
464 if (htab_table[idx].used) {
465 if ( (htab_table[idx].used == hval)
466 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
470 usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
472 // Second hash function, as suggested in [Knuth]
473 hval2 = 1 + hval % (htab_size - 2);
476 // Because size is prime this guarantees to step through all available indexes
478 idx = htab_size + idx - hval2;
483 // If we visited all entries leave the loop unsuccessfully
488 // If entry is found use it.
489 if ( (htab_table[idx].used == hval)
490 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
494 while (htab_table[idx].used);
497 // Not found => New entry
499 // If the table is full return an error
500 if (htab_filled >= htab_size) {
501 usbi_err(NULL, "hash table is full (%d entries)", htab_size);
505 // Concurrent threads might be storing the same entry at the same time
506 // (eg. "simultaneous" enums from different threads) => use a mutex
507 usbi_mutex_lock(&htab_write_mutex);
508 // Just free any previously allocated string (which should be the same as
509 // new one). The possibility of concurrent threads storing a collision
510 // string (same hash, different string) at the same time is extremely low
511 safe_free(htab_table[idx].str);
512 htab_table[idx].used = hval;
513 htab_table[idx].str = malloc(safe_strlen(str)+1);
514 if (htab_table[idx].str == NULL) {
515 usbi_err(NULL, "could not duplicate string for hash table");
516 usbi_mutex_unlock(&htab_write_mutex);
519 memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
521 usbi_mutex_unlock(&htab_write_mutex);
527 * Returns the session ID of a device's nth level ancestor
528 * If there's no device at the nth level, return 0
530 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
532 DWORD parent_devinst;
533 unsigned long session_id = 0;
534 char* sanitized_path = NULL;
535 char path[MAX_PATH_LENGTH];
538 if (level < 1) return 0;
539 for (i = 0; i<level; i++) {
540 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
543 devinst = parent_devinst;
545 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
548 // TODO (post hotplug): try without sanitizing
549 sanitized_path = sanitize_path(path);
550 if (sanitized_path == NULL) {
553 session_id = htab_hash(sanitized_path);
554 safe_free(sanitized_path);
559 * Populate the endpoints addresses of the device_priv interface helper structs
561 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
564 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
565 struct libusb_config_descriptor *conf_desc;
566 const struct libusb_interface_descriptor *if_desc;
567 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
569 r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
570 if (r != LIBUSB_SUCCESS) {
571 usbi_warn(ctx, "could not read config descriptor: error %d", r);
575 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
576 safe_free(priv->usb_interface[iface].endpoint);
578 if (if_desc->bNumEndpoints == 0) {
579 usbi_dbg("no endpoints found for interface %d", iface);
580 return LIBUSB_SUCCESS;
583 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
584 if (priv->usb_interface[iface].endpoint == NULL) {
585 return LIBUSB_ERROR_NO_MEM;
588 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
589 for (i=0; i<if_desc->bNumEndpoints; i++) {
590 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
591 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
593 libusb_free_config_descriptor(conf_desc);
595 // Extra init is required for WinUSB endpoints
596 if (priv->apib->id == USB_API_WINUSB) {
597 return winusb_configure_endpoints(dev_handle, iface);
600 return LIBUSB_SUCCESS;
603 // Lookup for a match in the list of API driver names
604 static bool is_api_driver(char* driver, uint8_t api)
607 const char sep_str[2] = {LIST_SEPARATOR, 0};
609 size_t len = safe_strlen(driver);
611 if (len == 0) return false;
612 tmp_str = calloc(len+1, 1);
613 if (tmp_str == NULL) return false;
614 memcpy(tmp_str, driver, len+1);
615 tok = strtok(tmp_str, sep_str);
616 while (tok != NULL) {
617 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
618 if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
623 tok = strtok(NULL, sep_str);
630 * auto-claiming and auto-release helper functions
632 #if defined(AUTO_CLAIM)
633 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
635 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
636 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
637 transfer->dev_handle);
638 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
639 int current_interface = *interface_number;
640 int r = LIBUSB_SUCCESS;
642 usbi_mutex_lock(&autoclaim_lock);
643 if (current_interface < 0) // No serviceable interface was found
645 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
646 // Must claim an interface of the same API type
647 if ( (priv->usb_interface[current_interface].apib->id == api_type)
648 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
649 usbi_dbg("auto-claimed interface %d for control request", current_interface);
650 if (handle_priv->autoclaim_count[current_interface] != 0) {
651 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
653 handle_priv->autoclaim_count[current_interface]++;
657 if (current_interface == USB_MAXINTERFACES) {
658 usbi_err(ctx, "could not auto-claim any interface");
659 r = LIBUSB_ERROR_NOT_FOUND;
662 // If we have a valid interface that was autoclaimed, we must increment
663 // its autoclaim count so that we can prevent an early release.
664 if (handle_priv->autoclaim_count[current_interface] != 0) {
665 handle_priv->autoclaim_count[current_interface]++;
668 usbi_mutex_unlock(&autoclaim_lock);
670 *interface_number = current_interface;
675 static void auto_release(struct usbi_transfer *itransfer)
677 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
678 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
679 libusb_device_handle *dev_handle = transfer->dev_handle;
680 struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
683 usbi_mutex_lock(&autoclaim_lock);
684 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
685 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
686 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
687 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
688 if (r == LIBUSB_SUCCESS) {
689 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
691 usbi_dbg("failed to auto-release interface %d (error=%d)",
692 transfer_priv->interface_number, r);
696 usbi_mutex_unlock(&autoclaim_lock);
702 * init: libusb backend init function
704 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
705 * In our implementation, we equate Windows' "HCD" to LibUSB's "bus". Note that bus is zero indexed.
706 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
708 static int windows_init(struct libusb_context *ctx)
710 int i, r = LIBUSB_ERROR_OTHER;
711 OSVERSIONINFO os_version;
713 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
715 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
716 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
717 if (semaphore == NULL) {
718 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
719 return LIBUSB_ERROR_NO_MEM;
722 // A successful wait brings our semaphore count to 0 (unsignaled)
723 // => any concurent wait stalls until the semaphore's release
724 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
725 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
726 CloseHandle(semaphore);
727 return LIBUSB_ERROR_NO_MEM;
730 // NB: concurrent usage supposes that init calls are equally balanced with
731 // exit calls. If init is called more than exit, we will not exit properly
732 if ( ++concurrent_usage == 0 ) { // First init?
734 memset(&os_version, 0, sizeof(OSVERSIONINFO));
735 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
736 windows_version = WINDOWS_UNSUPPORTED;
737 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
738 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
739 windows_version = WINDOWS_XP;
740 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
741 windows_version = WINDOWS_2003; // also includes XP 64
742 } else if (os_version.dwMajorVersion >= 6) {
743 windows_version = WINDOWS_VISTA_AND_LATER;
746 if (windows_version == WINDOWS_UNSUPPORTED) {
747 usbi_err(ctx, "This version of Windows is NOT supported");
748 r = LIBUSB_ERROR_NOT_SUPPORTED;
752 #if defined(AUTO_CLAIM)
753 // We need a lock for proper auto-release
754 usbi_mutex_init(&autoclaim_lock, NULL);
757 // Initialize pollable file descriptors
761 if (init_dlls() != LIBUSB_SUCCESS) {
762 usbi_err(ctx, "could not resolve DLL functions");
763 return LIBUSB_ERROR_NOT_FOUND;
766 // Initialize the low level APIs (we don't care about errors at this stage)
767 for (i=0; i<USB_API_MAX; i++) {
768 usb_api_backend[i].init(ctx);
771 // Because QueryPerformanceCounter might report different values when
772 // running on different cores, we create a separate thread for the timer
773 // calls, which we glue to the first core always to prevent timing discrepancies.
774 r = LIBUSB_ERROR_NO_MEM;
775 for (i = 0; i < 2; i++) {
776 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
777 if (timer_request[i] == NULL) {
778 usbi_err(ctx, "could not create timer request event %d - aborting", i);
782 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
783 if (timer_response == NULL) {
784 usbi_err(ctx, "could not create timer response semaphore - aborting");
787 timer_mutex = CreateMutex(NULL, FALSE, NULL);
788 if (timer_mutex == NULL) {
789 usbi_err(ctx, "could not create timer mutex - aborting");
792 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
793 if (timer_thread == NULL) {
794 usbi_err(ctx, "Unable to create timer thread - aborting");
797 SetThreadAffinityMask(timer_thread, 0);
799 // Create a hash table to store session ids. Second parameter is better if prime
800 htab_create(ctx, HTAB_SIZE);
802 // At this stage, either we went through full init successfully, or didn't need to
805 init_exit: // Holds semaphore here.
806 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
808 SetEvent(timer_request[1]); // actually the signal to quit the thread.
809 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
810 usbi_warn(ctx, "could not wait for timer thread to quit");
811 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
812 // all objects it might have held anyway.
814 CloseHandle(timer_thread);
817 for (i = 0; i < 2; i++) {
818 if (timer_request[i]) {
819 CloseHandle(timer_request[i]);
820 timer_request[i] = NULL;
823 if (timer_response) {
824 CloseHandle(timer_response);
825 timer_response = NULL;
828 CloseHandle(timer_mutex);
834 if (r != LIBUSB_SUCCESS)
835 --concurrent_usage; // Not expected to call libusb_exit if we failed.
837 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
838 CloseHandle(semaphore);
843 * HCD (root) hubs need to have their device descriptor manually populated
845 * Note that, like Microsoft does in the device manager, we populate the
846 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
848 static int force_hcd_device_descriptor(struct libusb_device *dev)
850 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
851 struct libusb_context *ctx = DEVICE_CTX(dev);
854 dev->num_configurations = 1;
855 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
856 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
857 priv->dev_descriptor.bNumConfigurations = 1;
858 priv->active_config = 1;
860 if (priv->parent_dev == NULL) {
861 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
862 return LIBUSB_ERROR_NO_DEVICE;
864 parent_priv = _device_priv(priv->parent_dev);
865 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
866 priv->dev_descriptor.idVendor = (uint16_t)vid;
867 priv->dev_descriptor.idProduct = (uint16_t)pid;
869 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
870 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
871 priv->dev_descriptor.idProduct = 1;
873 return LIBUSB_SUCCESS;
877 * fetch and cache all the config descriptors through I/O
879 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
881 DWORD size, ret_size;
882 struct libusb_context *ctx = DEVICE_CTX(dev);
883 struct windows_device_priv *priv = _device_priv(dev);
887 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
888 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
889 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
891 if (dev->num_configurations == 0)
892 return LIBUSB_ERROR_INVALID_PARAM;
894 priv->config_descriptor = malloc(dev->num_configurations * sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
895 if (priv->config_descriptor == NULL)
896 return LIBUSB_ERROR_NO_MEM;
897 for (i=0; i<dev->num_configurations; i++)
898 priv->config_descriptor[i] = NULL;
900 for (i=0, r=LIBUSB_SUCCESS; ; i++)
902 // safe loop: release all dynamic resources
903 safe_free(cd_buf_actual);
905 // safe loop: end of loop condition
906 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
909 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
910 memset(&cd_buf_short, 0, size);
912 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
913 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
914 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
915 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
916 cd_buf_short.req.SetupPacket.wIndex = i;
917 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
919 // Dummy call to get the required data size
920 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
921 &cd_buf_short, size, &ret_size, NULL)) {
922 usbi_err(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
923 LOOP_BREAK(LIBUSB_ERROR_IO);
926 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
927 usbi_err(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
928 LOOP_BREAK(LIBUSB_ERROR_IO);
931 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
932 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST)malloc(size)) == NULL) {
933 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
934 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
936 memset(cd_buf_actual, 0, size);
939 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
940 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
941 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
942 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
943 cd_buf_actual->SetupPacket.wIndex = i;
944 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
946 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
947 cd_buf_actual, size, &ret_size, NULL)) {
948 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
949 LOOP_BREAK(LIBUSB_ERROR_IO);
952 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
954 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
955 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
956 LOOP_BREAK(LIBUSB_ERROR_IO);
959 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
960 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
961 LOOP_BREAK(LIBUSB_ERROR_IO);
964 usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
965 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
967 // Cache the descriptor
968 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
969 if (priv->config_descriptor[i] == NULL)
970 return LIBUSB_ERROR_NO_MEM;
972 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
974 return LIBUSB_SUCCESS;
978 * Populate a libusb device structure
980 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
981 uint8_t port_number, char* device_id, DWORD devinst)
985 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
986 struct windows_device_priv *priv, *parent_priv;
987 struct libusb_context *ctx = DEVICE_CTX(dev);
988 struct libusb_device* tmp_dev;
991 if ((dev == NULL) || (parent_dev == NULL)) {
992 return LIBUSB_ERROR_NOT_FOUND;
994 priv = _device_priv(dev);
995 parent_priv = _device_priv(parent_dev);
996 if (parent_priv->apib->id != USB_API_HUB) {
997 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
998 return LIBUSB_ERROR_NOT_FOUND;
1001 // It is possible for the parent hub not to have been initialized yet
1002 // If that's the case, lookup the ancestors to set the bus number
1003 if (parent_dev->bus_number == 0) {
1005 tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
1006 if (tmp_dev == NULL) break;
1007 if (tmp_dev->bus_number != 0) {
1008 usbi_dbg("got bus number from ancestor #%d", i);
1009 parent_dev->bus_number = tmp_dev->bus_number;
1014 if (parent_dev->bus_number == 0) {
1015 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1016 return LIBUSB_ERROR_NOT_FOUND;
1018 dev->bus_number = parent_dev->bus_number;
1019 priv->port = port_number;
1020 priv->depth = parent_priv->depth + 1;
1021 priv->parent_dev = parent_dev;
1023 // If the device address is already set, we can stop here
1024 if (dev->device_address != 0) {
1025 return LIBUSB_SUCCESS;
1027 memset(&conn_info, 0, sizeof(conn_info));
1028 if (priv->depth != 0) { // Not a HCD hub
1029 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1030 FILE_FLAG_OVERLAPPED, NULL);
1031 if (handle == INVALID_HANDLE_VALUE) {
1032 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1033 return LIBUSB_ERROR_ACCESS;
1035 size = sizeof(conn_info);
1036 conn_info.ConnectionIndex = (ULONG)port_number;
1037 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1038 &conn_info, size, &size, NULL)) {
1039 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1040 device_id, windows_error_str(0));
1041 safe_closehandle(handle);
1042 return LIBUSB_ERROR_NO_DEVICE;
1044 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1045 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1046 safe_closehandle(handle);
1047 return LIBUSB_ERROR_NO_DEVICE;
1049 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1050 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1051 priv->active_config = conn_info.CurrentConfigurationValue;
1052 usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
1053 // If we can't read the config descriptors, just set the number of confs to zero
1054 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1055 dev->num_configurations = 0;
1056 priv->dev_descriptor.bNumConfigurations = 0;
1058 safe_closehandle(handle);
1060 if (conn_info.DeviceAddress > UINT8_MAX) {
1061 usbi_err(ctx, "program assertion failed: device address overflow");
1063 dev->device_address = (uint8_t)conn_info.DeviceAddress;
1064 switch (conn_info.Speed) {
1065 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1066 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1067 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1068 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1070 usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1074 dev->device_address = UINT8_MAX; // Hubs from HCD have a devaddr of 255
1075 force_hcd_device_descriptor(dev);
1078 usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1079 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1081 return LIBUSB_SUCCESS;
1084 // Returns the api type, or 0 if not found/unsupported
1085 static uint8_t get_api_type(struct libusb_context *ctx,
1086 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
1088 // Precedence for filter drivers vs driver is in the order of this array
1089 struct driver_lookup lookup[3] = {
1090 {"\0\0", SPDRP_SERVICE, "driver"},
1091 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1092 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1094 DWORD size, reg_type;
1098 // Check the service & filter names to know the API we should use
1099 for (k=0; k<3; k++) {
1100 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1101 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1102 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1103 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1104 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1105 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1107 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1108 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1109 // (currently ';'), so even if an unsuported one does, it's not an issue
1110 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1111 if (lookup[k].list[l] == 0) {
1112 lookup[k].list[l] = LIST_SEPARATOR;
1115 upperize(lookup[k].list);
1116 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1118 if (GetLastError() != ERROR_INVALID_DATA) {
1119 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1121 lookup[k].list[0] = 0;
1125 for (api=1; api<USB_API_MAX; api++) {
1126 for (k=0; k<3; k++) {
1127 if (is_api_driver(lookup[k].list, api)) {
1128 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1132 if (k >= 3) continue;
1138 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1139 char* dev_interface_path, char* device_id, uint8_t api)
1142 struct windows_device_priv *priv = _device_priv(dev);
1143 int interface_number;
1145 if (priv->apib->id != USB_API_COMPOSITE) {
1146 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1147 return LIBUSB_ERROR_NO_DEVICE;
1150 // Because MI_## are not necessarily in sequential order (some composite
1151 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1152 // interface number from the path's MI value
1153 interface_number = 0;
1154 for (i=0; device_id[i] != 0; ) {
1155 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1156 && (device_id[i++] == '_') ) {
1157 interface_number = (device_id[i++] - '0')*10;
1158 interface_number += device_id[i] - '0';
1163 if (device_id[i] == 0) {
1164 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1165 device_id, interface_number);
1168 if (priv->usb_interface[interface_number].path != NULL) {
1169 usbi_warn(ctx, "interface[%d] already set - ignoring: %s", interface_number, device_id);
1170 return LIBUSB_ERROR_ACCESS;
1173 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1174 priv->usb_interface[interface_number].path = dev_interface_path;
1175 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1176 priv->composite_api_flags |= 1<<api;
1178 return LIBUSB_SUCCESS;
1182 * get_device_list: libusb backend device enumeration function
1184 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1186 struct discovered_devs *discdevs = *_discdevs;
1187 HDEVINFO dev_info = { 0 };
1188 char* usb_class[2] = {"USB", "NUSB3"};
1189 SP_DEVINFO_DATA dev_info_data;
1190 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1191 #define MAX_ENUM_GUIDS 64
1192 const GUID* guid[MAX_ENUM_GUIDS];
1197 int r = LIBUSB_SUCCESS;
1198 int class_index = 0;
1199 unsigned int nb_guids, pass, i, j, ancestor;
1200 char path[MAX_PATH_LENGTH];
1201 char strbuf[MAX_PATH_LENGTH];
1202 struct libusb_device *dev, *parent_dev;
1203 struct windows_device_priv *priv, *parent_priv;
1204 char* dev_interface_path = NULL;
1205 char* dev_id_path = NULL;
1206 unsigned long session_id;
1207 DWORD size, reg_type, port_nr, install_state;
1210 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1214 // Keep a list of newly allocated devs to unref
1215 libusb_device** unref_list;
1216 unsigned int unref_size = 64;
1217 unsigned int unref_cur = 0;
1219 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1220 // PASS 2 : (re)enumerate HUBS
1221 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1222 // and list additional USB device interface GUIDs to explore
1223 // PASS 4 : (re)enumerate master USB devices that have a device interface
1224 // PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.
1226 // Init the GUID table
1227 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1228 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1229 guid[GEN_PASS] = NULL;
1230 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1231 nb_guids = DEV_PASS+1;
1233 unref_list = malloc(unref_size*sizeof(libusb_device*));
1234 if (unref_list == NULL) {
1235 return LIBUSB_ERROR_NO_MEM;
1238 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1239 //#define ENUM_DEBUG
1243 usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
1246 usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
1249 usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
1252 usbi_dbg("PROCESSING GENs");
1255 usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
1259 for (i = 0; ; i++) {
1260 // safe loop: free up any (unprotected) dynamic resource
1261 // NB: this is always executed before breaking the loop
1262 safe_free(dev_interface_details);
1263 safe_free(dev_interface_path);
1264 safe_free(dev_id_path);
1266 priv = parent_priv = NULL;
1267 dev = parent_dev = NULL;
1269 // Safe loop: end of loop conditions
1270 if (r != LIBUSB_SUCCESS) {
1273 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1274 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1277 if (pass != GEN_PASS) {
1278 // Except for GEN, all passes deal with device interfaces
1279 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1280 if (dev_interface_details == NULL) {
1283 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1284 if (dev_interface_path == NULL) {
1285 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1290 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1291 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
1292 while ( (class_index < 2) &&
1293 (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
1300 // Read the Device ID path. This is what we'll use as UID
1301 // Note that if the device is plugged in a different port or hub, the Device ID changes
1302 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1303 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1304 dev_info_data.DevInst);
1307 dev_id_path = sanitize_path(path);
1308 if (dev_id_path == NULL) {
1309 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1310 dev_info_data.DevInst);
1314 usbi_dbg("PRO: %s", dev_id_path);
1317 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1319 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1320 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1321 ®_type, (BYTE*)&port_nr, 4, &size))
1323 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1324 dev_id_path, windows_error_str(0));
1329 // Set API to use or get additional data from generic pass
1330 api = USB_API_UNSUPPORTED;
1335 // We use the GEN pass to detect driverless devices...
1336 size = sizeof(strbuf);
1337 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1338 ®_type, (BYTE*)strbuf, size, &size)) {
1339 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1340 usbi_info(ctx, "libusb will not be able to access it.");
1342 // ...and to add the additional device interface GUIDs
1343 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1344 if (key != INVALID_HANDLE_VALUE) {
1345 size = sizeof(guid_string_w);
1346 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1347 (BYTE*)guid_string_w, &size);
1349 if (s == ERROR_SUCCESS) {
1350 if (nb_guids >= MAX_ENUM_GUIDS) {
1351 // If this assert is ever reported, grow a GUID table dynamically
1352 usbi_err(ctx, "program assertion failed: too many GUIDs");
1353 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1355 if_guid = calloc(1, sizeof(GUID));
1356 pCLSIDFromString(guid_string_w, if_guid);
1357 guid[nb_guids++] = if_guid;
1358 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1363 // Get the API type (after checking that the driver installation is OK)
1364 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1365 ®_type, (BYTE*)&install_state, 4, &size))
1367 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1368 dev_id_path, windows_error_str(0));
1369 } else if (install_state != 0) {
1370 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1371 dev_id_path, install_state);
1374 api = get_api_type(ctx, &dev_info, &dev_info_data);
1378 // Find parent device (for the passes that need it)
1385 // Go through the ancestors until we see a face we recognize
1387 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1388 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1389 if (session_id == 0) {
1392 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1394 if (parent_dev == NULL) {
1395 usbi_dbg("unlisted ancestor for '%s' (newly connected, etc.) - ignoring", dev_id_path);
1398 parent_priv = _device_priv(parent_dev);
1399 // virtual USB devices are also listed during GEN - don't process these yet
1400 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1406 // Create new or match existing device, using the (hashed) device_id as session id
1407 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1408 // These are the passes that create "new" devices
1409 session_id = htab_hash(dev_id_path);
1410 dev = usbi_get_device_by_session_id(ctx, session_id);
1412 if (pass == DEV_PASS) {
1413 // This can occur if the OS only reports a newly plugged device after we started enum
1414 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1415 " - ignoring", dev_id_path);
1418 usbi_dbg("allocating new device for session [%X]", session_id);
1419 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1420 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1422 windows_device_priv_init(dev);
1423 // Keep track of devices that need unref
1424 unref_list[unref_cur++] = dev;
1425 if (unref_cur >= unref_size) {
1427 unref_list = realloc(unref_list, unref_size*sizeof(libusb_device*));
1428 if (unref_list == NULL) {
1429 usbi_err(ctx, "could not realloc list for unref - aborting.");
1430 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1434 usbi_dbg("found existing device for session [%X] (%d.%d)",
1435 session_id, dev->bus_number, dev->device_address);
1437 priv = _device_priv(dev);
1443 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1444 dev->device_address = 0;
1445 dev->num_configurations = 0;
1446 priv->apib = &usb_api_backend[USB_API_HUB];
1447 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1448 priv->path = dev_interface_path; dev_interface_path = NULL;
1452 // If the device has already been setup, don't do it again
1453 if (priv->path != NULL)
1455 // Take care of API initialization
1456 priv->path = dev_interface_path; dev_interface_path = NULL;
1457 priv->apib = &usb_api_backend[api];
1459 case USB_API_COMPOSITE:
1463 // For other devices, the first interface is the same as the device
1464 priv->usb_interface[0].path = malloc(safe_strlen(priv->path)+1);
1465 if (priv->usb_interface[0].path != NULL) {
1466 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1468 // The following is needed if we want API calls to work for both simple
1469 // and composite devices.
1470 for(j=0; j<USB_MAXINTERFACES; j++) {
1471 priv->usb_interface[j].apib = &usb_api_backend[api];
1477 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1478 if (r == LIBUSB_SUCCESS) {
1479 // Append device to the list of discovered devices
1480 discdevs = discovered_devs_append(*_discdevs, dev);
1482 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1484 *_discdevs = discdevs;
1485 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1486 // This can occur if the device was disconnected but Windows hasn't
1487 // refreshed its enumeration yet - in that case, we ignore the device
1491 default: // later passes
1492 if (parent_priv->apib->id == USB_API_COMPOSITE) {
1493 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1494 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
1495 case LIBUSB_SUCCESS:
1496 dev_interface_path = NULL;
1498 case LIBUSB_ERROR_ACCESS:
1499 // interface has already been set => make sure dev_interface_path is freed then
1511 // Free any additional GUIDs
1512 for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
1513 safe_free(guid[pass]);
1516 // Unref newly allocated devs
1517 for (i=0; i<unref_cur; i++) {
1518 safe_unref_device(unref_list[i]);
1520 safe_free(unref_list);
1526 * exit: libusb backend deinitialization function
1528 static void windows_exit(void)
1532 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1534 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1535 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1536 if (semaphore == NULL) {
1540 // A successful wait brings our semaphore count to 0 (unsignaled)
1541 // => any concurent wait stalls until the semaphore release
1542 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1543 CloseHandle(semaphore);
1547 // Only works if exits and inits are balanced exactly
1548 if (--concurrent_usage < 0) { // Last exit
1549 for (i=0; i<USB_API_MAX; i++) {
1550 usb_api_backend[i].exit();
1555 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1556 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1557 usbi_dbg("could not wait for timer thread to quit");
1558 TerminateThread(timer_thread, 1);
1560 CloseHandle(timer_thread);
1561 timer_thread = NULL;
1563 for (i = 0; i < 2; i++) {
1564 if (timer_request[i]) {
1565 CloseHandle(timer_request[i]);
1566 timer_request[i] = NULL;
1569 if (timer_response) {
1570 CloseHandle(timer_response);
1571 timer_response = NULL;
1574 CloseHandle(timer_mutex);
1580 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1581 CloseHandle(semaphore);
1584 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1586 struct windows_device_priv *priv = _device_priv(dev);
1588 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1591 return LIBUSB_SUCCESS;
1594 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1596 struct windows_device_priv *priv = _device_priv(dev);
1597 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1600 // config index is zero based
1601 if (config_index >= dev->num_configurations)
1602 return LIBUSB_ERROR_INVALID_PARAM;
1604 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1605 return LIBUSB_ERROR_NOT_FOUND;
1607 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1609 size = min(config_header->wTotalLength, len);
1610 memcpy(buffer, priv->config_descriptor[config_index], size);
1612 return LIBUSB_SUCCESS;
1616 * return the cached copy of the active config descriptor
1618 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1620 struct windows_device_priv *priv = _device_priv(dev);
1622 if (priv->active_config == 0)
1623 return LIBUSB_ERROR_NOT_FOUND;
1625 // config index is zero based
1626 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1629 static int windows_open(struct libusb_device_handle *dev_handle)
1631 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1632 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1634 if (priv->apib == NULL) {
1635 usbi_err(ctx, "program assertion failed - device is not initialized");
1636 return LIBUSB_ERROR_NO_DEVICE;
1639 return priv->apib->open(dev_handle);
1642 static void windows_close(struct libusb_device_handle *dev_handle)
1644 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1646 priv->apib->close(dev_handle);
1649 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1651 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1653 if (priv->active_config == 0) {
1655 return LIBUSB_ERROR_NOT_FOUND;
1658 *config = priv->active_config;
1659 return LIBUSB_SUCCESS;
1663 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1664 * does not currently expose a service that allows higher-level drivers to set
1665 * the configuration."
1667 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1669 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1670 int r = LIBUSB_SUCCESS;
1672 if (config >= USB_MAXCONFIG)
1673 return LIBUSB_ERROR_INVALID_PARAM;
1675 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1676 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1677 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1680 if (r == LIBUSB_SUCCESS) {
1681 priv->active_config = (uint8_t)config;
1686 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1688 int r = LIBUSB_SUCCESS;
1689 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1691 if (iface >= USB_MAXINTERFACES)
1692 return LIBUSB_ERROR_INVALID_PARAM;
1694 safe_free(priv->usb_interface[iface].endpoint);
1695 priv->usb_interface[iface].nb_endpoints= 0;
1697 r = priv->apib->claim_interface(dev_handle, iface);
1699 if (r == LIBUSB_SUCCESS) {
1700 r = windows_assign_endpoints(dev_handle, iface, 0);
1706 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1708 int r = LIBUSB_SUCCESS;
1709 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1711 safe_free(priv->usb_interface[iface].endpoint);
1712 priv->usb_interface[iface].nb_endpoints= 0;
1714 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1716 if (r == LIBUSB_SUCCESS) {
1717 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1723 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1725 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1727 return priv->apib->release_interface(dev_handle, iface);
1730 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1732 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1733 return priv->apib->clear_halt(dev_handle, endpoint);
1736 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1738 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1739 return priv->apib->reset_device(dev_handle);
1742 // The 3 functions below are unlikely to ever get supported on Windows
1743 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1745 return LIBUSB_ERROR_NOT_SUPPORTED;
1748 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1750 return LIBUSB_ERROR_NOT_SUPPORTED;
1753 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1755 return LIBUSB_ERROR_NOT_SUPPORTED;
1758 static void windows_destroy_device(struct libusb_device *dev)
1760 windows_device_priv_release(dev);
1763 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1765 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1767 usbi_free_fd(transfer_priv->pollable_fd.fd);
1768 #if defined(AUTO_CLAIM)
1769 // When auto claim is in use, attempt to release the auto-claimed interface
1770 auto_release(itransfer);
1774 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1776 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1777 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1778 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1779 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1782 r = priv->apib->submit_bulk_transfer(itransfer);
1783 if (r != LIBUSB_SUCCESS) {
1787 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1788 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1789 #if !defined(DYNAMIC_FDS)
1790 usbi_fd_notification(ctx);
1793 return LIBUSB_SUCCESS;
1796 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1798 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1799 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1800 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1801 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1804 r = priv->apib->submit_iso_transfer(itransfer);
1805 if (r != LIBUSB_SUCCESS) {
1809 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1810 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1811 #if !defined(DYNAMIC_FDS)
1812 usbi_fd_notification(ctx);
1815 return LIBUSB_SUCCESS;
1818 static int submit_control_transfer(struct usbi_transfer *itransfer)
1820 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1821 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1822 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1823 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1826 r = priv->apib->submit_control_transfer(itransfer);
1827 if (r != LIBUSB_SUCCESS) {
1831 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1832 #if !defined(DYNAMIC_FDS)
1833 usbi_fd_notification(ctx);
1836 return LIBUSB_SUCCESS;
1840 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1842 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1844 switch (transfer->type) {
1845 case LIBUSB_TRANSFER_TYPE_CONTROL:
1846 return submit_control_transfer(itransfer);
1847 case LIBUSB_TRANSFER_TYPE_BULK:
1848 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1849 return submit_bulk_transfer(itransfer);
1850 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1851 return submit_iso_transfer(itransfer);
1853 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1854 return LIBUSB_ERROR_INVALID_PARAM;
1858 static int windows_abort_control(struct usbi_transfer *itransfer)
1860 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1861 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1863 return priv->apib->abort_control(itransfer);
1866 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1868 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1869 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1871 return priv->apib->abort_transfers(itransfer);
1874 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1876 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1877 #if defined(FORCE_INSTANT_TIMEOUTS)
1878 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1880 // Forces instant overlapped completion on timeouts - use at your own risks
1881 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1882 transfer_priv->pollable_fd.overlapped->Internal &= ~STATUS_PENDING;
1885 switch (transfer->type) {
1886 case LIBUSB_TRANSFER_TYPE_CONTROL:
1887 return windows_abort_control(itransfer);
1888 case LIBUSB_TRANSFER_TYPE_BULK:
1889 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1890 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1891 return windows_abort_transfers(itransfer);
1893 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1894 return LIBUSB_ERROR_INVALID_PARAM;
1898 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1900 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1901 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1904 usbi_dbg("handling I/O completion with errcode %d", io_result);
1908 status = priv->apib->copy_transfer_data(itransfer, io_size);
1910 case ERROR_GEN_FAILURE:
1911 usbi_dbg("detected endpoint stall");
1912 status = LIBUSB_TRANSFER_STALL;
1914 case ERROR_SEM_TIMEOUT:
1915 usbi_dbg("detected semaphore timeout");
1916 status = LIBUSB_TRANSFER_TIMED_OUT;
1918 case ERROR_OPERATION_ABORTED:
1919 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1920 usbi_dbg("detected timeout");
1921 status = LIBUSB_TRANSFER_TIMED_OUT;
1923 usbi_dbg("detected operation aborted");
1924 status = LIBUSB_TRANSFER_CANCELLED;
1928 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
1929 status = LIBUSB_TRANSFER_ERROR;
1932 windows_clear_transfer_priv(itransfer); // Cancel polling
1933 usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
1936 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1938 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1940 switch (transfer->type) {
1941 case LIBUSB_TRANSFER_TYPE_CONTROL:
1942 case LIBUSB_TRANSFER_TYPE_BULK:
1943 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1944 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1945 windows_transfer_callback (itransfer, io_result, io_size);
1948 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1952 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
1954 struct windows_transfer_priv* transfer_priv = NULL;
1955 POLL_NFDS_TYPE i = 0;
1957 struct usbi_transfer *transfer;
1958 DWORD io_size, io_result;
1960 usbi_mutex_lock(&ctx->open_devs_lock);
1961 for (i = 0; i < nfds && num_ready > 0; i++) {
1963 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
1965 if (!fds[i].revents) {
1971 // Because a Windows OVERLAPPED is used for poll emulation,
1972 // a pollable fd is created and stored with each transfer
1973 usbi_mutex_lock(&ctx->flying_transfers_lock);
1974 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
1975 transfer_priv = usbi_transfer_get_os_priv(transfer);
1976 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
1981 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1984 // Handle async requests that completed synchronously first
1985 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
1986 io_result = NO_ERROR;
1987 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
1988 // Regular async overlapped
1989 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
1990 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
1991 io_result = NO_ERROR;
1993 io_result = GetLastError();
1995 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
1996 // let handle_callback free the event using the transfer wfd
1997 // If you don't use the transfer wfd, you run a risk of trying to free a
1998 // newly allocated wfd that took the place of the one from the transfer.
1999 windows_handle_callback(transfer, io_result, io_size);
2001 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2002 return LIBUSB_ERROR_NOT_FOUND;
2006 usbi_mutex_unlock(&ctx->open_devs_lock);
2007 return LIBUSB_SUCCESS;
2011 * Monotonic and real time functions
2013 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2015 LARGE_INTEGER hires_counter, li_frequency;
2019 // Init - find out if we have access to a monotonic (hires) timer
2020 if (!QueryPerformanceFrequency(&li_frequency)) {
2021 usbi_dbg("no hires timer available on this platform");
2022 hires_frequency = 0;
2023 hires_ticks_to_ps = UINT64_C(0);
2025 hires_frequency = li_frequency.QuadPart;
2026 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2027 // to picoseconds to compute the tv_nsecs part in clock_gettime
2028 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2029 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2032 // Main loop - wait for requests
2034 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2035 if ( (timer_index != 0) && (timer_index != 1) ) {
2036 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2039 if (request_count[timer_index] == 0) {
2040 // Request already handled
2041 ResetEvent(timer_request[timer_index]);
2042 // There's still a possiblity that a thread sends a request between the
2043 // time we test request_count[] == 0 and we reset the event, in which case
2044 // the request would be ignored. The simple solution to that is to test
2045 // request_count again and process requests if non zero.
2046 if (request_count[timer_index] == 0)
2049 switch (timer_index) {
2051 WaitForSingleObject(timer_mutex, INFINITE);
2052 // Requests to this thread are for hires always
2053 if (QueryPerformanceCounter(&hires_counter) != 0) {
2054 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2055 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2057 // Fallback to real-time if we can't get monotonic value
2058 // Note that real-time clock does not wait on the mutex or this thread.
2059 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2061 ReleaseMutex(timer_mutex);
2063 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2065 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2066 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2069 case 1: // time to quit
2070 usbi_dbg("timer thread quitting");
2074 usbi_dbg("ERROR: broken timer thread");
2078 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2081 ULARGE_INTEGER rtime;
2084 case USBI_CLOCK_MONOTONIC:
2085 if (hires_frequency != 0) {
2087 InterlockedIncrement((LONG*)&request_count[0]);
2088 SetEvent(timer_request[0]);
2089 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2092 WaitForSingleObject(timer_mutex, INFINITE);
2094 ReleaseMutex(timer_mutex);
2095 return LIBUSB_SUCCESS;
2097 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2098 break; // Retry until successful
2100 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2101 return LIBUSB_ERROR_OTHER;
2105 // Fall through and return real-time if monotonic was not detected @ timer init
2106 case USBI_CLOCK_REALTIME:
2107 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2108 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2109 // Note however that our resolution is bounded by the Windows system time
2110 // functions and is at best of the order of 1 ms (or, usually, worse)
2111 GetSystemTimeAsFileTime(&filetime);
2112 rtime.LowPart = filetime.dwLowDateTime;
2113 rtime.HighPart = filetime.dwHighDateTime;
2114 rtime.QuadPart -= epoch_time;
2115 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2116 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2117 return LIBUSB_SUCCESS;
2119 return LIBUSB_ERROR_INVALID_PARAM;
2124 // NB: MSVC6 does not support named initializers.
2125 const struct usbi_os_backend windows_backend = {
2130 windows_get_device_list,
2134 windows_get_device_descriptor,
2135 windows_get_active_config_descriptor,
2136 windows_get_config_descriptor,
2138 windows_get_configuration,
2139 windows_set_configuration,
2140 windows_claim_interface,
2141 windows_release_interface,
2143 windows_set_interface_altsetting,
2145 windows_reset_device,
2147 windows_kernel_driver_active,
2148 windows_detach_kernel_driver,
2149 windows_attach_kernel_driver,
2151 windows_destroy_device,
2153 windows_submit_transfer,
2154 windows_cancel_transfer,
2155 windows_clear_transfer_priv,
2157 windows_handle_events,
2159 windows_clock_gettime,
2160 #if defined(USBI_TIMERFD_AVAILABLE)
2163 sizeof(struct windows_device_priv),
2164 sizeof(struct windows_device_handle_priv),
2165 sizeof(struct windows_transfer_priv),
2173 static int unsupported_init(struct libusb_context *ctx) {
2174 return LIBUSB_SUCCESS;
2176 static int unsupported_exit(void) {
2177 return LIBUSB_SUCCESS;
2179 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2180 PRINT_UNSUPPORTED_API(open);
2182 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2183 usbi_dbg("unsupported API call for 'close'");
2185 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2186 PRINT_UNSUPPORTED_API(claim_interface);
2188 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2189 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2191 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2192 PRINT_UNSUPPORTED_API(release_interface);
2194 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2195 PRINT_UNSUPPORTED_API(clear_halt);
2197 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2198 PRINT_UNSUPPORTED_API(reset_device);
2200 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2201 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2203 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2204 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2206 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2207 PRINT_UNSUPPORTED_API(submit_control_transfer);
2209 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2210 PRINT_UNSUPPORTED_API(abort_control);
2212 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2213 PRINT_UNSUPPORTED_API(abort_transfers);
2215 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2216 PRINT_UNSUPPORTED_API(copy_transfer_data);
2219 // These names must be uppercase
2220 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
2221 const char* composite_driver_names[] = {"USBCCGP"};
2222 const char* winusb_driver_names[] = {"WINUSB"};
2223 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2225 USB_API_UNSUPPORTED,
2227 &CLASS_GUID_UNSUPPORTED,
2234 unsupported_claim_interface,
2235 unsupported_set_interface_altsetting,
2236 unsupported_release_interface,
2237 unsupported_clear_halt,
2238 unsupported_reset_device,
2239 unsupported_submit_bulk_transfer,
2240 unsupported_submit_iso_transfer,
2241 unsupported_submit_control_transfer,
2242 unsupported_abort_control,
2243 unsupported_abort_transfers,
2244 unsupported_copy_transfer_data,
2248 &CLASS_GUID_UNSUPPORTED,
2250 sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
2255 unsupported_claim_interface,
2256 unsupported_set_interface_altsetting,
2257 unsupported_release_interface,
2258 unsupported_clear_halt,
2259 unsupported_reset_device,
2260 unsupported_submit_bulk_transfer,
2261 unsupported_submit_iso_transfer,
2262 unsupported_submit_control_transfer,
2263 unsupported_abort_control,
2264 unsupported_abort_transfers,
2265 unsupported_copy_transfer_data,
2269 &CLASS_GUID_COMPOSITE,
2270 composite_driver_names,
2271 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2276 composite_claim_interface,
2277 composite_set_interface_altsetting,
2278 composite_release_interface,
2279 composite_clear_halt,
2280 composite_reset_device,
2281 composite_submit_bulk_transfer,
2282 composite_submit_iso_transfer,
2283 composite_submit_control_transfer,
2284 composite_abort_control,
2285 composite_abort_transfers,
2286 composite_copy_transfer_data,
2290 &CLASS_GUID_LIBUSB_WINUSB,
2291 winusb_driver_names,
2292 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2297 winusb_claim_interface,
2298 winusb_set_interface_altsetting,
2299 winusb_release_interface,
2301 winusb_reset_device,
2302 winusb_submit_bulk_transfer,
2303 unsupported_submit_iso_transfer,
2304 winusb_submit_control_transfer,
2305 winusb_abort_control,
2306 winusb_abort_transfers,
2307 winusb_copy_transfer_data,
2313 * WinUSB API functions
2315 static int winusb_init(struct libusb_context *ctx)
2317 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2318 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2319 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2320 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2321 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2322 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2323 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2324 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2325 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2326 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2327 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2328 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2329 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2330 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2331 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2332 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2333 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2335 api_winusb_available = true;
2336 return LIBUSB_SUCCESS;
2339 static int winusb_exit(void)
2341 return LIBUSB_SUCCESS;
2344 // NB: open and close must ensure that they only handle interface of
2345 // the right API type, as these functions can be called wholesale from
2346 // composite_open(), with interfaces belonging to different APIs
2347 static int winusb_open(struct libusb_device_handle *dev_handle)
2349 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2350 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2351 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2356 CHECK_WINUSB_AVAILABLE;
2358 // WinUSB requires a seperate handle for each interface
2359 for (i = 0; i < USB_MAXINTERFACES; i++) {
2360 if ( (priv->usb_interface[i].path != NULL)
2361 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2362 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2363 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2364 if (file_handle == INVALID_HANDLE_VALUE) {
2365 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2366 switch(GetLastError()) {
2367 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2368 return LIBUSB_ERROR_NO_DEVICE;
2369 case ERROR_ACCESS_DENIED:
2370 return LIBUSB_ERROR_ACCESS;
2372 return LIBUSB_ERROR_IO;
2375 handle_priv->interface_handle[i].dev_handle = file_handle;
2379 return LIBUSB_SUCCESS;
2382 static void winusb_close(struct libusb_device_handle *dev_handle)
2384 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2385 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2389 if (!api_winusb_available)
2392 for (i = 0; i < USB_MAXINTERFACES; i++) {
2393 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2394 file_handle = handle_priv->interface_handle[i].dev_handle;
2395 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2396 CloseHandle(file_handle);
2402 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
2404 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2405 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2406 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2409 uint8_t endpoint_address;
2412 CHECK_WINUSB_AVAILABLE;
2414 // With handle and enpoints set (in parent), we can setup the default pipe properties
2415 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2416 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2417 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2418 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2419 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2420 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2422 if (i == -1) continue; // Other policies don't apply to control endpoint
2424 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2425 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2426 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2428 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2429 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2430 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2432 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2433 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2434 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2437 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2438 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2439 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2443 return LIBUSB_SUCCESS;
2446 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2448 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2449 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2450 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2451 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2452 HANDLE file_handle, winusb_handle;
2454 CHECK_WINUSB_AVAILABLE;
2456 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2457 // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
2458 if ((is_using_usbccgp) || (iface == 0)) {
2459 // composite device (independent interfaces) or interface 0
2460 file_handle = handle_priv->interface_handle[iface].dev_handle;
2461 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2462 return LIBUSB_ERROR_NOT_FOUND;
2465 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2466 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2467 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2469 switch(GetLastError()) {
2470 case ERROR_BAD_COMMAND: // The device was disconnected
2471 return LIBUSB_ERROR_NO_DEVICE;
2473 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2474 return LIBUSB_ERROR_ACCESS;
2477 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2479 // For all other interfaces, use WinUsb_GetAssociatedInterface()
2480 winusb_handle = handle_priv->interface_handle[0].api_handle;
2481 // It is a requirement for multiple interface devices using WinUSB that you
2482 // must first claim the first interface before you claim any other
2483 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2484 #if defined(AUTO_CLAIM)
2485 file_handle = handle_priv->interface_handle[0].dev_handle;
2486 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2487 handle_priv->interface_handle[0].api_handle = winusb_handle;
2488 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2490 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2491 return LIBUSB_ERROR_ACCESS;
2494 usbi_warn(ctx, "you must claim interface 0 before you can claim %d with WinUSB", iface);
2495 return LIBUSB_ERROR_ACCESS;
2498 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2499 &handle_priv->interface_handle[iface].api_handle)) {
2500 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2501 switch(GetLastError()) {
2502 case ERROR_NO_MORE_ITEMS: // invalid iface
2503 return LIBUSB_ERROR_NOT_FOUND;
2504 case ERROR_BAD_COMMAND: // The device was disconnected
2505 return LIBUSB_ERROR_NO_DEVICE;
2506 case ERROR_ALREADY_EXISTS: // already claimed
2507 return LIBUSB_ERROR_BUSY;
2509 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2510 return LIBUSB_ERROR_ACCESS;
2514 usbi_dbg("claimed interface %d", iface);
2515 handle_priv->active_interface = iface;
2517 return LIBUSB_SUCCESS;
2520 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2522 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2523 HANDLE winusb_handle;
2525 CHECK_WINUSB_AVAILABLE;
2527 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2528 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2529 return LIBUSB_ERROR_NOT_FOUND;
2532 WinUsb_Free(winusb_handle);
2533 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2535 return LIBUSB_SUCCESS;
2539 * Return the first valid interface (of the same API type), for control transfers
2541 static int winusb_get_valid_interface(struct libusb_device_handle *dev_handle)
2543 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2546 for (i=0; i<USB_MAXINTERFACES; i++) {
2547 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2548 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2549 && (handle_priv->interface_handle[i].api_handle != 0)
2550 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE) ) {
2558 * Lookup interface by endpoint address. -1 if not found
2560 static int interface_by_endpoint(struct windows_device_priv *priv,
2561 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2564 for (i=0; i<USB_MAXINTERFACES; i++) {
2565 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2567 if (handle_priv->interface_handle[i].api_handle == 0)
2569 if (priv->usb_interface[i].endpoint == NULL)
2571 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2572 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2580 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2582 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2583 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2584 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2585 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2586 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2587 transfer->dev_handle);
2588 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2590 HANDLE winusb_handle;
2591 int current_interface;
2594 CHECK_WINUSB_AVAILABLE;
2596 transfer_priv->pollable_fd = INVALID_WINFD;
2597 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2599 if (size > MAX_CTRL_BUFFER_LENGTH)
2600 return LIBUSB_ERROR_INVALID_PARAM;
2602 current_interface = winusb_get_valid_interface(transfer->dev_handle);
2603 if (current_interface < 0) {
2604 #if defined(AUTO_CLAIM)
2605 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2606 return LIBUSB_ERROR_NOT_FOUND;
2609 usbi_warn(ctx, "no interface available for control transfer");
2610 return LIBUSB_ERROR_NOT_FOUND;
2614 usbi_dbg("will use interface %d", current_interface);
2615 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2617 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2618 // Always use the handle returned from usbi_create_fd (wfd.handle)
2620 return LIBUSB_ERROR_NO_MEM;
2623 // Sending of set configuration control requests from WinUSB creates issues
2624 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2625 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2626 if (setup->value != priv->active_config) {
2627 usbi_warn(ctx, "cannot set configuration other than the default one");
2628 usbi_free_fd(wfd.fd);
2629 return LIBUSB_ERROR_INVALID_PARAM;
2631 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2632 wfd.overlapped->InternalHigh = 0;
2634 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2635 if(GetLastError() != ERROR_IO_PENDING) {
2636 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2637 usbi_free_fd(wfd.fd);
2638 return LIBUSB_ERROR_IO;
2641 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2642 wfd.overlapped->InternalHigh = (DWORD)size;
2646 // Use priv_transfer to store data needed for async polling
2647 transfer_priv->pollable_fd = wfd;
2648 transfer_priv->interface_number = (uint8_t)current_interface;
2650 return LIBUSB_SUCCESS;
2653 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2655 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2656 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2657 HANDLE winusb_handle;
2659 CHECK_WINUSB_AVAILABLE;
2661 if (altsetting > 255) {
2662 return LIBUSB_ERROR_INVALID_PARAM;
2665 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2666 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2667 usbi_err(ctx, "interface must be claimed first");
2668 return LIBUSB_ERROR_NOT_FOUND;
2671 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2672 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2673 return LIBUSB_ERROR_IO;
2676 return LIBUSB_SUCCESS;
2679 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2681 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2682 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2683 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2684 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2685 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2686 HANDLE winusb_handle;
2687 bool direction_in, ret;
2688 int current_interface;
2691 CHECK_WINUSB_AVAILABLE;
2693 transfer_priv->pollable_fd = INVALID_WINFD;
2695 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2696 if (current_interface < 0) {
2697 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2698 return LIBUSB_ERROR_NOT_FOUND;
2701 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2703 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2704 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
2706 wfd = usbi_create_fd(winusb_handle, direction_in?_O_RDONLY:_O_WRONLY);
2707 // Always use the handle returned from usbi_create_fd (wfd.handle)
2709 return LIBUSB_ERROR_NO_MEM;
2713 usbi_dbg("reading %d bytes", transfer->length);
2714 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2716 usbi_dbg("writing %d bytes", transfer->length);
2717 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2720 if(GetLastError() != ERROR_IO_PENDING) {
2721 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2722 usbi_free_fd(wfd.fd);
2723 return LIBUSB_ERROR_IO;
2726 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2727 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2730 transfer_priv->pollable_fd = wfd;
2731 transfer_priv->interface_number = (uint8_t)current_interface;
2733 return LIBUSB_SUCCESS;
2736 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2738 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2739 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2740 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2741 HANDLE winusb_handle;
2742 int current_interface;
2744 CHECK_WINUSB_AVAILABLE;
2746 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2747 if (current_interface < 0) {
2748 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2749 return LIBUSB_ERROR_NOT_FOUND;
2752 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2753 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2755 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2756 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2757 return LIBUSB_ERROR_NO_DEVICE;
2760 return LIBUSB_SUCCESS;
2764 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2765 * through testing as well):
2766 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2767 * the control transfer using CancelIo"
2769 static int winusb_abort_control(struct usbi_transfer *itransfer)
2771 // Cancelling of the I/O is done in the parent
2772 return LIBUSB_SUCCESS;
2775 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2777 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2778 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2779 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2780 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2781 HANDLE winusb_handle;
2782 int current_interface;
2784 CHECK_WINUSB_AVAILABLE;
2786 current_interface = transfer_priv->interface_number;
2787 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2788 usbi_err(ctx, "program assertion failed: invalid interface_number");
2789 return LIBUSB_ERROR_NOT_FOUND;
2791 usbi_dbg("will use interface %d", current_interface);
2793 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2795 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2796 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2797 return LIBUSB_ERROR_NO_DEVICE;
2800 return LIBUSB_SUCCESS;
2804 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2805 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2806 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2807 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2808 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2809 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2811 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2812 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2814 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2815 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2816 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2818 HANDLE winusb_handle;
2821 CHECK_WINUSB_AVAILABLE;
2823 // Reset any available pipe (except control)
2824 for (i=0; i<USB_MAXINTERFACES; i++) {
2825 winusb_handle = handle_priv->interface_handle[i].api_handle;
2826 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2828 // Cancel any pollable I/O
2829 usbi_remove_pollfd(ctx, wfd.fd);
2830 usbi_free_fd(wfd.fd);
2831 wfd = handle_to_winfd(winusb_handle);
2834 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2835 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2836 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2837 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2838 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2839 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2841 // FlushPipe seems to fail on OUT pipes
2842 if ( (priv->usb_interface[i].endpoint[j] & LIBUSB_ENDPOINT_IN)
2843 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2844 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2845 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2847 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2848 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2849 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2855 return LIBUSB_SUCCESS;
2858 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2860 itransfer->transferred += io_size;
2861 return LIBUSB_TRANSFER_COMPLETED;
2866 * Composite API functions
2868 static int composite_init(struct libusb_context *ctx)
2870 return LIBUSB_SUCCESS;
2873 static int composite_exit(void)
2875 return LIBUSB_SUCCESS;
2878 static int composite_open(struct libusb_device_handle *dev_handle)
2880 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2883 uint8_t flag = 1<<USB_API_WINUSB;
2885 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2886 if (priv->composite_api_flags & flag) {
2887 r = usb_api_backend[api].open(dev_handle);
2888 if (r != LIBUSB_SUCCESS) {
2894 return LIBUSB_SUCCESS;
2897 static void composite_close(struct libusb_device_handle *dev_handle)
2899 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2901 uint8_t flag = 1<<USB_API_WINUSB;
2903 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2904 if (priv->composite_api_flags & flag) {
2905 usb_api_backend[api].close(dev_handle);
2911 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2913 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2914 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
2917 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2919 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2920 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
2923 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
2925 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2926 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
2929 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
2931 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2932 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2933 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2936 for (i=0; i<USB_MAXINTERFACES; i++) {
2937 if (priv->usb_interface[i].path != NULL) {
2938 usbi_dbg("using interface %d", i);
2939 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
2943 usbi_err(ctx, "no libusb supported interfaces to complete request");
2944 return LIBUSB_ERROR_NOT_FOUND;
2947 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2948 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2949 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2950 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2951 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2952 int current_interface;
2954 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2955 if (current_interface < 0) {
2956 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2957 return LIBUSB_ERROR_NOT_FOUND;
2960 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
2963 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
2964 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2965 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2966 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2967 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2968 int current_interface;
2970 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2971 if (current_interface < 0) {
2972 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2973 return LIBUSB_ERROR_NOT_FOUND;
2976 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
2979 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2981 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2982 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2983 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2984 int current_interface;
2986 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2987 if (current_interface < 0) {
2988 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2989 return LIBUSB_ERROR_NOT_FOUND;
2992 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
2995 static int composite_abort_control(struct usbi_transfer *itransfer)
2997 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2998 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2999 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3001 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
3004 static int composite_abort_transfers(struct usbi_transfer *itransfer)
3006 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3007 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3008 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3010 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
3013 static int composite_reset_device(struct libusb_device_handle *dev_handle)
3015 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3018 uint8_t flag = 1<<USB_API_WINUSB;
3020 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3021 if (priv->composite_api_flags & flag) {
3022 r = usb_api_backend[api].reset_device(dev_handle);
3023 if (r != LIBUSB_SUCCESS) {
3029 return LIBUSB_SUCCESS;
3032 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
3034 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3035 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3036 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3038 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);