2 * windows backend for libusbx 1.0
3 * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * 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
37 #include "poll_windows.h"
38 #include "windows_usb.h"
40 // The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
41 #if defined(_PREFAST_)
42 #pragma warning(disable:28719)
45 // The 2 macros below are used in conjunction with safe loops.
46 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
47 #define LOOP_BREAK(err) { r=err; continue; }
49 extern void usbi_fd_notification(struct libusb_context *ctx);
52 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
53 static int windows_clock_gettime(int clk_id, struct timespec *tp);
54 unsigned __stdcall windows_clock_gettime_threaded(void* param);
55 // WinUSB API prototypes
56 static int winusb_init(struct libusb_context *ctx);
57 static int winusb_exit(void);
58 static int winusb_open(struct libusb_device_handle *dev_handle);
59 static void winusb_close(struct libusb_device_handle *dev_handle);
60 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface);
61 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
62 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
63 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
64 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
65 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
66 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
67 static int winusb_abort_transfers(struct usbi_transfer *itransfer);
68 static int winusb_abort_control(struct usbi_transfer *itransfer);
69 static int winusb_reset_device(struct libusb_device_handle *dev_handle);
70 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
71 // Composite API prototypes
72 static int composite_init(struct libusb_context *ctx);
73 static int composite_exit(void);
74 static int composite_open(struct libusb_device_handle *dev_handle);
75 static void composite_close(struct libusb_device_handle *dev_handle);
76 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
77 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
78 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
79 static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
80 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
81 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
82 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
83 static int composite_abort_transfers(struct usbi_transfer *itransfer);
84 static int composite_abort_control(struct usbi_transfer *itransfer);
85 static int composite_reset_device(struct libusb_device_handle *dev_handle);
86 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
90 uint64_t hires_frequency, hires_ticks_to_ps;
91 const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
92 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
94 static int concurrent_usage = -1;
95 usbi_mutex_t autoclaim_lock;
97 // NB: index 0 is for monotonic and 1 is for the thread exit event
98 HANDLE timer_thread = NULL;
99 HANDLE timer_mutex = NULL;
100 struct timespec timer_tp;
101 volatile LONG request_count[2] = {0, 1}; // last one must be > 0
102 HANDLE timer_request[2] = { NULL, NULL };
103 HANDLE timer_response = NULL;
105 bool api_winusb_available = false;
106 #define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
108 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
109 if ((guid1 != NULL) && (guid2 != NULL)) {
110 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
115 #if defined(ENABLE_DEBUG_LOGGING) || (defined(_MSC_VER) && _MSC_VER < 1400)
116 static char* guid_to_string(const GUID* guid)
118 static char guid_string[MAX_GUID_STRING_LENGTH];
120 if (guid == NULL) return NULL;
121 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
122 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
123 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
124 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
130 * Converts a windows error to human readable string
131 * uses retval as errorcode, or, if 0, use GetLastError()
133 #if defined(ENABLE_LOGGING)
134 static char *windows_error_str(uint32_t retval)
136 static char err_string[ERR_BUFFER_SIZE];
140 uint32_t error_code, format_error;
142 error_code = retval?retval:GetLastError();
144 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%d] ", error_code);
146 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
147 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
148 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
150 format_error = GetLastError();
152 safe_sprintf(err_string, ERR_BUFFER_SIZE,
153 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
155 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
157 // Remove CR/LF terminators
158 for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
167 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
168 * Return an allocated sanitized string or NULL on error.
170 static char* sanitize_path(const char* path)
172 const char root_prefix[] = "\\\\.\\";
173 size_t j, size, root_size;
174 char* ret_path = NULL;
180 size = safe_strlen(path)+1;
181 root_size = sizeof(root_prefix)-1;
183 // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
184 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
185 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
186 add_root = root_size;
190 if ((ret_path = (char*) calloc(size, 1)) == NULL)
193 safe_strcpy(&ret_path[add_root], size-add_root, path);
195 // Ensure consistancy with root prefix
196 for (j=0; j<root_size; j++)
197 ret_path[j] = root_prefix[j];
199 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
200 for(j=root_size; j<size; j++) {
201 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
202 if (ret_path[j] == '\\')
210 * Cfgmgr32, OLE32 and SetupAPI DLL functions
212 static int init_dlls(void)
214 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
215 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
216 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
217 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
218 // Prefixed to avoid conflict with header files
219 DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
220 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
221 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
222 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
223 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
224 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
225 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
226 DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
227 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
228 DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
229 return LIBUSB_SUCCESS;
233 * enumerate interfaces for the whole USB class
236 * dev_info: a pointer to a dev_info list
237 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
238 * usb_class: the generic USB class for which to retrieve interface details
239 * index: zero based index of the interface in the device info list
241 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
242 * structure returned and call this function repeatedly using the same guid (with an
243 * incremented index starting at zero) until all interfaces have been returned.
245 static bool get_devinfo_data(struct libusb_context *ctx,
246 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, char* usb_class, unsigned _index)
249 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
250 if (*dev_info == INVALID_HANDLE_VALUE) {
255 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
256 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
257 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
258 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
259 _index, windows_error_str(0));
261 pSetupDiDestroyDeviceInfoList(*dev_info);
262 *dev_info = INVALID_HANDLE_VALUE;
269 * enumerate interfaces for a specific GUID
272 * dev_info: a pointer to a dev_info list
273 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
274 * guid: the GUID for which to retrieve interface details
275 * index: zero based index of the interface in the device info list
277 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
278 * structure returned and call this function repeatedly using the same guid (with an
279 * incremented index starting at zero) until all interfaces have been returned.
281 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
282 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
284 SP_DEVICE_INTERFACE_DATA dev_interface_data;
285 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
289 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
292 if (dev_info_data != NULL) {
293 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
294 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
295 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
296 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
297 _index, windows_error_str(0));
299 pSetupDiDestroyDeviceInfoList(*dev_info);
300 *dev_info = INVALID_HANDLE_VALUE;
305 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
306 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
307 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
308 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
309 _index, windows_error_str(0));
311 pSetupDiDestroyDeviceInfoList(*dev_info);
312 *dev_info = INVALID_HANDLE_VALUE;
316 // Read interface data (dummy + actual) to access the device path
317 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
318 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
319 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
320 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
321 _index, windows_error_str(0));
325 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
329 if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
330 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
334 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
335 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
336 dev_interface_details, size, &size, NULL)) {
337 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
338 _index, windows_error_str(0));
341 return dev_interface_details;
344 pSetupDiDestroyDeviceInfoList(*dev_info);
345 *dev_info = INVALID_HANDLE_VALUE;
349 /* Hash table functions - modified From glibc 2.3.2:
350 [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
351 [Knuth] The Art of Computer Programming, part 3 (6.4) */
352 typedef struct htab_entry {
356 htab_entry* htab_table = NULL;
357 usbi_mutex_t htab_write_mutex = NULL;
358 unsigned long htab_size, htab_filled;
360 /* For the used double hash method the table size has to be a prime. To
361 correct the user given table size we need a prime test. This trivial
362 algorithm is adequate because the code is called only during init and
363 the number is likely to be small */
364 static int isprime(unsigned long number)
366 // no even number will be passed
367 unsigned int divider = 3;
369 while((divider * divider < number) && (number % divider != 0))
372 return (number % divider != 0);
375 /* Before using the hash table we must allocate memory for it.
376 We allocate one element more as the found prime number says.
377 This is done for more effective indexing as explained in the
378 comment for the hash function. */
379 static int htab_create(struct libusb_context *ctx, unsigned long nel)
381 if (htab_table != NULL) {
382 usbi_err(ctx, "hash table already allocated");
386 usbi_mutex_init(&htab_write_mutex, NULL);
388 // Change nel to the first prime number not smaller as nel.
394 usbi_dbg("using %d entries hash table", nel);
397 // allocate memory and zero out.
398 htab_table = (htab_entry*) calloc(htab_size + 1, sizeof(htab_entry));
399 if (htab_table == NULL) {
400 usbi_err(ctx, "could not allocate space for hash table");
407 /* After using the hash table it has to be destroyed. */
408 static void htab_destroy(void)
411 if (htab_table == NULL) {
415 for (i=0; i<htab_size; i++) {
416 if (htab_table[i].used) {
417 safe_free(htab_table[i].str);
420 usbi_mutex_destroy(&htab_write_mutex);
421 safe_free(htab_table);
424 /* This is the search function. It uses double hashing with open addressing.
425 We use an trick to speed up the lookup. The table is created with one
426 more element available. This enables us to use the index zero special.
427 This index will never be used because we store the first hash index in
428 the field used where zero means not used. Every other value means used.
429 The used field can be used as a first fast comparison for equality of
430 the stored and the parameter value. This helps to prevent unnecessary
431 expensive calls of strcmp. */
432 static unsigned long htab_hash(char* str)
434 unsigned long hval, hval2;
436 unsigned long r = 5381;
440 // Compute main hash value (algorithm suggested by Nokia)
442 r = ((r << 5) + r) + c;
446 // compute table hash: simply take the modulus
447 hval = r % htab_size;
451 // Try the first index
454 if (htab_table[idx].used) {
455 if ( (htab_table[idx].used == hval)
456 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
460 usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
462 // Second hash function, as suggested in [Knuth]
463 hval2 = 1 + hval % (htab_size - 2);
466 // Because size is prime this guarantees to step through all available indexes
468 idx = htab_size + idx - hval2;
473 // If we visited all entries leave the loop unsuccessfully
478 // If entry is found use it.
479 if ( (htab_table[idx].used == hval)
480 && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
484 while (htab_table[idx].used);
487 // Not found => New entry
489 // If the table is full return an error
490 if (htab_filled >= htab_size) {
491 usbi_err(NULL, "hash table is full (%d entries)", htab_size);
495 // Concurrent threads might be storing the same entry at the same time
496 // (eg. "simultaneous" enums from different threads) => use a mutex
497 usbi_mutex_lock(&htab_write_mutex);
498 // Just free any previously allocated string (which should be the same as
499 // new one). The possibility of concurrent threads storing a collision
500 // string (same hash, different string) at the same time is extremely low
501 safe_free(htab_table[idx].str);
502 htab_table[idx].used = hval;
503 htab_table[idx].str = (char*) malloc(safe_strlen(str)+1);
504 if (htab_table[idx].str == NULL) {
505 usbi_err(NULL, "could not duplicate string for hash table");
506 usbi_mutex_unlock(&htab_write_mutex);
509 memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
511 usbi_mutex_unlock(&htab_write_mutex);
517 * Returns the session ID of a device's nth level ancestor
518 * If there's no device at the nth level, return 0
520 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
522 DWORD parent_devinst;
523 unsigned long session_id = 0;
524 char* sanitized_path = NULL;
525 char path[MAX_PATH_LENGTH];
528 if (level < 1) return 0;
529 for (i = 0; i<level; i++) {
530 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
533 devinst = parent_devinst;
535 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
538 // TODO (post hotplug): try without sanitizing
539 sanitized_path = sanitize_path(path);
540 if (sanitized_path == NULL) {
543 session_id = htab_hash(sanitized_path);
544 safe_free(sanitized_path);
549 * Populate the endpoints addresses of the device_priv interface helper structs
551 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
554 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
555 struct libusb_config_descriptor *conf_desc;
556 const struct libusb_interface_descriptor *if_desc;
557 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
559 r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
560 if (r != LIBUSB_SUCCESS) {
561 usbi_warn(ctx, "could not read config descriptor: error %d", r);
565 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
566 safe_free(priv->usb_interface[iface].endpoint);
568 if (if_desc->bNumEndpoints == 0) {
569 usbi_dbg("no endpoints found for interface %d", iface);
570 return LIBUSB_SUCCESS;
573 priv->usb_interface[iface].endpoint = (uint8_t*) malloc(if_desc->bNumEndpoints);
574 if (priv->usb_interface[iface].endpoint == NULL) {
575 return LIBUSB_ERROR_NO_MEM;
578 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
579 for (i=0; i<if_desc->bNumEndpoints; i++) {
580 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
581 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
583 libusb_free_config_descriptor(conf_desc);
585 // Extra init is required for WinUSB endpoints
586 if (priv->apib->id == USB_API_WINUSB) {
587 return winusb_configure_endpoints(dev_handle, iface);
590 return LIBUSB_SUCCESS;
593 // Lookup for a match in the list of API driver names
594 static bool is_api_driver(char* driver, uint8_t api)
597 const char sep_str[2] = {LIST_SEPARATOR, 0};
599 size_t len = safe_strlen(driver);
601 if (len == 0) return false;
602 tmp_str = (char*) calloc(len+1, 1);
603 if (tmp_str == NULL) return false;
604 memcpy(tmp_str, driver, len+1);
605 tok = strtok(tmp_str, sep_str);
606 while (tok != NULL) {
607 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
608 if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
613 tok = strtok(NULL, sep_str);
620 * auto-claiming and auto-release helper functions
622 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
624 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
625 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
626 transfer->dev_handle);
627 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
628 int current_interface = *interface_number;
629 int r = LIBUSB_SUCCESS;
631 usbi_mutex_lock(&autoclaim_lock);
632 if (current_interface < 0) // No serviceable interface was found
634 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
635 // Must claim an interface of the same API type
636 if ( (priv->usb_interface[current_interface].apib->id == api_type)
637 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
638 usbi_dbg("auto-claimed interface %d for control request", current_interface);
639 if (handle_priv->autoclaim_count[current_interface] != 0) {
640 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
642 handle_priv->autoclaim_count[current_interface]++;
646 if (current_interface == USB_MAXINTERFACES) {
647 usbi_err(ctx, "could not auto-claim any interface");
648 r = LIBUSB_ERROR_NOT_FOUND;
651 // If we have a valid interface that was autoclaimed, we must increment
652 // its autoclaim count so that we can prevent an early release.
653 if (handle_priv->autoclaim_count[current_interface] != 0) {
654 handle_priv->autoclaim_count[current_interface]++;
657 usbi_mutex_unlock(&autoclaim_lock);
659 *interface_number = current_interface;
664 static void auto_release(struct usbi_transfer *itransfer)
666 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
667 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
668 libusb_device_handle *dev_handle = transfer->dev_handle;
669 struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
672 usbi_mutex_lock(&autoclaim_lock);
673 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
674 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
675 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
676 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
677 if (r == LIBUSB_SUCCESS) {
678 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
680 usbi_dbg("failed to auto-release interface %d (%s)",
681 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
685 usbi_mutex_unlock(&autoclaim_lock);
689 * init: libusbx backend init function
691 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
692 * In our implementation, we equate Windows' "HCD" to libusbx's "bus". Note that bus is zero indexed.
693 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
695 static int windows_init(struct libusb_context *ctx)
697 int i, r = LIBUSB_ERROR_OTHER;
698 OSVERSIONINFO os_version;
700 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
702 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
703 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
704 if (semaphore == NULL) {
705 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
706 return LIBUSB_ERROR_NO_MEM;
709 // A successful wait brings our semaphore count to 0 (unsignaled)
710 // => any concurent wait stalls until the semaphore's release
711 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
712 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
713 CloseHandle(semaphore);
714 return LIBUSB_ERROR_NO_MEM;
717 // NB: concurrent usage supposes that init calls are equally balanced with
718 // exit calls. If init is called more than exit, we will not exit properly
719 if ( ++concurrent_usage == 0 ) { // First init?
721 memset(&os_version, 0, sizeof(OSVERSIONINFO));
722 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
723 windows_version = WINDOWS_UNSUPPORTED;
724 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
725 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
726 windows_version = WINDOWS_XP;
727 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
728 windows_version = WINDOWS_2003; // also includes XP 64
729 } else if (os_version.dwMajorVersion >= 6) {
730 windows_version = WINDOWS_VISTA_AND_LATER;
733 if (windows_version == WINDOWS_UNSUPPORTED) {
734 usbi_err(ctx, "This version of Windows is NOT supported");
735 r = LIBUSB_ERROR_NOT_SUPPORTED;
739 // We need a lock for proper auto-release
740 usbi_mutex_init(&autoclaim_lock, NULL);
742 // Initialize pollable file descriptors
746 if (init_dlls() != LIBUSB_SUCCESS) {
747 usbi_err(ctx, "could not resolve DLL functions");
748 return LIBUSB_ERROR_NOT_FOUND;
751 // Initialize the low level APIs (we don't care about errors at this stage)
752 for (i=0; i<USB_API_MAX; i++) {
753 usb_api_backend[i].init(ctx);
756 // Because QueryPerformanceCounter might report different values when
757 // running on different cores, we create a separate thread for the timer
758 // calls, which we glue to the first core always to prevent timing discrepancies.
759 r = LIBUSB_ERROR_NO_MEM;
760 for (i = 0; i < 2; i++) {
761 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
762 if (timer_request[i] == NULL) {
763 usbi_err(ctx, "could not create timer request event %d - aborting", i);
767 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
768 if (timer_response == NULL) {
769 usbi_err(ctx, "could not create timer response semaphore - aborting");
772 timer_mutex = CreateMutex(NULL, FALSE, NULL);
773 if (timer_mutex == NULL) {
774 usbi_err(ctx, "could not create timer mutex - aborting");
777 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
778 if (timer_thread == NULL) {
779 usbi_err(ctx, "Unable to create timer thread - aborting");
782 SetThreadAffinityMask(timer_thread, 0);
784 // Create a hash table to store session ids. Second parameter is better if prime
785 htab_create(ctx, HTAB_SIZE);
787 // At this stage, either we went through full init successfully, or didn't need to
790 init_exit: // Holds semaphore here.
791 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
793 SetEvent(timer_request[1]); // actually the signal to quit the thread.
794 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
795 usbi_warn(ctx, "could not wait for timer thread to quit");
796 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
797 // all objects it might have held anyway.
799 CloseHandle(timer_thread);
802 for (i = 0; i < 2; i++) {
803 if (timer_request[i]) {
804 CloseHandle(timer_request[i]);
805 timer_request[i] = NULL;
808 if (timer_response) {
809 CloseHandle(timer_response);
810 timer_response = NULL;
813 CloseHandle(timer_mutex);
819 if (r != LIBUSB_SUCCESS)
820 --concurrent_usage; // Not expected to call libusb_exit if we failed.
822 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
823 CloseHandle(semaphore);
828 * HCD (root) hubs need to have their device descriptor manually populated
830 * Note that, like Microsoft does in the device manager, we populate the
831 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
833 static int force_hcd_device_descriptor(struct libusb_device *dev)
835 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
836 struct libusb_context *ctx = DEVICE_CTX(dev);
839 dev->num_configurations = 1;
840 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
841 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
842 priv->dev_descriptor.bNumConfigurations = 1;
843 priv->active_config = 1;
845 if (priv->parent_dev == NULL) {
846 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
847 return LIBUSB_ERROR_NO_DEVICE;
849 parent_priv = _device_priv(priv->parent_dev);
850 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
851 priv->dev_descriptor.idVendor = (uint16_t)vid;
852 priv->dev_descriptor.idProduct = (uint16_t)pid;
854 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
855 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
856 priv->dev_descriptor.idProduct = 1;
858 return LIBUSB_SUCCESS;
862 * fetch and cache all the config descriptors through I/O
864 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
866 DWORD size, ret_size;
867 struct libusb_context *ctx = DEVICE_CTX(dev);
868 struct windows_device_priv *priv = _device_priv(dev);
872 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
873 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
874 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
876 if (dev->num_configurations == 0)
877 return LIBUSB_ERROR_INVALID_PARAM;
879 priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
880 if (priv->config_descriptor == NULL)
881 return LIBUSB_ERROR_NO_MEM;
882 for (i=0; i<dev->num_configurations; i++)
883 priv->config_descriptor[i] = NULL;
885 for (i=0, r=LIBUSB_SUCCESS; ; i++)
887 // safe loop: release all dynamic resources
888 safe_free(cd_buf_actual);
890 // safe loop: end of loop condition
891 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
894 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
895 memset(&cd_buf_short, 0, size);
897 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
898 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
899 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
900 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
901 cd_buf_short.req.SetupPacket.wIndex = i;
902 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
904 // Dummy call to get the required data size
905 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
906 &cd_buf_short, size, &ret_size, NULL)) {
907 usbi_err(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
908 LOOP_BREAK(LIBUSB_ERROR_IO);
911 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
912 usbi_err(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
913 LOOP_BREAK(LIBUSB_ERROR_IO);
916 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
917 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
918 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
919 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
921 memset(cd_buf_actual, 0, size);
924 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
925 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
926 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
927 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
928 cd_buf_actual->SetupPacket.wIndex = i;
929 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
931 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
932 cd_buf_actual, size, &ret_size, NULL)) {
933 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
934 LOOP_BREAK(LIBUSB_ERROR_IO);
937 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
939 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
940 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
941 LOOP_BREAK(LIBUSB_ERROR_IO);
944 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
945 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
946 LOOP_BREAK(LIBUSB_ERROR_IO);
949 usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
950 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
952 // Cache the descriptor
953 priv->config_descriptor[i] = (unsigned char*) malloc(cd_data->wTotalLength);
954 if (priv->config_descriptor[i] == NULL)
955 return LIBUSB_ERROR_NO_MEM;
956 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
958 return LIBUSB_SUCCESS;
962 * Populate a libusbx device structure
964 static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
965 uint8_t port_number, char* device_id, DWORD devinst)
969 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
970 struct windows_device_priv *priv, *parent_priv;
971 struct libusb_context *ctx = DEVICE_CTX(dev);
972 struct libusb_device* tmp_dev;
975 if ((dev == NULL) || (parent_dev == NULL)) {
976 return LIBUSB_ERROR_NOT_FOUND;
978 priv = _device_priv(dev);
979 parent_priv = _device_priv(parent_dev);
980 if (parent_priv->apib->id != USB_API_HUB) {
981 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
982 return LIBUSB_ERROR_NOT_FOUND;
985 // It is possible for the parent hub not to have been initialized yet
986 // If that's the case, lookup the ancestors to set the bus number
987 if (parent_dev->bus_number == 0) {
989 tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
990 if (tmp_dev == NULL) break;
991 if (tmp_dev->bus_number != 0) {
992 usbi_dbg("got bus number from ancestor #%d", i);
993 parent_dev->bus_number = tmp_dev->bus_number;
998 if (parent_dev->bus_number == 0) {
999 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1000 return LIBUSB_ERROR_NOT_FOUND;
1002 dev->bus_number = parent_dev->bus_number;
1003 priv->port = port_number;
1004 priv->depth = parent_priv->depth + 1;
1005 priv->parent_dev = parent_dev;
1007 // If the device address is already set, we can stop here
1008 if (dev->device_address != 0) {
1009 return LIBUSB_SUCCESS;
1011 memset(&conn_info, 0, sizeof(conn_info));
1012 if (priv->depth != 0) { // Not a HCD hub
1013 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1014 FILE_FLAG_OVERLAPPED, NULL);
1015 if (handle == INVALID_HANDLE_VALUE) {
1016 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1017 return LIBUSB_ERROR_ACCESS;
1019 size = sizeof(conn_info);
1020 conn_info.ConnectionIndex = (ULONG)port_number;
1021 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1022 &conn_info, size, &size, NULL)) {
1023 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1024 device_id, windows_error_str(0));
1025 safe_closehandle(handle);
1026 return LIBUSB_ERROR_NO_DEVICE;
1028 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1029 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1030 safe_closehandle(handle);
1031 return LIBUSB_ERROR_NO_DEVICE;
1033 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1034 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1035 priv->active_config = conn_info.CurrentConfigurationValue;
1036 usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
1037 // If we can't read the config descriptors, just set the number of confs to zero
1038 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1039 dev->num_configurations = 0;
1040 priv->dev_descriptor.bNumConfigurations = 0;
1042 safe_closehandle(handle);
1044 if (conn_info.DeviceAddress > UINT8_MAX) {
1045 usbi_err(ctx, "program assertion failed: device address overflow");
1047 dev->device_address = (uint8_t)conn_info.DeviceAddress;
1048 switch (conn_info.Speed) {
1049 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1050 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1051 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1052 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1054 usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
1058 dev->device_address = UINT8_MAX; // Hubs from HCD have a devaddr of 255
1059 force_hcd_device_descriptor(dev);
1062 usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
1063 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1065 return LIBUSB_SUCCESS;
1068 // Returns the api type, or 0 if not found/unsupported
1069 static uint8_t get_api_type(struct libusb_context *ctx,
1070 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
1072 // Precedence for filter drivers vs driver is in the order of this array
1073 struct driver_lookup lookup[3] = {
1074 {"\0\0", SPDRP_SERVICE, "driver"},
1075 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1076 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1078 DWORD size, reg_type;
1082 // Check the service & filter names to know the API we should use
1083 for (k=0; k<3; k++) {
1084 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1085 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1086 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1087 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1088 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1089 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1091 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1092 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1093 // (currently ';'), so even if an unsuported one does, it's not an issue
1094 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1095 if (lookup[k].list[l] == 0) {
1096 lookup[k].list[l] = LIST_SEPARATOR;
1099 upperize(lookup[k].list);
1100 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1102 if (GetLastError() != ERROR_INVALID_DATA) {
1103 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1105 lookup[k].list[0] = 0;
1109 for (api=1; api<USB_API_MAX; api++) {
1110 for (k=0; k<3; k++) {
1111 if (is_api_driver(lookup[k].list, api)) {
1112 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1116 if (k >= 3) continue;
1122 static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
1123 char* dev_interface_path, char* device_id, uint8_t api)
1126 struct windows_device_priv *priv = _device_priv(dev);
1127 int interface_number;
1129 if (priv->apib->id != USB_API_COMPOSITE) {
1130 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1131 return LIBUSB_ERROR_NO_DEVICE;
1134 // Because MI_## are not necessarily in sequential order (some composite
1135 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1136 // interface number from the path's MI value
1137 interface_number = 0;
1138 for (i=0; device_id[i] != 0; ) {
1139 if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
1140 && (device_id[i++] == '_') ) {
1141 interface_number = (device_id[i++] - '0')*10;
1142 interface_number += device_id[i] - '0';
1147 if (device_id[i] == 0) {
1148 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1149 device_id, interface_number);
1152 if (priv->usb_interface[interface_number].path != NULL) {
1153 usbi_warn(ctx, "interface[%d] already set - ignoring: %s", interface_number, device_id);
1154 return LIBUSB_ERROR_ACCESS;
1157 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1158 priv->usb_interface[interface_number].path = dev_interface_path;
1159 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1160 priv->composite_api_flags |= 1<<api;
1162 return LIBUSB_SUCCESS;
1166 * get_device_list: libusbx backend device enumeration function
1168 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1170 struct discovered_devs *discdevs;
1171 HDEVINFO dev_info = { 0 };
1172 char* usb_class[2] = {"USB", "NUSB3"};
1173 SP_DEVINFO_DATA dev_info_data;
1174 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1175 #define MAX_ENUM_GUIDS 64
1176 const GUID* guid[MAX_ENUM_GUIDS];
1181 int r = LIBUSB_SUCCESS;
1182 int class_index = 0;
1183 unsigned int nb_guids, pass, i, j, ancestor;
1184 char path[MAX_PATH_LENGTH];
1185 char strbuf[MAX_PATH_LENGTH];
1186 struct libusb_device *dev, *parent_dev;
1187 struct windows_device_priv *priv, *parent_priv;
1188 char* dev_interface_path = NULL;
1189 char* dev_id_path = NULL;
1190 unsigned long session_id;
1191 DWORD size, reg_type, port_nr, install_state;
1194 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1198 // Keep a list of newly allocated devs to unref
1199 libusb_device** unref_list;
1200 unsigned int unref_size = 64;
1201 unsigned int unref_cur = 0;
1203 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1204 // PASS 2 : (re)enumerate HUBS
1205 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1206 // and list additional USB device interface GUIDs to explore
1207 // PASS 4 : (re)enumerate master USB devices that have a device interface
1208 // PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.
1210 // Init the GUID table
1211 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1212 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1213 guid[GEN_PASS] = NULL;
1214 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1215 nb_guids = DEV_PASS+1;
1217 unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
1218 if (unref_list == NULL) {
1219 return LIBUSB_ERROR_NO_MEM;
1222 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1223 //#define ENUM_DEBUG
1227 usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
1230 usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
1233 usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
1236 usbi_dbg("PROCESSING GENs");
1239 usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
1243 for (i = 0; ; i++) {
1244 // safe loop: free up any (unprotected) dynamic resource
1245 // NB: this is always executed before breaking the loop
1246 safe_free(dev_interface_details);
1247 safe_free(dev_interface_path);
1248 safe_free(dev_id_path);
1249 priv = parent_priv = NULL;
1250 dev = parent_dev = NULL;
1252 // Safe loop: end of loop conditions
1253 if (r != LIBUSB_SUCCESS) {
1256 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1257 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1260 if (pass != GEN_PASS) {
1261 // Except for GEN, all passes deal with device interfaces
1262 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1263 if (dev_interface_details == NULL) {
1266 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1267 if (dev_interface_path == NULL) {
1268 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1273 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1274 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
1275 while ( (class_index < 2) &&
1276 (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
1283 // Read the Device ID path. This is what we'll use as UID
1284 // Note that if the device is plugged in a different port or hub, the Device ID changes
1285 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1286 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1287 dev_info_data.DevInst);
1290 dev_id_path = sanitize_path(path);
1291 if (dev_id_path == NULL) {
1292 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1293 dev_info_data.DevInst);
1297 usbi_dbg("PRO: %s", dev_id_path);
1300 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1302 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1303 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1304 ®_type, (BYTE*)&port_nr, 4, &size))
1306 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1307 dev_id_path, windows_error_str(0));
1312 // Set API to use or get additional data from generic pass
1313 api = USB_API_UNSUPPORTED;
1318 // We use the GEN pass to detect driverless devices...
1319 size = sizeof(strbuf);
1320 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1321 ®_type, (BYTE*)strbuf, size, &size)) {
1322 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1323 usbi_info(ctx, "libusbx will not be able to access it.");
1325 // ...and to add the additional device interface GUIDs
1326 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1327 if (key != INVALID_HANDLE_VALUE) {
1328 size = sizeof(guid_string_w);
1329 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1330 (BYTE*)guid_string_w, &size);
1332 if (s == ERROR_SUCCESS) {
1333 if (nb_guids >= MAX_ENUM_GUIDS) {
1334 // If this assert is ever reported, grow a GUID table dynamically
1335 usbi_err(ctx, "program assertion failed: too many GUIDs");
1336 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1338 if_guid = (GUID*) calloc(1, sizeof(GUID));
1339 pCLSIDFromString(guid_string_w, if_guid);
1340 guid[nb_guids++] = if_guid;
1341 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1346 // Get the API type (after checking that the driver installation is OK)
1347 if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1348 ®_type, (BYTE*)&install_state, 4, &size))
1350 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1351 dev_id_path, windows_error_str(0));
1352 } else if (install_state != 0) {
1353 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
1354 dev_id_path, install_state);
1357 api = get_api_type(ctx, &dev_info, &dev_info_data);
1361 // Find parent device (for the passes that need it)
1368 // Go through the ancestors until we see a face we recognize
1370 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1371 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1372 if (session_id == 0) {
1375 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1377 if (parent_dev == NULL) {
1378 usbi_dbg("unlisted ancestor for '%s' (newly connected, etc.) - ignoring", dev_id_path);
1381 parent_priv = _device_priv(parent_dev);
1382 // virtual USB devices are also listed during GEN - don't process these yet
1383 if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
1389 // Create new or match existing device, using the (hashed) device_id as session id
1390 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1391 // These are the passes that create "new" devices
1392 session_id = htab_hash(dev_id_path);
1393 dev = usbi_get_device_by_session_id(ctx, session_id);
1395 if (pass == DEV_PASS) {
1396 // This can occur if the OS only reports a newly plugged device after we started enum
1397 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1398 " - ignoring", dev_id_path);
1401 usbi_dbg("allocating new device for session [%X]", session_id);
1402 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1403 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1405 windows_device_priv_init(dev);
1406 // Keep track of devices that need unref
1407 unref_list[unref_cur++] = dev;
1408 if (unref_cur >= unref_size) {
1410 unref_list = realloc(unref_list, unref_size*sizeof(libusb_device*));
1411 if (unref_list == NULL) {
1412 usbi_err(ctx, "could not realloc list for unref - aborting.");
1413 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1417 usbi_dbg("found existing device for session [%X] (%d.%d)",
1418 session_id, dev->bus_number, dev->device_address);
1420 priv = _device_priv(dev);
1426 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1427 dev->device_address = 0;
1428 dev->num_configurations = 0;
1429 priv->apib = &usb_api_backend[USB_API_HUB];
1430 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1431 priv->path = dev_interface_path; dev_interface_path = NULL;
1435 // If the device has already been setup, don't do it again
1436 if (priv->path != NULL)
1438 // Take care of API initialization
1439 priv->path = dev_interface_path; dev_interface_path = NULL;
1440 priv->apib = &usb_api_backend[api];
1442 case USB_API_COMPOSITE:
1446 // For other devices, the first interface is the same as the device
1447 priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
1448 if (priv->usb_interface[0].path != NULL) {
1449 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1451 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1453 // The following is needed if we want API calls to work for both simple
1454 // and composite devices.
1455 for(j=0; j<USB_MAXINTERFACES; j++) {
1456 priv->usb_interface[j].apib = &usb_api_backend[api];
1462 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1463 if (r == LIBUSB_SUCCESS) {
1464 // Append device to the list of discovered devices
1465 discdevs = discovered_devs_append(*_discdevs, dev);
1467 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1469 *_discdevs = discdevs;
1470 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1471 // This can occur if the device was disconnected but Windows hasn't
1472 // refreshed its enumeration yet - in that case, we ignore the device
1476 default: // later passes
1477 if (parent_priv->apib->id == USB_API_COMPOSITE) {
1478 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1479 switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
1480 case LIBUSB_SUCCESS:
1481 dev_interface_path = NULL;
1483 case LIBUSB_ERROR_ACCESS:
1484 // interface has already been set => make sure dev_interface_path is freed then
1496 // Free any additional GUIDs
1497 for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
1498 safe_free(guid[pass]);
1501 // Unref newly allocated devs
1502 for (i=0; i<unref_cur; i++) {
1503 safe_unref_device(unref_list[i]);
1505 safe_free(unref_list);
1511 * exit: libusbx backend deinitialization function
1513 static void windows_exit(void)
1517 char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1519 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1520 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1521 if (semaphore == NULL) {
1525 // A successful wait brings our semaphore count to 0 (unsignaled)
1526 // => any concurent wait stalls until the semaphore release
1527 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1528 CloseHandle(semaphore);
1532 // Only works if exits and inits are balanced exactly
1533 if (--concurrent_usage < 0) { // Last exit
1534 for (i=0; i<USB_API_MAX; i++) {
1535 usb_api_backend[i].exit();
1540 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1541 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1542 usbi_dbg("could not wait for timer thread to quit");
1543 TerminateThread(timer_thread, 1);
1545 CloseHandle(timer_thread);
1546 timer_thread = NULL;
1548 for (i = 0; i < 2; i++) {
1549 if (timer_request[i]) {
1550 CloseHandle(timer_request[i]);
1551 timer_request[i] = NULL;
1554 if (timer_response) {
1555 CloseHandle(timer_response);
1556 timer_response = NULL;
1559 CloseHandle(timer_mutex);
1565 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1566 CloseHandle(semaphore);
1569 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1571 struct windows_device_priv *priv = _device_priv(dev);
1573 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1576 return LIBUSB_SUCCESS;
1579 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1581 struct windows_device_priv *priv = _device_priv(dev);
1582 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1585 // config index is zero based
1586 if (config_index >= dev->num_configurations)
1587 return LIBUSB_ERROR_INVALID_PARAM;
1589 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1590 return LIBUSB_ERROR_NOT_FOUND;
1592 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1594 size = min(config_header->wTotalLength, len);
1595 memcpy(buffer, priv->config_descriptor[config_index], size);
1597 return LIBUSB_SUCCESS;
1601 * return the cached copy of the active config descriptor
1603 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1605 struct windows_device_priv *priv = _device_priv(dev);
1607 if (priv->active_config == 0)
1608 return LIBUSB_ERROR_NOT_FOUND;
1610 // config index is zero based
1611 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1614 static int windows_open(struct libusb_device_handle *dev_handle)
1616 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1617 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1619 if (priv->apib == NULL) {
1620 usbi_err(ctx, "program assertion failed - device is not initialized");
1621 return LIBUSB_ERROR_NO_DEVICE;
1624 return priv->apib->open(dev_handle);
1627 static void windows_close(struct libusb_device_handle *dev_handle)
1629 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1631 priv->apib->close(dev_handle);
1634 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1636 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1638 if (priv->active_config == 0) {
1640 return LIBUSB_ERROR_NOT_FOUND;
1643 *config = priv->active_config;
1644 return LIBUSB_SUCCESS;
1648 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1649 * does not currently expose a service that allows higher-level drivers to set
1650 * the configuration."
1652 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1654 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1655 int r = LIBUSB_SUCCESS;
1657 if (config >= USB_MAXCONFIG)
1658 return LIBUSB_ERROR_INVALID_PARAM;
1660 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1661 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1662 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1665 if (r == LIBUSB_SUCCESS) {
1666 priv->active_config = (uint8_t)config;
1671 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1673 int r = LIBUSB_SUCCESS;
1674 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1676 if (iface >= USB_MAXINTERFACES)
1677 return LIBUSB_ERROR_INVALID_PARAM;
1679 safe_free(priv->usb_interface[iface].endpoint);
1680 priv->usb_interface[iface].nb_endpoints= 0;
1682 r = priv->apib->claim_interface(dev_handle, iface);
1684 if (r == LIBUSB_SUCCESS) {
1685 r = windows_assign_endpoints(dev_handle, iface, 0);
1691 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1693 int r = LIBUSB_SUCCESS;
1694 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1696 safe_free(priv->usb_interface[iface].endpoint);
1697 priv->usb_interface[iface].nb_endpoints= 0;
1699 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1701 if (r == LIBUSB_SUCCESS) {
1702 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1708 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1710 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1712 return priv->apib->release_interface(dev_handle, iface);
1715 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1717 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1718 return priv->apib->clear_halt(dev_handle, endpoint);
1721 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1723 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1724 return priv->apib->reset_device(dev_handle);
1727 // The 3 functions below are unlikely to ever get supported on Windows
1728 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1730 return LIBUSB_ERROR_NOT_SUPPORTED;
1733 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1735 return LIBUSB_ERROR_NOT_SUPPORTED;
1738 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1740 return LIBUSB_ERROR_NOT_SUPPORTED;
1743 static void windows_destroy_device(struct libusb_device *dev)
1745 windows_device_priv_release(dev);
1748 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1750 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1752 usbi_free_fd(transfer_priv->pollable_fd.fd);
1753 // When auto claim is in use, attempt to release the auto-claimed interface
1754 auto_release(itransfer);
1757 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1759 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1760 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1761 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1762 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1765 r = priv->apib->submit_bulk_transfer(itransfer);
1766 if (r != LIBUSB_SUCCESS) {
1770 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1771 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1773 usbi_fd_notification(ctx);
1774 return LIBUSB_SUCCESS;
1777 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1779 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1780 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1781 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1782 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1785 r = priv->apib->submit_iso_transfer(itransfer);
1786 if (r != LIBUSB_SUCCESS) {
1790 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1791 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1793 usbi_fd_notification(ctx);
1794 return LIBUSB_SUCCESS;
1797 static int submit_control_transfer(struct usbi_transfer *itransfer)
1799 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1800 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1801 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
1802 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1805 r = priv->apib->submit_control_transfer(itransfer);
1806 if (r != LIBUSB_SUCCESS) {
1810 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1812 usbi_fd_notification(ctx);
1813 return LIBUSB_SUCCESS;
1817 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1819 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1821 switch (transfer->type) {
1822 case LIBUSB_TRANSFER_TYPE_CONTROL:
1823 return submit_control_transfer(itransfer);
1824 case LIBUSB_TRANSFER_TYPE_BULK:
1825 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1826 if (IS_XFEROUT(transfer) &&
1827 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1828 return LIBUSB_ERROR_NOT_SUPPORTED;
1829 return submit_bulk_transfer(itransfer);
1830 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1831 return submit_iso_transfer(itransfer);
1833 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1834 return LIBUSB_ERROR_INVALID_PARAM;
1838 static int windows_abort_control(struct usbi_transfer *itransfer)
1840 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1841 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1843 return priv->apib->abort_control(itransfer);
1846 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1848 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1849 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1851 return priv->apib->abort_transfers(itransfer);
1854 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1856 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1858 switch (transfer->type) {
1859 case LIBUSB_TRANSFER_TYPE_CONTROL:
1860 return windows_abort_control(itransfer);
1861 case LIBUSB_TRANSFER_TYPE_BULK:
1862 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1863 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1864 return windows_abort_transfers(itransfer);
1866 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1867 return LIBUSB_ERROR_INVALID_PARAM;
1871 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1873 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1874 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1877 usbi_dbg("handling I/O completion with errcode %d", io_result);
1881 status = priv->apib->copy_transfer_data(itransfer, io_size);
1883 case ERROR_GEN_FAILURE:
1884 usbi_dbg("detected endpoint stall");
1885 status = LIBUSB_TRANSFER_STALL;
1887 case ERROR_SEM_TIMEOUT:
1888 usbi_dbg("detected semaphore timeout");
1889 status = LIBUSB_TRANSFER_TIMED_OUT;
1891 case ERROR_OPERATION_ABORTED:
1892 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1893 usbi_dbg("detected timeout");
1894 status = LIBUSB_TRANSFER_TIMED_OUT;
1896 usbi_dbg("detected operation aborted");
1897 status = LIBUSB_TRANSFER_CANCELLED;
1901 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
1902 status = LIBUSB_TRANSFER_ERROR;
1905 windows_clear_transfer_priv(itransfer); // Cancel polling
1906 usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
1909 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1911 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1913 switch (transfer->type) {
1914 case LIBUSB_TRANSFER_TYPE_CONTROL:
1915 case LIBUSB_TRANSFER_TYPE_BULK:
1916 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1917 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1918 windows_transfer_callback (itransfer, io_result, io_size);
1921 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1925 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
1927 struct windows_transfer_priv* transfer_priv = NULL;
1928 POLL_NFDS_TYPE i = 0;
1930 struct usbi_transfer *transfer;
1931 DWORD io_size, io_result;
1933 usbi_mutex_lock(&ctx->open_devs_lock);
1934 for (i = 0; i < nfds && num_ready > 0; i++) {
1936 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
1938 if (!fds[i].revents) {
1944 // Because a Windows OVERLAPPED is used for poll emulation,
1945 // a pollable fd is created and stored with each transfer
1946 usbi_mutex_lock(&ctx->flying_transfers_lock);
1947 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
1948 transfer_priv = usbi_transfer_get_os_priv(transfer);
1949 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
1954 usbi_mutex_unlock(&ctx->flying_transfers_lock);
1957 // Handle async requests that completed synchronously first
1958 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
1959 io_result = NO_ERROR;
1960 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
1961 // Regular async overlapped
1962 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
1963 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
1964 io_result = NO_ERROR;
1966 io_result = GetLastError();
1968 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
1969 // let handle_callback free the event using the transfer wfd
1970 // If you don't use the transfer wfd, you run a risk of trying to free a
1971 // newly allocated wfd that took the place of the one from the transfer.
1972 windows_handle_callback(transfer, io_result, io_size);
1974 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
1975 return LIBUSB_ERROR_NOT_FOUND;
1979 usbi_mutex_unlock(&ctx->open_devs_lock);
1980 return LIBUSB_SUCCESS;
1984 * Monotonic and real time functions
1986 unsigned __stdcall windows_clock_gettime_threaded(void* param)
1988 LARGE_INTEGER hires_counter, li_frequency;
1992 // Init - find out if we have access to a monotonic (hires) timer
1993 if (!QueryPerformanceFrequency(&li_frequency)) {
1994 usbi_dbg("no hires timer available on this platform");
1995 hires_frequency = 0;
1996 hires_ticks_to_ps = UINT64_C(0);
1998 hires_frequency = li_frequency.QuadPart;
1999 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2000 // to picoseconds to compute the tv_nsecs part in clock_gettime
2001 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2002 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2005 // Main loop - wait for requests
2007 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2008 if ( (timer_index != 0) && (timer_index != 1) ) {
2009 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2012 if (request_count[timer_index] == 0) {
2013 // Request already handled
2014 ResetEvent(timer_request[timer_index]);
2015 // There's still a possiblity that a thread sends a request between the
2016 // time we test request_count[] == 0 and we reset the event, in which case
2017 // the request would be ignored. The simple solution to that is to test
2018 // request_count again and process requests if non zero.
2019 if (request_count[timer_index] == 0)
2022 switch (timer_index) {
2024 WaitForSingleObject(timer_mutex, INFINITE);
2025 // Requests to this thread are for hires always
2026 if (QueryPerformanceCounter(&hires_counter) != 0) {
2027 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2028 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2030 // Fallback to real-time if we can't get monotonic value
2031 // Note that real-time clock does not wait on the mutex or this thread.
2032 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2034 ReleaseMutex(timer_mutex);
2036 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2038 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2039 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2042 case 1: // time to quit
2043 usbi_dbg("timer thread quitting");
2047 usbi_dbg("ERROR: broken timer thread");
2051 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2054 ULARGE_INTEGER rtime;
2057 case USBI_CLOCK_MONOTONIC:
2058 if (hires_frequency != 0) {
2060 InterlockedIncrement((LONG*)&request_count[0]);
2061 SetEvent(timer_request[0]);
2062 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2065 WaitForSingleObject(timer_mutex, INFINITE);
2067 ReleaseMutex(timer_mutex);
2068 return LIBUSB_SUCCESS;
2070 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2071 break; // Retry until successful
2073 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2074 return LIBUSB_ERROR_OTHER;
2078 // Fall through and return real-time if monotonic was not detected @ timer init
2079 case USBI_CLOCK_REALTIME:
2080 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2081 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2082 // Note however that our resolution is bounded by the Windows system time
2083 // functions and is at best of the order of 1 ms (or, usually, worse)
2084 GetSystemTimeAsFileTime(&filetime);
2085 rtime.LowPart = filetime.dwLowDateTime;
2086 rtime.HighPart = filetime.dwHighDateTime;
2087 rtime.QuadPart -= epoch_time;
2088 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2089 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2090 return LIBUSB_SUCCESS;
2092 return LIBUSB_ERROR_INVALID_PARAM;
2097 // NB: MSVC6 does not support named initializers.
2098 const struct usbi_os_backend windows_backend = {
2103 windows_get_device_list,
2107 windows_get_device_descriptor,
2108 windows_get_active_config_descriptor,
2109 windows_get_config_descriptor,
2111 windows_get_configuration,
2112 windows_set_configuration,
2113 windows_claim_interface,
2114 windows_release_interface,
2116 windows_set_interface_altsetting,
2118 windows_reset_device,
2120 windows_kernel_driver_active,
2121 windows_detach_kernel_driver,
2122 windows_attach_kernel_driver,
2124 windows_destroy_device,
2126 windows_submit_transfer,
2127 windows_cancel_transfer,
2128 windows_clear_transfer_priv,
2130 windows_handle_events,
2132 windows_clock_gettime,
2133 #if defined(USBI_TIMERFD_AVAILABLE)
2136 sizeof(struct windows_device_priv),
2137 sizeof(struct windows_device_handle_priv),
2138 sizeof(struct windows_transfer_priv),
2146 static int unsupported_init(struct libusb_context *ctx) {
2147 return LIBUSB_SUCCESS;
2149 static int unsupported_exit(void) {
2150 return LIBUSB_SUCCESS;
2152 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2153 PRINT_UNSUPPORTED_API(open);
2155 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2156 usbi_dbg("unsupported API call for 'close'");
2158 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2159 PRINT_UNSUPPORTED_API(claim_interface);
2161 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2162 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2164 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2165 PRINT_UNSUPPORTED_API(release_interface);
2167 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2168 PRINT_UNSUPPORTED_API(clear_halt);
2170 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2171 PRINT_UNSUPPORTED_API(reset_device);
2173 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2174 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2176 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2177 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2179 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2180 PRINT_UNSUPPORTED_API(submit_control_transfer);
2182 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2183 PRINT_UNSUPPORTED_API(abort_control);
2185 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2186 PRINT_UNSUPPORTED_API(abort_transfers);
2188 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2189 PRINT_UNSUPPORTED_API(copy_transfer_data);
2192 // These names must be uppercase
2193 const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "NUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3"};
2194 const char* composite_driver_names[] = {"USBCCGP"};
2195 const char* winusb_driver_names[] = {"WINUSB"};
2196 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2198 USB_API_UNSUPPORTED,
2200 &CLASS_GUID_UNSUPPORTED,
2207 unsupported_claim_interface,
2208 unsupported_set_interface_altsetting,
2209 unsupported_release_interface,
2210 unsupported_clear_halt,
2211 unsupported_reset_device,
2212 unsupported_submit_bulk_transfer,
2213 unsupported_submit_iso_transfer,
2214 unsupported_submit_control_transfer,
2215 unsupported_abort_control,
2216 unsupported_abort_transfers,
2217 unsupported_copy_transfer_data,
2221 &CLASS_GUID_UNSUPPORTED,
2223 sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
2228 unsupported_claim_interface,
2229 unsupported_set_interface_altsetting,
2230 unsupported_release_interface,
2231 unsupported_clear_halt,
2232 unsupported_reset_device,
2233 unsupported_submit_bulk_transfer,
2234 unsupported_submit_iso_transfer,
2235 unsupported_submit_control_transfer,
2236 unsupported_abort_control,
2237 unsupported_abort_transfers,
2238 unsupported_copy_transfer_data,
2242 &CLASS_GUID_COMPOSITE,
2243 composite_driver_names,
2244 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2249 composite_claim_interface,
2250 composite_set_interface_altsetting,
2251 composite_release_interface,
2252 composite_clear_halt,
2253 composite_reset_device,
2254 composite_submit_bulk_transfer,
2255 composite_submit_iso_transfer,
2256 composite_submit_control_transfer,
2257 composite_abort_control,
2258 composite_abort_transfers,
2259 composite_copy_transfer_data,
2263 &CLASS_GUID_LIBUSB_WINUSB,
2264 winusb_driver_names,
2265 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2270 winusb_claim_interface,
2271 winusb_set_interface_altsetting,
2272 winusb_release_interface,
2274 winusb_reset_device,
2275 winusb_submit_bulk_transfer,
2276 unsupported_submit_iso_transfer,
2277 winusb_submit_control_transfer,
2278 winusb_abort_control,
2279 winusb_abort_transfers,
2280 winusb_copy_transfer_data,
2286 * WinUSB API functions
2288 static int winusb_init(struct libusb_context *ctx)
2290 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2291 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2292 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2293 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2294 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2295 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2296 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2297 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2298 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2299 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2300 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2301 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2302 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2303 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2304 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2305 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2306 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2308 api_winusb_available = true;
2309 return LIBUSB_SUCCESS;
2312 static int winusb_exit(void)
2314 return LIBUSB_SUCCESS;
2317 // NB: open and close must ensure that they only handle interface of
2318 // the right API type, as these functions can be called wholesale from
2319 // composite_open(), with interfaces belonging to different APIs
2320 static int winusb_open(struct libusb_device_handle *dev_handle)
2322 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2323 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2324 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2329 CHECK_WINUSB_AVAILABLE;
2331 // WinUSB requires a seperate handle for each interface
2332 for (i = 0; i < USB_MAXINTERFACES; i++) {
2333 if ( (priv->usb_interface[i].path != NULL)
2334 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2335 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2336 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2337 if (file_handle == INVALID_HANDLE_VALUE) {
2338 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2339 switch(GetLastError()) {
2340 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2341 return LIBUSB_ERROR_NO_DEVICE;
2342 case ERROR_ACCESS_DENIED:
2343 return LIBUSB_ERROR_ACCESS;
2345 return LIBUSB_ERROR_IO;
2348 handle_priv->interface_handle[i].dev_handle = file_handle;
2352 return LIBUSB_SUCCESS;
2355 static void winusb_close(struct libusb_device_handle *dev_handle)
2357 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2358 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2362 if (!api_winusb_available)
2365 for (i = 0; i < USB_MAXINTERFACES; i++) {
2366 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2367 file_handle = handle_priv->interface_handle[i].dev_handle;
2368 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2369 CloseHandle(file_handle);
2375 static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
2377 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2378 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2379 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2382 uint8_t endpoint_address;
2385 CHECK_WINUSB_AVAILABLE;
2387 // With handle and enpoints set (in parent), we can setup the default pipe properties
2388 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2389 for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
2390 endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
2391 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2392 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
2393 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2395 if (i == -1) continue; // Other policies don't apply to control endpoint
2397 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2398 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2399 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2401 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2402 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2403 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2405 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2406 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2407 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2410 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2411 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2412 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2416 return LIBUSB_SUCCESS;
2419 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2421 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2422 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2423 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2424 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2425 HANDLE file_handle, winusb_handle;
2427 CHECK_WINUSB_AVAILABLE;
2429 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2430 // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
2431 if ((is_using_usbccgp) || (iface == 0)) {
2432 // composite device (independent interfaces) or interface 0
2433 file_handle = handle_priv->interface_handle[iface].dev_handle;
2434 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2435 return LIBUSB_ERROR_NOT_FOUND;
2438 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2439 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2440 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2442 switch(GetLastError()) {
2443 case ERROR_BAD_COMMAND: // The device was disconnected
2444 return LIBUSB_ERROR_NO_DEVICE;
2446 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2447 return LIBUSB_ERROR_ACCESS;
2450 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2452 // For all other interfaces, use WinUsb_GetAssociatedInterface()
2453 winusb_handle = handle_priv->interface_handle[0].api_handle;
2454 // It is a requirement for multiple interface devices using WinUSB that you
2455 // must first claim the first interface before you claim any other
2456 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2457 file_handle = handle_priv->interface_handle[0].dev_handle;
2458 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2459 handle_priv->interface_handle[0].api_handle = winusb_handle;
2460 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2462 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2463 return LIBUSB_ERROR_ACCESS;
2466 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2467 &handle_priv->interface_handle[iface].api_handle)) {
2468 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2469 switch(GetLastError()) {
2470 case ERROR_NO_MORE_ITEMS: // invalid iface
2471 return LIBUSB_ERROR_NOT_FOUND;
2472 case ERROR_BAD_COMMAND: // The device was disconnected
2473 return LIBUSB_ERROR_NO_DEVICE;
2474 case ERROR_ALREADY_EXISTS: // already claimed
2475 return LIBUSB_ERROR_BUSY;
2477 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2478 return LIBUSB_ERROR_ACCESS;
2482 usbi_dbg("claimed interface %d", iface);
2483 handle_priv->active_interface = iface;
2485 return LIBUSB_SUCCESS;
2488 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2490 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2491 HANDLE winusb_handle;
2493 CHECK_WINUSB_AVAILABLE;
2495 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2496 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2497 return LIBUSB_ERROR_NOT_FOUND;
2500 WinUsb_Free(winusb_handle);
2501 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2503 return LIBUSB_SUCCESS;
2507 * Return the first valid interface (of the same API type), for control transfers
2509 static int winusb_get_valid_interface(struct libusb_device_handle *dev_handle)
2511 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2514 for (i=0; i<USB_MAXINTERFACES; i++) {
2515 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2516 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2517 && (handle_priv->interface_handle[i].api_handle != 0)
2518 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE) ) {
2526 * Lookup interface by endpoint address. -1 if not found
2528 static int interface_by_endpoint(struct windows_device_priv *priv,
2529 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2532 for (i=0; i<USB_MAXINTERFACES; i++) {
2533 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2535 if (handle_priv->interface_handle[i].api_handle == 0)
2537 if (priv->usb_interface[i].endpoint == NULL)
2539 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2540 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2548 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2550 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2551 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2552 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2553 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2554 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
2555 transfer->dev_handle);
2556 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2558 HANDLE winusb_handle;
2559 int current_interface;
2562 CHECK_WINUSB_AVAILABLE;
2564 transfer_priv->pollable_fd = INVALID_WINFD;
2565 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2567 if (size > MAX_CTRL_BUFFER_LENGTH)
2568 return LIBUSB_ERROR_INVALID_PARAM;
2570 current_interface = winusb_get_valid_interface(transfer->dev_handle);
2571 if (current_interface < 0) {
2572 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2573 return LIBUSB_ERROR_NOT_FOUND;
2577 usbi_dbg("will use interface %d", current_interface);
2578 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2580 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2581 // Always use the handle returned from usbi_create_fd (wfd.handle)
2583 return LIBUSB_ERROR_NO_MEM;
2586 // Sending of set configuration control requests from WinUSB creates issues
2587 if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
2588 && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
2589 if (setup->value != priv->active_config) {
2590 usbi_warn(ctx, "cannot set configuration other than the default one");
2591 usbi_free_fd(wfd.fd);
2592 return LIBUSB_ERROR_INVALID_PARAM;
2594 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2595 wfd.overlapped->InternalHigh = 0;
2597 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2598 if(GetLastError() != ERROR_IO_PENDING) {
2599 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2600 usbi_free_fd(wfd.fd);
2601 return LIBUSB_ERROR_IO;
2604 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2605 wfd.overlapped->InternalHigh = (DWORD)size;
2609 // Use priv_transfer to store data needed for async polling
2610 transfer_priv->pollable_fd = wfd;
2611 transfer_priv->interface_number = (uint8_t)current_interface;
2613 return LIBUSB_SUCCESS;
2616 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2618 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2619 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2620 HANDLE winusb_handle;
2622 CHECK_WINUSB_AVAILABLE;
2624 if (altsetting > 255) {
2625 return LIBUSB_ERROR_INVALID_PARAM;
2628 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2629 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2630 usbi_err(ctx, "interface must be claimed first");
2631 return LIBUSB_ERROR_NOT_FOUND;
2634 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2635 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2636 return LIBUSB_ERROR_IO;
2639 return LIBUSB_SUCCESS;
2642 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2644 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2645 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2646 struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
2647 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2648 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2649 HANDLE winusb_handle;
2651 int current_interface;
2654 CHECK_WINUSB_AVAILABLE;
2656 transfer_priv->pollable_fd = INVALID_WINFD;
2658 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2659 if (current_interface < 0) {
2660 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2661 return LIBUSB_ERROR_NOT_FOUND;
2664 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2666 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2668 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? _O_RDONLY : _O_WRONLY);
2669 // Always use the handle returned from usbi_create_fd (wfd.handle)
2671 return LIBUSB_ERROR_NO_MEM;
2674 if (IS_XFERIN(transfer)) {
2675 usbi_dbg("reading %d bytes", transfer->length);
2676 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2678 usbi_dbg("writing %d bytes", transfer->length);
2679 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2682 if(GetLastError() != ERROR_IO_PENDING) {
2683 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2684 usbi_free_fd(wfd.fd);
2685 return LIBUSB_ERROR_IO;
2688 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2689 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2692 transfer_priv->pollable_fd = wfd;
2693 transfer_priv->interface_number = (uint8_t)current_interface;
2695 return LIBUSB_SUCCESS;
2698 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2700 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2701 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2702 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2703 HANDLE winusb_handle;
2704 int current_interface;
2706 CHECK_WINUSB_AVAILABLE;
2708 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2709 if (current_interface < 0) {
2710 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2711 return LIBUSB_ERROR_NOT_FOUND;
2714 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2715 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2717 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2718 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2719 return LIBUSB_ERROR_NO_DEVICE;
2722 return LIBUSB_SUCCESS;
2726 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2727 * through testing as well):
2728 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2729 * the control transfer using CancelIo"
2731 static int winusb_abort_control(struct usbi_transfer *itransfer)
2733 // Cancelling of the I/O is done in the parent
2734 return LIBUSB_SUCCESS;
2737 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2739 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2740 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2741 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2742 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2743 HANDLE winusb_handle;
2744 int current_interface;
2746 CHECK_WINUSB_AVAILABLE;
2748 current_interface = transfer_priv->interface_number;
2749 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2750 usbi_err(ctx, "program assertion failed: invalid interface_number");
2751 return LIBUSB_ERROR_NOT_FOUND;
2753 usbi_dbg("will use interface %d", current_interface);
2755 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2757 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2758 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2759 return LIBUSB_ERROR_NO_DEVICE;
2762 return LIBUSB_SUCCESS;
2766 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2767 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2768 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2769 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2770 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2771 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2773 // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2774 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2776 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2777 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2778 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2780 HANDLE winusb_handle;
2783 CHECK_WINUSB_AVAILABLE;
2785 // Reset any available pipe (except control)
2786 for (i=0; i<USB_MAXINTERFACES; i++) {
2787 winusb_handle = handle_priv->interface_handle[i].api_handle;
2788 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2790 // Cancel any pollable I/O
2791 usbi_remove_pollfd(ctx, wfd.fd);
2792 usbi_free_fd(wfd.fd);
2793 wfd = handle_to_winfd(winusb_handle);
2796 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2797 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2798 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2799 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2800 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2801 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2803 // FlushPipe seems to fail on OUT pipes
2804 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2805 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2806 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2807 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2809 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2810 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2811 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2817 return LIBUSB_SUCCESS;
2820 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2822 itransfer->transferred += io_size;
2823 return LIBUSB_TRANSFER_COMPLETED;
2828 * Composite API functions
2830 static int composite_init(struct libusb_context *ctx)
2832 return LIBUSB_SUCCESS;
2835 static int composite_exit(void)
2837 return LIBUSB_SUCCESS;
2840 static int composite_open(struct libusb_device_handle *dev_handle)
2842 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2845 uint8_t flag = 1<<USB_API_WINUSB;
2847 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2848 if (priv->composite_api_flags & flag) {
2849 r = usb_api_backend[api].open(dev_handle);
2850 if (r != LIBUSB_SUCCESS) {
2856 return LIBUSB_SUCCESS;
2859 static void composite_close(struct libusb_device_handle *dev_handle)
2861 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2863 uint8_t flag = 1<<USB_API_WINUSB;
2865 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2866 if (priv->composite_api_flags & flag) {
2867 usb_api_backend[api].close(dev_handle);
2873 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2875 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2876 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
2879 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2881 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2882 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
2885 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
2887 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2888 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
2891 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
2893 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2894 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2895 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2898 for (i=0; i<USB_MAXINTERFACES; i++) {
2899 if (priv->usb_interface[i].path != NULL) {
2900 usbi_dbg("using interface %d", i);
2901 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
2905 usbi_err(ctx, "no libusbx supported interfaces to complete request");
2906 return LIBUSB_ERROR_NOT_FOUND;
2909 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2910 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2911 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2912 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2913 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2914 int current_interface;
2916 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2917 if (current_interface < 0) {
2918 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2919 return LIBUSB_ERROR_NOT_FOUND;
2922 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
2925 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
2926 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2927 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2928 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2929 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2930 int current_interface;
2932 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2933 if (current_interface < 0) {
2934 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2935 return LIBUSB_ERROR_NOT_FOUND;
2938 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
2941 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2943 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2944 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2945 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2946 int current_interface;
2948 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2949 if (current_interface < 0) {
2950 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2951 return LIBUSB_ERROR_NOT_FOUND;
2954 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
2957 static int composite_abort_control(struct usbi_transfer *itransfer)
2959 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2960 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2961 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2963 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
2966 static int composite_abort_transfers(struct usbi_transfer *itransfer)
2968 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2969 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2970 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2972 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
2975 static int composite_reset_device(struct libusb_device_handle *dev_handle)
2977 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2980 uint8_t flag = 1<<USB_API_WINUSB;
2982 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
2983 if (priv->composite_api_flags & flag) {
2984 r = usb_api_backend[api].reset_device(dev_handle);
2985 if (r != LIBUSB_SUCCESS) {
2991 return LIBUSB_SUCCESS;
2994 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
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->copy_transfer_data(itransfer, io_size);