2 * windows backend for libusb 1.0
3 * Copyright (c) 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7 * Major code testing contribution by Xiaofan Chen
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 // COMPILATION OPTIONS:
25 // - Should libusb automatically claim (and release) the interfaces it requires?
27 // - Forces instant overlapped completion on timeouts: can prevents extensive
28 // wait in poll, after a timeout, but might affect subsequent API calls.
29 // ***USE AT YOUR OWN RISKS***
30 //#define FORCE_INSTANT_TIMEOUTS
41 #include <objbase.h> // for string to GUID conv. requires libole32.a
45 #include "poll_windows.h"
46 #include "windows_usb.h"
48 // The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
49 #if defined(_PREFAST_)
50 #pragma warning(disable:28719)
53 // The 2 macros below are used in conjunction with safe loops.
54 #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
55 #define LOOP_BREAK(err) { r=err; continue; }
57 extern void usbi_fd_notification(struct libusb_context *ctx);
60 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
61 static int windows_clock_gettime(int clk_id, struct timespec *tp);
62 unsigned __stdcall windows_clock_gettime_threaded(void* param);
63 // WinUSB API prototypes
64 static int winusb_init(struct libusb_context *ctx);
65 static int winusb_exit(void);
66 static int winusb_open(struct libusb_device_handle *dev_handle);
67 static void winusb_close(struct libusb_device_handle *dev_handle);
68 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
69 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
70 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
71 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
72 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
73 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
74 static int winusb_abort_transfers(struct usbi_transfer *itransfer);
75 static int winusb_abort_control(struct usbi_transfer *itransfer);
76 static int winusb_reset_device(struct libusb_device_handle *dev_handle);
77 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
79 static int hid_init(struct libusb_context *ctx);
80 static int hid_exit(void);
81 static int hid_open(struct libusb_device_handle *dev_handle);
82 static void hid_close(struct libusb_device_handle *dev_handle);
83 static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface);
84 static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface);
85 static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
86 static int hid_submit_control_transfer(struct usbi_transfer *itransfer);
87 static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer);
88 static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
89 static int hid_abort_transfers(struct usbi_transfer *itransfer);
90 static int hid_reset_device(struct libusb_device_handle *dev_handle);
91 static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
92 // Composite API prototypes
93 static int composite_init(struct libusb_context *ctx);
94 static int composite_exit(void);
95 static int composite_open(struct libusb_device_handle *dev_handle);
96 static void composite_close(struct libusb_device_handle *dev_handle);
97 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
98 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
99 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
100 static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
101 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
102 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
103 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
104 static int composite_abort_transfers(struct usbi_transfer *itransfer);
105 static int composite_abort_control(struct usbi_transfer *itransfer);
106 static int composite_reset_device(struct libusb_device_handle *dev_handle);
107 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
111 struct windows_hcd_priv* hcd_root = NULL;
112 uint64_t hires_frequency, hires_ticks_to_ps;
113 const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
114 enum windows_version windows_version = WINDOWS_UNSUPPORTED;
116 static int concurrent_usage = -1;
117 #if defined(AUTO_CLAIM)
118 usbi_mutex_t autoclaim_lock;
121 // NB: index 0 is for monotonic and 1 is for the thread exit event
122 HANDLE timer_thread = NULL;
123 HANDLE timer_mutex = NULL;
124 struct timespec timer_tp;
125 volatile LONG request_count[2] = {0, 1}; // last one must be > 0
126 HANDLE timer_request[2] = { NULL, NULL };
127 HANDLE timer_response = NULL;
129 bool api_winusb_available = false;
130 #define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
131 bool api_hid_available = false;
132 #define CHECK_HID_AVAILABLE do { if (!api_hid_available) return LIBUSB_ERROR_ACCESS; } while (0)
136 * Converts a WCHAR string to UTF8 (allocate returned string)
137 * Returns NULL on error
139 static char* wchar_to_utf8(LPCWSTR wstr)
144 // Find out the size we need to allocate for our converted string
145 size = wchar_to_utf8_ms(wstr, NULL, 0);
146 if (size <= 1) // An empty string would be size 1
149 if ((str = malloc(size)) == NULL)
152 if (wchar_to_utf8_ms(wstr, str, size) != size) {
160 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
161 if ((guid1 != NULL) && (guid2 != NULL)) {
162 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
168 static char* guid_to_string(const GUID guid)
170 static char guid_string[MAX_GUID_STRING_LENGTH];
172 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
173 (unsigned int)guid.Data1, guid.Data2, guid.Data3,
174 guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
175 guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
181 * Converts a windows error to human readable string
182 * uses retval as errorcode, or, if 0, use GetLastError()
184 static char *windows_error_str(uint32_t retval)
186 static char err_string[ERR_BUFFER_SIZE];
190 uint32_t error_code, format_error;
192 error_code = retval?retval:GetLastError();
194 safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%d] ", error_code);
196 size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
197 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &err_string[safe_strlen(err_string)],
198 ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
200 format_error = GetLastError();
202 safe_sprintf(err_string, ERR_BUFFER_SIZE,
203 "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
205 safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
207 // Remove CR/LF terminators
208 for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
216 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
217 * Return an allocated sanitized string or NULL on error.
219 static char* sanitize_path(const char* path)
221 const char root_prefix[] = "\\\\.\\";
222 size_t j, size, root_size;
223 char* ret_path = NULL;
229 size = safe_strlen(path)+1;
230 root_size = sizeof(root_prefix)-1;
232 // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
233 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
234 ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
235 add_root = root_size;
239 if ((ret_path = (char*)calloc(size, 1)) == NULL)
242 safe_strcpy(&ret_path[add_root], size-add_root, path);
244 // Ensure consistancy with root prefix
245 for (j=0; j<root_size; j++)
246 ret_path[j] = root_prefix[j];
248 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
249 for(j=root_size; j<size; j++) {
250 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
251 if (ret_path[j] == '\\')
259 * Cfgmgr32 API functions
261 static int Cfgmgr32_init(void)
263 DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
264 DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
265 DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
266 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
267 DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDW, TRUE);
269 return LIBUSB_SUCCESS;
273 * enumerate interfaces for a specific GUID
276 * dev_info: a pointer to a dev_info list
277 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
278 * guid: the GUID for which to retrieve interface details
279 * index: zero based index of the interface in the device info list
281 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
282 * structure returned and call this function repeatedly using the same guid (with an
283 * incremented index starting at zero) until all interfaces have been returned.
285 SP_DEVICE_INTERFACE_DETAIL_DATA *get_interface_details(struct libusb_context *ctx,
286 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, GUID guid, unsigned index)
288 SP_DEVICE_INTERFACE_DATA dev_interface_data;
289 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
293 *dev_info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
295 if (*dev_info == INVALID_HANDLE_VALUE) {
299 if (dev_info_data != NULL) {
300 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
301 if (!SetupDiEnumDeviceInfo(*dev_info, index, dev_info_data)) {
302 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
303 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
304 index, windows_error_str(0));
306 SetupDiDestroyDeviceInfoList(*dev_info);
307 *dev_info = INVALID_HANDLE_VALUE;
312 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
313 if (!SetupDiEnumDeviceInterfaces(*dev_info, NULL, &guid, index, &dev_interface_data)) {
314 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
315 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
316 index, windows_error_str(0));
318 SetupDiDestroyDeviceInfoList(*dev_info);
319 *dev_info = INVALID_HANDLE_VALUE;
323 // Read interface data (dummy + actual) to access the device path
324 if (!SetupDiGetDeviceInterfaceDetail(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
325 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
326 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
327 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
328 index, windows_error_str(0));
333 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
337 if ((dev_interface_details = malloc(size)) == NULL) {
338 usbi_err(ctx, "could not allocate interface data for index %u.", index);
342 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
343 if (!SetupDiGetDeviceInterfaceDetail(*dev_info, &dev_interface_data,
344 dev_interface_details, size, &size, NULL)) {
345 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
346 index, windows_error_str(0));
349 return dev_interface_details;
352 SetupDiDestroyDeviceInfoList(*dev_info);
353 *dev_info = INVALID_HANDLE_VALUE;
358 * Populate the endpoints addresses of the device_priv interface helper structs
360 static int windows_assign_endpoints(struct libusb_device *dev, int iface, int altsetting)
363 struct windows_device_priv *priv = __device_priv(dev);
364 struct libusb_config_descriptor *conf_desc;
365 const struct libusb_interface_descriptor *if_desc;
367 r = libusb_get_config_descriptor(dev, 0, &conf_desc);
368 if (r != LIBUSB_SUCCESS) {
369 usbi_warn(NULL, "could not read config descriptor: error %d", r);
373 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
374 safe_free(priv->usb_interface[iface].endpoint);
376 if (if_desc->bNumEndpoints == 0) {
377 usbi_dbg("no endpoints found for interface %d", iface);
378 return LIBUSB_SUCCESS;
381 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
382 if (priv->usb_interface[iface].endpoint == NULL) {
383 return LIBUSB_ERROR_NO_MEM;
386 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
387 for (i=0; i<if_desc->bNumEndpoints; i++) {
388 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
389 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
391 libusb_free_config_descriptor(conf_desc);
393 return LIBUSB_SUCCESS;
396 // Lookup for a match in the list of API driver names
397 bool is_api_driver(char* driver, uint8_t api)
400 const char sep_str[2] = {LIST_SEPARATOR, 0};
402 size_t len = safe_strlen(driver);
404 if (len == 0) return false;
405 tmp_str = calloc(len+1, 1);
406 if (tmp_str == NULL) return false;
407 memcpy(tmp_str, driver, len+1);
408 tok = strtok(tmp_str, sep_str);
409 while (tok != NULL) {
410 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
411 if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
416 tok = strtok(NULL, sep_str);
423 * auto-claiming and auto-release helper functions
425 #if defined(AUTO_CLAIM)
426 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
428 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
429 struct windows_device_handle_priv *handle_priv = __device_handle_priv(
430 transfer->dev_handle);
431 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
432 int current_interface = *interface_number;
433 int r = LIBUSB_SUCCESS;
440 return LIBUSB_ERROR_INVALID_PARAM;
443 usbi_mutex_lock(&autoclaim_lock);
444 if (current_interface < 0) // No serviceable interface was found
446 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
447 // Must claim an interface of the same API type
448 if ( (priv->usb_interface[current_interface].apib == &usb_api_backend[api_type])
449 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
450 usbi_dbg("auto-claimed interface %d for control request", current_interface);
451 if (handle_priv->autoclaim_count[current_interface] != 0) {
452 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
454 handle_priv->autoclaim_count[current_interface]++;
458 if (current_interface == USB_MAXINTERFACES) {
459 usbi_err(ctx, "could not auto-claim any interface");
460 r = LIBUSB_ERROR_NOT_FOUND;
463 // If we have a valid interface that was autoclaimed, we must increment
464 // its autoclaim count so that we can prevent an early release.
465 if (handle_priv->autoclaim_count[current_interface] != 0) {
466 handle_priv->autoclaim_count[current_interface]++;
469 usbi_mutex_unlock(&autoclaim_lock);
471 *interface_number = current_interface;
476 static void auto_release(struct usbi_transfer *itransfer)
478 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
479 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
480 libusb_device_handle *dev_handle = transfer->dev_handle;
481 struct windows_device_handle_priv* handle_priv = __device_handle_priv(dev_handle);
484 usbi_mutex_lock(&autoclaim_lock);
485 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
486 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
487 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
488 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
489 if (r == LIBUSB_SUCCESS) {
490 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
492 usbi_dbg("failed to auto-release interface %d (%s)",
493 transfer_priv->interface_number, libusb_strerror(r));
497 usbi_mutex_unlock(&autoclaim_lock);
503 * init: libusb backend init function
505 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
506 * In our implementation, we equate Windows' "HCD" to LibUSB's "bus". Note that bus is zero indexed.
507 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
509 static int windows_init(struct libusb_context *ctx)
512 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
515 int i, r = LIBUSB_ERROR_OTHER;
516 OSVERSIONINFO os_version;
518 struct windows_hcd_priv** _hcd_cur;
519 TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
521 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
522 semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
523 if (semaphore == NULL) {
524 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
525 return LIBUSB_ERROR_NO_MEM;
528 // A successful wait brings our semaphore count to 0 (unsignaled)
529 // => any concurent wait stalls until the semaphore's release
530 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
531 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
532 CloseHandle(semaphore);
533 return LIBUSB_ERROR_NO_MEM;
536 // NB: concurrent usage supposes that init calls are equally balanced with
537 // exit calls. If init is called more than exit, we will not exit properly
538 if ( ++concurrent_usage == 0 ) { // First init?
539 _hcd_cur = &hcd_root;
542 memset(&os_version, 0, sizeof(OSVERSIONINFO));
543 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
544 windows_version = WINDOWS_UNSUPPORTED;
545 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
546 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
547 windows_version = WINDOWS_XP;
548 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
549 windows_version = WINDOWS_2003; // also includes XP 64
550 } else if (os_version.dwMajorVersion >= 6) {
551 windows_version = WINDOWS_VISTA_AND_LATER;
554 if (windows_version == WINDOWS_UNSUPPORTED) {
555 usbi_err(ctx, "This version of Windows is NOT supported");
556 r = LIBUSB_ERROR_NOT_SUPPORTED;
560 #if defined(AUTO_CLAIM)
561 // We need a lock for proper auto-release
562 usbi_mutex_init(&autoclaim_lock, NULL);
565 // Initialize pollable file descriptors
568 // Load missing CFGMGR32.DLL imports
569 if (Cfgmgr32_init() != LIBUSB_SUCCESS) {
570 usbi_err(ctx, "could not resolve Cfgmgr32.dll functions");
571 return LIBUSB_ERROR_NOT_FOUND;
574 // Initialize the low level APIs (we don't care about errors at this stage)
575 for (i=0; i<USB_API_MAX; i++) {
576 usb_api_backend[i].init(ctx);
579 // Because QueryPerformanceCounter might report different values when
580 // running on different cores, we create a separate thread for the timer
581 // calls, which we glue to the first core always to prevent timing discrepancies.
582 r = LIBUSB_ERROR_NO_MEM;
583 for (i = 0; i < 2; i++) {
584 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
585 if (timer_request[i] == NULL) {
586 usbi_err(ctx, "could not create timer request event %d - aborting", i);
590 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
591 if (timer_response == NULL) {
592 usbi_err(ctx, "could not create timer response semaphore - aborting");
595 timer_mutex = CreateMutex(NULL, FALSE, NULL);
596 if (timer_mutex == NULL) {
597 usbi_err(ctx, "could not create timer mutex - aborting");
600 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
601 if (timer_thread == NULL) {
602 usbi_err(ctx, "Unable to create timer thread - aborting");
605 SetThreadAffinityMask(timer_thread, 0);
607 guid = GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
610 for (bus = 0; ; bus++)
612 // safe loop: free up any (unprotected) dynamic resource
613 // NB: this is always executed before breaking the loop
614 safe_free(dev_interface_details);
615 safe_free(*_hcd_cur);
617 dev_interface_details = get_interface_details(ctx, &dev_info, NULL, guid, bus);
618 // safe loop: end of loop condition
619 if ((dev_interface_details == NULL) || (r != LIBUSB_SUCCESS))
622 // Will need to change storage and size of libusb_bus_t if this ever occurs
623 if (bus == LIBUSB_BUS_MAX) {
624 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", LIBUSB_BUS_MAX);
628 // Allocate and init a new priv structure to hold our data
629 if ((*_hcd_cur = malloc(sizeof(struct windows_hcd_priv))) == NULL) {
630 usbi_err(ctx, "could not allocate private structure for bus %u. aborting.", bus);
631 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
633 windows_hcd_priv_init(*_hcd_cur);
634 (*_hcd_cur)->path = sanitize_path(dev_interface_details->DevicePath);
636 _hcd_cur = &((*_hcd_cur)->next);
638 // TODO (2nd official release): thread for hotplug (see darwin source)
641 if (hcd_root == NULL)
642 r = LIBUSB_ERROR_NO_DEVICE;
646 init_exit: // Holds semaphore here.
647 if(!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
649 SetEvent(timer_request[1]); // actually the signal to quit the thread.
650 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
651 usbi_warn(ctx, "could not wait for timer thread to quit");
652 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
653 // all objects it might have held anyway.
655 CloseHandle(timer_thread);
658 for (i = 0; i < 2; i++) {
659 if (timer_request[i]) {
660 CloseHandle(timer_request[i]);
661 timer_request[i] = NULL;
664 if (timer_response) {
665 CloseHandle(timer_response);
666 timer_response = NULL;
669 CloseHandle(timer_mutex);
674 if (r != LIBUSB_SUCCESS)
675 --concurrent_usage; // Not expected to call libusb_exit if we failed.
677 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
678 CloseHandle(semaphore);
683 * Initialize device structure, including active config
685 static int initialize_device(struct libusb_device *dev, libusb_bus_t busnum,
686 libusb_devaddr_t devaddr, char *path, int connection_index, uint8_t active_config,
687 struct libusb_device *parent_dev)
689 struct windows_device_priv *priv = __device_priv(dev);
691 windows_device_priv_init(priv);
693 dev->bus_number = busnum;
694 dev->device_address = devaddr;
696 priv->connection_index = connection_index;
697 priv->parent_dev = parent_dev;
699 priv->active_config = active_config;
701 if (priv->active_config != 0) {
702 usbi_dbg("active config: %d", priv->active_config);
704 // USB devices that don't have a config value are usually missing a driver
705 // TODO (after first official release): use this for automated driver installation
706 // NB: SetupDiGetDeviceRegistryProperty w/ SPDRP_INSTALL_STATE would tell us
707 // if the driver is properly installed, but driverless devices don't seem to
708 // be enumerable by SetupDi...
709 usbi_dbg("* This device has no driver => libusb will not be able to access it *");
712 return LIBUSB_SUCCESS;
716 * HCD (root) hubs need to have their device descriptor manually populated
718 * Note that we follow the Linux convention and use the "Linux Foundation root hub"
719 * vendor ID as well as the product ID to indicate the hub speed
721 static int force_hcd_device_descriptor(struct libusb_device *dev, HANDLE handle)
724 USB_HUB_CAPABILITIES hub_caps;
725 USB_HUB_CAPABILITIES_EX hub_caps_ex;
726 struct windows_device_priv *priv = __device_priv(dev);
727 struct libusb_context *ctx = DEVICE_CTX(dev);
729 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
730 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
731 dev->num_configurations = priv->dev_descriptor.bNumConfigurations = 1;
733 // The following is used to set the VIS:PID of root HUBs similarly to what
734 // Linux does: 1d6b:0001 is for 1x root hubs, 1d6b:0002 for 2x
735 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
736 if (windows_version >= WINDOWS_VISTA_AND_LATER) {
737 size = sizeof(USB_HUB_CAPABILITIES_EX);
738 if (DeviceIoControl(handle, IOCTL_USB_GET_HUB_CAPABILITIES_EX, &hub_caps_ex,
739 size, &hub_caps_ex, size, &size, NULL)) {
740 // Sanity check. HCD hub should always be root
741 if (!hub_caps_ex.CapabilityFlags.HubIsRoot) {
742 usbi_warn(ctx, "program assertion failed - HCD hub is not reported as root hub.");
744 priv->dev_descriptor.idProduct = hub_caps_ex.CapabilityFlags.HubIsHighSpeedCapable?2:1;
747 size = sizeof(USB_HUB_CAPABILITIES);
748 if (!DeviceIoControl(handle, IOCTL_USB_GET_HUB_CAPABILITIES, &hub_caps,
749 size, &hub_caps, size, &size, NULL)) {
750 usbi_warn(ctx, "could not read hub capabilities (std) for hub %s: %s",
751 priv->path, windows_error_str(0));
752 priv->dev_descriptor.idProduct = 1; // Indicate 1x speed
754 priv->dev_descriptor.idProduct = hub_caps.HubIs2xCapable?2:1;
758 return LIBUSB_SUCCESS;
762 * fetch and cache all the config descriptors through I/O
764 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle)
766 DWORD size, ret_size;
767 struct libusb_context *ctx = DEVICE_CTX(dev);
768 struct windows_device_priv *priv = __device_priv(dev);
772 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
773 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
774 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
776 if (dev->num_configurations == 0)
777 return LIBUSB_ERROR_INVALID_PARAM;
779 priv->config_descriptor = malloc(dev->num_configurations * sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
780 if (priv->config_descriptor == NULL)
781 return LIBUSB_ERROR_NO_MEM;
782 for (i=0; i<dev->num_configurations; i++)
783 priv->config_descriptor[i] = NULL;
785 for (i=0, r=LIBUSB_SUCCESS; ; i++)
787 // safe loop: release all dynamic resources
788 safe_free(cd_buf_actual);
790 // safe loop: end of loop condition
791 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
794 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
795 memset(&cd_buf_short, 0, size);
797 cd_buf_short.req.ConnectionIndex = priv->connection_index;
798 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
799 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
800 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
801 cd_buf_short.req.SetupPacket.wIndex = i;
802 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
804 // Dummy call to get the required data size
805 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
806 &cd_buf_short, size, &ret_size, NULL)) {
807 usbi_err(ctx, "could not access configuration descriptor (dummy): %s", windows_error_str(0));
808 LOOP_BREAK(LIBUSB_ERROR_IO);
811 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
812 usbi_err(ctx, "unexpected configuration descriptor size (dummy).");
813 LOOP_BREAK(LIBUSB_ERROR_IO);
816 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
817 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST)malloc(size)) == NULL) {
818 usbi_err(ctx, "could not allocate configuration descriptor buffer. aborting.");
819 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
821 memset(cd_buf_actual, 0, size);
824 cd_buf_actual->ConnectionIndex = priv->connection_index;
825 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
826 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
827 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
828 cd_buf_actual->SetupPacket.wIndex = i;
829 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
831 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
832 cd_buf_actual, size, &ret_size, NULL)) {
833 usbi_err(ctx, "could not access configuration descriptor (actual): %s", windows_error_str(0));
834 LOOP_BREAK(LIBUSB_ERROR_IO);
837 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
839 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
840 usbi_err(ctx, "unexpected configuration descriptor size (actual).");
841 LOOP_BREAK(LIBUSB_ERROR_IO);
844 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
845 usbi_err(ctx, "not a configuration descriptor");
846 LOOP_BREAK(LIBUSB_ERROR_IO);
849 usbi_dbg("cached config descriptor #%d (%d bytes)", i+1, cd_data->wTotalLength);
851 // Sanity check. Ensures that indexes for our list of config desc is in the right order
852 if (i != (cd_data->bConfigurationValue-1)) {
853 usbi_warn(ctx, "program assertion failed - config descriptors are being read out of order");
857 // Cache the descriptor
858 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
859 if (priv->config_descriptor[i] == NULL)
860 return LIBUSB_ERROR_NO_MEM;
862 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
864 return LIBUSB_SUCCESS;
868 * Recursively enumerates and finds all hubs & devices
870 static int usb_enumerate_hub(struct libusb_context *ctx, struct discovered_devs **_discdevs,
871 HANDLE hub_handle, libusb_bus_t busnum, struct libusb_device *parent_dev, uint8_t nb_ports)
873 struct discovered_devs *discdevs = *_discdevs;
874 struct libusb_device *dev = NULL;
875 DWORD size, size_initial, size_fixed, getname_ioctl;
876 HANDLE handle = INVALID_HANDLE_VALUE;
877 USB_HUB_NAME_FIXED s_hubname;
878 USB_NODE_CONNECTION_INFORMATION conn_info;
879 USB_NODE_INFORMATION hub_node;
880 bool is_hcd, need_unref = false;
883 char *tmp_str = NULL, *path_str = NULL;
884 unsigned long session_id;
885 libusb_devaddr_t devaddr = 0;
886 struct windows_device_priv *priv, *parent_priv;
888 // obviously, root (HCD) hubs have no parent
889 is_hcd = (parent_dev == NULL);
893 usbi_warn(ctx, "program assertion failed - invalid number of ports for HCD.");
894 return LIBUSB_ERROR_INVALID_PARAM;
897 size_initial = sizeof(USB_ROOT_HUB_NAME);
898 size_fixed = sizeof(USB_ROOT_HUB_NAME_FIXED);
899 getname_ioctl = IOCTL_USB_GET_ROOT_HUB_NAME;
903 parent_priv = __device_priv(parent_dev);
904 size_initial = sizeof(USB_NODE_CONNECTION_NAME);
905 size_fixed = sizeof(USB_NODE_CONNECTION_NAME_FIXED);
906 getname_ioctl = IOCTL_USB_GET_NODE_CONNECTION_NAME;
909 // Loop through all the ports on this hub
910 for (i = 1, r = LIBUSB_SUCCESS; ; i++)
912 // safe loop: release all dynamic resources
914 safe_unref_device(dev);
919 safe_closehandle(handle);
921 // safe loop: end of loop condition
922 if ((i > nb_ports) || (r != LIBUSB_SUCCESS))
925 memset(&conn_info, 0, sizeof(conn_info));
926 // For non HCDs, check if the node on this port is a hub or a regular device
928 size = sizeof(USB_NODE_CONNECTION_INFORMATION);
929 conn_info.ConnectionIndex = i;
930 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, &conn_info, size,
931 &conn_info, size, &size, NULL)) {
932 usbi_warn(ctx, "could not get node connection information: %s", windows_error_str(0));
936 if (conn_info.ConnectionStatus == NoDeviceConnected) {
940 if (conn_info.DeviceAddress == LIBUSB_DEVADDR_MAX) {
941 usbi_warn(ctx, "program assertion failed - device address is %d "
942 "(conflicts with root hub), ignoring device", LIBUSB_DEVADDR_MAX);
946 s_hubname.u.node.ConnectionIndex = i; // Only used for non HCDs (s_hubname is an union)
950 // HCDs have only 1 node, and it's always a hub
951 conn_info.DeviceAddress = LIBUSB_DEVADDR_MAX; // using 0 can conflict with driverless devices
952 conn_info.DeviceIsHub = true;
953 conn_info.CurrentConfigurationValue = 1;
956 // If this node is a hub (HCD or not), open it
957 if (conn_info.DeviceIsHub) {
959 if (!DeviceIoControl(hub_handle, getname_ioctl, &s_hubname, size,
960 &s_hubname, size, &size, NULL)) {
961 usbi_warn(ctx, "could not get hub path (dummy): %s", windows_error_str(0));
965 size = is_hcd?s_hubname.u.root.ActualLength:s_hubname.u.node.ActualLength;
966 if (size > size_fixed) {
967 usbi_warn(ctx, "program assertion failed - hub path is too long");
972 // previous call trashes some of the data
973 s_hubname.u.node.ConnectionIndex = i;
975 if (!DeviceIoControl(hub_handle, getname_ioctl, &s_hubname, size,
976 &s_hubname, size, &size, NULL)) {
977 usbi_warn(ctx, "could not get hub path (actual): %s", windows_error_str(0));
982 wstr = is_hcd?s_hubname.u.root.RootHubName:s_hubname.u.node.NodeName;
983 tmp_str = wchar_to_utf8(wstr);
984 if (tmp_str == NULL) {
985 usbi_err(ctx, "could not convert hub path string.");
986 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
989 path_str = sanitize_path(tmp_str);
990 if (path_str == NULL) {
991 usbi_err(ctx, "could not sanitize hub path string.");
992 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
996 handle = CreateFileA(path_str, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
997 FILE_FLAG_OVERLAPPED, NULL);
998 if(handle == INVALID_HANDLE_VALUE) {
999 usbi_warn(ctx, "could not open hub %s: %s", path_str, windows_error_str(0));
1004 // Generate a session ID
1005 // Will need to change the session_id computation if this assertion fails
1006 if (conn_info.DeviceAddress > LIBUSB_DEVADDR_MAX) {
1007 usbi_warn(ctx, "program assertion failed - device address is greater than %d, ignoring device",
1008 LIBUSB_DEVADDR_MAX);
1011 devaddr = (uint8_t)conn_info.DeviceAddress;
1013 // Same trick as linux for session_id, with same caveat
1014 session_id = busnum << (sizeof(libusb_devaddr_t)*8) | devaddr;
1015 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr, session_id);
1017 // Allocate device if needed
1018 dev = usbi_get_device_by_session_id(ctx, session_id);
1020 usbi_dbg("using existing device for session %ld", session_id);
1021 priv = __device_priv(dev);
1022 // Because we are rebuilding the list, there's no guarantee
1023 // the parent device pointer is still the same.
1024 // Other device data should still be reusable
1025 priv->parent_dev = parent_dev;
1027 usbi_dbg("allocating new device for session %ld", session_id);
1028 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1029 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1033 LOOP_CHECK(initialize_device(dev, busnum, devaddr, path_str, i,
1034 conn_info.CurrentConfigurationValue, parent_dev));
1035 priv = __device_priv(dev);
1037 path_str = NULL; // protect our path from being freed
1039 // Setup the cached descriptors. Note that only non HCDs can fetch descriptors
1041 // The device descriptor has been read with conn_info
1042 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1043 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1044 // If we can't read the config descriptors, just set the number of confs to zero
1045 if (cache_config_descriptors(dev, hub_handle) != LIBUSB_SUCCESS) {
1046 dev->num_configurations = 0;
1047 priv->dev_descriptor.bNumConfigurations = 0;
1050 LOOP_CHECK(force_hcd_device_descriptor(dev, handle));
1052 LOOP_CHECK(usbi_sanitize_device(dev));
1055 discdevs = discovered_devs_append(*_discdevs, dev);
1057 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1060 *_discdevs = discdevs;
1062 // Finally, if device is a hub, recurse
1063 if (conn_info.DeviceIsHub) {
1064 // Find number of ports for this hub
1065 size = sizeof(USB_NODE_INFORMATION);
1066 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_INFORMATION, &hub_node, size,
1067 &hub_node, size, &size, NULL)) {
1068 usbi_warn(ctx, "could not retreive information for hub %s: %s",
1069 priv->path, windows_error_str(0));
1073 if (hub_node.NodeType != UsbHub) {
1074 usbi_warn(ctx, "unexpected hub type (%d) for hub %s", hub_node.NodeType, priv->path);
1078 usbi_dbg("%d ports Hub: %s", hub_node.u.HubInformation.HubDescriptor.bNumberOfPorts, priv->path);
1080 usb_enumerate_hub(ctx, _discdevs, handle, busnum, dev,
1081 hub_node.u.HubInformation.HubDescriptor.bNumberOfPorts);
1089 * Composite device interfaces are not enumerated using GUID_DEVINTERFACE_USB_DEVICE,
1090 * but instead require a different lookup mechanism
1092 static int set_composite_device(struct libusb_context *ctx, DEVINST devinst, struct windows_device_priv *priv)
1094 // indexes for additional interface GUIDs, not available from "USB"
1095 // SetupDiGetClassDevs enumeration should go here. Typically, these are
1096 // device interfaces that begin with something else than "\\?\usb\"
1097 enum libusb_hid_report_type {
1098 HID_DEVICE_INTERFACE_GUID_INDEX = 0,
1099 MAX_DEVICE_INTERFACE_GUID_INDEX = 1
1102 DEVINST child_devinst, parent_devinst;
1103 unsigned i, j, max_guids, nb_paths, interface_number;
1109 SP_DEVINFO_DATA dev_info_data;
1110 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1112 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1113 GUID guid, class_guid;
1114 GUID guid_table[MAX_USB_DEVICES];
1115 char* sanitized_path[MAX_USB_DEVICES];
1116 char* hid_path[MAX_USB_DEVICES]; // An extra path is needed for HID
1117 uint8_t api_type[MAX_USB_DEVICES];
1118 char* sanitized_short = NULL;
1119 char path[MAX_PATH_LENGTH];
1120 char driver[MAX_KEY_LENGTH];
1122 dev_info = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
1123 if (dev_info == INVALID_HANDLE_VALUE) {
1124 return LIBUSB_ERROR_NOT_FOUND;
1127 // Manually add the HID GUID as it cannot be read with DeviceInterfaceGUIDs reg key)
1128 // NB the value returned by HidD_GetHidGuid, which is for interface class is different
1129 // from GUID_HID, which is the device class GUID
1130 HidD_GetHidGuid(&guid_table[HID_DEVICE_INTERFACE_GUID_INDEX]);
1131 // NB: for other interface guids, SetupDiClassGuidsFromName can be used
1132 max_guids = MAX_DEVICE_INTERFACE_GUID_INDEX;
1134 // First, retrieve all the device interface GUIDs
1137 dev_info_data.cbSize = sizeof(dev_info_data);
1138 if (!SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data)) {
1142 key = SetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1143 if (key == INVALID_HANDLE_VALUE) {
1144 usbi_dbg("could not open registry key");
1148 size = sizeof(guid_string_w);
1149 r = RegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &type,
1150 (BYTE*)guid_string_w, &size);
1152 if (r != ERROR_SUCCESS) {
1155 CLSIDFromString(guid_string_w, &guid);
1157 // identical device interface GUIDs are not supposed to happen, but are a real possibility
1158 // => check and ignore duplicates
1160 for (j=0; j<max_guids; j++) {
1161 if (memcmp(&guid_table[j], &guid, sizeof(GUID)) == 0) {
1167 guid_table[max_guids++] = guid;
1168 if (max_guids > MAX_USB_DEVICES) {
1169 usbi_warn(ctx, "more than %d devices - ignoring the rest", MAX_USB_DEVICES);
1174 SetupDiDestroyDeviceInfoList(dev_info);
1176 // Now let's find the device interface paths for all these devices
1178 for (j=0; j<max_guids; j++)
1180 guid = guid_table[j];
1184 safe_free(dev_interface_details);
1185 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1186 if (dev_interface_details == NULL)
1189 // HID devices (and possibly other classes) have an extra indirection
1190 // for an USB path we can recognize
1191 if (j == HID_DEVICE_INTERFACE_GUID_INDEX) {
1192 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1193 usbi_warn(ctx, "could not retrieve HID parent info data for device %s, skipping: %s",
1194 dev_interface_details->DevicePath, windows_error_str(0));
1198 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1199 usbi_warn(ctx, "could not retrieve HID parent's path for device %s, skipping: %s",
1200 dev_interface_details->DevicePath, windows_error_str(0));
1205 // In case we can't read the driver string through SPDRP_SERVICE (which is
1206 // the case for HID), we need the ClassGUID for comparison.
1207 if(!SetupDiGetDeviceRegistryPropertyW(dev_info, &dev_info_data, SPDRP_CLASSGUID,
1208 NULL, (BYTE*)guid_string_w, sizeof(guid_string_w), &size)) {
1209 usbi_warn(ctx, "could not read class GUID for device %s, skipping: %s",
1210 dev_interface_details->DevicePath, windows_error_str(0));
1213 CLSIDFromString(guid_string_w, &class_guid);
1215 // Attempt to read the driver string
1216 if(!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_SERVICE,
1217 NULL, (BYTE*)driver, MAX_KEY_LENGTH, &size)) {
1221 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
1222 if ( (is_api_driver(driver, api))
1223 || (guid_eq(&class_guid, usb_api_backend[api].class_guid)) ) {
1224 api_type[nb_paths] = api;
1225 if (j == HID_DEVICE_INTERFACE_GUID_INDEX) {
1226 hid_path[nb_paths] = sanitize_path(path);
1228 hid_path[nb_paths] = NULL;
1230 sanitized_path[nb_paths++] = sanitize_path(dev_interface_details->DevicePath);
1231 if (nb_paths > MAX_USB_DEVICES) {
1232 usbi_warn(ctx, "more than %d devices - ignoring the rest", MAX_USB_DEVICES);
1240 // Finally, match the interface paths with the interfaces. We do that
1241 // by looking at the children of the composite device
1242 // NB: if the interfaces are not found in their expected position,
1243 // claim_interface will issue a warning
1245 memset(&child_devinst, 0, sizeof(DEVINST)); // prevents /W4 warning
1246 for (i = 0; i<USB_MAXINTERFACES; i++)
1249 r = CM_Get_Child(&child_devinst, devinst, 0);
1251 r = CM_Get_Sibling(&child_devinst, child_devinst, 0);
1253 if (r == CR_NO_SUCH_DEVNODE) { // end of the siblings
1255 } else if (r != CR_SUCCESS) {
1256 usbi_dbg("unable to find interface sibling #%d, error = %X", i, r);
1260 r = CM_Get_Device_ID(child_devinst, path, MAX_PATH_LENGTH, 0);
1261 if (r != CR_SUCCESS) {
1262 usbi_err(ctx, "could not retrieve simple path for interface %d: CR error %d",
1266 sanitized_short = sanitize_path(path);
1267 if (sanitized_short == NULL) {
1268 usbi_err(ctx, "could not sanitize path for interface %d", i);
1272 // Because MI_## are not necessarily in sequential order (some composite HID
1273 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1274 // interface number from the path's MI value
1275 interface_number = i;
1276 for (j=0; sanitized_short[j] != 0; ) {
1277 if ( (sanitized_short[j++] == 'M') && (sanitized_short[j++] == 'I')
1278 && (sanitized_short[j++] == '_') ) {
1279 interface_number = (sanitized_short[j++] - '0')*10;
1280 interface_number += sanitized_short[j] - '0';
1284 if (sanitized_short[j] == 0) {
1285 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1286 sanitized_short, interface_number);
1289 for (j=0; j<nb_paths; j++) {
1290 if ( (safe_strncmp(sanitized_path[j], sanitized_short, safe_strlen(sanitized_short)) == 0)
1291 || (safe_strcmp(hid_path[j], sanitized_short) == 0 ) ) {
1292 // HID devices can have multiple collections (COL##) for each MI_## interface
1293 if (priv->usb_interface[interface_number].path != NULL) {
1294 usbi_dbg("interface_path[%d] already set - ignoring HID collection: %s",
1295 interface_number, sanitized_path[j]);
1296 if (api_type[j] != USB_API_HID) {
1297 usbi_warn(ctx, "program assertion failed - not an HID collection");
1300 priv->usb_interface[interface_number].path = sanitized_path[j];
1301 priv->usb_interface[interface_number].apib = &usb_api_backend[api_type[j]];
1302 if ((api_type[j] == USB_API_HID) && (priv->hid == NULL)) {
1303 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1305 priv->composite_api_flags |= 1<<api_type[j];
1306 sanitized_path[j] = NULL;
1310 safe_free(sanitized_short);
1312 if (priv->usb_interface[interface_number].path == NULL) {
1313 usbi_warn(ctx, "interface_path[%d]: unhandled API - interface will be disabled",
1317 usbi_dbg("interface_path[%d]: %s", interface_number, priv->usb_interface[interface_number].path);
1321 for (j=0; j<nb_paths; j++) {
1322 safe_free(sanitized_path[j]);
1323 safe_free(hid_path[j]);
1327 usbi_warn(ctx, "composite device: no interfaces were found");
1328 return LIBUSB_ERROR_NOT_FOUND;
1331 return LIBUSB_SUCCESS;
1335 * Likewise, HID device interfaces's path (\\.\HID\...) are not enumerated through the
1336 * generic USB devices GUID, but are actually children of one such device
1338 static int set_hid_device(struct libusb_context *ctx, struct windows_device_priv *priv)
1340 char path[MAX_PATH_LENGTH];
1341 char *sanitized_path = NULL;
1343 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1344 SP_DEVINFO_DATA dev_info_data;
1345 DEVINST parent_devinst;
1347 int r = LIBUSB_SUCCESS;
1348 unsigned i, interface_number;
1350 interface_number = 0;
1351 HidD_GetHidGuid(&guid);
1354 // safe loop: free up any (unprotected) dynamic resource
1355 safe_free(dev_interface_details);
1356 safe_free(sanitized_path);
1358 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1359 // safe loop: end of loop condition
1360 if ( (dev_interface_details == NULL)
1361 || (r != LIBUSB_SUCCESS) )
1364 // Retrieve parent's path using PnP Configuration Manager (CM)
1365 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1366 usbi_warn(ctx, "could not retrieve parent info data for device %s, skipping: %s",
1367 dev_interface_details->DevicePath, windows_error_str(0));
1371 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1372 usbi_warn(ctx, "could not retrieve parent's path for device %s, skipping: %s",
1373 dev_interface_details->DevicePath, windows_error_str(0));
1377 // Fix parent's path inconsistencies before attempting to compare
1378 sanitized_path = sanitize_path(path);
1379 if (sanitized_path == NULL) {
1380 usbi_warn(ctx, "could not sanitize parent's path for device %s, skipping.",
1381 dev_interface_details->DevicePath);
1385 // NB: we compare strings of different lengths below => strncmp
1386 if (safe_strncmp(priv->path, sanitized_path, safe_strlen(sanitized_path)) == 0) {
1387 priv->usb_interface[interface_number].path = sanitize_path(dev_interface_details->DevicePath);
1388 priv->usb_interface[interface_number].apib = &usb_api_backend[USB_API_HID];
1389 usbi_dbg("interface_path[%d]: %s", interface_number, priv->usb_interface[interface_number].path);
1394 return LIBUSB_SUCCESS;
1398 * This function retrieves and sets the paths of all non-hub devices
1399 * NB: No I/O with device is required during this call
1401 static int set_device_paths(struct libusb_context *ctx, struct discovered_devs *discdevs)
1403 // Precedence for filter drivers vs driver is in the order of this array
1404 struct driver_lookup lookup[3] = {
1405 {"\0\0", SPDRP_SERVICE, "driver"},
1406 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1407 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1409 struct windows_device_priv *priv;
1410 struct windows_device_priv *parent_priv;
1411 char path[MAX_PATH_LENGTH];
1412 char *sanitized_path = NULL;
1414 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1415 SP_DEVINFO_DATA dev_info_data;
1416 DEVINST parent_devinst;
1418 DWORD size, reg_type, install_state, port_nr;
1419 int r = LIBUSB_SUCCESS;
1420 unsigned i, j, k, l;
1424 // TODO (after first official release): MI_## automated driver installation
1425 guid = GUID_DEVINTERFACE_USB_DEVICE;
1428 // safe loop: free up any (unprotected) dynamic resource
1429 safe_free(dev_interface_details);
1430 safe_free(sanitized_path);
1432 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1433 // safe loop: end of loop condition
1434 if ( (dev_interface_details == NULL)
1435 || (r != LIBUSB_SUCCESS) )
1438 // Check that the driver installation is OK
1439 if ( (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1440 ®_type, (BYTE*)&install_state, 4, &size))
1442 usbi_warn(ctx, "could not detect installation state of driver for %s: %s",
1443 dev_interface_details->DevicePath, windows_error_str(0));
1444 } else if (install_state != 0) {
1445 usbi_warn(ctx, "driver for device %s is reporting an issue (code: %d) - skipping",
1446 dev_interface_details->DevicePath, install_state);
1450 // The SPDRP_ADDRESS for USB devices should be the device port number on the hub
1451 if ( (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_ADDRESS,
1452 ®_type, (BYTE*)&port_nr, 4, &size))
1454 usbi_warn(ctx, "could not retrieve port number for device %s, skipping: %s",
1455 dev_interface_details->DevicePath, windows_error_str(0));
1459 // Retrieve parent's path using PnP Configuration Manager (CM)
1460 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1461 usbi_warn(ctx, "could not retrieve parent info data for device %s, skipping: %s",
1462 dev_interface_details->DevicePath, windows_error_str(0));
1466 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1467 usbi_warn(ctx, "could not retrieve parent's path for device %s, skipping: %s",
1468 dev_interface_details->DevicePath, windows_error_str(0));
1472 // Fix parent's path inconsistencies before attempting to compare
1473 sanitized_path = sanitize_path(path);
1474 if (sanitized_path == NULL) {
1475 usbi_warn(ctx, "could not sanitize parent's path for device %s, skipping.",
1476 dev_interface_details->DevicePath);
1480 // With the parent path and port number, we should be able to locate our device
1481 // by comparing these values to the ones we got when enumerating hubs
1483 for (j=0; j<discdevs->len; j++) {
1484 priv = __device_priv(discdevs->devices[j]);
1486 if (priv->parent_dev == NULL) {
1487 continue; // ignore HCDs
1490 parent_priv = __device_priv(priv->parent_dev);
1492 // NB: we compare strings of different lengths below => strncmp
1493 if ( (safe_strncmp(parent_priv->path, sanitized_path, safe_strlen(sanitized_path)) == 0)
1494 && (port_nr == priv->connection_index) ) {
1496 priv->path = sanitize_path(dev_interface_details->DevicePath);
1498 usbi_dbg("path (%d:%d): %s", discdevs->devices[j]->bus_number,
1499 discdevs->devices[j]->device_address, priv->path);
1501 // Check the service & filter names to know the API we should use
1502 for (k=0; k<3; k++) {
1503 if (SetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, lookup[k].reg_prop,
1504 ®_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1505 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1506 if (lookup[k].reg_prop == SPDRP_SERVICE) {
1507 // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
1508 lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
1510 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1511 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1512 // (currently ';'), so even if an unsuported one does, it's not an issue
1513 for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
1514 if (lookup[k].list[l] == 0) {
1515 lookup[k].list[l] = LIST_SEPARATOR;
1518 upperize(lookup[k].list);
1519 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1522 if (GetLastError() != ERROR_INVALID_DATA) {
1523 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1525 lookup[k].list[0] = 0;
1529 for (api=0; api<USB_API_MAX; api++) {
1530 for (k=0; k<3; k++) {
1531 if (is_api_driver(lookup[k].list, api)) {
1532 usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
1536 if (k >= 3) continue;
1537 priv->apib = &usb_api_backend[api];
1539 case USB_API_COMPOSITE:
1540 set_composite_device(ctx, dev_info_data.DevInst, priv);
1543 safe_free(priv->hid);
1544 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1545 if (priv->hid == NULL) {
1546 usbi_err(ctx, "could not allocate HID data for %s, skipping",
1547 dev_interface_details->DevicePath);
1548 priv->apib = &usb_api_backend[USB_API_UNSUPPORTED];
1549 safe_free(priv->path);
1551 set_hid_device(ctx, priv);
1555 // For other devices, the first interface is the same as the device
1556 priv->usb_interface[0].path = malloc(safe_strlen(priv->path)+1);
1557 if (priv->usb_interface[0].path != NULL) {
1558 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1560 // The following is needed if we want to API calls to work for both simple
1561 // and composite devices, as
1562 for(k=0; k<USB_MAXINTERFACES; k++) {
1563 priv->usb_interface[k].apib = &usb_api_backend[api];
1572 usbi_warn(ctx, "could not match %s with a libusb device.", dev_interface_details->DevicePath);
1577 return LIBUSB_SUCCESS;
1581 * get_device_list: libusb backend device enumeration function
1583 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1585 struct windows_hcd_priv* hcd;
1586 HANDLE handle = INVALID_HANDLE_VALUE;
1587 int r = LIBUSB_SUCCESS;
1590 // Use the index of the HCD in the chained list as bus #
1591 for (hcd = hcd_root, bus = 0; ; hcd = hcd->next, bus++)
1593 safe_closehandle(handle);
1595 if ( (hcd == NULL) || (r != LIBUSB_SUCCESS) )
1598 if (bus == LIBUSB_BUS_MAX) {
1599 usbi_warn(ctx, "program assertion failed - got more than %d buses, skipping the rest.", LIBUSB_BUS_MAX);
1603 handle = CreateFileA(hcd->path, GENERIC_WRITE, FILE_SHARE_WRITE,
1604 NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
1605 if (handle == INVALID_HANDLE_VALUE) {
1606 usbi_warn(ctx, "could not open bus %u, skipping: %s", bus, windows_error_str(0));
1610 LOOP_CHECK(usb_enumerate_hub(ctx, _discdevs, handle, bus, NULL, 1));
1613 // Set the interface path for non-hubs
1614 r = set_device_paths(ctx, *_discdevs);
1620 * exit: libusb backend deinitialization function
1622 static void windows_exit(void)
1624 struct windows_hcd_priv* hcd_tmp;
1627 TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1629 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1630 semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
1631 if (semaphore == NULL) {
1635 // A successful wait brings our semaphore count to 0 (unsignaled)
1636 // => any concurent wait stalls until the semaphore release
1637 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1638 CloseHandle(semaphore);
1642 // Only works if exits and inits are balanced exactly
1643 if (--concurrent_usage < 0) { // Last exit
1644 while (hcd_root != NULL)
1646 hcd_tmp = hcd_root; // Keep a copy for free
1647 hcd_root = hcd_root->next;
1648 windows_hcd_priv_release(hcd_tmp);
1652 for (i=0; i<USB_API_MAX; i++) {
1653 usb_api_backend[i].exit();
1658 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1659 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1660 usbi_dbg("could not wait for timer thread to quit");
1661 TerminateThread(timer_thread, 1);
1663 CloseHandle(timer_thread);
1664 timer_thread = NULL;
1666 for (i = 0; i < 2; i++) {
1667 if (timer_request[i]) {
1668 CloseHandle(timer_request[i]);
1669 timer_request[i] = NULL;
1672 if (timer_response) {
1673 CloseHandle(timer_response);
1674 timer_response = NULL;
1677 CloseHandle(timer_mutex);
1682 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1683 CloseHandle(semaphore);
1686 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1688 struct windows_device_priv *priv = __device_priv(dev);
1690 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1693 return LIBUSB_SUCCESS;
1696 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1698 struct windows_device_priv *priv = __device_priv(dev);
1699 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1702 // config index is zero based
1703 if (config_index >= dev->num_configurations)
1704 return LIBUSB_ERROR_INVALID_PARAM;
1706 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1707 return LIBUSB_ERROR_NOT_FOUND;
1709 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1711 size = min(config_header->wTotalLength, len);
1712 memcpy(buffer, priv->config_descriptor[config_index], size);
1714 return LIBUSB_SUCCESS;
1718 * return the cached copy of the active config descriptor
1720 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1722 struct windows_device_priv *priv = __device_priv(dev);
1724 if (priv->active_config == 0)
1725 return LIBUSB_ERROR_NOT_FOUND;
1727 // config index is zero based
1728 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1731 static int windows_open(struct libusb_device_handle *dev_handle)
1733 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1734 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1736 if (priv->apib == NULL) {
1737 usbi_err(ctx, "program assertion failed - device is not initialized");
1738 return LIBUSB_ERROR_NO_DEVICE;
1741 return priv->apib->open(dev_handle);
1744 static void windows_close(struct libusb_device_handle *dev_handle)
1746 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1748 priv->apib->close(dev_handle);
1751 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1753 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1755 if (priv->active_config == 0) {
1757 return LIBUSB_ERROR_NOT_FOUND;
1760 *config = priv->active_config;
1761 return LIBUSB_SUCCESS;
1765 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1766 * does not currently expose a service that allows higher-level drivers to set
1767 * the configuration."
1769 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1771 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1772 int r = LIBUSB_SUCCESS;
1774 if (config >= USB_MAXCONFIG)
1775 return LIBUSB_ERROR_INVALID_PARAM;
1777 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1778 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1779 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1782 if (r == LIBUSB_SUCCESS) {
1783 priv->active_config = (uint8_t)config;
1788 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1790 int r = LIBUSB_SUCCESS;
1791 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1793 if (iface >= USB_MAXINTERFACES)
1794 return LIBUSB_ERROR_INVALID_PARAM;
1796 safe_free(priv->usb_interface[iface].endpoint);
1797 priv->usb_interface[iface].nb_endpoints= 0;
1799 r = priv->apib->claim_interface(dev_handle, iface);
1801 if (r == LIBUSB_SUCCESS) {
1802 r = windows_assign_endpoints(dev_handle->dev, iface, 0);
1808 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1810 int r = LIBUSB_SUCCESS;
1811 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1813 safe_free(priv->usb_interface[iface].endpoint);
1814 priv->usb_interface[iface].nb_endpoints= 0;
1816 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1818 if (r == LIBUSB_SUCCESS) {
1819 r = windows_assign_endpoints(dev_handle->dev, iface, altsetting);
1825 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1827 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1829 windows_set_interface_altsetting(dev_handle, iface, 0);
1830 return priv->apib->release_interface(dev_handle, iface);
1833 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1835 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1836 return priv->apib->clear_halt(dev_handle, endpoint);
1839 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1841 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1842 return priv->apib->reset_device(dev_handle);
1845 // The 3 functions below are unlikely to ever get supported on Windows
1846 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1848 return LIBUSB_ERROR_NOT_SUPPORTED;
1851 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1853 return LIBUSB_ERROR_NOT_SUPPORTED;
1856 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1858 return LIBUSB_ERROR_NOT_SUPPORTED;
1861 static void windows_destroy_device(struct libusb_device *dev)
1863 struct windows_device_priv *priv = __device_priv(dev);
1864 windows_device_priv_release(priv, dev->num_configurations);
1867 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1869 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1871 usbi_free_fd(transfer_priv->pollable_fd.fd);
1872 safe_free(transfer_priv->hid_buffer);
1873 #if defined(AUTO_CLAIM)
1874 // When auto claim is in use, attempt to release the auto-claimed interface
1875 auto_release(itransfer);
1879 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1881 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1882 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1883 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1884 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1887 r = priv->apib->submit_bulk_transfer(itransfer);
1888 if (r != LIBUSB_SUCCESS) {
1892 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1893 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1894 #if !defined(DYNAMIC_FDS)
1895 usbi_fd_notification(ctx);
1898 return LIBUSB_SUCCESS;
1901 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1903 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1904 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1905 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1906 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1909 r = priv->apib->submit_iso_transfer(itransfer);
1910 if (r != LIBUSB_SUCCESS) {
1914 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1915 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1916 #if !defined(DYNAMIC_FDS)
1917 usbi_fd_notification(ctx);
1920 return LIBUSB_SUCCESS;
1923 static int submit_control_transfer(struct usbi_transfer *itransfer)
1925 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1926 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1927 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1928 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1931 r = priv->apib->submit_control_transfer(itransfer);
1932 if (r != LIBUSB_SUCCESS) {
1936 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1937 #if !defined(DYNAMIC_FDS)
1938 usbi_fd_notification(ctx);
1941 return LIBUSB_SUCCESS;
1945 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1947 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1949 switch (transfer->type) {
1950 case LIBUSB_TRANSFER_TYPE_CONTROL:
1951 return submit_control_transfer(itransfer);
1952 case LIBUSB_TRANSFER_TYPE_BULK:
1953 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1954 return submit_bulk_transfer(itransfer);
1955 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1956 return submit_iso_transfer(itransfer);
1958 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1959 return LIBUSB_ERROR_INVALID_PARAM;
1963 static int windows_abort_control(struct usbi_transfer *itransfer)
1965 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1966 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1968 return priv->apib->abort_control(itransfer);
1971 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1973 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1974 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1976 return priv->apib->abort_transfers(itransfer);
1979 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1981 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1982 #if defined(FORCE_INSTANT_TIMEOUTS)
1983 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1985 // Forces instant overlapped completion on timeouts - use at your own risks
1986 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1987 transfer_priv->pollable_fd.overlapped->Internal &= ~STATUS_PENDING;
1990 switch (transfer->type) {
1991 case LIBUSB_TRANSFER_TYPE_CONTROL:
1992 return windows_abort_control(itransfer);
1993 case LIBUSB_TRANSFER_TYPE_BULK:
1994 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1995 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1996 return windows_abort_transfers(itransfer);
1998 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1999 return LIBUSB_ERROR_INVALID_PARAM;
2003 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2005 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2006 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
2009 usbi_dbg("handling I/O completion with errcode %d", io_result);
2013 status = priv->apib->copy_transfer_data(itransfer, io_size);
2015 case ERROR_GEN_FAILURE:
2016 usbi_dbg("detected endpoint stall");
2017 status = LIBUSB_TRANSFER_STALL;
2019 case ERROR_SEM_TIMEOUT:
2020 usbi_dbg("detected semaphore timeout");
2021 status = LIBUSB_TRANSFER_TIMED_OUT;
2023 case ERROR_OPERATION_ABORTED:
2024 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
2025 usbi_dbg("detected timeout");
2026 status = LIBUSB_TRANSFER_TIMED_OUT;
2028 usbi_dbg("detected operation aborted");
2029 status = LIBUSB_TRANSFER_CANCELLED;
2033 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
2034 status = LIBUSB_TRANSFER_ERROR;
2037 windows_clear_transfer_priv(itransfer); // Cancel polling
2038 usbi_handle_transfer_completion(itransfer, status);
2041 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2043 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2045 switch (transfer->type) {
2046 case LIBUSB_TRANSFER_TYPE_CONTROL:
2047 case LIBUSB_TRANSFER_TYPE_BULK:
2048 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2049 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2050 windows_transfer_callback (itransfer, io_result, io_size);
2053 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2057 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2059 struct windows_transfer_priv* transfer_priv = NULL;
2060 POLL_NFDS_TYPE i = 0;
2062 struct usbi_transfer *transfer;
2063 DWORD io_size, io_result;
2065 usbi_mutex_lock(&ctx->open_devs_lock);
2066 for (i = 0; i < nfds && num_ready > 0; i++) {
2068 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2070 if (!fds[i].revents) {
2076 // Because a Windows OVERLAPPED is used for poll emulation,
2077 // a pollable fd is created and stored with each transfer
2078 usbi_mutex_lock(&ctx->flying_transfers_lock);
2079 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2080 transfer_priv = usbi_transfer_get_os_priv(transfer);
2081 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2086 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2089 // Handle async requests that completed synchronously first
2090 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2091 io_result = NO_ERROR;
2092 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2093 // Regular async overlapped
2094 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2095 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2096 io_result = NO_ERROR;
2098 io_result = GetLastError();
2100 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2101 // let handle_callback free the event using the transfer wfd
2102 // If you don't use the transfer wfd, you run a risk of trying to free a
2103 // newly allocated wfd that took the place of the one from the transfer.
2104 windows_handle_callback(transfer, io_result, io_size);
2106 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2107 return LIBUSB_ERROR_NOT_FOUND;
2111 usbi_mutex_unlock(&ctx->open_devs_lock);
2112 return LIBUSB_SUCCESS;
2116 * Monotonic and real time functions
2118 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2120 LARGE_INTEGER hires_counter, li_frequency;
2124 // Init - find out if we have access to a monotonic (hires) timer
2125 if (!QueryPerformanceFrequency(&li_frequency)) {
2126 usbi_dbg("no hires timer available on this platform");
2127 hires_frequency = 0;
2128 hires_ticks_to_ps = UINT64_C(0);
2130 hires_frequency = li_frequency.QuadPart;
2131 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2132 // to picoseconds to compute the tv_nsecs part in clock_gettime
2133 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2134 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2137 // Main loop - wait for requests
2139 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2140 if ( (timer_index != 0) && (timer_index != 1) ) {
2141 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2144 if (request_count[timer_index] == 0) {
2145 // Request already handled
2146 ResetEvent(timer_request[timer_index]);
2147 // There's still a possiblity that a thread sends a request between the
2148 // time we test request_count[] == 0 and we reset the event, in which case
2149 // the request would be ignored. The simple solution to that is to test
2150 // request_count again and process requests if non zero.
2151 if (request_count[timer_index] == 0)
2154 switch (timer_index) {
2156 WaitForSingleObject(timer_mutex, INFINITE);
2157 // Requests to this thread are for hires always
2158 if (QueryPerformanceCounter(&hires_counter) != 0) {
2159 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2160 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2162 // Fallback to real-time if we can't get monotonic value
2163 // Note that real-time clock does not wait on the mutex or this thread.
2164 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2166 ReleaseMutex(timer_mutex);
2168 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2170 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2171 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2174 case 1: // time to quit
2175 usbi_dbg("timer thread quitting");
2179 usbi_dbg("ERROR: broken timer thread");
2183 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2186 ULARGE_INTEGER rtime;
2189 case USBI_CLOCK_MONOTONIC:
2190 if (hires_frequency != 0) {
2192 InterlockedIncrement((LONG*)&request_count[0]);
2193 SetEvent(timer_request[0]);
2194 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2197 WaitForSingleObject(timer_mutex, INFINITE);
2199 ReleaseMutex(timer_mutex);
2200 return LIBUSB_SUCCESS;
2202 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2203 break; // Retry until successful
2205 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2206 return LIBUSB_ERROR_OTHER;
2210 // Fall through and return real-time if monotonic was not detected @ timer init
2211 case USBI_CLOCK_REALTIME:
2212 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2213 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2214 // Note however that our resolution is bounded by the Windows system time
2215 // functions and is at best of the order of 1 ms (or, usually, worse)
2216 GetSystemTimeAsFileTime(&filetime);
2217 rtime.LowPart = filetime.dwLowDateTime;
2218 rtime.HighPart = filetime.dwHighDateTime;
2219 rtime.QuadPart -= epoch_time;
2220 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2221 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2222 return LIBUSB_SUCCESS;
2224 return LIBUSB_ERROR_INVALID_PARAM;
2229 // NB: MSVC6 does not support named initializers.
2230 const struct usbi_os_backend windows_backend = {
2235 windows_get_device_list,
2239 windows_get_device_descriptor,
2240 windows_get_active_config_descriptor,
2241 windows_get_config_descriptor,
2243 windows_get_configuration,
2244 windows_set_configuration,
2245 windows_claim_interface,
2246 windows_release_interface,
2248 windows_set_interface_altsetting,
2250 windows_reset_device,
2252 windows_kernel_driver_active,
2253 windows_detach_kernel_driver,
2254 windows_attach_kernel_driver,
2256 windows_destroy_device,
2258 windows_submit_transfer,
2259 windows_cancel_transfer,
2260 windows_clear_transfer_priv,
2262 windows_handle_events,
2264 windows_clock_gettime,
2265 #if defined(USBI_TIMERFD_AVAILABLE)
2268 sizeof(struct windows_device_priv),
2269 sizeof(struct windows_device_handle_priv),
2270 sizeof(struct windows_transfer_priv),
2278 static int unsupported_init(struct libusb_context *ctx) {
2279 return LIBUSB_SUCCESS;
2281 static int unsupported_exit(void) {
2282 return LIBUSB_SUCCESS;
2284 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2285 PRINT_UNSUPPORTED_API(open);
2287 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2288 usbi_dbg("unsupported API call for 'close'");
2290 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2291 PRINT_UNSUPPORTED_API(claim_interface);
2293 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2294 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2296 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2297 PRINT_UNSUPPORTED_API(release_interface);
2299 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2300 PRINT_UNSUPPORTED_API(clear_halt);
2302 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2303 PRINT_UNSUPPORTED_API(reset_device);
2305 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2306 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2308 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2309 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2311 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2312 PRINT_UNSUPPORTED_API(submit_control_transfer);
2314 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2315 PRINT_UNSUPPORTED_API(abort_control);
2317 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2318 PRINT_UNSUPPORTED_API(abort_transfers);
2320 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2321 PRINT_UNSUPPORTED_API(copy_transfer_data);
2324 // These names must be uppercase
2325 const char* composite_driver_names[] = {"USBCCGP"};
2326 const char* winusb_driver_names[] = {"WINUSB"};
2327 const char* hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2328 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2330 USB_API_UNSUPPORTED,
2332 &CLASS_GUID_UNSUPPORTED,
2339 unsupported_claim_interface,
2340 unsupported_set_interface_altsetting,
2341 unsupported_release_interface,
2342 unsupported_clear_halt,
2343 unsupported_reset_device,
2344 unsupported_submit_bulk_transfer,
2345 unsupported_submit_iso_transfer,
2346 unsupported_submit_control_transfer,
2347 unsupported_abort_control,
2348 unsupported_abort_transfers,
2349 unsupported_copy_transfer_data,
2353 &CLASS_GUID_COMPOSITE,
2354 composite_driver_names,
2355 sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
2360 composite_claim_interface,
2361 composite_set_interface_altsetting,
2362 composite_release_interface,
2363 composite_clear_halt,
2364 composite_reset_device,
2365 composite_submit_bulk_transfer,
2366 composite_submit_iso_transfer,
2367 composite_submit_control_transfer,
2368 composite_abort_control,
2369 composite_abort_transfers,
2370 composite_copy_transfer_data,
2374 &CLASS_GUID_LIBUSB_WINUSB,
2375 winusb_driver_names,
2376 sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
2381 winusb_claim_interface,
2382 winusb_set_interface_altsetting,
2383 winusb_release_interface,
2385 winusb_reset_device,
2386 winusb_submit_bulk_transfer,
2387 unsupported_submit_iso_transfer,
2388 winusb_submit_control_transfer,
2389 winusb_abort_control,
2390 winusb_abort_transfers,
2391 winusb_copy_transfer_data,
2397 sizeof(hid_driver_names)/sizeof(hid_driver_names[0]),
2402 hid_claim_interface,
2403 hid_set_interface_altsetting,
2404 hid_release_interface,
2407 hid_submit_bulk_transfer,
2408 unsupported_submit_iso_transfer,
2409 hid_submit_control_transfer,
2410 hid_abort_transfers,
2411 hid_abort_transfers,
2412 hid_copy_transfer_data,
2418 * WinUSB API functions
2420 static int winusb_init(struct libusb_context *ctx)
2422 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2423 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2424 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2425 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2426 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2427 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2428 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2429 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2430 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2431 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2432 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2433 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2434 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2435 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2436 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2437 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2438 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2440 api_winusb_available = true;
2441 return LIBUSB_SUCCESS;
2444 static int winusb_exit(void)
2446 return LIBUSB_SUCCESS;
2449 // NB: open and close must ensure that they only handle interface of
2450 // the right API type, as these functions can be called wholesale from
2451 // composite_open(), with interfaces belonging to different APIs
2452 static int winusb_open(struct libusb_device_handle *dev_handle)
2454 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2455 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2456 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2461 CHECK_WINUSB_AVAILABLE;
2463 // WinUSB requires a seperate handle for each interface
2464 for (i = 0; i < USB_MAXINTERFACES; i++) {
2465 if ( (priv->usb_interface[i].path != NULL)
2466 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2467 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2468 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2469 if (file_handle == INVALID_HANDLE_VALUE) {
2470 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2471 switch(GetLastError()) {
2472 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2473 return LIBUSB_ERROR_NO_DEVICE;
2474 case ERROR_ACCESS_DENIED:
2475 return LIBUSB_ERROR_ACCESS;
2477 return LIBUSB_ERROR_IO;
2480 handle_priv->interface_handle[i].dev_handle = file_handle;
2484 return LIBUSB_SUCCESS;
2487 static void winusb_close(struct libusb_device_handle *dev_handle)
2489 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2490 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2494 if (!api_winusb_available)
2497 for (i = 0; i < USB_MAXINTERFACES; i++) {
2498 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2499 file_handle = handle_priv->interface_handle[i].dev_handle;
2500 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2501 CloseHandle(file_handle);
2507 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2509 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2510 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2511 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2512 bool is_composite = (priv->apib->id == USB_API_COMPOSITE);
2513 HANDLE file_handle, winusb_handle;
2514 USB_INTERFACE_DESCRIPTOR if_desc;
2516 uint8_t endpoint_address;
2519 CHECK_WINUSB_AVAILABLE;
2521 // interfaces for composite devices are always independent, therefore
2522 // "alt" interfaces are only found on non-composite
2523 if ((!is_composite) && (iface != 0)) {
2524 winusb_handle = handle_priv->interface_handle[0].api_handle;
2525 // It is a requirement on Windows that to claim an interface >= 1
2526 // on a non-composite WinUSB device, you must first have claimed interface 0
2527 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2528 #if defined(AUTO_CLAIM)
2529 file_handle = handle_priv->interface_handle[0].dev_handle;
2530 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2531 handle_priv->interface_handle[0].api_handle = winusb_handle;
2532 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2534 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2535 return LIBUSB_ERROR_ACCESS;
2538 usbi_warn(ctx, "you must claim interface 0 before you can claim %d with WinUSB", iface);
2539 return LIBUSB_ERROR_ACCESS;
2542 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2543 &handle_priv->interface_handle[iface].api_handle)) {
2544 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2545 switch(GetLastError()) {
2546 case ERROR_NO_MORE_ITEMS: // invalid iface
2547 return LIBUSB_ERROR_NOT_FOUND;
2548 case ERROR_BAD_COMMAND: // The device was disconnected
2549 return LIBUSB_ERROR_NO_DEVICE;
2550 case ERROR_ALREADY_EXISTS: // already claimed
2551 return LIBUSB_ERROR_BUSY;
2553 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2554 return LIBUSB_ERROR_ACCESS;
2558 // composite device (independent interfaces) or interface 0
2559 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2560 file_handle = handle_priv->interface_handle[iface].dev_handle;
2561 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2562 return LIBUSB_ERROR_NOT_FOUND;
2565 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2566 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2567 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2569 switch(GetLastError()) {
2570 case ERROR_BAD_COMMAND: // The device was disconnected
2571 return LIBUSB_ERROR_NO_DEVICE;
2573 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2574 return LIBUSB_ERROR_ACCESS;
2577 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2579 if (!WinUsb_QueryInterfaceSettings(winusb_handle, 0, &if_desc)) {
2580 usbi_err(ctx, "could not query interface settings for interface %d: %s", iface, windows_error_str(0));
2581 } else if (if_desc.bInterfaceNumber != iface) {
2582 usbi_warn(ctx, "program assertion failed - WinUSB interface %d found at position %d",
2583 if_desc.bInterfaceNumber, iface);
2586 usbi_dbg("claimed interface %d", iface);
2587 handle_priv->active_interface = iface;
2589 // With handle and enpoints set (in parent), we can setup the default
2590 // pipe properties (copied from libusb-win32-v1)
2591 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2592 for (i=0; i<priv->usb_interface[iface].nb_endpoints; i++) {
2593 endpoint_address = priv->usb_interface[iface].endpoint[i];
2595 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2596 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2597 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2599 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2600 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2601 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2603 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2604 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2605 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2608 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2609 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2610 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2614 return LIBUSB_SUCCESS;
2617 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2619 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2620 HANDLE winusb_handle;
2622 CHECK_WINUSB_AVAILABLE;
2624 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2625 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2626 return LIBUSB_ERROR_NOT_FOUND;
2629 WinUsb_Free(winusb_handle);
2630 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2632 return LIBUSB_SUCCESS;
2636 * Return the first valid interface (of the same API type), for control transfers
2638 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2640 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2641 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2644 if ((api_id < USB_API_WINUSB) || (api_id > USB_API_HID)) {
2645 usbi_dbg("unsupported API ID");
2649 for (i=0; i<USB_MAXINTERFACES; i++) {
2650 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2651 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2652 && (handle_priv->interface_handle[i].api_handle != 0)
2653 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2654 && (priv->usb_interface[i].apib == &usb_api_backend[api_id]) ) {
2662 * Lookup interface by endpoint address. -1 if not found
2664 static int interface_by_endpoint(struct windows_device_priv *priv,
2665 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2668 for (i=0; i<USB_MAXINTERFACES; i++) {
2669 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2671 if (handle_priv->interface_handle[i].api_handle == 0)
2673 if (priv->usb_interface[i].endpoint == NULL)
2675 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2676 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2684 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2686 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2687 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2688 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2689 struct windows_device_handle_priv *handle_priv = __device_handle_priv(
2690 transfer->dev_handle);
2691 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2693 HANDLE winusb_handle;
2694 int current_interface;
2697 CHECK_WINUSB_AVAILABLE;
2699 transfer_priv->pollable_fd = INVALID_WINFD;
2700 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2702 if (size > MAX_CTRL_BUFFER_LENGTH)
2703 return LIBUSB_ERROR_INVALID_PARAM;
2705 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSB);
2706 if (current_interface < 0) {
2707 #if defined(AUTO_CLAIM)
2708 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2709 return LIBUSB_ERROR_NOT_FOUND;
2712 usbi_warn(ctx, "no interface available for control transfer");
2713 return LIBUSB_ERROR_NOT_FOUND;
2717 usbi_dbg("will use interface %d", current_interface);
2718 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2720 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2721 // Always use the handle returned from usbi_create_fd (wfd.handle)
2723 return LIBUSB_ERROR_NO_MEM;
2726 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2727 if(GetLastError() != ERROR_IO_PENDING) {
2728 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2729 usbi_free_fd(wfd.fd);
2730 return LIBUSB_ERROR_IO;
2733 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2734 wfd.overlapped->InternalHigh = (DWORD)size;
2737 // Use priv_transfer to store data needed for async polling
2738 transfer_priv->pollable_fd = wfd;
2739 transfer_priv->interface_number = (uint8_t)current_interface;
2741 return LIBUSB_SUCCESS;
2744 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2746 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2747 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2748 HANDLE winusb_handle;
2750 CHECK_WINUSB_AVAILABLE;
2752 if (altsetting > 255) {
2753 return LIBUSB_ERROR_INVALID_PARAM;
2756 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2757 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2758 usbi_err(ctx, "interface must be claimed first");
2759 return LIBUSB_ERROR_NOT_FOUND;
2762 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2763 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2764 return LIBUSB_ERROR_IO;
2767 return LIBUSB_SUCCESS;
2770 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2772 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2773 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2774 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2775 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
2776 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
2777 HANDLE winusb_handle;
2778 bool direction_in, ret;
2779 int current_interface;
2782 CHECK_WINUSB_AVAILABLE;
2784 transfer_priv->pollable_fd = INVALID_WINFD;
2786 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2787 if (current_interface < 0) {
2788 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2789 return LIBUSB_ERROR_NOT_FOUND;
2792 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2794 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2795 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
2797 wfd = usbi_create_fd(winusb_handle, direction_in?_O_RDONLY:_O_WRONLY);
2798 // Always use the handle returned from usbi_create_fd (wfd.handle)
2800 return LIBUSB_ERROR_NO_MEM;
2804 usbi_dbg("reading %d bytes", transfer->length);
2805 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2807 usbi_dbg("writing %d bytes", transfer->length);
2808 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2811 if(GetLastError() != ERROR_IO_PENDING) {
2812 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2813 usbi_free_fd(wfd.fd);
2814 return LIBUSB_ERROR_IO;
2817 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2818 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2821 transfer_priv->pollable_fd = wfd;
2822 transfer_priv->interface_number = (uint8_t)current_interface;
2824 return LIBUSB_SUCCESS;
2827 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2829 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2830 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2831 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2832 HANDLE winusb_handle;
2833 int current_interface;
2835 CHECK_WINUSB_AVAILABLE;
2837 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2838 if (current_interface < 0) {
2839 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2840 return LIBUSB_ERROR_NOT_FOUND;
2843 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2844 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2846 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2847 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2848 return LIBUSB_ERROR_NO_DEVICE;
2851 return LIBUSB_SUCCESS;
2855 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2856 * through testing as well):
2857 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2858 * the control transfer using CancelIo"
2860 static int winusb_abort_control(struct usbi_transfer *itransfer)
2862 // Cancelling of the I/O is done in the parent
2863 return LIBUSB_SUCCESS;
2866 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2868 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2869 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2870 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
2871 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2872 HANDLE winusb_handle;
2873 int current_interface;
2875 CHECK_WINUSB_AVAILABLE;
2877 current_interface = transfer_priv->interface_number;
2878 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2879 usbi_err(ctx, "program assertion failed: invalid interface_number");
2880 return LIBUSB_ERROR_NOT_FOUND;
2882 usbi_dbg("will use interface %d", current_interface);
2884 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2886 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2887 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2888 return LIBUSB_ERROR_NO_DEVICE;
2891 return LIBUSB_SUCCESS;
2895 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2896 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2897 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2898 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2899 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2900 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2902 // TODO (2nd official release): see if we can force eject the device and redetect it (reuse hotplug?)
2903 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2905 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2906 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2907 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2909 HANDLE winusb_handle;
2912 CHECK_WINUSB_AVAILABLE;
2914 // Reset any available pipe (except control)
2915 for (i=0; i<USB_MAXINTERFACES; i++) {
2916 winusb_handle = handle_priv->interface_handle[i].api_handle;
2917 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2919 // Cancel any pollable I/O
2920 usbi_remove_pollfd(ctx, wfd.fd);
2921 usbi_free_fd(wfd.fd);
2922 wfd = handle_to_winfd(winusb_handle);
2925 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2926 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2927 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2928 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2929 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2930 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2932 // FlushPipe seems to fail on OUT pipes
2933 if ( (priv->usb_interface[i].endpoint[j] & LIBUSB_ENDPOINT_IN)
2934 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2935 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2936 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2938 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2939 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2940 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2946 return LIBUSB_SUCCESS;
2949 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2951 itransfer->transferred += io_size;
2952 return LIBUSB_TRANSFER_COMPLETED;
2956 * Internal HID Support functions (from libusb-win32)
2957 * Note that functions that complete data transfer synchronously must return
2958 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
2960 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2961 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2963 static int _hid_wcslen(WCHAR *str)
2966 while (str[i] && (str[i] != 0x409)) {
2972 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2974 struct libusb_device_descriptor d;
2976 d.bLength = LIBUSB_DT_DEVICE_SIZE;
2977 d.bDescriptorType = LIBUSB_DT_DEVICE;
2978 d.bcdUSB = 0x0200; /* 2.00 */
2980 d.bDeviceSubClass = 0;
2981 d.bDeviceProtocol = 0;
2982 d.bMaxPacketSize0 = 64; /* fix this! */
2983 d.idVendor = (uint16_t)dev->vid;
2984 d.idProduct = (uint16_t)dev->pid;
2985 d.bcdDevice = 0x0100;
2986 d.iManufacturer = dev->string_index[0];
2987 d.iProduct = dev->string_index[1];
2988 d.iSerialNumber = dev->string_index[2];
2989 d.bNumConfigurations = 1;
2991 if (*size > LIBUSB_DT_DEVICE_SIZE)
2992 *size = LIBUSB_DT_DEVICE_SIZE;
2993 memcpy(data, &d, *size);
2994 return LIBUSB_COMPLETED;
2997 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2999 char num_endpoints = 0;
3000 size_t config_total_len = 0;
3001 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3002 struct libusb_config_descriptor *cd;
3003 struct libusb_interface_descriptor *id;
3004 struct libusb_hid_descriptor *hd;
3005 struct libusb_endpoint_descriptor *ed;
3008 if (dev->input_report_size)
3010 if (dev->output_report_size)
3013 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3014 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3017 cd = (struct libusb_config_descriptor *)tmp;
3018 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3019 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3020 + LIBUSB_DT_INTERFACE_SIZE);
3021 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3022 + LIBUSB_DT_INTERFACE_SIZE
3023 + LIBUSB_DT_HID_SIZE);
3025 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3026 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3027 cd->wTotalLength = (uint16_t) config_total_len;
3028 cd->bNumInterfaces = 1;
3029 cd->bConfigurationValue = 1;
3030 cd->iConfiguration = 0;
3031 cd->bmAttributes = 1 << 7; /* bus powered */
3034 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3035 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3036 id->bInterfaceNumber = 0;
3037 id->bAlternateSetting = 0;
3038 id->bNumEndpoints = num_endpoints;
3039 id->bInterfaceClass = 3;
3040 id->bInterfaceSubClass = 0;
3041 id->bInterfaceProtocol = 0;
3044 tmp_size = LIBUSB_DT_HID_SIZE;
3045 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3047 if (dev->input_report_size) {
3048 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3049 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3050 ed->bEndpointAddress = HID_IN_EP;
3051 ed->bmAttributes = 3;
3052 ed->wMaxPacketSize = dev->input_report_size - 1;
3058 if (dev->output_report_size) {
3059 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3060 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3061 ed->bEndpointAddress = HID_OUT_EP;
3062 ed->bmAttributes = 3;
3063 ed->wMaxPacketSize = dev->output_report_size - 1;
3067 if (*size > config_total_len)
3068 *size = config_total_len;
3069 memcpy(data, tmp, *size);
3070 return LIBUSB_COMPLETED;
3073 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int index,
3074 void *data, size_t *size)
3077 size_t tmp_size = 0;
3080 /* language ID, EN-US */
3081 char string_langid[] = {
3086 if ((*size < 2) || (*size > 255)) {
3087 return LIBUSB_ERROR_OVERFLOW;
3091 tmp = string_langid;
3092 tmp_size = sizeof(string_langid)+2;
3094 for (i=0; i<3; i++) {
3095 if (index == (dev->string_index[i])) {
3096 tmp = dev->string[i];
3097 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3101 if (i == 3) { // not found
3102 return LIBUSB_ERROR_INVALID_PARAM;
3107 return LIBUSB_ERROR_INVALID_PARAM;
3110 if (tmp_size < *size) {
3114 ((uint8_t*)data)[0] = (uint8_t)*size;
3115 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3116 memcpy((uint8_t*)data+2, tmp, *size-2);
3117 return LIBUSB_COMPLETED;
3120 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3122 struct libusb_hid_descriptor d;
3123 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3124 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3126 _hid_get_report_descriptor(dev, tmp, &report_len);
3128 d.bLength = LIBUSB_DT_HID_SIZE;
3129 d.bDescriptorType = LIBUSB_DT_HID;
3130 d.bcdHID = 0x0110; /* 1.10 */
3132 d.bNumDescriptors = 1;
3133 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3134 d.wClassDescriptorLength = (uint16_t)report_len;
3136 if (*size > LIBUSB_DT_HID_SIZE)
3137 *size = LIBUSB_DT_HID_SIZE;
3138 memcpy(data, &d, *size);
3139 return LIBUSB_COMPLETED;
3142 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3144 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3147 /* usage page (0xFFA0 == vendor defined) */
3148 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3149 /* usage (vendor defined) */
3150 d[i++] = 0x09; d[i++] = 0x01;
3151 /* start collection (application) */
3152 d[i++] = 0xA1; d[i++] = 0x01;
3154 if (dev->input_report_size) {
3155 /* usage (vendor defined) */
3156 d[i++] = 0x09; d[i++] = 0x01;
3157 /* logical minimum (0) */
3158 d[i++] = 0x15; d[i++] = 0x00;
3159 /* logical maximum (255) */
3160 d[i++] = 0x25; d[i++] = 0xFF;
3161 /* report size (8 bits) */
3162 d[i++] = 0x75; d[i++] = 0x08;
3164 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3165 /* input (data, variable, absolute) */
3166 d[i++] = 0x81; d[i++] = 0x00;
3169 if (dev->output_report_size) {
3170 /* usage (vendor defined) */
3171 d[i++] = 0x09; d[i++] = 0x02;
3172 /* logical minimum (0) */
3173 d[i++] = 0x15; d[i++] = 0x00;
3174 /* logical maximum (255) */
3175 d[i++] = 0x25; d[i++] = 0xFF;
3176 /* report size (8 bits) */
3177 d[i++] = 0x75; d[i++] = 0x08;
3179 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3180 /* output (data, variable, absolute) */
3181 d[i++] = 0x91; d[i++] = 0x00;
3183 /* feature report */
3184 if (dev->feature_report_size) {
3185 /* usage (vendor defined) */
3186 d[i++] = 0x09; d[i++] = 0x03;
3187 /* logical minimum (0) */
3188 d[i++] = 0x15; d[i++] = 0x00;
3189 /* logical maximum (255) */
3190 d[i++] = 0x25; d[i++] = 0xFF;
3191 /* report size (8 bits) */
3192 d[i++] = 0x75; d[i++] = 0x08;
3194 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3195 /* feature (data, variable, absolute) */
3196 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3199 /* end collection */
3204 memcpy(data, d, *size);
3205 return LIBUSB_COMPLETED;
3208 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3209 int type, int index, void *data, size_t *size)
3212 case LIBUSB_DT_DEVICE:
3213 usbi_dbg("LIBUSB_DT_DEVICE");
3214 return _hid_get_device_descriptor(dev, data, size);
3215 case LIBUSB_DT_CONFIG:
3216 usbi_dbg("LIBUSB_DT_CONFIG");
3218 return _hid_get_config_descriptor(dev, data, size);
3219 return LIBUSB_ERROR_INVALID_PARAM;
3220 case LIBUSB_DT_STRING:
3221 usbi_dbg("LIBUSB_DT_STRING");
3222 return _hid_get_string_descriptor(dev, index, data, size);
3224 usbi_dbg("LIBUSB_DT_HID");
3226 return _hid_get_hid_descriptor(dev, data, size);
3227 return LIBUSB_ERROR_INVALID_PARAM;
3228 case LIBUSB_DT_REPORT:
3229 usbi_dbg("LIBUSB_DT_REPORT");
3231 return _hid_get_report_descriptor(dev, data, size);
3232 return LIBUSB_ERROR_INVALID_PARAM;
3233 case LIBUSB_DT_PHYSICAL:
3234 usbi_dbg("LIBUSB_DT_PHYSICAL");
3235 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3236 return LIBUSB_COMPLETED;
3237 return LIBUSB_ERROR_OTHER;
3239 usbi_dbg("unsupported");
3240 return LIBUSB_ERROR_INVALID_PARAM;
3243 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3244 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3248 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3249 int r = LIBUSB_SUCCESS;
3251 if (tp->hid_buffer != NULL) {
3252 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3255 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3256 usbi_dbg("invalid size (%d)", *size);
3257 return LIBUSB_ERROR_INVALID_PARAM;
3260 switch (report_type) {
3261 case HID_REPORT_TYPE_INPUT:
3262 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3264 case HID_REPORT_TYPE_FEATURE:
3265 ioctl_code = IOCTL_HID_GET_FEATURE;
3268 usbi_dbg("unknown HID report type %d", report_type);
3269 return LIBUSB_ERROR_INVALID_PARAM;
3272 // When report IDs are not in use, add an extra byte for the report ID
3277 // Add a trailing byte to detect overflows
3278 buf = (uint8_t*)calloc(expected_size+1, 1);
3280 return LIBUSB_ERROR_NO_MEM;
3282 buf[0] = (uint8_t)id; // Must be set always
3283 usbi_dbg("report ID: 0x%02X", buf[0]);
3285 tp->hid_expected_size = expected_size;
3287 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3288 buf, expected_size+1, &read_size, overlapped)) {
3289 if (GetLastError() != ERROR_IO_PENDING) {
3290 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3292 return LIBUSB_ERROR_IO;
3294 // Asynchronous wait
3295 tp->hid_buffer = buf;
3296 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3297 return LIBUSB_SUCCESS;
3300 // Transfer completed synchronously => copy and discard extra buffer
3301 if (read_size == 0) {
3302 usbi_dbg("program assertion failed - read completed synchronously, but no data was read");
3306 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3308 if ((size_t)read_size > expected_size) {
3309 r = LIBUSB_ERROR_OVERFLOW;
3310 usbi_dbg("OVERFLOW!");
3312 r = LIBUSB_COMPLETED;
3316 // Discard report ID
3317 *size = MIN((size_t)read_size-1, *size);
3318 memcpy(data, buf+1, *size);
3320 *size = MIN((size_t)read_size, *size);
3321 memcpy(data, buf, *size);
3328 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3329 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3332 uint8_t *buf = NULL;
3333 DWORD ioctl_code, write_size= (DWORD)*size;
3335 if (tp->hid_buffer != NULL) {
3336 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3339 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3340 usbi_dbg("invalid size (%d)", *size);
3341 return LIBUSB_ERROR_INVALID_PARAM;
3344 switch (report_type) {
3345 case HID_REPORT_TYPE_OUTPUT:
3346 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3348 case HID_REPORT_TYPE_FEATURE:
3349 ioctl_code = IOCTL_HID_SET_FEATURE;
3352 usbi_dbg("unknown HID report type %d", report_type);
3353 return LIBUSB_ERROR_INVALID_PARAM;
3356 usbi_dbg("report ID: 0x%02X", id);
3357 // When report IDs are not used (i.e. when id == 0), we must add
3358 // a null report ID. Otherwise, we just use original data buffer
3362 buf = malloc(write_size);
3364 return LIBUSB_ERROR_NO_MEM;
3368 memcpy(buf + 1, data, *size);
3370 // This seems like a waste, but if we don't duplicate the
3371 // data, we'll get issues when freeing hid_buffer
3372 memcpy(buf, data, *size);
3374 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3378 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3379 buf, write_size, &write_size, overlapped)) {
3380 if (GetLastError() != ERROR_IO_PENDING) {
3381 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3383 return LIBUSB_ERROR_IO;
3385 tp->hid_buffer = buf;
3386 tp->hid_dest = NULL;
3387 return LIBUSB_SUCCESS;
3390 // Transfer completed synchronously
3391 if (write_size == 0) {
3392 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3395 *size = write_size - ((id == 0)?1:0);
3398 return LIBUSB_COMPLETED;
3401 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3402 int request, int value, int index, void *data, struct windows_transfer_priv *tp,
3403 size_t *size, OVERLAPPED* overlapped)
3405 int report_type = (value >> 8) & 0xFF;
3406 int report_id = value & 0xFF;
3408 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3409 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3410 return LIBUSB_ERROR_INVALID_PARAM;
3412 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3413 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3415 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3416 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3418 return LIBUSB_ERROR_INVALID_PARAM;
3425 static int hid_init(struct libusb_context *ctx)
3427 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3428 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3429 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3430 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3431 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3432 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3433 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3434 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3435 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3436 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3437 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3438 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3439 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3440 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3441 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3442 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3444 api_hid_available = true;
3445 return LIBUSB_SUCCESS;
3448 static int hid_exit(void)
3450 return LIBUSB_SUCCESS;
3453 // NB: open and close must ensure that they only handle interface of
3454 // the right API type, as these functions can be called wholesale from
3455 // composite_open(), with interfaces belonging to different APIs
3456 static int hid_open(struct libusb_device_handle *dev_handle)
3458 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3459 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3460 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3462 HIDD_ATTRIBUTES hid_attributes;
3463 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3464 HIDP_CAPS capabilities;
3465 HIDP_VALUE_CAPS *value_caps;
3467 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3469 // report IDs handling
3471 char* type[3] = {"input", "output", "feature"};
3472 int nb_ids[2]; // zero and nonzero report IDs
3474 CHECK_HID_AVAILABLE;
3475 if (priv->hid == NULL) {
3476 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3477 return LIBUSB_ERROR_NOT_FOUND;
3480 for (i = 0; i < USB_MAXINTERFACES; i++) {
3481 if ( (priv->usb_interface[i].path != NULL)
3482 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3483 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3484 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3486 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3487 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3488 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3489 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3490 * HidD_GetFeature (if the device supports Feature reports)."
3492 if (hid_handle == INVALID_HANDLE_VALUE) {
3493 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3494 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3495 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3496 if (hid_handle == INVALID_HANDLE_VALUE) {
3497 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3498 switch(GetLastError()) {
3499 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3500 return LIBUSB_ERROR_NO_DEVICE;
3501 case ERROR_ACCESS_DENIED:
3502 return LIBUSB_ERROR_ACCESS;
3504 return LIBUSB_ERROR_IO;
3507 priv->usb_interface[i].restricted_functionality = true;
3509 handle_priv->interface_handle[i].api_handle = hid_handle;
3513 hid_attributes.Size = sizeof(hid_attributes);
3515 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3516 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3520 priv->hid->vid = hid_attributes.VendorID;
3521 priv->hid->pid = hid_attributes.ProductID;
3523 // Set the maximum available input buffer size
3524 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3525 usbi_dbg("set maximum input buffer size to %d", i/2);
3527 // Get the maximum input and output report size
3528 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3529 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3532 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3533 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3537 // Find out if interrupt will need report IDs
3538 size[0] = capabilities.NumberInputValueCaps;
3539 size[1] = capabilities.NumberOutputValueCaps;
3540 size[2] = capabilities.NumberFeatureValueCaps;
3541 for (j=0; j<3; j++) {
3542 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3543 priv->hid->uses_report_ids[j] = false;
3545 value_caps = malloc(size[j] * sizeof(HIDP_VALUE_CAPS));
3546 if ( (value_caps != NULL)
3547 && (HidP_GetValueCaps(j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3548 && (size[j] >= 1) ) {
3551 for (i=0; i<(int)size[j]; i++) {
3552 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3553 if (value_caps[i].ReportID != 0) {
3559 if (nb_ids[1] != 0) {
3560 if (nb_ids[0] != 0) {
3561 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3564 priv->hid->uses_report_ids[j] = true;
3567 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3569 safe_free(value_caps);
3573 // Set the report sizes
3574 priv->hid->input_report_size = capabilities.InputReportByteLength;
3575 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3576 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3578 // Fetch string descriptors
3579 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3580 if (priv->hid->string_index[0] != 0) {
3581 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3582 sizeof(priv->hid->string[0]));
3584 priv->hid->string[0][0] = 0;
3586 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3587 if (priv->hid->string_index[1] != 0) {
3588 HidD_GetProductString(hid_handle, priv->hid->string[1],
3589 sizeof(priv->hid->string[1]));
3591 priv->hid->string[1][0] = 0;
3593 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3594 if (priv->hid->string_index[2] != 0) {
3595 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3596 sizeof(priv->hid->string[2]));
3598 priv->hid->string[2][0] = 0;
3602 if (preparsed_data) {
3603 HidD_FreePreparsedData(preparsed_data);
3606 return LIBUSB_SUCCESS;
3609 static void hid_close(struct libusb_device_handle *dev_handle)
3611 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3612 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3616 if (!api_hid_available)
3619 for (i = 0; i < USB_MAXINTERFACES; i++) {
3620 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3621 file_handle = handle_priv->interface_handle[i].api_handle;
3622 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3623 CloseHandle(file_handle);
3629 static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface)
3631 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3632 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3634 CHECK_HID_AVAILABLE;
3636 // NB: Disconnection detection is not possible in this function
3637 if (priv->usb_interface[iface].path == NULL) {
3638 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3641 // We use dev_handle as a flag for interface claimed
3642 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3643 return LIBUSB_ERROR_BUSY; // already claimed
3646 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3648 usbi_dbg("claimed interface %d", iface);
3649 handle_priv->active_interface = iface;
3651 return LIBUSB_SUCCESS;
3654 static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface)
3656 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3657 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3659 CHECK_HID_AVAILABLE;
3661 if (priv->usb_interface[iface].path == NULL) {
3662 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3665 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
3666 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3669 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3671 return LIBUSB_SUCCESS;
3674 static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
3676 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3678 CHECK_HID_AVAILABLE;
3680 if (altsetting > 255) {
3681 return LIBUSB_ERROR_INVALID_PARAM;
3684 if (altsetting != 0) {
3685 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3686 return LIBUSB_ERROR_NOT_SUPPORTED;
3689 return LIBUSB_SUCCESS;
3692 static int hid_submit_control_transfer(struct usbi_transfer *itransfer)
3694 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3695 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3696 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3697 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
3698 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3699 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3702 int current_interface, config;
3704 int r = LIBUSB_ERROR_INVALID_PARAM;
3706 CHECK_HID_AVAILABLE;
3708 transfer_priv->pollable_fd = INVALID_WINFD;
3709 safe_free(transfer_priv->hid_buffer);
3710 transfer_priv->hid_dest = NULL;
3711 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3713 if (size > MAX_CTRL_BUFFER_LENGTH) {
3714 return LIBUSB_ERROR_INVALID_PARAM;
3717 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3718 if (current_interface < 0) {
3719 #if defined(AUTO_CLAIM)
3720 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) {
3721 return LIBUSB_ERROR_NOT_FOUND;
3724 usbi_warn(ctx, "no interface available for control transfer");
3725 return LIBUSB_ERROR_NOT_FOUND;
3729 usbi_dbg("will use interface %d", current_interface);
3730 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3731 // Always use the handle returned from usbi_create_fd (wfd.handle)
3732 wfd = usbi_create_fd(hid_handle, _O_RDONLY);
3734 return LIBUSB_ERROR_NO_MEM;
3737 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3738 case LIBUSB_REQUEST_TYPE_STANDARD:
3739 switch(setup->request) {
3740 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3741 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3742 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3744 case LIBUSB_REQUEST_GET_CONFIGURATION:
3745 r = windows_get_configuration(transfer->dev_handle, &config);
3746 if (r == LIBUSB_SUCCESS) {
3748 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3749 r = LIBUSB_COMPLETED;
3752 case LIBUSB_REQUEST_SET_CONFIGURATION:
3753 if (setup->value == priv->active_config) {
3754 r = LIBUSB_COMPLETED;
3756 usbi_warn(ctx, "cannot set configuration other than the default one");
3757 r = LIBUSB_ERROR_INVALID_PARAM;
3760 case LIBUSB_REQUEST_GET_INTERFACE:
3762 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3763 r = LIBUSB_COMPLETED;
3765 case LIBUSB_REQUEST_SET_INTERFACE:
3766 r = hid_set_interface_altsetting(transfer->dev_handle, setup->index, setup->value);
3767 if (r == LIBUSB_SUCCESS) {
3768 r = LIBUSB_COMPLETED;
3772 usbi_warn(ctx, "unsupported HID control request");
3773 r = LIBUSB_ERROR_INVALID_PARAM;
3777 case LIBUSB_REQUEST_TYPE_CLASS:
3778 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3779 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3780 &size, wfd.overlapped);
3783 usbi_warn(ctx, "unsupported HID control request");
3784 r = LIBUSB_ERROR_INVALID_PARAM;
3788 if (r == LIBUSB_COMPLETED) {
3789 // Force request to be completed synchronously. Transferred size has been set by previous call
3790 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3791 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3792 // set InternalHigh to the number of bytes transferred
3793 wfd.overlapped->InternalHigh = (DWORD)size;
3797 if (r == LIBUSB_SUCCESS) {
3798 // Use priv_transfer to store data needed for async polling
3799 transfer_priv->pollable_fd = wfd;
3800 transfer_priv->interface_number = (uint8_t)current_interface;
3802 usbi_free_fd(wfd.fd);
3808 static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer) {
3809 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3810 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3811 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3812 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3813 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
3816 bool direction_in, ret;
3817 int current_interface, length;
3819 int r = LIBUSB_SUCCESS;
3821 CHECK_HID_AVAILABLE;
3823 transfer_priv->pollable_fd = INVALID_WINFD;
3824 transfer_priv->hid_dest = NULL;
3825 safe_free(transfer_priv->hid_buffer);
3827 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3828 if (current_interface < 0) {
3829 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3830 return LIBUSB_ERROR_NOT_FOUND;
3833 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3835 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3836 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3838 wfd = usbi_create_fd(hid_handle, direction_in?_O_RDONLY:_O_WRONLY);
3839 // Always use the handle returned from usbi_create_fd (wfd.handle)
3841 return LIBUSB_ERROR_NO_MEM;
3844 // If report IDs are not in use, an extra prefix byte must be added
3845 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
3846 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
3847 length = transfer->length+1;
3849 length = transfer->length;
3851 // Add a trailing byte to detect overflows on input
3852 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
3853 if (transfer_priv->hid_buffer == NULL) {
3854 return LIBUSB_ERROR_NO_MEM;
3856 transfer_priv->hid_expected_size = length;
3859 transfer_priv->hid_dest = transfer->buffer;
3860 usbi_dbg("reading %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3861 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
3863 if (!priv->hid->uses_report_ids[1]) {
3864 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
3866 // We could actually do without the calloc and memcpy in this case
3867 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3869 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3870 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3873 if (GetLastError() != ERROR_IO_PENDING) {
3874 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3875 usbi_free_fd(wfd.fd);
3876 safe_free(transfer_priv->hid_buffer);
3877 return LIBUSB_ERROR_IO;
3880 // Only write operations that completed synchronously need to free up
3881 // hid_buffer. For reads, copy_transfer_data() handles that process.
3882 if (!direction_in) {
3883 safe_free(transfer_priv->hid_buffer);
3886 usbi_err(ctx, "program assertion failed - no data was transferred");
3889 if (size > (size_t)length) {
3890 usbi_err(ctx, "OVERFLOW!");
3891 r = LIBUSB_ERROR_OVERFLOW;
3893 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3894 wfd.overlapped->InternalHigh = size;
3897 transfer_priv->pollable_fd = wfd;
3898 transfer_priv->interface_number = (uint8_t)current_interface;
3903 static int hid_abort_transfers(struct usbi_transfer *itransfer)
3905 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3906 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3907 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3909 int current_interface;
3911 CHECK_HID_AVAILABLE;
3913 current_interface = transfer_priv->interface_number;
3914 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3915 CancelIo(hid_handle);
3917 return LIBUSB_SUCCESS;
3920 static int hid_reset_device(struct libusb_device_handle *dev_handle)
3922 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3924 int current_interface;
3926 CHECK_HID_AVAILABLE;
3928 // Flushing the queues on all interfaces is the best we can achieve
3929 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3930 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3931 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
3932 HidD_FlushQueue(hid_handle);
3935 return LIBUSB_SUCCESS;
3938 static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
3940 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3941 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3942 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3944 int current_interface;
3946 CHECK_HID_AVAILABLE;
3948 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3949 if (current_interface < 0) {
3950 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3951 return LIBUSB_ERROR_NOT_FOUND;
3954 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3955 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3957 // No endpoint selection with Microsoft's implementation, so we try to flush the
3958 // whole interface. Should be OK for most case scenarios
3959 if (!HidD_FlushQueue(hid_handle)) {
3960 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3961 // Device was probably disconnected
3962 return LIBUSB_ERROR_NO_DEVICE;
3965 return LIBUSB_SUCCESS;
3968 // This extra function is only needed for HID
3969 static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
3970 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3971 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3972 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3973 int r = LIBUSB_TRANSFER_COMPLETED;
3974 uint32_t corrected_size = io_size;
3976 if (transfer_priv->hid_buffer != NULL) {
3977 // If we have a valid hid_buffer, it means the transfer was async
3978 if (transfer_priv->hid_dest != NULL) { // Data readout
3979 // First, check for overflow
3980 if (corrected_size > transfer_priv->hid_expected_size) {
3981 usbi_err(ctx, "OVERFLOW!");
3982 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
3983 r = LIBUSB_TRANSFER_OVERFLOW;
3986 if (transfer_priv->hid_buffer[0] == 0) {
3987 // Discard the 1 byte report ID prefix
3989 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
3991 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
3993 transfer_priv->hid_dest = NULL;
3995 // For write, we just need to free the hid buffer
3996 safe_free(transfer_priv->hid_buffer);
3998 itransfer->transferred += corrected_size;
4004 * Composite API functions
4006 static int composite_init(struct libusb_context *ctx)
4008 return LIBUSB_SUCCESS;
4011 static int composite_exit(void)
4013 return LIBUSB_SUCCESS;
4016 static int composite_open(struct libusb_device_handle *dev_handle)
4018 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4021 uint8_t flag = 1<<USB_API_WINUSB;
4023 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4024 if (priv->composite_api_flags & flag) {
4025 r = usb_api_backend[api].open(dev_handle);
4026 if (r != LIBUSB_SUCCESS) {
4032 return LIBUSB_SUCCESS;
4035 static void composite_close(struct libusb_device_handle *dev_handle)
4037 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4039 uint8_t flag = 1<<USB_API_WINUSB;
4041 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4042 if (priv->composite_api_flags & flag) {
4043 usb_api_backend[api].close(dev_handle);
4049 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
4051 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4052 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
4055 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
4057 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4058 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
4061 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
4063 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4064 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
4067 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
4069 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4070 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4071 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4074 // Interface shouldn't matter for control, but it does in practice, with Windows'
4075 // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4076 for (pass = 0; pass < 2; pass++) {
4077 for (i=0; i<USB_MAXINTERFACES; i++) {
4078 if (priv->usb_interface[i].path != NULL) {
4079 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4080 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4083 usbi_dbg("using interface %d", i);
4084 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
4089 usbi_err(ctx, "no libusb supported interfaces to complete request");
4090 return LIBUSB_ERROR_NOT_FOUND;
4093 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
4094 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4095 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4096 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
4097 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4098 int current_interface;
4100 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4101 if (current_interface < 0) {
4102 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4103 return LIBUSB_ERROR_NOT_FOUND;
4106 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
4109 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
4110 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4111 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4112 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
4113 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4114 int current_interface;
4116 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4117 if (current_interface < 0) {
4118 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4119 return LIBUSB_ERROR_NOT_FOUND;
4122 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
4125 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
4127 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4128 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
4129 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4130 int current_interface;
4132 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4133 if (current_interface < 0) {
4134 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4135 return LIBUSB_ERROR_NOT_FOUND;
4138 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
4141 static int composite_abort_control(struct usbi_transfer *itransfer)
4143 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4144 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4145 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4147 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
4150 static int composite_abort_transfers(struct usbi_transfer *itransfer)
4152 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4153 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4154 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4156 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
4159 static int composite_reset_device(struct libusb_device_handle *dev_handle)
4161 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4164 uint8_t flag = 1<<USB_API_WINUSB;
4166 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4167 if (priv->composite_api_flags & flag) {
4168 r = usb_api_backend[api].reset_device(dev_handle);
4169 if (r != LIBUSB_SUCCESS) {
4175 return LIBUSB_SUCCESS;
4178 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
4180 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4181 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4182 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4184 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);