2 * windows backend for libusb 1.0
3 * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4 * Copyright © 2016-2018 Chris Dickens <christopher.a.dickens@gmail.com>
5 * With contributions from Michael Plante, Orin Eman et al.
6 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
7 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
8 * Hash table functions adapted from glibc, by Ulrich Drepper et al.
9 * Major code testing contribution by Xiaofan Chen
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include "windows_winusb.h"
36 #define HANDLE_VALID(h) (((h) != NULL) && ((h) != INVALID_HANDLE_VALUE))
38 // The below macro is used in conjunction with safe loops.
39 #define LOOP_BREAK(err) \
45 // WinUSB-like API prototypes
46 static bool winusbx_init(struct libusb_context *ctx);
47 static void winusbx_exit(void);
48 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
49 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
50 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
51 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
52 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
53 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
54 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting);
55 static int winusbx_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
56 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
57 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
58 static int winusbx_cancel_transfer(int sub_api, struct usbi_transfer *itransfer);
59 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
60 static enum libusb_transfer_status winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length);
62 static bool hid_init(struct libusb_context *ctx);
63 static void hid_exit(void);
64 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
65 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
66 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
67 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
68 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting);
69 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
70 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
71 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
72 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
73 static enum libusb_transfer_status hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length);
74 // Composite API prototypes
75 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
76 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
77 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
78 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting);
79 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
80 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
81 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
82 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
83 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
84 static int composite_cancel_transfer(int sub_api, struct usbi_transfer *itransfer);
85 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
86 static enum libusb_transfer_status composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length);
88 static usbi_mutex_t autoclaim_lock;
91 static struct winusb_interface WinUSBX[SUB_API_MAX];
92 #define CHECK_WINUSBX_AVAILABLE(sub_api) \
94 if (sub_api == SUB_API_NOTSET) \
95 sub_api = priv->sub_api; \
96 if (WinUSBX[sub_api].hDll == NULL) \
97 return LIBUSB_ERROR_ACCESS; \
100 #define CHECK_HID_AVAILABLE \
102 if (DLL_HANDLE_NAME(hid) == NULL) \
103 return LIBUSB_ERROR_ACCESS; \
106 #if defined(ENABLE_LOGGING)
107 static const char *guid_to_string(const GUID *guid, char guid_string[MAX_GUID_STRING_LENGTH])
110 guid_string[0] = '\0';
114 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
115 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
116 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
117 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
123 static bool string_to_guid(const char guid_string[MAX_GUID_STRING_LENGTH], GUID *guid)
125 unsigned short tmp[4];
130 // Unfortunately MinGW complains that '%hhx' is not a valid format specifier,
131 // even though Visual Studio 2013 and later support it. Rather than complicating
132 // the logic in this function with '#ifdef's, use a temporary array on the stack
133 // to store the conversions.
134 r = sscanf(guid_string, "{%8x-%4hx-%4hx-%4hx-%4hx%4hx%4hx}%n%c",
135 (unsigned int *)&guid->Data1, &guid->Data2, &guid->Data3,
136 &tmp[0], &tmp[1], &tmp[2], &tmp[3], &num_chars, &extra);
138 if ((r != 7) || (num_chars != 38))
141 // Extract the bytes from the 2-byte shorts
142 guid->Data4[0] = (unsigned char)((tmp[0] >> 8) & 0xFF);
143 guid->Data4[1] = (unsigned char)(tmp[0] & 0xFF);
144 guid->Data4[2] = (unsigned char)((tmp[1] >> 8) & 0xFF);
145 guid->Data4[3] = (unsigned char)(tmp[1] & 0xFF);
146 guid->Data4[4] = (unsigned char)((tmp[2] >> 8) & 0xFF);
147 guid->Data4[5] = (unsigned char)(tmp[2] & 0xFF);
148 guid->Data4[6] = (unsigned char)((tmp[3] >> 8) & 0xFF);
149 guid->Data4[7] = (unsigned char)(tmp[3] & 0xFF);
155 * Normalize Microsoft's paths: return a duplicate of the given path
156 * with all characters converted to uppercase
158 static char *normalize_path(const char *path)
160 char *ret_path = _strdup(path);
163 if (ret_path == NULL)
166 for (p = ret_path; *p != '\0'; p++)
167 *p = (char)toupper((unsigned char)*p);
173 * Cfgmgr32, AdvAPI32, OLE32 and SetupAPI DLL functions
175 static bool init_dlls(struct libusb_context *ctx)
177 DLL_GET_HANDLE(ctx, Cfgmgr32);
178 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Parent, true);
179 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Child, true);
181 // Prefixed to avoid conflict with header files
182 DLL_GET_HANDLE(ctx, AdvAPI32);
183 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegQueryValueExA, true);
184 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegCloseKey, true);
186 DLL_GET_HANDLE(ctx, SetupAPI);
187 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetClassDevsA, true);
188 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInfo, true);
189 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInterfaces, true);
190 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInstanceIdA, true);
191 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInterfaceDetailA, true);
192 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceRegistryPropertyA, true);
193 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiDestroyDeviceInfoList, true);
194 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDevRegKey, true);
195 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDeviceInterfaceRegKey, true);
200 static void exit_dlls(void)
202 DLL_FREE_HANDLE(SetupAPI);
203 DLL_FREE_HANDLE(AdvAPI32);
204 DLL_FREE_HANDLE(Cfgmgr32);
208 * enumerate interfaces for the whole USB class
211 * dev_info: a pointer to a dev_info list
212 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
213 * enumerator: the generic USB class for which to retrieve interface details
214 * index: zero based index of the interface in the device info list
216 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
217 * structure returned and call this function repeatedly using the same guid (with an
218 * incremented index starting at zero) until all interfaces have been returned.
220 static bool get_devinfo_data(struct libusb_context *ctx,
221 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char *enumerator, unsigned _index)
224 *dev_info = pSetupDiGetClassDevsA(NULL, enumerator, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
225 if (*dev_info == INVALID_HANDLE_VALUE) {
226 usbi_err(ctx, "could not obtain device info set for PnP enumerator '%s': %s",
227 enumerator, windows_error_str(0));
232 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
233 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
234 if (GetLastError() != ERROR_NO_MORE_ITEMS)
235 usbi_err(ctx, "could not obtain device info data for PnP enumerator '%s' index %u: %s",
236 enumerator, _index, windows_error_str(0));
238 pSetupDiDestroyDeviceInfoList(*dev_info);
239 *dev_info = INVALID_HANDLE_VALUE;
246 * enumerate interfaces for a specific GUID
249 * dev_info: a pointer to a dev_info list
250 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
251 * guid: the GUID for which to retrieve interface details
252 * index: zero based index of the interface in the device info list
254 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
255 * structure returned and call this function repeatedly using the same guid (with an
256 * incremented index starting at zero) until all interfaces have been returned.
258 static int get_interface_details(struct libusb_context *ctx, HDEVINFO dev_info,
259 PSP_DEVINFO_DATA dev_info_data, LPCGUID guid, DWORD *_index, char **dev_interface_path)
261 SP_DEVICE_INTERFACE_DATA dev_interface_data;
262 PSP_DEVICE_INTERFACE_DETAIL_DATA_A dev_interface_details;
263 char guid_string[MAX_GUID_STRING_LENGTH];
266 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
267 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
269 if (!pSetupDiEnumDeviceInfo(dev_info, *_index, dev_info_data)) {
270 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
271 usbi_err(ctx, "Could not obtain device info data for %s index %lu: %s",
272 guid_to_string(guid, guid_string), ULONG_CAST(*_index), windows_error_str(0));
273 return LIBUSB_ERROR_OTHER;
277 return LIBUSB_SUCCESS;
280 // Always advance the index for the next iteration
283 if (pSetupDiEnumDeviceInterfaces(dev_info, dev_info_data, guid, 0, &dev_interface_data))
286 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
287 usbi_err(ctx, "Could not obtain interface data for %s devInst %lX: %s",
288 guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst), windows_error_str(0));
289 return LIBUSB_ERROR_OTHER;
292 // Device does not have an interface matching this GUID, skip
295 // Read interface data (dummy + actual) to access the device path
296 if (!pSetupDiGetDeviceInterfaceDetailA(dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
297 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
298 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
299 usbi_err(ctx, "could not access interface data (dummy) for %s devInst %lX: %s",
300 guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst), windows_error_str(0));
301 return LIBUSB_ERROR_OTHER;
304 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong");
305 return LIBUSB_ERROR_OTHER;
308 dev_interface_details = malloc(size);
309 if (dev_interface_details == NULL) {
310 usbi_err(ctx, "could not allocate interface data for %s devInst %lX",
311 guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst));
312 return LIBUSB_ERROR_NO_MEM;
315 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
316 if (!pSetupDiGetDeviceInterfaceDetailA(dev_info, &dev_interface_data,
317 dev_interface_details, size, NULL, NULL)) {
318 usbi_err(ctx, "could not access interface data (actual) for %s devInst %lX: %s",
319 guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst), windows_error_str(0));
320 free(dev_interface_details);
321 return LIBUSB_ERROR_OTHER;
324 *dev_interface_path = normalize_path(dev_interface_details->DevicePath);
325 free(dev_interface_details);
327 if (*dev_interface_path == NULL) {
328 usbi_err(ctx, "could not allocate interface path for %s devInst %lX",
329 guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst));
330 return LIBUSB_ERROR_NO_MEM;
333 return LIBUSB_SUCCESS;
336 /* For libusb0 filter */
337 static int get_interface_details_filter(struct libusb_context *ctx, HDEVINFO *dev_info,
338 DWORD _index, char *filter_path, char **dev_interface_path)
340 const GUID *libusb0_guid = &GUID_DEVINTERFACE_LIBUSB0_FILTER;
341 SP_DEVICE_INTERFACE_DATA dev_interface_data;
342 PSP_DEVICE_INTERFACE_DETAIL_DATA_A dev_interface_details;
343 HKEY hkey_dev_interface;
345 int err = LIBUSB_ERROR_OTHER;
348 *dev_info = pSetupDiGetClassDevsA(libusb0_guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
349 if (*dev_info == INVALID_HANDLE_VALUE) {
350 usbi_err(ctx, "could not obtain device info set: %s", windows_error_str(0));
351 return LIBUSB_ERROR_OTHER;
355 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
356 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, libusb0_guid, _index, &dev_interface_data)) {
357 if (GetLastError() != ERROR_NO_MORE_ITEMS) {
358 usbi_err(ctx, "Could not obtain interface data for index %lu: %s",
359 ULONG_CAST(_index), windows_error_str(0));
363 pSetupDiDestroyDeviceInfoList(*dev_info);
364 *dev_info = INVALID_HANDLE_VALUE;
365 return LIBUSB_SUCCESS;
368 // Read interface data (dummy + actual) to access the device path
369 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
370 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
371 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
372 usbi_err(ctx, "could not access interface data (dummy) for index %lu: %s",
373 ULONG_CAST(_index), windows_error_str(0));
377 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong");
381 dev_interface_details = malloc(size);
382 if (dev_interface_details == NULL) {
383 usbi_err(ctx, "could not allocate interface data for index %lu", ULONG_CAST(_index));
384 err = LIBUSB_ERROR_NO_MEM;
388 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
389 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, dev_interface_details, size, NULL, NULL)) {
390 usbi_err(ctx, "could not access interface data (actual) for index %lu: %s",
391 ULONG_CAST(_index), windows_error_str(0));
392 free(dev_interface_details);
396 *dev_interface_path = normalize_path(dev_interface_details->DevicePath);
397 free(dev_interface_details);
399 if (*dev_interface_path == NULL) {
400 usbi_err(ctx, "could not allocate interface path for index %lu", ULONG_CAST(_index));
401 err = LIBUSB_ERROR_NO_MEM;
405 // [trobinso] lookup the libusb0 symbolic index.
406 hkey_dev_interface = pSetupDiOpenDeviceInterfaceRegKey(*dev_info, &dev_interface_data, 0, KEY_READ);
407 if (hkey_dev_interface != INVALID_HANDLE_VALUE) {
408 DWORD libusb0_symboliclink_index = 0;
409 DWORD value_length = sizeof(DWORD);
412 status = pRegQueryValueExA(hkey_dev_interface, "LUsb0", NULL, NULL,
413 (LPBYTE)&libusb0_symboliclink_index, &value_length);
414 if (status == ERROR_SUCCESS) {
415 if (libusb0_symboliclink_index < 256) {
416 // libusb0.sys is connected to this device instance.
417 // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
418 sprintf(filter_path, "\\\\.\\libusb0-%04u", (unsigned int)libusb0_symboliclink_index);
419 usbi_dbg(ctx, "assigned libusb0 symbolic link %s", filter_path);
421 // libusb0.sys was connected to this device instance at one time; but not anymore.
424 pRegCloseKey(hkey_dev_interface);
426 usbi_warn(ctx, "could not open device interface registry key for index %lu: %s",
427 ULONG_CAST(_index), windows_error_str(0));
428 // TODO: should this be an error?
431 return LIBUSB_SUCCESS;
434 pSetupDiDestroyDeviceInfoList(*dev_info);
435 *dev_info = INVALID_HANDLE_VALUE;
440 * Returns the first known ancestor of a device
442 static struct libusb_device *get_ancestor(struct libusb_context *ctx,
443 DEVINST devinst, PDEVINST _parent_devinst)
445 struct libusb_device *dev = NULL;
446 DEVINST parent_devinst;
448 while (dev == NULL) {
449 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS)
451 devinst = parent_devinst;
452 dev = usbi_get_device_by_session_id(ctx, (unsigned long)devinst);
455 if ((dev != NULL) && (_parent_devinst != NULL))
456 *_parent_devinst = devinst;
462 * Determine which interface the given endpoint address belongs to
464 static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep)
466 const struct libusb_interface *intf;
467 const struct libusb_interface_descriptor *intf_desc;
471 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
472 intf = &conf_desc->interface[i];
473 for (j = 0; j < intf->num_altsetting; j++) {
474 intf_desc = &intf->altsetting[j];
475 for (k = 0; k < intf_desc->bNumEndpoints; k++) {
476 if (intf_desc->endpoint[k].bEndpointAddress == ep) {
477 usbi_dbg(NULL, "found endpoint %02X on interface %d", intf_desc->bInterfaceNumber, i);
478 return intf_desc->bInterfaceNumber;
484 usbi_dbg(NULL, "endpoint %02X not found on any interface", ep);
485 return LIBUSB_ERROR_NOT_FOUND;
489 * Open a device and associate the HANDLE with the context's I/O completion port
491 static HANDLE windows_open(struct libusb_device_handle *dev_handle, const char *path, DWORD access)
493 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
494 struct windows_context_priv *priv = usbi_get_context_priv(ctx);
497 handle = CreateFileA(path, access, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
498 if (handle == INVALID_HANDLE_VALUE)
501 if (CreateIoCompletionPort(handle, priv->completion_port, (ULONG_PTR)dev_handle, 0) == NULL) {
502 usbi_err(ctx, "failed to associate handle to I/O completion port: %s", windows_error_str(0));
504 return INVALID_HANDLE_VALUE;
511 * Populate the endpoints addresses of the device_priv interface helper structs
513 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
515 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
516 struct libusb_config_descriptor *conf_desc;
517 const struct libusb_interface_descriptor *if_desc;
520 r = libusb_get_active_config_descriptor(dev_handle->dev, &conf_desc);
521 if (r != LIBUSB_SUCCESS) {
522 usbi_warn(HANDLE_CTX(dev_handle), "could not read config descriptor: error %d", r);
526 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
527 safe_free(priv->usb_interface[iface].endpoint);
529 if (if_desc->bNumEndpoints == 0) {
530 usbi_dbg(HANDLE_CTX(dev_handle), "no endpoints found for interface %u", iface);
531 libusb_free_config_descriptor(conf_desc);
532 priv->usb_interface[iface].current_altsetting = altsetting;
533 return LIBUSB_SUCCESS;
536 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
537 if (priv->usb_interface[iface].endpoint == NULL) {
538 libusb_free_config_descriptor(conf_desc);
539 return LIBUSB_ERROR_NO_MEM;
542 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
543 for (i = 0; i < if_desc->bNumEndpoints; i++) {
544 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
545 usbi_dbg(HANDLE_CTX(dev_handle), "(re)assigned endpoint %02X to interface %u", priv->usb_interface[iface].endpoint[i], iface);
547 libusb_free_config_descriptor(conf_desc);
549 // Extra init may be required to configure endpoints
550 if (priv->apib->configure_endpoints)
551 r = priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
553 if (r == LIBUSB_SUCCESS)
554 priv->usb_interface[iface].current_altsetting = altsetting;
559 // Lookup for a match in the list of API driver names
560 // return -1 if not found, driver match number otherwise
561 static int get_sub_api(char *driver, int api)
563 const char sep_str[2] = {LIST_SEPARATOR, 0};
565 size_t len = strlen(driver);
569 return SUB_API_NOTSET;
571 tmp_str = _strdup(driver);
573 return SUB_API_NOTSET;
575 tok = strtok(tmp_str, sep_str);
576 while (tok != NULL) {
577 for (i = 0; i < usb_api_backend[api].nb_driver_names; i++) {
578 if (_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
583 tok = strtok(NULL, sep_str);
587 return SUB_API_NOTSET;
591 * auto-claiming and auto-release helper functions
593 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
595 struct winusb_device_handle_priv *handle_priv =
596 get_winusb_device_handle_priv(transfer->dev_handle);
597 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
598 int current_interface = *interface_number;
599 int r = LIBUSB_SUCCESS;
602 case USB_API_WINUSBX:
606 return LIBUSB_ERROR_INVALID_PARAM;
609 usbi_mutex_lock(&autoclaim_lock);
610 if (current_interface < 0) { // No serviceable interface was found
611 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
612 // Must claim an interface of the same API type
613 if ((priv->usb_interface[current_interface].apib->id == api_type)
614 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS)) {
615 usbi_dbg(TRANSFER_CTX(transfer), "auto-claimed interface %d for control request", current_interface);
616 if (handle_priv->autoclaim_count[current_interface] != 0)
617 usbi_err(TRANSFER_CTX(transfer), "program assertion failed - autoclaim_count was nonzero");
618 handle_priv->autoclaim_count[current_interface]++;
622 if (current_interface == USB_MAXINTERFACES) {
623 usbi_err(TRANSFER_CTX(transfer), "could not auto-claim any interface");
624 r = LIBUSB_ERROR_NOT_FOUND;
627 // If we have a valid interface that was autoclaimed, we must increment
628 // its autoclaim count so that we can prevent an early release.
629 if (handle_priv->autoclaim_count[current_interface] != 0)
630 handle_priv->autoclaim_count[current_interface]++;
632 usbi_mutex_unlock(&autoclaim_lock);
634 *interface_number = current_interface;
638 static void auto_release(struct usbi_transfer *itransfer)
640 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
641 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
642 libusb_device_handle *dev_handle = transfer->dev_handle;
643 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
646 usbi_mutex_lock(&autoclaim_lock);
647 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
648 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
649 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
650 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
651 if (r == LIBUSB_SUCCESS)
652 usbi_dbg(ITRANSFER_CTX(itransfer), "auto-released interface %d", transfer_priv->interface_number);
654 usbi_dbg(ITRANSFER_CTX(itransfer), "failed to auto-release interface %d (%s)",
655 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
658 usbi_mutex_unlock(&autoclaim_lock);
662 * init: libusb backend init function
664 static int winusb_init(struct libusb_context *ctx)
669 if (!init_dlls(ctx)) {
670 usbi_err(ctx, "could not resolve DLL functions");
671 return LIBUSB_ERROR_OTHER;
674 // Initialize the low level APIs (we don't care about errors at this stage)
675 for (i = 0; i < USB_API_MAX; i++) {
676 if (usb_api_backend[i].init && !usb_api_backend[i].init(ctx))
677 usbi_warn(ctx, "error initializing %s backend",
678 usb_api_backend[i].designation);
681 // We need a lock for proper auto-release
682 usbi_mutex_init(&autoclaim_lock);
684 return LIBUSB_SUCCESS;
688 * exit: libusb backend deinitialization function
690 static void winusb_exit(struct libusb_context *ctx)
696 usbi_mutex_destroy(&autoclaim_lock);
698 for (i = 0; i < USB_API_MAX; i++) {
699 if (usb_api_backend[i].exit)
700 usb_api_backend[i].exit();
707 * fetch and cache all the config descriptors through I/O
709 static void cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle)
711 struct libusb_context *ctx = DEVICE_CTX(dev);
712 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
713 DWORD size, ret_size;
714 uint8_t i, num_configurations;
716 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
717 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
718 PUSB_CONFIGURATION_DESCRIPTOR cd_data;
720 num_configurations = dev->device_descriptor.bNumConfigurations;
721 if (num_configurations == 0)
724 assert(sizeof(USB_DESCRIPTOR_REQUEST) == USB_DESCRIPTOR_REQUEST_SIZE);
726 priv->config_descriptor = calloc(num_configurations, sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
727 if (priv->config_descriptor == NULL) {
728 usbi_err(ctx, "could not allocate configuration descriptor array for '%s'", priv->dev_id);
732 for (i = 0; i <= num_configurations; i++) {
733 safe_free(cd_buf_actual);
735 if (i == num_configurations)
738 size = sizeof(cd_buf_short);
739 memset(&cd_buf_short.desc, 0, sizeof(cd_buf_short.desc));
741 cd_buf_short.req.ConnectionIndex = (ULONG)dev->port_number;
742 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
743 cd_buf_short.req.SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
744 cd_buf_short.req.SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
745 cd_buf_short.req.SetupPacket.wIndex = 0;
746 cd_buf_short.req.SetupPacket.wLength = (USHORT)sizeof(USB_CONFIGURATION_DESCRIPTOR);
748 // Dummy call to get the required data size. Initial failures are reported as info rather
749 // than error as they can occur for non-penalizing situations, such as with some hubs.
750 // coverity[tainted_data_argument]
751 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
752 &cd_buf_short, size, &ret_size, NULL)) {
753 usbi_info(ctx, "could not access configuration descriptor %u (dummy) for '%s': %s", i, priv->dev_id, windows_error_str(0));
757 if ((ret_size != size) || (cd_buf_short.desc.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
758 usbi_info(ctx, "unexpected configuration descriptor %u size (dummy) for '%s'", i, priv->dev_id);
762 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.desc.wTotalLength;
763 cd_buf_actual = malloc(size);
764 if (cd_buf_actual == NULL) {
765 usbi_err(ctx, "could not allocate configuration descriptor %u buffer for '%s'", i, priv->dev_id);
770 cd_buf_actual->ConnectionIndex = (ULONG)dev->port_number;
771 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
772 cd_buf_actual->SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
773 cd_buf_actual->SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
774 cd_buf_actual->SetupPacket.wIndex = 0;
775 cd_buf_actual->SetupPacket.wLength = cd_buf_short.desc.wTotalLength;
777 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
778 cd_buf_actual, size, &ret_size, NULL)) {
779 usbi_err(ctx, "could not access configuration descriptor %u (actual) for '%s': %s", i, priv->dev_id, windows_error_str(0));
783 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR *)cd_buf_actual + USB_DESCRIPTOR_REQUEST_SIZE);
785 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.desc.wTotalLength)) {
786 usbi_err(ctx, "unexpected configuration descriptor %u size (actual) for '%s'", i, priv->dev_id);
790 if (cd_data->bDescriptorType != LIBUSB_DT_CONFIG) {
791 usbi_err(ctx, "descriptor %u not a configuration descriptor for '%s'", i, priv->dev_id);
795 usbi_dbg(ctx, "cached config descriptor %u (bConfigurationValue=%u, %u bytes)",
796 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
798 // Cache the descriptor
799 priv->config_descriptor[i] = cd_data;
800 cd_buf_actual = NULL;
804 #define ROOT_HUB_FS_CONFIG_DESC_LENGTH 0x19
805 #define ROOT_HUB_HS_CONFIG_DESC_LENGTH 0x19
806 #define ROOT_HUB_SS_CONFIG_DESC_LENGTH 0x1f
807 #define CONFIG_DESC_WTOTAL_LENGTH_OFFSET 0x02
808 #define CONFIG_DESC_EP_MAX_PACKET_OFFSET 0x16
809 #define CONFIG_DESC_EP_BINTERVAL_OFFSET 0x18
811 static const uint8_t root_hub_config_descriptor_template[] = {
812 // Configuration Descriptor
813 LIBUSB_DT_CONFIG_SIZE, // bLength
814 LIBUSB_DT_CONFIG, // bDescriptorType
815 0x00, 0x00, // wTotalLength (filled in)
816 0x01, // bNumInterfaces
817 0x01, // bConfigurationValue
818 0x00, // iConfiguration
819 0xc0, // bmAttributes (reserved + self-powered)
821 // Interface Descriptor
822 LIBUSB_DT_INTERFACE_SIZE, // bLength
823 LIBUSB_DT_INTERFACE, // bDescriptorType
824 0x00, // bInterfaceNumber
825 0x00, // bAlternateSetting
826 0x01, // bNumEndpoints
827 LIBUSB_CLASS_HUB, // bInterfaceClass
828 0x00, // bInterfaceSubClass
829 0x00, // bInterfaceProtocol
831 // Endpoint Descriptor
832 LIBUSB_DT_ENDPOINT_SIZE, // bLength
833 LIBUSB_DT_ENDPOINT, // bDescriptorType
834 0x81, // bEndpointAddress
835 0x03, // bmAttributes (Interrupt)
836 0x00, 0x00, // wMaxPacketSize (filled in)
837 0x00, // bInterval (filled in)
838 // SuperSpeed Endpoint Companion Descriptor
839 LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE, // bLength
840 LIBUSB_DT_SS_ENDPOINT_COMPANION, // bDescriptorType
842 0x00, // bmAttributes
843 0x02, 0x00 // wBytesPerInterval
846 static int alloc_root_hub_config_desc(struct libusb_device *dev, ULONG num_ports,
847 uint8_t config_desc_length, uint8_t ep_interval)
849 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
852 priv->config_descriptor = malloc(sizeof(*priv->config_descriptor));
853 if (priv->config_descriptor == NULL)
854 return LIBUSB_ERROR_NO_MEM;
856 // Most config descriptors come from cache_config_descriptors() which obtains the
857 // descriptors from the hub using an allocated USB_DESCRIPTOR_REQUEST structure.
858 // To avoid an extra malloc + memcpy we just hold on to the USB_DESCRIPTOR_REQUEST
859 // structure we already have and back up the pointer in windows_device_priv_release()
860 // when freeing the descriptors. To keep a single execution path, we need to offset
861 // the pointer here by the same amount.
862 ptr = malloc(USB_DESCRIPTOR_REQUEST_SIZE + config_desc_length);
864 return LIBUSB_ERROR_NO_MEM;
866 ptr += USB_DESCRIPTOR_REQUEST_SIZE;
868 memcpy(ptr, root_hub_config_descriptor_template, config_desc_length);
869 ptr[CONFIG_DESC_WTOTAL_LENGTH_OFFSET] = config_desc_length;
870 ptr[CONFIG_DESC_EP_MAX_PACKET_OFFSET] = (uint8_t)((num_ports + 7) / 8);
871 ptr[CONFIG_DESC_EP_BINTERVAL_OFFSET] = ep_interval;
873 priv->config_descriptor[0] = (PUSB_CONFIGURATION_DESCRIPTOR)ptr;
874 priv->active_config = 1;
879 static int init_root_hub(struct libusb_device *dev)
881 struct libusb_context *ctx = DEVICE_CTX(dev);
882 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
883 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
884 USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
885 USB_NODE_INFORMATION hub_info;
886 enum libusb_speed speed = LIBUSB_SPEED_UNKNOWN;
887 uint8_t config_desc_length;
890 ULONG port_number, num_ports;
894 // Determining the speed of a root hub is painful. Microsoft does not directly report the speed
895 // capabilities of the root hub itself, only its ports and/or connected devices. Therefore we
896 // are forced to query each individual port of the root hub to try and infer the root hub's
897 // speed. Note that we have to query all ports because the presence of a device on that port
898 // changes if/how Windows returns any useful speed information.
899 handle = CreateFileA(priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
900 if (handle == INVALID_HANDLE_VALUE) {
901 usbi_err(ctx, "could not open root hub %s: %s", priv->path, windows_error_str(0));
902 return LIBUSB_ERROR_ACCESS;
905 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_INFORMATION, NULL, 0, &hub_info, sizeof(hub_info), &size, NULL)) {
906 usbi_warn(ctx, "could not get root hub info for '%s': %s", priv->dev_id, windows_error_str(0));
908 return LIBUSB_ERROR_ACCESS;
911 num_ports = hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts;
912 usbi_dbg(ctx, "root hub '%s' reports %lu ports", priv->dev_id, ULONG_CAST(num_ports));
914 if (windows_version >= WINDOWS_8) {
915 // Windows 8 and later is better at reporting the speed capabilities of the root hub,
916 // but it is not perfect. If no device is attached to the port being queried, the
917 // returned information will only indicate whether that port supports USB 3.0 signalling.
918 // That is not enough information to distinguish between SuperSpeed and SuperSpeed Plus.
919 for (port_number = 1; port_number <= num_ports; port_number++) {
920 conn_info_v2.ConnectionIndex = port_number;
921 conn_info_v2.Length = sizeof(conn_info_v2);
922 conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
923 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
924 &conn_info_v2, sizeof(conn_info_v2), &conn_info_v2, sizeof(conn_info_v2), &size, NULL)) {
925 usbi_warn(ctx, "could not get node connection information (V2) for root hub '%s' port %lu: %s",
926 priv->dev_id, ULONG_CAST(port_number), windows_error_str(0));
930 if (conn_info_v2.Flags.DeviceIsSuperSpeedPlusCapableOrHigher)
931 speed = MAX(speed, LIBUSB_SPEED_SUPER_PLUS);
932 else if (conn_info_v2.Flags.DeviceIsSuperSpeedCapableOrHigher || conn_info_v2.SupportedUsbProtocols.Usb300)
933 speed = MAX(speed, LIBUSB_SPEED_SUPER);
934 else if (conn_info_v2.SupportedUsbProtocols.Usb200)
935 speed = MAX(speed, LIBUSB_SPEED_HIGH);
937 speed = MAX(speed, LIBUSB_SPEED_FULL);
940 if (speed != LIBUSB_SPEED_UNKNOWN)
941 goto make_descriptors;
944 // At this point the speed is still not known, most likely because we are executing on
945 // Windows 7 or earlier. The following hackery peeks into the root hub's Device ID and
946 // tries to extract speed information from it, based on observed naming conventions.
947 // If this does not work, we will query individual ports of the root hub.
948 if (strstr(priv->dev_id, "ROOT_HUB31") != NULL)
949 speed = LIBUSB_SPEED_SUPER_PLUS;
950 else if (strstr(priv->dev_id, "ROOT_HUB30") != NULL)
951 speed = LIBUSB_SPEED_SUPER;
952 else if (strstr(priv->dev_id, "ROOT_HUB20") != NULL)
953 speed = LIBUSB_SPEED_HIGH;
955 if (speed != LIBUSB_SPEED_UNKNOWN)
956 goto make_descriptors;
958 // Windows only reports speed information about a connected device. This means that a root
959 // hub with no connected devices or devices that are all operating at a speed less than the
960 // highest speed that the root hub supports will not give us the correct speed.
961 for (port_number = 1; port_number <= num_ports; port_number++) {
962 conn_info.ConnectionIndex = port_number;
963 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, sizeof(conn_info),
964 &conn_info, sizeof(conn_info), &size, NULL)) {
965 usbi_warn(ctx, "could not get node connection information for root hub '%s' port %lu: %s",
966 priv->dev_id, ULONG_CAST(port_number), windows_error_str(0));
970 if (conn_info.ConnectionStatus != DeviceConnected)
973 if (conn_info.Speed == UsbHighSpeed) {
974 speed = LIBUSB_SPEED_HIGH;
982 dev->device_descriptor.bLength = LIBUSB_DT_DEVICE_SIZE;
983 dev->device_descriptor.bDescriptorType = LIBUSB_DT_DEVICE;
984 dev->device_descriptor.bDeviceClass = LIBUSB_CLASS_HUB;
985 if ((dev->device_descriptor.idVendor == 0) && (dev->device_descriptor.idProduct == 0)) {
986 dev->device_descriptor.idVendor = 0x1d6b; // Linux Foundation
987 dev->device_descriptor.idProduct = (uint16_t)speed;
989 dev->device_descriptor.bcdDevice = 0x0100;
990 dev->device_descriptor.bNumConfigurations = 1;
993 case LIBUSB_SPEED_SUPER_PLUS:
994 dev->device_descriptor.bcdUSB = 0x0310;
995 config_desc_length = ROOT_HUB_SS_CONFIG_DESC_LENGTH;
996 ep_interval = 0x0c; // 256ms
998 case LIBUSB_SPEED_SUPER:
999 dev->device_descriptor.bcdUSB = 0x0300;
1000 config_desc_length = ROOT_HUB_SS_CONFIG_DESC_LENGTH;
1001 ep_interval = 0x0c; // 256ms
1003 case LIBUSB_SPEED_HIGH:
1004 dev->device_descriptor.bcdUSB = 0x0200;
1005 config_desc_length = ROOT_HUB_HS_CONFIG_DESC_LENGTH;
1006 ep_interval = 0x0c; // 256ms
1008 case LIBUSB_SPEED_LOW: // Not used, but keeps compiler happy
1009 case LIBUSB_SPEED_UNKNOWN:
1010 // This case means absolutely no information about this root hub was determined.
1011 // There is not much choice than to be pessimistic and label this as a
1012 // full-speed device.
1013 speed = LIBUSB_SPEED_FULL;
1015 case LIBUSB_SPEED_FULL:
1016 dev->device_descriptor.bcdUSB = 0x0110;
1017 config_desc_length = ROOT_HUB_FS_CONFIG_DESC_LENGTH;
1018 ep_interval = 0xff; // 255ms
1020 default: // Impossible, buts keeps compiler happy
1021 usbi_err(ctx, "program assertion failed - unknown root hub speed");
1022 return LIBUSB_ERROR_INVALID_PARAM;
1025 if (speed >= LIBUSB_SPEED_SUPER) {
1026 dev->device_descriptor.bDeviceProtocol = 0x03; // USB 3.0 Hub
1027 dev->device_descriptor.bMaxPacketSize0 = 0x09; // 2^9 bytes
1029 dev->device_descriptor.bMaxPacketSize0 = 0x40; // 64 bytes
1034 r = alloc_root_hub_config_desc(dev, num_ports, config_desc_length, ep_interval);
1036 usbi_err(ctx, "could not allocate config descriptor for root hub '%s'", priv->dev_id);
1042 * Populate a libusb device structure
1044 static int init_device(struct libusb_device *dev, struct libusb_device *parent_dev,
1045 uint8_t port_number, DEVINST devinst)
1047 struct libusb_context *ctx = NULL;
1048 struct libusb_device *tmp_dev;
1049 struct winusb_device_priv *priv, *parent_priv, *tmp_priv;
1050 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
1051 USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
1054 uint8_t bus_number, depth;
1058 priv = usbi_get_device_priv(dev);
1060 // If the device is already initialized, we can stop here
1061 if (priv->initialized)
1062 return LIBUSB_SUCCESS;
1064 if (parent_dev != NULL) { // Not a HCD root hub
1065 ctx = DEVICE_CTX(dev);
1066 parent_priv = usbi_get_device_priv(parent_dev);
1067 if (parent_priv->apib->id != USB_API_HUB) {
1068 usbi_warn(ctx, "parent for device '%s' is not a hub", priv->dev_id);
1069 return LIBUSB_ERROR_NOT_FOUND;
1072 // Calculate depth and fetch bus number
1073 bus_number = parent_dev->bus_number;
1074 if (bus_number == 0) {
1075 tmp_dev = get_ancestor(ctx, devinst, &devinst);
1076 if (tmp_dev != parent_dev) {
1077 usbi_err(ctx, "program assertion failed - first ancestor is not parent");
1078 return LIBUSB_ERROR_NOT_FOUND;
1080 libusb_unref_device(tmp_dev);
1082 for (depth = 1; bus_number == 0; depth++) {
1083 tmp_dev = get_ancestor(ctx, devinst, &devinst);
1084 if (tmp_dev == NULL) {
1085 usbi_warn(ctx, "ancestor for device '%s' not found at depth %u", priv->dev_id, depth);
1086 return LIBUSB_ERROR_NO_DEVICE;
1088 if (tmp_dev->bus_number != 0) {
1089 bus_number = tmp_dev->bus_number;
1090 tmp_priv = usbi_get_device_priv(tmp_dev);
1091 depth += tmp_priv->depth;
1093 libusb_unref_device(tmp_dev);
1096 depth = parent_priv->depth + 1;
1099 if (bus_number == 0) {
1100 usbi_err(ctx, "program assertion failed - bus number not found for '%s'", priv->dev_id);
1101 return LIBUSB_ERROR_NOT_FOUND;
1104 dev->bus_number = bus_number;
1105 dev->port_number = port_number;
1106 dev->parent_dev = parent_dev;
1107 priv->depth = depth;
1109 hub_handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1110 if (hub_handle == INVALID_HANDLE_VALUE) {
1111 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1112 return LIBUSB_ERROR_ACCESS;
1115 conn_info.ConnectionIndex = (ULONG)port_number;
1116 // coverity[tainted_data_argument]
1119 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, sizeof(conn_info),
1120 &conn_info, sizeof(conn_info), &size, NULL)) {
1121 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1122 priv->dev_id, windows_error_str(0));
1123 CloseHandle(hub_handle);
1124 return LIBUSB_ERROR_NO_DEVICE;
1127 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1128 usbi_err(ctx, "device '%s' is no longer connected!", priv->dev_id);
1129 CloseHandle(hub_handle);
1130 return LIBUSB_ERROR_NO_DEVICE;
1133 if ((conn_info.DeviceDescriptor.bLength != LIBUSB_DT_DEVICE_SIZE)
1134 || (conn_info.DeviceDescriptor.bDescriptorType != LIBUSB_DT_DEVICE)) {
1139 static_assert(sizeof(dev->device_descriptor) == sizeof(conn_info.DeviceDescriptor),
1140 "mismatch between libusb and OS device descriptor sizes");
1141 memcpy(&dev->device_descriptor, &conn_info.DeviceDescriptor, LIBUSB_DT_DEVICE_SIZE);
1142 usbi_localize_device_descriptor(&dev->device_descriptor);
1144 priv->active_config = conn_info.CurrentConfigurationValue;
1145 if (priv->active_config == 0) {
1146 usbi_dbg(ctx, "0x%x:0x%x found %u configurations (not configured)",
1147 dev->device_descriptor.idVendor,
1148 dev->device_descriptor.idProduct,
1149 dev->device_descriptor.bNumConfigurations);
1152 } while (priv->active_config == 0 && --ginfotimeout >= 0);
1154 if ((conn_info.DeviceDescriptor.bLength != LIBUSB_DT_DEVICE_SIZE)
1155 || (conn_info.DeviceDescriptor.bDescriptorType != LIBUSB_DT_DEVICE)) {
1156 usbi_err(ctx, "device '%s' has invalid descriptor!", priv->dev_id);
1157 CloseHandle(hub_handle);
1158 return LIBUSB_ERROR_OTHER;
1161 if (priv->active_config == 0) {
1162 usbi_info(ctx, "0x%x:0x%x found %u configurations but device isn't configured, "
1163 "forcing current configuration to 1",
1164 dev->device_descriptor.idVendor,
1165 dev->device_descriptor.idProduct,
1166 dev->device_descriptor.bNumConfigurations);
1167 priv->active_config = 1;
1169 usbi_dbg(ctx, "found %u configurations (current config: %u)", dev->device_descriptor.bNumConfigurations, priv->active_config);
1172 // Cache as many config descriptors as we can
1173 cache_config_descriptors(dev, hub_handle);
1175 // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
1176 if (windows_version >= WINDOWS_8) {
1177 conn_info_v2.ConnectionIndex = (ULONG)port_number;
1178 conn_info_v2.Length = sizeof(USB_NODE_CONNECTION_INFORMATION_EX_V2);
1179 conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
1180 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
1181 &conn_info_v2, sizeof(conn_info_v2), &conn_info_v2, sizeof(conn_info_v2), &size, NULL)) {
1182 usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
1183 priv->dev_id, windows_error_str(0));
1184 } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedPlusOrHigher) {
1185 conn_info.Speed = UsbSuperSpeedPlus;
1186 } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
1187 conn_info.Speed = UsbSuperSpeed;
1191 CloseHandle(hub_handle);
1193 if (conn_info.DeviceAddress > UINT8_MAX)
1194 usbi_err(ctx, "program assertion failed - device address overflow");
1196 dev->device_address = (uint8_t)conn_info.DeviceAddress;
1198 switch (conn_info.Speed) {
1199 case UsbLowSpeed: dev->speed = LIBUSB_SPEED_LOW; break;
1200 case UsbFullSpeed: dev->speed = LIBUSB_SPEED_FULL; break;
1201 case UsbHighSpeed: dev->speed = LIBUSB_SPEED_HIGH; break;
1202 case UsbSuperSpeed: dev->speed = LIBUSB_SPEED_SUPER; break;
1203 case UsbSuperSpeedPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1205 usbi_warn(ctx, "unknown device speed %u", conn_info.Speed);
1209 r = init_root_hub(dev);
1214 r = usbi_sanitize_device(dev);
1218 priv->initialized = true;
1220 usbi_dbg(ctx, "(bus: %u, addr: %u, depth: %u, port: %u): '%s'",
1221 dev->bus_number, dev->device_address, priv->depth, dev->port_number, priv->dev_id);
1223 return LIBUSB_SUCCESS;
1226 static bool get_dev_port_number(HDEVINFO dev_info, SP_DEVINFO_DATA *dev_info_data, DWORD *port_nr)
1228 char buffer[MAX_KEY_LENGTH];
1231 // First try SPDRP_LOCATION_INFORMATION, which returns a REG_SZ. The string *may* have a format
1232 // similar to "Port_#0002.Hub_#000D", in which case we can extract the port number. However, we
1233 // cannot extract the port if the returned string does not follow this format.
1234 if (pSetupDiGetDeviceRegistryPropertyA(dev_info, dev_info_data, SPDRP_LOCATION_INFORMATION,
1235 NULL, (PBYTE)buffer, sizeof(buffer), NULL)) {
1236 // Check for the required format.
1237 if (strncmp(buffer, "Port_#", 6) == 0) {
1238 *port_nr = atoi(buffer + 6);
1243 // Next try SPDRP_LOCATION_PATHS, which returns a REG_MULTI_SZ (but we only examine the first
1244 // string in it). Each path has a format similar to,
1245 // "PCIROOT(B2)#PCI(0300)#PCI(0000)#USBROOT(0)#USB(1)#USB(2)#USBMI(3)", and the port number is
1246 // the number within the last "USB(x)" token.
1247 if (pSetupDiGetDeviceRegistryPropertyA(dev_info, dev_info_data, SPDRP_LOCATION_PATHS,
1248 NULL, (PBYTE)buffer, sizeof(buffer), NULL)) {
1249 // Find the last "#USB(x)" substring
1250 for (char *token = strrchr(buffer, '#'); token != NULL; token = strrchr(buffer, '#')) {
1251 if (strncmp(token, "#USB(", 5) == 0) {
1252 *port_nr = atoi(token + 5);
1255 // Shorten the string and try again.
1260 // Lastly, try SPDRP_ADDRESS, which returns a REG_DWORD. The address *may* be the port number,
1261 // which is true for the Microsoft driver but may not be true for other drivers. However, we
1262 // have no other options here but to accept what it returns.
1263 return pSetupDiGetDeviceRegistryPropertyA(dev_info, dev_info_data, SPDRP_ADDRESS,
1264 NULL, (PBYTE)port_nr, sizeof(*port_nr), &size) && (size == sizeof(*port_nr));
1267 static int enumerate_hcd_root_hub(struct libusb_context *ctx, const char *dev_id,
1268 uint8_t bus_number, DEVINST devinst)
1270 struct libusb_device *dev;
1271 struct winusb_device_priv *priv;
1272 unsigned long session_id;
1273 DEVINST child_devinst;
1275 if (CM_Get_Child(&child_devinst, devinst, 0) != CR_SUCCESS) {
1276 usbi_warn(ctx, "could not get child devinst for '%s'", dev_id);
1277 return LIBUSB_SUCCESS;
1280 session_id = (unsigned long)child_devinst;
1281 dev = usbi_get_device_by_session_id(ctx, session_id);
1283 usbi_err(ctx, "program assertion failed - HCD '%s' child not found", dev_id);
1284 return LIBUSB_SUCCESS;
1287 if (dev->bus_number == 0) {
1288 // Only do this once
1289 usbi_dbg(ctx, "assigning HCD '%s' bus number %u", dev_id, bus_number);
1290 dev->bus_number = bus_number;
1292 if (sscanf(dev_id, "PCI\\VEN_%04hx&DEV_%04hx%*s", &dev->device_descriptor.idVendor, &dev->device_descriptor.idProduct) != 2)
1293 usbi_warn(ctx, "could not infer VID/PID of HCD root hub from '%s'", dev_id);
1295 priv = usbi_get_device_priv(dev);
1296 priv->root_hub = true;
1299 libusb_unref_device(dev);
1300 return LIBUSB_SUCCESS;
1303 // Returns the api type, or 0 if not found/unsupported
1304 static void get_api_type(HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data,
1305 int *api, int *sub_api)
1307 // Precedence for filter drivers vs driver is in the order of this array
1308 struct driver_lookup lookup[3] = {
1309 {"\0\0", SPDRP_SERVICE, "driver"},
1310 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1311 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1313 DWORD size, reg_type;
1317 // Check the service & filter names to know the API we should use
1318 for (k = 0; k < 3; k++) {
1319 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1320 ®_type, (PBYTE)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1321 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1322 if (lookup[k].reg_prop == SPDRP_SERVICE)
1323 // our buffers are MAX_KEY_LENGTH + 1 so we can overflow if needed
1324 lookup[k].list[strlen(lookup[k].list) + 1] = 0;
1326 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1327 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1328 // (currently ';'), so even if an unsupported one does, it's not an issue
1329 for (l = 0; (lookup[k].list[l] != 0) || (lookup[k].list[l + 1] != 0); l++) {
1330 if (lookup[k].list[l] == 0)
1331 lookup[k].list[l] = LIST_SEPARATOR;
1333 usbi_dbg(NULL, "%s(s): %s", lookup[k].designation, lookup[k].list);
1335 if (GetLastError() != ERROR_INVALID_DATA)
1336 usbi_dbg(NULL, "could not access %s: %s", lookup[k].designation, windows_error_str(0));
1337 lookup[k].list[0] = 0;
1341 for (i = 2; i < USB_API_MAX; i++) {
1342 for (k = 0; k < 3; k++) {
1343 j = get_sub_api(lookup[k].list, i);
1345 usbi_dbg(NULL, "matched %s name against %s", lookup[k].designation,
1346 (i != USB_API_WINUSBX) ? usb_api_backend[i].designation : usb_api_backend[i].driver_name_list[j]);
1355 static int set_composite_interface(struct libusb_context *ctx, struct libusb_device *dev,
1356 char *dev_interface_path, char *device_id, int api, int sub_api)
1358 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
1359 int interface_number;
1362 // Because MI_## are not necessarily in sequential order (some composite
1363 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1364 // interface number from the path's MI value
1365 mi_str = strstr(device_id, "MI_");
1366 if ((mi_str != NULL) && isdigit((unsigned char)mi_str[3]) && isdigit((unsigned char)mi_str[4])) {
1367 interface_number = ((mi_str[3] - '0') * 10) + (mi_str[4] - '0');
1369 usbi_warn(ctx, "failure to read interface number for %s, using default value", device_id);
1370 interface_number = 0;
1373 if (interface_number >= USB_MAXINTERFACES) {
1374 usbi_warn(ctx, "interface %d too large - ignoring interface path %s", interface_number, dev_interface_path);
1375 return LIBUSB_ERROR_ACCESS;
1378 if (priv->usb_interface[interface_number].path != NULL) {
1379 if (api == USB_API_HID) {
1380 // HID devices can have multiple collections (COL##) for each MI_## interface
1381 usbi_dbg(ctx, "interface[%d] already set - ignoring HID collection: %s",
1382 interface_number, device_id);
1383 return LIBUSB_ERROR_ACCESS;
1385 // In other cases, just use the latest data
1386 safe_free(priv->usb_interface[interface_number].path);
1389 usbi_dbg(ctx, "interface[%d] = %s", interface_number, dev_interface_path);
1390 priv->usb_interface[interface_number].path = dev_interface_path;
1391 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1392 priv->usb_interface[interface_number].sub_api = sub_api;
1393 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1394 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1395 if (priv->hid == NULL)
1396 return LIBUSB_ERROR_NO_MEM;
1399 return LIBUSB_SUCCESS;
1402 static int set_hid_interface(struct libusb_context *ctx, struct libusb_device *dev,
1403 char *dev_interface_path)
1405 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
1408 if (priv->hid == NULL) {
1409 usbi_err(ctx, "program assertion failed - parent is not HID");
1410 return LIBUSB_ERROR_NO_DEVICE;
1411 } else if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1412 usbi_err(ctx, "program assertion failed - max USB interfaces reached for HID device");
1413 return LIBUSB_ERROR_NO_DEVICE;
1416 for (i = 0; i < priv->hid->nb_interfaces; i++) {
1417 if ((priv->usb_interface[i].path != NULL) && strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1418 usbi_dbg(ctx, "interface[%u] already set to %s", i, dev_interface_path);
1419 return LIBUSB_ERROR_ACCESS;
1423 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1424 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1425 usbi_dbg(ctx, "interface[%u] = %s", priv->hid->nb_interfaces, dev_interface_path);
1426 priv->hid->nb_interfaces++;
1427 return LIBUSB_SUCCESS;
1431 * get_device_list: libusb backend device enumeration function
1433 static int winusb_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1435 struct discovered_devs *discdevs;
1436 HDEVINFO *dev_info, dev_info_intf, dev_info_enum;
1437 SP_DEVINFO_DATA dev_info_data;
1440 int r = LIBUSB_SUCCESS;
1442 unsigned int pass, i, j;
1443 char enumerator[16];
1444 char dev_id[MAX_PATH_LENGTH];
1445 struct libusb_device *dev, *parent_dev;
1446 struct winusb_device_priv *priv, *parent_priv;
1447 char *dev_interface_path = NULL;
1448 unsigned long session_id;
1449 DWORD size, port_nr, reg_type, install_state;
1451 char guid_string[MAX_GUID_STRING_LENGTH];
1460 // Keep a list of guids that will be enumerated
1461 #define GUID_SIZE_STEP 8
1462 const GUID **guid_list, **new_guid_list;
1463 unsigned int guid_size = GUID_SIZE_STEP;
1464 unsigned int nb_guids;
1465 // Keep a list of PnP enumerator strings that are found
1466 const char *usb_enumerator[8] = { "USB" };
1467 unsigned int nb_usb_enumerators = 1;
1468 unsigned int usb_enum_index = 0;
1469 // Keep a list of newly allocated devs to unref
1470 #define UNREF_SIZE_STEP 16
1471 libusb_device **unref_list, **new_unref_list;
1472 unsigned int unref_size = UNREF_SIZE_STEP;
1473 unsigned int unref_cur = 0;
1475 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1476 // PASS 2 : (re)enumerate HUBS
1477 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1478 // and list additional USB device interface GUIDs to explore
1479 // PASS 4 : (re)enumerate master USB devices that have a device interface
1480 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1481 // set the device interfaces.
1483 // Init the GUID table
1484 guid_list = malloc(guid_size * sizeof(void *));
1485 if (guid_list == NULL) {
1486 usbi_err(ctx, "failed to alloc guid list");
1487 return LIBUSB_ERROR_NO_MEM;
1490 guid_list[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1491 guid_list[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1492 guid_list[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1493 guid_list[GEN_PASS] = NULL;
1494 if (HidD_GetHidGuid != NULL) {
1495 HidD_GetHidGuid(&hid_guid);
1496 guid_list[HID_PASS] = &hid_guid;
1498 guid_list[HID_PASS] = NULL;
1500 nb_guids = EXT_PASS;
1502 unref_list = malloc(unref_size * sizeof(void *));
1503 if (unref_list == NULL) {
1504 usbi_err(ctx, "failed to alloc unref list");
1505 free((void *)guid_list);
1506 return LIBUSB_ERROR_NO_MEM;
1509 dev_info_intf = pSetupDiGetClassDevsA(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
1510 if (dev_info_intf == INVALID_HANDLE_VALUE) {
1511 usbi_err(ctx, "failed to obtain device info list: %s", windows_error_str(0));
1513 free((void *)guid_list);
1514 return LIBUSB_ERROR_OTHER;
1517 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1518 //#define ENUM_DEBUG
1519 #if defined(ENABLE_LOGGING) && defined(ENUM_DEBUG)
1520 const char * const passname[] = {"HUB", "DEV", "HCD", "GEN", "HID", "EXT"};
1521 usbi_dbg(ctx, "#### PROCESSING %ss %s", passname[MIN(pass, EXT_PASS)], guid_to_string(guid_list[pass], guid_string));
1523 if ((pass == HID_PASS) && (guid_list[HID_PASS] == NULL))
1526 dev_info = (pass != GEN_PASS) ? &dev_info_intf : &dev_info_enum;
1528 for (i = 0; ; i++) {
1529 // safe loop: free up any (unprotected) dynamic resource
1530 // NB: this is always executed before breaking the loop
1531 safe_free(dev_interface_path);
1532 priv = parent_priv = NULL;
1533 dev = parent_dev = NULL;
1535 // Safe loop: end of loop conditions
1536 if (r != LIBUSB_SUCCESS)
1539 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1540 usbi_warn(ctx, "program assertion failed - found more than %u buses, skipping the rest", UINT8_MAX);
1544 if (pass != GEN_PASS) {
1545 // Except for GEN, all passes deal with device interfaces
1546 r = get_interface_details(ctx, *dev_info, &dev_info_data, guid_list[pass], &_index, &dev_interface_path);
1547 if ((r != LIBUSB_SUCCESS) || (dev_interface_path == NULL)) {
1552 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1553 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1554 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1555 // The Intel Alpine Ridge USB 3.1 driver uses "IARUSB3"
1556 for (; usb_enum_index < nb_usb_enumerators; usb_enum_index++) {
1557 if (get_devinfo_data(ctx, dev_info, &dev_info_data, usb_enumerator[usb_enum_index], i))
1561 if (usb_enum_index == nb_usb_enumerators)
1565 // Read the Device ID path
1566 if (!pSetupDiGetDeviceInstanceIdA(*dev_info, &dev_info_data, dev_id, sizeof(dev_id), NULL)) {
1567 usbi_warn(ctx, "could not read the device instance ID for devInst %lX, skipping",
1568 ULONG_CAST(dev_info_data.DevInst));
1573 usbi_dbg(ctx, "PRO: %s", dev_id);
1576 // Set API to use or get additional data from generic pass
1577 api = USB_API_UNSUPPORTED;
1578 sub_api = SUB_API_NOTSET;
1584 // Fetch the PnP enumerator class for this hub
1585 // This will allow us to enumerate all classes during the GEN pass
1586 if (!pSetupDiGetDeviceRegistryPropertyA(*dev_info, &dev_info_data, SPDRP_ENUMERATOR_NAME,
1587 NULL, (PBYTE)enumerator, sizeof(enumerator), NULL)) {
1588 usbi_err(ctx, "could not read enumerator string for device '%s': %s", dev_id, windows_error_str(0));
1589 LOOP_BREAK(LIBUSB_ERROR_OTHER);
1591 for (j = 0; j < nb_usb_enumerators; j++) {
1592 if (strcmp(usb_enumerator[j], enumerator) == 0)
1595 if (j == nb_usb_enumerators) {
1596 usbi_dbg(ctx, "found new PnP enumerator string '%s'", enumerator);
1597 if (nb_usb_enumerators < ARRAYSIZE(usb_enumerator)) {
1598 usb_enumerator[nb_usb_enumerators] = _strdup(enumerator);
1599 if (usb_enumerator[nb_usb_enumerators] != NULL) {
1600 nb_usb_enumerators++;
1602 usbi_err(ctx, "could not allocate enumerator string '%s'", enumerator);
1603 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1606 usbi_warn(ctx, "too many enumerator strings, some devices may not be accessible");
1611 // We use the GEN pass to detect driverless devices...
1612 if (!pSetupDiGetDeviceRegistryPropertyA(*dev_info, &dev_info_data, SPDRP_DRIVER,
1613 NULL, NULL, 0, NULL) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) {
1614 usbi_info(ctx, "The following device has no driver: '%s'", dev_id);
1615 usbi_info(ctx, "libusb will not be able to access it");
1617 // ...and to add the additional device interface GUIDs
1618 key = pSetupDiOpenDevRegKey(*dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1619 if (key == INVALID_HANDLE_VALUE)
1621 // Look for both DeviceInterfaceGUIDs *and* DeviceInterfaceGUID, in that order
1622 // If multiple GUIDs just process the first and ignore the others
1623 size = sizeof(guid_string);
1624 s = pRegQueryValueExA(key, "DeviceInterfaceGUIDs", NULL, ®_type,
1625 (LPBYTE)guid_string, &size);
1626 if (s == ERROR_FILE_NOT_FOUND)
1627 s = pRegQueryValueExA(key, "DeviceInterfaceGUID", NULL, ®_type,
1628 (LPBYTE)guid_string, &size);
1630 if (s == ERROR_FILE_NOT_FOUND) {
1631 break; /* no DeviceInterfaceGUID registered */
1632 } else if (s != ERROR_SUCCESS && s != ERROR_MORE_DATA) {
1633 usbi_warn(ctx, "unexpected error from pRegQueryValueExA for '%s'", dev_id);
1636 // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvalueexa#remarks
1637 // - "string may not have been stored with the proper terminating null characters"
1638 // - "Note that REG_MULTI_SZ strings could have two terminating null characters"
1639 if ((reg_type == REG_SZ && size >= sizeof(guid_string) - sizeof(char))
1640 || (reg_type == REG_MULTI_SZ && size >= sizeof(guid_string) - 2 * sizeof(char))) {
1641 if (nb_guids == guid_size) {
1642 new_guid_list = realloc((void *)guid_list, (guid_size + GUID_SIZE_STEP) * sizeof(void *));
1643 if (new_guid_list == NULL) {
1644 usbi_err(ctx, "failed to realloc guid list");
1645 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1647 guid_list = new_guid_list;
1648 guid_size += GUID_SIZE_STEP;
1650 if_guid = malloc(sizeof(*if_guid));
1651 if (if_guid == NULL) {
1652 usbi_err(ctx, "failed to alloc if_guid");
1653 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1655 if (!string_to_guid(guid_string, if_guid)) {
1656 usbi_warn(ctx, "device '%s' has malformed DeviceInterfaceGUID string '%s', skipping", dev_id, guid_string);
1659 // Check if we've already seen this GUID
1660 for (j = EXT_PASS; j < nb_guids; j++) {
1661 if (memcmp(guid_list[j], if_guid, sizeof(*if_guid)) == 0)
1664 if (j == nb_guids) {
1665 usbi_dbg(ctx, "extra GUID: %s", guid_string);
1666 guid_list[nb_guids++] = if_guid;
1668 // Duplicate, ignore
1673 usbi_warn(ctx, "unexpected type/size of DeviceInterfaceGUID for '%s'", dev_id);
1680 // Get the API type (after checking that the driver installation is OK)
1681 if ((!pSetupDiGetDeviceRegistryPropertyA(*dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1682 NULL, (PBYTE)&install_state, sizeof(install_state), &size)) || (size != sizeof(install_state))) {
1683 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1684 dev_id, windows_error_str(0));
1685 } else if (install_state != 0) {
1686 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %lu) - skipping",
1687 dev_id, ULONG_CAST(install_state));
1690 get_api_type(dev_info, &dev_info_data, &api, &sub_api);
1694 // Find parent device (for the passes that need it)
1695 if (pass >= GEN_PASS) {
1696 parent_dev = get_ancestor(ctx, dev_info_data.DevInst, NULL);
1697 if (parent_dev == NULL) {
1698 // Root hubs will not have a parent
1699 dev = usbi_get_device_by_session_id(ctx, (unsigned long)dev_info_data.DevInst);
1701 priv = usbi_get_device_priv(dev);
1704 libusb_unref_device(dev);
1707 usbi_dbg(ctx, "unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id);
1711 parent_priv = usbi_get_device_priv(parent_dev);
1712 // virtual USB devices are also listed during GEN - don't process these yet
1713 if ((pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB)) {
1714 libusb_unref_device(parent_dev);
1719 // Create new or match existing device, using the devInst as session id
1720 if ((pass <= GEN_PASS) && (pass != HCD_PASS)) { // For subsequent passes, we'll lookup the parent
1721 // These are the passes that create "new" devices
1722 session_id = (unsigned long)dev_info_data.DevInst;
1723 dev = usbi_get_device_by_session_id(ctx, session_id);
1726 usbi_dbg(ctx, "allocating new device for session [%lX]", session_id);
1727 dev = usbi_alloc_device(ctx, session_id);
1729 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1731 priv = winusb_device_priv_init(dev);
1732 priv->dev_id = _strdup(dev_id);
1733 priv->class_guid = dev_info_data.ClassGuid;
1734 if (priv->dev_id == NULL) {
1735 libusb_unref_device(dev);
1736 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1739 usbi_dbg(ctx, "found existing device for session [%lX]", session_id);
1741 priv = usbi_get_device_priv(dev);
1742 if (strcmp(priv->dev_id, dev_id) != 0) {
1743 usbi_dbg(ctx, "device instance ID for session [%lX] changed", session_id);
1744 usbi_disconnect_device(dev);
1745 libusb_unref_device(dev);
1748 if (!IsEqualGUID(&priv->class_guid, &dev_info_data.ClassGuid)) {
1749 usbi_dbg(ctx, "device class GUID for session [%lX] changed", session_id);
1750 usbi_disconnect_device(dev);
1751 libusb_unref_device(dev);
1757 // Keep track of devices that need unref
1758 if (unref_cur == unref_size) {
1759 new_unref_list = realloc(unref_list, (unref_size + UNREF_SIZE_STEP) * sizeof(void *));
1760 if (new_unref_list == NULL) {
1761 usbi_err(ctx, "could not realloc list for unref - aborting");
1762 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1764 unref_list = new_unref_list;
1765 unref_size += UNREF_SIZE_STEP;
1767 unref_list[unref_cur++] = dev;
1774 // If the device has already been setup, don't do it again
1775 if (priv->path != NULL)
1777 // Take care of API initialization
1778 priv->path = dev_interface_path;
1779 dev_interface_path = NULL;
1780 priv->apib = &usb_api_backend[api];
1781 priv->sub_api = sub_api;
1783 case USB_API_COMPOSITE:
1787 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1788 if (priv->hid == NULL)
1789 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1792 // For other devices, the first interface is the same as the device
1793 priv->usb_interface[0].path = _strdup(priv->path);
1794 if (priv->usb_interface[0].path == NULL)
1795 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1796 // The following is needed if we want API calls to work for both simple
1797 // and composite devices.
1798 for (j = 0; j < USB_MAXINTERFACES; j++)
1799 priv->usb_interface[j].apib = &usb_api_backend[api];
1804 r = enumerate_hcd_root_hub(ctx, dev_id, (uint8_t)(i + 1), dev_info_data.DevInst);
1808 if (!get_dev_port_number(*dev_info, &dev_info_data, &port_nr))
1809 usbi_warn(ctx, "could not retrieve port number for device '%s': %s", dev_id, windows_error_str(0));
1810 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_info_data.DevInst);
1811 if (r == LIBUSB_SUCCESS) {
1812 // Append device to the list of discovered devices
1813 discdevs = discovered_devs_append(*_discdevs, dev);
1815 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1817 *_discdevs = discdevs;
1819 // Failed to initialize a single device doesn't stop us from enumerating all other devices,
1820 // but we skip it (don't add to list of discovered devices)
1821 usbi_warn(ctx, "failed to initialize device '%s'", priv->dev_id);
1825 default: // HID_PASS and later
1826 if (parent_priv->apib->id == USB_API_HID || parent_priv->apib->id == USB_API_COMPOSITE) {
1827 if (parent_priv->apib->id == USB_API_HID) {
1828 usbi_dbg(ctx, "setting HID interface for [%lX]:", parent_dev->session_data);
1829 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1831 usbi_dbg(ctx, "setting composite interface for [%lX]:", parent_dev->session_data);
1832 r = set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id, api, sub_api);
1835 case LIBUSB_SUCCESS:
1836 dev_interface_path = NULL;
1838 case LIBUSB_ERROR_ACCESS:
1839 // interface has already been set => make sure dev_interface_path is freed then
1847 libusb_unref_device(parent_dev);
1853 pSetupDiDestroyDeviceInfoList(dev_info_intf);
1855 // Free any additional GUIDs
1856 for (pass = EXT_PASS; pass < nb_guids; pass++)
1857 free((void *)guid_list[pass]);
1858 free((void *)guid_list);
1860 // Free any PnP enumerator strings
1861 for (i = 1; i < nb_usb_enumerators; i++)
1862 free((void *)usb_enumerator[i]);
1864 // Unref newly allocated devs
1865 for (i = 0; i < unref_cur; i++)
1866 libusb_unref_device(unref_list[i]);
1872 static int winusb_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len)
1874 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
1875 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1877 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1878 return LIBUSB_ERROR_NOT_FOUND;
1880 config_header = priv->config_descriptor[config_index];
1882 len = MIN(len, config_header->wTotalLength);
1883 memcpy(buffer, config_header, len);
1887 static int winusb_get_config_descriptor_by_value(struct libusb_device *dev, uint8_t bConfigurationValue,
1890 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
1891 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1894 if (priv->config_descriptor == NULL)
1895 return LIBUSB_ERROR_NOT_FOUND;
1897 for (index = 0; index < dev->device_descriptor.bNumConfigurations; index++) {
1898 config_header = priv->config_descriptor[index];
1899 if (config_header == NULL)
1901 if (config_header->bConfigurationValue == bConfigurationValue) {
1902 *buffer = config_header;
1903 return (int)config_header->wTotalLength;
1907 return LIBUSB_ERROR_NOT_FOUND;
1911 * return the cached copy of the active config descriptor
1913 static int winusb_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len)
1915 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
1919 if (priv->active_config == 0)
1920 return LIBUSB_ERROR_NOT_FOUND;
1922 r = winusb_get_config_descriptor_by_value(dev, priv->active_config, &config_desc);
1926 len = MIN(len, (size_t)r);
1927 memcpy(buffer, config_desc, len);
1931 static int winusb_open(struct libusb_device_handle *dev_handle)
1933 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
1935 CHECK_SUPPORTED_API(priv->apib, open);
1937 return priv->apib->open(SUB_API_NOTSET, dev_handle);
1940 static void winusb_close(struct libusb_device_handle *dev_handle)
1942 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
1944 if (priv->apib->close)
1945 priv->apib->close(SUB_API_NOTSET, dev_handle);
1948 static int winusb_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config)
1950 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
1952 *config = priv->active_config;
1953 return LIBUSB_SUCCESS;
1957 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1958 * does not currently expose a service that allows higher-level drivers to set
1959 * the configuration."
1961 static int winusb_set_configuration(struct libusb_device_handle *dev_handle, uint8_t config)
1963 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
1964 int r = LIBUSB_SUCCESS;
1966 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1967 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1968 LIBUSB_REQUEST_SET_CONFIGURATION, config,
1971 if (r == LIBUSB_SUCCESS)
1972 priv->active_config = config;
1977 static int winusb_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface)
1979 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
1982 CHECK_SUPPORTED_API(priv->apib, claim_interface);
1984 safe_free(priv->usb_interface[iface].endpoint);
1985 priv->usb_interface[iface].nb_endpoints = 0;
1987 r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
1989 if (r == LIBUSB_SUCCESS)
1990 r = windows_assign_endpoints(dev_handle, iface, 0);
1995 static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
1997 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2000 CHECK_SUPPORTED_API(priv->apib, set_interface_altsetting);
2002 safe_free(priv->usb_interface[iface].endpoint);
2003 priv->usb_interface[iface].nb_endpoints = 0;
2005 r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
2007 if (r == LIBUSB_SUCCESS)
2008 r = windows_assign_endpoints(dev_handle, iface, altsetting);
2013 static int winusb_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface)
2015 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2017 CHECK_SUPPORTED_API(priv->apib, release_interface);
2019 return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
2022 static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
2024 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2026 CHECK_SUPPORTED_API(priv->apib, clear_halt);
2028 return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
2031 static int winusb_reset_device(struct libusb_device_handle *dev_handle)
2033 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2035 CHECK_SUPPORTED_API(priv->apib, reset_device);
2037 return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
2040 static void winusb_destroy_device(struct libusb_device *dev)
2042 winusb_device_priv_release(dev);
2045 static void winusb_clear_transfer_priv(struct usbi_transfer *itransfer)
2047 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
2048 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2049 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
2050 int sub_api = priv->sub_api;
2052 safe_free(transfer_priv->hid_buffer);
2054 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && sub_api == SUB_API_WINUSB) {
2055 if (transfer_priv->isoch_buffer_handle != NULL) {
2056 if (WinUSBX[sub_api].UnregisterIsochBuffer(transfer_priv->isoch_buffer_handle)) {
2057 transfer_priv->isoch_buffer_handle = NULL;
2059 usbi_warn(TRANSFER_CTX(transfer), "failed to unregister WinUSB isoch buffer: %s", windows_error_str(0));
2064 safe_free(transfer_priv->iso_context);
2066 // When auto claim is in use, attempt to release the auto-claimed interface
2067 auto_release(itransfer);
2070 static int winusb_submit_transfer(struct usbi_transfer *itransfer)
2072 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2073 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
2074 int (*transfer_fn)(int, struct usbi_transfer *);
2076 switch (transfer->type) {
2077 case LIBUSB_TRANSFER_TYPE_CONTROL:
2078 transfer_fn = priv->apib->submit_control_transfer;
2080 case LIBUSB_TRANSFER_TYPE_BULK:
2081 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2082 transfer_fn = priv->apib->submit_bulk_transfer;
2084 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2085 transfer_fn = priv->apib->submit_iso_transfer;
2088 // Should not get here since windows_submit_transfer() validates
2089 // the transfer->type field
2090 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2091 return LIBUSB_ERROR_INVALID_PARAM;
2094 if (transfer_fn == NULL) {
2095 usbi_warn(TRANSFER_CTX(transfer),
2096 "unsupported transfer type %d (unrecognized device driver)",
2098 return LIBUSB_ERROR_NOT_SUPPORTED;
2101 return transfer_fn(SUB_API_NOTSET, itransfer);
2104 static int winusb_cancel_transfer(struct usbi_transfer *itransfer)
2106 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2107 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
2109 CHECK_SUPPORTED_API(priv->apib, cancel_transfer);
2111 return priv->apib->cancel_transfer(SUB_API_NOTSET, itransfer);
2114 static enum libusb_transfer_status winusb_copy_transfer_data(struct usbi_transfer *itransfer, DWORD length)
2116 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2117 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
2119 if (priv->apib->copy_transfer_data == NULL) {
2120 usbi_err(TRANSFER_CTX(transfer), "program assertion failed - no function to copy transfer data");
2121 return LIBUSB_TRANSFER_ERROR;
2124 return priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, length);
2127 // NB: MSVC6 does not support named initializers.
2128 const struct windows_backend winusb_backend = {
2131 winusb_get_device_list,
2134 winusb_get_active_config_descriptor,
2135 winusb_get_config_descriptor,
2136 winusb_get_config_descriptor_by_value,
2137 winusb_get_configuration,
2138 winusb_set_configuration,
2139 winusb_claim_interface,
2140 winusb_release_interface,
2141 winusb_set_interface_altsetting,
2143 winusb_reset_device,
2144 winusb_destroy_device,
2145 winusb_submit_transfer,
2146 winusb_cancel_transfer,
2147 winusb_clear_transfer_priv,
2148 winusb_copy_transfer_data,
2155 static const char * const composite_driver_names[] = {"USBCCGP"};
2156 static const char * const winusbx_driver_names[] = {"libusbK", "libusb0", "WinUSB"};
2157 static const char * const hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2158 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2160 USB_API_UNSUPPORTED,
2162 NULL, /* driver_name_list */
2163 0, /* nb_driver_names */
2168 NULL, /* configure_endpoints */
2169 NULL, /* claim_interface */
2170 NULL, /* set_interface_altsetting */
2171 NULL, /* release_interface */
2172 NULL, /* clear_halt */
2173 NULL, /* reset_device */
2174 NULL, /* submit_bulk_transfer */
2175 NULL, /* submit_iso_transfer */
2176 NULL, /* submit_control_transfer */
2177 NULL, /* cancel_transfer */
2178 NULL, /* copy_transfer_data */
2183 NULL, /* driver_name_list */
2184 0, /* nb_driver_names */
2189 NULL, /* configure_endpoints */
2190 NULL, /* claim_interface */
2191 NULL, /* set_interface_altsetting */
2192 NULL, /* release_interface */
2193 NULL, /* clear_halt */
2194 NULL, /* reset_device */
2195 NULL, /* submit_bulk_transfer */
2196 NULL, /* submit_iso_transfer */
2197 NULL, /* submit_control_transfer */
2198 NULL, /* cancel_transfer */
2199 NULL, /* copy_transfer_data */
2204 composite_driver_names,
2205 ARRAYSIZE(composite_driver_names),
2210 NULL, /* configure_endpoints */
2211 composite_claim_interface,
2212 composite_set_interface_altsetting,
2213 composite_release_interface,
2214 composite_clear_halt,
2215 composite_reset_device,
2216 composite_submit_bulk_transfer,
2217 composite_submit_iso_transfer,
2218 composite_submit_control_transfer,
2219 composite_cancel_transfer,
2220 composite_copy_transfer_data,
2225 winusbx_driver_names,
2226 ARRAYSIZE(winusbx_driver_names),
2231 winusbx_configure_endpoints,
2232 winusbx_claim_interface,
2233 winusbx_set_interface_altsetting,
2234 winusbx_release_interface,
2236 winusbx_reset_device,
2237 winusbx_submit_bulk_transfer,
2238 winusbx_submit_iso_transfer,
2239 winusbx_submit_control_transfer,
2240 winusbx_cancel_transfer,
2241 winusbx_copy_transfer_data,
2247 ARRAYSIZE(hid_driver_names),
2252 NULL, /* configure_endpoints */
2253 hid_claim_interface,
2254 hid_set_interface_altsetting,
2255 hid_release_interface,
2258 hid_submit_bulk_transfer,
2259 NULL, /* submit_iso_transfer */
2260 hid_submit_control_transfer,
2261 NULL, /* cancel_transfer */
2262 hid_copy_transfer_data,
2268 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2270 #define WinUSB_Set(h, fn, required) \
2272 WinUSBX[SUB_API_WINUSB].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \
2273 if (required && (WinUSBX[SUB_API_WINUSB].fn == NULL)) { \
2274 usbi_err(ctx, "GetProcAddress() failed for WinUsb_%s", #fn); \
2275 goto cleanup_winusb; \
2279 #define libusbK_Set(sub_api, fn, required) \
2281 pLibK_GetProcAddress((PVOID *)&WinUSBX[sub_api].fn, sub_api, KUSB_FNID_##fn); \
2282 if (required && (WinUSBX[sub_api].fn == NULL)) { \
2283 usbi_err(ctx, "LibK_GetProcAddress() failed for LibK_%s", #fn); \
2284 goto cleanup_libusbk; \
2288 static bool winusbx_init(struct libusb_context *ctx)
2290 HMODULE hWinUSB, hlibusbK;
2292 hWinUSB = load_system_library(ctx, "WinUSB");
2293 if (hWinUSB != NULL) {
2294 WinUSB_Set(hWinUSB, AbortPipe, true);
2295 WinUSB_Set(hWinUSB, ControlTransfer, true);
2296 WinUSB_Set(hWinUSB, FlushPipe, true);
2297 WinUSB_Set(hWinUSB, Free, true);
2298 WinUSB_Set(hWinUSB, GetAssociatedInterface, true);
2299 WinUSB_Set(hWinUSB, Initialize, true);
2300 WinUSB_Set(hWinUSB, ReadPipe, true);
2301 WinUSB_Set(hWinUSB, ResetPipe, true);
2302 WinUSB_Set(hWinUSB, SetCurrentAlternateSetting, true);
2303 WinUSB_Set(hWinUSB, SetPipePolicy, true);
2304 WinUSB_Set(hWinUSB, WritePipe, true);
2306 // Check for isochronous transfers support (available starting with Windows 8.1)
2307 WinUSB_Set(hWinUSB, ReadIsochPipeAsap, false);
2308 if (WinUSBX[SUB_API_WINUSB].ReadIsochPipeAsap != NULL) {
2309 WinUSB_Set(hWinUSB, QueryPipeEx, true);
2310 WinUSB_Set(hWinUSB, RegisterIsochBuffer, true);
2311 WinUSB_Set(hWinUSB, UnregisterIsochBuffer, true);
2312 WinUSB_Set(hWinUSB, WriteIsochPipeAsap, true);
2315 WinUSBX[SUB_API_WINUSB].hDll = hWinUSB;
2317 usbi_info(ctx, "WinUSB DLL available (%s isoch support)",
2318 (WinUSBX[SUB_API_WINUSB].ReadIsochPipeAsap != NULL) ? "with" : "without");
2321 if (WinUSBX[SUB_API_WINUSB].hDll == NULL) {
2322 usbi_err(ctx, "failed to initialize WinUSB");
2323 memset(&WinUSBX[SUB_API_WINUSB], 0, sizeof(WinUSBX[SUB_API_WINUSB]));
2324 FreeLibrary(hWinUSB);
2328 usbi_info(ctx, "WinUSB DLL is not available");
2331 hlibusbK = load_system_library(ctx, "libusbK");
2332 if (hlibusbK != NULL) {
2333 LibK_GetVersion_t pLibK_GetVersion;
2334 LibK_GetProcAddress_t pLibK_GetProcAddress;
2337 pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(hlibusbK, "LibK_GetVersion");
2338 if (pLibK_GetVersion != NULL) {
2339 KLIB_VERSION LibK_Version;
2341 pLibK_GetVersion(&LibK_Version);
2342 usbi_dbg(ctx, "libusbK DLL found, version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2343 LibK_Version.Micro, LibK_Version.Nano);
2345 usbi_dbg(ctx, "libusbK DLL found, version unknown");
2348 pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(hlibusbK, "LibK_GetProcAddress");
2349 if (pLibK_GetProcAddress == NULL) {
2350 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2351 goto cleanup_libusbk;
2354 // NB: The below for loop works because the sub_api value for WinUSB
2355 // is a higher value than that of libusbK and libusb0
2356 for (; sub_api < SUB_API_WINUSB; sub_api++) {
2357 libusbK_Set(sub_api, AbortPipe, true);
2358 libusbK_Set(sub_api, ControlTransfer, true);
2359 libusbK_Set(sub_api, FlushPipe, true);
2360 libusbK_Set(sub_api, Free, true);
2361 libusbK_Set(sub_api, GetAssociatedInterface, true);
2362 libusbK_Set(sub_api, Initialize, true);
2363 libusbK_Set(sub_api, ReadPipe, true);
2364 libusbK_Set(sub_api, ResetPipe, true);
2365 libusbK_Set(sub_api, SetCurrentAlternateSetting, true);
2366 libusbK_Set(sub_api, SetPipePolicy, true);
2367 libusbK_Set(sub_api, WritePipe, true);
2369 // Optional isochronous support
2370 libusbK_Set(sub_api, IsoReadPipe, false);
2371 if (WinUSBX[sub_api].IsoReadPipe != NULL)
2372 libusbK_Set(sub_api, IsoWritePipe, true);
2374 // Optional device reset support
2375 libusbK_Set(sub_api, ResetDevice, false);
2377 WinUSBX[sub_api].hDll = hlibusbK;
2381 if (sub_api < SUB_API_WINUSB) {
2382 usbi_err(ctx, "failed to initialize libusbK");
2383 while (sub_api >= 0) {
2384 memset(&WinUSBX[sub_api], 0, sizeof(WinUSBX[sub_api]));
2387 FreeLibrary(hlibusbK);
2391 usbi_info(ctx, "libusbK DLL is not available");
2394 if ((hWinUSB == NULL) && (hlibusbK == NULL)) {
2395 usbi_warn(ctx, "neither WinUSB nor libusbK DLLs were found, "
2396 "you will not be able to access devices outside of enumeration");
2403 static void winusbx_exit(void)
2405 bool loaded = false;
2408 hDll = WinUSBX[SUB_API_LIBUSBK].hDll;
2414 hDll = WinUSBX[SUB_API_WINUSB].hDll;
2420 // Reset the WinUSBX API structures if something was loaded
2422 memset(&WinUSBX, 0, sizeof(WinUSBX));
2425 // NB: open and close must ensure that they only handle interface of
2426 // the right API type, as these functions can be called wholesale from
2427 // composite_open(), with interfaces belonging to different APIs
2428 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2430 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2431 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2435 CHECK_WINUSBX_AVAILABLE(sub_api);
2437 // WinUSB requires a separate handle for each interface
2438 for (i = 0; i < USB_MAXINTERFACES; i++) {
2439 if ((priv->usb_interface[i].path != NULL)
2440 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
2441 file_handle = windows_open(dev_handle, priv->usb_interface[i].path, GENERIC_READ | GENERIC_WRITE);
2442 if (file_handle == INVALID_HANDLE_VALUE) {
2443 usbi_err(HANDLE_CTX(dev_handle), "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2444 switch (GetLastError()) {
2445 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2446 return LIBUSB_ERROR_NO_DEVICE;
2447 case ERROR_ACCESS_DENIED:
2448 return LIBUSB_ERROR_ACCESS;
2450 return LIBUSB_ERROR_IO;
2454 handle_priv->interface_handle[i].dev_handle = file_handle;
2458 return LIBUSB_SUCCESS;
2461 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2463 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2464 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2468 if (sub_api == SUB_API_NOTSET)
2469 sub_api = priv->sub_api;
2471 if (WinUSBX[sub_api].hDll == NULL)
2474 if (priv->apib->id == USB_API_COMPOSITE) {
2475 // If this is a composite device, just free and close all WinUSB-like
2476 // interfaces directly (each is independent and not associated with another)
2477 for (i = 0; i < USB_MAXINTERFACES; i++) {
2478 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2479 handle = handle_priv->interface_handle[i].api_handle;
2480 if (HANDLE_VALID(handle))
2481 WinUSBX[sub_api].Free(handle);
2483 handle = handle_priv->interface_handle[i].dev_handle;
2484 if (HANDLE_VALID(handle))
2485 CloseHandle(handle);
2489 // If this is a WinUSB device, free all interfaces above interface 0,
2490 // then free and close interface 0 last
2491 for (i = 1; i < USB_MAXINTERFACES; i++) {
2492 handle = handle_priv->interface_handle[i].api_handle;
2493 if (HANDLE_VALID(handle))
2494 WinUSBX[sub_api].Free(handle);
2496 handle = handle_priv->interface_handle[0].api_handle;
2497 if (HANDLE_VALID(handle))
2498 WinUSBX[sub_api].Free(handle);
2500 handle = handle_priv->interface_handle[0].dev_handle;
2501 if (HANDLE_VALID(handle))
2502 CloseHandle(handle);
2506 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
2508 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2509 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2510 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2513 uint8_t endpoint_address;
2516 CHECK_WINUSBX_AVAILABLE(sub_api);
2518 // With handle and endpoints set (in parent), we can setup the default pipe properties
2519 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2520 for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
2521 endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
2522 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2523 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
2524 usbi_dbg(HANDLE_CTX(dev_handle), "failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2526 if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
2527 continue; // Other policies don't apply to control endpoint or libusb0
2530 handle_priv->interface_handle[iface].zlp[endpoint_address] = WINUSB_ZLP_UNSET;
2531 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2532 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
2533 usbi_dbg(HANDLE_CTX(dev_handle), "failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2535 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2536 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
2537 usbi_dbg(HANDLE_CTX(dev_handle), "failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2540 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2541 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2542 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2543 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
2544 usbi_dbg(HANDLE_CTX(dev_handle), "failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2546 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2547 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
2548 usbi_dbg(HANDLE_CTX(dev_handle), "failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2550 if (sub_api == SUB_API_LIBUSBK) {
2551 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2552 ISO_ALWAYS_START_ASAP, sizeof(UCHAR), &policy))
2553 usbi_dbg(HANDLE_CTX(dev_handle), "failed to enable ISO_ALWAYS_START_ASAP for endpoint %02X", endpoint_address);
2557 return LIBUSB_SUCCESS;
2560 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
2562 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
2563 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2564 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2565 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2567 char *dev_interface_path = NULL;
2568 char *dev_interface_path_guid_start;
2569 char filter_path[] = "\\\\.\\libusb0-0000";
2570 bool found_filter = false;
2571 HANDLE file_handle, winusb_handle;
2575 CHECK_WINUSBX_AVAILABLE(sub_api);
2577 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2578 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2579 if ((is_using_usbccgp) || (iface == 0)) {
2580 // composite device (independent interfaces) or interface 0
2581 file_handle = handle_priv->interface_handle[iface].dev_handle;
2582 if (!HANDLE_VALID(file_handle))
2583 return LIBUSB_ERROR_NOT_FOUND;
2585 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2586 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2587 err = GetLastError();
2589 case ERROR_BAD_COMMAND:
2590 // The device was disconnected
2591 usbi_err(ctx, "could not access interface %u: %s", iface, windows_error_str(0));
2592 return LIBUSB_ERROR_NO_DEVICE;
2594 // it may be that we're using the libusb0 filter driver.
2595 // TODO: can we move this whole business into the K/0 DLL?
2597 for (_index = 0; ; _index++) {
2598 safe_free(dev_interface_path);
2603 r = get_interface_details_filter(ctx, &dev_info, _index, filter_path, &dev_interface_path);
2604 if ((r != LIBUSB_SUCCESS) || (dev_interface_path == NULL))
2608 dev_interface_path_guid_start = strchr(dev_interface_path, '{');
2609 if (dev_interface_path_guid_start == NULL)
2611 *dev_interface_path_guid_start = '\0';
2613 if (strncmp(dev_interface_path, priv->usb_interface[iface].path, strlen(dev_interface_path)) == 0) {
2614 file_handle = windows_open(dev_handle, filter_path, GENERIC_READ | GENERIC_WRITE);
2615 if (file_handle != INVALID_HANDLE_VALUE) {
2616 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2617 // Replace the existing file handle with the working one
2618 CloseHandle(handle_priv->interface_handle[iface].dev_handle);
2619 handle_priv->interface_handle[iface].dev_handle = file_handle;
2620 found_filter = true;
2622 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2623 CloseHandle(file_handle);
2626 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2630 if (r != LIBUSB_SUCCESS)
2632 if (!found_filter) {
2633 usbi_err(ctx, "could not access interface %u: %s", iface, windows_error_str(err));
2634 return LIBUSB_ERROR_ACCESS;
2638 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2640 // For all other interfaces, use GetAssociatedInterface()
2641 winusb_handle = handle_priv->interface_handle[0].api_handle;
2642 // It is a requirement for multiple interface devices on Windows that, to you
2643 // must first claim the first interface before you claim the others
2644 if (!HANDLE_VALID(winusb_handle)) {
2645 file_handle = handle_priv->interface_handle[0].dev_handle;
2646 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2647 handle_priv->interface_handle[0].api_handle = winusb_handle;
2648 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %u with WinUSB)", iface);
2650 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %u with WinUSB): %s", iface, windows_error_str(0));
2651 return LIBUSB_ERROR_ACCESS;
2654 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
2655 &handle_priv->interface_handle[iface].api_handle)) {
2656 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2657 switch (GetLastError()) {
2658 case ERROR_NO_MORE_ITEMS: // invalid iface
2659 return LIBUSB_ERROR_NOT_FOUND;
2660 case ERROR_BAD_COMMAND: // The device was disconnected
2661 return LIBUSB_ERROR_NO_DEVICE;
2662 case ERROR_ALREADY_EXISTS: // already claimed
2663 return LIBUSB_ERROR_BUSY;
2665 usbi_err(ctx, "could not claim interface %u: %s", iface, windows_error_str(0));
2666 return LIBUSB_ERROR_ACCESS;
2669 handle_priv->interface_handle[iface].dev_handle = handle_priv->interface_handle[0].dev_handle;
2671 usbi_dbg(ctx, "claimed interface %u", iface);
2672 handle_priv->active_interface = iface;
2674 return LIBUSB_SUCCESS;
2677 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
2679 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2680 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2681 HANDLE winusb_handle;
2683 CHECK_WINUSBX_AVAILABLE(sub_api);
2685 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2686 if (!HANDLE_VALID(winusb_handle))
2687 return LIBUSB_ERROR_NOT_FOUND;
2689 WinUSBX[sub_api].Free(winusb_handle);
2690 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2692 return LIBUSB_SUCCESS;
2696 * Return the first valid interface (of the same API type), for control transfers
2698 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2700 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2701 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2704 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2705 usbi_dbg(HANDLE_CTX(dev_handle), "unsupported API ID");
2709 for (i = 0; i < USB_MAXINTERFACES; i++) {
2710 if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
2711 && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
2712 && (priv->usb_interface[i].apib->id == api_id))
2720 * Check a specific interface is valid (of the same API type), for control transfers
2722 static int check_valid_interface(struct libusb_device_handle *dev_handle, unsigned short interface, int api_id)
2724 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2725 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2727 if (interface >= USB_MAXINTERFACES)
2730 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2731 usbi_dbg(HANDLE_CTX(dev_handle), "unsupported API ID");
2735 // try the requested interface
2736 if (HANDLE_VALID(handle_priv->interface_handle[interface].dev_handle)
2737 && HANDLE_VALID(handle_priv->interface_handle[interface].api_handle)
2738 && (priv->usb_interface[interface].apib->id == api_id))
2745 * Lookup interface by endpoint address. -1 if not found
2747 static int interface_by_endpoint(struct winusb_device_priv *priv,
2748 struct winusb_device_handle_priv *handle_priv, uint8_t endpoint_address)
2752 for (i = 0; i < USB_MAXINTERFACES; i++) {
2753 if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
2755 if (priv->usb_interface[i].endpoint == NULL)
2757 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2758 if (priv->usb_interface[i].endpoint[j] == endpoint_address)
2766 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2768 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2769 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
2770 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
2771 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
2772 PWINUSB_SETUP_PACKET setup = (PWINUSB_SETUP_PACKET)transfer->buffer;
2774 HANDLE winusb_handle;
2775 OVERLAPPED *overlapped;
2776 int current_interface;
2778 CHECK_WINUSBX_AVAILABLE(sub_api);
2780 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2782 // Windows places upper limits on the control transfer size
2783 // See: https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/usb-bandwidth-allocation#maximum-transfer-size
2784 if (size > MAX_CTRL_BUFFER_LENGTH)
2785 return LIBUSB_ERROR_INVALID_PARAM;
2787 if ((setup->RequestType & 0x1F) == LIBUSB_RECIPIENT_INTERFACE)
2788 current_interface = check_valid_interface(transfer->dev_handle, setup->Index & 0xff, USB_API_WINUSBX);
2790 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2791 if (current_interface < 0) {
2792 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
2793 return LIBUSB_ERROR_NOT_FOUND;
2796 usbi_dbg(ITRANSFER_CTX(itransfer), "will use interface %d", current_interface);
2798 transfer_priv->interface_number = (uint8_t)current_interface;
2799 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2800 set_transfer_priv_handle(itransfer, handle_priv->interface_handle[current_interface].dev_handle);
2801 overlapped = get_transfer_priv_overlapped(itransfer);
2803 // Sending of set configuration control requests from WinUSB creates issues, except when using libusb0.sys
2804 if (sub_api != SUB_API_LIBUSB0
2805 && (LIBUSB_REQ_TYPE(setup->RequestType) == LIBUSB_REQUEST_TYPE_STANDARD)
2806 && (setup->Request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
2807 if (setup->Value != priv->active_config) {
2808 usbi_warn(TRANSFER_CTX(transfer), "cannot set configuration other than the default one");
2809 return LIBUSB_ERROR_NOT_SUPPORTED;
2811 windows_force_sync_completion(itransfer, 0);
2813 if (!WinUSBX[sub_api].ControlTransfer(winusb_handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, overlapped)) {
2814 if (GetLastError() != ERROR_IO_PENDING) {
2815 usbi_warn(TRANSFER_CTX(transfer), "ControlTransfer failed: %s", windows_error_str(0));
2816 return LIBUSB_ERROR_IO;
2821 return LIBUSB_SUCCESS;
2824 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
2826 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
2827 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
2828 HANDLE winusb_handle;
2830 CHECK_WINUSBX_AVAILABLE(sub_api);
2832 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2833 if (!HANDLE_VALID(winusb_handle)) {
2834 usbi_err(HANDLE_CTX(dev_handle), "interface must be claimed first");
2835 return LIBUSB_ERROR_NOT_FOUND;
2838 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, altsetting)) {
2839 usbi_err(HANDLE_CTX(dev_handle), "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2840 return LIBUSB_ERROR_IO;
2843 return LIBUSB_SUCCESS;
2847 static void WINAPI winusbx_native_iso_transfer_continue_stream_callback(struct libusb_transfer *transfer)
2849 // If this callback is invoked, this means that we attempted to set ContinueStream
2850 // to TRUE when calling Read/WriteIsochPipeAsap in winusbx_do_iso_transfer.
2851 // The role of this callback is to fallback to ContinueStream = FALSE if the transfer
2854 struct winusb_transfer_priv *transfer_priv =
2855 get_winusb_transfer_priv(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer));
2856 bool fallback = (transfer->status != LIBUSB_TRANSFER_COMPLETED);
2859 // Restore the user callback
2860 transfer->callback = transfer_priv->iso_user_callback;
2862 for (idx = 0; idx < transfer->num_iso_packets && !fallback; idx++) {
2863 if (transfer->iso_packet_desc[idx].status != LIBUSB_TRANSFER_COMPLETED)
2868 // If the transfer was successful, we restore the user callback and call it.
2869 if (transfer->callback)
2870 transfer->callback(transfer);
2872 // If the transfer wasn't successful we reschedule the transfer while forcing it
2873 // not to continue the stream. This might results in a 5-ms delay.
2874 transfer_priv->iso_break_stream = TRUE;
2875 libusb_submit_transfer(transfer);
2878 static int winusbx_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
2880 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2881 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
2882 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
2883 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
2884 HANDLE winusb_handle;
2885 OVERLAPPED *overlapped;
2887 int current_interface;
2889 CHECK_WINUSBX_AVAILABLE(sub_api);
2891 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2892 if (current_interface < 0) {
2893 usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
2894 return LIBUSB_ERROR_NOT_FOUND;
2897 usbi_dbg(TRANSFER_CTX(transfer), "matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2899 transfer_priv->interface_number = (uint8_t)current_interface;
2900 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2901 set_transfer_priv_handle(itransfer, handle_priv->interface_handle[current_interface].dev_handle);
2902 overlapped = get_transfer_priv_overlapped(itransfer);
2904 if ((sub_api == SUB_API_LIBUSBK) || (sub_api == SUB_API_LIBUSB0)) {
2907 size_t iso_ctx_size;
2908 PKISO_CONTEXT iso_context;
2910 if (WinUSBX[sub_api].IsoReadPipe == NULL) {
2911 usbi_warn(TRANSFER_CTX(transfer), "libusbK DLL does not support isoch transfers");
2912 return LIBUSB_ERROR_NOT_SUPPORTED;
2915 iso_ctx_size = sizeof(KISO_CONTEXT) + (transfer->num_iso_packets * sizeof(KISO_PACKET));
2916 transfer_priv->iso_context = iso_context = calloc(1, iso_ctx_size);
2917 if (transfer_priv->iso_context == NULL)
2918 return LIBUSB_ERROR_NO_MEM;
2921 iso_context->StartFrame = 0;
2922 iso_context->NumberOfPackets = (SHORT)transfer->num_iso_packets;
2924 // convert the transfer packet lengths to iso_packet offsets
2926 for (i = 0; i < transfer->num_iso_packets; i++) {
2927 iso_context->IsoPackets[i].offset = offset;
2928 offset += transfer->iso_packet_desc[i].length;
2931 if (IS_XFERIN(transfer)) {
2932 usbi_dbg(TRANSFER_CTX(transfer), "reading %d iso packets", transfer->num_iso_packets);
2933 ret = WinUSBX[sub_api].IsoReadPipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, overlapped, iso_context);
2935 usbi_dbg(TRANSFER_CTX(transfer), "writing %d iso packets", transfer->num_iso_packets);
2936 ret = WinUSBX[sub_api].IsoWritePipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, overlapped, iso_context);
2939 if (!ret && GetLastError() != ERROR_IO_PENDING) {
2940 usbi_err(TRANSFER_CTX(transfer), "IsoReadPipe/IsoWritePipe failed: %s", windows_error_str(0));
2941 return LIBUSB_ERROR_IO;
2944 return LIBUSB_SUCCESS;
2945 } else if (sub_api == SUB_API_WINUSB) {
2946 WINUSB_PIPE_INFORMATION_EX pipe_info_ex = { 0 };
2947 WINUSB_ISOCH_BUFFER_HANDLE buffer_handle;
2948 ULONG iso_transfer_size_multiple;
2949 int out_transfer_length = 0;
2952 // Depending on the version of Microsoft WinUSB, isochronous transfers may not be supported.
2953 if (WinUSBX[sub_api].ReadIsochPipeAsap == NULL) {
2954 usbi_warn(TRANSFER_CTX(transfer), "WinUSB DLL does not support isoch transfers");
2955 return LIBUSB_ERROR_NOT_SUPPORTED;
2958 if (sizeof(struct libusb_iso_packet_descriptor) != sizeof(USBD_ISO_PACKET_DESCRIPTOR)) {
2959 usbi_err(TRANSFER_CTX(transfer), "size of WinUsb and libusb isoch packet descriptors don't match");
2960 return LIBUSB_ERROR_NOT_SUPPORTED;
2963 // Query the pipe extended information to find the pipe index corresponding to the endpoint.
2964 for (idx = 0; idx < priv->usb_interface[current_interface].nb_endpoints; ++idx) {
2965 ret = WinUSBX[sub_api].QueryPipeEx(winusb_handle, (UINT8)priv->usb_interface[current_interface].current_altsetting, (UCHAR)idx, &pipe_info_ex);
2967 usbi_err(TRANSFER_CTX(transfer), "couldn't query interface settings for USB pipe with index %d. Error: %s", idx, windows_error_str(0));
2968 return LIBUSB_ERROR_NOT_FOUND;
2971 if (pipe_info_ex.PipeId == transfer->endpoint && pipe_info_ex.PipeType == UsbdPipeTypeIsochronous)
2975 // Make sure we found the index.
2976 if (idx == priv->usb_interface[current_interface].nb_endpoints) {
2977 usbi_err(TRANSFER_CTX(transfer), "couldn't find isoch endpoint 0x%02x", transfer->endpoint);
2978 return LIBUSB_ERROR_NOT_FOUND;
2981 if (IS_XFERIN(transfer)) {
2982 int interval = pipe_info_ex.Interval;
2984 // For high-speed and SuperSpeed device, the interval is 2**(bInterval-1).
2985 if (transfer->dev_handle->dev->speed >= LIBUSB_SPEED_HIGH)
2986 interval = (1 << (pipe_info_ex.Interval - 1));
2988 // WinUSB only supports isoch transfers spanning a full USB frames. Later, we might be smarter about this
2989 // and allocate a temporary buffer. However, this is harder than it seems as its destruction would depend on overlapped
2991 iso_transfer_size_multiple = (pipe_info_ex.MaximumBytesPerInterval * 8) / interval;
2992 if (transfer->length % iso_transfer_size_multiple != 0) {
2993 usbi_err(TRANSFER_CTX(transfer), "length of isoch buffer must be a multiple of the MaximumBytesPerInterval * 8 / Interval");
2994 return LIBUSB_ERROR_INVALID_PARAM;
2997 // If this is an OUT transfer, we make sure the isoch packets are contiguous as this isn't supported otherwise.
2998 bool size_should_be_zero = false;
3000 for (idx = 0; idx < transfer->num_iso_packets; ++idx) {
3001 if ((size_should_be_zero && transfer->iso_packet_desc[idx].length != 0) ||
3002 (transfer->iso_packet_desc[idx].length != pipe_info_ex.MaximumBytesPerInterval && idx + 1 < transfer->num_iso_packets && transfer->iso_packet_desc[idx + 1].length > 0)) {
3003 usbi_err(TRANSFER_CTX(transfer), "isoch packets for OUT transfer with WinUSB must be contiguous in memory");
3004 return LIBUSB_ERROR_INVALID_PARAM;
3007 size_should_be_zero = (transfer->iso_packet_desc[idx].length == 0);
3008 out_transfer_length += transfer->iso_packet_desc[idx].length;
3012 if (transfer_priv->isoch_buffer_handle != NULL) {
3013 if (WinUSBX[sub_api].UnregisterIsochBuffer(transfer_priv->isoch_buffer_handle)) {
3014 transfer_priv->isoch_buffer_handle = NULL;
3016 usbi_err(TRANSFER_CTX(transfer), "failed to unregister WinUSB isoch buffer: %s", windows_error_str(0));
3017 return LIBUSB_ERROR_OTHER;
3021 // Register the isoch buffer to the operating system.
3022 ret = WinUSBX[sub_api].RegisterIsochBuffer(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, &buffer_handle);
3024 usbi_err(TRANSFER_CTX(transfer), "failed to register WinUSB isoch buffer: %s", windows_error_str(0));
3025 return LIBUSB_ERROR_NO_MEM;
3028 // Important note: the WinUSB_Read/WriteIsochPipeAsap API requires a ContinueStream parameter that tells whether the isochronous
3029 // stream must be continued or if the WinUSB driver can schedule the transfer at its convenience. Profiling subsequent transfers
3030 // with ContinueStream = FALSE showed that 5 frames, i.e. about 5 milliseconds, were left empty between each transfer. This
3031 // is critical as this greatly diminish the achievable isochronous bandwidth. We solved the problem using the following strategy:
3032 // - Transfers are first scheduled with ContinueStream = TRUE and with winusbx_iso_transfer_continue_stream_callback as user callback.
3033 // - If the transfer succeeds, winusbx_iso_transfer_continue_stream_callback restore the user callback and calls its.
3034 // - If the transfer fails, winusbx_iso_transfer_continue_stream_callback reschedule the transfer and force ContinueStream = FALSE.
3035 if (!transfer_priv->iso_break_stream) {
3036 transfer_priv->iso_user_callback = transfer->callback;
3037 transfer->callback = winusbx_native_iso_transfer_continue_stream_callback;
3040 // Initiate the transfers.
3041 if (IS_XFERIN(transfer))
3042 ret = WinUSBX[sub_api].ReadIsochPipeAsap(buffer_handle, 0, transfer->length, !transfer_priv->iso_break_stream, transfer->num_iso_packets, (PUSBD_ISO_PACKET_DESCRIPTOR)transfer->iso_packet_desc, overlapped);
3044 ret = WinUSBX[sub_api].WriteIsochPipeAsap(buffer_handle, 0, out_transfer_length, !transfer_priv->iso_break_stream, overlapped);
3046 if (!ret && GetLastError() != ERROR_IO_PENDING) {
3047 usbi_err(TRANSFER_CTX(transfer), "ReadIsochPipeAsap/WriteIsochPipeAsap failed: %s", windows_error_str(0));
3048 if (!WinUSBX[sub_api].UnregisterIsochBuffer(buffer_handle))
3049 usbi_warn(TRANSFER_CTX(transfer), "failed to unregister WinUSB isoch buffer: %s", windows_error_str(0));
3050 return LIBUSB_ERROR_IO;
3053 // Restore the ContinueStream parameter to TRUE.
3054 transfer_priv->iso_break_stream = FALSE;
3056 transfer_priv->isoch_buffer_handle = buffer_handle;
3058 return LIBUSB_SUCCESS;
3060 PRINT_UNSUPPORTED_API(winusbx_submit_iso_transfer);
3061 return LIBUSB_ERROR_NOT_SUPPORTED;
3065 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3067 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3068 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
3069 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
3070 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
3071 HANDLE winusb_handle;
3072 OVERLAPPED *overlapped;
3074 int current_interface;
3076 CHECK_WINUSBX_AVAILABLE(sub_api);
3078 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3079 if (current_interface < 0) {
3080 usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
3081 return LIBUSB_ERROR_NOT_FOUND;
3084 usbi_dbg(TRANSFER_CTX(transfer), "matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3086 transfer_priv->interface_number = (uint8_t)current_interface;
3087 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3088 set_transfer_priv_handle(itransfer, handle_priv->interface_handle[current_interface].dev_handle);
3089 overlapped = get_transfer_priv_overlapped(itransfer);
3091 if (IS_XFERIN(transfer)) {
3092 usbi_dbg(TRANSFER_CTX(transfer), "reading %d bytes", transfer->length);
3093 ret = WinUSBX[sub_api].ReadPipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, overlapped);
3095 // Set SHORT_PACKET_TERMINATE if ZLP requested.
3096 // Changing this can be a problem with packets in flight, so only allow on the first transfer.
3097 UCHAR policy = (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) != 0;
3098 uint8_t* current_zlp = &handle_priv->interface_handle[current_interface].zlp[transfer->endpoint];
3099 if (*current_zlp == WINUSB_ZLP_UNSET) {
3101 !WinUSBX[sub_api].SetPipePolicy(winusb_handle, transfer->endpoint,
3102 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
3103 usbi_err(TRANSFER_CTX(transfer), "failed to set SHORT_PACKET_TERMINATE for endpoint %02X", transfer->endpoint);
3104 return LIBUSB_ERROR_NOT_SUPPORTED;
3106 *current_zlp = policy ? WINUSB_ZLP_ON : WINUSB_ZLP_OFF;
3107 } else if (policy != (*current_zlp == WINUSB_ZLP_ON)) {
3108 usbi_err(TRANSFER_CTX(transfer), "cannot change ZERO_PACKET for endpoint %02X on Windows", transfer->endpoint);
3109 return LIBUSB_ERROR_NOT_SUPPORTED;
3112 usbi_dbg(TRANSFER_CTX(transfer), "writing %d bytes", transfer->length);
3113 ret = WinUSBX[sub_api].WritePipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, overlapped);
3116 if (!ret && GetLastError() != ERROR_IO_PENDING) {
3117 usbi_err(TRANSFER_CTX(transfer), "ReadPipe/WritePipe failed: %s", windows_error_str(0));
3118 return LIBUSB_ERROR_IO;
3121 return LIBUSB_SUCCESS;
3124 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3126 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3127 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
3128 HANDLE winusb_handle;
3129 int current_interface;
3131 CHECK_WINUSBX_AVAILABLE(sub_api);
3133 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3134 if (current_interface < 0) {
3135 usbi_err(HANDLE_CTX(dev_handle), "unable to match endpoint to an open interface - cannot clear");
3136 return LIBUSB_ERROR_NOT_FOUND;
3139 usbi_dbg(HANDLE_CTX(dev_handle), "matched endpoint %02X with interface %d", endpoint, current_interface);
3140 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
3142 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
3143 usbi_err(HANDLE_CTX(dev_handle), "ResetPipe failed: %s", windows_error_str(0));
3144 return LIBUSB_ERROR_NO_DEVICE;
3147 return LIBUSB_SUCCESS;
3150 static int winusbx_cancel_transfer(int sub_api, struct usbi_transfer *itransfer)
3152 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3153 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
3154 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
3155 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
3156 int current_interface = transfer_priv->interface_number;
3159 CHECK_WINUSBX_AVAILABLE(sub_api);
3161 usbi_dbg(TRANSFER_CTX(transfer), "will use interface %d", current_interface);
3163 handle = handle_priv->interface_handle[current_interface].api_handle;
3164 if (!WinUSBX[sub_api].AbortPipe(handle, transfer->endpoint)) {
3165 usbi_err(TRANSFER_CTX(transfer), "AbortPipe failed: %s", windows_error_str(0));
3166 return LIBUSB_ERROR_NO_DEVICE;
3169 return LIBUSB_SUCCESS;
3173 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
3174 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
3175 * "WinUSB does not support host-initiated reset port and cycle port operations" and
3176 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
3177 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
3178 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
3180 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
3181 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3183 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3184 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
3185 HANDLE winusb_handle;
3188 CHECK_WINUSBX_AVAILABLE(sub_api);
3190 // Reset any available pipe (except control)
3191 for (i = 0; i < USB_MAXINTERFACES; i++) {
3192 winusb_handle = handle_priv->interface_handle[i].api_handle;
3193 if (HANDLE_VALID(winusb_handle)) {
3194 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
3195 usbi_dbg(HANDLE_CTX(dev_handle), "resetting ep %02X", priv->usb_interface[i].endpoint[j]);
3196 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
3197 usbi_err(HANDLE_CTX(dev_handle), "AbortPipe (pipe address %02X) failed: %s",
3198 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3200 // FlushPipe seems to fail on OUT pipes
3201 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
3202 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
3203 usbi_err(HANDLE_CTX(dev_handle), "FlushPipe (pipe address %02X) failed: %s",
3204 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3206 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
3207 usbi_err(HANDLE_CTX(dev_handle), "ResetPipe (pipe address %02X) failed: %s",
3208 priv->usb_interface[i].endpoint[j], windows_error_str(0));
3213 // libusbK & libusb0 have the ability to issue an actual device reset
3214 if ((sub_api != SUB_API_WINUSB) && (WinUSBX[sub_api].ResetDevice != NULL)) {
3215 winusb_handle = handle_priv->interface_handle[0].api_handle;
3216 if (HANDLE_VALID(winusb_handle))
3217 WinUSBX[sub_api].ResetDevice(winusb_handle);
3220 return LIBUSB_SUCCESS;
3223 static enum libusb_transfer_status winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length)
3225 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3226 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
3229 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) {
3230 // for isochronous, need to copy the individual iso packet actual_lengths and statuses
3231 if ((sub_api == SUB_API_LIBUSBK) || (sub_api == SUB_API_LIBUSB0)) {
3232 // iso only supported on libusbk-based backends for now
3233 PKISO_CONTEXT iso_context = transfer_priv->iso_context;
3234 for (i = 0; i < transfer->num_iso_packets; i++) {
3235 transfer->iso_packet_desc[i].actual_length = iso_context->IsoPackets[i].actual_length;
3236 // TODO translate USDB_STATUS codes http://msdn.microsoft.com/en-us/library/ff539136(VS.85).aspx to libusb_transfer_status
3237 //transfer->iso_packet_desc[i].status = transfer_priv->iso_context->IsoPackets[i].status;
3239 } else if (sub_api == SUB_API_WINUSB) {
3240 if (IS_XFERIN(transfer)) {
3241 /* Convert isochronous packet descriptor between Windows and libusb representation.
3242 * Both representation are guaranteed to have the same length in bytes.*/
3243 PUSBD_ISO_PACKET_DESCRIPTOR usbd_iso_packet_desc = (PUSBD_ISO_PACKET_DESCRIPTOR)transfer->iso_packet_desc;
3244 for (i = 0; i < transfer->num_iso_packets; i++) {
3245 unsigned int packet_length = (i < transfer->num_iso_packets - 1) ? (usbd_iso_packet_desc[i + 1].Offset - usbd_iso_packet_desc[i].Offset) : usbd_iso_packet_desc[i].Length;
3246 unsigned int actual_length = usbd_iso_packet_desc[i].Length;
3247 USBD_STATUS status = usbd_iso_packet_desc[i].Status;
3249 transfer->iso_packet_desc[i].length = packet_length;
3250 transfer->iso_packet_desc[i].actual_length = actual_length;
3251 transfer->iso_packet_desc[i].status = usbd_status_to_libusb_transfer_status(status);
3254 for (i = 0; i < transfer->num_iso_packets; i++) {
3255 transfer->iso_packet_desc[i].status = LIBUSB_TRANSFER_COMPLETED;
3259 // This should only occur if backend is not set correctly or other backend isoc is partially implemented
3260 PRINT_UNSUPPORTED_API(copy_transfer_data);
3261 return LIBUSB_TRANSFER_ERROR;
3265 itransfer->transferred += (int)length;
3266 return LIBUSB_TRANSFER_COMPLETED;
3270 * Internal HID Support functions (from libusb-win32)
3271 * Note that functions that complete data transfer synchronously must return
3272 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3274 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3275 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3277 static int _hid_wcslen(WCHAR *str)
3281 while (str[i] && (str[i] != 0x409))
3287 static int _hid_get_device_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
3289 struct libusb_device_descriptor d;
3291 d.bLength = LIBUSB_DT_DEVICE_SIZE;
3292 d.bDescriptorType = LIBUSB_DT_DEVICE;
3293 d.bcdUSB = 0x0200; /* 2.00 */
3295 d.bDeviceSubClass = 0;
3296 d.bDeviceProtocol = 0;
3297 d.bMaxPacketSize0 = 64; /* fix this! */
3298 d.idVendor = (uint16_t)hid_priv->vid;
3299 d.idProduct = (uint16_t)hid_priv->pid;
3300 d.bcdDevice = 0x0100;
3301 d.iManufacturer = hid_priv->string_index[0];
3302 d.iProduct = hid_priv->string_index[1];
3303 d.iSerialNumber = hid_priv->string_index[2];
3304 d.bNumConfigurations = 1;
3306 if (*size > LIBUSB_DT_DEVICE_SIZE)
3307 *size = LIBUSB_DT_DEVICE_SIZE;
3308 memcpy(data, &d, *size);
3310 return LIBUSB_COMPLETED;
3313 static int _hid_get_config_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
3315 char num_endpoints = 0;
3316 size_t config_total_len = 0;
3317 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3318 struct libusb_config_descriptor *cd;
3319 struct libusb_interface_descriptor *id;
3320 struct libusb_hid_descriptor *hd;
3321 struct libusb_endpoint_descriptor *ed;
3324 if (hid_priv->input_report_size)
3326 if (hid_priv->output_report_size)
3329 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3330 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3332 cd = (struct libusb_config_descriptor *)tmp;
3333 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3334 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3335 + LIBUSB_DT_INTERFACE_SIZE);
3336 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3337 + LIBUSB_DT_INTERFACE_SIZE
3338 + LIBUSB_DT_HID_SIZE);
3340 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3341 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3342 cd->wTotalLength = (uint16_t)config_total_len;
3343 cd->bNumInterfaces = 1;
3344 cd->bConfigurationValue = 1;
3345 cd->iConfiguration = 0;
3346 cd->bmAttributes = 1 << 7; /* bus powered */
3349 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3350 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3351 id->bInterfaceNumber = 0;
3352 id->bAlternateSetting = 0;
3353 id->bNumEndpoints = num_endpoints;
3354 id->bInterfaceClass = 3;
3355 id->bInterfaceSubClass = 0;
3356 id->bInterfaceProtocol = 0;
3359 tmp_size = LIBUSB_DT_HID_SIZE;
3360 _hid_get_hid_descriptor(hid_priv, hd, &tmp_size);
3362 if (hid_priv->input_report_size) {
3363 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3364 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3365 ed->bEndpointAddress = HID_IN_EP;
3366 ed->bmAttributes = 3;
3367 ed->wMaxPacketSize = hid_priv->input_report_size - 1;
3369 ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
3372 if (hid_priv->output_report_size) {
3373 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3374 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3375 ed->bEndpointAddress = HID_OUT_EP;
3376 ed->bmAttributes = 3;
3377 ed->wMaxPacketSize = hid_priv->output_report_size - 1;
3381 if (*size > config_total_len)
3382 *size = config_total_len;
3383 memcpy(data, tmp, *size);
3385 return LIBUSB_COMPLETED;
3388 static int _hid_get_string_descriptor(struct hid_device_priv *hid_priv, int _index,
3389 void *data, size_t *size, HANDLE hid_handle)
3392 WCHAR string[MAX_USB_STRING_LENGTH];
3393 size_t tmp_size = 0;
3396 /* language ID, EN-US */
3397 char string_langid[] = {0x09, 0x04};
3400 tmp = string_langid;
3401 tmp_size = sizeof(string_langid) + 2;
3403 for (i = 0; i < 3; i++) {
3404 if (_index == (hid_priv->string_index[i])) {
3405 tmp = hid_priv->string[i];
3406 tmp_size = (_hid_wcslen(hid_priv->string[i]) + 1) * sizeof(WCHAR);
3412 if (!HidD_GetIndexedString(hid_handle, _index, string, sizeof(string)))
3413 return LIBUSB_ERROR_INVALID_PARAM;
3415 tmp_size = (_hid_wcslen(string) + 1) * sizeof(WCHAR);
3420 return LIBUSB_ERROR_INVALID_PARAM;
3422 if (tmp_size < *size)
3426 ((uint8_t *)data)[0] = (uint8_t)*size;
3427 ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
3428 memcpy((uint8_t *)data + 2, tmp, *size - 2);
3430 return LIBUSB_COMPLETED;
3433 static int _hid_get_hid_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
3435 struct libusb_hid_descriptor d;
3436 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3437 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3439 _hid_get_report_descriptor(hid_priv, tmp, &report_len);
3441 d.bLength = LIBUSB_DT_HID_SIZE;
3442 d.bDescriptorType = LIBUSB_DT_HID;
3443 d.bcdHID = 0x0110; /* 1.10 */
3445 d.bNumDescriptors = 1;
3446 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3447 d.wClassDescriptorLength = (uint16_t)report_len;
3449 if (*size > LIBUSB_DT_HID_SIZE)
3450 *size = LIBUSB_DT_HID_SIZE;
3451 memcpy(data, &d, *size);
3453 return LIBUSB_COMPLETED;
3456 static int _hid_get_report_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
3458 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3462 d[i++] = 0x06; d[i++] = hid_priv->usagePage & 0xFF; d[i++] = hid_priv->usagePage >> 8;
3464 d[i++] = 0x09; d[i++] = (uint8_t)hid_priv->usage;
3465 /* start collection (application) */
3466 d[i++] = 0xA1; d[i++] = 0x01;
3468 if (hid_priv->input_report_size) {
3469 /* usage (vendor defined) */
3470 d[i++] = 0x09; d[i++] = 0x01;
3471 /* logical minimum (0) */
3472 d[i++] = 0x15; d[i++] = 0x00;
3473 /* logical maximum (255) */
3474 d[i++] = 0x25; d[i++] = 0xFF;
3475 /* report size (8 bits) */
3476 d[i++] = 0x75; d[i++] = 0x08;
3478 d[i++] = 0x95; d[i++] = (uint8_t)hid_priv->input_report_size - 1;
3479 /* input (data, variable, absolute) */
3480 d[i++] = 0x81; d[i++] = 0x00;
3483 if (hid_priv->output_report_size) {
3484 /* usage (vendor defined) */
3485 d[i++] = 0x09; d[i++] = 0x02;
3486 /* logical minimum (0) */
3487 d[i++] = 0x15; d[i++] = 0x00;
3488 /* logical maximum (255) */
3489 d[i++] = 0x25; d[i++] = 0xFF;
3490 /* report size (8 bits) */
3491 d[i++] = 0x75; d[i++] = 0x08;
3493 d[i++] = 0x95; d[i++] = (uint8_t)hid_priv->output_report_size - 1;
3494 /* output (data, variable, absolute) */
3495 d[i++] = 0x91; d[i++] = 0x00;
3497 /* feature report */
3498 if (hid_priv->feature_report_size) {
3499 /* usage (vendor defined) */
3500 d[i++] = 0x09; d[i++] = 0x03;
3501 /* logical minimum (0) */
3502 d[i++] = 0x15; d[i++] = 0x00;
3503 /* logical maximum (255) */
3504 d[i++] = 0x25; d[i++] = 0xFF;
3505 /* report size (8 bits) */
3506 d[i++] = 0x75; d[i++] = 0x08;
3508 d[i++] = 0x95; d[i++] = (uint8_t)hid_priv->feature_report_size - 1;
3509 /* feature (data, variable, absolute) */
3510 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3513 /* end collection */
3518 memcpy(data, d, *size);
3520 return LIBUSB_COMPLETED;
3523 static int _hid_get_descriptor(struct libusb_device *dev, HANDLE hid_handle, int recipient,
3524 int type, int _index, void *data, size_t *size)
3526 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
3530 case LIBUSB_DT_DEVICE:
3531 usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_DEVICE");
3532 return _hid_get_device_descriptor(priv->hid, data, size);
3533 case LIBUSB_DT_CONFIG:
3534 usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_CONFIG");
3536 return _hid_get_config_descriptor(priv->hid, data, size);
3537 return LIBUSB_ERROR_INVALID_PARAM;
3538 case LIBUSB_DT_STRING:
3539 usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_STRING");
3540 return _hid_get_string_descriptor(priv->hid, _index, data, size, hid_handle);
3542 usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_HID");
3544 return _hid_get_hid_descriptor(priv->hid, data, size);
3545 return LIBUSB_ERROR_INVALID_PARAM;
3546 case LIBUSB_DT_REPORT:
3547 usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_REPORT");
3549 return _hid_get_report_descriptor(priv->hid, data, size);
3550 return LIBUSB_ERROR_INVALID_PARAM;
3551 case LIBUSB_DT_PHYSICAL:
3552 usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_PHYSICAL");
3553 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3554 return LIBUSB_COMPLETED;
3555 return LIBUSB_ERROR_OTHER;
3558 usbi_warn(DEVICE_CTX(dev), "unsupported");
3559 return LIBUSB_ERROR_NOT_SUPPORTED;
3562 static int _hid_get_report(struct libusb_device *dev, HANDLE hid_handle, int id, void *data,
3563 struct winusb_transfer_priv *tp, size_t size, OVERLAPPED *overlapped, int report_type)
3565 DWORD ioctl_code, expected_size = (DWORD)size;
3568 if (tp->hid_buffer != NULL)
3569 usbi_err(DEVICE_CTX(dev), "program assertion failed - hid_buffer is not NULL");
3571 if ((size == 0) || (size > MAX_HID_REPORT_SIZE)) {
3572 usbi_warn(DEVICE_CTX(dev), "invalid size (%"PRIuPTR")", (uintptr_t)size);
3573 return LIBUSB_ERROR_INVALID_PARAM;
3576 switch (report_type) {
3577 case HID_REPORT_TYPE_INPUT:
3578 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3580 case HID_REPORT_TYPE_FEATURE:
3581 ioctl_code = IOCTL_HID_GET_FEATURE;
3584 usbi_warn(DEVICE_CTX(dev), "unknown HID report type %d", report_type);
3585 return LIBUSB_ERROR_INVALID_PARAM;
3588 // Add a trailing byte to detect overflows
3589 buf = calloc(1, expected_size + 1);
3591 return LIBUSB_ERROR_NO_MEM;
3593 buf[0] = (uint8_t)id; // Must be set always
3594 usbi_dbg(DEVICE_CTX(dev), "report ID: 0x%02X", buf[0]);
3596 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3597 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
3598 buf, expected_size + 1, NULL, overlapped)) {
3599 if (GetLastError() != ERROR_IO_PENDING) {
3600 usbi_err(DEVICE_CTX(dev), "failed to read HID Report: %s", windows_error_str(0));
3602 return LIBUSB_ERROR_IO;
3606 // Asynchronous wait
3607 tp->hid_buffer = buf;
3608 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3609 tp->hid_expected_size = expected_size;
3611 return LIBUSB_SUCCESS;
3614 static int _hid_set_report(struct libusb_device *dev, HANDLE hid_handle, int id, void *data,
3615 struct winusb_transfer_priv *tp, size_t size, OVERLAPPED *overlapped, int report_type)
3617 DWORD ioctl_code, write_size = (DWORD)size;
3618 // If an id is reported, we must allow MAX_HID_REPORT_SIZE + 1
3619 size_t max_report_size = MAX_HID_REPORT_SIZE + (id ? 1 : 0);
3622 if (tp->hid_buffer != NULL)
3623 usbi_err(DEVICE_CTX(dev), "program assertion failed - hid_buffer is not NULL");
3625 if ((size == 0) || (size > max_report_size)) {
3626 usbi_warn(DEVICE_CTX(dev), "invalid size (%"PRIuPTR")", (uintptr_t)size);
3627 return LIBUSB_ERROR_INVALID_PARAM;
3630 switch (report_type) {
3631 case HID_REPORT_TYPE_OUTPUT:
3632 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3634 case HID_REPORT_TYPE_FEATURE:
3635 ioctl_code = IOCTL_HID_SET_FEATURE;
3638 usbi_warn(DEVICE_CTX(dev), "unknown HID report type %d", report_type);
3639 return LIBUSB_ERROR_INVALID_PARAM;
3642 usbi_dbg(DEVICE_CTX(dev), "report ID: 0x%02X", id);
3643 // When report IDs are not used (i.e. when id == 0), we must add
3644 // a null report ID. Otherwise, we just use original data buffer
3648 buf = malloc(write_size);
3650 return LIBUSB_ERROR_NO_MEM;
3654 memcpy(buf + 1, data, size);
3656 // This seems like a waste, but if we don't duplicate the
3657 // data, we'll get issues when freeing hid_buffer
3658 memcpy(buf, data, size);
3660 usbi_warn(DEVICE_CTX(dev), "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3663 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3664 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3665 buf, write_size, NULL, overlapped)) {
3666 if (GetLastError() != ERROR_IO_PENDING) {
3667 usbi_err(DEVICE_CTX(dev), "failed to write HID Output Report: %s", windows_error_str(0));
3669 return LIBUSB_ERROR_IO;
3673 tp->hid_buffer = buf;
3674 tp->hid_dest = NULL;
3675 return LIBUSB_SUCCESS;
3678 static int _hid_class_request(struct libusb_device *dev, HANDLE hid_handle, int request_type,
3679 int request, int value, int _index, void *data, struct winusb_transfer_priv *tp,
3680 size_t size, OVERLAPPED *overlapped)
3682 int report_type = (value >> 8) & 0xFF;
3683 int report_id = value & 0xFF;
3687 if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3688 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
3689 return LIBUSB_ERROR_INVALID_PARAM;
3691 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3692 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3694 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3695 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3697 return LIBUSB_ERROR_INVALID_PARAM;
3703 static bool hid_init(struct libusb_context *ctx)
3705 DLL_GET_HANDLE(ctx, hid);
3707 DLL_LOAD_FUNC(hid, HidD_GetAttributes, true);
3708 DLL_LOAD_FUNC(hid, HidD_GetHidGuid, true);
3709 DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, true);
3710 DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, true);
3711 DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, true);
3712 DLL_LOAD_FUNC(hid, HidD_GetProductString, true);
3713 DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, true);
3714 DLL_LOAD_FUNC(hid, HidD_GetIndexedString, true);
3715 DLL_LOAD_FUNC(hid, HidP_GetCaps, true);
3716 DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, true);
3717 DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, true);
3718 DLL_LOAD_FUNC(hid, HidD_FlushQueue, true);
3719 DLL_LOAD_FUNC(hid, HidP_GetValueCaps, true);
3724 static void hid_exit(void)
3726 DLL_FREE_HANDLE(hid);
3729 // NB: open and close must ensure that they only handle interface of
3730 // the right API type, as these functions can be called wholesale from
3731 // composite_open(), with interfaces belonging to different APIs
3732 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3734 struct libusb_device *dev = dev_handle->dev;
3735 struct winusb_device_priv *priv = usbi_get_device_priv(dev);
3736 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3737 HIDD_ATTRIBUTES hid_attributes;
3738 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3739 HIDP_CAPS capabilities;
3740 HIDP_VALUE_CAPS *value_caps;
3741 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3743 // report IDs handling
3745 int nb_ids[2]; // zero and nonzero report IDs
3746 #if defined(ENABLE_LOGGING)
3747 const char * const type[3] = {"input", "output", "feature"};
3751 CHECK_HID_AVAILABLE;
3753 if (priv->hid == NULL) {
3754 usbi_err(HANDLE_CTX(dev_handle), "program assertion failed - private HID structure is uninitialized");
3755 return LIBUSB_ERROR_NOT_FOUND;
3758 for (i = 0; i < USB_MAXINTERFACES; i++) {
3759 if ((priv->usb_interface[i].path != NULL)
3760 && (priv->usb_interface[i].apib->id == USB_API_HID)) {
3761 hid_handle = windows_open(dev_handle, priv->usb_interface[i].path, GENERIC_READ | GENERIC_WRITE);
3763 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3764 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3765 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3766 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3767 * HidD_GetFeature (if the device supports Feature reports)."
3769 if (hid_handle == INVALID_HANDLE_VALUE) {
3770 usbi_warn(HANDLE_CTX(dev_handle), "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3771 hid_handle = windows_open(dev_handle, priv->usb_interface[i].path, 0);
3772 if (hid_handle == INVALID_HANDLE_VALUE) {
3773 usbi_err(HANDLE_CTX(dev_handle), "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3774 switch (GetLastError()) {
3775 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3776 return LIBUSB_ERROR_NO_DEVICE;
3777 case ERROR_ACCESS_DENIED:
3778 return LIBUSB_ERROR_ACCESS;
3780 return LIBUSB_ERROR_IO;
3783 priv->usb_interface[i].restricted_functionality = true;
3785 handle_priv->interface_handle[i].api_handle = hid_handle;
3789 hid_attributes.Size = sizeof(hid_attributes);
3791 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3792 usbi_err(HANDLE_CTX(dev_handle), "could not gain access to HID top collection (HidD_GetAttributes)");
3796 priv->hid->vid = hid_attributes.VendorID;
3797 priv->hid->pid = hid_attributes.ProductID;
3799 // Set the maximum available input buffer size
3800 for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
3801 usbi_dbg(HANDLE_CTX(dev_handle), "set maximum input buffer size to %d", i / 2);
3803 // Get the maximum input and output report size
3804 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3805 usbi_err(HANDLE_CTX(dev_handle), "could not read HID preparsed data (HidD_GetPreparsedData)");
3808 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3809 usbi_err(HANDLE_CTX(dev_handle), "could not parse HID capabilities (HidP_GetCaps)");
3813 // Find out if interrupt will need report IDs
3814 size[0] = capabilities.NumberInputValueCaps;
3815 size[1] = capabilities.NumberOutputValueCaps;
3816 size[2] = capabilities.NumberFeatureValueCaps;
3817 for (j = HidP_Input; j <= HidP_Feature; j++) {
3818 usbi_dbg(HANDLE_CTX(dev_handle), "%lu HID %s report value(s) found", ULONG_CAST(size[j]), type[j]);
3819 priv->hid->uses_report_ids[j] = false;
3821 value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3822 if ((value_caps != NULL)
3823 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3824 && (size[j] >= 1)) {
3827 for (i = 0; i < (int)size[j]; i++) {
3828 usbi_dbg(HANDLE_CTX(dev_handle), " Report ID: 0x%02X", value_caps[i].ReportID);
3829 if (value_caps[i].ReportID != 0)
3834 if (nb_ids[1] != 0) {
3836 usbi_warn(HANDLE_CTX(dev_handle), "program assertion failed - zero and nonzero report IDs used for %s",
3838 priv->hid->uses_report_ids[j] = true;
3841 usbi_warn(HANDLE_CTX(dev_handle), " could not process %s report IDs", type[j]);
3847 // Set the report sizes
3848 priv->hid->input_report_size = capabilities.InputReportByteLength;
3849 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3850 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3852 // Store usage and usagePage values
3853 priv->hid->usage = capabilities.Usage;
3854 priv->hid->usagePage = capabilities.UsagePage;
3856 // Fetch string descriptors
3857 priv->hid->string_index[0] = dev->device_descriptor.iManufacturer;
3858 if (priv->hid->string_index[0] != 0)
3859 HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
3861 priv->hid->string[0][0] = 0;
3863 priv->hid->string_index[1] = dev->device_descriptor.iProduct;
3864 if (priv->hid->string_index[1] != 0)
3865 HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1]));
3867 priv->hid->string[1][0] = 0;
3869 priv->hid->string_index[2] = dev->device_descriptor.iSerialNumber;
3870 if (priv->hid->string_index[2] != 0)
3871 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
3873 priv->hid->string[2][0] = 0;
3877 HidD_FreePreparsedData(preparsed_data);
3879 return LIBUSB_SUCCESS;
3882 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3884 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
3885 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3891 if (DLL_HANDLE_NAME(hid) == NULL)
3894 for (i = 0; i < USB_MAXINTERFACES; i++) {
3895 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3896 file_handle = handle_priv->interface_handle[i].api_handle;
3897 if (HANDLE_VALID(file_handle))
3898 CloseHandle(file_handle);
3903 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
3905 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3906 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
3909 CHECK_HID_AVAILABLE;
3911 // NB: Disconnection detection is not possible in this function
3912 if (priv->usb_interface[iface].path == NULL)
3913 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3915 // We use dev_handle as a flag for interface claimed
3916 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
3917 return LIBUSB_ERROR_BUSY; // already claimed
3919 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3921 usbi_dbg(HANDLE_CTX(dev_handle), "claimed interface %u", iface);
3922 handle_priv->active_interface = iface;
3924 return LIBUSB_SUCCESS;
3927 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
3929 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3930 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
3933 CHECK_HID_AVAILABLE;
3935 if (priv->usb_interface[iface].path == NULL)
3936 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3938 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
3939 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3941 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3943 return LIBUSB_SUCCESS;
3946 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
3951 CHECK_HID_AVAILABLE;
3953 if (altsetting != 0) {
3954 usbi_err(HANDLE_CTX(dev_handle), "set interface altsetting not supported for altsetting >0");
3955 return LIBUSB_ERROR_NOT_SUPPORTED;
3958 return LIBUSB_SUCCESS;
3961 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3963 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3964 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
3965 struct libusb_device_handle *dev_handle = transfer->dev_handle;
3966 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
3967 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
3968 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
3970 OVERLAPPED *overlapped;
3971 int current_interface;
3977 CHECK_HID_AVAILABLE;
3979 safe_free(transfer_priv->hid_buffer);
3980 transfer_priv->hid_dest = NULL;
3981 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3983 if (size > MAX_CTRL_BUFFER_LENGTH)
3984 return LIBUSB_ERROR_INVALID_PARAM;
3986 current_interface = get_valid_interface(dev_handle, USB_API_HID);
3987 if (current_interface < 0) {
3988 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS)
3989 return LIBUSB_ERROR_NOT_FOUND;
3992 usbi_dbg(ITRANSFER_CTX(itransfer), "will use interface %d", current_interface);
3994 transfer_priv->interface_number = (uint8_t)current_interface;
3995 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3996 set_transfer_priv_handle(itransfer, hid_handle);
3997 overlapped = get_transfer_priv_overlapped(itransfer);
3999 switch (LIBUSB_REQ_TYPE(setup->RequestType)) {
4000 case LIBUSB_REQUEST_TYPE_STANDARD:
4001 switch (setup->Request) {
4002 case LIBUSB_REQUEST_GET_DESCRIPTOR:
4003 r = _hid_get_descriptor(dev_handle->dev, hid_handle, LIBUSB_REQ_RECIPIENT(setup->RequestType),
4004 (setup->Value >> 8) & 0xFF, setup->Value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
4006 case LIBUSB_REQUEST_GET_CONFIGURATION:
4007 r = winusb_get_configuration(dev_handle, &config);
4008 if (r == LIBUSB_SUCCESS) {
4010 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = config;
4011 r = LIBUSB_COMPLETED;
4014 case LIBUSB_REQUEST_SET_CONFIGURATION:
4015 if (setup->Value == priv->active_config) {
4016 r = LIBUSB_COMPLETED;
4018 usbi_warn(TRANSFER_CTX(transfer), "cannot set configuration other than the default one");
4019 r = LIBUSB_ERROR_NOT_SUPPORTED;
4022 case LIBUSB_REQUEST_GET_INTERFACE:
4024 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
4025 r = LIBUSB_COMPLETED;
4027 case LIBUSB_REQUEST_SET_INTERFACE:
4028 r = hid_set_interface_altsetting(0, dev_handle, (uint8_t)setup->Index, (uint8_t)setup->Value);
4029 if (r == LIBUSB_SUCCESS)
4030 r = LIBUSB_COMPLETED;
4033 usbi_warn(TRANSFER_CTX(transfer), "unsupported HID control request");
4034 return LIBUSB_ERROR_NOT_SUPPORTED;
4037 case LIBUSB_REQUEST_TYPE_CLASS:
4038 r = _hid_class_request(dev_handle->dev, hid_handle, setup->RequestType, setup->Request, setup->Value,
4039 setup->Index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
4043 usbi_warn(TRANSFER_CTX(transfer), "unsupported HID control request");
4044 return LIBUSB_ERROR_NOT_SUPPORTED;
4050 if (r == LIBUSB_COMPLETED) {
4051 // Force request to be completed synchronously. Transferred size has been set by previous call
4052 windows_force_sync_completion(itransfer, (ULONG)size);
4056 return LIBUSB_SUCCESS;
4059 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
4061 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4062 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
4063 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
4064 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
4066 OVERLAPPED *overlapped;
4069 int current_interface, length;
4072 CHECK_HID_AVAILABLE;
4074 if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
4075 return LIBUSB_ERROR_NOT_SUPPORTED;
4077 transfer_priv->hid_dest = NULL;
4078 safe_free(transfer_priv->hid_buffer);
4080 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4081 if (current_interface < 0) {
4082 usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
4083 return LIBUSB_ERROR_NOT_FOUND;
4086 usbi_dbg(TRANSFER_CTX(transfer), "matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
4088 transfer_priv->interface_number = (uint8_t)current_interface;
4089 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4090 set_transfer_priv_handle(itransfer, hid_handle);
4091 overlapped = get_transfer_priv_overlapped(itransfer);
4092 direction_in = IS_XFERIN(transfer);
4094 // If report IDs are not in use, an extra prefix byte must be added
4095 if (((direction_in) && (!priv->hid->uses_report_ids[0]))
4096 || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
4097 length = transfer->length + 1;
4099 length = transfer->length;
4101 // Add a trailing byte to detect overflows on input
4102 transfer_priv->hid_buffer = calloc(1, length + 1);
4103 if (transfer_priv->hid_buffer == NULL)
4104 return LIBUSB_ERROR_NO_MEM;
4106 transfer_priv->hid_expected_size = length;
4109 transfer_priv->hid_dest = transfer->buffer;
4110 usbi_dbg(TRANSFER_CTX(transfer), "reading %d bytes (report ID: 0x00)", length);
4111 ret = ReadFile(hid_handle, transfer_priv->hid_buffer, length + 1, NULL, overlapped);
4113 if (!priv->hid->uses_report_ids[1])
4114 memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
4116 // We could actually do without the calloc and memcpy in this case
4117 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
4119 usbi_dbg(TRANSFER_CTX(transfer), "writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
4120 ret = WriteFile(hid_handle, transfer_priv->hid_buffer, length, NULL, overlapped);
4123 if (!ret && GetLastError() != ERROR_IO_PENDING) {
4124 usbi_err(TRANSFER_CTX(transfer), "HID transfer failed: %s", windows_error_str(0));
4125 safe_free(transfer_priv->hid_buffer);
4126 return LIBUSB_ERROR_IO;
4129 return LIBUSB_SUCCESS;
4132 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4134 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
4136 int current_interface;
4139 CHECK_HID_AVAILABLE;
4141 // Flushing the queues on all interfaces is the best we can achieve
4142 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
4143 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4144 if (HANDLE_VALID(hid_handle))
4145 HidD_FlushQueue(hid_handle);
4148 return LIBUSB_SUCCESS;
4151 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4153 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
4154 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4156 int current_interface;
4159 CHECK_HID_AVAILABLE;
4161 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4162 if (current_interface < 0) {
4163 usbi_err(HANDLE_CTX(dev_handle), "unable to match endpoint to an open interface - cannot clear");
4164 return LIBUSB_ERROR_NOT_FOUND;
4167 usbi_dbg(HANDLE_CTX(dev_handle), "matched endpoint %02X with interface %d", endpoint, current_interface);
4168 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
4170 // No endpoint selection with Microsoft's implementation, so we try to flush the
4171 // whole interface. Should be OK for most case scenarios
4172 if (!HidD_FlushQueue(hid_handle)) {
4173 usbi_err(HANDLE_CTX(dev_handle), "Flushing of HID queue failed: %s", windows_error_str(0));
4174 // Device was probably disconnected
4175 return LIBUSB_ERROR_NO_DEVICE;
4178 return LIBUSB_SUCCESS;
4181 // This extra function is only needed for HID
4182 static enum libusb_transfer_status hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length)
4184 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4185 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
4186 enum libusb_transfer_status r = LIBUSB_TRANSFER_COMPLETED;
4190 if (transfer_priv->hid_buffer != NULL) {
4191 // If we have a valid hid_buffer, it means the transfer was async
4192 if (transfer_priv->hid_dest != NULL) { // Data readout
4194 // First, check for overflow
4195 if ((size_t)length > transfer_priv->hid_expected_size) {
4196 usbi_err(TRANSFER_CTX(transfer), "OVERFLOW!");
4197 length = (DWORD)transfer_priv->hid_expected_size;
4198 r = LIBUSB_TRANSFER_OVERFLOW;
4201 if (transfer_priv->hid_buffer[0] == 0) {
4202 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, length);
4204 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, length);
4207 transfer_priv->hid_dest = NULL;
4209 // For write, we just need to free the hid buffer
4210 safe_free(transfer_priv->hid_buffer);
4213 itransfer->transferred += (int)length;
4219 * Composite API functions
4221 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4223 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4224 int i, r = LIBUSB_ERROR_NOT_FOUND;
4225 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4226 bool available[SUB_API_MAX + 1];
4230 for (i = 0; i < SUB_API_MAX + 1; i++)
4231 available[i] = false;
4233 for (i = 0; i < USB_MAXINTERFACES; i++) {
4234 switch (priv->usb_interface[i].apib->id) {
4235 case USB_API_WINUSBX:
4236 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4237 available[priv->usb_interface[i].sub_api] = true;
4240 available[SUB_API_MAX] = true;
4247 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4249 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4250 if (r != LIBUSB_SUCCESS)
4255 if (available[SUB_API_MAX]) { // HID driver
4256 r = hid_open(SUB_API_NOTSET, dev_handle);
4258 // On Windows 10 version 1903 (OS Build 18362) and later Windows blocks attempts to
4259 // open HID devices with a U2F usage unless running as administrator. We ignore this
4260 // failure and proceed without the HID device opened.
4261 if (r == LIBUSB_ERROR_ACCESS) {
4262 usbi_dbg(HANDLE_CTX(dev_handle), "ignoring access denied error while opening HID interface of composite device");
4270 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4272 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4274 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4275 bool available[SUB_API_MAX + 1];
4279 for (i = 0; i < SUB_API_MAX + 1; i++)
4280 available[i] = false;
4282 for (i = 0; i < USB_MAXINTERFACES; i++) {
4283 switch (priv->usb_interface[i].apib->id) {
4284 case USB_API_WINUSBX:
4285 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4286 available[priv->usb_interface[i].sub_api] = true;
4289 available[SUB_API_MAX] = true;
4296 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4298 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4301 if (available[SUB_API_MAX]) // HID driver
4302 hid_close(SUB_API_NOTSET, dev_handle);
4305 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
4307 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4310 CHECK_SUPPORTED_API(priv->usb_interface[iface].apib, claim_interface);
4312 return priv->usb_interface[iface].apib->
4313 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4316 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
4318 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4321 CHECK_SUPPORTED_API(priv->usb_interface[iface].apib, set_interface_altsetting);
4323 return priv->usb_interface[iface].apib->
4324 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4327 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
4329 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4332 CHECK_SUPPORTED_API(priv->usb_interface[iface].apib, release_interface);
4334 return priv->usb_interface[iface].apib->
4335 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4338 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4340 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4341 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
4342 struct libusb_config_descriptor *conf_desc;
4343 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
4348 // Interface shouldn't matter for control, but it does in practice, with Windows'
4349 // restrictions with regards to accessing HID keyboards and mice. Try to target
4350 // a specific interface first, if possible.
4351 switch (LIBUSB_REQ_RECIPIENT(setup->RequestType)) {
4352 case LIBUSB_RECIPIENT_INTERFACE:
4353 iface = setup->Index & 0xFF;
4355 case LIBUSB_RECIPIENT_ENDPOINT:
4356 r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc);
4357 if (r == LIBUSB_SUCCESS) {
4358 iface = get_interface_by_endpoint(conf_desc, (setup->Index & 0xFF));
4359 libusb_free_config_descriptor(conf_desc);
4362 // No break if not able to determine interface
4369 // Try and target a specific interface if the control setup indicates such
4370 if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4371 usbi_dbg(TRANSFER_CTX(transfer), "attempting control transfer targeted to interface %d", iface);
4372 if ((priv->usb_interface[iface].path != NULL)
4373 && (priv->usb_interface[iface].apib->submit_control_transfer != NULL)) {
4374 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4375 if (r == LIBUSB_SUCCESS)
4380 // Either not targeted to a specific interface or no luck in doing so.
4381 // Try a 2 pass approach with all interfaces.
4382 for (pass = 0; pass < 2; pass++) {
4383 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4384 if ((priv->usb_interface[iface].path != NULL)
4385 && (priv->usb_interface[iface].apib->submit_control_transfer != NULL)) {
4386 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4387 usbi_dbg(TRANSFER_CTX(transfer), "trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4390 usbi_dbg(TRANSFER_CTX(transfer), "using interface %d", iface);
4391 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4392 // If not supported on this API, it may be supported on another, so don't give up yet!!
4393 if (r == LIBUSB_ERROR_NOT_SUPPORTED)
4400 usbi_err(TRANSFER_CTX(transfer), "no libusb supported interfaces to complete request");
4401 return LIBUSB_ERROR_NOT_FOUND;
4404 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
4406 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4407 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
4408 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
4409 int current_interface;
4413 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4414 if (current_interface < 0) {
4415 usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
4416 return LIBUSB_ERROR_NOT_FOUND;
4419 CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, submit_bulk_transfer);
4421 return priv->usb_interface[current_interface].apib->
4422 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4425 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
4427 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4428 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
4429 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
4430 int current_interface;
4434 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4435 if (current_interface < 0) {
4436 usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
4437 return LIBUSB_ERROR_NOT_FOUND;
4440 CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, submit_iso_transfer);
4442 return priv->usb_interface[current_interface].apib->
4443 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4446 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4448 struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
4449 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4450 int current_interface;
4454 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4455 if (current_interface < 0) {
4456 usbi_err(HANDLE_CTX(dev_handle), "unable to match endpoint to an open interface - cannot clear");
4457 return LIBUSB_ERROR_NOT_FOUND;
4460 CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, clear_halt);
4462 return priv->usb_interface[current_interface].apib->
4463 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
4466 static int composite_cancel_transfer(int sub_api, struct usbi_transfer *itransfer)
4468 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4469 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
4470 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
4471 int current_interface = transfer_priv->interface_number;
4475 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
4476 usbi_err(TRANSFER_CTX(transfer), "program assertion failed - invalid interface_number");
4477 return LIBUSB_ERROR_NOT_FOUND;
4480 CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, cancel_transfer);
4482 return priv->usb_interface[current_interface].apib->
4483 cancel_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4486 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4488 struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
4490 bool available[SUB_API_MAX];
4494 for (i = 0; i < SUB_API_MAX; i++)
4495 available[i] = false;
4497 for (i = 0; i < USB_MAXINTERFACES; i++) {
4498 if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4499 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
4500 available[priv->usb_interface[i].sub_api] = true;
4503 for (i = 0; i < SUB_API_MAX; i++) {
4505 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4506 if (r != LIBUSB_SUCCESS)
4511 return LIBUSB_SUCCESS;
4514 static enum libusb_transfer_status composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length)
4516 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4517 struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
4518 struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
4519 int current_interface = transfer_priv->interface_number;
4522 if (priv->usb_interface[current_interface].apib->copy_transfer_data == NULL) {
4523 usbi_err(TRANSFER_CTX(transfer), "program assertion failed - no function to copy transfer data");
4524 return LIBUSB_TRANSFER_ERROR;
4527 return priv->usb_interface[current_interface].apib->
4528 copy_transfer_data(priv->usb_interface[current_interface].sub_api, itransfer, length);