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 for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
401 if (safe_strcmp(driver, usb_api_backend[api].driver_name_list[i]) == 0) {
409 * auto-claiming and auto-release helper functions
411 #if defined(AUTO_CLAIM)
412 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
414 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
415 struct windows_device_handle_priv *handle_priv = __device_handle_priv(
416 transfer->dev_handle);
417 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
418 int current_interface = *interface_number;
419 int r = LIBUSB_SUCCESS;
426 return LIBUSB_ERROR_INVALID_PARAM;
429 usbi_mutex_lock(&autoclaim_lock);
430 if (current_interface < 0) // No serviceable interface was found
432 for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
433 // Must claim an interface of the same API type
434 if ( (priv->usb_interface[current_interface].apib == &usb_api_backend[api_type])
435 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
436 usbi_dbg("auto-claimed interface %d for control request", current_interface);
437 if (handle_priv->autoclaim_count[current_interface] != 0) {
438 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
440 handle_priv->autoclaim_count[current_interface]++;
444 if (current_interface == USB_MAXINTERFACES) {
445 usbi_err(ctx, "could not auto-claim any interface");
446 r = LIBUSB_ERROR_NOT_FOUND;
449 // If we have a valid interface that was autoclaimed, we must increment
450 // its autoclaim count so that we can prevent an early release.
451 if (handle_priv->autoclaim_count[current_interface] != 0) {
452 handle_priv->autoclaim_count[current_interface]++;
455 usbi_mutex_unlock(&autoclaim_lock);
457 *interface_number = current_interface;
462 static void auto_release(struct usbi_transfer *itransfer)
464 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
465 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
466 libusb_device_handle *dev_handle = transfer->dev_handle;
467 struct windows_device_handle_priv* handle_priv = __device_handle_priv(dev_handle);
470 usbi_mutex_lock(&autoclaim_lock);
471 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
472 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
473 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
474 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
475 if (r == LIBUSB_SUCCESS) {
476 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
478 usbi_dbg("failed to auto-release interface %d (%s)",
479 transfer_priv->interface_number, libusb_strerror(r));
483 usbi_mutex_unlock(&autoclaim_lock);
489 * init: libusb backend init function
491 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
492 * In our implementation, we equate Windows' "HCD" to LibUSB's "bus". Note that bus is zero indexed.
493 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
495 static int windows_init(struct libusb_context *ctx)
498 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
501 int i, r = LIBUSB_ERROR_OTHER;
502 OSVERSIONINFO os_version;
504 struct windows_hcd_priv** _hcd_cur;
505 TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
507 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
508 semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
509 if (semaphore == NULL) {
510 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
511 return LIBUSB_ERROR_NO_MEM;
514 // A successful wait brings our semaphore count to 0 (unsignaled)
515 // => any concurent wait stalls until the semaphore's release
516 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
517 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
518 CloseHandle(semaphore);
519 return LIBUSB_ERROR_NO_MEM;
522 // NB: concurrent usage supposes that init calls are equally balanced with
523 // exit calls. If init is called more than exit, we will not exit properly
524 if ( ++concurrent_usage == 0 ) { // First init?
525 _hcd_cur = &hcd_root;
528 memset(&os_version, 0, sizeof(OSVERSIONINFO));
529 os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
530 windows_version = WINDOWS_UNSUPPORTED;
531 if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
532 if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
533 windows_version = WINDOWS_XP;
534 } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
535 windows_version = WINDOWS_2003; // also includes XP 64
536 } else if (os_version.dwMajorVersion >= 6) {
537 windows_version = WINDOWS_VISTA_AND_LATER;
540 if (windows_version == WINDOWS_UNSUPPORTED) {
541 usbi_err(ctx, "This version of Windows is NOT supported");
542 r = LIBUSB_ERROR_NOT_SUPPORTED;
546 #if defined(AUTO_CLAIM)
547 // We need a lock for proper auto-release
548 usbi_mutex_init(&autoclaim_lock, NULL);
551 // Initialize pollable file descriptors
554 // Load missing CFGMGR32.DLL imports
555 if (Cfgmgr32_init() != LIBUSB_SUCCESS) {
556 usbi_err(ctx, "could not resolve Cfgmgr32.dll functions");
557 return LIBUSB_ERROR_NOT_FOUND;
560 // Initialize the low level APIs (we don't care about errors at this stage)
561 for (i=0; i<USB_API_MAX; i++) {
562 usb_api_backend[i].init(ctx);
565 // Because QueryPerformanceCounter might report different values when
566 // running on different cores, we create a separate thread for the timer
567 // calls, which we glue to the first core always to prevent timing discrepancies.
568 r = LIBUSB_ERROR_NO_MEM;
569 for (i = 0; i < 2; i++) {
570 timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
571 if (timer_request[i] == NULL) {
572 usbi_err(ctx, "could not create timer request event %d - aborting", i);
576 timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
577 if (timer_response == NULL) {
578 usbi_err(ctx, "could not create timer response semaphore - aborting");
581 timer_mutex = CreateMutex(NULL, FALSE, NULL);
582 if (timer_mutex == NULL) {
583 usbi_err(ctx, "could not create timer mutex - aborting");
586 timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
587 if (timer_thread == NULL) {
588 usbi_err(ctx, "Unable to create timer thread - aborting");
591 SetThreadAffinityMask(timer_thread, 0);
593 guid = GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
596 for (bus = 0; ; bus++)
598 // safe loop: free up any (unprotected) dynamic resource
599 // NB: this is always executed before breaking the loop
600 safe_free(dev_interface_details);
601 safe_free(*_hcd_cur);
603 dev_interface_details = get_interface_details(ctx, &dev_info, NULL, guid, bus);
604 // safe loop: end of loop condition
605 if ((dev_interface_details == NULL) || (r != LIBUSB_SUCCESS))
608 // Will need to change storage and size of libusb_bus_t if this ever occurs
609 if (bus == LIBUSB_BUS_MAX) {
610 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", LIBUSB_BUS_MAX);
614 // Allocate and init a new priv structure to hold our data
615 if ((*_hcd_cur = malloc(sizeof(struct windows_hcd_priv))) == NULL) {
616 usbi_err(ctx, "could not allocate private structure for bus %u. aborting.", bus);
617 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
619 windows_hcd_priv_init(*_hcd_cur);
620 (*_hcd_cur)->path = sanitize_path(dev_interface_details->DevicePath);
622 _hcd_cur = &((*_hcd_cur)->next);
624 // TODO (2nd official release): thread for hotplug (see darwin source)
627 if (hcd_root == NULL)
628 r = LIBUSB_ERROR_NO_DEVICE;
632 init_exit: // Holds semaphore here.
633 if(!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
635 SetEvent(timer_request[1]); // actually the signal to quit the thread.
636 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
637 usbi_warn(ctx, "could not wait for timer thread to quit");
638 TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
639 // all objects it might have held anyway.
641 CloseHandle(timer_thread);
644 for (i = 0; i < 2; i++) {
645 if (timer_request[i]) {
646 CloseHandle(timer_request[i]);
647 timer_request[i] = NULL;
650 if (timer_response) {
651 CloseHandle(timer_response);
652 timer_response = NULL;
655 CloseHandle(timer_mutex);
660 if (r != LIBUSB_SUCCESS)
661 --concurrent_usage; // Not expected to call libusb_exit if we failed.
663 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
664 CloseHandle(semaphore);
669 * Initialize device structure, including active config
671 static int initialize_device(struct libusb_device *dev, libusb_bus_t busnum,
672 libusb_devaddr_t devaddr, char *path, int connection_index, uint8_t active_config,
673 struct libusb_device *parent_dev)
675 struct windows_device_priv *priv = __device_priv(dev);
677 windows_device_priv_init(priv);
679 dev->bus_number = busnum;
680 dev->device_address = devaddr;
682 priv->connection_index = connection_index;
683 priv->parent_dev = parent_dev;
685 priv->active_config = active_config;
687 if (priv->active_config != 0) {
688 usbi_dbg("active config: %d", priv->active_config);
690 // USB devices that don't have a config value are usually missing a driver
691 // TODO (after first official release): use this for automated driver installation
692 // NB: SetupDiGetDeviceRegistryProperty w/ SPDRP_INSTALL_STATE would tell us
693 // if the driver is properly installed, but driverless devices don't seem to
694 // be enumerable by SetupDi...
695 usbi_dbg("* This device has no driver => libusb will not be able to access it *");
698 return LIBUSB_SUCCESS;
702 * HCD (root) hubs need to have their device descriptor manually populated
704 * Note that we follow the Linux convention and use the "Linux Foundation root hub"
705 * vendor ID as well as the product ID to indicate the hub speed
707 static int force_hcd_device_descriptor(struct libusb_device *dev, HANDLE handle)
710 USB_HUB_CAPABILITIES hub_caps;
711 USB_HUB_CAPABILITIES_EX hub_caps_ex;
712 struct windows_device_priv *priv = __device_priv(dev);
713 struct libusb_context *ctx = DEVICE_CTX(dev);
715 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
716 priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
717 dev->num_configurations = priv->dev_descriptor.bNumConfigurations = 1;
719 // The following is used to set the VIS:PID of root HUBs similarly to what
720 // Linux does: 1d6b:0001 is for 1x root hubs, 1d6b:0002 for 2x
721 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
722 if (windows_version >= WINDOWS_VISTA_AND_LATER) {
723 size = sizeof(USB_HUB_CAPABILITIES_EX);
724 if (DeviceIoControl(handle, IOCTL_USB_GET_HUB_CAPABILITIES_EX, &hub_caps_ex,
725 size, &hub_caps_ex, size, &size, NULL)) {
726 // Sanity check. HCD hub should always be root
727 if (!hub_caps_ex.CapabilityFlags.HubIsRoot) {
728 usbi_warn(ctx, "program assertion failed - HCD hub is not reported as root hub.");
730 priv->dev_descriptor.idProduct = hub_caps_ex.CapabilityFlags.HubIsHighSpeedCapable?2:1;
733 size = sizeof(USB_HUB_CAPABILITIES);
734 if (!DeviceIoControl(handle, IOCTL_USB_GET_HUB_CAPABILITIES, &hub_caps,
735 size, &hub_caps, size, &size, NULL)) {
736 usbi_warn(ctx, "could not read hub capabilities (std) for hub %s: %s",
737 priv->path, windows_error_str(0));
738 priv->dev_descriptor.idProduct = 1; // Indicate 1x speed
740 priv->dev_descriptor.idProduct = hub_caps.HubIs2xCapable?2:1;
744 return LIBUSB_SUCCESS;
748 * fetch and cache all the config descriptors through I/O
750 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle)
752 DWORD size, ret_size;
753 struct libusb_context *ctx = DEVICE_CTX(dev);
754 struct windows_device_priv *priv = __device_priv(dev);
758 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
759 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
760 PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
762 if (dev->num_configurations == 0)
763 return LIBUSB_ERROR_INVALID_PARAM;
765 priv->config_descriptor = malloc(dev->num_configurations * sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
766 if (priv->config_descriptor == NULL)
767 return LIBUSB_ERROR_NO_MEM;
768 for (i=0; i<dev->num_configurations; i++)
769 priv->config_descriptor[i] = NULL;
771 for (i=0, r=LIBUSB_SUCCESS; ; i++)
773 // safe loop: release all dynamic resources
774 safe_free(cd_buf_actual);
776 // safe loop: end of loop condition
777 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
780 size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
781 memset(&cd_buf_short, 0, size);
783 cd_buf_short.req.ConnectionIndex = priv->connection_index;
784 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
785 cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
786 cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
787 cd_buf_short.req.SetupPacket.wIndex = i;
788 cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
790 // Dummy call to get the required data size
791 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
792 &cd_buf_short, size, &ret_size, NULL)) {
793 usbi_err(ctx, "could not access configuration descriptor (dummy): %s", windows_error_str(0));
794 LOOP_BREAK(LIBUSB_ERROR_IO);
797 if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
798 usbi_err(ctx, "unexpected configuration descriptor size (dummy).");
799 LOOP_BREAK(LIBUSB_ERROR_IO);
802 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
803 if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST)malloc(size)) == NULL) {
804 usbi_err(ctx, "could not allocate configuration descriptor buffer. aborting.");
805 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
807 memset(cd_buf_actual, 0, size);
810 cd_buf_actual->ConnectionIndex = priv->connection_index;
811 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
812 cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
813 cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
814 cd_buf_actual->SetupPacket.wIndex = i;
815 cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
817 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
818 cd_buf_actual, size, &ret_size, NULL)) {
819 usbi_err(ctx, "could not access configuration descriptor (actual): %s", windows_error_str(0));
820 LOOP_BREAK(LIBUSB_ERROR_IO);
823 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
825 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
826 usbi_err(ctx, "unexpected configuration descriptor size (actual).");
827 LOOP_BREAK(LIBUSB_ERROR_IO);
830 if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
831 usbi_err(ctx, "not a configuration descriptor");
832 LOOP_BREAK(LIBUSB_ERROR_IO);
835 usbi_dbg("cached config descriptor #%d (%d bytes)", i+1, cd_data->wTotalLength);
837 // Sanity check. Ensures that indexes for our list of config desc is in the right order
838 if (i != (cd_data->bConfigurationValue-1)) {
839 usbi_warn(ctx, "program assertion failed - config descriptors are being read out of order");
843 // Cache the descriptor
844 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
845 if (priv->config_descriptor[i] == NULL)
846 return LIBUSB_ERROR_NO_MEM;
848 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
850 return LIBUSB_SUCCESS;
854 * Recursively enumerates and finds all hubs & devices
856 static int usb_enumerate_hub(struct libusb_context *ctx, struct discovered_devs **_discdevs,
857 HANDLE hub_handle, libusb_bus_t busnum, struct libusb_device *parent_dev, uint8_t nb_ports)
859 struct discovered_devs *discdevs = *_discdevs;
860 struct libusb_device *dev = NULL;
861 DWORD size, size_initial, size_fixed, getname_ioctl;
862 HANDLE handle = INVALID_HANDLE_VALUE;
863 USB_HUB_NAME_FIXED s_hubname;
864 USB_NODE_CONNECTION_INFORMATION conn_info;
865 USB_NODE_INFORMATION hub_node;
866 bool is_hcd, need_unref = false;
869 char *tmp_str = NULL, *path_str = NULL;
870 unsigned long session_id;
871 libusb_devaddr_t devaddr = 0;
872 struct windows_device_priv *priv, *parent_priv;
874 // obviously, root (HCD) hubs have no parent
875 is_hcd = (parent_dev == NULL);
879 usbi_warn(ctx, "program assertion failed - invalid number of ports for HCD.");
880 return LIBUSB_ERROR_INVALID_PARAM;
883 size_initial = sizeof(USB_ROOT_HUB_NAME);
884 size_fixed = sizeof(USB_ROOT_HUB_NAME_FIXED);
885 getname_ioctl = IOCTL_USB_GET_ROOT_HUB_NAME;
889 parent_priv = __device_priv(parent_dev);
890 size_initial = sizeof(USB_NODE_CONNECTION_NAME);
891 size_fixed = sizeof(USB_NODE_CONNECTION_NAME_FIXED);
892 getname_ioctl = IOCTL_USB_GET_NODE_CONNECTION_NAME;
895 // Loop through all the ports on this hub
896 for (i = 1, r = LIBUSB_SUCCESS; ; i++)
898 // safe loop: release all dynamic resources
900 safe_unref_device(dev);
905 safe_closehandle(handle);
907 // safe loop: end of loop condition
908 if ((i > nb_ports) || (r != LIBUSB_SUCCESS))
911 memset(&conn_info, 0, sizeof(conn_info));
912 // For non HCDs, check if the node on this port is a hub or a regular device
914 size = sizeof(USB_NODE_CONNECTION_INFORMATION);
915 conn_info.ConnectionIndex = i;
916 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, &conn_info, size,
917 &conn_info, size, &size, NULL)) {
918 usbi_warn(ctx, "could not get node connection information: %s", windows_error_str(0));
922 if (conn_info.ConnectionStatus == NoDeviceConnected) {
926 if (conn_info.DeviceAddress == LIBUSB_DEVADDR_MAX) {
927 usbi_warn(ctx, "program assertion failed - device address is %d "
928 "(conflicts with root hub), ignoring device", LIBUSB_DEVADDR_MAX);
932 s_hubname.u.node.ConnectionIndex = i; // Only used for non HCDs (s_hubname is an union)
936 // HCDs have only 1 node, and it's always a hub
937 conn_info.DeviceAddress = LIBUSB_DEVADDR_MAX; // using 0 can conflict with driverless devices
938 conn_info.DeviceIsHub = true;
939 conn_info.CurrentConfigurationValue = 1;
942 // If this node is a hub (HCD or not), open it
943 if (conn_info.DeviceIsHub) {
945 if (!DeviceIoControl(hub_handle, getname_ioctl, &s_hubname, size,
946 &s_hubname, size, &size, NULL)) {
947 usbi_warn(ctx, "could not get hub path (dummy): %s", windows_error_str(0));
951 size = is_hcd?s_hubname.u.root.ActualLength:s_hubname.u.node.ActualLength;
952 if (size > size_fixed) {
953 usbi_warn(ctx, "program assertion failed - hub path is too long");
958 // previous call trashes some of the data
959 s_hubname.u.node.ConnectionIndex = i;
961 if (!DeviceIoControl(hub_handle, getname_ioctl, &s_hubname, size,
962 &s_hubname, size, &size, NULL)) {
963 usbi_warn(ctx, "could not get hub path (actual): %s", windows_error_str(0));
968 wstr = is_hcd?s_hubname.u.root.RootHubName:s_hubname.u.node.NodeName;
969 tmp_str = wchar_to_utf8(wstr);
970 if (tmp_str == NULL) {
971 usbi_err(ctx, "could not convert hub path string.");
972 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
975 path_str = sanitize_path(tmp_str);
976 if (path_str == NULL) {
977 usbi_err(ctx, "could not sanitize hub path string.");
978 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
982 handle = CreateFileA(path_str, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
983 FILE_FLAG_OVERLAPPED, NULL);
984 if(handle == INVALID_HANDLE_VALUE) {
985 usbi_warn(ctx, "could not open hub %s: %s", path_str, windows_error_str(0));
990 // Generate a session ID
991 // Will need to change the session_id computation if this assertion fails
992 if (conn_info.DeviceAddress > LIBUSB_DEVADDR_MAX) {
993 usbi_warn(ctx, "program assertion failed - device address is greater than %d, ignoring device",
997 devaddr = (uint8_t)conn_info.DeviceAddress;
999 // Same trick as linux for session_id, with same caveat
1000 session_id = busnum << (sizeof(libusb_devaddr_t)*8) | devaddr;
1001 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr, session_id);
1003 // Allocate device if needed
1004 dev = usbi_get_device_by_session_id(ctx, session_id);
1006 usbi_dbg("using existing device for session %ld", session_id);
1007 priv = __device_priv(dev);
1008 // Because we are rebuilding the list, there's no guarantee
1009 // the parent device pointer is still the same.
1010 // Other device data should still be reusable
1011 priv->parent_dev = parent_dev;
1013 usbi_dbg("allocating new device for session %ld", session_id);
1014 if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
1015 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1019 LOOP_CHECK(initialize_device(dev, busnum, devaddr, path_str, i,
1020 conn_info.CurrentConfigurationValue, parent_dev));
1021 priv = __device_priv(dev);
1023 path_str = NULL; // protect our path from being freed
1025 // Setup the cached descriptors. Note that only non HCDs can fetch descriptors
1027 // The device descriptor has been read with conn_info
1028 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1029 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1030 // If we can't read the config descriptors, just set the number of confs to zero
1031 if (cache_config_descriptors(dev, hub_handle) != LIBUSB_SUCCESS) {
1032 dev->num_configurations = 0;
1033 priv->dev_descriptor.bNumConfigurations = 0;
1036 LOOP_CHECK(force_hcd_device_descriptor(dev, handle));
1038 LOOP_CHECK(usbi_sanitize_device(dev));
1041 discdevs = discovered_devs_append(*_discdevs, dev);
1043 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1046 *_discdevs = discdevs;
1048 // Finally, if device is a hub, recurse
1049 if (conn_info.DeviceIsHub) {
1050 // Find number of ports for this hub
1051 size = sizeof(USB_NODE_INFORMATION);
1052 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_INFORMATION, &hub_node, size,
1053 &hub_node, size, &size, NULL)) {
1054 usbi_warn(ctx, "could not retreive information for hub %s: %s",
1055 priv->path, windows_error_str(0));
1059 if (hub_node.NodeType != UsbHub) {
1060 usbi_warn(ctx, "unexpected hub type (%d) for hub %s", hub_node.NodeType, priv->path);
1064 usbi_dbg("%d ports Hub: %s", hub_node.u.HubInformation.HubDescriptor.bNumberOfPorts, priv->path);
1066 usb_enumerate_hub(ctx, _discdevs, handle, busnum, dev,
1067 hub_node.u.HubInformation.HubDescriptor.bNumberOfPorts);
1075 * Composite device interfaces are not enumerated using GUID_DEVINTERFACE_USB_DEVICE,
1076 * but instead require a different lookup mechanism
1078 static int set_composite_device(struct libusb_context *ctx, DEVINST devinst, struct windows_device_priv *priv)
1080 // indexes for additional interface GUIDs, not available from "USB"
1081 // SetupDiGetClassDevs enumeration should go here. Typically, these are
1082 // device interfaces that begin with something else than "\\?\usb\"
1083 enum libusb_hid_report_type {
1084 HID_DEVICE_INTERFACE_GUID_INDEX = 0,
1085 MAX_DEVICE_INTERFACE_GUID_INDEX = 1
1088 DEVINST child_devinst, parent_devinst;
1089 unsigned i, j, max_guids, nb_paths, interface_number;
1095 SP_DEVINFO_DATA dev_info_data;
1096 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1098 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1099 GUID guid, class_guid;
1100 GUID guid_table[MAX_USB_DEVICES];
1101 char* sanitized_path[MAX_USB_DEVICES];
1102 char* hid_path[MAX_USB_DEVICES]; // An extra path is needed for HID
1103 uint8_t api_type[MAX_USB_DEVICES];
1104 char* sanitized_short = NULL;
1105 char path[MAX_PATH_LENGTH];
1106 char driver[MAX_KEY_LENGTH];
1108 dev_info = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
1109 if (dev_info == INVALID_HANDLE_VALUE) {
1110 return LIBUSB_ERROR_NOT_FOUND;
1113 // Manually add the HID GUID as it cannot be read with DeviceInterfaceGUIDs reg key)
1114 // NB the value returned by HidD_GetHidGuid, which is for interface class is different
1115 // from GUID_HID, which is the device class GUID
1116 HidD_GetHidGuid(&guid_table[HID_DEVICE_INTERFACE_GUID_INDEX]);
1117 // NB: for other interface guids, SetupDiClassGuidsFromName can be used
1118 max_guids = MAX_DEVICE_INTERFACE_GUID_INDEX;
1120 // First, retrieve all the device interface GUIDs
1123 dev_info_data.cbSize = sizeof(dev_info_data);
1124 if (!SetupDiEnumDeviceInfo(dev_info, i, &dev_info_data)) {
1128 key = SetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1129 if (key == INVALID_HANDLE_VALUE) {
1130 usbi_dbg("could not open registry key");
1134 size = sizeof(guid_string_w);
1135 r = RegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &type,
1136 (BYTE*)guid_string_w, &size);
1138 if (r != ERROR_SUCCESS) {
1141 CLSIDFromString(guid_string_w, &guid);
1143 // identical device interface GUIDs are not supposed to happen, but are a real possibility
1144 // => check and ignore duplicates
1146 for (j=0; j<max_guids; j++) {
1147 if (memcmp(&guid_table[j], &guid, sizeof(GUID)) == 0) {
1153 guid_table[max_guids++] = guid;
1154 if (max_guids > MAX_USB_DEVICES) {
1155 usbi_warn(ctx, "more than %d devices - ignoring the rest", MAX_USB_DEVICES);
1160 SetupDiDestroyDeviceInfoList(dev_info);
1162 // Now let's find the device interface paths for all these devices
1164 for (j=0; j<max_guids; j++)
1166 guid = guid_table[j];
1170 safe_free(dev_interface_details);
1171 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1172 if (dev_interface_details == NULL)
1175 // HID devices (and possibly other classes) have an extra indirection
1176 // for an USB path we can recognize
1177 if (j == HID_DEVICE_INTERFACE_GUID_INDEX) {
1178 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1179 usbi_warn(ctx, "could not retrieve HID parent info data for device %s, skipping: %s",
1180 dev_interface_details->DevicePath, windows_error_str(0));
1184 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1185 usbi_warn(ctx, "could not retrieve HID parent's path for device %s, skipping: %s",
1186 dev_interface_details->DevicePath, windows_error_str(0));
1191 // In case we can't read the driver string through SPDRP_SERVICE (which is
1192 // the case for HID), we need the ClassGUID for comparison.
1193 if(!SetupDiGetDeviceRegistryPropertyW(dev_info, &dev_info_data, SPDRP_CLASSGUID,
1194 NULL, (BYTE*)guid_string_w, sizeof(guid_string_w), &size)) {
1195 usbi_warn(ctx, "could not read class GUID for device %s, skipping: %s",
1196 dev_interface_details->DevicePath, windows_error_str(0));
1199 CLSIDFromString(guid_string_w, &class_guid);
1201 // Attempt to read the driver string
1202 if(!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_SERVICE,
1203 NULL, (BYTE*)driver, MAX_KEY_LENGTH, &size)) {
1207 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
1208 if ( (is_api_driver(driver, api))
1209 || (guid_eq(&class_guid, usb_api_backend[api].class_guid)) ) {
1210 api_type[nb_paths] = api;
1211 if (j == HID_DEVICE_INTERFACE_GUID_INDEX) {
1212 hid_path[nb_paths] = sanitize_path(path);
1214 hid_path[nb_paths] = NULL;
1216 sanitized_path[nb_paths++] = sanitize_path(dev_interface_details->DevicePath);
1217 if (nb_paths > MAX_USB_DEVICES) {
1218 usbi_warn(ctx, "more than %d devices - ignoring the rest", MAX_USB_DEVICES);
1226 // Finally, match the interface paths with the interfaces. We do that
1227 // by looking at the children of the composite device
1228 // NB: if the interfaces are not found in their expected position,
1229 // claim_interface will issue a warning
1231 memset(&child_devinst, 0, sizeof(DEVINST)); // prevents /W4 warning
1232 for (i = 0; i<USB_MAXINTERFACES; i++)
1235 r = CM_Get_Child(&child_devinst, devinst, 0);
1237 r = CM_Get_Sibling(&child_devinst, child_devinst, 0);
1239 if (r == CR_NO_SUCH_DEVNODE) { // end of the siblings
1241 } else if (r != CR_SUCCESS) {
1242 usbi_dbg("unable to find interface sibling #%d, error = %X", i, r);
1246 r = CM_Get_Device_ID(child_devinst, path, MAX_PATH_LENGTH, 0);
1247 if (r != CR_SUCCESS) {
1248 usbi_err(ctx, "could not retrieve simple path for interface %d: CR error %d",
1252 sanitized_short = sanitize_path(path);
1253 if (sanitized_short == NULL) {
1254 usbi_err(ctx, "could not sanitize path for interface %d", i);
1258 // Because MI_## are not necessarily in sequential order (some composite HID
1259 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1260 // interface number from the path's MI value
1261 interface_number = i;
1262 for (j=0; sanitized_short[j] != 0; ) {
1263 if ( (sanitized_short[j++] == 'M') && (sanitized_short[j++] == 'I')
1264 && (sanitized_short[j++] == '_') ) {
1265 interface_number = (sanitized_short[j++] - '0')*10;
1266 interface_number += sanitized_short[j] - '0';
1270 if (sanitized_short[j] == 0) {
1271 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1272 sanitized_short, interface_number);
1275 for (j=0; j<nb_paths; j++) {
1276 if ( (safe_strncmp(sanitized_path[j], sanitized_short, safe_strlen(sanitized_short)) == 0)
1277 || (safe_strcmp(hid_path[j], sanitized_short) == 0 ) ) {
1278 // HID devices can have multiple collections (COL##) for each MI_## interface
1279 if (priv->usb_interface[interface_number].path != NULL) {
1280 usbi_dbg("interface_path[%d] already set - ignoring HID collection: %s",
1281 interface_number, sanitized_path[j]);
1282 if (api_type[j] != USB_API_HID) {
1283 usbi_warn(ctx, "program assertion failed - not an HID collection");
1286 priv->usb_interface[interface_number].path = sanitized_path[j];
1287 priv->usb_interface[interface_number].apib = &usb_api_backend[api_type[j]];
1288 if ((api_type[j] == USB_API_HID) && (priv->hid == NULL)) {
1289 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1291 priv->composite_api_flags |= 1<<api_type[j];
1292 sanitized_path[j] = NULL;
1296 safe_free(sanitized_short);
1298 if (priv->usb_interface[interface_number].path == NULL) {
1299 usbi_warn(ctx, "interface_path[%d]: unhandled API - interface will be disabled",
1303 usbi_dbg("interface_path[%d]: %s", interface_number, priv->usb_interface[interface_number].path);
1307 for (j=0; j<nb_paths; j++) {
1308 safe_free(sanitized_path[j]);
1309 safe_free(hid_path[j]);
1313 usbi_warn(ctx, "composite device: no interfaces were found");
1314 return LIBUSB_ERROR_NOT_FOUND;
1317 return LIBUSB_SUCCESS;
1321 * Likewise, HID device interfaces's path (\\.\HID\...) are not enumerated through the
1322 * generic USB devices GUID, but are actually children of one such device
1324 static int set_hid_device(struct libusb_context *ctx, struct windows_device_priv *priv)
1326 char path[MAX_PATH_LENGTH];
1327 char *sanitized_path = NULL;
1329 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1330 SP_DEVINFO_DATA dev_info_data;
1331 DEVINST parent_devinst;
1333 int r = LIBUSB_SUCCESS;
1334 unsigned i, interface_number;
1336 interface_number = 0;
1337 HidD_GetHidGuid(&guid);
1340 // safe loop: free up any (unprotected) dynamic resource
1341 safe_free(dev_interface_details);
1342 safe_free(sanitized_path);
1344 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1345 // safe loop: end of loop condition
1346 if ( (dev_interface_details == NULL)
1347 || (r != LIBUSB_SUCCESS) )
1350 // Retrieve parent's path using PnP Configuration Manager (CM)
1351 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1352 usbi_warn(ctx, "could not retrieve parent info data for device %s, skipping: %s",
1353 dev_interface_details->DevicePath, windows_error_str(0));
1357 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1358 usbi_warn(ctx, "could not retrieve parent's path for device %s, skipping: %s",
1359 dev_interface_details->DevicePath, windows_error_str(0));
1363 // Fix parent's path inconsistencies before attempting to compare
1364 sanitized_path = sanitize_path(path);
1365 if (sanitized_path == NULL) {
1366 usbi_warn(ctx, "could not sanitize parent's path for device %s, skipping.",
1367 dev_interface_details->DevicePath);
1371 // NB: we compare strings of different lengths below => strncmp
1372 if (safe_strncmp(priv->path, sanitized_path, safe_strlen(sanitized_path)) == 0) {
1373 priv->usb_interface[interface_number].path = sanitize_path(dev_interface_details->DevicePath);
1374 priv->usb_interface[interface_number].apib = &usb_api_backend[USB_API_HID];
1375 usbi_dbg("interface_path[%d]: %s", interface_number, priv->usb_interface[interface_number].path);
1380 return LIBUSB_SUCCESS;
1384 * This function retrieves and sets the paths of all non-hub devices
1385 * NB: No I/O with device is required during this call
1387 static int set_device_paths(struct libusb_context *ctx, struct discovered_devs *discdevs)
1389 struct windows_device_priv *priv;
1390 struct windows_device_priv *parent_priv;
1391 char path[MAX_PATH_LENGTH];
1392 char reg_key[MAX_KEY_LENGTH];
1393 char *sanitized_path = NULL;
1395 SP_DEVICE_INTERFACE_DETAIL_DATA *dev_interface_details = NULL;
1396 SP_DEVINFO_DATA dev_info_data;
1397 DEVINST parent_devinst;
1399 DWORD size, reg_type, install_state, port_nr;
1400 int r = LIBUSB_SUCCESS;
1405 // TODO (after first official release): MI_## automated driver installation
1406 guid = GUID_DEVINTERFACE_USB_DEVICE;
1409 // safe loop: free up any (unprotected) dynamic resource
1410 safe_free(dev_interface_details);
1411 safe_free(sanitized_path);
1413 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid, i);
1414 // safe loop: end of loop condition
1415 if ( (dev_interface_details == NULL)
1416 || (r != LIBUSB_SUCCESS) )
1419 // Check that the driver installation is OK
1420 if ( (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1421 ®_type, (BYTE*)&install_state, 4, &size))
1423 usbi_warn(ctx, "could not detect installation state of driver for %s: %s",
1424 dev_interface_details->DevicePath, windows_error_str(0));
1425 } else if (install_state != 0) {
1426 usbi_warn(ctx, "driver for device %s is reporting an issue (code: %d) - skipping",
1427 dev_interface_details->DevicePath, install_state);
1431 // The SPDRP_ADDRESS for USB devices should be the device port number on the hub
1432 if ( (!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_ADDRESS,
1433 ®_type, (BYTE*)&port_nr, 4, &size))
1435 usbi_warn(ctx, "could not retrieve port number for device %s, skipping: %s",
1436 dev_interface_details->DevicePath, windows_error_str(0));
1440 // Retrieve parent's path using PnP Configuration Manager (CM)
1441 if (CM_Get_Parent(&parent_devinst, dev_info_data.DevInst, 0) != CR_SUCCESS) {
1442 usbi_warn(ctx, "could not retrieve parent info data for device %s, skipping: %s",
1443 dev_interface_details->DevicePath, windows_error_str(0));
1447 if (CM_Get_Device_ID(parent_devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
1448 usbi_warn(ctx, "could not retrieve parent's path for device %s, skipping: %s",
1449 dev_interface_details->DevicePath, windows_error_str(0));
1453 // Fix parent's path inconsistencies before attempting to compare
1454 sanitized_path = sanitize_path(path);
1455 if (sanitized_path == NULL) {
1456 usbi_warn(ctx, "could not sanitize parent's path for device %s, skipping.",
1457 dev_interface_details->DevicePath);
1461 // With the parent path and port number, we should be able to locate our device
1462 // by comparing these values to the ones we got when enumerating hubs
1464 for (j=0; j<discdevs->len; j++) {
1465 priv = __device_priv(discdevs->devices[j]);
1467 if (priv->parent_dev == NULL) {
1468 continue; // ignore HCDs
1471 parent_priv = __device_priv(priv->parent_dev);
1473 // NB: we compare strings of different lengths below => strncmp
1474 if ( (safe_strncmp(parent_priv->path, sanitized_path, safe_strlen(sanitized_path)) == 0)
1475 && (port_nr == priv->connection_index) ) {
1477 priv->path = sanitize_path(dev_interface_details->DevicePath);
1479 usbi_dbg("path (%d:%d): %s", discdevs->devices[j]->bus_number,
1480 discdevs->devices[j]->device_address, priv->path);
1482 // Check the service name to know what kind of device we have.
1483 // The service name is really the driver name without ".sys" ("WinUSB", "HidUsb", ...)
1484 // It tells us if we can use WinUSB, if we have a composite device, and the API to use
1485 if(!SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data, SPDRP_SERVICE,
1486 ®_type, (BYTE*)reg_key, MAX_KEY_LENGTH, &size)) {
1487 usbi_err(ctx, "could not retrieve driver information for device %s, skipping: %s",
1488 dev_interface_details->DevicePath, windows_error_str(0));
1492 usbi_dbg("driver: %s", reg_key);
1495 for (api = 0; api<USB_API_MAX; api++) {
1496 if (is_api_driver(reg_key, api)) {
1497 priv->apib = &usb_api_backend[api];
1499 case USB_API_COMPOSITE:
1500 set_composite_device(ctx, dev_info_data.DevInst, priv);
1503 safe_free(priv->hid);
1504 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1505 if (priv->hid == NULL) {
1506 usbi_err(ctx, "could not allocate HID data for %s, skipping",
1507 dev_interface_details->DevicePath);
1508 priv->apib = &usb_api_backend[USB_API_UNSUPPORTED];
1509 safe_free(priv->path);
1511 set_hid_device(ctx, priv);
1515 // For other devices, the first interface is the same as the device
1516 priv->usb_interface[0].path = malloc(safe_strlen(priv->path)+1);
1517 if (priv->usb_interface[0].path != NULL) {
1518 safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
1520 // The following is needed if we want to API calls to work for both simple
1521 // and composite devices, as
1522 for(k=0; k<USB_MAXINTERFACES; k++) {
1523 priv->usb_interface[k].apib = &usb_api_backend[api];
1533 usbi_warn(ctx, "could not match %s with a libusb device.", dev_interface_details->DevicePath);
1538 return LIBUSB_SUCCESS;
1542 * get_device_list: libusb backend device enumeration function
1544 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1546 struct windows_hcd_priv* hcd;
1547 HANDLE handle = INVALID_HANDLE_VALUE;
1548 int r = LIBUSB_SUCCESS;
1551 // Use the index of the HCD in the chained list as bus #
1552 for (hcd = hcd_root, bus = 0; ; hcd = hcd->next, bus++)
1554 safe_closehandle(handle);
1556 if ( (hcd == NULL) || (r != LIBUSB_SUCCESS) )
1559 if (bus == LIBUSB_BUS_MAX) {
1560 usbi_warn(ctx, "program assertion failed - got more than %d buses, skipping the rest.", LIBUSB_BUS_MAX);
1564 handle = CreateFileA(hcd->path, GENERIC_WRITE, FILE_SHARE_WRITE,
1565 NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
1566 if (handle == INVALID_HANDLE_VALUE) {
1567 usbi_warn(ctx, "could not open bus %u, skipping: %s", bus, windows_error_str(0));
1571 LOOP_CHECK(usb_enumerate_hub(ctx, _discdevs, handle, bus, NULL, 1));
1574 // Set the interface path for non-hubs
1575 r = set_device_paths(ctx, *_discdevs);
1581 * exit: libusb backend deinitialization function
1583 static void windows_exit(void)
1585 struct windows_hcd_priv* hcd_tmp;
1588 TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
1590 sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
1591 semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
1592 if (semaphore == NULL) {
1596 // A successful wait brings our semaphore count to 0 (unsignaled)
1597 // => any concurent wait stalls until the semaphore release
1598 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1599 CloseHandle(semaphore);
1603 // Only works if exits and inits are balanced exactly
1604 if (--concurrent_usage < 0) { // Last exit
1605 while (hcd_root != NULL)
1607 hcd_tmp = hcd_root; // Keep a copy for free
1608 hcd_root = hcd_root->next;
1609 windows_hcd_priv_release(hcd_tmp);
1613 for (i=0; i<USB_API_MAX; i++) {
1614 usb_api_backend[i].exit();
1619 SetEvent(timer_request[1]); // actually the signal to quit the thread.
1620 if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
1621 usbi_dbg("could not wait for timer thread to quit");
1622 TerminateThread(timer_thread, 1);
1624 CloseHandle(timer_thread);
1625 timer_thread = NULL;
1627 for (i = 0; i < 2; i++) {
1628 if (timer_request[i]) {
1629 CloseHandle(timer_request[i]);
1630 timer_request[i] = NULL;
1633 if (timer_response) {
1634 CloseHandle(timer_response);
1635 timer_response = NULL;
1638 CloseHandle(timer_mutex);
1643 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1644 CloseHandle(semaphore);
1647 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1649 struct windows_device_priv *priv = __device_priv(dev);
1651 memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
1654 return LIBUSB_SUCCESS;
1657 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1659 struct windows_device_priv *priv = __device_priv(dev);
1660 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1663 // config index is zero based
1664 if (config_index >= dev->num_configurations)
1665 return LIBUSB_ERROR_INVALID_PARAM;
1667 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1668 return LIBUSB_ERROR_NOT_FOUND;
1670 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1672 size = min(config_header->wTotalLength, len);
1673 memcpy(buffer, priv->config_descriptor[config_index], size);
1675 return LIBUSB_SUCCESS;
1679 * return the cached copy of the active config descriptor
1681 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1683 struct windows_device_priv *priv = __device_priv(dev);
1685 if (priv->active_config == 0)
1686 return LIBUSB_ERROR_NOT_FOUND;
1688 // config index is zero based
1689 return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
1692 static int windows_open(struct libusb_device_handle *dev_handle)
1694 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1695 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1697 if (priv->apib == NULL) {
1698 usbi_err(ctx, "program assertion failed - device is not initialized");
1699 return LIBUSB_ERROR_NO_DEVICE;
1702 return priv->apib->open(dev_handle);
1705 static void windows_close(struct libusb_device_handle *dev_handle)
1707 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1709 priv->apib->close(dev_handle);
1712 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1714 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1716 if (priv->active_config == 0) {
1718 return LIBUSB_ERROR_NOT_FOUND;
1721 *config = priv->active_config;
1722 return LIBUSB_SUCCESS;
1726 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1727 * does not currently expose a service that allows higher-level drivers to set
1728 * the configuration."
1730 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1732 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1733 int r = LIBUSB_SUCCESS;
1735 if (config >= USB_MAXCONFIG)
1736 return LIBUSB_ERROR_INVALID_PARAM;
1738 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1739 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1740 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1743 if (r == LIBUSB_SUCCESS) {
1744 priv->active_config = (uint8_t)config;
1749 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1751 int r = LIBUSB_SUCCESS;
1752 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1754 if (iface >= USB_MAXINTERFACES)
1755 return LIBUSB_ERROR_INVALID_PARAM;
1757 safe_free(priv->usb_interface[iface].endpoint);
1758 priv->usb_interface[iface].nb_endpoints= 0;
1760 r = priv->apib->claim_interface(dev_handle, iface);
1762 if (r == LIBUSB_SUCCESS) {
1763 r = windows_assign_endpoints(dev_handle->dev, iface, 0);
1769 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1771 int r = LIBUSB_SUCCESS;
1772 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1774 safe_free(priv->usb_interface[iface].endpoint);
1775 priv->usb_interface[iface].nb_endpoints= 0;
1777 r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
1779 if (r == LIBUSB_SUCCESS) {
1780 r = windows_assign_endpoints(dev_handle->dev, iface, altsetting);
1786 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1788 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1790 windows_set_interface_altsetting(dev_handle, iface, 0);
1791 return priv->apib->release_interface(dev_handle, iface);
1794 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1796 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1797 return priv->apib->clear_halt(dev_handle, endpoint);
1800 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1802 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
1803 return priv->apib->reset_device(dev_handle);
1806 // The 3 functions below are unlikely to ever get supported on Windows
1807 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1809 return LIBUSB_ERROR_NOT_SUPPORTED;
1812 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1814 return LIBUSB_ERROR_NOT_SUPPORTED;
1817 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1819 return LIBUSB_ERROR_NOT_SUPPORTED;
1822 static void windows_destroy_device(struct libusb_device *dev)
1824 struct windows_device_priv *priv = __device_priv(dev);
1825 windows_device_priv_release(priv, dev->num_configurations);
1828 static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1830 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1832 usbi_free_fd(transfer_priv->pollable_fd.fd);
1833 safe_free(transfer_priv->hid_buffer);
1834 #if defined(AUTO_CLAIM)
1835 // When auto claim is in use, attempt to release the auto-claimed interface
1836 auto_release(itransfer);
1840 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1842 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1843 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1844 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1845 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1848 r = priv->apib->submit_bulk_transfer(itransfer);
1849 if (r != LIBUSB_SUCCESS) {
1853 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1854 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1855 #if !defined(DYNAMIC_FDS)
1856 usbi_fd_notification(ctx);
1859 return LIBUSB_SUCCESS;
1862 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1864 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1865 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1866 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1867 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1870 r = priv->apib->submit_iso_transfer(itransfer);
1871 if (r != LIBUSB_SUCCESS) {
1875 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1876 (short)((transfer->endpoint & LIBUSB_ENDPOINT_IN)?POLLIN:POLLOUT));
1877 #if !defined(DYNAMIC_FDS)
1878 usbi_fd_notification(ctx);
1881 return LIBUSB_SUCCESS;
1884 static int submit_control_transfer(struct usbi_transfer *itransfer)
1886 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1887 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1888 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1889 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1892 r = priv->apib->submit_control_transfer(itransfer);
1893 if (r != LIBUSB_SUCCESS) {
1897 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1898 #if !defined(DYNAMIC_FDS)
1899 usbi_fd_notification(ctx);
1902 return LIBUSB_SUCCESS;
1906 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1908 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1910 switch (transfer->type) {
1911 case LIBUSB_TRANSFER_TYPE_CONTROL:
1912 return submit_control_transfer(itransfer);
1913 case LIBUSB_TRANSFER_TYPE_BULK:
1914 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1915 return submit_bulk_transfer(itransfer);
1916 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1917 return submit_iso_transfer(itransfer);
1919 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1920 return LIBUSB_ERROR_INVALID_PARAM;
1924 static int windows_abort_control(struct usbi_transfer *itransfer)
1926 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1927 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1929 return priv->apib->abort_control(itransfer);
1932 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1934 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1935 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1937 return priv->apib->abort_transfers(itransfer);
1940 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
1942 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1943 #if defined(FORCE_INSTANT_TIMEOUTS)
1944 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1946 // Forces instant overlapped completion on timeouts - use at your own risks
1947 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1948 transfer_priv->pollable_fd.overlapped->Internal &= ~STATUS_PENDING;
1951 switch (transfer->type) {
1952 case LIBUSB_TRANSFER_TYPE_CONTROL:
1953 return windows_abort_control(itransfer);
1954 case LIBUSB_TRANSFER_TYPE_BULK:
1955 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1956 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1957 return windows_abort_transfers(itransfer);
1959 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
1960 return LIBUSB_ERROR_INVALID_PARAM;
1964 static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
1966 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1967 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
1970 usbi_dbg("handling I/O completion with errcode %d", io_result);
1974 status = priv->apib->copy_transfer_data(itransfer, io_size);
1976 case ERROR_GEN_FAILURE:
1977 usbi_dbg("detected endpoint stall");
1978 status = LIBUSB_TRANSFER_STALL;
1980 case ERROR_SEM_TIMEOUT:
1981 usbi_dbg("detected semaphore timeout");
1982 status = LIBUSB_TRANSFER_TIMED_OUT;
1984 case ERROR_OPERATION_ABORTED:
1985 if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
1986 usbi_dbg("detected timeout");
1987 status = LIBUSB_TRANSFER_TIMED_OUT;
1989 usbi_dbg("detected operation aborted");
1990 status = LIBUSB_TRANSFER_CANCELLED;
1994 usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
1995 status = LIBUSB_TRANSFER_ERROR;
1998 windows_clear_transfer_priv(itransfer); // Cancel polling
1999 usbi_handle_transfer_completion(itransfer, status);
2002 static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
2004 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2006 switch (transfer->type) {
2007 case LIBUSB_TRANSFER_TYPE_CONTROL:
2008 case LIBUSB_TRANSFER_TYPE_BULK:
2009 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2010 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2011 windows_transfer_callback (itransfer, io_result, io_size);
2014 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2018 static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, nfds_t nfds, int num_ready)
2020 struct windows_transfer_priv* transfer_priv = NULL;
2023 struct usbi_transfer *transfer;
2024 DWORD io_size, io_result;
2026 usbi_mutex_lock(&ctx->open_devs_lock);
2027 for (i = 0; i < nfds && num_ready > 0; i++) {
2029 usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
2031 if (!fds[i].revents) {
2037 // Because a Windows OVERLAPPED is used for poll emulation,
2038 // a pollable fd is created and stored with each transfer
2039 usbi_mutex_lock(&ctx->flying_transfers_lock);
2040 list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
2041 transfer_priv = usbi_transfer_get_os_priv(transfer);
2042 if (transfer_priv->pollable_fd.fd == fds[i].fd) {
2047 usbi_mutex_unlock(&ctx->flying_transfers_lock);
2050 // Handle async requests that completed synchronously first
2051 if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
2052 io_result = NO_ERROR;
2053 io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
2054 // Regular async overlapped
2055 } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
2056 transfer_priv->pollable_fd.overlapped, &io_size, false)) {
2057 io_result = NO_ERROR;
2059 io_result = GetLastError();
2061 usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
2062 // let handle_callback free the event using the transfer wfd
2063 // If you don't use the transfer wfd, you run a risk of trying to free a
2064 // newly allocated wfd that took the place of the one from the transfer.
2065 windows_handle_callback(transfer, io_result, io_size);
2067 usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
2068 return LIBUSB_ERROR_NOT_FOUND;
2072 usbi_mutex_unlock(&ctx->open_devs_lock);
2073 return LIBUSB_SUCCESS;
2077 * Monotonic and real time functions
2079 unsigned __stdcall windows_clock_gettime_threaded(void* param)
2081 LARGE_INTEGER hires_counter, li_frequency;
2085 // Init - find out if we have access to a monotonic (hires) timer
2086 if (!QueryPerformanceFrequency(&li_frequency)) {
2087 usbi_dbg("no hires timer available on this platform");
2088 hires_frequency = 0;
2089 hires_ticks_to_ps = UINT64_C(0);
2091 hires_frequency = li_frequency.QuadPart;
2092 // The hires frequency can go as high as 4 GHz, so we'll use a conversion
2093 // to picoseconds to compute the tv_nsecs part in clock_gettime
2094 hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
2095 usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
2098 // Main loop - wait for requests
2100 timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
2101 if ( (timer_index != 0) && (timer_index != 1) ) {
2102 usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
2105 if (request_count[timer_index] == 0) {
2106 // Request already handled
2107 ResetEvent(timer_request[timer_index]);
2108 // There's still a possiblity that a thread sends a request between the
2109 // time we test request_count[] == 0 and we reset the event, in which case
2110 // the request would be ignored. The simple solution to that is to test
2111 // request_count again and process requests if non zero.
2112 if (request_count[timer_index] == 0)
2115 switch (timer_index) {
2117 WaitForSingleObject(timer_mutex, INFINITE);
2118 // Requests to this thread are for hires always
2119 if (QueryPerformanceCounter(&hires_counter) != 0) {
2120 timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
2121 timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
2123 // Fallback to real-time if we can't get monotonic value
2124 // Note that real-time clock does not wait on the mutex or this thread.
2125 windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
2127 ReleaseMutex(timer_mutex);
2129 nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
2131 && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
2132 usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
2135 case 1: // time to quit
2136 usbi_dbg("timer thread quitting");
2140 usbi_dbg("ERROR: broken timer thread");
2144 static int windows_clock_gettime(int clk_id, struct timespec *tp)
2147 ULARGE_INTEGER rtime;
2150 case USBI_CLOCK_MONOTONIC:
2151 if (hires_frequency != 0) {
2153 InterlockedIncrement((LONG*)&request_count[0]);
2154 SetEvent(timer_request[0]);
2155 r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
2158 WaitForSingleObject(timer_mutex, INFINITE);
2160 ReleaseMutex(timer_mutex);
2161 return LIBUSB_SUCCESS;
2163 usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
2164 break; // Retry until successful
2166 usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
2167 return LIBUSB_ERROR_OTHER;
2171 // Fall through and return real-time if monotonic was not detected @ timer init
2172 case USBI_CLOCK_REALTIME:
2173 // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
2174 // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
2175 // Note however that our resolution is bounded by the Windows system time
2176 // functions and is at best of the order of 1 ms (or, usually, worse)
2177 GetSystemTimeAsFileTime(&filetime);
2178 rtime.LowPart = filetime.dwLowDateTime;
2179 rtime.HighPart = filetime.dwHighDateTime;
2180 rtime.QuadPart -= epoch_time;
2181 tp->tv_sec = (long)(rtime.QuadPart / 10000000);
2182 tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
2183 return LIBUSB_SUCCESS;
2185 return LIBUSB_ERROR_INVALID_PARAM;
2190 // NB: MSVC6 does not support named initializers.
2191 const struct usbi_os_backend windows_backend = {
2196 windows_get_device_list,
2200 windows_get_device_descriptor,
2201 windows_get_active_config_descriptor,
2202 windows_get_config_descriptor,
2204 windows_get_configuration,
2205 windows_set_configuration,
2206 windows_claim_interface,
2207 windows_release_interface,
2209 windows_set_interface_altsetting,
2211 windows_reset_device,
2213 windows_kernel_driver_active,
2214 windows_detach_kernel_driver,
2215 windows_attach_kernel_driver,
2217 windows_destroy_device,
2219 windows_submit_transfer,
2220 windows_cancel_transfer,
2221 windows_clear_transfer_priv,
2223 windows_handle_events,
2225 windows_clock_gettime,
2226 #if defined(USBI_TIMERFD_AVAILABLE)
2229 sizeof(struct windows_device_priv),
2230 sizeof(struct windows_device_handle_priv),
2231 sizeof(struct windows_transfer_priv),
2239 static int unsupported_init(struct libusb_context *ctx) {
2240 return LIBUSB_SUCCESS;
2242 static int unsupported_exit(void) {
2243 return LIBUSB_SUCCESS;
2245 static int unsupported_open(struct libusb_device_handle *dev_handle) {
2246 PRINT_UNSUPPORTED_API(open);
2248 static void unsupported_close(struct libusb_device_handle *dev_handle) {
2249 usbi_dbg("unsupported API call for 'close'");
2251 static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
2252 PRINT_UNSUPPORTED_API(claim_interface);
2254 static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
2255 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2257 static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
2258 PRINT_UNSUPPORTED_API(release_interface);
2260 static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2261 PRINT_UNSUPPORTED_API(clear_halt);
2263 static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
2264 PRINT_UNSUPPORTED_API(reset_device);
2266 static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
2267 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2269 static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
2270 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2272 static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
2273 PRINT_UNSUPPORTED_API(submit_control_transfer);
2275 static int unsupported_abort_control(struct usbi_transfer *itransfer) {
2276 PRINT_UNSUPPORTED_API(abort_control);
2278 static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
2279 PRINT_UNSUPPORTED_API(abort_transfers);
2281 static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
2282 PRINT_UNSUPPORTED_API(copy_transfer_data);
2285 const char* composite_driver_names[] = {"usbccgp"};
2286 const char* winusb_driver_names[] = {"WinUSB"};
2287 const char* hid_driver_names[] = {"HidUsb", "mouhid", "kbdhid"};
2288 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2290 USB_API_UNSUPPORTED,
2291 &CLASS_GUID_UNSUPPORTED,
2298 unsupported_claim_interface,
2299 unsupported_set_interface_altsetting,
2300 unsupported_release_interface,
2301 unsupported_clear_halt,
2302 unsupported_reset_device,
2303 unsupported_submit_bulk_transfer,
2304 unsupported_submit_iso_transfer,
2305 unsupported_submit_control_transfer,
2306 unsupported_abort_control,
2307 unsupported_abort_transfers,
2308 unsupported_copy_transfer_data,
2311 &CLASS_GUID_COMPOSITE,
2312 composite_driver_names,
2318 composite_claim_interface,
2319 composite_set_interface_altsetting,
2320 composite_release_interface,
2321 composite_clear_halt,
2322 composite_reset_device,
2323 composite_submit_bulk_transfer,
2324 composite_submit_iso_transfer,
2325 composite_submit_control_transfer,
2326 composite_abort_control,
2327 composite_abort_transfers,
2328 composite_copy_transfer_data,
2331 &CLASS_GUID_LIBUSB_WINUSB,
2332 winusb_driver_names,
2338 winusb_claim_interface,
2339 winusb_set_interface_altsetting,
2340 winusb_release_interface,
2342 winusb_reset_device,
2343 winusb_submit_bulk_transfer,
2344 unsupported_submit_iso_transfer,
2345 winusb_submit_control_transfer,
2346 winusb_abort_control,
2347 winusb_abort_transfers,
2348 winusb_copy_transfer_data,
2358 hid_claim_interface,
2359 hid_set_interface_altsetting,
2360 hid_release_interface,
2363 hid_submit_bulk_transfer,
2364 unsupported_submit_iso_transfer,
2365 hid_submit_control_transfer,
2366 hid_abort_transfers,
2367 hid_abort_transfers,
2368 hid_copy_transfer_data,
2374 * WinUSB API functions
2376 static int winusb_init(struct libusb_context *ctx)
2378 DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
2379 DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
2380 DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
2381 DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
2382 DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
2383 DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
2384 DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
2385 DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
2386 DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
2387 DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
2388 DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
2389 DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
2390 DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
2391 DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
2392 DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
2393 DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
2394 DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
2396 api_winusb_available = true;
2397 return LIBUSB_SUCCESS;
2400 static int winusb_exit(void)
2402 return LIBUSB_SUCCESS;
2405 // NB: open and close must ensure that they only handle interface of
2406 // the right API type, as these functions can be called wholesale from
2407 // composite_open(), with interfaces belonging to different APIs
2408 static int winusb_open(struct libusb_device_handle *dev_handle)
2410 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2411 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2412 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2417 CHECK_WINUSB_AVAILABLE;
2419 // WinUSB requires a seperate handle for each interface
2420 for (i = 0; i < USB_MAXINTERFACES; i++) {
2421 if ( (priv->usb_interface[i].path != NULL)
2422 && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
2423 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2424 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2425 if (file_handle == INVALID_HANDLE_VALUE) {
2426 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2427 switch(GetLastError()) {
2428 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2429 return LIBUSB_ERROR_NO_DEVICE;
2430 case ERROR_ACCESS_DENIED:
2431 return LIBUSB_ERROR_ACCESS;
2433 return LIBUSB_ERROR_IO;
2436 handle_priv->interface_handle[i].dev_handle = file_handle;
2440 return LIBUSB_SUCCESS;
2443 static void winusb_close(struct libusb_device_handle *dev_handle)
2445 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2446 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2450 if (!api_winusb_available)
2453 for (i = 0; i < USB_MAXINTERFACES; i++) {
2454 if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
2455 file_handle = handle_priv->interface_handle[i].dev_handle;
2456 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
2457 CloseHandle(file_handle);
2463 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
2465 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2466 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2467 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2468 bool is_composite = (priv->apib->id == USB_API_COMPOSITE);
2469 HANDLE file_handle, winusb_handle;
2470 USB_INTERFACE_DESCRIPTOR if_desc;
2472 uint8_t endpoint_address;
2475 CHECK_WINUSB_AVAILABLE;
2477 // interfaces for composite devices are always independent, therefore
2478 // "alt" interfaces are only found on non-composite
2479 if ((!is_composite) && (iface != 0)) {
2480 winusb_handle = handle_priv->interface_handle[0].api_handle;
2481 // It is a requirement on Windows that to claim an interface >= 1
2482 // on a non-composite WinUSB device, you must first have claimed interface 0
2483 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2484 #if defined(AUTO_CLAIM)
2485 file_handle = handle_priv->interface_handle[0].dev_handle;
2486 if (WinUsb_Initialize(file_handle, &winusb_handle)) {
2487 handle_priv->interface_handle[0].api_handle = winusb_handle;
2488 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2490 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
2491 return LIBUSB_ERROR_ACCESS;
2494 usbi_warn(ctx, "you must claim interface 0 before you can claim %d with WinUSB", iface);
2495 return LIBUSB_ERROR_ACCESS;
2498 if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
2499 &handle_priv->interface_handle[iface].api_handle)) {
2500 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2501 switch(GetLastError()) {
2502 case ERROR_NO_MORE_ITEMS: // invalid iface
2503 return LIBUSB_ERROR_NOT_FOUND;
2504 case ERROR_BAD_COMMAND: // The device was disconnected
2505 return LIBUSB_ERROR_NO_DEVICE;
2506 case ERROR_ALREADY_EXISTS: // already claimed
2507 return LIBUSB_ERROR_BUSY;
2509 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2510 return LIBUSB_ERROR_ACCESS;
2514 // composite device (independent interfaces) or interface 0
2515 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2516 file_handle = handle_priv->interface_handle[iface].dev_handle;
2517 if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
2518 return LIBUSB_ERROR_NOT_FOUND;
2521 if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
2522 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2523 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2525 switch(GetLastError()) {
2526 case ERROR_BAD_COMMAND: // The device was disconnected
2527 return LIBUSB_ERROR_NO_DEVICE;
2529 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2530 return LIBUSB_ERROR_ACCESS;
2533 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2535 if (!WinUsb_QueryInterfaceSettings(winusb_handle, 0, &if_desc)) {
2536 usbi_err(ctx, "could not query interface settings for interface %d: %s", iface, windows_error_str(0));
2537 } else if (if_desc.bInterfaceNumber != iface) {
2538 usbi_warn(ctx, "program assertion failed - WinUSB interface %d found at position %d",
2539 if_desc.bInterfaceNumber, iface);
2542 usbi_dbg("claimed interface %d", iface);
2543 handle_priv->active_interface = iface;
2545 // With handle and enpoints set (in parent), we can setup the default
2546 // pipe properties (copied from libusb-win32-v1)
2547 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2548 for (i=0; i<priv->usb_interface[iface].nb_endpoints; i++) {
2549 endpoint_address = priv->usb_interface[iface].endpoint[i];
2551 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2552 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
2553 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2555 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2556 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) {
2557 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2559 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2560 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) {
2561 usbi_dbg("failed to disable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2564 if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
2565 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
2566 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2570 return LIBUSB_SUCCESS;
2573 static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
2575 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2576 HANDLE winusb_handle;
2578 CHECK_WINUSB_AVAILABLE;
2580 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2581 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2582 return LIBUSB_ERROR_NOT_FOUND;
2585 WinUsb_Free(winusb_handle);
2586 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2588 return LIBUSB_SUCCESS;
2592 * Return the first valid interface (of the same API type), for control transfers
2594 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2596 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2597 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2600 if ((api_id < USB_API_WINUSB) || (api_id > USB_API_HID)) {
2601 usbi_dbg("unsupported API ID");
2605 for (i=0; i<USB_MAXINTERFACES; i++) {
2606 if ( (handle_priv->interface_handle[i].dev_handle != 0)
2607 && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
2608 && (handle_priv->interface_handle[i].api_handle != 0)
2609 && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE)
2610 && (priv->usb_interface[i].apib == &usb_api_backend[api_id]) ) {
2618 * Lookup interface by endpoint address. -1 if not found
2620 static int interface_by_endpoint(struct windows_device_priv *priv,
2621 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2624 for (i=0; i<USB_MAXINTERFACES; i++) {
2625 if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
2627 if (handle_priv->interface_handle[i].api_handle == 0)
2629 if (priv->usb_interface[i].endpoint == NULL)
2631 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2632 if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
2640 static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
2642 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2643 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2644 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2645 struct windows_device_handle_priv *handle_priv = __device_handle_priv(
2646 transfer->dev_handle);
2647 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
2649 HANDLE winusb_handle;
2650 int current_interface;
2653 CHECK_WINUSB_AVAILABLE;
2655 transfer_priv->pollable_fd = INVALID_WINFD;
2656 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2658 if (size > MAX_CTRL_BUFFER_LENGTH)
2659 return LIBUSB_ERROR_INVALID_PARAM;
2661 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSB);
2662 if (current_interface < 0) {
2663 #if defined(AUTO_CLAIM)
2664 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
2665 return LIBUSB_ERROR_NOT_FOUND;
2668 usbi_warn(ctx, "no interface available for control transfer");
2669 return LIBUSB_ERROR_NOT_FOUND;
2673 usbi_dbg("will use interface %d", current_interface);
2674 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2676 wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
2677 // Always use the handle returned from usbi_create_fd (wfd.handle)
2679 return LIBUSB_ERROR_NO_MEM;
2682 if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2683 if(GetLastError() != ERROR_IO_PENDING) {
2684 usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
2685 usbi_free_fd(wfd.fd);
2686 return LIBUSB_ERROR_IO;
2689 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2690 wfd.overlapped->InternalHigh = (DWORD)size;
2693 // Use priv_transfer to store data needed for async polling
2694 transfer_priv->pollable_fd = wfd;
2695 transfer_priv->interface_number = (uint8_t)current_interface;
2697 return LIBUSB_SUCCESS;
2700 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
2702 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2703 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2704 HANDLE winusb_handle;
2706 CHECK_WINUSB_AVAILABLE;
2708 if (altsetting > 255) {
2709 return LIBUSB_ERROR_INVALID_PARAM;
2712 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2713 if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
2714 usbi_err(ctx, "interface must be claimed first");
2715 return LIBUSB_ERROR_NOT_FOUND;
2718 if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2719 usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2720 return LIBUSB_ERROR_IO;
2723 return LIBUSB_SUCCESS;
2726 static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
2728 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2729 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2730 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2731 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
2732 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
2733 HANDLE winusb_handle;
2734 bool direction_in, ret;
2735 int current_interface;
2738 CHECK_WINUSB_AVAILABLE;
2740 transfer_priv->pollable_fd = INVALID_WINFD;
2742 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2743 if (current_interface < 0) {
2744 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2745 return LIBUSB_ERROR_NOT_FOUND;
2748 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2750 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2751 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
2753 wfd = usbi_create_fd(winusb_handle, direction_in?_O_RDONLY:_O_WRONLY);
2754 // Always use the handle returned from usbi_create_fd (wfd.handle)
2756 return LIBUSB_ERROR_NO_MEM;
2760 usbi_dbg("reading %d bytes", transfer->length);
2761 ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2763 usbi_dbg("writing %d bytes", transfer->length);
2764 ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2767 if(GetLastError() != ERROR_IO_PENDING) {
2768 usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
2769 usbi_free_fd(wfd.fd);
2770 return LIBUSB_ERROR_IO;
2773 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2774 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2777 transfer_priv->pollable_fd = wfd;
2778 transfer_priv->interface_number = (uint8_t)current_interface;
2780 return LIBUSB_SUCCESS;
2783 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2785 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2786 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2787 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2788 HANDLE winusb_handle;
2789 int current_interface;
2791 CHECK_WINUSB_AVAILABLE;
2793 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2794 if (current_interface < 0) {
2795 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2796 return LIBUSB_ERROR_NOT_FOUND;
2799 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2800 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2802 if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
2803 usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
2804 return LIBUSB_ERROR_NO_DEVICE;
2807 return LIBUSB_SUCCESS;
2811 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2812 * through testing as well):
2813 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2814 * the control transfer using CancelIo"
2816 static int winusb_abort_control(struct usbi_transfer *itransfer)
2818 // Cancelling of the I/O is done in the parent
2819 return LIBUSB_SUCCESS;
2822 static int winusb_abort_transfers(struct usbi_transfer *itransfer)
2824 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2825 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2826 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
2827 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2828 HANDLE winusb_handle;
2829 int current_interface;
2831 CHECK_WINUSB_AVAILABLE;
2833 current_interface = transfer_priv->interface_number;
2834 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2835 usbi_err(ctx, "program assertion failed: invalid interface_number");
2836 return LIBUSB_ERROR_NOT_FOUND;
2838 usbi_dbg("will use interface %d", current_interface);
2840 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2842 if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
2843 usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
2844 return LIBUSB_ERROR_NO_DEVICE;
2847 return LIBUSB_SUCCESS;
2851 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2852 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2853 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2854 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2855 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2856 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2858 // TODO (2nd official release): see if we can force eject the device and redetect it (reuse hotplug?)
2859 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2861 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2862 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
2863 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
2865 HANDLE winusb_handle;
2868 CHECK_WINUSB_AVAILABLE;
2870 // Reset any available pipe (except control)
2871 for (i=0; i<USB_MAXINTERFACES; i++) {
2872 winusb_handle = handle_priv->interface_handle[i].api_handle;
2873 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
2875 // Cancel any pollable I/O
2876 usbi_remove_pollfd(ctx, wfd.fd);
2877 usbi_free_fd(wfd.fd);
2878 wfd = handle_to_winfd(winusb_handle);
2881 if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
2882 for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
2883 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2884 if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2885 usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
2886 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2888 // FlushPipe seems to fail on OUT pipes
2889 if ( (priv->usb_interface[i].endpoint[j] & LIBUSB_ENDPOINT_IN)
2890 && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
2891 usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
2892 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2894 if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
2895 usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
2896 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2902 return LIBUSB_SUCCESS;
2905 static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2907 itransfer->transferred += io_size;
2908 return LIBUSB_TRANSFER_COMPLETED;
2912 * Internal HID Support functions (from libusb-win32)
2913 * Note that functions that complete data transfer synchronously must return
2914 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
2916 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2917 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size);
2919 static int _hid_wcslen(WCHAR *str)
2922 while (str[i] && (str[i] != 0x409)) {
2928 static int _hid_get_device_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2930 struct libusb_device_descriptor d;
2932 d.bLength = LIBUSB_DT_DEVICE_SIZE;
2933 d.bDescriptorType = LIBUSB_DT_DEVICE;
2934 d.bcdUSB = 0x0200; /* 2.00 */
2936 d.bDeviceSubClass = 0;
2937 d.bDeviceProtocol = 0;
2938 d.bMaxPacketSize0 = 64; /* fix this! */
2939 d.idVendor = (uint16_t)dev->vid;
2940 d.idProduct = (uint16_t)dev->pid;
2941 d.bcdDevice = 0x0100;
2942 d.iManufacturer = dev->string_index[0];
2943 d.iProduct = dev->string_index[1];
2944 d.iSerialNumber = dev->string_index[2];
2945 d.bNumConfigurations = 1;
2947 if (*size > LIBUSB_DT_DEVICE_SIZE)
2948 *size = LIBUSB_DT_DEVICE_SIZE;
2949 memcpy(data, &d, *size);
2950 return LIBUSB_COMPLETED;
2953 static int _hid_get_config_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
2955 char num_endpoints = 0;
2956 size_t config_total_len = 0;
2957 char tmp[HID_MAX_CONFIG_DESC_SIZE];
2958 struct libusb_config_descriptor *cd;
2959 struct libusb_interface_descriptor *id;
2960 struct libusb_hid_descriptor *hd;
2961 struct libusb_endpoint_descriptor *ed;
2964 if (dev->input_report_size)
2966 if (dev->output_report_size)
2969 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
2970 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
2973 cd = (struct libusb_config_descriptor *)tmp;
2974 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
2975 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
2976 + LIBUSB_DT_INTERFACE_SIZE);
2977 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
2978 + LIBUSB_DT_INTERFACE_SIZE
2979 + LIBUSB_DT_HID_SIZE);
2981 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
2982 cd->bDescriptorType = LIBUSB_DT_CONFIG;
2983 cd->wTotalLength = (uint16_t) config_total_len;
2984 cd->bNumInterfaces = 1;
2985 cd->bConfigurationValue = 1;
2986 cd->iConfiguration = 0;
2987 cd->bmAttributes = 1 << 7; /* bus powered */
2990 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
2991 id->bDescriptorType = LIBUSB_DT_INTERFACE;
2992 id->bInterfaceNumber = 0;
2993 id->bAlternateSetting = 0;
2994 id->bNumEndpoints = num_endpoints;
2995 id->bInterfaceClass = 3;
2996 id->bInterfaceSubClass = 0;
2997 id->bInterfaceProtocol = 0;
3000 tmp_size = LIBUSB_DT_HID_SIZE;
3001 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3003 if (dev->input_report_size) {
3004 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3005 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3006 ed->bEndpointAddress = HID_IN_EP;
3007 ed->bmAttributes = 3;
3008 ed->wMaxPacketSize = dev->input_report_size - 1;
3014 if (dev->output_report_size) {
3015 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3016 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3017 ed->bEndpointAddress = HID_OUT_EP;
3018 ed->bmAttributes = 3;
3019 ed->wMaxPacketSize = dev->output_report_size - 1;
3023 if (*size > config_total_len)
3024 *size = config_total_len;
3025 memcpy(data, tmp, *size);
3026 return LIBUSB_COMPLETED;
3029 static int _hid_get_string_descriptor(struct hid_device_priv* dev, int index,
3030 void *data, size_t *size)
3033 size_t tmp_size = 0;
3036 /* language ID, EN-US */
3037 char string_langid[] = {
3042 if ((*size < 2) || (*size > 255)) {
3043 return LIBUSB_ERROR_OVERFLOW;
3047 tmp = string_langid;
3048 tmp_size = sizeof(string_langid)+2;
3050 for (i=0; i<3; i++) {
3051 if (index == (dev->string_index[i])) {
3052 tmp = dev->string[i];
3053 tmp_size = (_hid_wcslen(dev->string[i])+1) * sizeof(WCHAR);
3057 if (i == 3) { // not found
3058 return LIBUSB_ERROR_INVALID_PARAM;
3063 return LIBUSB_ERROR_INVALID_PARAM;
3066 if (tmp_size < *size) {
3070 ((uint8_t*)data)[0] = (uint8_t)*size;
3071 ((uint8_t*)data)[1] = LIBUSB_DT_STRING;
3072 memcpy((uint8_t*)data+2, tmp, *size-2);
3073 return LIBUSB_COMPLETED;
3076 static int _hid_get_hid_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3078 struct libusb_hid_descriptor d;
3079 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3080 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3082 _hid_get_report_descriptor(dev, tmp, &report_len);
3084 d.bLength = LIBUSB_DT_HID_SIZE;
3085 d.bDescriptorType = LIBUSB_DT_HID;
3086 d.bcdHID = 0x0110; /* 1.10 */
3088 d.bNumDescriptors = 1;
3089 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3090 d.wClassDescriptorLength = (uint16_t)report_len;
3092 if (*size > LIBUSB_DT_HID_SIZE)
3093 *size = LIBUSB_DT_HID_SIZE;
3094 memcpy(data, &d, *size);
3095 return LIBUSB_COMPLETED;
3098 static int _hid_get_report_descriptor(struct hid_device_priv* dev, void *data, size_t *size)
3100 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3103 /* usage page (0xFFA0 == vendor defined) */
3104 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3105 /* usage (vendor defined) */
3106 d[i++] = 0x09; d[i++] = 0x01;
3107 /* start collection (application) */
3108 d[i++] = 0xA1; d[i++] = 0x01;
3110 if (dev->input_report_size) {
3111 /* usage (vendor defined) */
3112 d[i++] = 0x09; d[i++] = 0x01;
3113 /* logical minimum (0) */
3114 d[i++] = 0x15; d[i++] = 0x00;
3115 /* logical maximum (255) */
3116 d[i++] = 0x25; d[i++] = 0xFF;
3117 /* report size (8 bits) */
3118 d[i++] = 0x75; d[i++] = 0x08;
3120 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3121 /* input (data, variable, absolute) */
3122 d[i++] = 0x81; d[i++] = 0x00;
3125 if (dev->output_report_size) {
3126 /* usage (vendor defined) */
3127 d[i++] = 0x09; d[i++] = 0x02;
3128 /* logical minimum (0) */
3129 d[i++] = 0x15; d[i++] = 0x00;
3130 /* logical maximum (255) */
3131 d[i++] = 0x25; d[i++] = 0xFF;
3132 /* report size (8 bits) */
3133 d[i++] = 0x75; d[i++] = 0x08;
3135 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3136 /* output (data, variable, absolute) */
3137 d[i++] = 0x91; d[i++] = 0x00;
3139 /* feature report */
3140 if (dev->feature_report_size) {
3141 /* usage (vendor defined) */
3142 d[i++] = 0x09; d[i++] = 0x03;
3143 /* logical minimum (0) */
3144 d[i++] = 0x15; d[i++] = 0x00;
3145 /* logical maximum (255) */
3146 d[i++] = 0x25; d[i++] = 0xFF;
3147 /* report size (8 bits) */
3148 d[i++] = 0x75; d[i++] = 0x08;
3150 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3151 /* feature (data, variable, absolute) */
3152 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3155 /* end collection */
3160 memcpy(data, d, *size);
3161 return LIBUSB_COMPLETED;
3164 static int _hid_get_descriptor(struct hid_device_priv* dev, HANDLE hid_handle, int recipient,
3165 int type, int index, void *data, size_t *size)
3168 case LIBUSB_DT_DEVICE:
3169 usbi_dbg("LIBUSB_DT_DEVICE");
3170 return _hid_get_device_descriptor(dev, data, size);
3171 case LIBUSB_DT_CONFIG:
3172 usbi_dbg("LIBUSB_DT_CONFIG");
3174 return _hid_get_config_descriptor(dev, data, size);
3175 return LIBUSB_ERROR_INVALID_PARAM;
3176 case LIBUSB_DT_STRING:
3177 usbi_dbg("LIBUSB_DT_STRING");
3178 return _hid_get_string_descriptor(dev, index, data, size);
3180 usbi_dbg("LIBUSB_DT_HID");
3182 return _hid_get_hid_descriptor(dev, data, size);
3183 return LIBUSB_ERROR_INVALID_PARAM;
3184 case LIBUSB_DT_REPORT:
3185 usbi_dbg("LIBUSB_DT_REPORT");
3187 return _hid_get_report_descriptor(dev, data, size);
3188 return LIBUSB_ERROR_INVALID_PARAM;
3189 case LIBUSB_DT_PHYSICAL:
3190 usbi_dbg("LIBUSB_DT_PHYSICAL");
3191 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3192 return LIBUSB_COMPLETED;
3193 return LIBUSB_ERROR_OTHER;
3195 usbi_dbg("unsupported");
3196 return LIBUSB_ERROR_INVALID_PARAM;
3199 static int _hid_get_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3200 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3204 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3205 int r = LIBUSB_SUCCESS;
3207 if (tp->hid_buffer != NULL) {
3208 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3211 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3212 usbi_dbg("invalid size (%d)", *size);
3213 return LIBUSB_ERROR_INVALID_PARAM;
3216 switch (report_type) {
3217 case HID_REPORT_TYPE_INPUT:
3218 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3220 case HID_REPORT_TYPE_FEATURE:
3221 ioctl_code = IOCTL_HID_GET_FEATURE;
3224 usbi_dbg("unknown HID report type %d", report_type);
3225 return LIBUSB_ERROR_INVALID_PARAM;
3228 // When report IDs are not in use, add an extra byte for the report ID
3233 // Add a trailing byte to detect overflows
3234 buf = (uint8_t*)calloc(expected_size+1, 1);
3236 return LIBUSB_ERROR_NO_MEM;
3238 buf[0] = (uint8_t)id; // Must be set always
3239 usbi_dbg("report ID: 0x%02X", buf[0]);
3241 tp->hid_expected_size = expected_size;
3243 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size+1,
3244 buf, expected_size+1, &read_size, overlapped)) {
3245 if (GetLastError() != ERROR_IO_PENDING) {
3246 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3248 return LIBUSB_ERROR_IO;
3250 // Asynchronous wait
3251 tp->hid_buffer = buf;
3252 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3253 return LIBUSB_SUCCESS;
3256 // Transfer completed synchronously => copy and discard extra buffer
3257 if (read_size == 0) {
3258 usbi_dbg("program assertion failed - read completed synchronously, but no data was read");
3262 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3264 if ((size_t)read_size > expected_size) {
3265 r = LIBUSB_ERROR_OVERFLOW;
3266 usbi_dbg("OVERFLOW!");
3268 r = LIBUSB_COMPLETED;
3272 // Discard report ID
3273 *size = MIN((size_t)read_size-1, *size);
3274 memcpy(data, buf+1, *size);
3276 *size = MIN((size_t)read_size, *size);
3277 memcpy(data, buf, *size);
3284 static int _hid_set_report(struct hid_device_priv* dev, HANDLE hid_handle, int id, void *data,
3285 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED* overlapped,
3288 uint8_t *buf = NULL;
3289 DWORD ioctl_code, write_size= (DWORD)*size;
3291 if (tp->hid_buffer != NULL) {
3292 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3295 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3296 usbi_dbg("invalid size (%d)", *size);
3297 return LIBUSB_ERROR_INVALID_PARAM;
3300 switch (report_type) {
3301 case HID_REPORT_TYPE_OUTPUT:
3302 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3304 case HID_REPORT_TYPE_FEATURE:
3305 ioctl_code = IOCTL_HID_SET_FEATURE;
3308 usbi_dbg("unknown HID report type %d", report_type);
3309 return LIBUSB_ERROR_INVALID_PARAM;
3312 usbi_dbg("report ID: 0x%02X", id);
3313 // When report IDs are not used (i.e. when id == 0), we must add
3314 // a null report ID. Otherwise, we just use original data buffer
3318 buf = malloc(write_size);
3320 return LIBUSB_ERROR_NO_MEM;
3324 memcpy(buf + 1, data, *size);
3326 // This seems like a waste, but if we don't duplicate the
3327 // data, we'll get issues when freeing hid_buffer
3328 memcpy(buf, data, *size);
3330 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3334 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3335 buf, write_size, &write_size, overlapped)) {
3336 if (GetLastError() != ERROR_IO_PENDING) {
3337 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3339 return LIBUSB_ERROR_IO;
3341 tp->hid_buffer = buf;
3342 tp->hid_dest = NULL;
3343 return LIBUSB_SUCCESS;
3346 // Transfer completed synchronously
3347 if (write_size == 0) {
3348 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3351 *size = write_size - ((id == 0)?1:0);
3354 return LIBUSB_COMPLETED;
3357 static int _hid_class_request(struct hid_device_priv* dev, HANDLE hid_handle, int request_type,
3358 int request, int value, int index, void *data, struct windows_transfer_priv *tp,
3359 size_t *size, OVERLAPPED* overlapped)
3361 int report_type = (value >> 8) & 0xFF;
3362 int report_id = value & 0xFF;
3364 if ( (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3365 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE) )
3366 return LIBUSB_ERROR_INVALID_PARAM;
3368 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3369 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3371 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3372 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3374 return LIBUSB_ERROR_INVALID_PARAM;
3381 static int hid_init(struct libusb_context *ctx)
3383 DLL_LOAD(hid.dll, HidD_GetAttributes, TRUE);
3384 DLL_LOAD(hid.dll, HidD_GetHidGuid, TRUE);
3385 DLL_LOAD(hid.dll, HidD_GetPreparsedData, TRUE);
3386 DLL_LOAD(hid.dll, HidD_FreePreparsedData, TRUE);
3387 DLL_LOAD(hid.dll, HidD_GetManufacturerString, TRUE);
3388 DLL_LOAD(hid.dll, HidD_GetProductString, TRUE);
3389 DLL_LOAD(hid.dll, HidD_GetSerialNumberString, TRUE);
3390 DLL_LOAD(hid.dll, HidP_GetCaps, TRUE);
3391 DLL_LOAD(hid.dll, HidD_SetNumInputBuffers, TRUE);
3392 DLL_LOAD(hid.dll, HidD_SetFeature, TRUE);
3393 DLL_LOAD(hid.dll, HidD_GetFeature, TRUE);
3394 DLL_LOAD(hid.dll, HidD_GetPhysicalDescriptor, TRUE);
3395 DLL_LOAD(hid.dll, HidD_GetInputReport, FALSE);
3396 DLL_LOAD(hid.dll, HidD_SetOutputReport, FALSE);
3397 DLL_LOAD(hid.dll, HidD_FlushQueue, TRUE);
3398 DLL_LOAD(hid.dll, HidP_GetValueCaps, TRUE);
3400 api_hid_available = true;
3401 return LIBUSB_SUCCESS;
3404 static int hid_exit(void)
3406 return LIBUSB_SUCCESS;
3409 // NB: open and close must ensure that they only handle interface of
3410 // the right API type, as these functions can be called wholesale from
3411 // composite_open(), with interfaces belonging to different APIs
3412 static int hid_open(struct libusb_device_handle *dev_handle)
3414 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3415 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3416 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3418 HIDD_ATTRIBUTES hid_attributes;
3419 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3420 HIDP_CAPS capabilities;
3421 HIDP_VALUE_CAPS *value_caps;
3423 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3425 // report IDs handling
3427 char* type[3] = {"input", "output", "feature"};
3428 int nb_ids[2]; // zero and nonzero report IDs
3430 CHECK_HID_AVAILABLE;
3431 if (priv->hid == NULL) {
3432 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3433 return LIBUSB_ERROR_NOT_FOUND;
3436 for (i = 0; i < USB_MAXINTERFACES; i++) {
3437 if ( (priv->usb_interface[i].path != NULL)
3438 && (priv->usb_interface[i].apib->id == USB_API_HID) ) {
3439 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3440 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3442 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3443 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3444 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3445 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3446 * HidD_GetFeature (if the device supports Feature reports)."
3448 if (hid_handle == INVALID_HANDLE_VALUE) {
3449 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3450 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3451 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3452 if (hid_handle == INVALID_HANDLE_VALUE) {
3453 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3454 switch(GetLastError()) {
3455 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3456 return LIBUSB_ERROR_NO_DEVICE;
3457 case ERROR_ACCESS_DENIED:
3458 return LIBUSB_ERROR_ACCESS;
3460 return LIBUSB_ERROR_IO;
3463 priv->usb_interface[i].restricted_functionality = true;
3465 handle_priv->interface_handle[i].api_handle = hid_handle;
3469 hid_attributes.Size = sizeof(hid_attributes);
3471 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3472 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3476 priv->hid->vid = hid_attributes.VendorID;
3477 priv->hid->pid = hid_attributes.ProductID;
3479 // Set the maximum available input buffer size
3480 for (i=32; HidD_SetNumInputBuffers(hid_handle, i); i*=2);
3481 usbi_dbg("set maximum input buffer size to %d", i/2);
3483 // Get the maximum input and output report size
3484 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3485 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3488 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3489 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3493 // Find out if interrupt will need report IDs
3494 size[0] = capabilities.NumberInputValueCaps;
3495 size[1] = capabilities.NumberOutputValueCaps;
3496 size[2] = capabilities.NumberFeatureValueCaps;
3497 for (j=0; j<3; j++) {
3498 usbi_dbg("%d HID %s report value(s) found", size[j], type[j]);
3499 priv->hid->uses_report_ids[j] = false;
3501 value_caps = malloc(size[j] * sizeof(HIDP_VALUE_CAPS));
3502 if ( (value_caps != NULL)
3503 && (HidP_GetValueCaps(j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3504 && (size[j] >= 1) ) {
3507 for (i=0; i<(int)size[j]; i++) {
3508 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3509 if (value_caps[i].ReportID != 0) {
3515 if (nb_ids[1] != 0) {
3516 if (nb_ids[0] != 0) {
3517 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3520 priv->hid->uses_report_ids[j] = true;
3523 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3525 safe_free(value_caps);
3529 // Set the report sizes
3530 priv->hid->input_report_size = capabilities.InputReportByteLength;
3531 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3532 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3534 // Fetch string descriptors
3535 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3536 if (priv->hid->string_index[0] != 0) {
3537 HidD_GetManufacturerString(hid_handle, priv->hid->string[0],
3538 sizeof(priv->hid->string[0]));
3540 priv->hid->string[0][0] = 0;
3542 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3543 if (priv->hid->string_index[1] != 0) {
3544 HidD_GetProductString(hid_handle, priv->hid->string[1],
3545 sizeof(priv->hid->string[1]));
3547 priv->hid->string[1][0] = 0;
3549 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3550 if (priv->hid->string_index[2] != 0) {
3551 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2],
3552 sizeof(priv->hid->string[2]));
3554 priv->hid->string[2][0] = 0;
3558 if (preparsed_data) {
3559 HidD_FreePreparsedData(preparsed_data);
3562 return LIBUSB_SUCCESS;
3565 static void hid_close(struct libusb_device_handle *dev_handle)
3567 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3568 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3572 if (!api_hid_available)
3575 for (i = 0; i < USB_MAXINTERFACES; i++) {
3576 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3577 file_handle = handle_priv->interface_handle[i].api_handle;
3578 if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
3579 CloseHandle(file_handle);
3585 static int hid_claim_interface(struct libusb_device_handle *dev_handle, int iface)
3587 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3588 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3590 CHECK_HID_AVAILABLE;
3592 // NB: Disconnection detection is not possible in this function
3593 if (priv->usb_interface[iface].path == NULL) {
3594 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3597 // We use dev_handle as a flag for interface claimed
3598 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) {
3599 return LIBUSB_ERROR_BUSY; // already claimed
3602 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3604 usbi_dbg("claimed interface %d", iface);
3605 handle_priv->active_interface = iface;
3607 return LIBUSB_SUCCESS;
3610 static int hid_release_interface(struct libusb_device_handle *dev_handle, int iface)
3612 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3613 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3615 CHECK_HID_AVAILABLE;
3617 if (priv->usb_interface[iface].path == NULL) {
3618 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3621 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) {
3622 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3625 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3627 return LIBUSB_SUCCESS;
3630 static int hid_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
3632 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3634 CHECK_HID_AVAILABLE;
3636 if (altsetting > 255) {
3637 return LIBUSB_ERROR_INVALID_PARAM;
3640 if (altsetting != 0) {
3641 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3642 return LIBUSB_ERROR_NOT_SUPPORTED;
3645 return LIBUSB_SUCCESS;
3648 static int hid_submit_control_transfer(struct usbi_transfer *itransfer)
3650 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3651 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3652 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3653 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
3654 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3655 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
3658 int current_interface, config;
3660 int r = LIBUSB_ERROR_INVALID_PARAM;
3662 CHECK_HID_AVAILABLE;
3664 transfer_priv->pollable_fd = INVALID_WINFD;
3665 safe_free(transfer_priv->hid_buffer);
3666 transfer_priv->hid_dest = NULL;
3667 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3669 if (size > MAX_CTRL_BUFFER_LENGTH) {
3670 return LIBUSB_ERROR_INVALID_PARAM;
3673 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3674 if (current_interface < 0) {
3675 #if defined(AUTO_CLAIM)
3676 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) {
3677 return LIBUSB_ERROR_NOT_FOUND;
3680 usbi_warn(ctx, "no interface available for control transfer");
3681 return LIBUSB_ERROR_NOT_FOUND;
3685 usbi_dbg("will use interface %d", current_interface);
3686 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3687 // Always use the handle returned from usbi_create_fd (wfd.handle)
3688 wfd = usbi_create_fd(hid_handle, _O_RDONLY);
3690 return LIBUSB_ERROR_NO_MEM;
3693 switch(LIBUSB_REQ_TYPE(setup->request_type)) {
3694 case LIBUSB_REQUEST_TYPE_STANDARD:
3695 switch(setup->request) {
3696 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3697 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type),
3698 (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3700 case LIBUSB_REQUEST_GET_CONFIGURATION:
3701 r = windows_get_configuration(transfer->dev_handle, &config);
3702 if (r == LIBUSB_SUCCESS) {
3704 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3705 r = LIBUSB_COMPLETED;
3708 case LIBUSB_REQUEST_SET_CONFIGURATION:
3709 if (setup->value == priv->active_config) {
3710 r = LIBUSB_COMPLETED;
3712 usbi_warn(ctx, "cannot set configuration other than the default one");
3713 r = LIBUSB_ERROR_INVALID_PARAM;
3716 case LIBUSB_REQUEST_GET_INTERFACE:
3718 ((uint8_t*)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3719 r = LIBUSB_COMPLETED;
3721 case LIBUSB_REQUEST_SET_INTERFACE:
3722 r = hid_set_interface_altsetting(transfer->dev_handle, setup->index, setup->value);
3723 if (r == LIBUSB_SUCCESS) {
3724 r = LIBUSB_COMPLETED;
3728 usbi_warn(ctx, "unsupported HID control request");
3729 r = LIBUSB_ERROR_INVALID_PARAM;
3733 case LIBUSB_REQUEST_TYPE_CLASS:
3734 r =_hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value,
3735 setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3736 &size, wfd.overlapped);
3739 usbi_warn(ctx, "unsupported HID control request");
3740 r = LIBUSB_ERROR_INVALID_PARAM;
3744 if (r == LIBUSB_COMPLETED) {
3745 // Force request to be completed synchronously. Transferred size has been set by previous call
3746 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3747 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3748 // set InternalHigh to the number of bytes transferred
3749 wfd.overlapped->InternalHigh = (DWORD)size;
3753 if (r == LIBUSB_SUCCESS) {
3754 // Use priv_transfer to store data needed for async polling
3755 transfer_priv->pollable_fd = wfd;
3756 transfer_priv->interface_number = (uint8_t)current_interface;
3758 usbi_free_fd(wfd.fd);
3764 static int hid_submit_bulk_transfer(struct usbi_transfer *itransfer) {
3765 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3766 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3767 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3768 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3769 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
3772 bool direction_in, ret;
3773 int current_interface, length;
3775 int r = LIBUSB_SUCCESS;
3777 CHECK_HID_AVAILABLE;
3779 transfer_priv->pollable_fd = INVALID_WINFD;
3780 transfer_priv->hid_dest = NULL;
3781 safe_free(transfer_priv->hid_buffer);
3783 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3784 if (current_interface < 0) {
3785 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3786 return LIBUSB_ERROR_NOT_FOUND;
3789 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3791 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3792 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3794 wfd = usbi_create_fd(hid_handle, direction_in?_O_RDONLY:_O_WRONLY);
3795 // Always use the handle returned from usbi_create_fd (wfd.handle)
3797 return LIBUSB_ERROR_NO_MEM;
3800 // If report IDs are not in use, an extra prefix byte must be added
3801 if ( ((direction_in) && (!priv->hid->uses_report_ids[0]))
3802 || ((!direction_in) && (!priv->hid->uses_report_ids[1])) ) {
3803 length = transfer->length+1;
3805 length = transfer->length;
3807 // Add a trailing byte to detect overflows on input
3808 transfer_priv->hid_buffer = (uint8_t*)calloc(length+1, 1);
3809 if (transfer_priv->hid_buffer == NULL) {
3810 return LIBUSB_ERROR_NO_MEM;
3812 transfer_priv->hid_expected_size = length;
3815 transfer_priv->hid_dest = transfer->buffer;
3816 usbi_dbg("reading %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3817 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length+1, &size, wfd.overlapped);
3819 if (!priv->hid->uses_report_ids[1]) {
3820 memcpy(transfer_priv->hid_buffer+1, transfer->buffer, transfer->length);
3822 // We could actually do without the calloc and memcpy in this case
3823 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3825 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3826 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3829 if (GetLastError() != ERROR_IO_PENDING) {
3830 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3831 usbi_free_fd(wfd.fd);
3832 safe_free(transfer_priv->hid_buffer);
3833 return LIBUSB_ERROR_IO;
3836 // Only write operations that completed synchronously need to free up
3837 // hid_buffer. For reads, copy_transfer_data() handles that process.
3838 if (!direction_in) {
3839 safe_free(transfer_priv->hid_buffer);
3842 usbi_err(ctx, "program assertion failed - no data was transferred");
3845 if (size > (size_t)length) {
3846 usbi_err(ctx, "OVERFLOW!");
3847 r = LIBUSB_ERROR_OVERFLOW;
3849 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3850 wfd.overlapped->InternalHigh = size;
3853 transfer_priv->pollable_fd = wfd;
3854 transfer_priv->interface_number = (uint8_t)current_interface;
3859 static int hid_abort_transfers(struct usbi_transfer *itransfer)
3861 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3862 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3863 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
3865 int current_interface;
3867 CHECK_HID_AVAILABLE;
3869 current_interface = transfer_priv->interface_number;
3870 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3871 CancelIo(hid_handle);
3873 return LIBUSB_SUCCESS;
3876 static int hid_reset_device(struct libusb_device_handle *dev_handle)
3878 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3880 int current_interface;
3882 CHECK_HID_AVAILABLE;
3884 // Flushing the queues on all interfaces is the best we can achieve
3885 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3886 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3887 if ((hid_handle != 0) && (hid_handle != INVALID_HANDLE_VALUE)) {
3888 HidD_FlushQueue(hid_handle);
3891 return LIBUSB_SUCCESS;
3894 static int hid_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
3896 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3897 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
3898 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3900 int current_interface;
3902 CHECK_HID_AVAILABLE;
3904 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3905 if (current_interface < 0) {
3906 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3907 return LIBUSB_ERROR_NOT_FOUND;
3910 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3911 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3913 // No endpoint selection with Microsoft's implementation, so we try to flush the
3914 // whole interface. Should be OK for most case scenarios
3915 if (!HidD_FlushQueue(hid_handle)) {
3916 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3917 // Device was probably disconnected
3918 return LIBUSB_ERROR_NO_DEVICE;
3921 return LIBUSB_SUCCESS;
3924 // This extra function is only needed for HID
3925 static int hid_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
3926 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3927 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3928 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3929 int r = LIBUSB_TRANSFER_COMPLETED;
3930 uint32_t corrected_size = io_size;
3932 if (transfer_priv->hid_buffer != NULL) {
3933 // If we have a valid hid_buffer, it means the transfer was async
3934 if (transfer_priv->hid_dest != NULL) { // Data readout
3935 // First, check for overflow
3936 if (corrected_size > transfer_priv->hid_expected_size) {
3937 usbi_err(ctx, "OVERFLOW!");
3938 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
3939 r = LIBUSB_TRANSFER_OVERFLOW;
3942 if (transfer_priv->hid_buffer[0] == 0) {
3943 // Discard the 1 byte report ID prefix
3945 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer+1, corrected_size);
3947 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
3949 transfer_priv->hid_dest = NULL;
3951 // For write, we just need to free the hid buffer
3952 safe_free(transfer_priv->hid_buffer);
3954 itransfer->transferred += corrected_size;
3960 * Composite API functions
3962 static int composite_init(struct libusb_context *ctx)
3964 return LIBUSB_SUCCESS;
3967 static int composite_exit(void)
3969 return LIBUSB_SUCCESS;
3972 static int composite_open(struct libusb_device_handle *dev_handle)
3974 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3977 uint8_t flag = 1<<USB_API_WINUSB;
3979 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3980 if (priv->composite_api_flags & flag) {
3981 r = usb_api_backend[api].open(dev_handle);
3982 if (r != LIBUSB_SUCCESS) {
3988 return LIBUSB_SUCCESS;
3991 static void composite_close(struct libusb_device_handle *dev_handle)
3993 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
3995 uint8_t flag = 1<<USB_API_WINUSB;
3997 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
3998 if (priv->composite_api_flags & flag) {
3999 usb_api_backend[api].close(dev_handle);
4005 static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
4007 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4008 return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
4011 static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
4013 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4014 return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
4017 static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
4019 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4020 return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
4023 static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
4025 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4026 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4027 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4030 // Interface shouldn't matter for control, but it does in practice, with Windows'
4031 // restrictions with regards to accessing HID keyboards and mice. Try a 2 pass approach
4032 for (pass = 0; pass < 2; pass++) {
4033 for (i=0; i<USB_MAXINTERFACES; i++) {
4034 if (priv->usb_interface[i].path != NULL) {
4035 if ((pass == 0) && (priv->usb_interface[i].restricted_functionality)) {
4036 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", i);
4039 usbi_dbg("using interface %d", i);
4040 return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
4045 usbi_err(ctx, "no libusb supported interfaces to complete request");
4046 return LIBUSB_ERROR_NOT_FOUND;
4049 static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
4050 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4051 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4052 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
4053 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4054 int current_interface;
4056 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4057 if (current_interface < 0) {
4058 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4059 return LIBUSB_ERROR_NOT_FOUND;
4062 return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
4065 static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
4066 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4067 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4068 struct windows_device_handle_priv *handle_priv = __device_handle_priv(transfer->dev_handle);
4069 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4070 int current_interface;
4072 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4073 if (current_interface < 0) {
4074 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4075 return LIBUSB_ERROR_NOT_FOUND;
4078 return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
4081 static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
4083 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4084 struct windows_device_handle_priv *handle_priv = __device_handle_priv(dev_handle);
4085 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4086 int current_interface;
4088 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4089 if (current_interface < 0) {
4090 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4091 return LIBUSB_ERROR_NOT_FOUND;
4094 return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
4097 static int composite_abort_control(struct usbi_transfer *itransfer)
4099 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4100 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4101 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4103 return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
4106 static int composite_abort_transfers(struct usbi_transfer *itransfer)
4108 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4109 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4110 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4112 return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
4115 static int composite_reset_device(struct libusb_device_handle *dev_handle)
4117 struct windows_device_priv *priv = __device_priv(dev_handle->dev);
4120 uint8_t flag = 1<<USB_API_WINUSB;
4122 for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
4123 if (priv->composite_api_flags & flag) {
4124 r = usb_api_backend[api].reset_device(dev_handle);
4125 if (r != LIBUSB_SUCCESS) {
4131 return LIBUSB_SUCCESS;
4134 static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
4136 struct libusb_transfer *transfer = __USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4137 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4138 struct windows_device_priv *priv = __device_priv(transfer->dev_handle->dev);
4140 return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);