2 * windows backend for libusb 1.0
3 * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7 * Hash table functions adapted from glibc, by Ulrich Drepper et al.
8 * Major code testing contribution by Xiaofan Chen
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #if !defined(USE_USBDK)
41 #include "poll_windows.h"
42 #include "windows_winusb.h"
44 #define HANDLE_VALID(h) (((h) != 0) && ((h) != INVALID_HANDLE_VALUE))
46 // The 2 macros below are used in conjunction with safe loops.
47 #define LOOP_CHECK(fcall) \
50 if (r != LIBUSB_SUCCESS) \
53 #define LOOP_BREAK(err) \
59 // WinUSB-like API prototypes
60 static int winusbx_init(int sub_api, struct libusb_context *ctx);
61 static int winusbx_exit(int sub_api);
62 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
63 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
64 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
65 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
66 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
67 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
68 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
69 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
70 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
71 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
72 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
73 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
74 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
76 static int hid_init(int sub_api, struct libusb_context *ctx);
77 static int hid_exit(int sub_api);
78 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
79 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
80 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
81 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
82 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
83 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
84 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
85 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
86 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
87 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
88 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
89 // Composite API prototypes
90 static int composite_init(int sub_api, struct libusb_context *ctx);
91 static int composite_exit(int sub_api);
92 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
93 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
94 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
95 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
96 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
97 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
98 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
99 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
100 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
101 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
102 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
103 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
104 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
108 int windows_version = WINDOWS_UNDEFINED;
109 static char windows_version_str[128] = "Undefined";
111 static int concurrent_usage = -1;
112 static usbi_mutex_t autoclaim_lock;
114 #define CHECK_WINUSBX_AVAILABLE(sub_api) \
116 if (sub_api == SUB_API_NOTSET) \
117 sub_api = priv->sub_api; \
118 if (!WinUSBX[sub_api].initialized) \
119 return LIBUSB_ERROR_ACCESS; \
122 static HMODULE WinUSBX_handle = NULL;
123 static struct winusb_interface WinUSBX[SUB_API_MAX];
124 static const char *sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
126 static bool api_hid_available = false;
127 #define CHECK_HID_AVAILABLE \
129 if (!api_hid_available) \
130 return LIBUSB_ERROR_ACCESS; \
133 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2)
135 if ((guid1 != NULL) && (guid2 != NULL))
136 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
141 #if defined(ENABLE_LOGGING)
142 static char *guid_to_string(const GUID *guid)
144 static char guid_string[MAX_GUID_STRING_LENGTH];
149 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
150 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
151 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
152 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
159 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
160 * Return an allocated sanitized string or NULL on error.
162 static char *sanitize_path(const char *path)
164 const char root_prefix[] = { '\\', '\\', '.', '\\' };
172 size = strlen(path) + 1;
174 // Microsoft indiscriminately uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
175 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\'))
176 || ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
177 add_root = sizeof(root_prefix);
181 ret_path = malloc(size);
182 if (ret_path == NULL)
185 strcpy(&ret_path[add_root], path);
187 // Ensure consistency with root prefix
188 memcpy(ret_path, root_prefix, sizeof(root_prefix));
190 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
191 for (j = sizeof(root_prefix); j < size; j++) {
192 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
193 if (ret_path[j] == '\\')
201 * Cfgmgr32, OLE32 and SetupAPI DLL functions
203 static int init_dlls(void)
205 DLL_GET_HANDLE(Cfgmgr32);
206 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Parent, TRUE);
207 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Child, TRUE);
208 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Sibling, TRUE);
209 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Device_IDA, TRUE);
211 // Prefixed to avoid conflict with header files
212 DLL_GET_HANDLE(AdvAPI32);
213 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegQueryValueExW, TRUE);
214 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegCloseKey, TRUE);
216 DLL_GET_HANDLE(Kernel32);
217 DLL_LOAD_FUNC_PREFIXED(Kernel32, p, IsWow64Process, FALSE);
219 DLL_GET_HANDLE(OLE32);
220 DLL_LOAD_FUNC_PREFIXED(OLE32, p, CLSIDFromString, TRUE);
222 DLL_GET_HANDLE(SetupAPI);
223 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetClassDevsA, TRUE);
224 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInfo, TRUE);
225 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInterfaces, TRUE);
226 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
227 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiDestroyDeviceInfoList, TRUE);
228 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDevRegKey, TRUE);
229 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
230 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
232 return LIBUSB_SUCCESS;
235 static void exit_dlls(void)
237 DLL_FREE_HANDLE(Cfgmgr32);
238 DLL_FREE_HANDLE(AdvAPI32);
239 DLL_FREE_HANDLE(Kernel32);
240 DLL_FREE_HANDLE(OLE32);
241 DLL_FREE_HANDLE(SetupAPI);
245 * enumerate interfaces for the whole USB class
248 * dev_info: a pointer to a dev_info list
249 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
250 * usb_class: the generic USB class for which to retrieve interface details
251 * index: zero based index of the interface in the device info list
253 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
254 * structure returned and call this function repeatedly using the same guid (with an
255 * incremented index starting at zero) until all interfaces have been returned.
257 static bool get_devinfo_data(struct libusb_context *ctx,
258 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char *usb_class, unsigned _index)
261 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
262 if (*dev_info == INVALID_HANDLE_VALUE)
266 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
267 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
268 if (GetLastError() != ERROR_NO_MORE_ITEMS)
269 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
270 _index, windows_error_str(0));
272 pSetupDiDestroyDeviceInfoList(*dev_info);
273 *dev_info = INVALID_HANDLE_VALUE;
280 * enumerate interfaces for a specific GUID
283 * dev_info: a pointer to a dev_info list
284 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
285 * guid: the GUID for which to retrieve interface details
286 * index: zero based index of the interface in the device info list
288 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
289 * structure returned and call this function repeatedly using the same guid (with an
290 * incremented index starting at zero) until all interfaces have been returned.
292 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
293 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index)
295 SP_DEVICE_INTERFACE_DATA dev_interface_data;
296 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details;
300 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
302 if (dev_info_data != NULL) {
303 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
304 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
305 if (GetLastError() != ERROR_NO_MORE_ITEMS)
306 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
307 _index, windows_error_str(0));
309 pSetupDiDestroyDeviceInfoList(*dev_info);
310 *dev_info = INVALID_HANDLE_VALUE;
315 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
316 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
317 if (GetLastError() != ERROR_NO_MORE_ITEMS)
318 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
319 _index, windows_error_str(0));
321 pSetupDiDestroyDeviceInfoList(*dev_info);
322 *dev_info = INVALID_HANDLE_VALUE;
326 // Read interface data (dummy + actual) to access the device path
327 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
328 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
329 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
330 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
331 _index, windows_error_str(0));
335 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
339 dev_interface_details = calloc(1, size);
340 if (dev_interface_details == NULL) {
341 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
345 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
346 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
347 dev_interface_details, size, &size, NULL)) {
348 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
349 _index, windows_error_str(0));
352 return dev_interface_details;
355 pSetupDiDestroyDeviceInfoList(*dev_info);
356 *dev_info = INVALID_HANDLE_VALUE;
360 /* For libusb0 filter */
361 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
362 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index, char *filter_path)
364 SP_DEVICE_INTERFACE_DATA dev_interface_data;
365 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details;
369 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
371 if (dev_info_data != NULL) {
372 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
373 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
374 if (GetLastError() != ERROR_NO_MORE_ITEMS)
375 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
376 _index, windows_error_str(0));
378 pSetupDiDestroyDeviceInfoList(*dev_info);
379 *dev_info = INVALID_HANDLE_VALUE;
384 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
385 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
386 if (GetLastError() != ERROR_NO_MORE_ITEMS)
387 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
388 _index, windows_error_str(0));
390 pSetupDiDestroyDeviceInfoList(*dev_info);
391 *dev_info = INVALID_HANDLE_VALUE;
395 // Read interface data (dummy + actual) to access the device path
396 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
397 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
398 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
399 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
400 _index, windows_error_str(0));
404 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
408 dev_interface_details = calloc(1, size);
409 if (dev_interface_details == NULL) {
410 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
414 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
415 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, dev_interface_details, size, &size, NULL))
416 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
417 _index, windows_error_str(0));
419 // [trobinso] lookup the libusb0 symbolic index.
420 if (dev_interface_details) {
421 HKEY hkey_device_interface = pSetupDiOpenDeviceInterfaceRegKey(*dev_info, &dev_interface_data, 0, KEY_READ);
422 if (hkey_device_interface != INVALID_HANDLE_VALUE) {
423 DWORD libusb0_symboliclink_index = 0;
424 DWORD value_length = sizeof(DWORD);
425 DWORD value_type = 0;
428 status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
429 (LPBYTE)&libusb0_symboliclink_index, &value_length);
430 if (status == ERROR_SUCCESS) {
431 if (libusb0_symboliclink_index < 256) {
432 // libusb0.sys is connected to this device instance.
433 // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
434 sprintf(filter_path, "\\\\.\\libusb0-%04u", (unsigned int)libusb0_symboliclink_index);
435 usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
437 // libusb0.sys was connected to this device instance at one time; but not anymore.
440 pRegCloseKey(hkey_device_interface);
444 return dev_interface_details;
447 pSetupDiDestroyDeviceInfoList(*dev_info);
448 *dev_info = INVALID_HANDLE_VALUE;
453 * Returns the session ID of a device's nth level ancestor
454 * If there's no device at the nth level, return 0
456 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
458 DWORD parent_devinst;
459 unsigned long session_id;
460 char *sanitized_path;
461 char path[MAX_PATH_LENGTH];
467 for (i = 0; i < level; i++) {
468 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS)
470 devinst = parent_devinst;
473 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS)
476 // TODO: (post hotplug): try without sanitizing
477 sanitized_path = sanitize_path(path);
478 if (sanitized_path == NULL)
481 session_id = htab_hash(sanitized_path);
482 free(sanitized_path);
487 * Determine which interface the given endpoint address belongs to
489 static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep)
491 const struct libusb_interface *intf;
492 const struct libusb_interface_descriptor *intf_desc;
495 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
496 intf = &conf_desc->interface[i];
497 for (j = 0; j < intf->num_altsetting; j++) {
498 intf_desc = &intf->altsetting[j];
499 for (k = 0; k < intf_desc->bNumEndpoints; k++) {
500 if (intf_desc->endpoint[k].bEndpointAddress == ep) {
501 usbi_dbg("found endpoint %02X on interface %d", intf_desc->bInterfaceNumber, i);
502 return intf_desc->bInterfaceNumber;
508 usbi_dbg("endpoint %02X not found on any interface", ep);
509 return LIBUSB_ERROR_NOT_FOUND;
513 * Populate the endpoints addresses of the device_priv interface helper structs
515 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
518 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
519 struct libusb_config_descriptor *conf_desc;
520 const struct libusb_interface_descriptor *if_desc;
521 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
523 r = libusb_get_active_config_descriptor(dev_handle->dev, &conf_desc);
524 if (r != LIBUSB_SUCCESS) {
525 usbi_warn(ctx, "could not read config descriptor: error %d", r);
529 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
530 safe_free(priv->usb_interface[iface].endpoint);
532 if (if_desc->bNumEndpoints == 0) {
533 usbi_dbg("no endpoints found for interface %d", iface);
534 libusb_free_config_descriptor(conf_desc);
535 return LIBUSB_SUCCESS;
538 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
539 if (priv->usb_interface[iface].endpoint == NULL) {
540 libusb_free_config_descriptor(conf_desc);
541 return LIBUSB_ERROR_NO_MEM;
544 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
545 for (i = 0; i < if_desc->bNumEndpoints; i++) {
546 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
547 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
549 libusb_free_config_descriptor(conf_desc);
551 // Extra init may be required to configure endpoints
552 return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
555 // Lookup for a match in the list of API driver names
556 // return -1 if not found, driver match number otherwise
557 static int get_sub_api(char *driver, int api)
560 const char sep_str[2] = {LIST_SEPARATOR, 0};
562 size_t len = strlen(driver);
565 return SUB_API_NOTSET;
567 tmp_str = _strdup(driver);
569 return SUB_API_NOTSET;
571 tok = strtok(tmp_str, sep_str);
572 while (tok != NULL) {
573 for (i = 0; i < usb_api_backend[api].nb_driver_names; i++) {
574 if (_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
579 tok = strtok(NULL, sep_str);
583 return SUB_API_NOTSET;
587 * auto-claiming and auto-release helper functions
589 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
591 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
592 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
593 transfer->dev_handle);
594 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
595 int current_interface = *interface_number;
596 int r = LIBUSB_SUCCESS;
599 case USB_API_WINUSBX:
603 return LIBUSB_ERROR_INVALID_PARAM;
606 usbi_mutex_lock(&autoclaim_lock);
607 if (current_interface < 0) { // No serviceable interface was found
608 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
609 // Must claim an interface of the same API type
610 if ((priv->usb_interface[current_interface].apib->id == api_type)
611 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS)) {
612 usbi_dbg("auto-claimed interface %d for control request", current_interface);
613 if (handle_priv->autoclaim_count[current_interface] != 0)
614 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
615 handle_priv->autoclaim_count[current_interface]++;
619 if (current_interface == USB_MAXINTERFACES) {
620 usbi_err(ctx, "could not auto-claim any interface");
621 r = LIBUSB_ERROR_NOT_FOUND;
624 // If we have a valid interface that was autoclaimed, we must increment
625 // its autoclaim count so that we can prevent an early release.
626 if (handle_priv->autoclaim_count[current_interface] != 0)
627 handle_priv->autoclaim_count[current_interface]++;
629 usbi_mutex_unlock(&autoclaim_lock);
631 *interface_number = current_interface;
635 static void auto_release(struct usbi_transfer *itransfer)
637 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
638 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
639 libusb_device_handle *dev_handle = transfer->dev_handle;
640 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
643 usbi_mutex_lock(&autoclaim_lock);
644 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
645 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
646 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
647 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
648 if (r == LIBUSB_SUCCESS)
649 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
651 usbi_dbg("failed to auto-release interface %d (%s)",
652 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
655 usbi_mutex_unlock(&autoclaim_lock);
658 /* Windows version dtection */
659 static BOOL is_x64(void)
663 // Detect if we're running a 32 or 64 bit system
664 if (sizeof(uintptr_t) < 8) {
665 if (pIsWow64Process != NULL)
666 pIsWow64Process(GetCurrentProcess(), &ret);
674 static void get_windows_version(void)
676 OSVERSIONINFOEXA vi, vi2;
677 const char *arch, *w = NULL;
678 unsigned major, minor;
679 ULONGLONG major_equal, minor_equal;
682 memset(&vi, 0, sizeof(vi));
683 vi.dwOSVersionInfoSize = sizeof(vi);
684 if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
685 memset(&vi, 0, sizeof(vi));
686 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
687 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
691 if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
692 if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) {
693 // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
694 // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
696 major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
697 for (major = vi.dwMajorVersion; major <= 9; major++) {
698 memset(&vi2, 0, sizeof(vi2));
699 vi2.dwOSVersionInfoSize = sizeof(vi2);
700 vi2.dwMajorVersion = major;
701 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
704 if (vi.dwMajorVersion < major) {
705 vi.dwMajorVersion = major;
706 vi.dwMinorVersion = 0;
709 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
710 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
711 memset(&vi2, 0, sizeof(vi2));
712 vi2.dwOSVersionInfoSize = sizeof(vi2);
713 vi2.dwMinorVersion = minor;
714 if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
717 vi.dwMinorVersion = minor;
725 if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) {
726 ws = (vi.wProductType <= VER_NT_WORKSTATION);
727 windows_version = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
728 switch (windows_version) {
729 case 0x50: w = "2000"; break;
730 case 0x51: w = "XP"; break;
731 case 0x52: w = "2003"; break;
732 case 0x60: w = (ws ? "Vista" : "2008"); break;
733 case 0x61: w = (ws ? "7" : "2008_R2"); break;
734 case 0x62: w = (ws ? "8" : "2012"); break;
735 case 0x63: w = (ws ? "8.1" : "2012_R2"); break;
736 case 0x64: w = (ws ? "10" : "2015"); break;
738 if (windows_version < 0x50)
739 windows_version = WINDOWS_UNSUPPORTED;
747 arch = is_x64() ? "64-bit" : "32-bit";
750 snprintf(windows_version_str, sizeof(windows_version_str), "%s %u.%u %s",
751 (vi.dwPlatformId == VER_PLATFORM_WIN32_NT ? "NT" : "??"),
752 (unsigned int)vi.dwMajorVersion, (unsigned int)vi.dwMinorVersion, arch);
753 else if (vi.wServicePackMinor)
754 snprintf(windows_version_str, sizeof(windows_version_str), "%s SP%u.%u %s",
755 w, vi.wServicePackMajor, vi.wServicePackMinor, arch);
756 else if (vi.wServicePackMajor)
757 snprintf(windows_version_str, sizeof(windows_version_str), "%s SP%u %s",
758 w, vi.wServicePackMajor, arch);
760 snprintf(windows_version_str, sizeof(windows_version_str), "%s %s",
765 * init: libusb backend init function
767 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
768 * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed.
769 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
771 static int windows_init(struct libusb_context *ctx)
773 int i, r = LIBUSB_ERROR_OTHER;
775 char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
777 sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
778 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
779 if (semaphore == NULL) {
780 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
781 return LIBUSB_ERROR_NO_MEM;
784 // A successful wait brings our semaphore count to 0 (unsignaled)
785 // => any concurent wait stalls until the semaphore's release
786 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
787 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
788 CloseHandle(semaphore);
789 return LIBUSB_ERROR_NO_MEM;
792 // NB: concurrent usage supposes that init calls are equally balanced with
793 // exit calls. If init is called more than exit, we will not exit properly
794 if (++concurrent_usage == 0) { // First init?
795 get_windows_version();
796 usbi_dbg("Windows %s", windows_version_str);
798 if (windows_version == WINDOWS_UNSUPPORTED) {
799 usbi_err(ctx, "This version of Windows is NOT supported");
800 r = LIBUSB_ERROR_NOT_SUPPORTED;
804 // We need a lock for proper auto-release
805 usbi_mutex_init(&autoclaim_lock);
807 // Initialize pollable file descriptors
811 if (init_dlls() != LIBUSB_SUCCESS) {
812 usbi_err(ctx, "could not resolve DLL functions");
816 // Initialize the low level APIs (we don't care about errors at this stage)
817 for (i = 0; i < USB_API_MAX; i++)
818 usb_api_backend[i].init(SUB_API_NOTSET, ctx);
820 r = windows_common_init(ctx);
824 // At this stage, either we went through full init successfully, or didn't need to
827 init_exit: // Holds semaphore here.
828 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
829 for (i = 0; i < USB_API_MAX; i++)
830 usb_api_backend[i].exit(SUB_API_NOTSET);
833 windows_common_exit();
834 usbi_mutex_destroy(&autoclaim_lock);
837 if (r != LIBUSB_SUCCESS)
838 --concurrent_usage; // Not expected to call libusb_exit if we failed.
840 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
841 CloseHandle(semaphore);
846 * HCD (root) hubs need to have their device descriptor manually populated
848 * Note that, like Microsoft does in the device manager, we populate the
849 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
851 static int force_hcd_device_descriptor(struct libusb_device *dev)
853 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
854 struct libusb_context *ctx = DEVICE_CTX(dev);
857 dev->num_configurations = 1;
858 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
859 priv->dev_descriptor.bDescriptorType = LIBUSB_DT_DEVICE;
860 priv->dev_descriptor.bNumConfigurations = 1;
861 priv->active_config = 1;
863 if (dev->parent_dev == NULL) {
864 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
865 return LIBUSB_ERROR_NO_DEVICE;
868 parent_priv = _device_priv(dev->parent_dev);
869 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
870 priv->dev_descriptor.idVendor = (uint16_t)vid;
871 priv->dev_descriptor.idProduct = (uint16_t)pid;
873 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
874 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
875 priv->dev_descriptor.idProduct = 1;
878 return LIBUSB_SUCCESS;
882 * fetch and cache all the config descriptors through I/O
884 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char *device_id)
886 DWORD size, ret_size;
887 struct libusb_context *ctx = DEVICE_CTX(dev);
888 struct windows_device_priv *priv = _device_priv(dev);
892 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
893 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
894 PUSB_CONFIGURATION_DESCRIPTOR cd_data;
896 if (dev->num_configurations == 0)
897 return LIBUSB_ERROR_INVALID_PARAM;
899 priv->config_descriptor = calloc(dev->num_configurations, sizeof(unsigned char *));
900 if (priv->config_descriptor == NULL)
901 return LIBUSB_ERROR_NO_MEM;
903 for (i = 0, r = LIBUSB_SUCCESS; ; i++) {
904 // safe loop: release all dynamic resources
905 safe_free(cd_buf_actual);
907 // safe loop: end of loop condition
908 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
911 size = sizeof(cd_buf_short);
912 memset(&cd_buf_short, 0, size);
914 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
915 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
916 cd_buf_short.req.SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
917 cd_buf_short.req.SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
918 cd_buf_short.req.SetupPacket.wIndex = 0;
919 cd_buf_short.req.SetupPacket.wLength = (USHORT)sizeof(USB_CONFIGURATION_DESCRIPTOR);
921 // Dummy call to get the required data size. Initial failures are reported as info rather
922 // than error as they can occur for non-penalizing situations, such as with some hubs.
923 // coverity[tainted_data_argument]
924 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
925 &cd_buf_short, size, &ret_size, NULL)) {
926 usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
927 LOOP_BREAK(LIBUSB_ERROR_IO);
930 if ((ret_size != size) || (cd_buf_short.desc.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
931 usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
932 LOOP_BREAK(LIBUSB_ERROR_IO);
935 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.desc.wTotalLength;
936 cd_buf_actual = calloc(1, size);
937 if (cd_buf_actual == NULL) {
938 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
939 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
943 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
944 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
945 cd_buf_actual->SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
946 cd_buf_actual->SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
947 cd_buf_actual->SetupPacket.wIndex = 0;
948 cd_buf_actual->SetupPacket.wLength = cd_buf_short.desc.wTotalLength;
950 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
951 cd_buf_actual, size, &ret_size, NULL)) {
952 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
953 LOOP_BREAK(LIBUSB_ERROR_IO);
956 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR *)cd_buf_actual + sizeof(USB_DESCRIPTOR_REQUEST));
958 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.desc.wTotalLength)) {
959 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
960 LOOP_BREAK(LIBUSB_ERROR_IO);
963 if (cd_data->bDescriptorType != LIBUSB_DT_CONFIG) {
964 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
965 LOOP_BREAK(LIBUSB_ERROR_IO);
968 usbi_dbg("cached config descriptor %d (bConfigurationValue=%u, %u bytes)",
969 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
971 // Cache the descriptor
972 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
973 if (priv->config_descriptor[i] == NULL)
974 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
975 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
978 // Any failure will result in dev->num_configurations being forced to 0.
979 // We need to release any memory that may have been allocated for config
980 // descriptors that were successfully retrieved, otherwise that memory
982 if (r != LIBUSB_SUCCESS) {
983 for (i = 0; i < dev->num_configurations; i++)
984 free(priv->config_descriptor[i]);
991 * Populate a libusb device structure
993 static int init_device(struct libusb_device *dev, struct libusb_device *parent_dev,
994 uint8_t port_number, char *device_id, DWORD devinst)
998 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
999 USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
1000 struct windows_device_priv *priv, *parent_priv;
1001 struct libusb_context *ctx;
1002 struct libusb_device *tmp_dev;
1003 unsigned long tmp_id;
1006 if ((dev == NULL) || (parent_dev == NULL))
1007 return LIBUSB_ERROR_NOT_FOUND;
1009 ctx = DEVICE_CTX(dev);
1010 priv = _device_priv(dev);
1011 parent_priv = _device_priv(parent_dev);
1012 if (parent_priv->apib->id != USB_API_HUB) {
1013 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1014 return LIBUSB_ERROR_NOT_FOUND;
1017 // It is possible for the parent hub not to have been initialized yet
1018 // If that's the case, lookup the ancestors to set the bus number
1019 if (parent_dev->bus_number == 0) {
1020 for (i = 2; ; i++) {
1021 tmp_id = get_ancestor_session_id(devinst, i);
1025 tmp_dev = usbi_get_device_by_session_id(ctx, tmp_id);
1026 if (tmp_dev == NULL)
1029 if (tmp_dev->bus_number != 0) {
1030 usbi_dbg("got bus number from ancestor #%u", i);
1031 parent_dev->bus_number = tmp_dev->bus_number;
1032 libusb_unref_device(tmp_dev);
1036 libusb_unref_device(tmp_dev);
1040 if (parent_dev->bus_number == 0) {
1041 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1042 return LIBUSB_ERROR_NOT_FOUND;
1045 dev->bus_number = parent_dev->bus_number;
1046 priv->port = port_number;
1047 dev->port_number = port_number;
1048 priv->depth = parent_priv->depth + 1;
1049 dev->parent_dev = parent_dev;
1051 // If the device address is already set, we can stop here
1052 if (dev->device_address != 0)
1053 return LIBUSB_SUCCESS;
1055 memset(&conn_info, 0, sizeof(conn_info));
1056 if (priv->depth != 0) { // Not a HCD hub
1057 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1058 FILE_FLAG_OVERLAPPED, NULL);
1059 if (handle == INVALID_HANDLE_VALUE) {
1060 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1061 return LIBUSB_ERROR_ACCESS;
1064 size = sizeof(conn_info);
1065 conn_info.ConnectionIndex = (ULONG)port_number;
1066 // coverity[tainted_data_argument]
1067 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1068 &conn_info, size, &size, NULL)) {
1069 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1070 device_id, windows_error_str(0));
1071 CloseHandle(handle);
1072 return LIBUSB_ERROR_NO_DEVICE;
1075 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1076 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1077 CloseHandle(handle);
1078 return LIBUSB_ERROR_NO_DEVICE;
1081 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1082 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1083 priv->active_config = conn_info.CurrentConfigurationValue;
1084 usbi_dbg("found %u configurations (active conf: %u)", dev->num_configurations, priv->active_config);
1086 // If we can't read the config descriptors, just set the number of confs to zero
1087 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1088 dev->num_configurations = 0;
1089 priv->dev_descriptor.bNumConfigurations = 0;
1092 // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
1093 if (windows_version >= WINDOWS_8) {
1094 memset(&conn_info_v2, 0, sizeof(conn_info_v2));
1095 size = sizeof(conn_info_v2);
1096 conn_info_v2.ConnectionIndex = (ULONG)port_number;
1097 conn_info_v2.Length = size;
1098 conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
1099 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
1100 &conn_info_v2, size, &conn_info_v2, size, &size, NULL)) {
1101 usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
1102 device_id, windows_error_str(0));
1103 } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
1104 conn_info.Speed = 3;
1108 CloseHandle(handle);
1110 if (conn_info.DeviceAddress > UINT8_MAX)
1111 usbi_err(ctx, "program assertion failed: device address overflow");
1113 dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
1114 if (dev->device_address == 1)
1115 usbi_err(ctx, "program assertion failed: device address collision with root hub");
1117 switch (conn_info.Speed) {
1118 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1119 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1120 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1121 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1123 usbi_warn(ctx, "Got unknown device speed %u", conn_info.Speed);
1127 dev->device_address = 1; // root hubs are set to use device number 1
1128 force_hcd_device_descriptor(dev);
1131 usbi_sanitize_device(dev);
1133 usbi_dbg("(bus: %u, addr: %u, depth: %u, port: %u): '%s'",
1134 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1136 return LIBUSB_SUCCESS;
1139 // Returns the api type, or 0 if not found/unsupported
1140 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
1141 SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
1143 // Precedence for filter drivers vs driver is in the order of this array
1144 struct driver_lookup lookup[3] = {
1145 {"\0\0", SPDRP_SERVICE, "driver"},
1146 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1147 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1149 DWORD size, reg_type;
1153 *api = USB_API_UNSUPPORTED;
1154 *sub_api = SUB_API_NOTSET;
1156 // Check the service & filter names to know the API we should use
1157 for (k = 0; k < 3; k++) {
1158 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1159 ®_type, (BYTE *)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1160 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1161 if (lookup[k].reg_prop == SPDRP_SERVICE)
1162 // our buffers are MAX_KEY_LENGTH + 1 so we can overflow if needed
1163 lookup[k].list[strlen(lookup[k].list) + 1] = 0;
1165 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1166 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1167 // (currently ';'), so even if an unsuported one does, it's not an issue
1168 for (l = 0; (lookup[k].list[l] != 0) || (lookup[k].list[l + 1] != 0); l++) {
1169 if (lookup[k].list[l] == 0)
1170 lookup[k].list[l] = LIST_SEPARATOR;
1172 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1174 if (GetLastError() != ERROR_INVALID_DATA)
1175 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1176 lookup[k].list[0] = 0;
1180 for (i = 1; i < USB_API_MAX; i++) {
1181 for (k = 0; k < 3; k++) {
1182 j = get_sub_api(lookup[k].list, i);
1184 usbi_dbg("matched %s name against %s", lookup[k].designation,
1185 (i != USB_API_WINUSBX) ? usb_api_backend[i].designation : sub_api_name[j]);
1194 static int set_composite_interface(struct libusb_context *ctx, struct libusb_device *dev,
1195 char *dev_interface_path, char *device_id, int api, int sub_api)
1198 struct windows_device_priv *priv = _device_priv(dev);
1199 int interface_number;
1201 if (priv->apib->id != USB_API_COMPOSITE) {
1202 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1203 return LIBUSB_ERROR_NO_DEVICE;
1206 // Because MI_## are not necessarily in sequential order (some composite
1207 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1208 // interface number from the path's MI value
1209 interface_number = 0;
1210 for (i = 0; device_id[i] != 0; ) {
1211 if ((device_id[i++] == 'M') && (device_id[i++] == 'I')
1212 && (device_id[i++] == '_')) {
1213 interface_number = (device_id[i++] - '0') * 10;
1214 interface_number += device_id[i] - '0';
1219 if (device_id[i] == 0)
1220 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1221 device_id, interface_number);
1223 if (priv->usb_interface[interface_number].path != NULL) {
1224 if (api == USB_API_HID) {
1225 // HID devices can have multiple collections (COL##) for each MI_## interface
1226 usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1227 interface_number, device_id);
1228 return LIBUSB_ERROR_ACCESS;
1230 // In other cases, just use the latest data
1231 safe_free(priv->usb_interface[interface_number].path);
1234 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1235 priv->usb_interface[interface_number].path = dev_interface_path;
1236 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1237 priv->usb_interface[interface_number].sub_api = sub_api;
1238 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1239 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1240 if (priv->hid == NULL)
1241 return LIBUSB_ERROR_NO_MEM;
1244 return LIBUSB_SUCCESS;
1247 static int set_hid_interface(struct libusb_context *ctx, struct libusb_device *dev,
1248 char *dev_interface_path)
1251 struct windows_device_priv *priv = _device_priv(dev);
1253 if (priv->hid == NULL) {
1254 usbi_err(ctx, "program assertion failed: parent is not HID");
1255 return LIBUSB_ERROR_NO_DEVICE;
1256 } else if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1257 usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
1258 return LIBUSB_ERROR_NO_DEVICE;
1261 for (i = 0; i < priv->hid->nb_interfaces; i++) {
1262 if ((priv->usb_interface[i].path != NULL) && strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1263 usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
1264 return LIBUSB_ERROR_ACCESS;
1268 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1269 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1270 usbi_dbg("interface[%u] = %s", priv->hid->nb_interfaces, dev_interface_path);
1271 priv->hid->nb_interfaces++;
1272 return LIBUSB_SUCCESS;
1276 * get_device_list: libusb backend device enumeration function
1278 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1280 struct discovered_devs *discdevs;
1281 HDEVINFO dev_info = { 0 };
1282 const char *usb_class[] = {"USB", "NUSB3", "IUSB3", "IARUSB3"};
1283 SP_DEVINFO_DATA dev_info_data = { 0 };
1284 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1286 #define MAX_ENUM_GUIDS 64
1287 const GUID *guid[MAX_ENUM_GUIDS];
1293 int r = LIBUSB_SUCCESS;
1295 size_t class_index = 0;
1296 unsigned int nb_guids, pass, i, j, ancestor;
1297 char path[MAX_PATH_LENGTH];
1298 char strbuf[MAX_PATH_LENGTH];
1299 struct libusb_device *dev, *parent_dev;
1300 struct windows_device_priv *priv, *parent_priv;
1301 char *dev_interface_path = NULL;
1302 char *dev_id_path = NULL;
1303 unsigned long session_id;
1304 DWORD size, reg_type, port_nr, install_state;
1306 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1309 // Keep a list of newly allocated devs to unref
1310 libusb_device **unref_list, **new_unref_list;
1311 unsigned int unref_size = 64;
1312 unsigned int unref_cur = 0;
1314 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1315 // PASS 2 : (re)enumerate HUBS
1316 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1317 // and list additional USB device interface GUIDs to explore
1318 // PASS 4 : (re)enumerate master USB devices that have a device interface
1319 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1320 // set the device interfaces.
1322 // Init the GUID table
1323 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1324 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1325 guid[GEN_PASS] = NULL;
1326 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1327 HidD_GetHidGuid(&hid_guid);
1328 guid[HID_PASS] = &hid_guid;
1329 nb_guids = HID_PASS + 1;
1331 unref_list = calloc(unref_size, sizeof(libusb_device *));
1332 if (unref_list == NULL)
1333 return LIBUSB_ERROR_NO_MEM;
1335 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1336 //#define ENUM_DEBUG
1337 #if defined(ENABLE_LOGGING) && defined(ENUM_DEBUG)
1338 const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
1339 usbi_dbg("#### PROCESSING %ss %s", passname[(pass <= HID_PASS) ? pass : (HID_PASS + 1)],
1340 (pass != GEN_PASS) ? guid_to_string(guid[pass]) : "");
1342 for (i = 0; ; i++) {
1343 // safe loop: free up any (unprotected) dynamic resource
1344 // NB: this is always executed before breaking the loop
1345 safe_free(dev_interface_details);
1346 safe_free(dev_interface_path);
1347 safe_free(dev_id_path);
1348 priv = parent_priv = NULL;
1349 dev = parent_dev = NULL;
1351 // Safe loop: end of loop conditions
1352 if (r != LIBUSB_SUCCESS)
1355 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1356 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1360 if (pass != GEN_PASS) {
1361 // Except for GEN, all passes deal with device interfaces
1362 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1363 if (dev_interface_details == NULL)
1366 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1367 if (dev_interface_path == NULL) {
1368 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1372 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1373 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1374 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1375 // The Intel Alpine Ridge USB 3.1 driver uses "IARUSB3"
1376 for (; class_index < ARRAYSIZE(usb_class); class_index++) {
1377 if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
1381 if (class_index >= ARRAYSIZE(usb_class))
1385 // Read the Device ID path. This is what we'll use as UID
1386 // Note that if the device is plugged in a different port or hub, the Device ID changes
1387 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1388 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1389 (unsigned int)dev_info_data.DevInst);
1393 dev_id_path = sanitize_path(path);
1394 if (dev_id_path == NULL) {
1395 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1396 (unsigned int)dev_info_data.DevInst);
1400 usbi_dbg("PRO: %s", dev_id_path);
1403 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1405 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1406 if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1407 ®_type, (BYTE *)&port_nr, 4, &size)) || (size != 4)) {
1408 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1409 dev_id_path, windows_error_str(0));
1414 // Set API to use or get additional data from generic pass
1415 api = USB_API_UNSUPPORTED;
1416 sub_api = SUB_API_NOTSET;
1421 // We use the GEN pass to detect driverless devices...
1422 size = sizeof(strbuf);
1423 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1424 ®_type, (BYTE *)strbuf, size, &size)) {
1425 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1426 usbi_info(ctx, "libusb will not be able to access it.");
1428 // ...and to add the additional device interface GUIDs
1429 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1430 if (key != INVALID_HANDLE_VALUE) {
1431 size = sizeof(guid_string_w);
1432 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1433 (BYTE *)guid_string_w, &size);
1435 if (s == ERROR_SUCCESS) {
1436 if (nb_guids >= MAX_ENUM_GUIDS) {
1437 // If this assert is ever reported, grow a GUID table dynamically
1438 usbi_err(ctx, "program assertion failed: too many GUIDs");
1439 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1441 if_guid = calloc(1, sizeof(GUID));
1442 if (if_guid == NULL) {
1443 usbi_err(ctx, "could not calloc for if_guid: not enough memory");
1444 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1446 pCLSIDFromString(guid_string_w, if_guid);
1447 guid[nb_guids++] = if_guid;
1448 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1456 // Get the API type (after checking that the driver installation is OK)
1457 if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1458 ®_type, (BYTE *)&install_state, 4, &size)) || (size != 4)) {
1459 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1460 dev_id_path, windows_error_str(0));
1461 } else if (install_state != 0) {
1462 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %u) - skipping",
1463 dev_id_path, (unsigned int)install_state);
1466 get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
1470 // Find parent device (for the passes that need it)
1477 // Go through the ancestors until we see a face we recognize
1479 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1480 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1481 if (session_id == 0)
1484 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1487 if (parent_dev == NULL) {
1488 usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1492 parent_priv = _device_priv(parent_dev);
1493 // virtual USB devices are also listed during GEN - don't process these yet
1494 if ((pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB)) {
1495 libusb_unref_device(parent_dev);
1502 // Create new or match existing device, using the (hashed) device_id as session id
1503 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1504 // These are the passes that create "new" devices
1505 session_id = htab_hash(dev_id_path);
1506 dev = usbi_get_device_by_session_id(ctx, session_id);
1508 if (pass == DEV_PASS) {
1509 // This can occur if the OS only reports a newly plugged device after we started enum
1510 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1511 " - ignoring", dev_id_path);
1515 usbi_dbg("allocating new device for session [%lX]", session_id);
1516 dev = usbi_alloc_device(ctx, session_id);
1518 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1520 priv = windows_device_priv_init(dev);
1522 usbi_dbg("found existing device for session [%lX] (%u.%u)",
1523 session_id, dev->bus_number, dev->device_address);
1525 priv = _device_priv(dev);
1526 if ((parent_dev != NULL) && (dev->parent_dev != NULL)) {
1527 if (dev->parent_dev != parent_dev) {
1528 // It is possible for the actual parent device to not have existed at the
1529 // time of enumeration, so the currently assigned parent may in fact be a
1530 // grandparent. If the devices differ, we assume the "new" parent device
1531 // is in fact closer to the device.
1532 usbi_dbg("updating parent device [session %lX -> %lX]",
1533 dev->parent_dev->session_data, parent_dev->session_data);
1534 libusb_unref_device(dev->parent_dev);
1535 dev->parent_dev = parent_dev;
1537 // We hold a reference to parent_dev instance, but this device already
1538 // has a parent_dev reference (only one per child)
1539 libusb_unref_device(parent_dev);
1544 // Keep track of devices that need unref
1545 unref_list[unref_cur++] = dev;
1546 if (unref_cur >= unref_size) {
1548 new_unref_list = usbi_reallocf(unref_list, unref_size * sizeof(libusb_device *));
1549 if (new_unref_list == NULL) {
1550 usbi_err(ctx, "could not realloc list for unref - aborting.");
1551 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1553 unref_list = new_unref_list;
1561 // If the hcd has already been setup, don't do it again
1562 if (priv->path != NULL)
1564 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1565 dev->device_address = 0;
1566 dev->num_configurations = 0;
1567 priv->apib = &usb_api_backend[USB_API_HUB];
1568 priv->sub_api = SUB_API_NOTSET;
1569 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1570 priv->path = dev_interface_path;
1571 dev_interface_path = NULL;
1575 // If the device has already been setup, don't do it again
1576 if (priv->path != NULL)
1578 // Take care of API initialization
1579 priv->path = dev_interface_path;
1580 dev_interface_path = NULL;
1581 priv->apib = &usb_api_backend[api];
1582 priv->sub_api = sub_api;
1584 case USB_API_COMPOSITE:
1588 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1589 if (priv->hid == NULL)
1590 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1592 priv->hid->nb_interfaces = 0;
1595 // For other devices, the first interface is the same as the device
1596 priv->usb_interface[0].path = _strdup(priv->path);
1597 if (priv->usb_interface[0].path == NULL)
1598 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1599 // The following is needed if we want API calls to work for both simple
1600 // and composite devices.
1601 for (j = 0; j < USB_MAXINTERFACES; j++)
1602 priv->usb_interface[j].apib = &usb_api_backend[api];
1608 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1609 if (r == LIBUSB_SUCCESS) {
1610 // Append device to the list of discovered devices
1611 discdevs = discovered_devs_append(*_discdevs, dev);
1613 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1615 *_discdevs = discdevs;
1616 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1617 // This can occur if the device was disconnected but Windows hasn't
1618 // refreshed its enumeration yet - in that case, we ignore the device
1622 default: // HID_PASS and later
1623 if (parent_priv->apib->id == USB_API_HID || parent_priv->apib->id == USB_API_COMPOSITE) {
1624 if (parent_priv->apib->id == USB_API_HID) {
1625 usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1626 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1628 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1629 r = set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api);
1632 case LIBUSB_SUCCESS:
1633 dev_interface_path = NULL;
1635 case LIBUSB_ERROR_ACCESS:
1636 // interface has already been set => make sure dev_interface_path is freed then
1644 libusb_unref_device(parent_dev);
1650 // Free any additional GUIDs
1651 for (pass = HID_PASS + 1; pass < nb_guids; pass++)
1652 free((void *)guid[pass]);
1654 // Unref newly allocated devs
1655 for (i = 0; i < unref_cur; i++)
1656 libusb_unref_device(unref_list[i]);
1663 * exit: libusb backend deinitialization function
1665 static void windows_exit(void)
1669 char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
1671 sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
1672 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1673 if (semaphore == NULL)
1676 // A successful wait brings our semaphore count to 0 (unsignaled)
1677 // => any concurent wait stalls until the semaphore release
1678 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1679 CloseHandle(semaphore);
1683 // Only works if exits and inits are balanced exactly
1684 if (--concurrent_usage < 0) { // Last exit
1685 for (i = 0; i < USB_API_MAX; i++)
1686 usb_api_backend[i].exit(SUB_API_NOTSET);
1689 windows_common_exit();
1690 usbi_mutex_destroy(&autoclaim_lock);
1693 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1694 CloseHandle(semaphore);
1697 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1699 struct windows_device_priv *priv = _device_priv(dev);
1701 memcpy(buffer, &priv->dev_descriptor, DEVICE_DESC_LENGTH);
1704 return LIBUSB_SUCCESS;
1707 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1709 struct windows_device_priv *priv = _device_priv(dev);
1710 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1713 // config index is zero based
1714 if (config_index >= dev->num_configurations)
1715 return LIBUSB_ERROR_INVALID_PARAM;
1717 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1718 return LIBUSB_ERROR_NOT_FOUND;
1720 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1722 size = MIN(config_header->wTotalLength, len);
1723 memcpy(buffer, priv->config_descriptor[config_index], size);
1729 static int windows_get_config_descriptor_by_value(struct libusb_device *dev, uint8_t bConfigurationValue,
1730 unsigned char **buffer, int *host_endian)
1732 struct windows_device_priv *priv = _device_priv(dev);
1733 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1739 if (priv->config_descriptor == NULL)
1740 return LIBUSB_ERROR_NOT_FOUND;
1742 for (index = 0; index < dev->num_configurations; index++) {
1743 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[index];
1744 if (config_header->bConfigurationValue == bConfigurationValue) {
1745 *buffer = priv->config_descriptor[index];
1746 return (int)config_header->wTotalLength;
1750 return LIBUSB_ERROR_NOT_FOUND;
1754 * return the cached copy of the active config descriptor
1756 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1758 struct windows_device_priv *priv = _device_priv(dev);
1759 unsigned char *config_desc;
1762 if (priv->active_config == 0)
1763 return LIBUSB_ERROR_NOT_FOUND;
1765 r = windows_get_config_descriptor_by_value(dev, priv->active_config, &config_desc, host_endian);
1769 len = MIN((size_t)r, len);
1770 memcpy(buffer, config_desc, len);
1774 static int windows_open(struct libusb_device_handle *dev_handle)
1776 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1777 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1779 if (priv->apib == NULL) {
1780 usbi_err(ctx, "program assertion failed - device is not initialized");
1781 return LIBUSB_ERROR_NO_DEVICE;
1784 return priv->apib->open(SUB_API_NOTSET, dev_handle);
1787 static void windows_close(struct libusb_device_handle *dev_handle)
1789 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1791 priv->apib->close(SUB_API_NOTSET, dev_handle);
1794 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1796 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1798 if (priv->active_config == 0) {
1800 return LIBUSB_ERROR_NOT_FOUND;
1803 *config = priv->active_config;
1804 return LIBUSB_SUCCESS;
1808 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1809 * does not currently expose a service that allows higher-level drivers to set
1810 * the configuration."
1812 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1814 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1815 int r = LIBUSB_SUCCESS;
1817 if (config >= USB_MAXCONFIG)
1818 return LIBUSB_ERROR_INVALID_PARAM;
1820 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1821 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1822 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1825 if (r == LIBUSB_SUCCESS)
1826 priv->active_config = (uint8_t)config;
1831 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1833 int r = LIBUSB_SUCCESS;
1834 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1836 safe_free(priv->usb_interface[iface].endpoint);
1837 priv->usb_interface[iface].nb_endpoints = 0;
1839 r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
1841 if (r == LIBUSB_SUCCESS)
1842 r = windows_assign_endpoints(dev_handle, iface, 0);
1847 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1849 int r = LIBUSB_SUCCESS;
1850 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1852 safe_free(priv->usb_interface[iface].endpoint);
1853 priv->usb_interface[iface].nb_endpoints = 0;
1855 r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
1857 if (r == LIBUSB_SUCCESS)
1858 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1863 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1865 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1867 return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
1870 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1872 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1873 return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
1876 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1878 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1879 return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
1882 // The 3 functions below are unlikely to ever get supported on Windows
1883 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1885 return LIBUSB_ERROR_NOT_SUPPORTED;
1888 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1890 return LIBUSB_ERROR_NOT_SUPPORTED;
1893 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1895 return LIBUSB_ERROR_NOT_SUPPORTED;
1898 static void windows_destroy_device(struct libusb_device *dev)
1900 windows_device_priv_release(dev);
1903 void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1905 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1907 usbi_free_fd(&transfer_priv->pollable_fd);
1908 safe_free(transfer_priv->hid_buffer);
1909 // When auto claim is in use, attempt to release the auto-claimed interface
1910 auto_release(itransfer);
1913 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1915 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1916 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1917 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1918 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1921 r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
1922 if (r != LIBUSB_SUCCESS)
1925 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1926 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1928 return LIBUSB_SUCCESS;
1931 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1933 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1934 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1935 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1936 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1939 r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
1940 if (r != LIBUSB_SUCCESS)
1943 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1944 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1946 return LIBUSB_SUCCESS;
1949 static int submit_control_transfer(struct usbi_transfer *itransfer)
1951 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1952 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1953 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1954 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1957 r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
1958 if (r != LIBUSB_SUCCESS)
1961 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1963 return LIBUSB_SUCCESS;
1966 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1968 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1970 switch (transfer->type) {
1971 case LIBUSB_TRANSFER_TYPE_CONTROL:
1972 return submit_control_transfer(itransfer);
1973 case LIBUSB_TRANSFER_TYPE_BULK:
1974 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1975 if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1976 return LIBUSB_ERROR_NOT_SUPPORTED;
1977 return submit_bulk_transfer(itransfer);
1978 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1979 return submit_iso_transfer(itransfer);
1980 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1981 return LIBUSB_ERROR_NOT_SUPPORTED;
1983 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1984 return LIBUSB_ERROR_INVALID_PARAM;
1988 static int windows_abort_control(struct usbi_transfer *itransfer)
1990 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1991 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1993 return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
1996 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1998 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1999 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2001 return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
2004 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
2006 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2008 switch (transfer->type) {
2009 case LIBUSB_TRANSFER_TYPE_CONTROL:
2010 return windows_abort_control(itransfer);
2011 case LIBUSB_TRANSFER_TYPE_BULK:
2012 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2013 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2014 return windows_abort_transfers(itransfer);
2015 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2016 return LIBUSB_ERROR_NOT_SUPPORTED;
2018 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2019 return LIBUSB_ERROR_INVALID_PARAM;
2023 int windows_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2025 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2026 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2027 return priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2030 struct winfd *windows_get_fd(struct usbi_transfer *transfer)
2032 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(transfer);
2033 return &transfer_priv->pollable_fd;
2036 void windows_get_overlapped_result(struct usbi_transfer *transfer, struct winfd *pollable_fd, DWORD *io_result, DWORD *io_size)
2038 if (HasOverlappedIoCompletedSync(pollable_fd->overlapped)) {
2039 *io_result = NO_ERROR;
2040 *io_size = (DWORD)pollable_fd->overlapped->InternalHigh;
2041 } else if (GetOverlappedResult(pollable_fd->handle, pollable_fd->overlapped, io_size, false)) {
2042 // Regular async overlapped
2043 *io_result = NO_ERROR;
2045 *io_result = GetLastError();
2049 // NB: MSVC6 does not support named initializers.
2050 const struct usbi_os_backend usbi_backend = {
2052 USBI_CAP_HAS_HID_ACCESS,
2056 windows_get_device_list,
2057 NULL, /* hotplug_poll */
2061 windows_get_device_descriptor,
2062 windows_get_active_config_descriptor,
2063 windows_get_config_descriptor,
2064 windows_get_config_descriptor_by_value,
2066 windows_get_configuration,
2067 windows_set_configuration,
2068 windows_claim_interface,
2069 windows_release_interface,
2071 windows_set_interface_altsetting,
2073 windows_reset_device,
2075 NULL, /* alloc_streams */
2076 NULL, /* free_streams */
2078 NULL, /* dev_mem_alloc */
2079 NULL, /* dev_mem_free */
2081 windows_kernel_driver_active,
2082 windows_detach_kernel_driver,
2083 windows_attach_kernel_driver,
2085 windows_destroy_device,
2087 windows_submit_transfer,
2088 windows_cancel_transfer,
2089 windows_clear_transfer_priv,
2091 windows_handle_events,
2094 windows_clock_gettime,
2095 #if defined(USBI_TIMERFD_AVAILABLE)
2099 sizeof(struct windows_device_priv),
2100 sizeof(struct windows_device_handle_priv),
2101 sizeof(struct windows_transfer_priv),
2108 static int unsupported_init(int sub_api, struct libusb_context *ctx)
2110 return LIBUSB_SUCCESS;
2113 static int unsupported_exit(int sub_api)
2115 return LIBUSB_SUCCESS;
2118 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle)
2120 PRINT_UNSUPPORTED_API(open);
2123 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle)
2125 usbi_dbg("unsupported API call for 'close'");
2128 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2130 PRINT_UNSUPPORTED_API(configure_endpoints);
2133 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2135 PRINT_UNSUPPORTED_API(claim_interface);
2138 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2140 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2143 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2145 PRINT_UNSUPPORTED_API(release_interface);
2148 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2150 PRINT_UNSUPPORTED_API(clear_halt);
2153 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2155 PRINT_UNSUPPORTED_API(reset_device);
2158 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2160 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2163 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
2165 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2168 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2170 PRINT_UNSUPPORTED_API(submit_control_transfer);
2173 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer)
2175 PRINT_UNSUPPORTED_API(abort_control);
2178 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2180 PRINT_UNSUPPORTED_API(abort_transfers);
2183 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2185 PRINT_UNSUPPORTED_API(copy_transfer_data);
2188 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2190 return LIBUSB_SUCCESS;
2193 // These names must be uppercase
2194 static const char *hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30", "VHHUB", "AUSB3HUB"};
2195 static const char *composite_driver_names[] = {"USBCCGP"};
2196 static const char *winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2197 static const char *hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2198 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2200 USB_API_UNSUPPORTED,
2208 unsupported_configure_endpoints,
2209 unsupported_claim_interface,
2210 unsupported_set_interface_altsetting,
2211 unsupported_release_interface,
2212 unsupported_clear_halt,
2213 unsupported_reset_device,
2214 unsupported_submit_bulk_transfer,
2215 unsupported_submit_iso_transfer,
2216 unsupported_submit_control_transfer,
2217 unsupported_abort_control,
2218 unsupported_abort_transfers,
2219 unsupported_copy_transfer_data,
2225 ARRAYSIZE(hub_driver_names),
2230 unsupported_configure_endpoints,
2231 unsupported_claim_interface,
2232 unsupported_set_interface_altsetting,
2233 unsupported_release_interface,
2234 unsupported_clear_halt,
2235 unsupported_reset_device,
2236 unsupported_submit_bulk_transfer,
2237 unsupported_submit_iso_transfer,
2238 unsupported_submit_control_transfer,
2239 unsupported_abort_control,
2240 unsupported_abort_transfers,
2241 unsupported_copy_transfer_data,
2246 composite_driver_names,
2247 ARRAYSIZE(composite_driver_names),
2252 common_configure_endpoints,
2253 composite_claim_interface,
2254 composite_set_interface_altsetting,
2255 composite_release_interface,
2256 composite_clear_halt,
2257 composite_reset_device,
2258 composite_submit_bulk_transfer,
2259 composite_submit_iso_transfer,
2260 composite_submit_control_transfer,
2261 composite_abort_control,
2262 composite_abort_transfers,
2263 composite_copy_transfer_data,
2268 winusbx_driver_names,
2269 ARRAYSIZE(winusbx_driver_names),
2274 winusbx_configure_endpoints,
2275 winusbx_claim_interface,
2276 winusbx_set_interface_altsetting,
2277 winusbx_release_interface,
2279 winusbx_reset_device,
2280 winusbx_submit_bulk_transfer,
2281 unsupported_submit_iso_transfer,
2282 winusbx_submit_control_transfer,
2283 winusbx_abort_control,
2284 winusbx_abort_transfers,
2285 winusbx_copy_transfer_data,
2291 ARRAYSIZE(hid_driver_names),
2296 common_configure_endpoints,
2297 hid_claim_interface,
2298 hid_set_interface_altsetting,
2299 hid_release_interface,
2302 hid_submit_bulk_transfer,
2303 unsupported_submit_iso_transfer,
2304 hid_submit_control_transfer,
2305 hid_abort_transfers,
2306 hid_abort_transfers,
2307 hid_copy_transfer_data,
2313 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2315 #define WinUSBX_Set(fn) \
2317 if (native_winusb) \
2318 WinUSBX[i].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \
2320 pLibK_GetProcAddress((PVOID *)&WinUSBX[i].fn, i, KUSB_FNID_##fn); \
2323 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2328 KLIB_VERSION LibK_Version;
2329 LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2330 LibK_GetVersion_t pLibK_GetVersion;
2332 h = LoadLibraryA("libusbK");
2335 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2336 h = LoadLibraryA("WinUSB");
2339 usbi_warn(ctx, "WinUSB DLL is not available either, "
2340 "you will not be able to access devices outside of enumeration");
2341 return LIBUSB_ERROR_NOT_FOUND;
2344 usbi_dbg("using libusbK DLL for universal access");
2345 pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(h, "LibK_GetVersion");
2346 if (pLibK_GetVersion != NULL) {
2347 pLibK_GetVersion(&LibK_Version);
2348 usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2349 LibK_Version.Micro, LibK_Version.Nano);
2351 pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(h, "LibK_GetProcAddress");
2352 if (pLibK_GetProcAddress == NULL) {
2353 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2355 return LIBUSB_ERROR_NOT_FOUND;
2359 native_winusb = (pLibK_GetProcAddress == NULL);
2360 for (i = SUB_API_LIBUSBK; i < SUB_API_MAX; i++) {
2361 WinUSBX_Set(AbortPipe);
2362 WinUSBX_Set(ControlTransfer);
2363 WinUSBX_Set(FlushPipe);
2365 WinUSBX_Set(GetAssociatedInterface);
2366 WinUSBX_Set(GetCurrentAlternateSetting);
2367 WinUSBX_Set(GetDescriptor);
2368 WinUSBX_Set(GetOverlappedResult);
2369 WinUSBX_Set(GetPipePolicy);
2370 WinUSBX_Set(GetPowerPolicy);
2371 WinUSBX_Set(Initialize);
2372 WinUSBX_Set(QueryDeviceInformation);
2373 WinUSBX_Set(QueryInterfaceSettings);
2374 WinUSBX_Set(QueryPipe);
2375 WinUSBX_Set(ReadPipe);
2376 WinUSBX_Set(ResetPipe);
2377 WinUSBX_Set(SetCurrentAlternateSetting);
2378 WinUSBX_Set(SetPipePolicy);
2379 WinUSBX_Set(SetPowerPolicy);
2380 WinUSBX_Set(WritePipe);
2382 WinUSBX_Set(ResetDevice);
2384 if (WinUSBX[i].Initialize != NULL) {
2385 WinUSBX[i].initialized = true;
2386 usbi_dbg("initalized sub API %s", sub_api_name[i]);
2388 usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2389 WinUSBX[i].initialized = false;
2394 return LIBUSB_SUCCESS;
2397 static int winusbx_exit(int sub_api)
2399 if (WinUSBX_handle != NULL) {
2400 FreeLibrary(WinUSBX_handle);
2401 WinUSBX_handle = NULL;
2403 /* Reset the WinUSBX API structures */
2404 memset(&WinUSBX, 0, sizeof(WinUSBX));
2407 return LIBUSB_SUCCESS;
2410 // NB: open and close must ensure that they only handle interface of
2411 // the right API type, as these functions can be called wholesale from
2412 // composite_open(), with interfaces belonging to different APIs
2413 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2415 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2416 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2417 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2422 CHECK_WINUSBX_AVAILABLE(sub_api);
2424 // WinUSB requires a separate handle for each interface
2425 for (i = 0; i < USB_MAXINTERFACES; i++) {
2426 if ((priv->usb_interface[i].path != NULL)
2427 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
2428 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2429 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2430 if (file_handle == INVALID_HANDLE_VALUE) {
2431 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2432 switch(GetLastError()) {
2433 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2434 return LIBUSB_ERROR_NO_DEVICE;
2435 case ERROR_ACCESS_DENIED:
2436 return LIBUSB_ERROR_ACCESS;
2438 return LIBUSB_ERROR_IO;
2441 handle_priv->interface_handle[i].dev_handle = file_handle;
2445 return LIBUSB_SUCCESS;
2448 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2450 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2451 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2455 if (sub_api == SUB_API_NOTSET)
2456 sub_api = priv->sub_api;
2458 if (!WinUSBX[sub_api].initialized)
2461 if (priv->apib->id == USB_API_COMPOSITE) {
2462 // If this is a composite device, just free and close all WinUSB-like
2463 // interfaces directly (each is independent and not associated with another)
2464 for (i = 0; i < USB_MAXINTERFACES; i++) {
2465 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2466 handle = handle_priv->interface_handle[i].api_handle;
2467 if (HANDLE_VALID(handle))
2468 WinUSBX[sub_api].Free(handle);
2470 handle = handle_priv->interface_handle[i].dev_handle;
2471 if (HANDLE_VALID(handle))
2472 CloseHandle(handle);
2476 // If this is a WinUSB device, free all interfaces above interface 0,
2477 // then free and close interface 0 last
2478 for (i = 1; i < USB_MAXINTERFACES; i++) {
2479 handle = handle_priv->interface_handle[i].api_handle;
2480 if (HANDLE_VALID(handle))
2481 WinUSBX[sub_api].Free(handle);
2483 handle = handle_priv->interface_handle[0].api_handle;
2484 if (HANDLE_VALID(handle))
2485 WinUSBX[sub_api].Free(handle);
2487 handle = handle_priv->interface_handle[0].dev_handle;
2488 if (HANDLE_VALID(handle))
2489 CloseHandle(handle);
2493 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2495 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2496 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2497 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2500 uint8_t endpoint_address;
2503 CHECK_WINUSBX_AVAILABLE(sub_api);
2505 // With handle and enpoints set (in parent), we can setup the default pipe properties
2506 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2507 for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
2508 endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
2509 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2510 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
2511 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2513 if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
2514 continue; // Other policies don't apply to control endpoint or libusb0
2517 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2518 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
2519 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2521 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2522 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
2523 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2526 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2527 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2528 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2529 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
2530 usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2532 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2533 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
2534 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2537 return LIBUSB_SUCCESS;
2540 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2542 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2543 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2544 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2545 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2546 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2547 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2548 SP_DEVINFO_DATA dev_info_data;
2549 char *dev_path_no_guid = NULL;
2550 char filter_path[] = "\\\\.\\libusb0-0000";
2551 bool found_filter = false;
2552 HANDLE file_handle, winusb_handle;
2556 CHECK_WINUSBX_AVAILABLE(sub_api);
2558 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2559 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2560 if ((is_using_usbccgp) || (iface == 0)) {
2561 // composite device (independent interfaces) or interface 0
2562 file_handle = handle_priv->interface_handle[iface].dev_handle;
2563 if (!HANDLE_VALID(file_handle))
2564 return LIBUSB_ERROR_NOT_FOUND;
2566 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2567 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2568 err = GetLastError();
2570 case ERROR_BAD_COMMAND:
2571 // The device was disconnected
2572 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2573 return LIBUSB_ERROR_NO_DEVICE;
2575 // it may be that we're using the libusb0 filter driver.
2576 // TODO: can we move this whole business into the K/0 DLL?
2577 for (i = 0; ; i++) {
2578 safe_free(dev_interface_details);
2579 safe_free(dev_path_no_guid);
2581 dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2582 if ((found_filter) || (dev_interface_details == NULL))
2586 dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2587 if (dev_path_no_guid == NULL)
2590 if (strncmp(dev_path_no_guid, priv->usb_interface[iface].path, strlen(dev_path_no_guid)) == 0) {
2591 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2592 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2593 if (file_handle != INVALID_HANDLE_VALUE) {
2594 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2595 // Replace the existing file handle with the working one
2596 CloseHandle(handle_priv->interface_handle[iface].dev_handle);
2597 handle_priv->interface_handle[iface].dev_handle = file_handle;
2598 found_filter = true;
2600 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2601 CloseHandle(file_handle);
2604 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2608 free(dev_interface_details);
2609 if (!found_filter) {
2610 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2611 return LIBUSB_ERROR_ACCESS;
2615 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2617 // For all other interfaces, use GetAssociatedInterface()
2618 winusb_handle = handle_priv->interface_handle[0].api_handle;
2619 // It is a requirement for multiple interface devices on Windows that, to you
2620 // must first claim the first interface before you claim the others
2621 if (!HANDLE_VALID(winusb_handle)) {
2622 file_handle = handle_priv->interface_handle[0].dev_handle;
2623 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2624 handle_priv->interface_handle[0].api_handle = winusb_handle;
2625 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2627 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2628 return LIBUSB_ERROR_ACCESS;
2631 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
2632 &handle_priv->interface_handle[iface].api_handle)) {
2633 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2634 switch(GetLastError()) {
2635 case ERROR_NO_MORE_ITEMS: // invalid iface
2636 return LIBUSB_ERROR_NOT_FOUND;
2637 case ERROR_BAD_COMMAND: // The device was disconnected
2638 return LIBUSB_ERROR_NO_DEVICE;
2639 case ERROR_ALREADY_EXISTS: // already claimed
2640 return LIBUSB_ERROR_BUSY;
2642 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2643 return LIBUSB_ERROR_ACCESS;
2647 usbi_dbg("claimed interface %d", iface);
2648 handle_priv->active_interface = iface;
2650 return LIBUSB_SUCCESS;
2653 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2655 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2656 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2657 HANDLE winusb_handle;
2659 CHECK_WINUSBX_AVAILABLE(sub_api);
2661 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2662 if (!HANDLE_VALID(winusb_handle))
2663 return LIBUSB_ERROR_NOT_FOUND;
2665 WinUSBX[sub_api].Free(winusb_handle);
2666 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2668 return LIBUSB_SUCCESS;
2672 * Return the first valid interface (of the same API type), for control transfers
2674 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2676 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2677 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2680 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2681 usbi_dbg("unsupported API ID");
2685 for (i = 0; i < USB_MAXINTERFACES; i++) {
2686 if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
2687 && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
2688 && (priv->usb_interface[i].apib->id == api_id))
2696 * Lookup interface by endpoint address. -1 if not found
2698 static int interface_by_endpoint(struct windows_device_priv *priv,
2699 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2703 for (i = 0; i < USB_MAXINTERFACES; i++) {
2704 if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
2706 if (priv->usb_interface[i].endpoint == NULL)
2708 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2709 if (priv->usb_interface[i].endpoint[j] == endpoint_address)
2717 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2719 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2720 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2721 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2722 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2723 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2724 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
2726 HANDLE winusb_handle;
2727 int current_interface;
2730 CHECK_WINUSBX_AVAILABLE(sub_api);
2732 transfer_priv->pollable_fd = INVALID_WINFD;
2733 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2735 // Windows places upper limits on the control transfer size
2736 // See: https://msdn.microsoft.com/en-us/library/windows/hardware/ff538112.aspx
2737 if (size > MAX_CTRL_BUFFER_LENGTH)
2738 return LIBUSB_ERROR_INVALID_PARAM;
2740 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2741 if (current_interface < 0) {
2742 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
2743 return LIBUSB_ERROR_NOT_FOUND;
2746 usbi_dbg("will use interface %d", current_interface);
2747 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2749 wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
2750 // Always use the handle returned from usbi_create_fd (wfd.handle)
2752 return LIBUSB_ERROR_NO_MEM;
2754 // Sending of set configuration control requests from WinUSB creates issues
2755 if ((LIBUSB_REQ_TYPE(setup->RequestType) == LIBUSB_REQUEST_TYPE_STANDARD)
2756 && (setup->Request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
2757 if (setup->Value != priv->active_config) {
2758 usbi_warn(ctx, "cannot set configuration other than the default one");
2760 return LIBUSB_ERROR_INVALID_PARAM;
2762 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2763 wfd.overlapped->InternalHigh = 0;
2765 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2766 if (GetLastError() != ERROR_IO_PENDING) {
2767 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
2769 return LIBUSB_ERROR_IO;
2772 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2773 wfd.overlapped->InternalHigh = (DWORD)size;
2777 // Use priv_transfer to store data needed for async polling
2778 transfer_priv->pollable_fd = wfd;
2779 transfer_priv->interface_number = (uint8_t)current_interface;
2781 return LIBUSB_SUCCESS;
2784 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2786 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2787 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2788 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2789 HANDLE winusb_handle;
2791 CHECK_WINUSBX_AVAILABLE(sub_api);
2793 if (altsetting > 255)
2794 return LIBUSB_ERROR_INVALID_PARAM;
2796 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2797 if (!HANDLE_VALID(winusb_handle)) {
2798 usbi_err(ctx, "interface must be claimed first");
2799 return LIBUSB_ERROR_NOT_FOUND;
2802 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2803 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2804 return LIBUSB_ERROR_IO;
2807 return LIBUSB_SUCCESS;
2810 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2812 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2813 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2814 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2815 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2816 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2817 HANDLE winusb_handle;
2819 int current_interface;
2822 CHECK_WINUSBX_AVAILABLE(sub_api);
2824 transfer_priv->pollable_fd = INVALID_WINFD;
2826 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2827 if (current_interface < 0) {
2828 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2829 return LIBUSB_ERROR_NOT_FOUND;
2832 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2834 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2836 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
2837 // Always use the handle returned from usbi_create_fd (wfd.handle)
2839 return LIBUSB_ERROR_NO_MEM;
2841 if (IS_XFERIN(transfer)) {
2842 usbi_dbg("reading %d bytes", transfer->length);
2843 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2845 usbi_dbg("writing %d bytes", transfer->length);
2846 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2850 if (GetLastError() != ERROR_IO_PENDING) {
2851 usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
2853 return LIBUSB_ERROR_IO;
2856 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2857 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2860 transfer_priv->pollable_fd = wfd;
2861 transfer_priv->interface_number = (uint8_t)current_interface;
2863 return LIBUSB_SUCCESS;
2866 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2868 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2869 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2870 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2871 HANDLE winusb_handle;
2872 int current_interface;
2874 CHECK_WINUSBX_AVAILABLE(sub_api);
2876 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2877 if (current_interface < 0) {
2878 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2879 return LIBUSB_ERROR_NOT_FOUND;
2882 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2883 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2885 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
2886 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
2887 return LIBUSB_ERROR_NO_DEVICE;
2890 return LIBUSB_SUCCESS;
2894 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2895 * through testing as well):
2896 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2897 * the control transfer using CancelIo"
2899 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
2901 // Cancelling of the I/O is done in the parent
2902 return LIBUSB_SUCCESS;
2905 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2907 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2908 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2909 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2910 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2911 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2912 HANDLE winusb_handle;
2913 int current_interface;
2915 CHECK_WINUSBX_AVAILABLE(sub_api);
2917 current_interface = transfer_priv->interface_number;
2918 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2919 usbi_err(ctx, "program assertion failed: invalid interface_number");
2920 return LIBUSB_ERROR_NOT_FOUND;
2922 usbi_dbg("will use interface %d", current_interface);
2924 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2926 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
2927 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
2928 return LIBUSB_ERROR_NO_DEVICE;
2931 return LIBUSB_SUCCESS;
2935 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2936 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2937 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2938 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2939 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2940 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2942 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2943 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2945 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2946 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2947 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2949 HANDLE winusb_handle;
2952 CHECK_WINUSBX_AVAILABLE(sub_api);
2954 // Reset any available pipe (except control)
2955 for (i = 0; i < USB_MAXINTERFACES; i++) {
2956 winusb_handle = handle_priv->interface_handle[i].api_handle;
2957 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0; ) {
2958 // Cancel any pollable I/O
2959 usbi_remove_pollfd(ctx, wfd.fd);
2961 wfd = handle_to_winfd(winusb_handle);
2964 if (HANDLE_VALID(winusb_handle)) {
2965 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2966 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2967 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2968 usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
2969 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2971 // FlushPipe seems to fail on OUT pipes
2972 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2973 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
2974 usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
2975 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2977 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2978 usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
2979 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2984 // libusbK & libusb0 have the ability to issue an actual device reset
2985 if (WinUSBX[sub_api].ResetDevice != NULL) {
2986 winusb_handle = handle_priv->interface_handle[0].api_handle;
2987 if (HANDLE_VALID(winusb_handle))
2988 WinUSBX[sub_api].ResetDevice(winusb_handle);
2991 return LIBUSB_SUCCESS;
2994 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2996 itransfer->transferred += io_size;
2997 return LIBUSB_TRANSFER_COMPLETED;
3001 * Internal HID Support functions (from libusb-win32)
3002 * Note that functions that complete data transfer synchronously must return
3003 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3005 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3006 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3008 static int _hid_wcslen(WCHAR *str)
3012 while (str[i] && (str[i] != 0x409))
3018 static int _hid_get_device_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3020 struct libusb_device_descriptor d;
3022 d.bLength = LIBUSB_DT_DEVICE_SIZE;
3023 d.bDescriptorType = LIBUSB_DT_DEVICE;
3024 d.bcdUSB = 0x0200; /* 2.00 */
3026 d.bDeviceSubClass = 0;
3027 d.bDeviceProtocol = 0;
3028 d.bMaxPacketSize0 = 64; /* fix this! */
3029 d.idVendor = (uint16_t)dev->vid;
3030 d.idProduct = (uint16_t)dev->pid;
3031 d.bcdDevice = 0x0100;
3032 d.iManufacturer = dev->string_index[0];
3033 d.iProduct = dev->string_index[1];
3034 d.iSerialNumber = dev->string_index[2];
3035 d.bNumConfigurations = 1;
3037 if (*size > LIBUSB_DT_DEVICE_SIZE)
3038 *size = LIBUSB_DT_DEVICE_SIZE;
3039 memcpy(data, &d, *size);
3041 return LIBUSB_COMPLETED;
3044 static int _hid_get_config_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3046 char num_endpoints = 0;
3047 size_t config_total_len = 0;
3048 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3049 struct libusb_config_descriptor *cd;
3050 struct libusb_interface_descriptor *id;
3051 struct libusb_hid_descriptor *hd;
3052 struct libusb_endpoint_descriptor *ed;
3055 if (dev->input_report_size)
3057 if (dev->output_report_size)
3060 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3061 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3063 cd = (struct libusb_config_descriptor *)tmp;
3064 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3065 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3066 + LIBUSB_DT_INTERFACE_SIZE);
3067 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3068 + LIBUSB_DT_INTERFACE_SIZE
3069 + LIBUSB_DT_HID_SIZE);
3071 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3072 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3073 cd->wTotalLength = (uint16_t)config_total_len;
3074 cd->bNumInterfaces = 1;
3075 cd->bConfigurationValue = 1;
3076 cd->iConfiguration = 0;
3077 cd->bmAttributes = 1 << 7; /* bus powered */
3080 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3081 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3082 id->bInterfaceNumber = 0;
3083 id->bAlternateSetting = 0;
3084 id->bNumEndpoints = num_endpoints;
3085 id->bInterfaceClass = 3;
3086 id->bInterfaceSubClass = 0;
3087 id->bInterfaceProtocol = 0;
3090 tmp_size = LIBUSB_DT_HID_SIZE;
3091 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3093 if (dev->input_report_size) {
3094 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3095 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3096 ed->bEndpointAddress = HID_IN_EP;
3097 ed->bmAttributes = 3;
3098 ed->wMaxPacketSize = dev->input_report_size - 1;
3100 ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
3103 if (dev->output_report_size) {
3104 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3105 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3106 ed->bEndpointAddress = HID_OUT_EP;
3107 ed->bmAttributes = 3;
3108 ed->wMaxPacketSize = dev->output_report_size - 1;
3112 if (*size > config_total_len)
3113 *size = config_total_len;
3114 memcpy(data, tmp, *size);
3116 return LIBUSB_COMPLETED;
3119 static int _hid_get_string_descriptor(struct hid_device_priv *dev, int _index,
3120 void *data, size_t *size)
3123 size_t tmp_size = 0;
3126 /* language ID, EN-US */
3127 char string_langid[] = {0x09, 0x04};
3129 if ((*size < 2) || (*size > 255))
3130 return LIBUSB_ERROR_OVERFLOW;
3133 tmp = string_langid;
3134 tmp_size = sizeof(string_langid) + 2;
3136 for (i = 0; i < 3; i++) {
3137 if (_index == (dev->string_index[i])) {
3138 tmp = dev->string[i];
3139 tmp_size = (_hid_wcslen(dev->string[i]) + 1) * sizeof(WCHAR);
3144 if (i == 3) // not found
3145 return LIBUSB_ERROR_INVALID_PARAM;
3149 return LIBUSB_ERROR_INVALID_PARAM;
3151 if (tmp_size < *size)
3155 ((uint8_t *)data)[0] = (uint8_t)*size;
3156 ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
3157 memcpy((uint8_t *)data + 2, tmp, *size - 2);
3159 return LIBUSB_COMPLETED;
3162 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3164 struct libusb_hid_descriptor d;
3165 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3166 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3168 _hid_get_report_descriptor(dev, tmp, &report_len);
3170 d.bLength = LIBUSB_DT_HID_SIZE;
3171 d.bDescriptorType = LIBUSB_DT_HID;
3172 d.bcdHID = 0x0110; /* 1.10 */
3174 d.bNumDescriptors = 1;
3175 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3176 d.wClassDescriptorLength = (uint16_t)report_len;
3178 if (*size > LIBUSB_DT_HID_SIZE)
3179 *size = LIBUSB_DT_HID_SIZE;
3180 memcpy(data, &d, *size);
3182 return LIBUSB_COMPLETED;
3185 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3187 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3190 /* usage page (0xFFA0 == vendor defined) */
3191 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3192 /* usage (vendor defined) */
3193 d[i++] = 0x09; d[i++] = 0x01;
3194 /* start collection (application) */
3195 d[i++] = 0xA1; d[i++] = 0x01;
3197 if (dev->input_report_size) {
3198 /* usage (vendor defined) */
3199 d[i++] = 0x09; d[i++] = 0x01;
3200 /* logical minimum (0) */
3201 d[i++] = 0x15; d[i++] = 0x00;
3202 /* logical maximum (255) */
3203 d[i++] = 0x25; d[i++] = 0xFF;
3204 /* report size (8 bits) */
3205 d[i++] = 0x75; d[i++] = 0x08;
3207 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3208 /* input (data, variable, absolute) */
3209 d[i++] = 0x81; d[i++] = 0x00;
3212 if (dev->output_report_size) {
3213 /* usage (vendor defined) */
3214 d[i++] = 0x09; d[i++] = 0x02;
3215 /* logical minimum (0) */
3216 d[i++] = 0x15; d[i++] = 0x00;
3217 /* logical maximum (255) */
3218 d[i++] = 0x25; d[i++] = 0xFF;
3219 /* report size (8 bits) */
3220 d[i++] = 0x75; d[i++] = 0x08;
3222 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3223 /* output (data, variable, absolute) */
3224 d[i++] = 0x91; d[i++] = 0x00;
3226 /* feature report */
3227 if (dev->feature_report_size) {
3228 /* usage (vendor defined) */
3229 d[i++] = 0x09; d[i++] = 0x03;
3230 /* logical minimum (0) */
3231 d[i++] = 0x15; d[i++] = 0x00;
3232 /* logical maximum (255) */
3233 d[i++] = 0x25; d[i++] = 0xFF;
3234 /* report size (8 bits) */
3235 d[i++] = 0x75; d[i++] = 0x08;
3237 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3238 /* feature (data, variable, absolute) */
3239 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3242 /* end collection */
3247 memcpy(data, d, *size);
3249 return LIBUSB_COMPLETED;
3252 static int _hid_get_descriptor(struct hid_device_priv *dev, HANDLE hid_handle, int recipient,
3253 int type, int _index, void *data, size_t *size)
3256 case LIBUSB_DT_DEVICE:
3257 usbi_dbg("LIBUSB_DT_DEVICE");
3258 return _hid_get_device_descriptor(dev, data, size);
3259 case LIBUSB_DT_CONFIG:
3260 usbi_dbg("LIBUSB_DT_CONFIG");
3262 return _hid_get_config_descriptor(dev, data, size);
3263 return LIBUSB_ERROR_INVALID_PARAM;
3264 case LIBUSB_DT_STRING:
3265 usbi_dbg("LIBUSB_DT_STRING");
3266 return _hid_get_string_descriptor(dev, _index, data, size);
3268 usbi_dbg("LIBUSB_DT_HID");
3270 return _hid_get_hid_descriptor(dev, data, size);
3271 return LIBUSB_ERROR_INVALID_PARAM;
3272 case LIBUSB_DT_REPORT:
3273 usbi_dbg("LIBUSB_DT_REPORT");
3275 return _hid_get_report_descriptor(dev, data, size);
3276 return LIBUSB_ERROR_INVALID_PARAM;
3277 case LIBUSB_DT_PHYSICAL:
3278 usbi_dbg("LIBUSB_DT_PHYSICAL");
3279 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3280 return LIBUSB_COMPLETED;
3281 return LIBUSB_ERROR_OTHER;
3284 usbi_dbg("unsupported");
3285 return LIBUSB_ERROR_NOT_SUPPORTED;
3288 static int _hid_get_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3289 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3292 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3293 int r = LIBUSB_SUCCESS;
3295 if (tp->hid_buffer != NULL)
3296 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3298 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3299 usbi_dbg("invalid size (%u)", *size);
3300 return LIBUSB_ERROR_INVALID_PARAM;
3303 switch (report_type) {
3304 case HID_REPORT_TYPE_INPUT:
3305 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3307 case HID_REPORT_TYPE_FEATURE:
3308 ioctl_code = IOCTL_HID_GET_FEATURE;
3311 usbi_dbg("unknown HID report type %d", report_type);
3312 return LIBUSB_ERROR_INVALID_PARAM;
3315 // Add a trailing byte to detect overflows
3316 buf = calloc(1, expected_size + 1);
3318 return LIBUSB_ERROR_NO_MEM;
3320 buf[0] = (uint8_t)id; // Must be set always
3321 usbi_dbg("report ID: 0x%02X", buf[0]);
3323 tp->hid_expected_size = expected_size;
3324 read_size = expected_size;
3326 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3327 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
3328 buf, expected_size + 1, &read_size, overlapped)) {
3329 if (GetLastError() != ERROR_IO_PENDING) {
3330 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3332 return LIBUSB_ERROR_IO;
3334 // Asynchronous wait
3335 tp->hid_buffer = buf;
3336 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3337 return LIBUSB_SUCCESS;
3340 // Transfer completed synchronously => copy and discard extra buffer
3341 if (read_size == 0) {
3342 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3346 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3348 if ((size_t)read_size > expected_size) {
3349 r = LIBUSB_ERROR_OVERFLOW;
3350 usbi_dbg("OVERFLOW!");
3352 r = LIBUSB_COMPLETED;
3355 *size = MIN((size_t)read_size, *size);
3357 memcpy(data, buf + 1, *size); // Discard report ID
3359 memcpy(data, buf, *size);
3366 static int _hid_set_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3367 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3369 uint8_t *buf = NULL;
3370 DWORD ioctl_code, write_size = (DWORD)*size;
3371 // If an id is reported, we must allow MAX_HID_REPORT_SIZE + 1
3372 size_t max_report_size = MAX_HID_REPORT_SIZE + (id ? 1 : 0);
3374 if (tp->hid_buffer != NULL)
3375 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3377 if ((*size == 0) || (*size > max_report_size)) {
3378 usbi_dbg("invalid size (%u)", *size);
3379 return LIBUSB_ERROR_INVALID_PARAM;
3382 switch (report_type) {
3383 case HID_REPORT_TYPE_OUTPUT:
3384 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3386 case HID_REPORT_TYPE_FEATURE:
3387 ioctl_code = IOCTL_HID_SET_FEATURE;
3390 usbi_dbg("unknown HID report type %d", report_type);
3391 return LIBUSB_ERROR_INVALID_PARAM;
3394 usbi_dbg("report ID: 0x%02X", id);
3395 // When report IDs are not used (i.e. when id == 0), we must add
3396 // a null report ID. Otherwise, we just use original data buffer
3400 buf = malloc(write_size);
3402 return LIBUSB_ERROR_NO_MEM;
3406 memcpy(buf + 1, data, *size);
3408 // This seems like a waste, but if we don't duplicate the
3409 // data, we'll get issues when freeing hid_buffer
3410 memcpy(buf, data, *size);
3412 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3415 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3416 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3417 buf, write_size, &write_size, overlapped)) {
3418 if (GetLastError() != ERROR_IO_PENDING) {
3419 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3421 return LIBUSB_ERROR_IO;
3423 tp->hid_buffer = buf;
3424 tp->hid_dest = NULL;
3425 return LIBUSB_SUCCESS;
3428 // Transfer completed synchronously
3430 if (write_size == 0)
3431 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3434 return LIBUSB_COMPLETED;
3437 static int _hid_class_request(struct hid_device_priv *dev, HANDLE hid_handle, int request_type,
3438 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3439 size_t *size, OVERLAPPED *overlapped)
3441 int report_type = (value >> 8) & 0xFF;
3442 int report_id = value & 0xFF;
3444 if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3445 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
3446 return LIBUSB_ERROR_INVALID_PARAM;
3448 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3449 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3451 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3452 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3454 return LIBUSB_ERROR_INVALID_PARAM;
3461 static int hid_init(int sub_api, struct libusb_context *ctx)
3463 DLL_GET_HANDLE(hid);
3464 DLL_LOAD_FUNC(hid, HidD_GetAttributes, TRUE);
3465 DLL_LOAD_FUNC(hid, HidD_GetHidGuid, TRUE);
3466 DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, TRUE);
3467 DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, TRUE);
3468 DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, TRUE);
3469 DLL_LOAD_FUNC(hid, HidD_GetProductString, TRUE);
3470 DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, TRUE);
3471 DLL_LOAD_FUNC(hid, HidP_GetCaps, TRUE);
3472 DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, TRUE);
3473 DLL_LOAD_FUNC(hid, HidD_SetFeature, TRUE);
3474 DLL_LOAD_FUNC(hid, HidD_GetFeature, TRUE);
3475 DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, TRUE);
3476 DLL_LOAD_FUNC(hid, HidD_GetInputReport, FALSE);
3477 DLL_LOAD_FUNC(hid, HidD_SetOutputReport, FALSE);
3478 DLL_LOAD_FUNC(hid, HidD_FlushQueue, TRUE);
3479 DLL_LOAD_FUNC(hid, HidP_GetValueCaps, TRUE);
3481 api_hid_available = true;
3482 return LIBUSB_SUCCESS;
3485 static int hid_exit(int sub_api)
3487 DLL_FREE_HANDLE(hid);
3489 return LIBUSB_SUCCESS;
3492 // NB: open and close must ensure that they only handle interface of
3493 // the right API type, as these functions can be called wholesale from
3494 // composite_open(), with interfaces belonging to different APIs
3495 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3497 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3498 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3499 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3500 HIDD_ATTRIBUTES hid_attributes;
3501 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3502 HIDP_CAPS capabilities;
3503 HIDP_VALUE_CAPS *value_caps;
3504 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3506 // report IDs handling
3508 int nb_ids[2]; // zero and nonzero report IDs
3509 #if defined(ENABLE_LOGGING)
3510 const char *type[3] = {"input", "output", "feature"};
3513 CHECK_HID_AVAILABLE;
3515 if (priv->hid == NULL) {
3516 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3517 return LIBUSB_ERROR_NOT_FOUND;
3520 for (i = 0; i < USB_MAXINTERFACES; i++) {
3521 if ((priv->usb_interface[i].path != NULL)
3522 && (priv->usb_interface[i].apib->id == USB_API_HID)) {
3523 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3524 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3526 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3527 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3528 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3529 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3530 * HidD_GetFeature (if the device supports Feature reports)."
3532 if (hid_handle == INVALID_HANDLE_VALUE) {
3533 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3534 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3535 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3536 if (hid_handle == INVALID_HANDLE_VALUE) {
3537 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3538 switch(GetLastError()) {
3539 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3540 return LIBUSB_ERROR_NO_DEVICE;
3541 case ERROR_ACCESS_DENIED:
3542 return LIBUSB_ERROR_ACCESS;
3544 return LIBUSB_ERROR_IO;
3547 priv->usb_interface[i].restricted_functionality = true;
3549 handle_priv->interface_handle[i].api_handle = hid_handle;
3553 hid_attributes.Size = sizeof(hid_attributes);
3555 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3556 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3560 priv->hid->vid = hid_attributes.VendorID;
3561 priv->hid->pid = hid_attributes.ProductID;
3563 // Set the maximum available input buffer size
3564 for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
3565 usbi_dbg("set maximum input buffer size to %d", i / 2);
3567 // Get the maximum input and output report size
3568 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3569 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3572 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3573 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3577 // Find out if interrupt will need report IDs
3578 size[0] = capabilities.NumberInputValueCaps;
3579 size[1] = capabilities.NumberOutputValueCaps;
3580 size[2] = capabilities.NumberFeatureValueCaps;
3581 for (j = HidP_Input; j <= HidP_Feature; j++) {
3582 usbi_dbg("%u HID %s report value(s) found", (unsigned int)size[j], type[j]);
3583 priv->hid->uses_report_ids[j] = false;
3585 value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3586 if ((value_caps != NULL)
3587 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3588 && (size[j] >= 1)) {
3591 for (i = 0; i < (int)size[j]; i++) {
3592 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3593 if (value_caps[i].ReportID != 0)
3598 if (nb_ids[1] != 0) {
3600 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3602 priv->hid->uses_report_ids[j] = true;
3605 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3611 // Set the report sizes
3612 priv->hid->input_report_size = capabilities.InputReportByteLength;
3613 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3614 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3616 // Fetch string descriptors
3617 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3618 if (priv->hid->string_index[0] != 0)
3619 HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
3621 priv->hid->string[0][0] = 0;
3623 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3624 if (priv->hid->string_index[1] != 0)
3625 HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1]));
3627 priv->hid->string[1][0] = 0;
3629 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3630 if (priv->hid->string_index[2] != 0)
3631 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
3633 priv->hid->string[2][0] = 0;
3637 HidD_FreePreparsedData(preparsed_data);
3639 return LIBUSB_SUCCESS;
3642 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3644 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3645 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3649 if (!api_hid_available)
3652 for (i = 0; i < USB_MAXINTERFACES; i++) {
3653 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3654 file_handle = handle_priv->interface_handle[i].api_handle;
3655 if (HANDLE_VALID(file_handle))
3656 CloseHandle(file_handle);
3661 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3663 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3664 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3666 CHECK_HID_AVAILABLE;
3668 // NB: Disconnection detection is not possible in this function
3669 if (priv->usb_interface[iface].path == NULL)
3670 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3672 // We use dev_handle as a flag for interface claimed
3673 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
3674 return LIBUSB_ERROR_BUSY; // already claimed
3677 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3679 usbi_dbg("claimed interface %d", iface);
3680 handle_priv->active_interface = iface;
3682 return LIBUSB_SUCCESS;
3685 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3687 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3688 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3690 CHECK_HID_AVAILABLE;
3692 if (priv->usb_interface[iface].path == NULL)
3693 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3695 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
3696 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3698 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3700 return LIBUSB_SUCCESS;
3703 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3705 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3707 CHECK_HID_AVAILABLE;
3709 if (altsetting > 255)
3710 return LIBUSB_ERROR_INVALID_PARAM;
3712 if (altsetting != 0) {
3713 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3714 return LIBUSB_ERROR_NOT_SUPPORTED;
3717 return LIBUSB_SUCCESS;
3720 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3722 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3723 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3724 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3725 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3726 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3727 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
3730 int current_interface, config;
3732 int r = LIBUSB_ERROR_INVALID_PARAM;
3734 CHECK_HID_AVAILABLE;
3736 transfer_priv->pollable_fd = INVALID_WINFD;
3737 safe_free(transfer_priv->hid_buffer);
3738 transfer_priv->hid_dest = NULL;
3739 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3741 if (size > MAX_CTRL_BUFFER_LENGTH)
3742 return LIBUSB_ERROR_INVALID_PARAM;
3744 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3745 if (current_interface < 0) {
3746 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS)
3747 return LIBUSB_ERROR_NOT_FOUND;
3750 usbi_dbg("will use interface %d", current_interface);
3751 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3752 // Always use the handle returned from usbi_create_fd (wfd.handle)
3753 wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
3755 return LIBUSB_ERROR_NOT_FOUND;
3757 switch(LIBUSB_REQ_TYPE(setup->RequestType)) {
3758 case LIBUSB_REQUEST_TYPE_STANDARD:
3759 switch(setup->Request) {
3760 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3761 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->RequestType),
3762 (setup->Value >> 8) & 0xFF, setup->Value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3764 case LIBUSB_REQUEST_GET_CONFIGURATION:
3765 r = windows_get_configuration(transfer->dev_handle, &config);
3766 if (r == LIBUSB_SUCCESS) {
3768 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3769 r = LIBUSB_COMPLETED;
3772 case LIBUSB_REQUEST_SET_CONFIGURATION:
3773 if (setup->Value == priv->active_config) {
3774 r = LIBUSB_COMPLETED;
3776 usbi_warn(ctx, "cannot set configuration other than the default one");
3777 r = LIBUSB_ERROR_NOT_SUPPORTED;
3780 case LIBUSB_REQUEST_GET_INTERFACE:
3782 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3783 r = LIBUSB_COMPLETED;
3785 case LIBUSB_REQUEST_SET_INTERFACE:
3786 r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->Index, setup->Value);
3787 if (r == LIBUSB_SUCCESS)
3788 r = LIBUSB_COMPLETED;
3791 usbi_warn(ctx, "unsupported HID control request");
3792 r = LIBUSB_ERROR_NOT_SUPPORTED;
3796 case LIBUSB_REQUEST_TYPE_CLASS:
3797 r = _hid_class_request(priv->hid, wfd.handle, setup->RequestType, setup->Request, setup->Value,
3798 setup->Index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3799 &size, wfd.overlapped);
3802 usbi_warn(ctx, "unsupported HID control request");
3803 r = LIBUSB_ERROR_NOT_SUPPORTED;
3807 if (r == LIBUSB_COMPLETED) {
3808 // Force request to be completed synchronously. Transferred size has been set by previous call
3809 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3810 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3811 // set InternalHigh to the number of bytes transferred
3812 wfd.overlapped->InternalHigh = (DWORD)size;
3816 if (r == LIBUSB_SUCCESS) {
3817 // Use priv_transfer to store data needed for async polling
3818 transfer_priv->pollable_fd = wfd;
3819 transfer_priv->interface_number = (uint8_t)current_interface;
3827 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3829 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3830 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3831 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3832 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3833 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3836 bool direction_in, ret;
3837 int current_interface, length;
3839 int r = LIBUSB_SUCCESS;
3841 CHECK_HID_AVAILABLE;
3843 transfer_priv->pollable_fd = INVALID_WINFD;
3844 transfer_priv->hid_dest = NULL;
3845 safe_free(transfer_priv->hid_buffer);
3847 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3848 if (current_interface < 0) {
3849 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3850 return LIBUSB_ERROR_NOT_FOUND;
3853 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3855 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3856 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3858 wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
3859 // Always use the handle returned from usbi_create_fd (wfd.handle)
3861 return LIBUSB_ERROR_NO_MEM;
3863 // If report IDs are not in use, an extra prefix byte must be added
3864 if (((direction_in) && (!priv->hid->uses_report_ids[0]))
3865 || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
3866 length = transfer->length + 1;
3868 length = transfer->length;
3870 // Add a trailing byte to detect overflows on input
3871 transfer_priv->hid_buffer = calloc(1, length + 1);
3872 if (transfer_priv->hid_buffer == NULL)
3873 return LIBUSB_ERROR_NO_MEM;
3875 transfer_priv->hid_expected_size = length;
3878 transfer_priv->hid_dest = transfer->buffer;
3879 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
3880 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length + 1, &size, wfd.overlapped);
3882 if (!priv->hid->uses_report_ids[1])
3883 memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
3885 // We could actually do without the calloc and memcpy in this case
3886 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3888 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3889 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3893 if (GetLastError() != ERROR_IO_PENDING) {
3894 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3896 safe_free(transfer_priv->hid_buffer);
3897 return LIBUSB_ERROR_IO;
3900 // Only write operations that completed synchronously need to free up
3901 // hid_buffer. For reads, copy_transfer_data() handles that process.
3903 safe_free(transfer_priv->hid_buffer);
3906 usbi_err(ctx, "program assertion failed - no data was transferred");
3909 if (size > (size_t)length) {
3910 usbi_err(ctx, "OVERFLOW!");
3911 r = LIBUSB_ERROR_OVERFLOW;
3913 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3914 wfd.overlapped->InternalHigh = size;
3917 transfer_priv->pollable_fd = wfd;
3918 transfer_priv->interface_number = (uint8_t)current_interface;
3923 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3925 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3926 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3927 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3929 int current_interface;
3931 CHECK_HID_AVAILABLE;
3933 current_interface = transfer_priv->interface_number;
3934 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3935 CancelIo(hid_handle);
3937 return LIBUSB_SUCCESS;
3940 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3942 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3944 int current_interface;
3946 CHECK_HID_AVAILABLE;
3948 // Flushing the queues on all interfaces is the best we can achieve
3949 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3950 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3951 if (HANDLE_VALID(hid_handle))
3952 HidD_FlushQueue(hid_handle);
3955 return LIBUSB_SUCCESS;
3958 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3960 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3961 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3962 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3964 int current_interface;
3966 CHECK_HID_AVAILABLE;
3968 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3969 if (current_interface < 0) {
3970 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3971 return LIBUSB_ERROR_NOT_FOUND;
3974 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3975 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3977 // No endpoint selection with Microsoft's implementation, so we try to flush the
3978 // whole interface. Should be OK for most case scenarios
3979 if (!HidD_FlushQueue(hid_handle)) {
3980 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3981 // Device was probably disconnected
3982 return LIBUSB_ERROR_NO_DEVICE;
3985 return LIBUSB_SUCCESS;
3988 // This extra function is only needed for HID
3989 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3991 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3992 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3993 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3994 int r = LIBUSB_TRANSFER_COMPLETED;
3995 uint32_t corrected_size = io_size;
3997 if (transfer_priv->hid_buffer != NULL) {
3998 // If we have a valid hid_buffer, it means the transfer was async
3999 if (transfer_priv->hid_dest != NULL) { // Data readout
4000 if (corrected_size > 0) {
4001 // First, check for overflow
4002 if (corrected_size > transfer_priv->hid_expected_size) {
4003 usbi_err(ctx, "OVERFLOW!");
4004 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4005 r = LIBUSB_TRANSFER_OVERFLOW;
4008 if (transfer_priv->hid_buffer[0] == 0) {
4009 // Discard the 1 byte report ID prefix
4011 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, corrected_size);
4013 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4016 transfer_priv->hid_dest = NULL;
4018 // For write, we just need to free the hid buffer
4019 safe_free(transfer_priv->hid_buffer);
4022 itransfer->transferred += corrected_size;
4028 * Composite API functions
4030 static int composite_init(int sub_api, struct libusb_context *ctx)
4032 return LIBUSB_SUCCESS;
4035 static int composite_exit(int sub_api)
4037 return LIBUSB_SUCCESS;
4040 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4042 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4043 int r = LIBUSB_ERROR_NOT_FOUND;
4045 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4046 bool available[SUB_API_MAX + 1] = { 0 };
4048 for (i = 0; i < USB_MAXINTERFACES; i++) {
4049 switch (priv->usb_interface[i].apib->id) {
4050 case USB_API_WINUSBX:
4051 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4052 available[priv->usb_interface[i].sub_api] = true;
4055 available[SUB_API_MAX] = true;
4062 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4064 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4065 if (r != LIBUSB_SUCCESS)
4070 if (available[SUB_API_MAX]) // HID driver
4071 r = hid_open(SUB_API_NOTSET, dev_handle);
4076 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4078 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4080 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4081 bool available[SUB_API_MAX + 1] = { 0 };
4083 for (i = 0; i < USB_MAXINTERFACES; i++) {
4084 switch (priv->usb_interface[i].apib->id) {
4085 case USB_API_WINUSBX:
4086 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4087 available[priv->usb_interface[i].sub_api] = true;
4090 available[SUB_API_MAX] = true;
4097 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4099 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4102 if (available[SUB_API_MAX]) // HID driver
4103 hid_close(SUB_API_NOTSET, dev_handle);
4106 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4108 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4110 return priv->usb_interface[iface].apib->
4111 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4114 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4116 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4118 return priv->usb_interface[iface].apib->
4119 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4122 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4124 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4126 return priv->usb_interface[iface].apib->
4127 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4130 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4132 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4133 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4134 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4135 struct libusb_config_descriptor *conf_desc;
4136 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
4139 // Interface shouldn't matter for control, but it does in practice, with Windows'
4140 // restrictions with regards to accessing HID keyboards and mice. Try to target
4141 // a specific interface first, if possible.
4142 switch (LIBUSB_REQ_RECIPIENT(setup->RequestType)) {
4143 case LIBUSB_RECIPIENT_INTERFACE:
4144 iface = setup->Index & 0xFF;
4146 case LIBUSB_RECIPIENT_ENDPOINT:
4147 r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc);
4148 if (r == LIBUSB_SUCCESS) {
4149 iface = get_interface_by_endpoint(conf_desc, (setup->Index & 0xFF));
4150 libusb_free_config_descriptor(conf_desc);
4153 // Fall through if not able to determine interface
4159 // Try and target a specific interface if the control setup indicates such
4160 if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4161 usbi_dbg("attempting control transfer targeted to interface %d", iface);
4162 if (priv->usb_interface[iface].path != NULL) {
4163 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4164 if (r == LIBUSB_SUCCESS)
4169 // Either not targeted to a specific interface or no luck in doing so.
4170 // Try a 2 pass approach with all interfaces.
4171 for (pass = 0; pass < 2; pass++) {
4172 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4173 if (priv->usb_interface[iface].path != NULL) {
4174 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4175 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4178 usbi_dbg("using interface %d", iface);
4179 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4180 // If not supported on this API, it may be supported on another, so don't give up yet!!
4181 if (r == LIBUSB_ERROR_NOT_SUPPORTED)
4188 usbi_err(ctx, "no libusb supported interfaces to complete request");
4189 return LIBUSB_ERROR_NOT_FOUND;
4192 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4193 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4194 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4195 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4196 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4197 int current_interface;
4199 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4200 if (current_interface < 0) {
4201 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4202 return LIBUSB_ERROR_NOT_FOUND;
4205 return priv->usb_interface[current_interface].apib->
4206 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4209 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4210 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4211 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4212 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4213 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4214 int current_interface;
4216 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4217 if (current_interface < 0) {
4218 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4219 return LIBUSB_ERROR_NOT_FOUND;
4222 return priv->usb_interface[current_interface].apib->
4223 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4226 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4228 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4229 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4230 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4231 int current_interface;
4233 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4234 if (current_interface < 0) {
4235 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4236 return LIBUSB_ERROR_NOT_FOUND;
4239 return priv->usb_interface[current_interface].apib->
4240 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
4243 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4245 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4246 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4247 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4249 return priv->usb_interface[transfer_priv->interface_number].apib->
4250 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4253 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4255 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4256 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4257 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4259 return priv->usb_interface[transfer_priv->interface_number].apib->
4260 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4263 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4265 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4268 bool available[SUB_API_MAX];
4270 for (i = 0; i < SUB_API_MAX; i++)
4271 available[i] = false;
4273 for (i = 0; i < USB_MAXINTERFACES; i++) {
4274 if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4275 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
4276 available[priv->usb_interface[i].sub_api] = true;
4279 for (i = 0; i < SUB_API_MAX; i++) {
4281 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4282 if (r != LIBUSB_SUCCESS)
4287 return LIBUSB_SUCCESS;
4290 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4292 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4293 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4294 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4296 return priv->usb_interface[transfer_priv->interface_number].apib->
4297 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
4300 #endif /* !USE_USBDK */