2 * windows backend for libusb 1.0
3 * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
6 * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
7 * Hash table functions adapted from glibc, by Ulrich Drepper et al.
8 * Major code testing contribution by Xiaofan Chen
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #if !defined(USE_USBDK)
41 #include "poll_windows.h"
42 #include "windows_winusb.h"
44 #define HANDLE_VALID(h) (((h) != 0) && ((h) != INVALID_HANDLE_VALUE))
46 // The 2 macros below are used in conjunction with safe loops.
47 #define LOOP_CHECK(fcall) \
50 if (r != LIBUSB_SUCCESS) \
53 #define LOOP_BREAK(err) \
59 // WinUSB-like API prototypes
60 static int winusbx_init(int sub_api, struct libusb_context *ctx);
61 static int winusbx_exit(int sub_api);
62 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
63 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
64 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface);
65 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
66 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
67 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
68 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
69 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
70 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
71 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
72 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer);
73 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
74 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
76 static int hid_init(int sub_api, struct libusb_context *ctx);
77 static int hid_exit(int sub_api);
78 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
79 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
80 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
81 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
82 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
83 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
84 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
85 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
86 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
87 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
88 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
89 // Composite API prototypes
90 static int composite_init(int sub_api, struct libusb_context *ctx);
91 static int composite_exit(int sub_api);
92 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
93 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
94 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
95 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting);
96 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface);
97 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
98 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
99 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
100 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
101 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer);
102 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer);
103 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
104 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size);
108 int windows_version = WINDOWS_UNDEFINED;
110 static int concurrent_usage = -1;
111 static usbi_mutex_t autoclaim_lock;
113 #define CHECK_WINUSBX_AVAILABLE(sub_api) \
115 if (sub_api == SUB_API_NOTSET) \
116 sub_api = priv->sub_api; \
117 if (!WinUSBX[sub_api].initialized) \
118 return LIBUSB_ERROR_ACCESS; \
121 static HMODULE WinUSBX_handle = NULL;
122 static struct winusb_interface WinUSBX[SUB_API_MAX];
123 static const char *sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES;
125 static bool api_hid_available = false;
126 #define CHECK_HID_AVAILABLE \
128 if (!api_hid_available) \
129 return LIBUSB_ERROR_ACCESS; \
132 static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2)
134 if ((guid1 != NULL) && (guid2 != NULL))
135 return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
140 #if defined(ENABLE_LOGGING)
141 static char *guid_to_string(const GUID *guid)
143 static char guid_string[MAX_GUID_STRING_LENGTH];
148 sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
149 (unsigned int)guid->Data1, guid->Data2, guid->Data3,
150 guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
151 guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
158 * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
159 * Return an allocated sanitized string or NULL on error.
161 static char *sanitize_path(const char *path)
163 const char root_prefix[] = { '\\', '\\', '.', '\\' };
171 size = strlen(path) + 1;
173 // Microsoft indiscriminately uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
174 if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\'))
175 || ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
176 add_root = sizeof(root_prefix);
180 ret_path = malloc(size);
181 if (ret_path == NULL)
184 strcpy(&ret_path[add_root], path);
186 // Ensure consistency with root prefix
187 memcpy(ret_path, root_prefix, sizeof(root_prefix));
189 // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
190 for (j = sizeof(root_prefix); j < size; j++) {
191 ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
192 if (ret_path[j] == '\\')
200 * Cfgmgr32, OLE32 and SetupAPI DLL functions
202 static int init_dlls(void)
204 DLL_GET_HANDLE(Cfgmgr32);
205 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Parent, TRUE);
206 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Child, TRUE);
207 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Sibling, TRUE);
208 DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Device_IDA, TRUE);
210 // Prefixed to avoid conflict with header files
211 DLL_GET_HANDLE(AdvAPI32);
212 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegQueryValueExW, TRUE);
213 DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegCloseKey, TRUE);
215 DLL_GET_HANDLE(Kernel32);
216 DLL_LOAD_FUNC_PREFIXED(Kernel32, p, IsWow64Process, FALSE);
218 DLL_GET_HANDLE(OLE32);
219 DLL_LOAD_FUNC_PREFIXED(OLE32, p, CLSIDFromString, TRUE);
221 DLL_GET_HANDLE(SetupAPI);
222 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetClassDevsA, TRUE);
223 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInfo, TRUE);
224 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInterfaces, TRUE);
225 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
226 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiDestroyDeviceInfoList, TRUE);
227 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDevRegKey, TRUE);
228 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
229 DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDeviceInterfaceRegKey, TRUE);
231 return LIBUSB_SUCCESS;
234 static void exit_dlls(void)
236 DLL_FREE_HANDLE(Cfgmgr32);
237 DLL_FREE_HANDLE(AdvAPI32);
238 DLL_FREE_HANDLE(Kernel32);
239 DLL_FREE_HANDLE(OLE32);
240 DLL_FREE_HANDLE(SetupAPI);
244 * enumerate interfaces for the whole USB class
247 * dev_info: a pointer to a dev_info list
248 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
249 * usb_class: the generic USB class for which to retrieve interface details
250 * index: zero based index of the interface in the device info list
252 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
253 * structure returned and call this function repeatedly using the same guid (with an
254 * incremented index starting at zero) until all interfaces have been returned.
256 static bool get_devinfo_data(struct libusb_context *ctx,
257 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char *usb_class, unsigned _index)
260 *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
261 if (*dev_info == INVALID_HANDLE_VALUE)
265 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
266 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
267 if (GetLastError() != ERROR_NO_MORE_ITEMS)
268 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
269 _index, windows_error_str(0));
271 pSetupDiDestroyDeviceInfoList(*dev_info);
272 *dev_info = INVALID_HANDLE_VALUE;
279 * enumerate interfaces for a specific GUID
282 * dev_info: a pointer to a dev_info list
283 * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
284 * guid: the GUID for which to retrieve interface details
285 * index: zero based index of the interface in the device info list
287 * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
288 * structure returned and call this function repeatedly using the same guid (with an
289 * incremented index starting at zero) until all interfaces have been returned.
291 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
292 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index)
294 SP_DEVICE_INTERFACE_DATA dev_interface_data;
295 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details;
299 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
301 if (dev_info_data != NULL) {
302 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
303 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
304 if (GetLastError() != ERROR_NO_MORE_ITEMS)
305 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
306 _index, windows_error_str(0));
308 pSetupDiDestroyDeviceInfoList(*dev_info);
309 *dev_info = INVALID_HANDLE_VALUE;
314 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
315 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
316 if (GetLastError() != ERROR_NO_MORE_ITEMS)
317 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
318 _index, windows_error_str(0));
320 pSetupDiDestroyDeviceInfoList(*dev_info);
321 *dev_info = INVALID_HANDLE_VALUE;
325 // Read interface data (dummy + actual) to access the device path
326 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
327 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
328 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
329 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
330 _index, windows_error_str(0));
334 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
338 dev_interface_details = calloc(1, size);
339 if (dev_interface_details == NULL) {
340 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
344 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
345 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
346 dev_interface_details, size, &size, NULL)) {
347 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
348 _index, windows_error_str(0));
351 return dev_interface_details;
354 pSetupDiDestroyDeviceInfoList(*dev_info);
355 *dev_info = INVALID_HANDLE_VALUE;
359 /* For libusb0 filter */
360 static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx,
361 HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index, char *filter_path)
363 SP_DEVICE_INTERFACE_DATA dev_interface_data;
364 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details;
368 *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
370 if (dev_info_data != NULL) {
371 dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
372 if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
373 if (GetLastError() != ERROR_NO_MORE_ITEMS)
374 usbi_err(ctx, "Could not obtain device info data for index %u: %s",
375 _index, windows_error_str(0));
377 pSetupDiDestroyDeviceInfoList(*dev_info);
378 *dev_info = INVALID_HANDLE_VALUE;
383 dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
384 if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
385 if (GetLastError() != ERROR_NO_MORE_ITEMS)
386 usbi_err(ctx, "Could not obtain interface data for index %u: %s",
387 _index, windows_error_str(0));
389 pSetupDiDestroyDeviceInfoList(*dev_info);
390 *dev_info = INVALID_HANDLE_VALUE;
394 // Read interface data (dummy + actual) to access the device path
395 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
396 // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
397 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
398 usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
399 _index, windows_error_str(0));
403 usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
407 dev_interface_details = calloc(1, size);
408 if (dev_interface_details == NULL) {
409 usbi_err(ctx, "could not allocate interface data for index %u.", _index);
413 dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
414 if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, dev_interface_details, size, &size, NULL))
415 usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
416 _index, windows_error_str(0));
418 // [trobinso] lookup the libusb0 symbolic index.
419 if (dev_interface_details) {
420 HKEY hkey_device_interface = pSetupDiOpenDeviceInterfaceRegKey(*dev_info, &dev_interface_data, 0, KEY_READ);
421 if (hkey_device_interface != INVALID_HANDLE_VALUE) {
422 DWORD libusb0_symboliclink_index = 0;
423 DWORD value_length = sizeof(DWORD);
424 DWORD value_type = 0;
427 status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type,
428 (LPBYTE)&libusb0_symboliclink_index, &value_length);
429 if (status == ERROR_SUCCESS) {
430 if (libusb0_symboliclink_index < 256) {
431 // libusb0.sys is connected to this device instance.
432 // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
433 sprintf(filter_path, "\\\\.\\libusb0-%04u", (unsigned int)libusb0_symboliclink_index);
434 usbi_dbg("assigned libusb0 symbolic link %s", filter_path);
436 // libusb0.sys was connected to this device instance at one time; but not anymore.
439 pRegCloseKey(hkey_device_interface);
443 return dev_interface_details;
446 pSetupDiDestroyDeviceInfoList(*dev_info);
447 *dev_info = INVALID_HANDLE_VALUE;
452 * Returns the session ID of a device's nth level ancestor
453 * If there's no device at the nth level, return 0
455 static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
457 DWORD parent_devinst;
458 unsigned long session_id;
459 char *sanitized_path;
460 char path[MAX_PATH_LENGTH];
466 for (i = 0; i < level; i++) {
467 if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS)
469 devinst = parent_devinst;
472 if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS)
475 // TODO: (post hotplug): try without sanitizing
476 sanitized_path = sanitize_path(path);
477 if (sanitized_path == NULL)
480 session_id = htab_hash(sanitized_path);
481 free(sanitized_path);
486 * Determine which interface the given endpoint address belongs to
488 static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep)
490 const struct libusb_interface *intf;
491 const struct libusb_interface_descriptor *intf_desc;
494 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
495 intf = &conf_desc->interface[i];
496 for (j = 0; j < intf->num_altsetting; j++) {
497 intf_desc = &intf->altsetting[j];
498 for (k = 0; k < intf_desc->bNumEndpoints; k++) {
499 if (intf_desc->endpoint[k].bEndpointAddress == ep) {
500 usbi_dbg("found endpoint %02X on interface %d", intf_desc->bInterfaceNumber, i);
501 return intf_desc->bInterfaceNumber;
507 usbi_dbg("endpoint %02X not found on any interface", ep);
508 return LIBUSB_ERROR_NOT_FOUND;
512 * Populate the endpoints addresses of the device_priv interface helper structs
514 static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
517 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
518 struct libusb_config_descriptor *conf_desc;
519 const struct libusb_interface_descriptor *if_desc;
520 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
522 r = libusb_get_active_config_descriptor(dev_handle->dev, &conf_desc);
523 if (r != LIBUSB_SUCCESS) {
524 usbi_warn(ctx, "could not read config descriptor: error %d", r);
528 if_desc = &conf_desc->interface[iface].altsetting[altsetting];
529 safe_free(priv->usb_interface[iface].endpoint);
531 if (if_desc->bNumEndpoints == 0) {
532 usbi_dbg("no endpoints found for interface %d", iface);
533 libusb_free_config_descriptor(conf_desc);
534 return LIBUSB_SUCCESS;
537 priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
538 if (priv->usb_interface[iface].endpoint == NULL) {
539 libusb_free_config_descriptor(conf_desc);
540 return LIBUSB_ERROR_NO_MEM;
543 priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
544 for (i = 0; i < if_desc->bNumEndpoints; i++) {
545 priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
546 usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
548 libusb_free_config_descriptor(conf_desc);
550 // Extra init may be required to configure endpoints
551 return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
554 // Lookup for a match in the list of API driver names
555 // return -1 if not found, driver match number otherwise
556 static int get_sub_api(char *driver, int api)
559 const char sep_str[2] = {LIST_SEPARATOR, 0};
561 size_t len = strlen(driver);
564 return SUB_API_NOTSET;
566 tmp_str = _strdup(driver);
568 return SUB_API_NOTSET;
570 tok = strtok(tmp_str, sep_str);
571 while (tok != NULL) {
572 for (i = 0; i < usb_api_backend[api].nb_driver_names; i++) {
573 if (_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
578 tok = strtok(NULL, sep_str);
582 return SUB_API_NOTSET;
586 * auto-claiming and auto-release helper functions
588 static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
590 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
591 struct windows_device_handle_priv *handle_priv = _device_handle_priv(
592 transfer->dev_handle);
593 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
594 int current_interface = *interface_number;
595 int r = LIBUSB_SUCCESS;
598 case USB_API_WINUSBX:
602 return LIBUSB_ERROR_INVALID_PARAM;
605 usbi_mutex_lock(&autoclaim_lock);
606 if (current_interface < 0) { // No serviceable interface was found
607 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
608 // Must claim an interface of the same API type
609 if ((priv->usb_interface[current_interface].apib->id == api_type)
610 && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS)) {
611 usbi_dbg("auto-claimed interface %d for control request", current_interface);
612 if (handle_priv->autoclaim_count[current_interface] != 0)
613 usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
614 handle_priv->autoclaim_count[current_interface]++;
618 if (current_interface == USB_MAXINTERFACES) {
619 usbi_err(ctx, "could not auto-claim any interface");
620 r = LIBUSB_ERROR_NOT_FOUND;
623 // If we have a valid interface that was autoclaimed, we must increment
624 // its autoclaim count so that we can prevent an early release.
625 if (handle_priv->autoclaim_count[current_interface] != 0)
626 handle_priv->autoclaim_count[current_interface]++;
628 usbi_mutex_unlock(&autoclaim_lock);
630 *interface_number = current_interface;
634 static void auto_release(struct usbi_transfer *itransfer)
636 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
637 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
638 libusb_device_handle *dev_handle = transfer->dev_handle;
639 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
642 usbi_mutex_lock(&autoclaim_lock);
643 if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
644 handle_priv->autoclaim_count[transfer_priv->interface_number]--;
645 if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
646 r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
647 if (r == LIBUSB_SUCCESS)
648 usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
650 usbi_dbg("failed to auto-release interface %d (%s)",
651 transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
654 usbi_mutex_unlock(&autoclaim_lock);
657 /* Windows version dtection */
658 static BOOL is_x64(void)
662 // Detect if we're running a 32 or 64 bit system
663 if (sizeof(uintptr_t) < 8) {
664 if (pIsWow64Process != NULL)
665 pIsWow64Process(GetCurrentProcess(), &ret);
673 static void get_windows_version(void)
675 OSVERSIONINFOEXA vi, vi2;
676 const char *arch, *w = NULL;
677 unsigned major, minor;
678 ULONGLONG major_equal, minor_equal;
681 memset(&vi, 0, sizeof(vi));
682 vi.dwOSVersionInfoSize = sizeof(vi);
683 if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
684 memset(&vi, 0, sizeof(vi));
685 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
686 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
690 if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
691 if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) {
692 // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
693 // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
695 major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
696 for (major = vi.dwMajorVersion; major <= 9; major++) {
697 memset(&vi2, 0, sizeof(vi2));
698 vi2.dwOSVersionInfoSize = sizeof(vi2);
699 vi2.dwMajorVersion = major;
700 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
703 if (vi.dwMajorVersion < major) {
704 vi.dwMajorVersion = major;
705 vi.dwMinorVersion = 0;
708 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
709 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
710 memset(&vi2, 0, sizeof(vi2));
711 vi2.dwOSVersionInfoSize = sizeof(vi2);
712 vi2.dwMinorVersion = minor;
713 if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
716 vi.dwMinorVersion = minor;
724 if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) {
725 ws = (vi.wProductType <= VER_NT_WORKSTATION);
726 windows_version = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
727 switch (windows_version) {
728 case 0x50: w = "2000"; break;
729 case 0x51: w = "XP"; break;
730 case 0x52: w = "2003"; break;
731 case 0x60: w = (ws ? "Vista" : "2008"); break;
732 case 0x61: w = (ws ? "7" : "2008_R2"); break;
733 case 0x62: w = (ws ? "8" : "2012"); break;
734 case 0x63: w = (ws ? "8.1" : "2012_R2"); break;
735 case 0x64: w = (ws ? "10" : "2015"); break;
737 if (windows_version < 0x50)
738 windows_version = WINDOWS_UNSUPPORTED;
746 arch = is_x64() ? "64-bit" : "32-bit";
749 usbi_dbg("Windows %s %u.%u %s", (vi.dwPlatformId == VER_PLATFORM_WIN32_NT ? "NT" : "??"),
750 (unsigned int)vi.dwMajorVersion, (unsigned int)vi.dwMinorVersion, arch);
751 else if (vi.wServicePackMinor)
752 usbi_dbg("Windows %s SP%u.%u %s", w, vi.wServicePackMajor, vi.wServicePackMinor, arch);
753 else if (vi.wServicePackMajor)
754 usbi_dbg("Windows %s SP%u %s", w, vi.wServicePackMajor, arch);
756 usbi_dbg("Windows %s %s", w, arch);
760 * init: libusb backend init function
762 * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
763 * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed.
764 * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
766 static int windows_init(struct libusb_context *ctx)
768 int i, r = LIBUSB_ERROR_OTHER;
770 char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
772 sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
773 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
774 if (semaphore == NULL) {
775 usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
776 return LIBUSB_ERROR_NO_MEM;
779 // A successful wait brings our semaphore count to 0 (unsignaled)
780 // => any concurent wait stalls until the semaphore's release
781 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
782 usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
783 CloseHandle(semaphore);
784 return LIBUSB_ERROR_NO_MEM;
787 // NB: concurrent usage supposes that init calls are equally balanced with
788 // exit calls. If init is called more than exit, we will not exit properly
789 if (++concurrent_usage == 0) { // First init?
790 get_windows_version();
792 if (windows_version == WINDOWS_UNSUPPORTED) {
793 usbi_err(ctx, "This version of Windows is NOT supported");
794 r = LIBUSB_ERROR_NOT_SUPPORTED;
798 // We need a lock for proper auto-release
799 usbi_mutex_init(&autoclaim_lock);
801 // Initialize pollable file descriptors
805 if (init_dlls() != LIBUSB_SUCCESS) {
806 usbi_err(ctx, "could not resolve DLL functions");
810 // Initialize the low level APIs (we don't care about errors at this stage)
811 for (i = 0; i < USB_API_MAX; i++)
812 usb_api_backend[i].init(SUB_API_NOTSET, ctx);
814 r = windows_common_init(ctx);
818 // At this stage, either we went through full init successfully, or didn't need to
821 init_exit: // Holds semaphore here.
822 if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
823 for (i = 0; i < USB_API_MAX; i++)
824 usb_api_backend[i].exit(SUB_API_NOTSET);
827 windows_common_exit();
828 usbi_mutex_destroy(&autoclaim_lock);
831 if (r != LIBUSB_SUCCESS)
832 --concurrent_usage; // Not expected to call libusb_exit if we failed.
834 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
835 CloseHandle(semaphore);
840 * HCD (root) hubs need to have their device descriptor manually populated
842 * Note that, like Microsoft does in the device manager, we populate the
843 * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
845 static int force_hcd_device_descriptor(struct libusb_device *dev)
847 struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
848 struct libusb_context *ctx = DEVICE_CTX(dev);
851 dev->num_configurations = 1;
852 priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
853 priv->dev_descriptor.bDescriptorType = LIBUSB_DT_DEVICE;
854 priv->dev_descriptor.bNumConfigurations = 1;
855 priv->active_config = 1;
857 if (dev->parent_dev == NULL) {
858 usbi_err(ctx, "program assertion failed - HCD hub has no parent");
859 return LIBUSB_ERROR_NO_DEVICE;
862 parent_priv = _device_priv(dev->parent_dev);
863 if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
864 priv->dev_descriptor.idVendor = (uint16_t)vid;
865 priv->dev_descriptor.idProduct = (uint16_t)pid;
867 usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
868 priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
869 priv->dev_descriptor.idProduct = 1;
872 return LIBUSB_SUCCESS;
876 * fetch and cache all the config descriptors through I/O
878 static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char *device_id)
880 DWORD size, ret_size;
881 struct libusb_context *ctx = DEVICE_CTX(dev);
882 struct windows_device_priv *priv = _device_priv(dev);
886 USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
887 PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
888 PUSB_CONFIGURATION_DESCRIPTOR cd_data;
890 if (dev->num_configurations == 0)
891 return LIBUSB_ERROR_INVALID_PARAM;
893 priv->config_descriptor = calloc(dev->num_configurations, sizeof(unsigned char *));
894 if (priv->config_descriptor == NULL)
895 return LIBUSB_ERROR_NO_MEM;
897 for (i = 0, r = LIBUSB_SUCCESS; ; i++) {
898 // safe loop: release all dynamic resources
899 safe_free(cd_buf_actual);
901 // safe loop: end of loop condition
902 if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
905 size = sizeof(cd_buf_short);
906 memset(&cd_buf_short, 0, size);
908 cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
909 cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
910 cd_buf_short.req.SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
911 cd_buf_short.req.SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
912 cd_buf_short.req.SetupPacket.wIndex = 0;
913 cd_buf_short.req.SetupPacket.wLength = (USHORT)sizeof(USB_CONFIGURATION_DESCRIPTOR);
915 // Dummy call to get the required data size. Initial failures are reported as info rather
916 // than error as they can occur for non-penalizing situations, such as with some hubs.
917 // coverity[tainted_data_argument]
918 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
919 &cd_buf_short, size, &ret_size, NULL)) {
920 usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
921 LOOP_BREAK(LIBUSB_ERROR_IO);
924 if ((ret_size != size) || (cd_buf_short.desc.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
925 usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
926 LOOP_BREAK(LIBUSB_ERROR_IO);
929 size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.desc.wTotalLength;
930 cd_buf_actual = calloc(1, size);
931 if (cd_buf_actual == NULL) {
932 usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
933 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
937 cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
938 cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
939 cd_buf_actual->SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
940 cd_buf_actual->SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
941 cd_buf_actual->SetupPacket.wIndex = 0;
942 cd_buf_actual->SetupPacket.wLength = cd_buf_short.desc.wTotalLength;
944 if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
945 cd_buf_actual, size, &ret_size, NULL)) {
946 usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
947 LOOP_BREAK(LIBUSB_ERROR_IO);
950 cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR *)cd_buf_actual + sizeof(USB_DESCRIPTOR_REQUEST));
952 if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.desc.wTotalLength)) {
953 usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
954 LOOP_BREAK(LIBUSB_ERROR_IO);
957 if (cd_data->bDescriptorType != LIBUSB_DT_CONFIG) {
958 usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
959 LOOP_BREAK(LIBUSB_ERROR_IO);
962 usbi_dbg("cached config descriptor %d (bConfigurationValue=%u, %u bytes)",
963 i, cd_data->bConfigurationValue, cd_data->wTotalLength);
965 // Cache the descriptor
966 priv->config_descriptor[i] = malloc(cd_data->wTotalLength);
967 if (priv->config_descriptor[i] == NULL)
968 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
969 memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
972 // Any failure will result in dev->num_configurations being forced to 0.
973 // We need to release any memory that may have been allocated for config
974 // descriptors that were successfully retrieved, otherwise that memory
976 if (r != LIBUSB_SUCCESS) {
977 for (i = 0; i < dev->num_configurations; i++)
978 free(priv->config_descriptor[i]);
985 * Populate a libusb device structure
987 static int init_device(struct libusb_device *dev, struct libusb_device *parent_dev,
988 uint8_t port_number, char *device_id, DWORD devinst)
992 USB_NODE_CONNECTION_INFORMATION_EX conn_info;
993 USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
994 struct windows_device_priv *priv, *parent_priv;
995 struct libusb_context *ctx;
996 struct libusb_device *tmp_dev;
997 unsigned long tmp_id;
1000 if ((dev == NULL) || (parent_dev == NULL))
1001 return LIBUSB_ERROR_NOT_FOUND;
1003 ctx = DEVICE_CTX(dev);
1004 priv = _device_priv(dev);
1005 parent_priv = _device_priv(parent_dev);
1006 if (parent_priv->apib->id != USB_API_HUB) {
1007 usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
1008 return LIBUSB_ERROR_NOT_FOUND;
1011 // It is possible for the parent hub not to have been initialized yet
1012 // If that's the case, lookup the ancestors to set the bus number
1013 if (parent_dev->bus_number == 0) {
1014 for (i = 2; ; i++) {
1015 tmp_id = get_ancestor_session_id(devinst, i);
1019 tmp_dev = usbi_get_device_by_session_id(ctx, tmp_id);
1020 if (tmp_dev == NULL)
1023 if (tmp_dev->bus_number != 0) {
1024 usbi_dbg("got bus number from ancestor #%u", i);
1025 parent_dev->bus_number = tmp_dev->bus_number;
1026 libusb_unref_device(tmp_dev);
1030 libusb_unref_device(tmp_dev);
1034 if (parent_dev->bus_number == 0) {
1035 usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
1036 return LIBUSB_ERROR_NOT_FOUND;
1039 dev->bus_number = parent_dev->bus_number;
1040 priv->port = port_number;
1041 dev->port_number = port_number;
1042 priv->depth = parent_priv->depth + 1;
1043 dev->parent_dev = parent_dev;
1045 // If the device address is already set, we can stop here
1046 if (dev->device_address != 0)
1047 return LIBUSB_SUCCESS;
1049 memset(&conn_info, 0, sizeof(conn_info));
1050 if (priv->depth != 0) { // Not a HCD hub
1051 handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1052 FILE_FLAG_OVERLAPPED, NULL);
1053 if (handle == INVALID_HANDLE_VALUE) {
1054 usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
1055 return LIBUSB_ERROR_ACCESS;
1058 size = sizeof(conn_info);
1059 conn_info.ConnectionIndex = (ULONG)port_number;
1060 // coverity[tainted_data_argument]
1061 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
1062 &conn_info, size, &size, NULL)) {
1063 usbi_warn(ctx, "could not get node connection information for device '%s': %s",
1064 device_id, windows_error_str(0));
1065 CloseHandle(handle);
1066 return LIBUSB_ERROR_NO_DEVICE;
1069 if (conn_info.ConnectionStatus == NoDeviceConnected) {
1070 usbi_err(ctx, "device '%s' is no longer connected!", device_id);
1071 CloseHandle(handle);
1072 return LIBUSB_ERROR_NO_DEVICE;
1075 memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
1076 dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
1077 priv->active_config = conn_info.CurrentConfigurationValue;
1078 usbi_dbg("found %u configurations (active conf: %u)", dev->num_configurations, priv->active_config);
1080 // If we can't read the config descriptors, just set the number of confs to zero
1081 if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
1082 dev->num_configurations = 0;
1083 priv->dev_descriptor.bNumConfigurations = 0;
1086 // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
1087 if (windows_version >= WINDOWS_8) {
1088 memset(&conn_info_v2, 0, sizeof(conn_info_v2));
1089 size = sizeof(conn_info_v2);
1090 conn_info_v2.ConnectionIndex = (ULONG)port_number;
1091 conn_info_v2.Length = size;
1092 conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
1093 if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
1094 &conn_info_v2, size, &conn_info_v2, size, &size, NULL)) {
1095 usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
1096 device_id, windows_error_str(0));
1097 } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
1098 conn_info.Speed = 3;
1102 CloseHandle(handle);
1104 if (conn_info.DeviceAddress > UINT8_MAX)
1105 usbi_err(ctx, "program assertion failed: device address overflow");
1107 dev->device_address = (uint8_t)conn_info.DeviceAddress + 1;
1108 if (dev->device_address == 1)
1109 usbi_err(ctx, "program assertion failed: device address collision with root hub");
1111 switch (conn_info.Speed) {
1112 case 0: dev->speed = LIBUSB_SPEED_LOW; break;
1113 case 1: dev->speed = LIBUSB_SPEED_FULL; break;
1114 case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
1115 case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
1117 usbi_warn(ctx, "Got unknown device speed %u", conn_info.Speed);
1121 dev->device_address = 1; // root hubs are set to use device number 1
1122 force_hcd_device_descriptor(dev);
1125 usbi_sanitize_device(dev);
1127 usbi_dbg("(bus: %u, addr: %u, depth: %u, port: %u): '%s'",
1128 dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
1130 return LIBUSB_SUCCESS;
1133 // Returns the api type, or 0 if not found/unsupported
1134 static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info,
1135 SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api)
1137 // Precedence for filter drivers vs driver is in the order of this array
1138 struct driver_lookup lookup[3] = {
1139 {"\0\0", SPDRP_SERVICE, "driver"},
1140 {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
1141 {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
1143 DWORD size, reg_type;
1147 *api = USB_API_UNSUPPORTED;
1148 *sub_api = SUB_API_NOTSET;
1150 // Check the service & filter names to know the API we should use
1151 for (k = 0; k < 3; k++) {
1152 if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
1153 ®_type, (BYTE *)lookup[k].list, MAX_KEY_LENGTH, &size)) {
1154 // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
1155 if (lookup[k].reg_prop == SPDRP_SERVICE)
1156 // our buffers are MAX_KEY_LENGTH + 1 so we can overflow if needed
1157 lookup[k].list[strlen(lookup[k].list) + 1] = 0;
1159 // MULTI_SZ is a pain to work with. Turn it into something much more manageable
1160 // NB: none of the driver names we check against contain LIST_SEPARATOR,
1161 // (currently ';'), so even if an unsuported one does, it's not an issue
1162 for (l = 0; (lookup[k].list[l] != 0) || (lookup[k].list[l + 1] != 0); l++) {
1163 if (lookup[k].list[l] == 0)
1164 lookup[k].list[l] = LIST_SEPARATOR;
1166 usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
1168 if (GetLastError() != ERROR_INVALID_DATA)
1169 usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
1170 lookup[k].list[0] = 0;
1174 for (i = 1; i < USB_API_MAX; i++) {
1175 for (k = 0; k < 3; k++) {
1176 j = get_sub_api(lookup[k].list, i);
1178 usbi_dbg("matched %s name against %s", lookup[k].designation,
1179 (i != USB_API_WINUSBX) ? usb_api_backend[i].designation : sub_api_name[j]);
1188 static int set_composite_interface(struct libusb_context *ctx, struct libusb_device *dev,
1189 char *dev_interface_path, char *device_id, int api, int sub_api)
1192 struct windows_device_priv *priv = _device_priv(dev);
1193 int interface_number;
1195 if (priv->apib->id != USB_API_COMPOSITE) {
1196 usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
1197 return LIBUSB_ERROR_NO_DEVICE;
1200 // Because MI_## are not necessarily in sequential order (some composite
1201 // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
1202 // interface number from the path's MI value
1203 interface_number = 0;
1204 for (i = 0; device_id[i] != 0; ) {
1205 if ((device_id[i++] == 'M') && (device_id[i++] == 'I')
1206 && (device_id[i++] == '_')) {
1207 interface_number = (device_id[i++] - '0') * 10;
1208 interface_number += device_id[i] - '0';
1213 if (device_id[i] == 0)
1214 usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
1215 device_id, interface_number);
1217 if (priv->usb_interface[interface_number].path != NULL) {
1218 if (api == USB_API_HID) {
1219 // HID devices can have multiple collections (COL##) for each MI_## interface
1220 usbi_dbg("interface[%d] already set - ignoring HID collection: %s",
1221 interface_number, device_id);
1222 return LIBUSB_ERROR_ACCESS;
1224 // In other cases, just use the latest data
1225 safe_free(priv->usb_interface[interface_number].path);
1228 usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
1229 priv->usb_interface[interface_number].path = dev_interface_path;
1230 priv->usb_interface[interface_number].apib = &usb_api_backend[api];
1231 priv->usb_interface[interface_number].sub_api = sub_api;
1232 if ((api == USB_API_HID) && (priv->hid == NULL)) {
1233 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1234 if (priv->hid == NULL)
1235 return LIBUSB_ERROR_NO_MEM;
1238 return LIBUSB_SUCCESS;
1241 static int set_hid_interface(struct libusb_context *ctx, struct libusb_device *dev,
1242 char *dev_interface_path)
1245 struct windows_device_priv *priv = _device_priv(dev);
1247 if (priv->hid == NULL) {
1248 usbi_err(ctx, "program assertion failed: parent is not HID");
1249 return LIBUSB_ERROR_NO_DEVICE;
1250 } else if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
1251 usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device");
1252 return LIBUSB_ERROR_NO_DEVICE;
1255 for (i = 0; i < priv->hid->nb_interfaces; i++) {
1256 if ((priv->usb_interface[i].path != NULL) && strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
1257 usbi_dbg("interface[%d] already set to %s", i, dev_interface_path);
1258 return LIBUSB_ERROR_ACCESS;
1262 priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
1263 priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
1264 usbi_dbg("interface[%u] = %s", priv->hid->nb_interfaces, dev_interface_path);
1265 priv->hid->nb_interfaces++;
1266 return LIBUSB_SUCCESS;
1270 * get_device_list: libusb backend device enumeration function
1272 static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
1274 struct discovered_devs *discdevs;
1275 HDEVINFO dev_info = { 0 };
1276 const char *usb_class[] = {"USB", "NUSB3", "IUSB3", "IARUSB3"};
1277 SP_DEVINFO_DATA dev_info_data = { 0 };
1278 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
1280 #define MAX_ENUM_GUIDS 64
1281 const GUID *guid[MAX_ENUM_GUIDS];
1287 int r = LIBUSB_SUCCESS;
1289 size_t class_index = 0;
1290 unsigned int nb_guids, pass, i, j, ancestor;
1291 char path[MAX_PATH_LENGTH];
1292 char strbuf[MAX_PATH_LENGTH];
1293 struct libusb_device *dev, *parent_dev;
1294 struct windows_device_priv *priv, *parent_priv;
1295 char *dev_interface_path = NULL;
1296 char *dev_id_path = NULL;
1297 unsigned long session_id;
1298 DWORD size, reg_type, port_nr, install_state;
1300 WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
1303 // Keep a list of newly allocated devs to unref
1304 libusb_device **unref_list, **new_unref_list;
1305 unsigned int unref_size = 64;
1306 unsigned int unref_cur = 0;
1308 // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
1309 // PASS 2 : (re)enumerate HUBS
1310 // PASS 3 : (re)enumerate generic USB devices (including driverless)
1311 // and list additional USB device interface GUIDs to explore
1312 // PASS 4 : (re)enumerate master USB devices that have a device interface
1313 // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
1314 // set the device interfaces.
1316 // Init the GUID table
1317 guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
1318 guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
1319 guid[GEN_PASS] = NULL;
1320 guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
1321 HidD_GetHidGuid(&hid_guid);
1322 guid[HID_PASS] = &hid_guid;
1323 nb_guids = HID_PASS + 1;
1325 unref_list = calloc(unref_size, sizeof(libusb_device *));
1326 if (unref_list == NULL)
1327 return LIBUSB_ERROR_NO_MEM;
1329 for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
1330 //#define ENUM_DEBUG
1331 #if defined(ENABLE_LOGGING) && defined(ENUM_DEBUG)
1332 const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" };
1333 usbi_dbg("#### PROCESSING %ss %s", passname[(pass <= HID_PASS) ? pass : (HID_PASS + 1)],
1334 (pass != GEN_PASS) ? guid_to_string(guid[pass]) : "");
1336 for (i = 0; ; i++) {
1337 // safe loop: free up any (unprotected) dynamic resource
1338 // NB: this is always executed before breaking the loop
1339 safe_free(dev_interface_details);
1340 safe_free(dev_interface_path);
1341 safe_free(dev_id_path);
1342 priv = parent_priv = NULL;
1343 dev = parent_dev = NULL;
1345 // Safe loop: end of loop conditions
1346 if (r != LIBUSB_SUCCESS)
1349 if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
1350 usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
1354 if (pass != GEN_PASS) {
1355 // Except for GEN, all passes deal with device interfaces
1356 dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
1357 if (dev_interface_details == NULL)
1360 dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
1361 if (dev_interface_path == NULL) {
1362 usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
1366 // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
1367 // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
1368 // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
1369 // The Intel Alpine Ridge USB 3.1 driver uses "IARUSB3"
1370 for (; class_index < ARRAYSIZE(usb_class); class_index++) {
1371 if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))
1375 if (class_index >= ARRAYSIZE(usb_class))
1379 // Read the Device ID path. This is what we'll use as UID
1380 // Note that if the device is plugged in a different port or hub, the Device ID changes
1381 if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
1382 usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
1383 (unsigned int)dev_info_data.DevInst);
1387 dev_id_path = sanitize_path(path);
1388 if (dev_id_path == NULL) {
1389 usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
1390 (unsigned int)dev_info_data.DevInst);
1394 usbi_dbg("PRO: %s", dev_id_path);
1397 // The SPDRP_ADDRESS for USB devices is the device port number on the hub
1399 if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
1400 if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
1401 ®_type, (BYTE *)&port_nr, 4, &size)) || (size != 4)) {
1402 usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
1403 dev_id_path, windows_error_str(0));
1408 // Set API to use or get additional data from generic pass
1409 api = USB_API_UNSUPPORTED;
1410 sub_api = SUB_API_NOTSET;
1415 // We use the GEN pass to detect driverless devices...
1416 size = sizeof(strbuf);
1417 if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
1418 ®_type, (BYTE *)strbuf, size, &size)) {
1419 usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
1420 usbi_info(ctx, "libusb will not be able to access it.");
1422 // ...and to add the additional device interface GUIDs
1423 key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
1424 if (key != INVALID_HANDLE_VALUE) {
1425 size = sizeof(guid_string_w);
1426 s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type,
1427 (BYTE *)guid_string_w, &size);
1429 if (s == ERROR_SUCCESS) {
1430 if (nb_guids >= MAX_ENUM_GUIDS) {
1431 // If this assert is ever reported, grow a GUID table dynamically
1432 usbi_err(ctx, "program assertion failed: too many GUIDs");
1433 LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
1435 if_guid = calloc(1, sizeof(GUID));
1436 if (if_guid == NULL) {
1437 usbi_err(ctx, "could not calloc for if_guid: not enough memory");
1438 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1440 pCLSIDFromString(guid_string_w, if_guid);
1441 guid[nb_guids++] = if_guid;
1442 usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
1450 // Get the API type (after checking that the driver installation is OK)
1451 if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
1452 ®_type, (BYTE *)&install_state, 4, &size)) || (size != 4)) {
1453 usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
1454 dev_id_path, windows_error_str(0));
1455 } else if (install_state != 0) {
1456 usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %u) - skipping",
1457 dev_id_path, (unsigned int)install_state);
1460 get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api);
1464 // Find parent device (for the passes that need it)
1471 // Go through the ancestors until we see a face we recognize
1473 for (ancestor = 1; parent_dev == NULL; ancestor++) {
1474 session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
1475 if (session_id == 0)
1478 parent_dev = usbi_get_device_by_session_id(ctx, session_id);
1481 if (parent_dev == NULL) {
1482 usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path);
1486 parent_priv = _device_priv(parent_dev);
1487 // virtual USB devices are also listed during GEN - don't process these yet
1488 if ((pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB)) {
1489 libusb_unref_device(parent_dev);
1496 // Create new or match existing device, using the (hashed) device_id as session id
1497 if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
1498 // These are the passes that create "new" devices
1499 session_id = htab_hash(dev_id_path);
1500 dev = usbi_get_device_by_session_id(ctx, session_id);
1502 if (pass == DEV_PASS) {
1503 // This can occur if the OS only reports a newly plugged device after we started enum
1504 usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
1505 " - ignoring", dev_id_path);
1509 usbi_dbg("allocating new device for session [%lX]", session_id);
1510 dev = usbi_alloc_device(ctx, session_id);
1512 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1514 priv = windows_device_priv_init(dev);
1516 usbi_dbg("found existing device for session [%lX] (%u.%u)",
1517 session_id, dev->bus_number, dev->device_address);
1519 priv = _device_priv(dev);
1520 if ((parent_dev != NULL) && (dev->parent_dev != NULL)) {
1521 if (dev->parent_dev != parent_dev) {
1522 // It is possible for the actual parent device to not have existed at the
1523 // time of enumeration, so the currently assigned parent may in fact be a
1524 // grandparent. If the devices differ, we assume the "new" parent device
1525 // is in fact closer to the device.
1526 usbi_dbg("updating parent device [session %lX -> %lX]",
1527 dev->parent_dev->session_data, parent_dev->session_data);
1528 libusb_unref_device(dev->parent_dev);
1529 dev->parent_dev = parent_dev;
1531 // We hold a reference to parent_dev instance, but this device already
1532 // has a parent_dev reference (only one per child)
1533 libusb_unref_device(parent_dev);
1538 // Keep track of devices that need unref
1539 unref_list[unref_cur++] = dev;
1540 if (unref_cur >= unref_size) {
1542 new_unref_list = usbi_reallocf(unref_list, unref_size * sizeof(libusb_device *));
1543 if (new_unref_list == NULL) {
1544 usbi_err(ctx, "could not realloc list for unref - aborting.");
1545 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1547 unref_list = new_unref_list;
1555 // If the hcd has already been setup, don't do it again
1556 if (priv->path != NULL)
1558 dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
1559 dev->device_address = 0;
1560 dev->num_configurations = 0;
1561 priv->apib = &usb_api_backend[USB_API_HUB];
1562 priv->sub_api = SUB_API_NOTSET;
1563 priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
1564 priv->path = dev_interface_path;
1565 dev_interface_path = NULL;
1569 // If the device has already been setup, don't do it again
1570 if (priv->path != NULL)
1572 // Take care of API initialization
1573 priv->path = dev_interface_path;
1574 dev_interface_path = NULL;
1575 priv->apib = &usb_api_backend[api];
1576 priv->sub_api = sub_api;
1578 case USB_API_COMPOSITE:
1582 priv->hid = calloc(1, sizeof(struct hid_device_priv));
1583 if (priv->hid == NULL)
1584 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1586 priv->hid->nb_interfaces = 0;
1589 // For other devices, the first interface is the same as the device
1590 priv->usb_interface[0].path = _strdup(priv->path);
1591 if (priv->usb_interface[0].path == NULL)
1592 usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
1593 // The following is needed if we want API calls to work for both simple
1594 // and composite devices.
1595 for (j = 0; j < USB_MAXINTERFACES; j++)
1596 priv->usb_interface[j].apib = &usb_api_backend[api];
1602 r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
1603 if (r == LIBUSB_SUCCESS) {
1604 // Append device to the list of discovered devices
1605 discdevs = discovered_devs_append(*_discdevs, dev);
1607 LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
1609 *_discdevs = discdevs;
1610 } else if (r == LIBUSB_ERROR_NO_DEVICE) {
1611 // This can occur if the device was disconnected but Windows hasn't
1612 // refreshed its enumeration yet - in that case, we ignore the device
1616 default: // HID_PASS and later
1617 if (parent_priv->apib->id == USB_API_HID || parent_priv->apib->id == USB_API_COMPOSITE) {
1618 if (parent_priv->apib->id == USB_API_HID) {
1619 usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data);
1620 r = set_hid_interface(ctx, parent_dev, dev_interface_path);
1622 usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
1623 r = set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api);
1626 case LIBUSB_SUCCESS:
1627 dev_interface_path = NULL;
1629 case LIBUSB_ERROR_ACCESS:
1630 // interface has already been set => make sure dev_interface_path is freed then
1638 libusb_unref_device(parent_dev);
1644 // Free any additional GUIDs
1645 for (pass = HID_PASS + 1; pass < nb_guids; pass++)
1646 free((void *)guid[pass]);
1648 // Unref newly allocated devs
1649 for (i = 0; i < unref_cur; i++)
1650 libusb_unref_device(unref_list[i]);
1657 * exit: libusb backend deinitialization function
1659 static void windows_exit(struct libusb_context *ctx)
1663 char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0'
1666 sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF));
1667 semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
1668 if (semaphore == NULL)
1671 // A successful wait brings our semaphore count to 0 (unsignaled)
1672 // => any concurent wait stalls until the semaphore release
1673 if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
1674 CloseHandle(semaphore);
1678 // Only works if exits and inits are balanced exactly
1679 if (--concurrent_usage < 0) { // Last exit
1680 for (i = 0; i < USB_API_MAX; i++)
1681 usb_api_backend[i].exit(SUB_API_NOTSET);
1684 windows_common_exit();
1685 usbi_mutex_destroy(&autoclaim_lock);
1688 ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
1689 CloseHandle(semaphore);
1692 static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
1694 struct windows_device_priv *priv = _device_priv(dev);
1696 memcpy(buffer, &priv->dev_descriptor, DEVICE_DESC_LENGTH);
1699 return LIBUSB_SUCCESS;
1702 static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
1704 struct windows_device_priv *priv = _device_priv(dev);
1705 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1708 // config index is zero based
1709 if (config_index >= dev->num_configurations)
1710 return LIBUSB_ERROR_INVALID_PARAM;
1712 if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
1713 return LIBUSB_ERROR_NOT_FOUND;
1715 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
1717 size = MIN(config_header->wTotalLength, len);
1718 memcpy(buffer, priv->config_descriptor[config_index], size);
1724 static int windows_get_config_descriptor_by_value(struct libusb_device *dev, uint8_t bConfigurationValue,
1725 unsigned char **buffer, int *host_endian)
1727 struct windows_device_priv *priv = _device_priv(dev);
1728 PUSB_CONFIGURATION_DESCRIPTOR config_header;
1734 if (priv->config_descriptor == NULL)
1735 return LIBUSB_ERROR_NOT_FOUND;
1737 for (index = 0; index < dev->num_configurations; index++) {
1738 config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[index];
1739 if (config_header->bConfigurationValue == bConfigurationValue) {
1740 *buffer = priv->config_descriptor[index];
1741 return (int)config_header->wTotalLength;
1745 return LIBUSB_ERROR_NOT_FOUND;
1749 * return the cached copy of the active config descriptor
1751 static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
1753 struct windows_device_priv *priv = _device_priv(dev);
1754 unsigned char *config_desc;
1757 if (priv->active_config == 0)
1758 return LIBUSB_ERROR_NOT_FOUND;
1760 r = windows_get_config_descriptor_by_value(dev, priv->active_config, &config_desc, host_endian);
1764 len = MIN((size_t)r, len);
1765 memcpy(buffer, config_desc, len);
1769 static int windows_open(struct libusb_device_handle *dev_handle)
1771 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1772 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
1774 if (priv->apib == NULL) {
1775 usbi_err(ctx, "program assertion failed - device is not initialized");
1776 return LIBUSB_ERROR_NO_DEVICE;
1779 return priv->apib->open(SUB_API_NOTSET, dev_handle);
1782 static void windows_close(struct libusb_device_handle *dev_handle)
1784 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1786 priv->apib->close(SUB_API_NOTSET, dev_handle);
1789 static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
1791 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1793 if (priv->active_config == 0) {
1795 return LIBUSB_ERROR_NOT_FOUND;
1798 *config = priv->active_config;
1799 return LIBUSB_SUCCESS;
1803 * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
1804 * does not currently expose a service that allows higher-level drivers to set
1805 * the configuration."
1807 static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
1809 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1810 int r = LIBUSB_SUCCESS;
1812 if (config >= USB_MAXCONFIG)
1813 return LIBUSB_ERROR_INVALID_PARAM;
1815 r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
1816 LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
1817 LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
1820 if (r == LIBUSB_SUCCESS)
1821 priv->active_config = (uint8_t)config;
1826 static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
1828 int r = LIBUSB_SUCCESS;
1829 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1831 safe_free(priv->usb_interface[iface].endpoint);
1832 priv->usb_interface[iface].nb_endpoints = 0;
1834 r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
1836 if (r == LIBUSB_SUCCESS)
1837 r = windows_assign_endpoints(dev_handle, iface, 0);
1842 static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
1844 int r = LIBUSB_SUCCESS;
1845 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1847 safe_free(priv->usb_interface[iface].endpoint);
1848 priv->usb_interface[iface].nb_endpoints = 0;
1850 r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
1852 if (r == LIBUSB_SUCCESS)
1853 r = windows_assign_endpoints(dev_handle, iface, altsetting);
1858 static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
1860 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1862 return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
1865 static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
1867 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1868 return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
1871 static int windows_reset_device(struct libusb_device_handle *dev_handle)
1873 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
1874 return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
1877 // The 3 functions below are unlikely to ever get supported on Windows
1878 static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
1880 return LIBUSB_ERROR_NOT_SUPPORTED;
1883 static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1885 return LIBUSB_ERROR_NOT_SUPPORTED;
1888 static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
1890 return LIBUSB_ERROR_NOT_SUPPORTED;
1893 static void windows_destroy_device(struct libusb_device *dev)
1895 windows_device_priv_release(dev);
1898 void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
1900 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1902 usbi_free_fd(&transfer_priv->pollable_fd);
1903 safe_free(transfer_priv->hid_buffer);
1904 // When auto claim is in use, attempt to release the auto-claimed interface
1905 auto_release(itransfer);
1908 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1910 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1911 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1912 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1913 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1916 r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer);
1917 if (r != LIBUSB_SUCCESS)
1920 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1921 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1923 return LIBUSB_SUCCESS;
1926 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1928 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1929 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1930 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1931 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1934 r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer);
1935 if (r != LIBUSB_SUCCESS)
1938 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
1939 (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
1941 return LIBUSB_SUCCESS;
1944 static int submit_control_transfer(struct usbi_transfer *itransfer)
1946 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1947 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
1948 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
1949 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1952 r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer);
1953 if (r != LIBUSB_SUCCESS)
1956 usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
1958 return LIBUSB_SUCCESS;
1961 static int windows_submit_transfer(struct usbi_transfer *itransfer)
1963 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1965 switch (transfer->type) {
1966 case LIBUSB_TRANSFER_TYPE_CONTROL:
1967 return submit_control_transfer(itransfer);
1968 case LIBUSB_TRANSFER_TYPE_BULK:
1969 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1970 if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1971 return LIBUSB_ERROR_NOT_SUPPORTED;
1972 return submit_bulk_transfer(itransfer);
1973 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1974 return submit_iso_transfer(itransfer);
1975 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1976 return LIBUSB_ERROR_NOT_SUPPORTED;
1978 usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
1979 return LIBUSB_ERROR_INVALID_PARAM;
1983 static int windows_abort_control(struct usbi_transfer *itransfer)
1985 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1986 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1988 return priv->apib->abort_control(SUB_API_NOTSET, itransfer);
1991 static int windows_abort_transfers(struct usbi_transfer *itransfer)
1993 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1994 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
1996 return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer);
1999 static int windows_cancel_transfer(struct usbi_transfer *itransfer)
2001 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2003 switch (transfer->type) {
2004 case LIBUSB_TRANSFER_TYPE_CONTROL:
2005 return windows_abort_control(itransfer);
2006 case LIBUSB_TRANSFER_TYPE_BULK:
2007 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2008 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2009 return windows_abort_transfers(itransfer);
2010 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2011 return LIBUSB_ERROR_NOT_SUPPORTED;
2013 usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
2014 return LIBUSB_ERROR_INVALID_PARAM;
2018 int windows_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
2020 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2021 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2022 return priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size);
2025 struct winfd *windows_get_fd(struct usbi_transfer *transfer)
2027 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(transfer);
2028 return &transfer_priv->pollable_fd;
2031 void windows_get_overlapped_result(struct usbi_transfer *transfer, struct winfd *pollable_fd, DWORD *io_result, DWORD *io_size)
2033 if (HasOverlappedIoCompletedSync(pollable_fd->overlapped)) {
2034 *io_result = NO_ERROR;
2035 *io_size = (DWORD)pollable_fd->overlapped->InternalHigh;
2036 } else if (GetOverlappedResult(pollable_fd->handle, pollable_fd->overlapped, io_size, false)) {
2037 // Regular async overlapped
2038 *io_result = NO_ERROR;
2040 *io_result = GetLastError();
2044 // NB: MSVC6 does not support named initializers.
2045 const struct usbi_os_backend usbi_backend = {
2047 USBI_CAP_HAS_HID_ACCESS,
2050 NULL, /* set_option */
2052 windows_get_device_list,
2053 NULL, /* hotplug_poll */
2057 windows_get_device_descriptor,
2058 windows_get_active_config_descriptor,
2059 windows_get_config_descriptor,
2060 windows_get_config_descriptor_by_value,
2062 windows_get_configuration,
2063 windows_set_configuration,
2064 windows_claim_interface,
2065 windows_release_interface,
2067 windows_set_interface_altsetting,
2069 windows_reset_device,
2071 NULL, /* alloc_streams */
2072 NULL, /* free_streams */
2074 NULL, /* dev_mem_alloc */
2075 NULL, /* dev_mem_free */
2077 windows_kernel_driver_active,
2078 windows_detach_kernel_driver,
2079 windows_attach_kernel_driver,
2081 windows_destroy_device,
2083 windows_submit_transfer,
2084 windows_cancel_transfer,
2085 windows_clear_transfer_priv,
2087 windows_handle_events,
2090 windows_clock_gettime,
2091 #if defined(USBI_TIMERFD_AVAILABLE)
2095 sizeof(struct windows_device_priv),
2096 sizeof(struct windows_device_handle_priv),
2097 sizeof(struct windows_transfer_priv),
2104 static int unsupported_init(int sub_api, struct libusb_context *ctx)
2106 return LIBUSB_SUCCESS;
2109 static int unsupported_exit(int sub_api)
2111 return LIBUSB_SUCCESS;
2114 static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle)
2116 PRINT_UNSUPPORTED_API(open);
2119 static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle)
2121 usbi_dbg("unsupported API call for 'close'");
2124 static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2126 PRINT_UNSUPPORTED_API(configure_endpoints);
2129 static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2131 PRINT_UNSUPPORTED_API(claim_interface);
2134 static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2136 PRINT_UNSUPPORTED_API(set_interface_altsetting);
2139 static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2141 PRINT_UNSUPPORTED_API(release_interface);
2144 static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2146 PRINT_UNSUPPORTED_API(clear_halt);
2149 static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2151 PRINT_UNSUPPORTED_API(reset_device);
2154 static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2156 PRINT_UNSUPPORTED_API(submit_bulk_transfer);
2159 static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
2161 PRINT_UNSUPPORTED_API(submit_iso_transfer);
2164 static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2166 PRINT_UNSUPPORTED_API(submit_control_transfer);
2169 static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer)
2171 PRINT_UNSUPPORTED_API(abort_control);
2174 static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2176 PRINT_UNSUPPORTED_API(abort_transfers);
2179 static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2181 PRINT_UNSUPPORTED_API(copy_transfer_data);
2184 static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2186 return LIBUSB_SUCCESS;
2189 // These names must be uppercase
2190 static const char *hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30", "VHHUB", "AUSB3HUB"};
2191 static const char *composite_driver_names[] = {"USBCCGP"};
2192 static const char *winusbx_driver_names[] = WINUSBX_DRV_NAMES;
2193 static const char *hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
2194 const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
2196 USB_API_UNSUPPORTED,
2204 unsupported_configure_endpoints,
2205 unsupported_claim_interface,
2206 unsupported_set_interface_altsetting,
2207 unsupported_release_interface,
2208 unsupported_clear_halt,
2209 unsupported_reset_device,
2210 unsupported_submit_bulk_transfer,
2211 unsupported_submit_iso_transfer,
2212 unsupported_submit_control_transfer,
2213 unsupported_abort_control,
2214 unsupported_abort_transfers,
2215 unsupported_copy_transfer_data,
2221 ARRAYSIZE(hub_driver_names),
2226 unsupported_configure_endpoints,
2227 unsupported_claim_interface,
2228 unsupported_set_interface_altsetting,
2229 unsupported_release_interface,
2230 unsupported_clear_halt,
2231 unsupported_reset_device,
2232 unsupported_submit_bulk_transfer,
2233 unsupported_submit_iso_transfer,
2234 unsupported_submit_control_transfer,
2235 unsupported_abort_control,
2236 unsupported_abort_transfers,
2237 unsupported_copy_transfer_data,
2242 composite_driver_names,
2243 ARRAYSIZE(composite_driver_names),
2248 common_configure_endpoints,
2249 composite_claim_interface,
2250 composite_set_interface_altsetting,
2251 composite_release_interface,
2252 composite_clear_halt,
2253 composite_reset_device,
2254 composite_submit_bulk_transfer,
2255 composite_submit_iso_transfer,
2256 composite_submit_control_transfer,
2257 composite_abort_control,
2258 composite_abort_transfers,
2259 composite_copy_transfer_data,
2264 winusbx_driver_names,
2265 ARRAYSIZE(winusbx_driver_names),
2270 winusbx_configure_endpoints,
2271 winusbx_claim_interface,
2272 winusbx_set_interface_altsetting,
2273 winusbx_release_interface,
2275 winusbx_reset_device,
2276 winusbx_submit_bulk_transfer,
2277 unsupported_submit_iso_transfer,
2278 winusbx_submit_control_transfer,
2279 winusbx_abort_control,
2280 winusbx_abort_transfers,
2281 winusbx_copy_transfer_data,
2287 ARRAYSIZE(hid_driver_names),
2292 common_configure_endpoints,
2293 hid_claim_interface,
2294 hid_set_interface_altsetting,
2295 hid_release_interface,
2298 hid_submit_bulk_transfer,
2299 unsupported_submit_iso_transfer,
2300 hid_submit_control_transfer,
2301 hid_abort_transfers,
2302 hid_abort_transfers,
2303 hid_copy_transfer_data,
2309 * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
2311 #define WinUSBX_Set(fn) \
2313 if (native_winusb) \
2314 WinUSBX[i].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \
2316 pLibK_GetProcAddress((PVOID *)&WinUSBX[i].fn, i, KUSB_FNID_##fn); \
2319 static int winusbx_init(int sub_api, struct libusb_context *ctx)
2324 KLIB_VERSION LibK_Version;
2325 LibK_GetProcAddress_t pLibK_GetProcAddress = NULL;
2326 LibK_GetVersion_t pLibK_GetVersion;
2328 h = LoadLibraryA("libusbK");
2331 usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB");
2332 h = LoadLibraryA("WinUSB");
2335 usbi_warn(ctx, "WinUSB DLL is not available either, "
2336 "you will not be able to access devices outside of enumeration");
2337 return LIBUSB_ERROR_NOT_FOUND;
2340 usbi_dbg("using libusbK DLL for universal access");
2341 pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(h, "LibK_GetVersion");
2342 if (pLibK_GetVersion != NULL) {
2343 pLibK_GetVersion(&LibK_Version);
2344 usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
2345 LibK_Version.Micro, LibK_Version.Nano);
2347 pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(h, "LibK_GetProcAddress");
2348 if (pLibK_GetProcAddress == NULL) {
2349 usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
2351 return LIBUSB_ERROR_NOT_FOUND;
2355 native_winusb = (pLibK_GetProcAddress == NULL);
2356 for (i = SUB_API_LIBUSBK; i < SUB_API_MAX; i++) {
2357 WinUSBX_Set(AbortPipe);
2358 WinUSBX_Set(ControlTransfer);
2359 WinUSBX_Set(FlushPipe);
2361 WinUSBX_Set(GetAssociatedInterface);
2362 WinUSBX_Set(GetCurrentAlternateSetting);
2363 WinUSBX_Set(GetDescriptor);
2364 WinUSBX_Set(GetOverlappedResult);
2365 WinUSBX_Set(GetPipePolicy);
2366 WinUSBX_Set(GetPowerPolicy);
2367 WinUSBX_Set(Initialize);
2368 WinUSBX_Set(QueryDeviceInformation);
2369 WinUSBX_Set(QueryInterfaceSettings);
2370 WinUSBX_Set(QueryPipe);
2371 WinUSBX_Set(ReadPipe);
2372 WinUSBX_Set(ResetPipe);
2373 WinUSBX_Set(SetCurrentAlternateSetting);
2374 WinUSBX_Set(SetPipePolicy);
2375 WinUSBX_Set(SetPowerPolicy);
2376 WinUSBX_Set(WritePipe);
2378 WinUSBX_Set(ResetDevice);
2380 if (WinUSBX[i].Initialize != NULL) {
2381 WinUSBX[i].initialized = true;
2382 usbi_dbg("initalized sub API %s", sub_api_name[i]);
2384 usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]);
2385 WinUSBX[i].initialized = false;
2390 return LIBUSB_SUCCESS;
2393 static int winusbx_exit(int sub_api)
2395 if (WinUSBX_handle != NULL) {
2396 FreeLibrary(WinUSBX_handle);
2397 WinUSBX_handle = NULL;
2399 /* Reset the WinUSBX API structures */
2400 memset(&WinUSBX, 0, sizeof(WinUSBX));
2403 return LIBUSB_SUCCESS;
2406 // NB: open and close must ensure that they only handle interface of
2407 // the right API type, as these functions can be called wholesale from
2408 // composite_open(), with interfaces belonging to different APIs
2409 static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
2411 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2412 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2413 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2418 CHECK_WINUSBX_AVAILABLE(sub_api);
2420 // WinUSB requires a separate handle for each interface
2421 for (i = 0; i < USB_MAXINTERFACES; i++) {
2422 if ((priv->usb_interface[i].path != NULL)
2423 && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
2424 file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2425 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2426 if (file_handle == INVALID_HANDLE_VALUE) {
2427 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
2428 switch(GetLastError()) {
2429 case ERROR_FILE_NOT_FOUND: // The device was disconnected
2430 return LIBUSB_ERROR_NO_DEVICE;
2431 case ERROR_ACCESS_DENIED:
2432 return LIBUSB_ERROR_ACCESS;
2434 return LIBUSB_ERROR_IO;
2437 handle_priv->interface_handle[i].dev_handle = file_handle;
2441 return LIBUSB_SUCCESS;
2444 static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
2446 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2447 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2451 if (sub_api == SUB_API_NOTSET)
2452 sub_api = priv->sub_api;
2454 if (!WinUSBX[sub_api].initialized)
2457 if (priv->apib->id == USB_API_COMPOSITE) {
2458 // If this is a composite device, just free and close all WinUSB-like
2459 // interfaces directly (each is independent and not associated with another)
2460 for (i = 0; i < USB_MAXINTERFACES; i++) {
2461 if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
2462 handle = handle_priv->interface_handle[i].api_handle;
2463 if (HANDLE_VALID(handle))
2464 WinUSBX[sub_api].Free(handle);
2466 handle = handle_priv->interface_handle[i].dev_handle;
2467 if (HANDLE_VALID(handle))
2468 CloseHandle(handle);
2472 // If this is a WinUSB device, free all interfaces above interface 0,
2473 // then free and close interface 0 last
2474 for (i = 1; i < USB_MAXINTERFACES; i++) {
2475 handle = handle_priv->interface_handle[i].api_handle;
2476 if (HANDLE_VALID(handle))
2477 WinUSBX[sub_api].Free(handle);
2479 handle = handle_priv->interface_handle[0].api_handle;
2480 if (HANDLE_VALID(handle))
2481 WinUSBX[sub_api].Free(handle);
2483 handle = handle_priv->interface_handle[0].dev_handle;
2484 if (HANDLE_VALID(handle))
2485 CloseHandle(handle);
2489 static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2491 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2492 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2493 HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
2496 uint8_t endpoint_address;
2499 CHECK_WINUSBX_AVAILABLE(sub_api);
2501 // With handle and enpoints set (in parent), we can setup the default pipe properties
2502 // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
2503 for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
2504 endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
2505 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2506 PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
2507 usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
2509 if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
2510 continue; // Other policies don't apply to control endpoint or libusb0
2513 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2514 SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
2515 usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
2517 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2518 IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
2519 usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
2522 /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
2523 https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
2524 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2525 ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
2526 usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
2528 if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
2529 AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
2530 usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
2533 return LIBUSB_SUCCESS;
2536 static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2538 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2539 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2540 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2541 bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
2542 SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
2543 HDEVINFO dev_info = INVALID_HANDLE_VALUE;
2544 SP_DEVINFO_DATA dev_info_data;
2545 char *dev_path_no_guid = NULL;
2546 char filter_path[] = "\\\\.\\libusb0-0000";
2547 bool found_filter = false;
2548 HANDLE file_handle, winusb_handle;
2552 CHECK_WINUSBX_AVAILABLE(sub_api);
2554 // If the device is composite, but using the default Windows composite parent driver (usbccgp)
2555 // or if it's the first WinUSB-like interface, we get a handle through Initialize().
2556 if ((is_using_usbccgp) || (iface == 0)) {
2557 // composite device (independent interfaces) or interface 0
2558 file_handle = handle_priv->interface_handle[iface].dev_handle;
2559 if (!HANDLE_VALID(file_handle))
2560 return LIBUSB_ERROR_NOT_FOUND;
2562 if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2563 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2564 err = GetLastError();
2566 case ERROR_BAD_COMMAND:
2567 // The device was disconnected
2568 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
2569 return LIBUSB_ERROR_NO_DEVICE;
2571 // it may be that we're using the libusb0 filter driver.
2572 // TODO: can we move this whole business into the K/0 DLL?
2573 for (i = 0; ; i++) {
2574 safe_free(dev_interface_details);
2575 safe_free(dev_path_no_guid);
2577 dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path);
2578 if ((found_filter) || (dev_interface_details == NULL))
2582 dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{"));
2583 if (dev_path_no_guid == NULL)
2586 if (strncmp(dev_path_no_guid, priv->usb_interface[iface].path, strlen(dev_path_no_guid)) == 0) {
2587 file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
2588 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
2589 if (file_handle != INVALID_HANDLE_VALUE) {
2590 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2591 // Replace the existing file handle with the working one
2592 CloseHandle(handle_priv->interface_handle[iface].dev_handle);
2593 handle_priv->interface_handle[iface].dev_handle = file_handle;
2594 found_filter = true;
2596 usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
2597 CloseHandle(file_handle);
2600 usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
2604 free(dev_interface_details);
2605 if (!found_filter) {
2606 usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err));
2607 return LIBUSB_ERROR_ACCESS;
2611 handle_priv->interface_handle[iface].api_handle = winusb_handle;
2613 // For all other interfaces, use GetAssociatedInterface()
2614 winusb_handle = handle_priv->interface_handle[0].api_handle;
2615 // It is a requirement for multiple interface devices on Windows that, to you
2616 // must first claim the first interface before you claim the others
2617 if (!HANDLE_VALID(winusb_handle)) {
2618 file_handle = handle_priv->interface_handle[0].dev_handle;
2619 if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
2620 handle_priv->interface_handle[0].api_handle = winusb_handle;
2621 usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
2623 usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0));
2624 return LIBUSB_ERROR_ACCESS;
2627 if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
2628 &handle_priv->interface_handle[iface].api_handle)) {
2629 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2630 switch(GetLastError()) {
2631 case ERROR_NO_MORE_ITEMS: // invalid iface
2632 return LIBUSB_ERROR_NOT_FOUND;
2633 case ERROR_BAD_COMMAND: // The device was disconnected
2634 return LIBUSB_ERROR_NO_DEVICE;
2635 case ERROR_ALREADY_EXISTS: // already claimed
2636 return LIBUSB_ERROR_BUSY;
2638 usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
2639 return LIBUSB_ERROR_ACCESS;
2643 usbi_dbg("claimed interface %d", iface);
2644 handle_priv->active_interface = iface;
2646 return LIBUSB_SUCCESS;
2649 static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
2651 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2652 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2653 HANDLE winusb_handle;
2655 CHECK_WINUSBX_AVAILABLE(sub_api);
2657 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2658 if (!HANDLE_VALID(winusb_handle))
2659 return LIBUSB_ERROR_NOT_FOUND;
2661 WinUSBX[sub_api].Free(winusb_handle);
2662 handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
2664 return LIBUSB_SUCCESS;
2668 * Return the first valid interface (of the same API type), for control transfers
2670 static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
2672 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2673 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2676 if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
2677 usbi_dbg("unsupported API ID");
2681 for (i = 0; i < USB_MAXINTERFACES; i++) {
2682 if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
2683 && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
2684 && (priv->usb_interface[i].apib->id == api_id))
2692 * Lookup interface by endpoint address. -1 if not found
2694 static int interface_by_endpoint(struct windows_device_priv *priv,
2695 struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
2699 for (i = 0; i < USB_MAXINTERFACES; i++) {
2700 if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
2702 if (priv->usb_interface[i].endpoint == NULL)
2704 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2705 if (priv->usb_interface[i].endpoint[j] == endpoint_address)
2713 static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
2715 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2716 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2717 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2718 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2719 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2720 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
2722 HANDLE winusb_handle;
2723 int current_interface;
2726 CHECK_WINUSBX_AVAILABLE(sub_api);
2728 transfer_priv->pollable_fd = INVALID_WINFD;
2729 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
2731 // Windows places upper limits on the control transfer size
2732 // See: https://msdn.microsoft.com/en-us/library/windows/hardware/ff538112.aspx
2733 if (size > MAX_CTRL_BUFFER_LENGTH)
2734 return LIBUSB_ERROR_INVALID_PARAM;
2736 current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
2737 if (current_interface < 0) {
2738 if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
2739 return LIBUSB_ERROR_NOT_FOUND;
2742 usbi_dbg("will use interface %d", current_interface);
2743 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2745 wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL);
2746 // Always use the handle returned from usbi_create_fd (wfd.handle)
2748 return LIBUSB_ERROR_NO_MEM;
2750 // Sending of set configuration control requests from WinUSB creates issues
2751 if ((LIBUSB_REQ_TYPE(setup->RequestType) == LIBUSB_REQUEST_TYPE_STANDARD)
2752 && (setup->Request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
2753 if (setup->Value != priv->active_config) {
2754 usbi_warn(ctx, "cannot set configuration other than the default one");
2756 return LIBUSB_ERROR_INVALID_PARAM;
2758 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2759 wfd.overlapped->InternalHigh = 0;
2761 if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
2762 if (GetLastError() != ERROR_IO_PENDING) {
2763 usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0));
2765 return LIBUSB_ERROR_IO;
2768 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2769 wfd.overlapped->InternalHigh = (DWORD)size;
2773 // Use priv_transfer to store data needed for async polling
2774 transfer_priv->pollable_fd = wfd;
2775 transfer_priv->interface_number = (uint8_t)current_interface;
2777 return LIBUSB_SUCCESS;
2780 static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
2782 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2783 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2784 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2785 HANDLE winusb_handle;
2787 CHECK_WINUSBX_AVAILABLE(sub_api);
2789 if (altsetting > 255)
2790 return LIBUSB_ERROR_INVALID_PARAM;
2792 winusb_handle = handle_priv->interface_handle[iface].api_handle;
2793 if (!HANDLE_VALID(winusb_handle)) {
2794 usbi_err(ctx, "interface must be claimed first");
2795 return LIBUSB_ERROR_NOT_FOUND;
2798 if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
2799 usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
2800 return LIBUSB_ERROR_IO;
2803 return LIBUSB_SUCCESS;
2806 static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
2808 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2809 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2810 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2811 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2812 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2813 HANDLE winusb_handle;
2815 int current_interface;
2818 CHECK_WINUSBX_AVAILABLE(sub_api);
2820 transfer_priv->pollable_fd = INVALID_WINFD;
2822 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
2823 if (current_interface < 0) {
2824 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
2825 return LIBUSB_ERROR_NOT_FOUND;
2828 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
2830 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2832 wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL);
2833 // Always use the handle returned from usbi_create_fd (wfd.handle)
2835 return LIBUSB_ERROR_NO_MEM;
2837 if (IS_XFERIN(transfer)) {
2838 usbi_dbg("reading %d bytes", transfer->length);
2839 ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2841 usbi_dbg("writing %d bytes", transfer->length);
2842 ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
2846 if (GetLastError() != ERROR_IO_PENDING) {
2847 usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0));
2849 return LIBUSB_ERROR_IO;
2852 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
2853 wfd.overlapped->InternalHigh = (DWORD)transfer->length;
2856 transfer_priv->pollable_fd = wfd;
2857 transfer_priv->interface_number = (uint8_t)current_interface;
2859 return LIBUSB_SUCCESS;
2862 static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
2864 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2865 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2866 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2867 HANDLE winusb_handle;
2868 int current_interface;
2870 CHECK_WINUSBX_AVAILABLE(sub_api);
2872 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
2873 if (current_interface < 0) {
2874 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
2875 return LIBUSB_ERROR_NOT_FOUND;
2878 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
2879 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2881 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
2882 usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0));
2883 return LIBUSB_ERROR_NO_DEVICE;
2886 return LIBUSB_SUCCESS;
2890 * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
2891 * through testing as well):
2892 * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
2893 * the control transfer using CancelIo"
2895 static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer)
2897 // Cancelling of the I/O is done in the parent
2898 return LIBUSB_SUCCESS;
2901 static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
2903 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2904 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
2905 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
2906 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
2907 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
2908 HANDLE winusb_handle;
2909 int current_interface;
2911 CHECK_WINUSBX_AVAILABLE(sub_api);
2913 current_interface = transfer_priv->interface_number;
2914 if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
2915 usbi_err(ctx, "program assertion failed: invalid interface_number");
2916 return LIBUSB_ERROR_NOT_FOUND;
2918 usbi_dbg("will use interface %d", current_interface);
2920 winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
2922 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) {
2923 usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0));
2924 return LIBUSB_ERROR_NO_DEVICE;
2927 return LIBUSB_SUCCESS;
2931 * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
2932 * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
2933 * "WinUSB does not support host-initiated reset port and cycle port operations" and
2934 * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
2935 * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
2936 * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
2938 // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
2939 static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
2941 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
2942 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
2943 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
2945 HANDLE winusb_handle;
2948 CHECK_WINUSBX_AVAILABLE(sub_api);
2950 // Reset any available pipe (except control)
2951 for (i = 0; i < USB_MAXINTERFACES; i++) {
2952 winusb_handle = handle_priv->interface_handle[i].api_handle;
2953 for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0; ) {
2954 // Cancel any pollable I/O
2955 usbi_remove_pollfd(ctx, wfd.fd);
2957 wfd = handle_to_winfd(winusb_handle);
2960 if (HANDLE_VALID(winusb_handle)) {
2961 for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
2962 usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
2963 if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2964 usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s",
2965 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2967 // FlushPipe seems to fail on OUT pipes
2968 if (IS_EPIN(priv->usb_interface[i].endpoint[j])
2969 && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
2970 usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s",
2971 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2973 if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
2974 usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s",
2975 priv->usb_interface[i].endpoint[j], windows_error_str(0));
2980 // libusbK & libusb0 have the ability to issue an actual device reset
2981 if (WinUSBX[sub_api].ResetDevice != NULL) {
2982 winusb_handle = handle_priv->interface_handle[0].api_handle;
2983 if (HANDLE_VALID(winusb_handle))
2984 WinUSBX[sub_api].ResetDevice(winusb_handle);
2987 return LIBUSB_SUCCESS;
2990 static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
2992 itransfer->transferred += io_size;
2993 return LIBUSB_TRANSFER_COMPLETED;
2997 * Internal HID Support functions (from libusb-win32)
2998 * Note that functions that complete data transfer synchronously must return
2999 * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
3001 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3002 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
3004 static int _hid_wcslen(WCHAR *str)
3008 while (str[i] && (str[i] != 0x409))
3014 static int _hid_get_device_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3016 struct libusb_device_descriptor d;
3018 d.bLength = LIBUSB_DT_DEVICE_SIZE;
3019 d.bDescriptorType = LIBUSB_DT_DEVICE;
3020 d.bcdUSB = 0x0200; /* 2.00 */
3022 d.bDeviceSubClass = 0;
3023 d.bDeviceProtocol = 0;
3024 d.bMaxPacketSize0 = 64; /* fix this! */
3025 d.idVendor = (uint16_t)dev->vid;
3026 d.idProduct = (uint16_t)dev->pid;
3027 d.bcdDevice = 0x0100;
3028 d.iManufacturer = dev->string_index[0];
3029 d.iProduct = dev->string_index[1];
3030 d.iSerialNumber = dev->string_index[2];
3031 d.bNumConfigurations = 1;
3033 if (*size > LIBUSB_DT_DEVICE_SIZE)
3034 *size = LIBUSB_DT_DEVICE_SIZE;
3035 memcpy(data, &d, *size);
3037 return LIBUSB_COMPLETED;
3040 static int _hid_get_config_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3042 char num_endpoints = 0;
3043 size_t config_total_len = 0;
3044 char tmp[HID_MAX_CONFIG_DESC_SIZE];
3045 struct libusb_config_descriptor *cd;
3046 struct libusb_interface_descriptor *id;
3047 struct libusb_hid_descriptor *hd;
3048 struct libusb_endpoint_descriptor *ed;
3051 if (dev->input_report_size)
3053 if (dev->output_report_size)
3056 config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
3057 + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
3059 cd = (struct libusb_config_descriptor *)tmp;
3060 id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
3061 hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3062 + LIBUSB_DT_INTERFACE_SIZE);
3063 ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
3064 + LIBUSB_DT_INTERFACE_SIZE
3065 + LIBUSB_DT_HID_SIZE);
3067 cd->bLength = LIBUSB_DT_CONFIG_SIZE;
3068 cd->bDescriptorType = LIBUSB_DT_CONFIG;
3069 cd->wTotalLength = (uint16_t)config_total_len;
3070 cd->bNumInterfaces = 1;
3071 cd->bConfigurationValue = 1;
3072 cd->iConfiguration = 0;
3073 cd->bmAttributes = 1 << 7; /* bus powered */
3076 id->bLength = LIBUSB_DT_INTERFACE_SIZE;
3077 id->bDescriptorType = LIBUSB_DT_INTERFACE;
3078 id->bInterfaceNumber = 0;
3079 id->bAlternateSetting = 0;
3080 id->bNumEndpoints = num_endpoints;
3081 id->bInterfaceClass = 3;
3082 id->bInterfaceSubClass = 0;
3083 id->bInterfaceProtocol = 0;
3086 tmp_size = LIBUSB_DT_HID_SIZE;
3087 _hid_get_hid_descriptor(dev, hd, &tmp_size);
3089 if (dev->input_report_size) {
3090 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3091 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3092 ed->bEndpointAddress = HID_IN_EP;
3093 ed->bmAttributes = 3;
3094 ed->wMaxPacketSize = dev->input_report_size - 1;
3096 ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
3099 if (dev->output_report_size) {
3100 ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
3101 ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
3102 ed->bEndpointAddress = HID_OUT_EP;
3103 ed->bmAttributes = 3;
3104 ed->wMaxPacketSize = dev->output_report_size - 1;
3108 if (*size > config_total_len)
3109 *size = config_total_len;
3110 memcpy(data, tmp, *size);
3112 return LIBUSB_COMPLETED;
3115 static int _hid_get_string_descriptor(struct hid_device_priv *dev, int _index,
3116 void *data, size_t *size, HANDLE hid_handle)
3119 WCHAR string[MAX_USB_STRING_LENGTH];
3120 size_t tmp_size = 0;
3123 /* language ID, EN-US */
3124 char string_langid[] = {0x09, 0x04};
3126 if ((*size < 2) || (*size > 255))
3127 return LIBUSB_ERROR_OVERFLOW;
3130 tmp = string_langid;
3131 tmp_size = sizeof(string_langid) + 2;
3133 for (i = 0; i < 3; i++) {
3134 if (_index == (dev->string_index[i])) {
3135 tmp = dev->string[i];
3136 tmp_size = (_hid_wcslen(dev->string[i]) + 1) * sizeof(WCHAR);
3142 if (!HidD_GetIndexedString(hid_handle, _index, string, sizeof(string)))
3143 return LIBUSB_ERROR_INVALID_PARAM;
3145 tmp_size = (_hid_wcslen(string) + 1) * sizeof(WCHAR);
3150 return LIBUSB_ERROR_INVALID_PARAM;
3152 if (tmp_size < *size)
3156 ((uint8_t *)data)[0] = (uint8_t)*size;
3157 ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
3158 memcpy((uint8_t *)data + 2, tmp, *size - 2);
3160 return LIBUSB_COMPLETED;
3163 static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3165 struct libusb_hid_descriptor d;
3166 uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
3167 size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
3169 _hid_get_report_descriptor(dev, tmp, &report_len);
3171 d.bLength = LIBUSB_DT_HID_SIZE;
3172 d.bDescriptorType = LIBUSB_DT_HID;
3173 d.bcdHID = 0x0110; /* 1.10 */
3175 d.bNumDescriptors = 1;
3176 d.bClassDescriptorType = LIBUSB_DT_REPORT;
3177 d.wClassDescriptorLength = (uint16_t)report_len;
3179 if (*size > LIBUSB_DT_HID_SIZE)
3180 *size = LIBUSB_DT_HID_SIZE;
3181 memcpy(data, &d, *size);
3183 return LIBUSB_COMPLETED;
3186 static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size)
3188 uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
3192 d[i++] = 0x06; d[i++] = dev->usagePage & 0xFF; d[i++] = dev->usagePage >> 8;
3194 d[i++] = 0x09; d[i++] = (uint8_t)dev->usage;
3195 /* start collection (application) */
3196 d[i++] = 0xA1; d[i++] = 0x01;
3198 if (dev->input_report_size) {
3199 /* usage (vendor defined) */
3200 d[i++] = 0x09; d[i++] = 0x01;
3201 /* logical minimum (0) */
3202 d[i++] = 0x15; d[i++] = 0x00;
3203 /* logical maximum (255) */
3204 d[i++] = 0x25; d[i++] = 0xFF;
3205 /* report size (8 bits) */
3206 d[i++] = 0x75; d[i++] = 0x08;
3208 d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1;
3209 /* input (data, variable, absolute) */
3210 d[i++] = 0x81; d[i++] = 0x00;
3213 if (dev->output_report_size) {
3214 /* usage (vendor defined) */
3215 d[i++] = 0x09; d[i++] = 0x02;
3216 /* logical minimum (0) */
3217 d[i++] = 0x15; d[i++] = 0x00;
3218 /* logical maximum (255) */
3219 d[i++] = 0x25; d[i++] = 0xFF;
3220 /* report size (8 bits) */
3221 d[i++] = 0x75; d[i++] = 0x08;
3223 d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1;
3224 /* output (data, variable, absolute) */
3225 d[i++] = 0x91; d[i++] = 0x00;
3227 /* feature report */
3228 if (dev->feature_report_size) {
3229 /* usage (vendor defined) */
3230 d[i++] = 0x09; d[i++] = 0x03;
3231 /* logical minimum (0) */
3232 d[i++] = 0x15; d[i++] = 0x00;
3233 /* logical maximum (255) */
3234 d[i++] = 0x25; d[i++] = 0xFF;
3235 /* report size (8 bits) */
3236 d[i++] = 0x75; d[i++] = 0x08;
3238 d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1;
3239 /* feature (data, variable, absolute) */
3240 d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
3243 /* end collection */
3248 memcpy(data, d, *size);
3250 return LIBUSB_COMPLETED;
3253 static int _hid_get_descriptor(struct hid_device_priv *dev, HANDLE hid_handle, int recipient,
3254 int type, int _index, void *data, size_t *size)
3257 case LIBUSB_DT_DEVICE:
3258 usbi_dbg("LIBUSB_DT_DEVICE");
3259 return _hid_get_device_descriptor(dev, data, size);
3260 case LIBUSB_DT_CONFIG:
3261 usbi_dbg("LIBUSB_DT_CONFIG");
3263 return _hid_get_config_descriptor(dev, data, size);
3264 return LIBUSB_ERROR_INVALID_PARAM;
3265 case LIBUSB_DT_STRING:
3266 usbi_dbg("LIBUSB_DT_STRING");
3267 return _hid_get_string_descriptor(dev, _index, data, size, hid_handle);
3269 usbi_dbg("LIBUSB_DT_HID");
3271 return _hid_get_hid_descriptor(dev, data, size);
3272 return LIBUSB_ERROR_INVALID_PARAM;
3273 case LIBUSB_DT_REPORT:
3274 usbi_dbg("LIBUSB_DT_REPORT");
3276 return _hid_get_report_descriptor(dev, data, size);
3277 return LIBUSB_ERROR_INVALID_PARAM;
3278 case LIBUSB_DT_PHYSICAL:
3279 usbi_dbg("LIBUSB_DT_PHYSICAL");
3280 if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
3281 return LIBUSB_COMPLETED;
3282 return LIBUSB_ERROR_OTHER;
3285 usbi_dbg("unsupported");
3286 return LIBUSB_ERROR_NOT_SUPPORTED;
3289 static int _hid_get_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3290 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3293 DWORD ioctl_code, read_size, expected_size = (DWORD)*size;
3294 int r = LIBUSB_SUCCESS;
3296 if (tp->hid_buffer != NULL)
3297 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3299 if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) {
3300 usbi_dbg("invalid size (%u)", *size);
3301 return LIBUSB_ERROR_INVALID_PARAM;
3304 switch (report_type) {
3305 case HID_REPORT_TYPE_INPUT:
3306 ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
3308 case HID_REPORT_TYPE_FEATURE:
3309 ioctl_code = IOCTL_HID_GET_FEATURE;
3312 usbi_dbg("unknown HID report type %d", report_type);
3313 return LIBUSB_ERROR_INVALID_PARAM;
3316 // Add a trailing byte to detect overflows
3317 buf = calloc(1, expected_size + 1);
3319 return LIBUSB_ERROR_NO_MEM;
3321 buf[0] = (uint8_t)id; // Must be set always
3322 usbi_dbg("report ID: 0x%02X", buf[0]);
3324 tp->hid_expected_size = expected_size;
3325 read_size = expected_size;
3327 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3328 if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
3329 buf, expected_size + 1, &read_size, overlapped)) {
3330 if (GetLastError() != ERROR_IO_PENDING) {
3331 usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0));
3333 return LIBUSB_ERROR_IO;
3335 // Asynchronous wait
3336 tp->hid_buffer = buf;
3337 tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
3338 return LIBUSB_SUCCESS;
3341 // Transfer completed synchronously => copy and discard extra buffer
3342 if (read_size == 0) {
3343 usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read");
3347 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3349 if ((size_t)read_size > expected_size) {
3350 r = LIBUSB_ERROR_OVERFLOW;
3351 usbi_dbg("OVERFLOW!");
3353 r = LIBUSB_COMPLETED;
3356 *size = MIN((size_t)read_size, *size);
3358 memcpy(data, buf + 1, *size); // Discard report ID
3360 memcpy(data, buf, *size);
3367 static int _hid_set_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data,
3368 struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type)
3370 uint8_t *buf = NULL;
3371 DWORD ioctl_code, write_size = (DWORD)*size;
3372 // If an id is reported, we must allow MAX_HID_REPORT_SIZE + 1
3373 size_t max_report_size = MAX_HID_REPORT_SIZE + (id ? 1 : 0);
3375 if (tp->hid_buffer != NULL)
3376 usbi_dbg("program assertion failed: hid_buffer is not NULL");
3378 if ((*size == 0) || (*size > max_report_size)) {
3379 usbi_dbg("invalid size (%u)", *size);
3380 return LIBUSB_ERROR_INVALID_PARAM;
3383 switch (report_type) {
3384 case HID_REPORT_TYPE_OUTPUT:
3385 ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
3387 case HID_REPORT_TYPE_FEATURE:
3388 ioctl_code = IOCTL_HID_SET_FEATURE;
3391 usbi_dbg("unknown HID report type %d", report_type);
3392 return LIBUSB_ERROR_INVALID_PARAM;
3395 usbi_dbg("report ID: 0x%02X", id);
3396 // When report IDs are not used (i.e. when id == 0), we must add
3397 // a null report ID. Otherwise, we just use original data buffer
3401 buf = malloc(write_size);
3403 return LIBUSB_ERROR_NO_MEM;
3407 memcpy(buf + 1, data, *size);
3409 // This seems like a waste, but if we don't duplicate the
3410 // data, we'll get issues when freeing hid_buffer
3411 memcpy(buf, data, *size);
3413 usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
3416 // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
3417 if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
3418 buf, write_size, &write_size, overlapped)) {
3419 if (GetLastError() != ERROR_IO_PENDING) {
3420 usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0));
3422 return LIBUSB_ERROR_IO;
3424 tp->hid_buffer = buf;
3425 tp->hid_dest = NULL;
3426 return LIBUSB_SUCCESS;
3429 // Transfer completed synchronously
3431 if (write_size == 0)
3432 usbi_dbg("program assertion failed - write completed synchronously, but no data was written");
3435 return LIBUSB_COMPLETED;
3438 static int _hid_class_request(struct hid_device_priv *dev, HANDLE hid_handle, int request_type,
3439 int request, int value, int _index, void *data, struct windows_transfer_priv *tp,
3440 size_t *size, OVERLAPPED *overlapped)
3442 int report_type = (value >> 8) & 0xFF;
3443 int report_id = value & 0xFF;
3445 if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
3446 && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
3447 return LIBUSB_ERROR_INVALID_PARAM;
3449 if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
3450 return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3452 if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
3453 return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
3455 return LIBUSB_ERROR_INVALID_PARAM;
3462 static int hid_init(int sub_api, struct libusb_context *ctx)
3464 DLL_GET_HANDLE(hid);
3465 DLL_LOAD_FUNC(hid, HidD_GetAttributes, TRUE);
3466 DLL_LOAD_FUNC(hid, HidD_GetHidGuid, TRUE);
3467 DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, TRUE);
3468 DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, TRUE);
3469 DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, TRUE);
3470 DLL_LOAD_FUNC(hid, HidD_GetProductString, TRUE);
3471 DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, TRUE);
3472 DLL_LOAD_FUNC(hid, HidD_GetIndexedString, TRUE);
3473 DLL_LOAD_FUNC(hid, HidP_GetCaps, TRUE);
3474 DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, TRUE);
3475 DLL_LOAD_FUNC(hid, HidD_SetFeature, TRUE);
3476 DLL_LOAD_FUNC(hid, HidD_GetFeature, TRUE);
3477 DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, TRUE);
3478 DLL_LOAD_FUNC(hid, HidD_GetInputReport, FALSE);
3479 DLL_LOAD_FUNC(hid, HidD_SetOutputReport, FALSE);
3480 DLL_LOAD_FUNC(hid, HidD_FlushQueue, TRUE);
3481 DLL_LOAD_FUNC(hid, HidP_GetValueCaps, TRUE);
3483 api_hid_available = true;
3484 return LIBUSB_SUCCESS;
3487 static int hid_exit(int sub_api)
3489 DLL_FREE_HANDLE(hid);
3491 return LIBUSB_SUCCESS;
3494 // NB: open and close must ensure that they only handle interface of
3495 // the right API type, as these functions can be called wholesale from
3496 // composite_open(), with interfaces belonging to different APIs
3497 static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
3499 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3500 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3501 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3502 HIDD_ATTRIBUTES hid_attributes;
3503 PHIDP_PREPARSED_DATA preparsed_data = NULL;
3504 HIDP_CAPS capabilities;
3505 HIDP_VALUE_CAPS *value_caps;
3506 HANDLE hid_handle = INVALID_HANDLE_VALUE;
3508 // report IDs handling
3510 int nb_ids[2]; // zero and nonzero report IDs
3511 #if defined(ENABLE_LOGGING)
3512 const char *type[3] = {"input", "output", "feature"};
3515 CHECK_HID_AVAILABLE;
3517 if (priv->hid == NULL) {
3518 usbi_err(ctx, "program assertion failed - private HID structure is unitialized");
3519 return LIBUSB_ERROR_NOT_FOUND;
3522 for (i = 0; i < USB_MAXINTERFACES; i++) {
3523 if ((priv->usb_interface[i].path != NULL)
3524 && (priv->usb_interface[i].apib->id == USB_API_HID)) {
3525 hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
3526 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3528 * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
3529 * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
3530 * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
3531 * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
3532 * HidD_GetFeature (if the device supports Feature reports)."
3534 if (hid_handle == INVALID_HANDLE_VALUE) {
3535 usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
3536 hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ,
3537 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
3538 if (hid_handle == INVALID_HANDLE_VALUE) {
3539 usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
3540 switch(GetLastError()) {
3541 case ERROR_FILE_NOT_FOUND: // The device was disconnected
3542 return LIBUSB_ERROR_NO_DEVICE;
3543 case ERROR_ACCESS_DENIED:
3544 return LIBUSB_ERROR_ACCESS;
3546 return LIBUSB_ERROR_IO;
3549 priv->usb_interface[i].restricted_functionality = true;
3551 handle_priv->interface_handle[i].api_handle = hid_handle;
3555 hid_attributes.Size = sizeof(hid_attributes);
3557 if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
3558 usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)");
3562 priv->hid->vid = hid_attributes.VendorID;
3563 priv->hid->pid = hid_attributes.ProductID;
3565 // Set the maximum available input buffer size
3566 for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
3567 usbi_dbg("set maximum input buffer size to %d", i / 2);
3569 // Get the maximum input and output report size
3570 if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
3571 usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)");
3574 if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
3575 usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)");
3579 // Find out if interrupt will need report IDs
3580 size[0] = capabilities.NumberInputValueCaps;
3581 size[1] = capabilities.NumberOutputValueCaps;
3582 size[2] = capabilities.NumberFeatureValueCaps;
3583 for (j = HidP_Input; j <= HidP_Feature; j++) {
3584 usbi_dbg("%u HID %s report value(s) found", (unsigned int)size[j], type[j]);
3585 priv->hid->uses_report_ids[j] = false;
3587 value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
3588 if ((value_caps != NULL)
3589 && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
3590 && (size[j] >= 1)) {
3593 for (i = 0; i < (int)size[j]; i++) {
3594 usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID);
3595 if (value_caps[i].ReportID != 0)
3600 if (nb_ids[1] != 0) {
3602 usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s",
3604 priv->hid->uses_report_ids[j] = true;
3607 usbi_warn(ctx, " could not process %s report IDs", type[j]);
3613 // Set the report sizes
3614 priv->hid->input_report_size = capabilities.InputReportByteLength;
3615 priv->hid->output_report_size = capabilities.OutputReportByteLength;
3616 priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
3618 // Store usage and usagePage values
3619 priv->hid->usage = capabilities.Usage;
3620 priv->hid->usagePage = capabilities.UsagePage;
3622 // Fetch string descriptors
3623 priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer;
3624 if (priv->hid->string_index[0] != 0)
3625 HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
3627 priv->hid->string[0][0] = 0;
3629 priv->hid->string_index[1] = priv->dev_descriptor.iProduct;
3630 if (priv->hid->string_index[1] != 0)
3631 HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1]));
3633 priv->hid->string[1][0] = 0;
3635 priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber;
3636 if (priv->hid->string_index[2] != 0)
3637 HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
3639 priv->hid->string[2][0] = 0;
3643 HidD_FreePreparsedData(preparsed_data);
3645 return LIBUSB_SUCCESS;
3648 static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
3650 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3651 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3655 if (!api_hid_available)
3658 for (i = 0; i < USB_MAXINTERFACES; i++) {
3659 if (priv->usb_interface[i].apib->id == USB_API_HID) {
3660 file_handle = handle_priv->interface_handle[i].api_handle;
3661 if (HANDLE_VALID(file_handle))
3662 CloseHandle(file_handle);
3667 static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3669 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3670 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3672 CHECK_HID_AVAILABLE;
3674 // NB: Disconnection detection is not possible in this function
3675 if (priv->usb_interface[iface].path == NULL)
3676 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3678 // We use dev_handle as a flag for interface claimed
3679 if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
3680 return LIBUSB_ERROR_BUSY; // already claimed
3683 handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
3685 usbi_dbg("claimed interface %d", iface);
3686 handle_priv->active_interface = iface;
3688 return LIBUSB_SUCCESS;
3691 static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
3693 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3694 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3696 CHECK_HID_AVAILABLE;
3698 if (priv->usb_interface[iface].path == NULL)
3699 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3701 if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
3702 return LIBUSB_ERROR_NOT_FOUND; // invalid iface
3704 handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
3706 return LIBUSB_SUCCESS;
3709 static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
3711 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3713 CHECK_HID_AVAILABLE;
3715 if (altsetting > 255)
3716 return LIBUSB_ERROR_INVALID_PARAM;
3718 if (altsetting != 0) {
3719 usbi_err(ctx, "set interface altsetting not supported for altsetting >0");
3720 return LIBUSB_ERROR_NOT_SUPPORTED;
3723 return LIBUSB_SUCCESS;
3726 static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
3728 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3729 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3730 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3731 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3732 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3733 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
3736 int current_interface, config;
3738 int r = LIBUSB_ERROR_INVALID_PARAM;
3740 CHECK_HID_AVAILABLE;
3742 transfer_priv->pollable_fd = INVALID_WINFD;
3743 safe_free(transfer_priv->hid_buffer);
3744 transfer_priv->hid_dest = NULL;
3745 size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
3747 if (size > MAX_CTRL_BUFFER_LENGTH)
3748 return LIBUSB_ERROR_INVALID_PARAM;
3750 current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID);
3751 if (current_interface < 0) {
3752 if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS)
3753 return LIBUSB_ERROR_NOT_FOUND;
3756 usbi_dbg("will use interface %d", current_interface);
3757 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3758 // Always use the handle returned from usbi_create_fd (wfd.handle)
3759 wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL);
3761 return LIBUSB_ERROR_NOT_FOUND;
3763 switch(LIBUSB_REQ_TYPE(setup->RequestType)) {
3764 case LIBUSB_REQUEST_TYPE_STANDARD:
3765 switch(setup->Request) {
3766 case LIBUSB_REQUEST_GET_DESCRIPTOR:
3767 r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->RequestType),
3768 (setup->Value >> 8) & 0xFF, setup->Value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
3770 case LIBUSB_REQUEST_GET_CONFIGURATION:
3771 r = windows_get_configuration(transfer->dev_handle, &config);
3772 if (r == LIBUSB_SUCCESS) {
3774 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config;
3775 r = LIBUSB_COMPLETED;
3778 case LIBUSB_REQUEST_SET_CONFIGURATION:
3779 if (setup->Value == priv->active_config) {
3780 r = LIBUSB_COMPLETED;
3782 usbi_warn(ctx, "cannot set configuration other than the default one");
3783 r = LIBUSB_ERROR_NOT_SUPPORTED;
3786 case LIBUSB_REQUEST_GET_INTERFACE:
3788 ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
3789 r = LIBUSB_COMPLETED;
3791 case LIBUSB_REQUEST_SET_INTERFACE:
3792 r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->Index, setup->Value);
3793 if (r == LIBUSB_SUCCESS)
3794 r = LIBUSB_COMPLETED;
3797 usbi_warn(ctx, "unsupported HID control request");
3798 r = LIBUSB_ERROR_NOT_SUPPORTED;
3802 case LIBUSB_REQUEST_TYPE_CLASS:
3803 r = _hid_class_request(priv->hid, wfd.handle, setup->RequestType, setup->Request, setup->Value,
3804 setup->Index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
3805 &size, wfd.overlapped);
3808 usbi_warn(ctx, "unsupported HID control request");
3809 r = LIBUSB_ERROR_NOT_SUPPORTED;
3813 if (r == LIBUSB_COMPLETED) {
3814 // Force request to be completed synchronously. Transferred size has been set by previous call
3815 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3816 // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx
3817 // set InternalHigh to the number of bytes transferred
3818 wfd.overlapped->InternalHigh = (DWORD)size;
3822 if (r == LIBUSB_SUCCESS) {
3823 // Use priv_transfer to store data needed for async polling
3824 transfer_priv->pollable_fd = wfd;
3825 transfer_priv->interface_number = (uint8_t)current_interface;
3833 static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
3835 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3836 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3837 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3838 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3839 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
3842 bool direction_in, ret;
3843 int current_interface, length;
3845 int r = LIBUSB_SUCCESS;
3847 CHECK_HID_AVAILABLE;
3849 transfer_priv->pollable_fd = INVALID_WINFD;
3850 transfer_priv->hid_dest = NULL;
3851 safe_free(transfer_priv->hid_buffer);
3853 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
3854 if (current_interface < 0) {
3855 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
3856 return LIBUSB_ERROR_NOT_FOUND;
3859 usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
3861 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3862 direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
3864 wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL);
3865 // Always use the handle returned from usbi_create_fd (wfd.handle)
3867 return LIBUSB_ERROR_NO_MEM;
3869 // If report IDs are not in use, an extra prefix byte must be added
3870 if (((direction_in) && (!priv->hid->uses_report_ids[0]))
3871 || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
3872 length = transfer->length + 1;
3874 length = transfer->length;
3876 // Add a trailing byte to detect overflows on input
3877 transfer_priv->hid_buffer = calloc(1, length + 1);
3878 if (transfer_priv->hid_buffer == NULL)
3879 return LIBUSB_ERROR_NO_MEM;
3881 transfer_priv->hid_expected_size = length;
3884 transfer_priv->hid_dest = transfer->buffer;
3885 usbi_dbg("reading %d bytes (report ID: 0x00)", length);
3886 ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length + 1, &size, wfd.overlapped);
3888 if (!priv->hid->uses_report_ids[1])
3889 memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
3891 // We could actually do without the calloc and memcpy in this case
3892 memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
3894 usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
3895 ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped);
3899 if (GetLastError() != ERROR_IO_PENDING) {
3900 usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0));
3902 safe_free(transfer_priv->hid_buffer);
3903 return LIBUSB_ERROR_IO;
3906 // Only write operations that completed synchronously need to free up
3907 // hid_buffer. For reads, copy_transfer_data() handles that process.
3909 safe_free(transfer_priv->hid_buffer);
3912 usbi_err(ctx, "program assertion failed - no data was transferred");
3915 if (size > (size_t)length) {
3916 usbi_err(ctx, "OVERFLOW!");
3917 r = LIBUSB_ERROR_OVERFLOW;
3919 wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
3920 wfd.overlapped->InternalHigh = size;
3923 transfer_priv->pollable_fd = wfd;
3924 transfer_priv->interface_number = (uint8_t)current_interface;
3929 static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
3931 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3932 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
3933 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
3935 int current_interface;
3937 CHECK_HID_AVAILABLE;
3939 current_interface = transfer_priv->interface_number;
3940 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3941 CancelIo(hid_handle);
3943 return LIBUSB_SUCCESS;
3946 static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
3948 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3950 int current_interface;
3952 CHECK_HID_AVAILABLE;
3954 // Flushing the queues on all interfaces is the best we can achieve
3955 for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
3956 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3957 if (HANDLE_VALID(hid_handle))
3958 HidD_FlushQueue(hid_handle);
3961 return LIBUSB_SUCCESS;
3964 static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
3966 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
3967 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
3968 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
3970 int current_interface;
3972 CHECK_HID_AVAILABLE;
3974 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
3975 if (current_interface < 0) {
3976 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
3977 return LIBUSB_ERROR_NOT_FOUND;
3980 usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
3981 hid_handle = handle_priv->interface_handle[current_interface].api_handle;
3983 // No endpoint selection with Microsoft's implementation, so we try to flush the
3984 // whole interface. Should be OK for most case scenarios
3985 if (!HidD_FlushQueue(hid_handle)) {
3986 usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0));
3987 // Device was probably disconnected
3988 return LIBUSB_ERROR_NO_DEVICE;
3991 return LIBUSB_SUCCESS;
3994 // This extra function is only needed for HID
3995 static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
3997 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
3998 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
3999 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4000 int r = LIBUSB_TRANSFER_COMPLETED;
4001 uint32_t corrected_size = io_size;
4003 if (transfer_priv->hid_buffer != NULL) {
4004 // If we have a valid hid_buffer, it means the transfer was async
4005 if (transfer_priv->hid_dest != NULL) { // Data readout
4006 if (corrected_size > 0) {
4007 // First, check for overflow
4008 if (corrected_size > transfer_priv->hid_expected_size) {
4009 usbi_err(ctx, "OVERFLOW!");
4010 corrected_size = (uint32_t)transfer_priv->hid_expected_size;
4011 r = LIBUSB_TRANSFER_OVERFLOW;
4014 if (transfer_priv->hid_buffer[0] == 0) {
4015 // Discard the 1 byte report ID prefix
4017 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, corrected_size);
4019 memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size);
4022 transfer_priv->hid_dest = NULL;
4024 // For write, we just need to free the hid buffer
4025 safe_free(transfer_priv->hid_buffer);
4028 itransfer->transferred += corrected_size;
4034 * Composite API functions
4036 static int composite_init(int sub_api, struct libusb_context *ctx)
4038 return LIBUSB_SUCCESS;
4041 static int composite_exit(int sub_api)
4043 return LIBUSB_SUCCESS;
4046 static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
4048 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4049 int r = LIBUSB_ERROR_NOT_FOUND;
4051 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4052 bool available[SUB_API_MAX + 1] = { 0 };
4054 for (i = 0; i < USB_MAXINTERFACES; i++) {
4055 switch (priv->usb_interface[i].apib->id) {
4056 case USB_API_WINUSBX:
4057 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4058 available[priv->usb_interface[i].sub_api] = true;
4061 available[SUB_API_MAX] = true;
4068 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4070 r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
4071 if (r != LIBUSB_SUCCESS)
4076 if (available[SUB_API_MAX]) // HID driver
4077 r = hid_open(SUB_API_NOTSET, dev_handle);
4082 static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
4084 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4086 // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
4087 bool available[SUB_API_MAX + 1] = { 0 };
4089 for (i = 0; i < USB_MAXINTERFACES; i++) {
4090 switch (priv->usb_interface[i].apib->id) {
4091 case USB_API_WINUSBX:
4092 if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
4093 available[priv->usb_interface[i].sub_api] = true;
4096 available[SUB_API_MAX] = true;
4103 for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
4105 usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
4108 if (available[SUB_API_MAX]) // HID driver
4109 hid_close(SUB_API_NOTSET, dev_handle);
4112 static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4114 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4116 return priv->usb_interface[iface].apib->
4117 claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4120 static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting)
4122 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4124 return priv->usb_interface[iface].apib->
4125 set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
4128 static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface)
4130 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4132 return priv->usb_interface[iface].apib->
4133 release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
4136 static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
4138 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4139 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4140 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4141 struct libusb_config_descriptor *conf_desc;
4142 WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
4145 // Interface shouldn't matter for control, but it does in practice, with Windows'
4146 // restrictions with regards to accessing HID keyboards and mice. Try to target
4147 // a specific interface first, if possible.
4148 switch (LIBUSB_REQ_RECIPIENT(setup->RequestType)) {
4149 case LIBUSB_RECIPIENT_INTERFACE:
4150 iface = setup->Index & 0xFF;
4152 case LIBUSB_RECIPIENT_ENDPOINT:
4153 r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc);
4154 if (r == LIBUSB_SUCCESS) {
4155 iface = get_interface_by_endpoint(conf_desc, (setup->Index & 0xFF));
4156 libusb_free_config_descriptor(conf_desc);
4159 // Fall through if not able to determine interface
4165 // Try and target a specific interface if the control setup indicates such
4166 if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
4167 usbi_dbg("attempting control transfer targeted to interface %d", iface);
4168 if (priv->usb_interface[iface].path != NULL) {
4169 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4170 if (r == LIBUSB_SUCCESS)
4175 // Either not targeted to a specific interface or no luck in doing so.
4176 // Try a 2 pass approach with all interfaces.
4177 for (pass = 0; pass < 2; pass++) {
4178 for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
4179 if (priv->usb_interface[iface].path != NULL) {
4180 if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
4181 usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
4184 usbi_dbg("using interface %d", iface);
4185 r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
4186 // If not supported on this API, it may be supported on another, so don't give up yet!!
4187 if (r == LIBUSB_ERROR_NOT_SUPPORTED)
4194 usbi_err(ctx, "no libusb supported interfaces to complete request");
4195 return LIBUSB_ERROR_NOT_FOUND;
4198 static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) {
4199 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4200 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4201 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4202 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4203 int current_interface;
4205 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4206 if (current_interface < 0) {
4207 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4208 return LIBUSB_ERROR_NOT_FOUND;
4211 return priv->usb_interface[current_interface].apib->
4212 submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4215 static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) {
4216 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4217 struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
4218 struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
4219 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4220 int current_interface;
4222 current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
4223 if (current_interface < 0) {
4224 usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
4225 return LIBUSB_ERROR_NOT_FOUND;
4228 return priv->usb_interface[current_interface].apib->
4229 submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
4232 static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
4234 struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
4235 struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
4236 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4237 int current_interface;
4239 current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
4240 if (current_interface < 0) {
4241 usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
4242 return LIBUSB_ERROR_NOT_FOUND;
4245 return priv->usb_interface[current_interface].apib->
4246 clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
4249 static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer)
4251 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4252 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4253 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4255 return priv->usb_interface[transfer_priv->interface_number].apib->
4256 abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4259 static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer)
4261 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4262 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4263 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4265 return priv->usb_interface[transfer_priv->interface_number].apib->
4266 abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer);
4269 static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
4271 struct windows_device_priv *priv = _device_priv(dev_handle->dev);
4274 bool available[SUB_API_MAX];
4276 for (i = 0; i < SUB_API_MAX; i++)
4277 available[i] = false;
4279 for (i = 0; i < USB_MAXINTERFACES; i++) {
4280 if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
4281 && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
4282 available[priv->usb_interface[i].sub_api] = true;
4285 for (i = 0; i < SUB_API_MAX; i++) {
4287 r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
4288 if (r != LIBUSB_SUCCESS)
4293 return LIBUSB_SUCCESS;
4296 static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size)
4298 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
4299 struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
4300 struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
4302 return priv->usb_interface[transfer_priv->interface_number].apib->
4303 copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size);
4306 #endif /* !USE_USBDK */