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)
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;
1069 usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1073 dev->device_address = UINT8_MAX; // Hubs from HCD have a devaddr of 255
1074 force_hcd_device_descriptor(dev);
1077 usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1078 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1080 return LIBUSB_SUCCESS;
1083 // Returns the api type, or 0 if not found/unsupported
1084 static uint8_t get_api_type(struct libusb_context *ctx,
1085 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
1087 // Precedence for filter drivers vs driver is in the order of this array
1088 struct driver_lookup lookup[3] = {
1089 {"\0\0", SPDRP_SERVICE, "driver"},
1090 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1091 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1093 DWORD size, reg_type;
1097 // Check the service & filter names to know the API we should use
1098 for (k=0; k<3; k++) {
1099 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1100 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1101 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1102 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1103 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1104 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1106 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1107 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1108 // (currently ';'), so even if an unsuported one does, it's not an issue
1109 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1110 if (lookup[k].list[l] == 0) {
1111 lookup[k].list[l] = LIST_SEPARATOR;
1114 upperize(lookup[k].list);
1115 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1117 if (GetLastError() != ERROR_INVALID_DATA) {
1118 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1120 lookup[k].list[0] = 0;
1124 for (api=1; api<USB_API_MAX; api++) {
1125 for (k=0; k<3; k++) {
1126 if (is_api_driver(lookup[k].list, api)) {
1127 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1131 if (k >= 3) continue;
1137 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1138 char* dev_interface_path, char* device_id, uint8_t api)
1141 struct windows_device_priv *priv = _device_priv(dev);
1142 int interface_number;
1144 if (priv->apib->id != USB_API_COMPOSITE) {
1145 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1146 return LIBUSB_ERROR_NO_DEVICE;
1149 // Because MI_## are not necessarily in sequential order (some composite
1150 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1151 // interface number from the path's MI value
1152 interface_number = 0;
1153 for (i=0; device_id[i] != 0; ) {
1154 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1155 && (device_id[i++] == '_') ) {
1156 interface_number = (device_id[i++] - '0')*10;
1157 interface_number += device_id[i] - '0';
1162 if (device_id[i] == 0) {
1163 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1164 device_id, interface_number);
1167 if (priv->usb_interface[interface_number].path != NULL) {
1168 usbi_warn(ctx, "interface[%d] already set - ignoring: %s", interface_number, device_id);
1169 return LIBUSB_ERROR_ACCESS;
1172 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1173 priv->usb_interface[interface_number].path = dev_interface_path;
1174 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1175 priv->composite_api_flags |= 1<<api;
1177 return LIBUSB_SUCCESS;
1181 * get_device_list: libusb backend device enumeration function
1183 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1185 struct discovered_devs *discdevs = *_discdevs;
1186 HDEVINFO dev_info = { 0 };
1187 char* usb_class[2] = {"USB", "NUSB3"};
1188 SP_DEVINFO_DATA dev_info_data;
1189 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1190 #define MAX_ENUM_GUIDS 64
1191 const GUID* guid[MAX_ENUM_GUIDS];
1196 int r = LIBUSB_SUCCESS;
1197 int class_index = 0;
1198 unsigned int nb_guids, pass, i, j, ancestor;
1199 char path[MAX_PATH_LENGTH];
1200 char strbuf[MAX_PATH_LENGTH];
1201 struct libusb_device *dev, *parent_dev;
1202 struct windows_device_priv *priv, *parent_priv;
1203 char* dev_interface_path = NULL;
1204 char* dev_id_path = NULL;
1205 unsigned long session_id;
1206 DWORD size, reg_type, port_nr, install_state;
1209 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1213 // Keep a list of newly allocated devs to unref
1214 libusb_device** unref_list;
1215 unsigned int unref_size = 64;
1216 unsigned int unref_cur = 0;
1218 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1219 // PASS 2 : (re)enumerate HUBS
1220 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1221 // and list additional USB device interface GUIDs to explore
1222 // PASS 4 : (re)enumerate master USB devices that have a device interface
1223 // PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.
1225 // Init the GUID table
1226 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1227 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1228 guid[GEN_PASS] = NULL;
1229 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1230 nb_guids = DEV_PASS+1;
1232 unref_list = malloc(unref_size*sizeof(libusb_device*));
1233 if (unref_list == NULL) {
1234 return LIBUSB_ERROR_NO_MEM;
1237 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1238 //#define ENUM_DEBUG
1242 usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
1245 usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
1248 usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
1251 usbi_dbg("PROCESSING GENs");
1254 usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
1258 for (i = 0; ; i++) {
1259 // safe loop: free up any (unprotected) dynamic resource
1260 // NB: this is always executed before breaking the loop
1261 safe_free(dev_interface_details);
1262 safe_free(dev_interface_path);
1263 safe_free(dev_id_path);
1265 priv = parent_priv = NULL;
1266 dev = parent_dev = NULL;
1268 // Safe loop: end of loop conditions
1269 if (r != LIBUSB_SUCCESS) {
1272 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1273 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1276 if (pass != GEN_PASS) {
1277 // Except for GEN, all passes deal with device interfaces
1278 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1279 if (dev_interface_details == NULL) {
1282 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1283 if (dev_interface_path == NULL) {
1284 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1289 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1290 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
1291 while ( (class_index < 2) &&
1292 (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
1299 // Read the Device ID path. This is what we'll use as UID
1300 // Note that if the device is plugged in a different port or hub, the Device ID changes
1301 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1302 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1303 dev_info_data.DevInst);
1306 dev_id_path = sanitize_path(path);
1307 if (dev_id_path == NULL) {
1308 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1309 dev_info_data.DevInst);
1313 usbi_dbg("PRO: %s", dev_id_path);
1316 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1318 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1319 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1320 ®_type, (BYTE*)&port_nr, 4, &size))
1322 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1323 dev_id_path, windows_error_str(0));
1328 // Set API to use or get additional data from generic pass
1329 api = USB_API_UNSUPPORTED;
1334 // We use the GEN pass to detect driverless devices...
1335 size = sizeof(strbuf);
1336 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1337 ®_type, (BYTE*)strbuf, size, &size)) {
1338 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1339 usbi_info(ctx, "libusb will not be able to access it.");
1341 // ...and to add the additional device interface GUIDs
1342 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1343 if (key != INVALID_HANDLE_VALUE) {
1344 size = sizeof(guid_string_w);
1345 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1346 (BYTE*)guid_string_w, &size);
1348 if (s == ERROR_SUCCESS) {
1349 if (nb_guids >= MAX_ENUM_GUIDS) {
1350 // If this assert is ever reported, grow a GUID table dynamically
1351 usbi_err(ctx, "program assertion failed: too many GUIDs");
1352 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1354 if_guid = calloc(1, sizeof(GUID));
1355 pCLSIDFromString(guid_string_w, if_guid);
1356 guid[nb_guids++] = if_guid;
1357 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1362 // Get the API type (after checking that the driver installation is OK)
1363 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1364 ®_type, (BYTE*)&install_state, 4, &size))
1366 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1367 dev_id_path, windows_error_str(0));
1368 } else if (install_state != 0) {
1369 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1370 dev_id_path, install_state);
1373 api = get_api_type(ctx, &dev_info, &dev_info_data);
1377 // Find parent device (for the passes that need it)
1384 // Go through the ancestors until we see a face we recognize
1386 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1387 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1388 if (session_id == 0) {
1391 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1393 if (parent_dev == NULL) {
1394 usbi_dbg("unlisted ancestor for '%s' (newly connected, etc.) - ignoring", dev_id_path);
1397 parent_priv = _device_priv(parent_dev);
1398 // virtual USB devices are also listed during GEN - don't process these yet
1399 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1405 // Create new or match existing device, using the (hashed) device_id as session id
1406 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1407 // These are the passes that create "new" devices
1408 session_id = htab_hash(dev_id_path);
1409 dev = usbi_get_device_by_session_id(ctx, session_id);
1411 if (pass == DEV_PASS) {
1412 // This can occur if the OS only reports a newly plugged device after we started enum
1413 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1414 " - ignoring", dev_id_path);
1417 usbi_dbg("allocating new device for session [%X]", session_id);
1418 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1419 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1421 windows_device_priv_init(dev);
1422 // Keep track of devices that need unref
1423 unref_list[unref_cur++] = dev;
1424 if (unref_cur > unref_size) {
1426 unref_list = realloc(unref_list, unref_size*sizeof(libusb_device*));
1427 if (unref_list == NULL) {
1428 usbi_err(ctx, "could not realloc list for unref - aborting.");
1429 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1433 usbi_dbg("found existing device for session [%X] (%d.%d)",
1434 session_id, dev->bus_number, dev->device_address);
1436 priv = _device_priv(dev);
1442 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1443 dev->device_address = 0;
1444 dev->num_configurations = 0;
1445 priv->apib = &usb_api_backend[USB_API_HUB];
1446 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1447 priv->path = dev_interface_path; dev_interface_path = NULL;
1451 // If the device has already been setup, don't do it again
1452 if (priv->path != NULL)
1454 // Take care of API initialization
1455 priv->path = dev_interface_path; dev_interface_path = NULL;
1456 priv->apib = &usb_api_backend[api];
1458 case USB_API_COMPOSITE:
1462 // For other devices, the first interface is the same as the device
1463 priv->usb_interface[0].path = malloc(safe_strlen(priv->path)+1);
1464 if (priv->usb_interface[0].path != NULL) {
1465 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1467 // The following is needed if we want API calls to work for both simple
1468 // and composite devices.
1469 for(j=0; j<USB_MAXINTERFACES; j++) {
1470 priv->usb_interface[j].apib = &usb_api_backend[api];
1476 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1477 if (r == LIBUSB_SUCCESS) {
1478 // Append device to the list of discovered devices
1479 discdevs = discovered_devs_append(*_discdevs, dev);
1481 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1483 *_discdevs = discdevs;
1484 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1485 // This can occur if the device was disconnected but Windows hasn't
1486 // refreshed its enumeration yet - in that case, we ignore the device
1490 default: // later passes
1491 if (parent_priv->apib->id == USB_API_COMPOSITE) {
1492 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1493 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
1494 case LIBUSB_SUCCESS:
1495 dev_interface_path = NULL;
1497 case LIBUSB_ERROR_ACCESS:
1498 // interface has already been set => make sure dev_interface_path is freed then
1510 // Free any additional GUIDs
1511 for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
1512 safe_free(guid[pass]);
1515 // Unref newly allocated devs
1516 for (i=0; i<unref_cur; i++) {
1517 safe_unref_device(unref_list[i]);
1519 safe_free(unref_list);
1525 * exit: libusb backend deinitialization function
1527 static void windows_exit(void)
1531 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1533 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1534 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1535 if (semaphore == NULL) {
1539 // A successful wait brings our semaphore count to 0 (unsignaled)
1540 // => any concurent wait stalls until the semaphore release
1541 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1542 CloseHandle(semaphore);
1546 // Only works if exits and inits are balanced exactly
1547 if (--concurrent_usage < 0) { // Last exit
1548 for (i=0; i<USB_API_MAX; i++) {
1549 usb_api_backend[i].exit();
1554 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1555 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1556 usbi_dbg("could not wait for timer thread to quit");
1557 TerminateThread(timer_thread, 1);
1559 CloseHandle(timer_thread);
1560 timer_thread = NULL;
1562 for (i = 0; i < 2; i++) {
1563 if (timer_request[i]) {
1564 CloseHandle(timer_request[i]);
1565 timer_request[i] = NULL;
1568 if (timer_response) {
1569 CloseHandle(timer_response);
1570 timer_response = NULL;
1573 CloseHandle(timer_mutex);
1579 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1580 CloseHandle(semaphore);
1583 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1585 struct windows_device_priv *priv = _device_priv(dev);
1587 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1590 return LIBUSB_SUCCESS;
1593 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1595 struct windows_device_priv *priv = _device_priv(dev);
1596 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1599 // config index is zero based
1600 if (config_index >= dev->num_configurations)
1601 return LIBUSB_ERROR_INVALID_PARAM;
1603 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1604 return LIBUSB_ERROR_NOT_FOUND;
1606 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1608 size = min(config_header->wTotalLength, len);
1609 memcpy(buffer, priv->config_descriptor[config_index], size);
1611 return LIBUSB_SUCCESS;
1615 * return the cached copy of the active config descriptor
1617 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1619 struct windows_device_priv *priv = _device_priv(dev);
1621 if (priv->active_config == 0)
1622 return LIBUSB_ERROR_NOT_FOUND;
1624 // config index is zero based
1625 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1628 static int windows_open(struct libusb_device_handle *dev_handle)
1630 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1631 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1633 if (priv->apib == NULL) {
1634 usbi_err(ctx, "program assertion failed - device is not initialized");
1635 return LIBUSB_ERROR_NO_DEVICE;
1638 return priv->apib->open(dev_handle);
1641 static void windows_close(struct libusb_device_handle *dev_handle)
1643 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1645 priv->apib->close(dev_handle);
1648 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1650 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1652 if (priv->active_config == 0) {
1654 return LIBUSB_ERROR_NOT_FOUND;
1657 *config = priv->active_config;
1658 return LIBUSB_SUCCESS;
1662 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1663 * does not currently expose a service that allows higher-level drivers to set
1664 * the configuration."
1666 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1668 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1669 int r = LIBUSB_SUCCESS;
1671 if (config >= USB_MAXCONFIG)
1672 return LIBUSB_ERROR_INVALID_PARAM;
1674 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1675 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1676 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1679 if (r == LIBUSB_SUCCESS) {
1680 priv->active_config = (uint8_t)config;
1685 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1687 int r = LIBUSB_SUCCESS;
1688 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1690 if (iface >= USB_MAXINTERFACES)
1691 return LIBUSB_ERROR_INVALID_PARAM;
1693 safe_free(priv->usb_interface[iface].endpoint);
1694 priv->usb_interface[iface].nb_endpoints= 0;
1696 r = priv->apib->claim_interface(dev_handle, iface);
1698 if (r == LIBUSB_SUCCESS) {
1699 r = windows_assign_endpoints(dev_handle, iface, 0);
1705 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1707 int r = LIBUSB_SUCCESS;
1708 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1710 safe_free(priv->usb_interface[iface].endpoint);
1711 priv->usb_interface[iface].nb_endpoints= 0;
1713 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1715 if (r == LIBUSB_SUCCESS) {
1716 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1722 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1724 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1726 return priv->apib->release_interface(dev_handle, iface);
1729 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1731 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1732 return priv->apib->clear_halt(dev_handle, endpoint);
1735 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1737 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1738 return priv->apib->reset_device(dev_handle);
1741 // The 3 functions below are unlikely to ever get supported on Windows
1742 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1744 return LIBUSB_ERROR_NOT_SUPPORTED;
1747 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1749 return LIBUSB_ERROR_NOT_SUPPORTED;
1752 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1754 return LIBUSB_ERROR_NOT_SUPPORTED;
1757 static void windows_destroy_device(struct libusb_device *dev)
1759 windows_device_priv_release(dev);
1762 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1764 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1766 usbi_free_fd(transfer_priv->pollable_fd.fd);
1767 #if defined(AUTO_CLAIM)
1768 // When auto claim is in use, attempt to release the auto-claimed interface
1769 auto_release(itransfer);
1773 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1775 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1776 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1777 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1778 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1781 r = priv->apib->submit_bulk_transfer(itransfer);
1782 if (r != LIBUSB_SUCCESS) {
1786 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1787 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1788 #if !defined(DYNAMIC_FDS)
1789 usbi_fd_notification(ctx);
1792 return LIBUSB_SUCCESS;
1795 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1797 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1798 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1799 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1800 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1803 r = priv->apib->submit_iso_transfer(itransfer);
1804 if (r != LIBUSB_SUCCESS) {
1808 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1809 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1810 #if !defined(DYNAMIC_FDS)
1811 usbi_fd_notification(ctx);
1814 return LIBUSB_SUCCESS;
1817 static int submit_control_transfer(struct usbi_transfer *itransfer)
1819 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1820 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1821 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1822 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1825 r = priv->apib->submit_control_transfer(itransfer);
1826 if (r != LIBUSB_SUCCESS) {
1830 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1831 #if !defined(DYNAMIC_FDS)
1832 usbi_fd_notification(ctx);
1835 return LIBUSB_SUCCESS;
1839 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1841 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1843 switch (transfer->type) {
1844 case LIBUSB_TRANSFER_TYPE_CONTROL:
1845 return submit_control_transfer(itransfer);
1846 case LIBUSB_TRANSFER_TYPE_BULK:
1847 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1848 return submit_bulk_transfer(itransfer);
1849 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1850 return submit_iso_transfer(itransfer);
1852 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1853 return LIBUSB_ERROR_INVALID_PARAM;
1857 static int windows_abort_control(struct usbi_transfer *itransfer)
1859 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1860 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1862 return priv->apib->abort_control(itransfer);
1865 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1867 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1868 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1870 return priv->apib->abort_transfers(itransfer);
1873 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1875 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1876 #if defined(FORCE_INSTANT_TIMEOUTS)
1877 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1879 // Forces instant overlapped completion on timeouts - use at your own risks
1880 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1881 transfer_priv->pollable_fd.overlapped->Internal &= ~STATUS_PENDING;
1884 switch (transfer->type) {
1885 case LIBUSB_TRANSFER_TYPE_CONTROL:
1886 return windows_abort_control(itransfer);
1887 case LIBUSB_TRANSFER_TYPE_BULK:
1888 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1889 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1890 return windows_abort_transfers(itransfer);
1892 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1893 return LIBUSB_ERROR_INVALID_PARAM;
1897 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1899 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1900 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1903 usbi_dbg("handling I/O completion with errcode %d", io_result);
1907 status = priv->apib->copy_transfer_data(itransfer, io_size);
1909 case ERROR_GEN_FAILURE:
1910 usbi_dbg("detected endpoint stall");
1911 status = LIBUSB_TRANSFER_STALL;
1913 case ERROR_SEM_TIMEOUT:
1914 usbi_dbg("detected semaphore timeout");
1915 status = LIBUSB_TRANSFER_TIMED_OUT;
1917 case ERROR_OPERATION_ABORTED:
1918 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1919 usbi_dbg("detected timeout");
1920 status = LIBUSB_TRANSFER_TIMED_OUT;
1922 usbi_dbg("detected operation aborted");
1923 status = LIBUSB_TRANSFER_CANCELLED;
1927 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
1928 status = LIBUSB_TRANSFER_ERROR;
1931 windows_clear_transfer_priv(itransfer); // Cancel polling
1932 usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
1935 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1937 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1939 switch (transfer->type) {
1940 case LIBUSB_TRANSFER_TYPE_CONTROL:
1941 case LIBUSB_TRANSFER_TYPE_BULK:
1942 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1943 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1944 windows_transfer_callback (itransfer, io_result, io_size);
1947 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1951 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
1953 struct windows_transfer_priv* transfer_priv = NULL;
1954 POLL_NFDS_TYPE i = 0;
1956 struct usbi_transfer *transfer;
1957 DWORD io_size, io_result;
1959 usbi_mutex_lock(&ctx->open_devs_lock);
1960 for (i = 0; i < nfds && num_ready > 0; i++) {
1962 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
1964 if (!fds[i].revents) {
1970 // Because a Windows OVERLAPPED is used for poll emulation,
1971 // a pollable fd is created and stored with each transfer
1972 usbi_mutex_lock(&ctx->flying_transfers_lock);
1973 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
1974 transfer_priv = usbi_transfer_get_os_priv(transfer);
1975 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
1980 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1983 // Handle async requests that completed synchronously first
1984 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
1985 io_result = NO_ERROR;
1986 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
1987 // Regular async overlapped
1988 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
1989 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
1990 io_result = NO_ERROR;
1992 io_result = GetLastError();
1994 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
1995 // let handle_callback free the event using the transfer wfd
1996 // If you don't use the transfer wfd, you run a risk of trying to free a
1997 // newly allocated wfd that took the place of the one from the transfer.
1998 windows_handle_callback(transfer, io_result, io_size);
2000 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2001 return LIBUSB_ERROR_NOT_FOUND;
2005 usbi_mutex_unlock(&ctx->open_devs_lock);
2006 return LIBUSB_SUCCESS;
2010 * Monotonic and real time functions
2012 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2014 LARGE_INTEGER hires_counter, li_frequency;
2018 // Init - find out if we have access to a monotonic (hires) timer
2019 if (!QueryPerformanceFrequency(&li_frequency)) {
2020 usbi_dbg("no hires timer available on this platform");
2021 hires_frequency = 0;
2022 hires_ticks_to_ps = UINT64_C(0);
2024 hires_frequency = li_frequency.QuadPart;
2025 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2026 // to picoseconds to compute the tv_nsecs part in clock_gettime
2027 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2028 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2031 // Main loop - wait for requests
2033 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2034 if ( (timer_index != 0) && (timer_index != 1) ) {
2035 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2038 if (request_count[timer_index] == 0) {
2039 // Request already handled
2040 ResetEvent(timer_request[timer_index]);
2041 // There's still a possiblity that a thread sends a request between the
2042 // time we test request_count[] == 0 and we reset the event, in which case
2043 // the request would be ignored. The simple solution to that is to test
2044 // request_count again and process requests if non zero.
2045 if (request_count[timer_index] == 0)
2048 switch (timer_index) {
2050 WaitForSingleObject(timer_mutex, INFINITE);
2051 // Requests to this thread are for hires always
2052 if (QueryPerformanceCounter(&hires_counter) != 0) {
2053 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2054 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2056 // Fallback to real-time if we can't get monotonic value
2057 // Note that real-time clock does not wait on the mutex or this thread.
2058 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2060 ReleaseMutex(timer_mutex);
2062 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2064 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2065 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2068 case 1: // time to quit
2069 usbi_dbg("timer thread quitting");
2073 usbi_dbg("ERROR: broken timer thread");
2077 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2080 ULARGE_INTEGER rtime;
2083 case USBI_CLOCK_MONOTONIC:
2084 if (hires_frequency != 0) {
2086 InterlockedIncrement((LONG*)&request_count[0]);
2087 SetEvent(timer_request[0]);
2088 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2091 WaitForSingleObject(timer_mutex, INFINITE);
2093 ReleaseMutex(timer_mutex);
2094 return LIBUSB_SUCCESS;
2096 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2097 break; // Retry until successful
2099 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2100 return LIBUSB_ERROR_OTHER;
2104 // Fall through and return real-time if monotonic was not detected @ timer init
2105 case USBI_CLOCK_REALTIME:
2106 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2107 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2108 // Note however that our resolution is bounded by the Windows system time
2109 // functions and is at best of the order of 1 ms (or, usually, worse)
2110 GetSystemTimeAsFileTime(&filetime);
2111 rtime.LowPart = filetime.dwLowDateTime;
2112 rtime.HighPart = filetime.dwHighDateTime;
2113 rtime.QuadPart -= epoch_time;
2114 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2115 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2116 return LIBUSB_SUCCESS;
2118 return LIBUSB_ERROR_INVALID_PARAM;
2123 // NB: MSVC6 does not support named initializers.
2124 const struct usbi_os_backend windows_backend = {
2129 windows_get_device_list,
2133 windows_get_device_descriptor,
2134 windows_get_active_config_descriptor,
2135 windows_get_config_descriptor,
2137 windows_get_configuration,
2138 windows_set_configuration,
2139 windows_claim_interface,
2140 windows_release_interface,
2142 windows_set_interface_altsetting,
2144 windows_reset_device,
2146 windows_kernel_driver_active,
2147 windows_detach_kernel_driver,
2148 windows_attach_kernel_driver,
2150 windows_destroy_device,
2152 windows_submit_transfer,
2153 windows_cancel_transfer,
2154 windows_clear_transfer_priv,
2156 windows_handle_events,
2158 windows_clock_gettime,
2159 #if defined(USBI_TIMERFD_AVAILABLE)
2162 sizeof(struct windows_device_priv),
2163 sizeof(struct windows_device_handle_priv),
2164 sizeof(struct windows_transfer_priv),
2172 static int unsupported_init(struct libusb_context *ctx) {
2173 return LIBUSB_SUCCESS;
2175 static int unsupported_exit(void) {
2176 return LIBUSB_SUCCESS;
2178 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2179 PRINT_UNSUPPORTED_API(open);
2181 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2182 usbi_dbg("unsupported API call for 'close'");
2184 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2185 PRINT_UNSUPPORTED_API(claim_interface);
2187 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2188 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2190 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2191 PRINT_UNSUPPORTED_API(release_interface);
2193 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2194 PRINT_UNSUPPORTED_API(clear_halt);
2196 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2197 PRINT_UNSUPPORTED_API(reset_device);
2199 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2200 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2202 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2203 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2205 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2206 PRINT_UNSUPPORTED_API(submit_control_transfer);
2208 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2209 PRINT_UNSUPPORTED_API(abort_control);
2211 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2212 PRINT_UNSUPPORTED_API(abort_transfers);
2214 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2215 PRINT_UNSUPPORTED_API(copy_transfer_data);
2218 // These names must be uppercase
2219 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
2220 const char* composite_driver_names[] = {"USBCCGP"};
2221 const char* winusb_driver_names[] = {"WINUSB"};
2222 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2224 USB_API_UNSUPPORTED,
2226 &CLASS_GUID_UNSUPPORTED,
2233 unsupported_claim_interface,
2234 unsupported_set_interface_altsetting,
2235 unsupported_release_interface,
2236 unsupported_clear_halt,
2237 unsupported_reset_device,
2238 unsupported_submit_bulk_transfer,
2239 unsupported_submit_iso_transfer,
2240 unsupported_submit_control_transfer,
2241 unsupported_abort_control,
2242 unsupported_abort_transfers,
2243 unsupported_copy_transfer_data,
2247 &CLASS_GUID_UNSUPPORTED,
2249 sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
2254 unsupported_claim_interface,
2255 unsupported_set_interface_altsetting,
2256 unsupported_release_interface,
2257 unsupported_clear_halt,
2258 unsupported_reset_device,
2259 unsupported_submit_bulk_transfer,
2260 unsupported_submit_iso_transfer,
2261 unsupported_submit_control_transfer,
2262 unsupported_abort_control,
2263 unsupported_abort_transfers,
2264 unsupported_copy_transfer_data,
2268 &CLASS_GUID_COMPOSITE,
2269 composite_driver_names,
2270 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2275 composite_claim_interface,
2276 composite_set_interface_altsetting,
2277 composite_release_interface,
2278 composite_clear_halt,
2279 composite_reset_device,
2280 composite_submit_bulk_transfer,
2281 composite_submit_iso_transfer,
2282 composite_submit_control_transfer,
2283 composite_abort_control,
2284 composite_abort_transfers,
2285 composite_copy_transfer_data,
2289 &CLASS_GUID_LIBUSB_WINUSB,
2290 winusb_driver_names,
2291 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2296 winusb_claim_interface,
2297 winusb_set_interface_altsetting,
2298 winusb_release_interface,
2300 winusb_reset_device,
2301 winusb_submit_bulk_transfer,
2302 unsupported_submit_iso_transfer,
2303 winusb_submit_control_transfer,
2304 winusb_abort_control,
2305 winusb_abort_transfers,
2306 winusb_copy_transfer_data,
2312 * WinUSB API functions
2314 static int winusb_init(struct libusb_context *ctx)
2316 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2317 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2318 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2319 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2320 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2321 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2322 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2323 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2324 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2325 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2326 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2327 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2328 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2329 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2330 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2331 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2332 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2334 api_winusb_available = true;
2335 return LIBUSB_SUCCESS;
2338 static int winusb_exit(void)
2340 return LIBUSB_SUCCESS;
2343 // NB: open and close must ensure that they only handle interface of
2344 // the right API type, as these functions can be called wholesale from
2345 // composite_open(), with interfaces belonging to different APIs
2346 static int winusb_open(struct libusb_device_handle *dev_handle)
2348 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2349 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2350 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2355 CHECK_WINUSB_AVAILABLE;
2357 // WinUSB requires a seperate handle for each interface
2358 for (i = 0; i < USB_MAXINTERFACES; i++) {
2359 if ( (priv->usb_interface[i].path != NULL)
2360 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2361 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2362 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2363 if (file_handle == INVALID_HANDLE_VALUE) {
2364 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2365 switch(GetLastError()) {
2366 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2367 return LIBUSB_ERROR_NO_DEVICE;
2368 case ERROR_ACCESS_DENIED:
2369 return LIBUSB_ERROR_ACCESS;
2371 return LIBUSB_ERROR_IO;
2374 handle_priv->interface_handle[i].dev_handle = file_handle;
2378 return LIBUSB_SUCCESS;
2381 static void winusb_close(struct libusb_device_handle *dev_handle)
2383 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2384 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2388 if (!api_winusb_available)
2391 for (i = 0; i < USB_MAXINTERFACES; i++) {
2392 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2393 file_handle = handle_priv->interface_handle[i].dev_handle;
2394 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2395 CloseHandle(file_handle);
2401 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
2403 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2404 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2405 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2408 uint8_t endpoint_address;
2411 CHECK_WINUSB_AVAILABLE;
2413 // With handle and enpoints set (in parent), we can setup the default pipe properties
2414 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2415 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2416 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2417 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2418 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2419 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2421 if (i == -1) continue; // Other policies don't apply to control endpoint
2423 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2424 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2425 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2427 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2428 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2429 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2431 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2432 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2433 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2436 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2437 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2438 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2442 return LIBUSB_SUCCESS;
2445 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2447 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2448 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2449 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2450 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2451 HANDLE file_handle, winusb_handle;
2453 CHECK_WINUSB_AVAILABLE;
2455 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2456 // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
2457 if ((is_using_usbccgp) || (iface == 0)) {
2458 // composite device (independent interfaces) or interface 0
2459 file_handle = handle_priv->interface_handle[iface].dev_handle;
2460 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2461 return LIBUSB_ERROR_NOT_FOUND;
2464 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2465 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2466 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2468 switch(GetLastError()) {
2469 case ERROR_BAD_COMMAND: // The device was disconnected
2470 return LIBUSB_ERROR_NO_DEVICE;
2472 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2473 return LIBUSB_ERROR_ACCESS;
2476 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2478 // For all other interfaces, use WinUsb_GetAssociatedInterface()
2479 winusb_handle = handle_priv->interface_handle[0].api_handle;
2480 // It is a requirement for multiple interface devices using WinUSB that you
2481 // must first claim the first interface before you claim any other
2482 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2483 #if defined(AUTO_CLAIM)
2484 file_handle = handle_priv->interface_handle[0].dev_handle;
2485 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2486 handle_priv->interface_handle[0].api_handle = winusb_handle;
2487 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2489 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2490 return LIBUSB_ERROR_ACCESS;
2493 usbi_warn(ctx, "you must claim interface 0 before you can claim %d with WinUSB", iface);
2494 return LIBUSB_ERROR_ACCESS;
2497 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2498 &handle_priv->interface_handle[iface].api_handle)) {
2499 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2500 switch(GetLastError()) {
2501 case ERROR_NO_MORE_ITEMS: // invalid iface
2502 return LIBUSB_ERROR_NOT_FOUND;
2503 case ERROR_BAD_COMMAND: // The device was disconnected
2504 return LIBUSB_ERROR_NO_DEVICE;
2505 case ERROR_ALREADY_EXISTS: // already claimed
2506 return LIBUSB_ERROR_BUSY;
2508 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2509 return LIBUSB_ERROR_ACCESS;
2513 usbi_dbg("claimed interface %d", iface);
2514 handle_priv->active_interface = iface;
2516 return LIBUSB_SUCCESS;
2519 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2521 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2522 HANDLE winusb_handle;
2524 CHECK_WINUSB_AVAILABLE;
2526 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2527 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2528 return LIBUSB_ERROR_NOT_FOUND;
2531 WinUsb_Free(winusb_handle);
2532 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2534 return LIBUSB_SUCCESS;
2538 * Return the first valid interface (of the same API type), for control transfers
2540 static int winusb_get_valid_interface(struct libusb_device_handle *dev_handle)
2542 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2545 for (i=0; i<USB_MAXINTERFACES; i++) {
2546 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2547 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2548 && (handle_priv->interface_handle[i].api_handle != 0)
2549 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE) ) {
2557 * Lookup interface by endpoint address. -1 if not found
2559 static int interface_by_endpoint(struct windows_device_priv *priv,
2560 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2563 for (i=0; i<USB_MAXINTERFACES; i++) {
2564 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2566 if (handle_priv->interface_handle[i].api_handle == 0)
2568 if (priv->usb_interface[i].endpoint == NULL)
2570 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2571 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2579 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2581 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2582 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2583 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2584 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2585 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2586 transfer->dev_handle);
2587 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2589 HANDLE winusb_handle;
2590 int current_interface;
2593 CHECK_WINUSB_AVAILABLE;
2595 transfer_priv->pollable_fd = INVALID_WINFD;
2596 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2598 if (size > MAX_CTRL_BUFFER_LENGTH)
2599 return LIBUSB_ERROR_INVALID_PARAM;
2601 current_interface = winusb_get_valid_interface(transfer->dev_handle);
2602 if (current_interface < 0) {
2603 #if defined(AUTO_CLAIM)
2604 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2605 return LIBUSB_ERROR_NOT_FOUND;
2608 usbi_warn(ctx, "no interface available for control transfer");
2609 return LIBUSB_ERROR_NOT_FOUND;
2613 usbi_dbg("will use interface %d", current_interface);
2614 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2616 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2617 // Always use the handle returned from usbi_create_fd (wfd.handle)
2619 return LIBUSB_ERROR_NO_MEM;
2622 // Sending of set configuration control requests from WinUSB creates issues
2623 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2624 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2625 if (setup->value != priv->active_config) {
2626 usbi_warn(ctx, "cannot set configuration other than the default one");
2627 usbi_free_fd(wfd.fd);
2628 return LIBUSB_ERROR_INVALID_PARAM;
2630 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2631 wfd.overlapped->InternalHigh = 0;
2633 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2634 if(GetLastError() != ERROR_IO_PENDING) {
2635 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2636 usbi_free_fd(wfd.fd);
2637 return LIBUSB_ERROR_IO;
2640 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2641 wfd.overlapped->InternalHigh = (DWORD)size;
2645 // Use priv_transfer to store data needed for async polling
2646 transfer_priv->pollable_fd = wfd;
2647 transfer_priv->interface_number = (uint8_t)current_interface;
2649 return LIBUSB_SUCCESS;
2652 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2654 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2655 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2656 HANDLE winusb_handle;
2658 CHECK_WINUSB_AVAILABLE;
2660 if (altsetting > 255) {
2661 return LIBUSB_ERROR_INVALID_PARAM;
2664 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2665 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2666 usbi_err(ctx, "interface must be claimed first");
2667 return LIBUSB_ERROR_NOT_FOUND;
2670 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2671 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2672 return LIBUSB_ERROR_IO;
2675 return LIBUSB_SUCCESS;
2678 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2680 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2681 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2682 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2683 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2684 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2685 HANDLE winusb_handle;
2686 bool direction_in, ret;
2687 int current_interface;
2690 CHECK_WINUSB_AVAILABLE;
2692 transfer_priv->pollable_fd = INVALID_WINFD;
2694 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2695 if (current_interface < 0) {
2696 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2697 return LIBUSB_ERROR_NOT_FOUND;
2700 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2702 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2703 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
2705 wfd = usbi_create_fd(winusb_handle, direction_in?_O_RDONLY:_O_WRONLY);
2706 // Always use the handle returned from usbi_create_fd (wfd.handle)
2708 return LIBUSB_ERROR_NO_MEM;
2712 usbi_dbg("reading %d bytes", transfer->length);
2713 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2715 usbi_dbg("writing %d bytes", transfer->length);
2716 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2719 if(GetLastError() != ERROR_IO_PENDING) {
2720 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2721 usbi_free_fd(wfd.fd);
2722 return LIBUSB_ERROR_IO;
2725 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2726 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2729 transfer_priv->pollable_fd = wfd;
2730 transfer_priv->interface_number = (uint8_t)current_interface;
2732 return LIBUSB_SUCCESS;
2735 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2737 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2738 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2739 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2740 HANDLE winusb_handle;
2741 int current_interface;
2743 CHECK_WINUSB_AVAILABLE;
2745 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2746 if (current_interface < 0) {
2747 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2748 return LIBUSB_ERROR_NOT_FOUND;
2751 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2752 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2754 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2755 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2756 return LIBUSB_ERROR_NO_DEVICE;
2759 return LIBUSB_SUCCESS;
2763 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2764 * through testing as well):
2765 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2766 * the control transfer using CancelIo"
2768 static int winusb_abort_control(struct usbi_transfer *itransfer)
2770 // Cancelling of the I/O is done in the parent
2771 return LIBUSB_SUCCESS;
2774 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2776 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2777 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2778 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2779 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2780 HANDLE winusb_handle;
2781 int current_interface;
2783 CHECK_WINUSB_AVAILABLE;
2785 current_interface = transfer_priv->interface_number;
2786 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2787 usbi_err(ctx, "program assertion failed: invalid interface_number");
2788 return LIBUSB_ERROR_NOT_FOUND;
2790 usbi_dbg("will use interface %d", current_interface);
2792 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2794 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2795 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2796 return LIBUSB_ERROR_NO_DEVICE;
2799 return LIBUSB_SUCCESS;
2803 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2804 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2805 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2806 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2807 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2808 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2810 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2811 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2813 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2814 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2815 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2817 HANDLE winusb_handle;
2820 CHECK_WINUSB_AVAILABLE;
2822 // Reset any available pipe (except control)
2823 for (i=0; i<USB_MAXINTERFACES; i++) {
2824 winusb_handle = handle_priv->interface_handle[i].api_handle;
2825 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2827 // Cancel any pollable I/O
2828 usbi_remove_pollfd(ctx, wfd.fd);
2829 usbi_free_fd(wfd.fd);
2830 wfd = handle_to_winfd(winusb_handle);
2833 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2834 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2835 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2836 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2837 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2838 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2840 // FlushPipe seems to fail on OUT pipes
2841 if ( (priv->usb_interface[i].endpoint[j] & LIBUSB_ENDPOINT_IN)
2842 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2843 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2844 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2846 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2847 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2848 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2854 return LIBUSB_SUCCESS;
2857 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2859 itransfer->transferred += io_size;
2860 return LIBUSB_TRANSFER_COMPLETED;
2865 * Composite API functions
2867 static int composite_init(struct libusb_context *ctx)
2869 return LIBUSB_SUCCESS;
2872 static int composite_exit(void)
2874 return LIBUSB_SUCCESS;
2877 static int composite_open(struct libusb_device_handle *dev_handle)
2879 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2882 uint8_t flag = 1<<USB_API_WINUSB;
2884 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2885 if (priv->composite_api_flags & flag) {
2886 r = usb_api_backend[api].open(dev_handle);
2887 if (r != LIBUSB_SUCCESS) {
2893 return LIBUSB_SUCCESS;
2896 static void composite_close(struct libusb_device_handle *dev_handle)
2898 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2900 uint8_t flag = 1<<USB_API_WINUSB;
2902 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2903 if (priv->composite_api_flags & flag) {
2904 usb_api_backend[api].close(dev_handle);
2910 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2912 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2913 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
2916 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2918 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2919 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
2922 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
2924 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2925 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
2928 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
2930 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2931 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2932 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2935 for (i=0; i<USB_MAXINTERFACES; i++) {
2936 if (priv->usb_interface[i].path != NULL) {
2937 usbi_dbg("using interface %d", i);
2938 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
2942 usbi_err(ctx, "no libusb supported interfaces to complete request");
2943 return LIBUSB_ERROR_NOT_FOUND;
2946 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2947 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2948 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2949 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2950 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2951 int current_interface;
2953 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2954 if (current_interface < 0) {
2955 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2956 return LIBUSB_ERROR_NOT_FOUND;
2959 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
2962 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
2963 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2964 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2965 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2966 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2967 int current_interface;
2969 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2970 if (current_interface < 0) {
2971 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2972 return LIBUSB_ERROR_NOT_FOUND;
2975 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
2978 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2980 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2981 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2982 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2983 int current_interface;
2985 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2986 if (current_interface < 0) {
2987 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2988 return LIBUSB_ERROR_NOT_FOUND;
2991 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
2994 static int composite_abort_control(struct usbi_transfer *itransfer)
2996 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2997 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2998 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3000 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
3003 static int composite_abort_transfers(struct usbi_transfer *itransfer)
3005 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3006 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3007 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3009 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
3012 static int composite_reset_device(struct libusb_device_handle *dev_handle)
3014 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3017 uint8_t flag = 1<<USB_API_WINUSB;
3019 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3020 if (priv->composite_api_flags & flag) {
3021 r = usb_api_backend[api].reset_device(dev_handle);
3022 if (r != LIBUSB_SUCCESS) {
3028 return LIBUSB_SUCCESS;
3031 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
3033 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3034 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3035 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3037 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);