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)
2098 sizeof(struct windows_device_priv),
2099 sizeof(struct windows_device_handle_priv),
2100 sizeof(struct windows_transfer_priv),
2107 static int unsupported_init(int sub_api, struct libusb_context *ctx)
2109 return LIBUSB_SUCCESS;
2112 static int unsupported_exit(int sub_api)
2114 return LIBUSB_SUCCESS;
2117 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle)
2119 PRINT_UNSUPPORTED_API(open);
2122 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle)
2124 usbi_dbg("unsupported API call for 'close'");
2127 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2129 PRINT_UNSUPPORTED_API(configure_endpoints);
2132 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2134 PRINT_UNSUPPORTED_API(claim_interface);
2137 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2139 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2142 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2144 PRINT_UNSUPPORTED_API(release_interface);
2147 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2149 PRINT_UNSUPPORTED_API(clear_halt);
2152 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2154 PRINT_UNSUPPORTED_API(reset_device);
2157 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2159 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2162 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
2164 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2167 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2169 PRINT_UNSUPPORTED_API(submit_control_transfer);
2172 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer)
2174 PRINT_UNSUPPORTED_API(abort_control);
2177 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2179 PRINT_UNSUPPORTED_API(abort_transfers);
2182 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2184 PRINT_UNSUPPORTED_API(copy_transfer_data);
2187 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2189 return LIBUSB_SUCCESS;
2192 // These names must be uppercase
2193 static const char *hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30", "VHHUB", "AUSB3HUB"};
2194 static const char *composite_driver_names[] = {"USBCCGP"};
2195 static const char *winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2196 static const char *hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2197 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2199 USB_API_UNSUPPORTED,
2207 unsupported_configure_endpoints,
2208 unsupported_claim_interface,
2209 unsupported_set_interface_altsetting,
2210 unsupported_release_interface,
2211 unsupported_clear_halt,
2212 unsupported_reset_device,
2213 unsupported_submit_bulk_transfer,
2214 unsupported_submit_iso_transfer,
2215 unsupported_submit_control_transfer,
2216 unsupported_abort_control,
2217 unsupported_abort_transfers,
2218 unsupported_copy_transfer_data,
2224 ARRAYSIZE(hub_driver_names),
2229 unsupported_configure_endpoints,
2230 unsupported_claim_interface,
2231 unsupported_set_interface_altsetting,
2232 unsupported_release_interface,
2233 unsupported_clear_halt,
2234 unsupported_reset_device,
2235 unsupported_submit_bulk_transfer,
2236 unsupported_submit_iso_transfer,
2237 unsupported_submit_control_transfer,
2238 unsupported_abort_control,
2239 unsupported_abort_transfers,
2240 unsupported_copy_transfer_data,
2245 composite_driver_names,
2246 ARRAYSIZE(composite_driver_names),
2251 common_configure_endpoints,
2252 composite_claim_interface,
2253 composite_set_interface_altsetting,
2254 composite_release_interface,
2255 composite_clear_halt,
2256 composite_reset_device,
2257 composite_submit_bulk_transfer,
2258 composite_submit_iso_transfer,
2259 composite_submit_control_transfer,
2260 composite_abort_control,
2261 composite_abort_transfers,
2262 composite_copy_transfer_data,
2267 winusbx_driver_names,
2268 ARRAYSIZE(winusbx_driver_names),
2273 winusbx_configure_endpoints,
2274 winusbx_claim_interface,
2275 winusbx_set_interface_altsetting,
2276 winusbx_release_interface,
2278 winusbx_reset_device,
2279 winusbx_submit_bulk_transfer,
2280 unsupported_submit_iso_transfer,
2281 winusbx_submit_control_transfer,
2282 winusbx_abort_control,
2283 winusbx_abort_transfers,
2284 winusbx_copy_transfer_data,
2290 ARRAYSIZE(hid_driver_names),
2295 common_configure_endpoints,
2296 hid_claim_interface,
2297 hid_set_interface_altsetting,
2298 hid_release_interface,
2301 hid_submit_bulk_transfer,
2302 unsupported_submit_iso_transfer,
2303 hid_submit_control_transfer,
2304 hid_abort_transfers,
2305 hid_abort_transfers,
2306 hid_copy_transfer_data,
2312 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2314 #define WinUSBX_Set(fn) \
2316 if (native_winusb) \
2317 WinUSBX[i].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \
2319 pLibK_GetProcAddress((PVOID *)&WinUSBX[i].fn, i, KUSB_FNID_##fn); \
2322 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2327 KLIB_VERSION LibK_Version;
2328 LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2329 LibK_GetVersion_t pLibK_GetVersion;
2331 h = LoadLibraryA("libusbK");
2334 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2335 h = LoadLibraryA("WinUSB");
2338 usbi_warn(ctx, "WinUSB DLL is not available either, "
2339 "you will not be able to access devices outside of enumeration");
2340 return LIBUSB_ERROR_NOT_FOUND;
2343 usbi_dbg("using libusbK DLL for universal access");
2344 pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(h, "LibK_GetVersion");
2345 if (pLibK_GetVersion != NULL) {
2346 pLibK_GetVersion(&LibK_Version);
2347 usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2348 LibK_Version.Micro, LibK_Version.Nano);
2350 pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(h, "LibK_GetProcAddress");
2351 if (pLibK_GetProcAddress == NULL) {
2352 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2354 return LIBUSB_ERROR_NOT_FOUND;
2358 native_winusb = (pLibK_GetProcAddress == NULL);
2359 for (i = SUB_API_LIBUSBK; i < SUB_API_MAX; i++) {
2360 WinUSBX_Set(AbortPipe);
2361 WinUSBX_Set(ControlTransfer);
2362 WinUSBX_Set(FlushPipe);
2364 WinUSBX_Set(GetAssociatedInterface);
2365 WinUSBX_Set(GetCurrentAlternateSetting);
2366 WinUSBX_Set(GetDescriptor);
2367 WinUSBX_Set(GetOverlappedResult);
2368 WinUSBX_Set(GetPipePolicy);
2369 WinUSBX_Set(GetPowerPolicy);
2370 WinUSBX_Set(Initialize);
2371 WinUSBX_Set(QueryDeviceInformation);
2372 WinUSBX_Set(QueryInterfaceSettings);
2373 WinUSBX_Set(QueryPipe);
2374 WinUSBX_Set(ReadPipe);
2375 WinUSBX_Set(ResetPipe);
2376 WinUSBX_Set(SetCurrentAlternateSetting);
2377 WinUSBX_Set(SetPipePolicy);
2378 WinUSBX_Set(SetPowerPolicy);
2379 WinUSBX_Set(WritePipe);
2381 WinUSBX_Set(ResetDevice);
2383 if (WinUSBX[i].Initialize != NULL) {
2384 WinUSBX[i].initialized = true;
2385 usbi_dbg("initalized sub API %s", sub_api_name[i]);
2387 usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2388 WinUSBX[i].initialized = false;
2393 return LIBUSB_SUCCESS;
2396 static int winusbx_exit(int sub_api)
2398 if (WinUSBX_handle != NULL) {
2399 FreeLibrary(WinUSBX_handle);
2400 WinUSBX_handle = NULL;
2402 /* Reset the WinUSBX API structures */
2403 memset(&WinUSBX, 0, sizeof(WinUSBX));
2406 return LIBUSB_SUCCESS;
2409 // NB: open and close must ensure that they only handle interface of
2410 // the right API type, as these functions can be called wholesale from
2411 // composite_open(), with interfaces belonging to different APIs
2412 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2414 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2415 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2416 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2421 CHECK_WINUSBX_AVAILABLE(sub_api);
2423 // WinUSB requires a separate handle for each interface
2424 for (i = 0; i < USB_MAXINTERFACES; i++) {
2425 if ((priv->usb_interface[i].path != NULL)
2426 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
2427 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2428 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2429 if (file_handle == INVALID_HANDLE_VALUE) {
2430 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2431 switch(GetLastError()) {
2432 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2433 return LIBUSB_ERROR_NO_DEVICE;
2434 case ERROR_ACCESS_DENIED:
2435 return LIBUSB_ERROR_ACCESS;
2437 return LIBUSB_ERROR_IO;
2440 handle_priv->interface_handle[i].dev_handle = file_handle;
2444 return LIBUSB_SUCCESS;
2447 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2449 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2450 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2454 if (sub_api == SUB_API_NOTSET)
2455 sub_api = priv->sub_api;
2457 if (!WinUSBX[sub_api].initialized)
2460 if (priv->apib->id == USB_API_COMPOSITE) {
2461 // If this is a composite device, just free and close all WinUSB-like
2462 // interfaces directly (each is independent and not associated with another)
2463 for (i = 0; i < USB_MAXINTERFACES; i++) {
2464 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2465 handle = handle_priv->interface_handle[i].api_handle;
2466 if (HANDLE_VALID(handle))
2467 WinUSBX[sub_api].Free(handle);
2469 handle = handle_priv->interface_handle[i].dev_handle;
2470 if (HANDLE_VALID(handle))
2471 CloseHandle(handle);
2475 // If this is a WinUSB device, free all interfaces above interface 0,
2476 // then free and close interface 0 last
2477 for (i = 1; i < USB_MAXINTERFACES; i++) {
2478 handle = handle_priv->interface_handle[i].api_handle;
2479 if (HANDLE_VALID(handle))
2480 WinUSBX[sub_api].Free(handle);
2482 handle = handle_priv->interface_handle[0].api_handle;
2483 if (HANDLE_VALID(handle))
2484 WinUSBX[sub_api].Free(handle);
2486 handle = handle_priv->interface_handle[0].dev_handle;
2487 if (HANDLE_VALID(handle))
2488 CloseHandle(handle);
2492 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2494 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2495 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2496 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2499 uint8_t endpoint_address;
2502 CHECK_WINUSBX_AVAILABLE(sub_api);
2504 // With handle and enpoints set (in parent), we can setup the default pipe properties
2505 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2506 for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
2507 endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
2508 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2509 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
2510 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2512 if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
2513 continue; // Other policies don't apply to control endpoint or libusb0
2516 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2517 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
2518 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2520 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2521 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
2522 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2525 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2526 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2527 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2528 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
2529 usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2531 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2532 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
2533 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2536 return LIBUSB_SUCCESS;
2539 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2541 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2542 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2543 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2544 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2545 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2546 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2547 SP_DEVINFO_DATA dev_info_data;
2548 char *dev_path_no_guid = NULL;
2549 char filter_path[] = "\\\\.\\libusb0-0000";
2550 bool found_filter = false;
2551 HANDLE file_handle, winusb_handle;
2555 CHECK_WINUSBX_AVAILABLE(sub_api);
2557 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2558 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2559 if ((is_using_usbccgp) || (iface == 0)) {
2560 // composite device (independent interfaces) or interface 0
2561 file_handle = handle_priv->interface_handle[iface].dev_handle;
2562 if (!HANDLE_VALID(file_handle))
2563 return LIBUSB_ERROR_NOT_FOUND;
2565 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2566 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2567 err = GetLastError();
2569 case ERROR_BAD_COMMAND:
2570 // The device was disconnected
2571 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2572 return LIBUSB_ERROR_NO_DEVICE;
2574 // it may be that we're using the libusb0 filter driver.
2575 // TODO: can we move this whole business into the K/0 DLL?
2576 for (i = 0; ; i++) {
2577 safe_free(dev_interface_details);
2578 safe_free(dev_path_no_guid);
2580 dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2581 if ((found_filter) || (dev_interface_details == NULL))
2585 dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2586 if (dev_path_no_guid == NULL)
2589 if (strncmp(dev_path_no_guid, priv->usb_interface[iface].path, strlen(dev_path_no_guid)) == 0) {
2590 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2591 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2592 if (file_handle != INVALID_HANDLE_VALUE) {
2593 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2594 // Replace the existing file handle with the working one
2595 CloseHandle(handle_priv->interface_handle[iface].dev_handle);
2596 handle_priv->interface_handle[iface].dev_handle = file_handle;
2597 found_filter = true;
2599 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2600 CloseHandle(file_handle);
2603 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2607 free(dev_interface_details);
2608 if (!found_filter) {
2609 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2610 return LIBUSB_ERROR_ACCESS;
2614 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2616 // For all other interfaces, use GetAssociatedInterface()
2617 winusb_handle = handle_priv->interface_handle[0].api_handle;
2618 // It is a requirement for multiple interface devices on Windows that, to you
2619 // must first claim the first interface before you claim the others
2620 if (!HANDLE_VALID(winusb_handle)) {
2621 file_handle = handle_priv->interface_handle[0].dev_handle;
2622 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2623 handle_priv->interface_handle[0].api_handle = winusb_handle;
2624 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2626 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2627 return LIBUSB_ERROR_ACCESS;
2630 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
2631 &handle_priv->interface_handle[iface].api_handle)) {
2632 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2633 switch(GetLastError()) {
2634 case ERROR_NO_MORE_ITEMS: // invalid iface
2635 return LIBUSB_ERROR_NOT_FOUND;
2636 case ERROR_BAD_COMMAND: // The device was disconnected
2637 return LIBUSB_ERROR_NO_DEVICE;
2638 case ERROR_ALREADY_EXISTS: // already claimed
2639 return LIBUSB_ERROR_BUSY;
2641 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2642 return LIBUSB_ERROR_ACCESS;
2646 usbi_dbg("claimed interface %d", iface);
2647 handle_priv->active_interface = iface;
2649 return LIBUSB_SUCCESS;
2652 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2654 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2655 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2656 HANDLE winusb_handle;
2658 CHECK_WINUSBX_AVAILABLE(sub_api);
2660 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2661 if (!HANDLE_VALID(winusb_handle))
2662 return LIBUSB_ERROR_NOT_FOUND;
2664 WinUSBX[sub_api].Free(winusb_handle);
2665 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2667 return LIBUSB_SUCCESS;
2671 * Return the first valid interface (of the same API type), for control transfers
2673 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2675 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2676 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2679 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2680 usbi_dbg("unsupported API ID");
2684 for (i = 0; i < USB_MAXINTERFACES; i++) {
2685 if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
2686 && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
2687 && (priv->usb_interface[i].apib->id == api_id))
2695 * Lookup interface by endpoint address. -1 if not found
2697 static int interface_by_endpoint(struct windows_device_priv *priv,
2698 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2702 for (i = 0; i < USB_MAXINTERFACES; i++) {
2703 if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
2705 if (priv->usb_interface[i].endpoint == NULL)
2707 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2708 if (priv->usb_interface[i].endpoint[j] == endpoint_address)
2716 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2718 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2719 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2720 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2721 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2722 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2723 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
2725 HANDLE winusb_handle;
2726 int current_interface;
2729 CHECK_WINUSBX_AVAILABLE(sub_api);
2731 transfer_priv->pollable_fd = INVALID_WINFD;
2732 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2734 // Windows places upper limits on the control transfer size
2735 // See: https://msdn.microsoft.com/en-us/library/windows/hardware/ff538112.aspx
2736 if (size > MAX_CTRL_BUFFER_LENGTH)
2737 return LIBUSB_ERROR_INVALID_PARAM;
2739 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2740 if (current_interface < 0) {
2741 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
2742 return LIBUSB_ERROR_NOT_FOUND;
2745 usbi_dbg("will use interface %d", current_interface);
2746 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2748 wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
2749 // Always use the handle returned from usbi_create_fd (wfd.handle)
2751 return LIBUSB_ERROR_NO_MEM;
2753 // Sending of set configuration control requests from WinUSB creates issues
2754 if ((LIBUSB_REQ_TYPE(setup->RequestType) == LIBUSB_REQUEST_TYPE_STANDARD)
2755 && (setup->Request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
2756 if (setup->Value != priv->active_config) {
2757 usbi_warn(ctx, "cannot set configuration other than the default one");
2759 return LIBUSB_ERROR_INVALID_PARAM;
2761 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2762 wfd.overlapped->InternalHigh = 0;
2764 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2765 if (GetLastError() != ERROR_IO_PENDING) {
2766 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
2768 return LIBUSB_ERROR_IO;
2771 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2772 wfd.overlapped->InternalHigh = (DWORD)size;
2776 // Use priv_transfer to store data needed for async polling
2777 transfer_priv->pollable_fd = wfd;
2778 transfer_priv->interface_number = (uint8_t)current_interface;
2780 return LIBUSB_SUCCESS;
2783 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2785 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2786 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2787 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2788 HANDLE winusb_handle;
2790 CHECK_WINUSBX_AVAILABLE(sub_api);
2792 if (altsetting > 255)
2793 return LIBUSB_ERROR_INVALID_PARAM;
2795 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2796 if (!HANDLE_VALID(winusb_handle)) {
2797 usbi_err(ctx, "interface must be claimed first");
2798 return LIBUSB_ERROR_NOT_FOUND;
2801 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2802 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2803 return LIBUSB_ERROR_IO;
2806 return LIBUSB_SUCCESS;
2809 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2811 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2812 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2813 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2814 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2815 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2816 HANDLE winusb_handle;
2818 int current_interface;
2821 CHECK_WINUSBX_AVAILABLE(sub_api);
2823 transfer_priv->pollable_fd = INVALID_WINFD;
2825 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2826 if (current_interface < 0) {
2827 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2828 return LIBUSB_ERROR_NOT_FOUND;
2831 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2833 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2835 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
2836 // Always use the handle returned from usbi_create_fd (wfd.handle)
2838 return LIBUSB_ERROR_NO_MEM;
2840 if (IS_XFERIN(transfer)) {
2841 usbi_dbg("reading %d bytes", transfer->length);
2842 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2844 usbi_dbg("writing %d bytes", transfer->length);
2845 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2849 if (GetLastError() != ERROR_IO_PENDING) {
2850 usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
2852 return LIBUSB_ERROR_IO;
2855 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2856 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2859 transfer_priv->pollable_fd = wfd;
2860 transfer_priv->interface_number = (uint8_t)current_interface;
2862 return LIBUSB_SUCCESS;
2865 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2867 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2868 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2869 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2870 HANDLE winusb_handle;
2871 int current_interface;
2873 CHECK_WINUSBX_AVAILABLE(sub_api);
2875 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2876 if (current_interface < 0) {
2877 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2878 return LIBUSB_ERROR_NOT_FOUND;
2881 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2882 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2884 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
2885 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
2886 return LIBUSB_ERROR_NO_DEVICE;
2889 return LIBUSB_SUCCESS;
2893 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2894 * through testing as well):
2895 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2896 * the control transfer using CancelIo"
2898 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
2900 // Cancelling of the I/O is done in the parent
2901 return LIBUSB_SUCCESS;
2904 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2906 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2907 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2908 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2909 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2910 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2911 HANDLE winusb_handle;
2912 int current_interface;
2914 CHECK_WINUSBX_AVAILABLE(sub_api);
2916 current_interface = transfer_priv->interface_number;
2917 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2918 usbi_err(ctx, "program assertion failed: invalid interface_number");
2919 return LIBUSB_ERROR_NOT_FOUND;
2921 usbi_dbg("will use interface %d", current_interface);
2923 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2925 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
2926 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
2927 return LIBUSB_ERROR_NO_DEVICE;
2930 return LIBUSB_SUCCESS;
2934 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2935 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2936 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2937 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2938 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2939 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2941 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2942 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2944 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2945 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2946 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2948 HANDLE winusb_handle;
2951 CHECK_WINUSBX_AVAILABLE(sub_api);
2953 // Reset any available pipe (except control)
2954 for (i = 0; i < USB_MAXINTERFACES; i++) {
2955 winusb_handle = handle_priv->interface_handle[i].api_handle;
2956 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0; ) {
2957 // Cancel any pollable I/O
2958 usbi_remove_pollfd(ctx, wfd.fd);
2960 wfd = handle_to_winfd(winusb_handle);
2963 if (HANDLE_VALID(winusb_handle)) {
2964 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2965 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2966 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2967 usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
2968 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2970 // FlushPipe seems to fail on OUT pipes
2971 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2972 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
2973 usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
2974 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2976 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2977 usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
2978 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2983 // libusbK & libusb0 have the ability to issue an actual device reset
2984 if (WinUSBX[sub_api].ResetDevice != NULL) {
2985 winusb_handle = handle_priv->interface_handle[0].api_handle;
2986 if (HANDLE_VALID(winusb_handle))
2987 WinUSBX[sub_api].ResetDevice(winusb_handle);
2990 return LIBUSB_SUCCESS;
2993 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2995 itransfer->transferred += io_size;
2996 return LIBUSB_TRANSFER_COMPLETED;
3000 * Internal HID Support functions (from libusb-win32)
3001 * Note that functions that complete data transfer synchronously must return
3002 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3004 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3005 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3007 static int _hid_wcslen(WCHAR *str)
3011 while (str[i] && (str[i] != 0x409))
3017 static int _hid_get_device_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3019 struct libusb_device_descriptor d;
3021 d.bLength = LIBUSB_DT_DEVICE_SIZE;
3022 d.bDescriptorType = LIBUSB_DT_DEVICE;
3023 d.bcdUSB = 0x0200; /* 2.00 */
3025 d.bDeviceSubClass = 0;
3026 d.bDeviceProtocol = 0;
3027 d.bMaxPacketSize0 = 64; /* fix this! */
3028 d.idVendor = (uint16_t)dev->vid;
3029 d.idProduct = (uint16_t)dev->pid;
3030 d.bcdDevice = 0x0100;
3031 d.iManufacturer = dev->string_index[0];
3032 d.iProduct = dev->string_index[1];
3033 d.iSerialNumber = dev->string_index[2];
3034 d.bNumConfigurations = 1;
3036 if (*size > LIBUSB_DT_DEVICE_SIZE)
3037 *size = LIBUSB_DT_DEVICE_SIZE;
3038 memcpy(data, &d, *size);
3040 return LIBUSB_COMPLETED;
3043 static int _hid_get_config_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3045 char num_endpoints = 0;
3046 size_t config_total_len = 0;
3047 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3048 struct libusb_config_descriptor *cd;
3049 struct libusb_interface_descriptor *id;
3050 struct libusb_hid_descriptor *hd;
3051 struct libusb_endpoint_descriptor *ed;
3054 if (dev->input_report_size)
3056 if (dev->output_report_size)
3059 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3060 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3062 cd = (struct libusb_config_descriptor *)tmp;
3063 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3064 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3065 + LIBUSB_DT_INTERFACE_SIZE);
3066 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3067 + LIBUSB_DT_INTERFACE_SIZE
3068 + LIBUSB_DT_HID_SIZE);
3070 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3071 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3072 cd->wTotalLength = (uint16_t)config_total_len;
3073 cd->bNumInterfaces = 1;
3074 cd->bConfigurationValue = 1;
3075 cd->iConfiguration = 0;
3076 cd->bmAttributes = 1 << 7; /* bus powered */
3079 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3080 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3081 id->bInterfaceNumber = 0;
3082 id->bAlternateSetting = 0;
3083 id->bNumEndpoints = num_endpoints;
3084 id->bInterfaceClass = 3;
3085 id->bInterfaceSubClass = 0;
3086 id->bInterfaceProtocol = 0;
3089 tmp_size = LIBUSB_DT_HID_SIZE;
3090 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3092 if (dev->input_report_size) {
3093 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3094 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3095 ed->bEndpointAddress = HID_IN_EP;
3096 ed->bmAttributes = 3;
3097 ed->wMaxPacketSize = dev->input_report_size - 1;
3099 ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
3102 if (dev->output_report_size) {
3103 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3104 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3105 ed->bEndpointAddress = HID_OUT_EP;
3106 ed->bmAttributes = 3;
3107 ed->wMaxPacketSize = dev->output_report_size - 1;
3111 if (*size > config_total_len)
3112 *size = config_total_len;
3113 memcpy(data, tmp, *size);
3115 return LIBUSB_COMPLETED;
3118 static int _hid_get_string_descriptor(struct hid_device_priv *dev, int _index,
3119 void *data, size_t *size)
3122 size_t tmp_size = 0;
3125 /* language ID, EN-US */
3126 char string_langid[] = {0x09, 0x04};
3128 if ((*size < 2) || (*size > 255))
3129 return LIBUSB_ERROR_OVERFLOW;
3132 tmp = string_langid;
3133 tmp_size = sizeof(string_langid) + 2;
3135 for (i = 0; i < 3; i++) {
3136 if (_index == (dev->string_index[i])) {
3137 tmp = dev->string[i];
3138 tmp_size = (_hid_wcslen(dev->string[i]) + 1) * sizeof(WCHAR);
3143 if (i == 3) // not found
3144 return LIBUSB_ERROR_INVALID_PARAM;
3148 return LIBUSB_ERROR_INVALID_PARAM;
3150 if (tmp_size < *size)
3154 ((uint8_t *)data)[0] = (uint8_t)*size;
3155 ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
3156 memcpy((uint8_t *)data + 2, tmp, *size - 2);
3158 return LIBUSB_COMPLETED;
3161 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3163 struct libusb_hid_descriptor d;
3164 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3165 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3167 _hid_get_report_descriptor(dev, tmp, &report_len);
3169 d.bLength = LIBUSB_DT_HID_SIZE;
3170 d.bDescriptorType = LIBUSB_DT_HID;
3171 d.bcdHID = 0x0110; /* 1.10 */
3173 d.bNumDescriptors = 1;
3174 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3175 d.wClassDescriptorLength = (uint16_t)report_len;
3177 if (*size > LIBUSB_DT_HID_SIZE)
3178 *size = LIBUSB_DT_HID_SIZE;
3179 memcpy(data, &d, *size);
3181 return LIBUSB_COMPLETED;
3184 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3186 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3189 /* usage page (0xFFA0 == vendor defined) */
3190 d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF;
3191 /* usage (vendor defined) */
3192 d[i++] = 0x09; d[i++] = 0x01;
3193 /* start collection (application) */
3194 d[i++] = 0xA1; d[i++] = 0x01;
3196 if (dev->input_report_size) {
3197 /* usage (vendor defined) */
3198 d[i++] = 0x09; d[i++] = 0x01;
3199 /* logical minimum (0) */
3200 d[i++] = 0x15; d[i++] = 0x00;
3201 /* logical maximum (255) */
3202 d[i++] = 0x25; d[i++] = 0xFF;
3203 /* report size (8 bits) */
3204 d[i++] = 0x75; d[i++] = 0x08;
3206 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3207 /* input (data, variable, absolute) */
3208 d[i++] = 0x81; d[i++] = 0x00;
3211 if (dev->output_report_size) {
3212 /* usage (vendor defined) */
3213 d[i++] = 0x09; d[i++] = 0x02;
3214 /* logical minimum (0) */
3215 d[i++] = 0x15; d[i++] = 0x00;
3216 /* logical maximum (255) */
3217 d[i++] = 0x25; d[i++] = 0xFF;
3218 /* report size (8 bits) */
3219 d[i++] = 0x75; d[i++] = 0x08;
3221 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3222 /* output (data, variable, absolute) */
3223 d[i++] = 0x91; d[i++] = 0x00;
3225 /* feature report */
3226 if (dev->feature_report_size) {
3227 /* usage (vendor defined) */
3228 d[i++] = 0x09; d[i++] = 0x03;
3229 /* logical minimum (0) */
3230 d[i++] = 0x15; d[i++] = 0x00;
3231 /* logical maximum (255) */
3232 d[i++] = 0x25; d[i++] = 0xFF;
3233 /* report size (8 bits) */
3234 d[i++] = 0x75; d[i++] = 0x08;
3236 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3237 /* feature (data, variable, absolute) */
3238 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3241 /* end collection */
3246 memcpy(data, d, *size);
3248 return LIBUSB_COMPLETED;
3251 static int _hid_get_descriptor(struct hid_device_priv *dev, HANDLE hid_handle, int recipient,
3252 int type, int _index, void *data, size_t *size)
3255 case LIBUSB_DT_DEVICE:
3256 usbi_dbg("LIBUSB_DT_DEVICE");
3257 return _hid_get_device_descriptor(dev, data, size);
3258 case LIBUSB_DT_CONFIG:
3259 usbi_dbg("LIBUSB_DT_CONFIG");
3261 return _hid_get_config_descriptor(dev, data, size);
3262 return LIBUSB_ERROR_INVALID_PARAM;
3263 case LIBUSB_DT_STRING:
3264 usbi_dbg("LIBUSB_DT_STRING");
3265 return _hid_get_string_descriptor(dev, _index, data, size);
3267 usbi_dbg("LIBUSB_DT_HID");
3269 return _hid_get_hid_descriptor(dev, data, size);
3270 return LIBUSB_ERROR_INVALID_PARAM;
3271 case LIBUSB_DT_REPORT:
3272 usbi_dbg("LIBUSB_DT_REPORT");
3274 return _hid_get_report_descriptor(dev, data, size);
3275 return LIBUSB_ERROR_INVALID_PARAM;
3276 case LIBUSB_DT_PHYSICAL:
3277 usbi_dbg("LIBUSB_DT_PHYSICAL");
3278 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3279 return LIBUSB_COMPLETED;
3280 return LIBUSB_ERROR_OTHER;
3283 usbi_dbg("unsupported");
3284 return LIBUSB_ERROR_NOT_SUPPORTED;
3287 static int _hid_get_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3288 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3291 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3292 int r = LIBUSB_SUCCESS;
3294 if (tp->hid_buffer != NULL)
3295 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3297 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3298 usbi_dbg("invalid size (%u)", *size);
3299 return LIBUSB_ERROR_INVALID_PARAM;
3302 switch (report_type) {
3303 case HID_REPORT_TYPE_INPUT:
3304 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3306 case HID_REPORT_TYPE_FEATURE:
3307 ioctl_code = IOCTL_HID_GET_FEATURE;
3310 usbi_dbg("unknown HID report type %d", report_type);
3311 return LIBUSB_ERROR_INVALID_PARAM;
3314 // Add a trailing byte to detect overflows
3315 buf = calloc(1, expected_size + 1);
3317 return LIBUSB_ERROR_NO_MEM;
3319 buf[0] = (uint8_t)id; // Must be set always
3320 usbi_dbg("report ID: 0x%02X", buf[0]);
3322 tp->hid_expected_size = expected_size;
3323 read_size = expected_size;
3325 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3326 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
3327 buf, expected_size + 1, &read_size, overlapped)) {
3328 if (GetLastError() != ERROR_IO_PENDING) {
3329 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3331 return LIBUSB_ERROR_IO;
3333 // Asynchronous wait
3334 tp->hid_buffer = buf;
3335 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3336 return LIBUSB_SUCCESS;
3339 // Transfer completed synchronously => copy and discard extra buffer
3340 if (read_size == 0) {
3341 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3345 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3347 if ((size_t)read_size > expected_size) {
3348 r = LIBUSB_ERROR_OVERFLOW;
3349 usbi_dbg("OVERFLOW!");
3351 r = LIBUSB_COMPLETED;
3354 *size = MIN((size_t)read_size, *size);
3356 memcpy(data, buf + 1, *size); // Discard report ID
3358 memcpy(data, buf, *size);
3365 static int _hid_set_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3366 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3368 uint8_t *buf = NULL;
3369 DWORD ioctl_code, write_size = (DWORD)*size;
3370 // If an id is reported, we must allow MAX_HID_REPORT_SIZE + 1
3371 size_t max_report_size = MAX_HID_REPORT_SIZE + (id ? 1 : 0);
3373 if (tp->hid_buffer != NULL)
3374 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3376 if ((*size == 0) || (*size > max_report_size)) {
3377 usbi_dbg("invalid size (%u)", *size);
3378 return LIBUSB_ERROR_INVALID_PARAM;
3381 switch (report_type) {
3382 case HID_REPORT_TYPE_OUTPUT:
3383 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3385 case HID_REPORT_TYPE_FEATURE:
3386 ioctl_code = IOCTL_HID_SET_FEATURE;
3389 usbi_dbg("unknown HID report type %d", report_type);
3390 return LIBUSB_ERROR_INVALID_PARAM;
3393 usbi_dbg("report ID: 0x%02X", id);
3394 // When report IDs are not used (i.e. when id == 0), we must add
3395 // a null report ID. Otherwise, we just use original data buffer
3399 buf = malloc(write_size);
3401 return LIBUSB_ERROR_NO_MEM;
3405 memcpy(buf + 1, data, *size);
3407 // This seems like a waste, but if we don't duplicate the
3408 // data, we'll get issues when freeing hid_buffer
3409 memcpy(buf, data, *size);
3411 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3414 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3415 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3416 buf, write_size, &write_size, overlapped)) {
3417 if (GetLastError() != ERROR_IO_PENDING) {
3418 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3420 return LIBUSB_ERROR_IO;
3422 tp->hid_buffer = buf;
3423 tp->hid_dest = NULL;
3424 return LIBUSB_SUCCESS;
3427 // Transfer completed synchronously
3429 if (write_size == 0)
3430 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3433 return LIBUSB_COMPLETED;
3436 static int _hid_class_request(struct hid_device_priv *dev, HANDLE hid_handle, int request_type,
3437 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3438 size_t *size, OVERLAPPED *overlapped)
3440 int report_type = (value >> 8) & 0xFF;
3441 int report_id = value & 0xFF;
3443 if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3444 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
3445 return LIBUSB_ERROR_INVALID_PARAM;
3447 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3448 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3450 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3451 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3453 return LIBUSB_ERROR_INVALID_PARAM;
3460 static int hid_init(int sub_api, struct libusb_context *ctx)
3462 DLL_GET_HANDLE(hid);
3463 DLL_LOAD_FUNC(hid, HidD_GetAttributes, TRUE);
3464 DLL_LOAD_FUNC(hid, HidD_GetHidGuid, TRUE);
3465 DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, TRUE);
3466 DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, TRUE);
3467 DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, TRUE);
3468 DLL_LOAD_FUNC(hid, HidD_GetProductString, TRUE);
3469 DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, TRUE);
3470 DLL_LOAD_FUNC(hid, HidP_GetCaps, TRUE);
3471 DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, TRUE);
3472 DLL_LOAD_FUNC(hid, HidD_SetFeature, TRUE);
3473 DLL_LOAD_FUNC(hid, HidD_GetFeature, TRUE);
3474 DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, TRUE);
3475 DLL_LOAD_FUNC(hid, HidD_GetInputReport, FALSE);
3476 DLL_LOAD_FUNC(hid, HidD_SetOutputReport, FALSE);
3477 DLL_LOAD_FUNC(hid, HidD_FlushQueue, TRUE);
3478 DLL_LOAD_FUNC(hid, HidP_GetValueCaps, TRUE);
3480 api_hid_available = true;
3481 return LIBUSB_SUCCESS;
3484 static int hid_exit(int sub_api)
3486 DLL_FREE_HANDLE(hid);
3488 return LIBUSB_SUCCESS;
3491 // NB: open and close must ensure that they only handle interface of
3492 // the right API type, as these functions can be called wholesale from
3493 // composite_open(), with interfaces belonging to different APIs
3494 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3496 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3497 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3498 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3499 HIDD_ATTRIBUTES hid_attributes;
3500 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3501 HIDP_CAPS capabilities;
3502 HIDP_VALUE_CAPS *value_caps;
3503 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3505 // report IDs handling
3507 int nb_ids[2]; // zero and nonzero report IDs
3508 #if defined(ENABLE_LOGGING)
3509 const char *type[3] = {"input", "output", "feature"};
3512 CHECK_HID_AVAILABLE;
3514 if (priv->hid == NULL) {
3515 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3516 return LIBUSB_ERROR_NOT_FOUND;
3519 for (i = 0; i < USB_MAXINTERFACES; i++) {
3520 if ((priv->usb_interface[i].path != NULL)
3521 && (priv->usb_interface[i].apib->id == USB_API_HID)) {
3522 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3523 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3525 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3526 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3527 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3528 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3529 * HidD_GetFeature (if the device supports Feature reports)."
3531 if (hid_handle == INVALID_HANDLE_VALUE) {
3532 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3533 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3534 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3535 if (hid_handle == INVALID_HANDLE_VALUE) {
3536 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3537 switch(GetLastError()) {
3538 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3539 return LIBUSB_ERROR_NO_DEVICE;
3540 case ERROR_ACCESS_DENIED:
3541 return LIBUSB_ERROR_ACCESS;
3543 return LIBUSB_ERROR_IO;
3546 priv->usb_interface[i].restricted_functionality = true;
3548 handle_priv->interface_handle[i].api_handle = hid_handle;
3552 hid_attributes.Size = sizeof(hid_attributes);
3554 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3555 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3559 priv->hid->vid = hid_attributes.VendorID;
3560 priv->hid->pid = hid_attributes.ProductID;
3562 // Set the maximum available input buffer size
3563 for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
3564 usbi_dbg("set maximum input buffer size to %d", i / 2);
3566 // Get the maximum input and output report size
3567 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3568 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3571 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3572 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3576 // Find out if interrupt will need report IDs
3577 size[0] = capabilities.NumberInputValueCaps;
3578 size[1] = capabilities.NumberOutputValueCaps;
3579 size[2] = capabilities.NumberFeatureValueCaps;
3580 for (j = HidP_Input; j <= HidP_Feature; j++) {
3581 usbi_dbg("%u HID %s report value(s) found", (unsigned int)size[j], type[j]);
3582 priv->hid->uses_report_ids[j] = false;
3584 value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3585 if ((value_caps != NULL)
3586 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3587 && (size[j] >= 1)) {
3590 for (i = 0; i < (int)size[j]; i++) {
3591 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3592 if (value_caps[i].ReportID != 0)
3597 if (nb_ids[1] != 0) {
3599 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3601 priv->hid->uses_report_ids[j] = true;
3604 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3610 // Set the report sizes
3611 priv->hid->input_report_size = capabilities.InputReportByteLength;
3612 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3613 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3615 // Fetch string descriptors
3616 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3617 if (priv->hid->string_index[0] != 0)
3618 HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
3620 priv->hid->string[0][0] = 0;
3622 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3623 if (priv->hid->string_index[1] != 0)
3624 HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1]));
3626 priv->hid->string[1][0] = 0;
3628 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3629 if (priv->hid->string_index[2] != 0)
3630 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
3632 priv->hid->string[2][0] = 0;
3636 HidD_FreePreparsedData(preparsed_data);
3638 return LIBUSB_SUCCESS;
3641 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3643 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3644 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3648 if (!api_hid_available)
3651 for (i = 0; i < USB_MAXINTERFACES; i++) {
3652 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3653 file_handle = handle_priv->interface_handle[i].api_handle;
3654 if (HANDLE_VALID(file_handle))
3655 CloseHandle(file_handle);
3660 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3662 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3663 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3665 CHECK_HID_AVAILABLE;
3667 // NB: Disconnection detection is not possible in this function
3668 if (priv->usb_interface[iface].path == NULL)
3669 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3671 // We use dev_handle as a flag for interface claimed
3672 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
3673 return LIBUSB_ERROR_BUSY; // already claimed
3676 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3678 usbi_dbg("claimed interface %d", iface);
3679 handle_priv->active_interface = iface;
3681 return LIBUSB_SUCCESS;
3684 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3686 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3687 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3689 CHECK_HID_AVAILABLE;
3691 if (priv->usb_interface[iface].path == NULL)
3692 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3694 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
3695 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3697 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3699 return LIBUSB_SUCCESS;
3702 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3704 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3706 CHECK_HID_AVAILABLE;
3708 if (altsetting > 255)
3709 return LIBUSB_ERROR_INVALID_PARAM;
3711 if (altsetting != 0) {
3712 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3713 return LIBUSB_ERROR_NOT_SUPPORTED;
3716 return LIBUSB_SUCCESS;
3719 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3721 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3722 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3723 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3724 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3725 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3726 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
3729 int current_interface, config;
3731 int r = LIBUSB_ERROR_INVALID_PARAM;
3733 CHECK_HID_AVAILABLE;
3735 transfer_priv->pollable_fd = INVALID_WINFD;
3736 safe_free(transfer_priv->hid_buffer);
3737 transfer_priv->hid_dest = NULL;
3738 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3740 if (size > MAX_CTRL_BUFFER_LENGTH)
3741 return LIBUSB_ERROR_INVALID_PARAM;
3743 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3744 if (current_interface < 0) {
3745 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS)
3746 return LIBUSB_ERROR_NOT_FOUND;
3749 usbi_dbg("will use interface %d", current_interface);
3750 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3751 // Always use the handle returned from usbi_create_fd (wfd.handle)
3752 wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
3754 return LIBUSB_ERROR_NOT_FOUND;
3756 switch(LIBUSB_REQ_TYPE(setup->RequestType)) {
3757 case LIBUSB_REQUEST_TYPE_STANDARD:
3758 switch(setup->Request) {
3759 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3760 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->RequestType),
3761 (setup->Value >> 8) & 0xFF, setup->Value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3763 case LIBUSB_REQUEST_GET_CONFIGURATION:
3764 r = windows_get_configuration(transfer->dev_handle, &config);
3765 if (r == LIBUSB_SUCCESS) {
3767 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3768 r = LIBUSB_COMPLETED;
3771 case LIBUSB_REQUEST_SET_CONFIGURATION:
3772 if (setup->Value == priv->active_config) {
3773 r = LIBUSB_COMPLETED;
3775 usbi_warn(ctx, "cannot set configuration other than the default one");
3776 r = LIBUSB_ERROR_NOT_SUPPORTED;
3779 case LIBUSB_REQUEST_GET_INTERFACE:
3781 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3782 r = LIBUSB_COMPLETED;
3784 case LIBUSB_REQUEST_SET_INTERFACE:
3785 r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->Index, setup->Value);
3786 if (r == LIBUSB_SUCCESS)
3787 r = LIBUSB_COMPLETED;
3790 usbi_warn(ctx, "unsupported HID control request");
3791 r = LIBUSB_ERROR_NOT_SUPPORTED;
3795 case LIBUSB_REQUEST_TYPE_CLASS:
3796 r = _hid_class_request(priv->hid, wfd.handle, setup->RequestType, setup->Request, setup->Value,
3797 setup->Index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3798 &size, wfd.overlapped);
3801 usbi_warn(ctx, "unsupported HID control request");
3802 r = LIBUSB_ERROR_NOT_SUPPORTED;
3806 if (r == LIBUSB_COMPLETED) {
3807 // Force request to be completed synchronously. Transferred size has been set by previous call
3808 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3809 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3810 // set InternalHigh to the number of bytes transferred
3811 wfd.overlapped->InternalHigh = (DWORD)size;
3815 if (r == LIBUSB_SUCCESS) {
3816 // Use priv_transfer to store data needed for async polling
3817 transfer_priv->pollable_fd = wfd;
3818 transfer_priv->interface_number = (uint8_t)current_interface;
3826 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3828 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3829 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3830 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3831 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3832 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3835 bool direction_in, ret;
3836 int current_interface, length;
3838 int r = LIBUSB_SUCCESS;
3840 CHECK_HID_AVAILABLE;
3842 transfer_priv->pollable_fd = INVALID_WINFD;
3843 transfer_priv->hid_dest = NULL;
3844 safe_free(transfer_priv->hid_buffer);
3846 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3847 if (current_interface < 0) {
3848 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3849 return LIBUSB_ERROR_NOT_FOUND;
3852 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3854 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3855 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3857 wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
3858 // Always use the handle returned from usbi_create_fd (wfd.handle)
3860 return LIBUSB_ERROR_NO_MEM;
3862 // If report IDs are not in use, an extra prefix byte must be added
3863 if (((direction_in) && (!priv->hid->uses_report_ids[0]))
3864 || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
3865 length = transfer->length + 1;
3867 length = transfer->length;
3869 // Add a trailing byte to detect overflows on input
3870 transfer_priv->hid_buffer = calloc(1, length + 1);
3871 if (transfer_priv->hid_buffer == NULL)
3872 return LIBUSB_ERROR_NO_MEM;
3874 transfer_priv->hid_expected_size = length;
3877 transfer_priv->hid_dest = transfer->buffer;
3878 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
3879 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length + 1, &size, wfd.overlapped);
3881 if (!priv->hid->uses_report_ids[1])
3882 memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
3884 // We could actually do without the calloc and memcpy in this case
3885 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3887 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3888 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3892 if (GetLastError() != ERROR_IO_PENDING) {
3893 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3895 safe_free(transfer_priv->hid_buffer);
3896 return LIBUSB_ERROR_IO;
3899 // Only write operations that completed synchronously need to free up
3900 // hid_buffer. For reads, copy_transfer_data() handles that process.
3902 safe_free(transfer_priv->hid_buffer);
3905 usbi_err(ctx, "program assertion failed - no data was transferred");
3908 if (size > (size_t)length) {
3909 usbi_err(ctx, "OVERFLOW!");
3910 r = LIBUSB_ERROR_OVERFLOW;
3912 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3913 wfd.overlapped->InternalHigh = size;
3916 transfer_priv->pollable_fd = wfd;
3917 transfer_priv->interface_number = (uint8_t)current_interface;
3922 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3924 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3925 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3926 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3928 int current_interface;
3930 CHECK_HID_AVAILABLE;
3932 current_interface = transfer_priv->interface_number;
3933 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3934 CancelIo(hid_handle);
3936 return LIBUSB_SUCCESS;
3939 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3941 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3943 int current_interface;
3945 CHECK_HID_AVAILABLE;
3947 // Flushing the queues on all interfaces is the best we can achieve
3948 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3949 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3950 if (HANDLE_VALID(hid_handle))
3951 HidD_FlushQueue(hid_handle);
3954 return LIBUSB_SUCCESS;
3957 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3959 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3960 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3961 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3963 int current_interface;
3965 CHECK_HID_AVAILABLE;
3967 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3968 if (current_interface < 0) {
3969 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3970 return LIBUSB_ERROR_NOT_FOUND;
3973 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3974 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3976 // No endpoint selection with Microsoft's implementation, so we try to flush the
3977 // whole interface. Should be OK for most case scenarios
3978 if (!HidD_FlushQueue(hid_handle)) {
3979 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3980 // Device was probably disconnected
3981 return LIBUSB_ERROR_NO_DEVICE;
3984 return LIBUSB_SUCCESS;
3987 // This extra function is only needed for HID
3988 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3990 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3991 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3992 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3993 int r = LIBUSB_TRANSFER_COMPLETED;
3994 uint32_t corrected_size = io_size;
3996 if (transfer_priv->hid_buffer != NULL) {
3997 // If we have a valid hid_buffer, it means the transfer was async
3998 if (transfer_priv->hid_dest != NULL) { // Data readout
3999 if (corrected_size > 0) {
4000 // First, check for overflow
4001 if (corrected_size > transfer_priv->hid_expected_size) {
4002 usbi_err(ctx, "OVERFLOW!");
4003 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4004 r = LIBUSB_TRANSFER_OVERFLOW;
4007 if (transfer_priv->hid_buffer[0] == 0) {
4008 // Discard the 1 byte report ID prefix
4010 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, corrected_size);
4012 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4015 transfer_priv->hid_dest = NULL;
4017 // For write, we just need to free the hid buffer
4018 safe_free(transfer_priv->hid_buffer);
4021 itransfer->transferred += corrected_size;
4027 * Composite API functions
4029 static int composite_init(int sub_api, struct libusb_context *ctx)
4031 return LIBUSB_SUCCESS;
4034 static int composite_exit(int sub_api)
4036 return LIBUSB_SUCCESS;
4039 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4041 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4042 int r = LIBUSB_ERROR_NOT_FOUND;
4044 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4045 bool available[SUB_API_MAX + 1] = { 0 };
4047 for (i = 0; i < USB_MAXINTERFACES; i++) {
4048 switch (priv->usb_interface[i].apib->id) {
4049 case USB_API_WINUSBX:
4050 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4051 available[priv->usb_interface[i].sub_api] = true;
4054 available[SUB_API_MAX] = true;
4061 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4063 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4064 if (r != LIBUSB_SUCCESS)
4069 if (available[SUB_API_MAX]) // HID driver
4070 r = hid_open(SUB_API_NOTSET, dev_handle);
4075 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4077 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4079 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4080 bool available[SUB_API_MAX + 1] = { 0 };
4082 for (i = 0; i < USB_MAXINTERFACES; i++) {
4083 switch (priv->usb_interface[i].apib->id) {
4084 case USB_API_WINUSBX:
4085 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4086 available[priv->usb_interface[i].sub_api] = true;
4089 available[SUB_API_MAX] = true;
4096 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4098 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4101 if (available[SUB_API_MAX]) // HID driver
4102 hid_close(SUB_API_NOTSET, dev_handle);
4105 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4107 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4109 return priv->usb_interface[iface].apib->
4110 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4113 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4115 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4117 return priv->usb_interface[iface].apib->
4118 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4121 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4123 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4125 return priv->usb_interface[iface].apib->
4126 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4129 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4131 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4132 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4133 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4134 struct libusb_config_descriptor *conf_desc;
4135 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
4138 // Interface shouldn't matter for control, but it does in practice, with Windows'
4139 // restrictions with regards to accessing HID keyboards and mice. Try to target
4140 // a specific interface first, if possible.
4141 switch (LIBUSB_REQ_RECIPIENT(setup->RequestType)) {
4142 case LIBUSB_RECIPIENT_INTERFACE:
4143 iface = setup->Index & 0xFF;
4145 case LIBUSB_RECIPIENT_ENDPOINT:
4146 r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc);
4147 if (r == LIBUSB_SUCCESS) {
4148 iface = get_interface_by_endpoint(conf_desc, (setup->Index & 0xFF));
4149 libusb_free_config_descriptor(conf_desc);
4152 // Fall through if not able to determine interface
4158 // Try and target a specific interface if the control setup indicates such
4159 if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4160 usbi_dbg("attempting control transfer targeted to interface %d", iface);
4161 if (priv->usb_interface[iface].path != NULL) {
4162 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4163 if (r == LIBUSB_SUCCESS)
4168 // Either not targeted to a specific interface or no luck in doing so.
4169 // Try a 2 pass approach with all interfaces.
4170 for (pass = 0; pass < 2; pass++) {
4171 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4172 if (priv->usb_interface[iface].path != NULL) {
4173 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4174 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4177 usbi_dbg("using interface %d", iface);
4178 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4179 // If not supported on this API, it may be supported on another, so don't give up yet!!
4180 if (r == LIBUSB_ERROR_NOT_SUPPORTED)
4187 usbi_err(ctx, "no libusb supported interfaces to complete request");
4188 return LIBUSB_ERROR_NOT_FOUND;
4191 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4192 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4193 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4194 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4195 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4196 int current_interface;
4198 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4199 if (current_interface < 0) {
4200 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4201 return LIBUSB_ERROR_NOT_FOUND;
4204 return priv->usb_interface[current_interface].apib->
4205 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4208 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4209 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4210 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4211 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4212 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4213 int current_interface;
4215 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4216 if (current_interface < 0) {
4217 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4218 return LIBUSB_ERROR_NOT_FOUND;
4221 return priv->usb_interface[current_interface].apib->
4222 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4225 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4227 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4228 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4229 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4230 int current_interface;
4232 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4233 if (current_interface < 0) {
4234 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4235 return LIBUSB_ERROR_NOT_FOUND;
4238 return priv->usb_interface[current_interface].apib->
4239 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
4242 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4244 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4245 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4246 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4248 return priv->usb_interface[transfer_priv->interface_number].apib->
4249 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4252 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4254 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4255 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4256 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4258 return priv->usb_interface[transfer_priv->interface_number].apib->
4259 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4262 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4264 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4267 bool available[SUB_API_MAX];
4269 for (i = 0; i < SUB_API_MAX; i++)
4270 available[i] = false;
4272 for (i = 0; i < USB_MAXINTERFACES; i++) {
4273 if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4274 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
4275 available[priv->usb_interface[i].sub_api] = true;
4278 for (i = 0; i < SUB_API_MAX; i++) {
4280 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4281 if (r != LIBUSB_SUCCESS)
4286 return LIBUSB_SUCCESS;
4289 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4291 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4292 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4293 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4295 return priv->usb_interface[transfer_priv->interface_number].apib->
4296 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
4299 #endif /* !USE_USBDK */