windows_usb.c 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998
  1. /*
  2. * windows backend for libusb 1.0
  3. * Copyright (c) 2009-2010 Pete Batard <pbatard@gmail.com>
  4. * With contributions from Michael Plante, Orin Eman et al.
  5. * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
  6. * Hash table functions adapted from glibc, by Ulrich Drepper et al.
  7. * Major code testing contribution by Xiaofan Chen
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include <config.h>
  24. #include <windows.h>
  25. #include <setupapi.h>
  26. #include <ctype.h>
  27. #include <errno.h>
  28. #include <fcntl.h>
  29. #include <process.h>
  30. #include <stdio.h>
  31. #include <objbase.h>
  32. #include <winioctl.h>
  33. #include <libusbi.h>
  34. #include "poll_windows.h"
  35. #include "windows_usb.h"
  36. // The following prevents "banned API" errors when using the MS's WDK OACR/Prefast
  37. #if defined(_PREFAST_)
  38. #pragma warning(disable:28719)
  39. #endif
  40. // The 2 macros below are used in conjunction with safe loops.
  41. #define LOOP_CHECK(fcall) { r=fcall; if (r != LIBUSB_SUCCESS) continue; }
  42. #define LOOP_BREAK(err) { r=err; continue; }
  43. extern void usbi_fd_notification(struct libusb_context *ctx);
  44. // Helper prototypes
  45. static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian);
  46. static int windows_clock_gettime(int clk_id, struct timespec *tp);
  47. unsigned __stdcall windows_clock_gettime_threaded(void* param);
  48. // WinUSB API prototypes
  49. static int winusb_init(struct libusb_context *ctx);
  50. static int winusb_exit(void);
  51. static int winusb_open(struct libusb_device_handle *dev_handle);
  52. static void winusb_close(struct libusb_device_handle *dev_handle);
  53. static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface);
  54. static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface);
  55. static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface);
  56. static int winusb_submit_control_transfer(struct usbi_transfer *itransfer);
  57. static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
  58. static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer);
  59. static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
  60. static int winusb_abort_transfers(struct usbi_transfer *itransfer);
  61. static int winusb_abort_control(struct usbi_transfer *itransfer);
  62. static int winusb_reset_device(struct libusb_device_handle *dev_handle);
  63. static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
  64. // Composite API prototypes
  65. static int composite_init(struct libusb_context *ctx);
  66. static int composite_exit(void);
  67. static int composite_open(struct libusb_device_handle *dev_handle);
  68. static void composite_close(struct libusb_device_handle *dev_handle);
  69. static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface);
  70. static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting);
  71. static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface);
  72. static int composite_submit_control_transfer(struct usbi_transfer *itransfer);
  73. static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer);
  74. static int composite_submit_iso_transfer(struct usbi_transfer *itransfer);
  75. static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
  76. static int composite_abort_transfers(struct usbi_transfer *itransfer);
  77. static int composite_abort_control(struct usbi_transfer *itransfer);
  78. static int composite_reset_device(struct libusb_device_handle *dev_handle);
  79. static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size);
  80. // Global variables
  81. uint64_t hires_frequency, hires_ticks_to_ps;
  82. const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
  83. enum windows_version windows_version = WINDOWS_UNSUPPORTED;
  84. // Concurrency
  85. static int concurrent_usage = -1;
  86. usbi_mutex_t autoclaim_lock;
  87. // Timer thread
  88. // NB: index 0 is for monotonic and 1 is for the thread exit event
  89. HANDLE timer_thread = NULL;
  90. HANDLE timer_mutex = NULL;
  91. struct timespec timer_tp;
  92. volatile LONG request_count[2] = {0, 1}; // last one must be > 0
  93. HANDLE timer_request[2] = { NULL, NULL };
  94. HANDLE timer_response = NULL;
  95. // API globals
  96. bool api_winusb_available = false;
  97. #define CHECK_WINUSB_AVAILABLE do { if (!api_winusb_available) return LIBUSB_ERROR_ACCESS; } while (0)
  98. static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) {
  99. if ((guid1 != NULL) && (guid2 != NULL)) {
  100. return (memcmp(guid1, guid2, sizeof(GUID)) == 0);
  101. }
  102. return false;
  103. }
  104. #if defined(ENABLE_DEBUG_LOGGING) || (defined(_MSC_VER) && _MSC_VER < 1400)
  105. static char* guid_to_string(const GUID* guid)
  106. {
  107. static char guid_string[MAX_GUID_STRING_LENGTH];
  108. if (guid == NULL) return NULL;
  109. sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
  110. (unsigned int)guid->Data1, guid->Data2, guid->Data3,
  111. guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  112. guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  113. return guid_string;
  114. }
  115. #endif
  116. /*
  117. * Converts a windows error to human readable string
  118. * uses retval as errorcode, or, if 0, use GetLastError()
  119. */
  120. static char *windows_error_str(uint32_t retval)
  121. {
  122. static char err_string[ERR_BUFFER_SIZE];
  123. DWORD size;
  124. size_t i;
  125. uint32_t error_code, format_error;
  126. error_code = retval?retval:GetLastError();
  127. safe_sprintf(err_string, ERR_BUFFER_SIZE, "[%d] ", error_code);
  128. size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
  129. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &err_string[safe_strlen(err_string)],
  130. ERR_BUFFER_SIZE - (DWORD)safe_strlen(err_string), NULL);
  131. if (size == 0) {
  132. format_error = GetLastError();
  133. if (format_error)
  134. safe_sprintf(err_string, ERR_BUFFER_SIZE,
  135. "Windows error code %u (FormatMessage error code %u)", error_code, format_error);
  136. else
  137. safe_sprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", error_code);
  138. } else {
  139. // Remove CR/LF terminators
  140. for (i=safe_strlen(err_string)-1; ((err_string[i]==0x0A) || (err_string[i]==0x0D)); i--) {
  141. err_string[i] = 0;
  142. }
  143. }
  144. return err_string;
  145. }
  146. /*
  147. * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes.
  148. * Return an allocated sanitized string or NULL on error.
  149. */
  150. static char* sanitize_path(const char* path)
  151. {
  152. const char root_prefix[] = "\\\\.\\";
  153. size_t j, size, root_size;
  154. char* ret_path = NULL;
  155. size_t add_root = 0;
  156. if (path == NULL)
  157. return NULL;
  158. size = safe_strlen(path)+1;
  159. root_size = sizeof(root_prefix)-1;
  160. // Microsoft indiscriminatly uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes.
  161. if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) ||
  162. ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) {
  163. add_root = root_size;
  164. size += add_root;
  165. }
  166. if ((ret_path = (char*)calloc(size, 1)) == NULL)
  167. return NULL;
  168. safe_strcpy(&ret_path[add_root], size-add_root, path);
  169. // Ensure consistancy with root prefix
  170. for (j=0; j<root_size; j++)
  171. ret_path[j] = root_prefix[j];
  172. // Same goes for '\' and '#' after the root prefix. Ensure '#' is used
  173. for(j=root_size; j<size; j++) {
  174. ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too
  175. if (ret_path[j] == '\\')
  176. ret_path[j] = '#';
  177. }
  178. return ret_path;
  179. }
  180. /*
  181. * Cfgmgr32, OLE32 and SetupAPI DLL functions
  182. */
  183. static int init_dlls(void)
  184. {
  185. DLL_LOAD(Cfgmgr32.dll, CM_Get_Parent, TRUE);
  186. DLL_LOAD(Cfgmgr32.dll, CM_Get_Child, TRUE);
  187. DLL_LOAD(Cfgmgr32.dll, CM_Get_Sibling, TRUE);
  188. DLL_LOAD(Cfgmgr32.dll, CM_Get_Device_IDA, TRUE);
  189. // Prefixed to avoid conflict with header files
  190. DLL_LOAD_PREFIXED(OLE32.dll, p, CLSIDFromString, TRUE);
  191. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetClassDevsA, TRUE);
  192. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInfo, TRUE);
  193. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiEnumDeviceInterfaces, TRUE);
  194. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceInterfaceDetailA, TRUE);
  195. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiDestroyDeviceInfoList, TRUE);
  196. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiOpenDevRegKey, TRUE);
  197. DLL_LOAD_PREFIXED(SetupAPI.dll, p, SetupDiGetDeviceRegistryPropertyA, TRUE);
  198. DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegQueryValueExW, TRUE);
  199. DLL_LOAD_PREFIXED(AdvAPI32.dll, p, RegCloseKey, TRUE);
  200. return LIBUSB_SUCCESS;
  201. }
  202. /*
  203. * enumerate interfaces for the whole USB class
  204. *
  205. * Parameters:
  206. * dev_info: a pointer to a dev_info list
  207. * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
  208. * usb_class: the generic USB class for which to retrieve interface details
  209. * index: zero based index of the interface in the device info list
  210. *
  211. * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
  212. * structure returned and call this function repeatedly using the same guid (with an
  213. * incremented index starting at zero) until all interfaces have been returned.
  214. */
  215. static bool get_devinfo_data(struct libusb_context *ctx,
  216. HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, char* usb_class, unsigned _index)
  217. {
  218. if (_index <= 0) {
  219. *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
  220. if (*dev_info == INVALID_HANDLE_VALUE) {
  221. return false;
  222. }
  223. }
  224. dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
  225. if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
  226. if (GetLastError() != ERROR_NO_MORE_ITEMS) {
  227. usbi_err(ctx, "Could not obtain device info data for index %u: %s",
  228. _index, windows_error_str(0));
  229. }
  230. pSetupDiDestroyDeviceInfoList(*dev_info);
  231. *dev_info = INVALID_HANDLE_VALUE;
  232. return false;
  233. }
  234. return true;
  235. }
  236. /*
  237. * enumerate interfaces for a specific GUID
  238. *
  239. * Parameters:
  240. * dev_info: a pointer to a dev_info list
  241. * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
  242. * guid: the GUID for which to retrieve interface details
  243. * index: zero based index of the interface in the device info list
  244. *
  245. * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
  246. * structure returned and call this function repeatedly using the same guid (with an
  247. * incremented index starting at zero) until all interfaces have been returned.
  248. */
  249. static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx,
  250. HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID* guid, unsigned _index)
  251. {
  252. SP_DEVICE_INTERFACE_DATA dev_interface_data;
  253. SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
  254. DWORD size;
  255. if (_index <= 0) {
  256. *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
  257. }
  258. if (dev_info_data != NULL) {
  259. dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
  260. if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
  261. if (GetLastError() != ERROR_NO_MORE_ITEMS) {
  262. usbi_err(ctx, "Could not obtain device info data for index %u: %s",
  263. _index, windows_error_str(0));
  264. }
  265. pSetupDiDestroyDeviceInfoList(*dev_info);
  266. *dev_info = INVALID_HANDLE_VALUE;
  267. return NULL;
  268. }
  269. }
  270. dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  271. if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) {
  272. if (GetLastError() != ERROR_NO_MORE_ITEMS) {
  273. usbi_err(ctx, "Could not obtain interface data for index %u: %s",
  274. _index, windows_error_str(0));
  275. }
  276. pSetupDiDestroyDeviceInfoList(*dev_info);
  277. *dev_info = INVALID_HANDLE_VALUE;
  278. return NULL;
  279. }
  280. // Read interface data (dummy + actual) to access the device path
  281. if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
  282. // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
  283. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  284. usbi_err(ctx, "could not access interface data (dummy) for index %u: %s",
  285. _index, windows_error_str(0));
  286. goto err_exit;
  287. }
  288. } else {
  289. usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong.");
  290. goto err_exit;
  291. }
  292. if ((dev_interface_details = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) calloc(size, 1)) == NULL) {
  293. usbi_err(ctx, "could not allocate interface data for index %u.", _index);
  294. goto err_exit;
  295. }
  296. dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
  297. if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data,
  298. dev_interface_details, size, &size, NULL)) {
  299. usbi_err(ctx, "could not access interface data (actual) for index %u: %s",
  300. _index, windows_error_str(0));
  301. }
  302. return dev_interface_details;
  303. err_exit:
  304. pSetupDiDestroyDeviceInfoList(*dev_info);
  305. *dev_info = INVALID_HANDLE_VALUE;
  306. return NULL;
  307. }
  308. /* Hash table functions - modified From glibc 2.3.2:
  309. [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986
  310. [Knuth] The Art of Computer Programming, part 3 (6.4) */
  311. typedef struct htab_entry {
  312. unsigned long used;
  313. char* str;
  314. } htab_entry;
  315. htab_entry* htab_table = NULL;
  316. usbi_mutex_t htab_write_mutex = NULL;
  317. unsigned long htab_size, htab_filled;
  318. /* For the used double hash method the table size has to be a prime. To
  319. correct the user given table size we need a prime test. This trivial
  320. algorithm is adequate because the code is called only during init and
  321. the number is likely to be small */
  322. static int isprime(unsigned long number)
  323. {
  324. // no even number will be passed
  325. unsigned int divider = 3;
  326. while((divider * divider < number) && (number % divider != 0))
  327. divider += 2;
  328. return (number % divider != 0);
  329. }
  330. /* Before using the hash table we must allocate memory for it.
  331. We allocate one element more as the found prime number says.
  332. This is done for more effective indexing as explained in the
  333. comment for the hash function. */
  334. static int htab_create(struct libusb_context *ctx, unsigned long nel)
  335. {
  336. if (htab_table != NULL) {
  337. usbi_err(ctx, "hash table already allocated");
  338. }
  339. // Create a mutex
  340. usbi_mutex_init(&htab_write_mutex, NULL);
  341. // Change nel to the first prime number not smaller as nel.
  342. nel |= 1;
  343. while(!isprime(nel))
  344. nel += 2;
  345. htab_size = nel;
  346. usbi_dbg("using %d entries hash table", nel);
  347. htab_filled = 0;
  348. // allocate memory and zero out.
  349. htab_table = (htab_entry*)calloc(htab_size + 1, sizeof(htab_entry));
  350. if (htab_table == NULL) {
  351. usbi_err(ctx, "could not allocate space for hash table");
  352. return 0;
  353. }
  354. return 1;
  355. }
  356. /* After using the hash table it has to be destroyed. */
  357. static void htab_destroy(void)
  358. {
  359. size_t i;
  360. if (htab_table == NULL) {
  361. return;
  362. }
  363. for (i=0; i<htab_size; i++) {
  364. if (htab_table[i].used) {
  365. safe_free(htab_table[i].str);
  366. }
  367. }
  368. usbi_mutex_destroy(&htab_write_mutex);
  369. safe_free(htab_table);
  370. }
  371. /* This is the search function. It uses double hashing with open addressing.
  372. We use an trick to speed up the lookup. The table is created with one
  373. more element available. This enables us to use the index zero special.
  374. This index will never be used because we store the first hash index in
  375. the field used where zero means not used. Every other value means used.
  376. The used field can be used as a first fast comparison for equality of
  377. the stored and the parameter value. This helps to prevent unnecessary
  378. expensive calls of strcmp. */
  379. static unsigned long htab_hash(char* str)
  380. {
  381. unsigned long hval, hval2;
  382. unsigned long idx;
  383. unsigned long r = 5381;
  384. int c;
  385. char* sz = str;
  386. // Compute main hash value (algorithm suggested by Nokia)
  387. while ((c = *sz++))
  388. r = ((r << 5) + r) + c;
  389. if (r == 0)
  390. ++r;
  391. // compute table hash: simply take the modulus
  392. hval = r % htab_size;
  393. if (hval == 0)
  394. ++hval;
  395. // Try the first index
  396. idx = hval;
  397. if (htab_table[idx].used) {
  398. if ( (htab_table[idx].used == hval)
  399. && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
  400. // existing hash
  401. return idx;
  402. }
  403. usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str);
  404. // Second hash function, as suggested in [Knuth]
  405. hval2 = 1 + hval % (htab_size - 2);
  406. do {
  407. // Because size is prime this guarantees to step through all available indexes
  408. if (idx <= hval2) {
  409. idx = htab_size + idx - hval2;
  410. } else {
  411. idx -= hval2;
  412. }
  413. // If we visited all entries leave the loop unsuccessfully
  414. if (idx == hval) {
  415. break;
  416. }
  417. // If entry is found use it.
  418. if ( (htab_table[idx].used == hval)
  419. && (safe_strcmp(str, htab_table[idx].str) == 0) ) {
  420. return idx;
  421. }
  422. }
  423. while (htab_table[idx].used);
  424. }
  425. // Not found => New entry
  426. // If the table is full return an error
  427. if (htab_filled >= htab_size) {
  428. usbi_err(NULL, "hash table is full (%d entries)", htab_size);
  429. return 0;
  430. }
  431. // Concurrent threads might be storing the same entry at the same time
  432. // (eg. "simultaneous" enums from different threads) => use a mutex
  433. usbi_mutex_lock(&htab_write_mutex);
  434. // Just free any previously allocated string (which should be the same as
  435. // new one). The possibility of concurrent threads storing a collision
  436. // string (same hash, different string) at the same time is extremely low
  437. safe_free(htab_table[idx].str);
  438. htab_table[idx].used = hval;
  439. htab_table[idx].str = (char*) calloc(1, safe_strlen(str)+1);
  440. if (htab_table[idx].str == NULL) {
  441. usbi_err(NULL, "could not duplicate string for hash table");
  442. usbi_mutex_unlock(&htab_write_mutex);
  443. return 0;
  444. }
  445. memcpy(htab_table[idx].str, str, safe_strlen(str)+1);
  446. ++htab_filled;
  447. usbi_mutex_unlock(&htab_write_mutex);
  448. return idx;
  449. }
  450. /*
  451. * Returns the session ID of a device's nth level ancestor
  452. * If there's no device at the nth level, return 0
  453. */
  454. static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level)
  455. {
  456. DWORD parent_devinst;
  457. unsigned long session_id = 0;
  458. char* sanitized_path = NULL;
  459. char path[MAX_PATH_LENGTH];
  460. unsigned i;
  461. if (level < 1) return 0;
  462. for (i = 0; i<level; i++) {
  463. if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) {
  464. return 0;
  465. }
  466. devinst = parent_devinst;
  467. }
  468. if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) {
  469. return 0;
  470. }
  471. // TODO (post hotplug): try without sanitizing
  472. sanitized_path = sanitize_path(path);
  473. if (sanitized_path == NULL) {
  474. return 0;
  475. }
  476. session_id = htab_hash(sanitized_path);
  477. safe_free(sanitized_path);
  478. return session_id;
  479. }
  480. /*
  481. * Populate the endpoints addresses of the device_priv interface helper structs
  482. */
  483. static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting)
  484. {
  485. int i, r;
  486. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  487. struct libusb_config_descriptor *conf_desc;
  488. const struct libusb_interface_descriptor *if_desc;
  489. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  490. r = libusb_get_config_descriptor(dev_handle->dev, 0, &conf_desc);
  491. if (r != LIBUSB_SUCCESS) {
  492. usbi_warn(ctx, "could not read config descriptor: error %d", r);
  493. return r;
  494. }
  495. if_desc = &conf_desc->interface[iface].altsetting[altsetting];
  496. safe_free(priv->usb_interface[iface].endpoint);
  497. if (if_desc->bNumEndpoints == 0) {
  498. usbi_dbg("no endpoints found for interface %d", iface);
  499. return LIBUSB_SUCCESS;
  500. }
  501. priv->usb_interface[iface].endpoint = (uint8_t*) calloc(1, if_desc->bNumEndpoints);
  502. if (priv->usb_interface[iface].endpoint == NULL) {
  503. return LIBUSB_ERROR_NO_MEM;
  504. }
  505. priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
  506. for (i=0; i<if_desc->bNumEndpoints; i++) {
  507. priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
  508. usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface);
  509. }
  510. libusb_free_config_descriptor(conf_desc);
  511. // Extra init is required for WinUSB endpoints
  512. if (priv->apib->id == USB_API_WINUSB) {
  513. return winusb_configure_endpoints(dev_handle, iface);
  514. }
  515. return LIBUSB_SUCCESS;
  516. }
  517. // Lookup for a match in the list of API driver names
  518. static bool is_api_driver(char* driver, uint8_t api)
  519. {
  520. uint8_t i;
  521. const char sep_str[2] = {LIST_SEPARATOR, 0};
  522. char *tok, *tmp_str;
  523. size_t len = safe_strlen(driver);
  524. if (len == 0) return false;
  525. tmp_str = (char*) calloc(1, len+1);
  526. if (tmp_str == NULL) return false;
  527. memcpy(tmp_str, driver, len+1);
  528. tok = strtok(tmp_str, sep_str);
  529. while (tok != NULL) {
  530. for (i=0; i<usb_api_backend[api].nb_driver_names; i++) {
  531. if (safe_strcmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
  532. free(tmp_str);
  533. return true;
  534. }
  535. }
  536. tok = strtok(NULL, sep_str);
  537. }
  538. free (tmp_str);
  539. return false;
  540. }
  541. /*
  542. * auto-claiming and auto-release helper functions
  543. */
  544. static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
  545. {
  546. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  547. struct windows_device_handle_priv *handle_priv = _device_handle_priv(
  548. transfer->dev_handle);
  549. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  550. int current_interface = *interface_number;
  551. int r = LIBUSB_SUCCESS;
  552. usbi_mutex_lock(&autoclaim_lock);
  553. if (current_interface < 0) // No serviceable interface was found
  554. {
  555. for (current_interface=0; current_interface<USB_MAXINTERFACES; current_interface++) {
  556. // Must claim an interface of the same API type
  557. if ( (priv->usb_interface[current_interface].apib->id == api_type)
  558. && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS) ) {
  559. usbi_dbg("auto-claimed interface %d for control request", current_interface);
  560. if (handle_priv->autoclaim_count[current_interface] != 0) {
  561. usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero");
  562. }
  563. handle_priv->autoclaim_count[current_interface]++;
  564. break;
  565. }
  566. }
  567. if (current_interface == USB_MAXINTERFACES) {
  568. usbi_err(ctx, "could not auto-claim any interface");
  569. r = LIBUSB_ERROR_NOT_FOUND;
  570. }
  571. } else {
  572. // If we have a valid interface that was autoclaimed, we must increment
  573. // its autoclaim count so that we can prevent an early release.
  574. if (handle_priv->autoclaim_count[current_interface] != 0) {
  575. handle_priv->autoclaim_count[current_interface]++;
  576. }
  577. }
  578. usbi_mutex_unlock(&autoclaim_lock);
  579. *interface_number = current_interface;
  580. return r;
  581. }
  582. static void auto_release(struct usbi_transfer *itransfer)
  583. {
  584. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  585. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  586. libusb_device_handle *dev_handle = transfer->dev_handle;
  587. struct windows_device_handle_priv* handle_priv = _device_handle_priv(dev_handle);
  588. int r;
  589. usbi_mutex_lock(&autoclaim_lock);
  590. if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
  591. handle_priv->autoclaim_count[transfer_priv->interface_number]--;
  592. if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
  593. r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
  594. if (r == LIBUSB_SUCCESS) {
  595. usbi_dbg("auto-released interface %d", transfer_priv->interface_number);
  596. } else {
  597. usbi_dbg("failed to auto-release interface %d (%s)",
  598. transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
  599. }
  600. }
  601. }
  602. usbi_mutex_unlock(&autoclaim_lock);
  603. }
  604. /*
  605. * init: libusb backend init function
  606. *
  607. * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list
  608. * In our implementation, we equate Windows' "HCD" to LibUSB's "bus". Note that bus is zero indexed.
  609. * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?)
  610. */
  611. static int windows_init(struct libusb_context *ctx)
  612. {
  613. int i, r = LIBUSB_ERROR_OTHER;
  614. OSVERSIONINFO os_version;
  615. HANDLE semaphore;
  616. char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
  617. sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
  618. semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
  619. if (semaphore == NULL) {
  620. usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
  621. return LIBUSB_ERROR_NO_MEM;
  622. }
  623. // A successful wait brings our semaphore count to 0 (unsignaled)
  624. // => any concurent wait stalls until the semaphore's release
  625. if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
  626. usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
  627. CloseHandle(semaphore);
  628. return LIBUSB_ERROR_NO_MEM;
  629. }
  630. // NB: concurrent usage supposes that init calls are equally balanced with
  631. // exit calls. If init is called more than exit, we will not exit properly
  632. if ( ++concurrent_usage == 0 ) { // First init?
  633. // Detect OS version
  634. memset(&os_version, 0, sizeof(OSVERSIONINFO));
  635. os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  636. windows_version = WINDOWS_UNSUPPORTED;
  637. if ((GetVersionEx(&os_version) != 0) && (os_version.dwPlatformId == VER_PLATFORM_WIN32_NT)) {
  638. if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 1)) {
  639. windows_version = WINDOWS_XP;
  640. } else if ((os_version.dwMajorVersion == 5) && (os_version.dwMinorVersion == 2)) {
  641. windows_version = WINDOWS_2003; // also includes XP 64
  642. } else if (os_version.dwMajorVersion >= 6) {
  643. windows_version = WINDOWS_VISTA_AND_LATER;
  644. }
  645. }
  646. if (windows_version == WINDOWS_UNSUPPORTED) {
  647. usbi_err(ctx, "This version of Windows is NOT supported");
  648. r = LIBUSB_ERROR_NOT_SUPPORTED;
  649. goto init_exit;
  650. }
  651. // We need a lock for proper auto-release
  652. usbi_mutex_init(&autoclaim_lock, NULL);
  653. // Initialize pollable file descriptors
  654. init_polling();
  655. // Load DLL imports
  656. if (init_dlls() != LIBUSB_SUCCESS) {
  657. usbi_err(ctx, "could not resolve DLL functions");
  658. return LIBUSB_ERROR_NOT_FOUND;
  659. }
  660. // Initialize the low level APIs (we don't care about errors at this stage)
  661. for (i=0; i<USB_API_MAX; i++) {
  662. usb_api_backend[i].init(ctx);
  663. }
  664. // Because QueryPerformanceCounter might report different values when
  665. // running on different cores, we create a separate thread for the timer
  666. // calls, which we glue to the first core always to prevent timing discrepancies.
  667. r = LIBUSB_ERROR_NO_MEM;
  668. for (i = 0; i < 2; i++) {
  669. timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
  670. if (timer_request[i] == NULL) {
  671. usbi_err(ctx, "could not create timer request event %d - aborting", i);
  672. goto init_exit;
  673. }
  674. }
  675. timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
  676. if (timer_response == NULL) {
  677. usbi_err(ctx, "could not create timer response semaphore - aborting");
  678. goto init_exit;
  679. }
  680. timer_mutex = CreateMutex(NULL, FALSE, NULL);
  681. if (timer_mutex == NULL) {
  682. usbi_err(ctx, "could not create timer mutex - aborting");
  683. goto init_exit;
  684. }
  685. timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, NULL, 0, NULL);
  686. if (timer_thread == NULL) {
  687. usbi_err(ctx, "Unable to create timer thread - aborting");
  688. goto init_exit;
  689. }
  690. SetThreadAffinityMask(timer_thread, 0);
  691. // Create a hash table to store session ids. Second parameter is better if prime
  692. htab_create(ctx, HTAB_SIZE);
  693. }
  694. // At this stage, either we went through full init successfully, or didn't need to
  695. r = LIBUSB_SUCCESS;
  696. init_exit: // Holds semaphore here.
  697. if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
  698. if (timer_thread) {
  699. SetEvent(timer_request[1]); // actually the signal to quit the thread.
  700. if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
  701. usbi_warn(ctx, "could not wait for timer thread to quit");
  702. TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
  703. // all objects it might have held anyway.
  704. }
  705. CloseHandle(timer_thread);
  706. timer_thread = NULL;
  707. }
  708. for (i = 0; i < 2; i++) {
  709. if (timer_request[i]) {
  710. CloseHandle(timer_request[i]);
  711. timer_request[i] = NULL;
  712. }
  713. }
  714. if (timer_response) {
  715. CloseHandle(timer_response);
  716. timer_response = NULL;
  717. }
  718. if (timer_mutex) {
  719. CloseHandle(timer_mutex);
  720. timer_mutex = NULL;
  721. }
  722. htab_destroy();
  723. }
  724. if (r != LIBUSB_SUCCESS)
  725. --concurrent_usage; // Not expected to call libusb_exit if we failed.
  726. ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
  727. CloseHandle(semaphore);
  728. return r;
  729. }
  730. /*
  731. * HCD (root) hubs need to have their device descriptor manually populated
  732. *
  733. * Note that, like Microsoft does in the device manager, we populate the
  734. * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device.
  735. */
  736. static int force_hcd_device_descriptor(struct libusb_device *dev)
  737. {
  738. struct windows_device_priv *parent_priv, *priv = _device_priv(dev);
  739. struct libusb_context *ctx = DEVICE_CTX(dev);
  740. int vid, pid;
  741. dev->num_configurations = 1;
  742. priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR);
  743. priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE;
  744. priv->dev_descriptor.bNumConfigurations = 1;
  745. priv->active_config = 1;
  746. if (priv->parent_dev == NULL) {
  747. usbi_err(ctx, "program assertion failed - HCD hub has no parent");
  748. return LIBUSB_ERROR_NO_DEVICE;
  749. }
  750. parent_priv = _device_priv(priv->parent_dev);
  751. if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) {
  752. priv->dev_descriptor.idVendor = (uint16_t)vid;
  753. priv->dev_descriptor.idProduct = (uint16_t)pid;
  754. } else {
  755. usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path);
  756. priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub
  757. priv->dev_descriptor.idProduct = 1;
  758. }
  759. return LIBUSB_SUCCESS;
  760. }
  761. /*
  762. * fetch and cache all the config descriptors through I/O
  763. */
  764. static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char* device_id)
  765. {
  766. DWORD size, ret_size;
  767. struct libusb_context *ctx = DEVICE_CTX(dev);
  768. struct windows_device_priv *priv = _device_priv(dev);
  769. int r;
  770. uint8_t i;
  771. USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
  772. PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
  773. PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL;
  774. if (dev->num_configurations == 0)
  775. return LIBUSB_ERROR_INVALID_PARAM;
  776. priv->config_descriptor = (unsigned char**) calloc(dev->num_configurations, sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
  777. if (priv->config_descriptor == NULL)
  778. return LIBUSB_ERROR_NO_MEM;
  779. for (i=0; i<dev->num_configurations; i++)
  780. priv->config_descriptor[i] = NULL;
  781. for (i=0, r=LIBUSB_SUCCESS; ; i++)
  782. {
  783. // safe loop: release all dynamic resources
  784. safe_free(cd_buf_actual);
  785. // safe loop: end of loop condition
  786. if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS))
  787. break;
  788. size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT);
  789. memset(&cd_buf_short, 0, size);
  790. cd_buf_short.req.ConnectionIndex = (ULONG)priv->port;
  791. cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
  792. cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
  793. cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
  794. cd_buf_short.req.SetupPacket.wIndex = i;
  795. cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
  796. // Dummy call to get the required data size
  797. if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
  798. &cd_buf_short, size, &ret_size, NULL)) {
  799. usbi_err(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0));
  800. LOOP_BREAK(LIBUSB_ERROR_IO);
  801. }
  802. if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
  803. usbi_err(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id);
  804. LOOP_BREAK(LIBUSB_ERROR_IO);
  805. }
  806. size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength;
  807. if ((cd_buf_actual = (PUSB_DESCRIPTOR_REQUEST) calloc(1, size)) == NULL) {
  808. usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id);
  809. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  810. }
  811. memset(cd_buf_actual, 0, size);
  812. // Actual call
  813. cd_buf_actual->ConnectionIndex = (ULONG)priv->port;
  814. cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
  815. cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR;
  816. cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i;
  817. cd_buf_actual->SetupPacket.wIndex = i;
  818. cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST));
  819. if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
  820. cd_buf_actual, size, &ret_size, NULL)) {
  821. usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0));
  822. LOOP_BREAK(LIBUSB_ERROR_IO);
  823. }
  824. cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR*)cd_buf_actual+sizeof(USB_DESCRIPTOR_REQUEST));
  825. if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) {
  826. usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id);
  827. LOOP_BREAK(LIBUSB_ERROR_IO);
  828. }
  829. if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) {
  830. usbi_err(ctx, "not a configuration descriptor for '%s'", device_id);
  831. LOOP_BREAK(LIBUSB_ERROR_IO);
  832. }
  833. usbi_dbg("cached config descriptor %d (bConfigurationValue=%d, %d bytes)",
  834. i, cd_data->bConfigurationValue, cd_data->wTotalLength);
  835. // Cache the descriptor
  836. priv->config_descriptor[i] = (unsigned char*) calloc(1, cd_data->wTotalLength);
  837. if (priv->config_descriptor[i] == NULL)
  838. return LIBUSB_ERROR_NO_MEM;
  839. memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength);
  840. }
  841. return LIBUSB_SUCCESS;
  842. }
  843. /*
  844. * Populate a libusb device structure
  845. */
  846. static int init_device(struct libusb_device* dev, struct libusb_device* parent_dev,
  847. uint8_t port_number, char* device_id, DWORD devinst)
  848. {
  849. HANDLE handle;
  850. DWORD size;
  851. USB_NODE_CONNECTION_INFORMATION_EX conn_info;
  852. struct windows_device_priv *priv, *parent_priv;
  853. struct libusb_context *ctx = DEVICE_CTX(dev);
  854. struct libusb_device* tmp_dev;
  855. unsigned i;
  856. if ((dev == NULL) || (parent_dev == NULL)) {
  857. return LIBUSB_ERROR_NOT_FOUND;
  858. }
  859. priv = _device_priv(dev);
  860. parent_priv = _device_priv(parent_dev);
  861. if (parent_priv->apib->id != USB_API_HUB) {
  862. usbi_warn(ctx, "parent for device '%s' is not a hub", device_id);
  863. return LIBUSB_ERROR_NOT_FOUND;
  864. }
  865. // It is possible for the parent hub not to have been initialized yet
  866. // If that's the case, lookup the ancestors to set the bus number
  867. if (parent_dev->bus_number == 0) {
  868. for (i=2; ; i++) {
  869. tmp_dev = usbi_get_device_by_session_id(ctx, get_ancestor_session_id(devinst, i));
  870. if (tmp_dev == NULL) break;
  871. if (tmp_dev->bus_number != 0) {
  872. usbi_dbg("got bus number from ancestor #%d", i);
  873. parent_dev->bus_number = tmp_dev->bus_number;
  874. break;
  875. }
  876. }
  877. }
  878. if (parent_dev->bus_number == 0) {
  879. usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id);
  880. return LIBUSB_ERROR_NOT_FOUND;
  881. }
  882. dev->bus_number = parent_dev->bus_number;
  883. priv->port = port_number;
  884. priv->depth = parent_priv->depth + 1;
  885. priv->parent_dev = parent_dev;
  886. // If the device address is already set, we can stop here
  887. if (dev->device_address != 0) {
  888. return LIBUSB_SUCCESS;
  889. }
  890. memset(&conn_info, 0, sizeof(conn_info));
  891. if (priv->depth != 0) { // Not a HCD hub
  892. handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
  893. FILE_FLAG_OVERLAPPED, NULL);
  894. if (handle == INVALID_HANDLE_VALUE) {
  895. usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
  896. return LIBUSB_ERROR_ACCESS;
  897. }
  898. size = sizeof(conn_info);
  899. conn_info.ConnectionIndex = (ULONG)port_number;
  900. if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size,
  901. &conn_info, size, &size, NULL)) {
  902. usbi_warn(ctx, "could not get node connection information for device '%s': %s",
  903. device_id, windows_error_str(0));
  904. safe_closehandle(handle);
  905. return LIBUSB_ERROR_NO_DEVICE;
  906. }
  907. if (conn_info.ConnectionStatus == NoDeviceConnected) {
  908. usbi_err(ctx, "device '%s' is no longer connected!", device_id);
  909. safe_closehandle(handle);
  910. return LIBUSB_ERROR_NO_DEVICE;
  911. }
  912. memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR));
  913. dev->num_configurations = priv->dev_descriptor.bNumConfigurations;
  914. priv->active_config = conn_info.CurrentConfigurationValue;
  915. usbi_dbg("found %d configurations (active conf: %d)", dev->num_configurations, priv->active_config);
  916. // If we can't read the config descriptors, just set the number of confs to zero
  917. if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) {
  918. dev->num_configurations = 0;
  919. priv->dev_descriptor.bNumConfigurations = 0;
  920. }
  921. safe_closehandle(handle);
  922. if (conn_info.DeviceAddress > UINT8_MAX) {
  923. usbi_err(ctx, "program assertion failed: device address overflow");
  924. }
  925. dev->device_address = (uint8_t)conn_info.DeviceAddress;
  926. switch (conn_info.Speed) {
  927. case 0: dev->speed = LIBUSB_SPEED_LOW; break;
  928. case 1: dev->speed = LIBUSB_SPEED_FULL; break;
  929. case 2: dev->speed = LIBUSB_SPEED_HIGH; break;
  930. case 3: dev->speed = LIBUSB_SPEED_SUPER; break;
  931. default:
  932. usbi_warn(ctx, "Got unknown device speed %d", conn_info.Speed);
  933. break;
  934. }
  935. } else {
  936. dev->device_address = UINT8_MAX; // Hubs from HCD have a devaddr of 255
  937. force_hcd_device_descriptor(dev);
  938. }
  939. usbi_sanitize_device(dev);
  940. usbi_dbg("(bus: %d, addr: %d, depth: %d, port: %d): '%s'",
  941. dev->bus_number, dev->device_address, priv->depth, priv->port, device_id);
  942. return LIBUSB_SUCCESS;
  943. }
  944. // Returns the api type, or 0 if not found/unsupported
  945. static uint8_t get_api_type(struct libusb_context *ctx,
  946. HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data)
  947. {
  948. // Precedence for filter drivers vs driver is in the order of this array
  949. struct driver_lookup lookup[3] = {
  950. {"\0\0", SPDRP_SERVICE, "driver"},
  951. {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
  952. {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
  953. };
  954. DWORD size, reg_type;
  955. unsigned k, l;
  956. uint8_t api;
  957. // Check the service & filter names to know the API we should use
  958. for (k=0; k<3; k++) {
  959. if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
  960. &reg_type, (BYTE*)lookup[k].list, MAX_KEY_LENGTH, &size)) {
  961. // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
  962. if (lookup[k].reg_prop == SPDRP_SERVICE) {
  963. // our buffers are MAX_KEY_LENGTH+1 so we can overflow if needed
  964. lookup[k].list[safe_strlen(lookup[k].list)+1] = 0;
  965. }
  966. // MULTI_SZ is a pain to work with. Turn it into something much more manageable
  967. // NB: none of the driver names we check against contain LIST_SEPARATOR,
  968. // (currently ';'), so even if an unsuported one does, it's not an issue
  969. for (l=0; (lookup[k].list[l] != 0) || (lookup[k].list[l+1] != 0); l++) {
  970. if (lookup[k].list[l] == 0) {
  971. lookup[k].list[l] = LIST_SEPARATOR;
  972. }
  973. }
  974. upperize(lookup[k].list);
  975. usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list);
  976. } else {
  977. if (GetLastError() != ERROR_INVALID_DATA) {
  978. usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0));
  979. }
  980. lookup[k].list[0] = 0;
  981. }
  982. }
  983. for (api=1; api<USB_API_MAX; api++) {
  984. for (k=0; k<3; k++) {
  985. if (is_api_driver(lookup[k].list, api)) {
  986. usbi_dbg("matched %s name against %s", lookup[k].designation, usb_api_backend[api].designation);
  987. break;
  988. }
  989. }
  990. if (k >= 3) continue;
  991. return api;
  992. }
  993. return 0;
  994. }
  995. static int set_composite_interface(struct libusb_context* ctx, struct libusb_device* dev,
  996. char* dev_interface_path, char* device_id, uint8_t api)
  997. {
  998. unsigned i;
  999. struct windows_device_priv *priv = _device_priv(dev);
  1000. int interface_number;
  1001. if (priv->apib->id != USB_API_COMPOSITE) {
  1002. usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id);
  1003. return LIBUSB_ERROR_NO_DEVICE;
  1004. }
  1005. // Because MI_## are not necessarily in sequential order (some composite
  1006. // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
  1007. // interface number from the path's MI value
  1008. interface_number = 0;
  1009. for (i=0; device_id[i] != 0; ) {
  1010. if ( (device_id[i++] == 'M') && (device_id[i++] == 'I')
  1011. && (device_id[i++] == '_') ) {
  1012. interface_number = (device_id[i++] - '0')*10;
  1013. interface_number += device_id[i] - '0';
  1014. break;
  1015. }
  1016. }
  1017. if (device_id[i] == 0) {
  1018. usbi_warn(ctx, "failure to read interface number for %s. Using default value %d",
  1019. device_id, interface_number);
  1020. }
  1021. if (priv->usb_interface[interface_number].path != NULL) {
  1022. usbi_warn(ctx, "interface[%d] already set - ignoring: %s", interface_number, device_id);
  1023. return LIBUSB_ERROR_ACCESS;
  1024. }
  1025. usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path);
  1026. priv->usb_interface[interface_number].path = dev_interface_path;
  1027. priv->usb_interface[interface_number].apib = &usb_api_backend[api];
  1028. priv->composite_api_flags |= 1<<api;
  1029. return LIBUSB_SUCCESS;
  1030. }
  1031. /*
  1032. * get_device_list: libusb backend device enumeration function
  1033. */
  1034. static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
  1035. {
  1036. struct discovered_devs *discdevs;
  1037. HDEVINFO dev_info = { 0 };
  1038. char* usb_class[2] = {"USB", "NUSB3"};
  1039. SP_DEVINFO_DATA dev_info_data;
  1040. SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL;
  1041. #define MAX_ENUM_GUIDS 64
  1042. const GUID* guid[MAX_ENUM_GUIDS];
  1043. #define HCD_PASS 0
  1044. #define HUB_PASS 1
  1045. #define GEN_PASS 2
  1046. #define DEV_PASS 3
  1047. int r = LIBUSB_SUCCESS;
  1048. int class_index = 0;
  1049. unsigned int nb_guids, pass, i, j, ancestor;
  1050. char path[MAX_PATH_LENGTH];
  1051. char strbuf[MAX_PATH_LENGTH];
  1052. struct libusb_device *dev, *parent_dev;
  1053. struct windows_device_priv *priv, *parent_priv;
  1054. char* dev_interface_path = NULL;
  1055. char* dev_id_path = NULL;
  1056. unsigned long session_id;
  1057. DWORD size, reg_type, port_nr, install_state;
  1058. BOOL b = FALSE;
  1059. HKEY key;
  1060. WCHAR guid_string_w[MAX_GUID_STRING_LENGTH];
  1061. GUID* if_guid;
  1062. LONG s;
  1063. uint8_t api;
  1064. // Keep a list of newly allocated devs to unref
  1065. libusb_device** unref_list;
  1066. unsigned int unref_size = 64;
  1067. unsigned int unref_cur = 0;
  1068. // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
  1069. // PASS 2 : (re)enumerate HUBS
  1070. // PASS 3 : (re)enumerate generic USB devices (including driverless)
  1071. // and list additional USB device interface GUIDs to explore
  1072. // PASS 4 : (re)enumerate master USB devices that have a device interface
  1073. // PASS 5+: (re)enumerate device interfaced GUIDs and set the device interfaces.
  1074. // Init the GUID table
  1075. guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
  1076. guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
  1077. guid[GEN_PASS] = NULL;
  1078. guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
  1079. nb_guids = DEV_PASS+1;
  1080. unref_list = (libusb_device**) calloc(unref_size, sizeof(libusb_device*));
  1081. if (unref_list == NULL) {
  1082. return LIBUSB_ERROR_NO_MEM;
  1083. }
  1084. for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
  1085. //#define ENUM_DEBUG
  1086. #ifdef ENUM_DEBUG
  1087. switch(pass) {
  1088. case HCD_PASS:
  1089. usbi_dbg("PROCESSING HCDs %s", guid_to_string(guid[pass]));
  1090. break;
  1091. case HUB_PASS:
  1092. usbi_dbg("PROCESSING HUBs %s", guid_to_string(guid[pass]));
  1093. break;
  1094. case DEV_PASS:
  1095. usbi_dbg("PROCESSING DEVs %s", guid_to_string(guid[pass]));
  1096. break;
  1097. case GEN_PASS:
  1098. usbi_dbg("PROCESSING GENs");
  1099. break;
  1100. default:
  1101. usbi_dbg("PROCESSING EXTs %s", guid_to_string(guid[pass]));
  1102. break;
  1103. }
  1104. #endif
  1105. for (i = 0; ; i++) {
  1106. // safe loop: free up any (unprotected) dynamic resource
  1107. // NB: this is always executed before breaking the loop
  1108. safe_free(dev_interface_details);
  1109. safe_free(dev_interface_path);
  1110. safe_free(dev_id_path);
  1111. priv = parent_priv = NULL;
  1112. dev = parent_dev = NULL;
  1113. // Safe loop: end of loop conditions
  1114. if (r != LIBUSB_SUCCESS) {
  1115. break;
  1116. }
  1117. if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
  1118. usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX);
  1119. break;
  1120. }
  1121. if (pass != GEN_PASS) {
  1122. // Except for GEN, all passes deal with device interfaces
  1123. dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i);
  1124. if (dev_interface_details == NULL) {
  1125. break;
  1126. } else {
  1127. dev_interface_path = sanitize_path(dev_interface_details->DevicePath);
  1128. if (dev_interface_path == NULL) {
  1129. usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath);
  1130. continue;
  1131. }
  1132. }
  1133. } else {
  1134. // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
  1135. // being listed under the "NUSB3" PnP Symbolic Name rather than "USB"
  1136. while ( (class_index < 2) &&
  1137. (!(b = get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i))) ) {
  1138. class_index++;
  1139. i = 0;
  1140. }
  1141. if (!b) break;
  1142. }
  1143. // Read the Device ID path. This is what we'll use as UID
  1144. // Note that if the device is plugged in a different port or hub, the Device ID changes
  1145. if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) {
  1146. usbi_warn(ctx, "could not read the device id path for devinst %X, skipping",
  1147. dev_info_data.DevInst);
  1148. continue;
  1149. }
  1150. dev_id_path = sanitize_path(path);
  1151. if (dev_id_path == NULL) {
  1152. usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping",
  1153. dev_info_data.DevInst);
  1154. continue;
  1155. }
  1156. #ifdef ENUM_DEBUG
  1157. usbi_dbg("PRO: %s", dev_id_path);
  1158. #endif
  1159. // The SPDRP_ADDRESS for USB devices is the device port number on the hub
  1160. port_nr = 0;
  1161. if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) {
  1162. if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS,
  1163. &reg_type, (BYTE*)&port_nr, 4, &size))
  1164. || (size != 4) ) {
  1165. usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s",
  1166. dev_id_path, windows_error_str(0));
  1167. continue;
  1168. }
  1169. }
  1170. // Set API to use or get additional data from generic pass
  1171. api = USB_API_UNSUPPORTED;
  1172. switch (pass) {
  1173. case HCD_PASS:
  1174. break;
  1175. case GEN_PASS:
  1176. // We use the GEN pass to detect driverless devices...
  1177. size = sizeof(strbuf);
  1178. if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER,
  1179. &reg_type, (BYTE*)strbuf, size, &size)) {
  1180. usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path);
  1181. usbi_info(ctx, "libusb will not be able to access it.");
  1182. }
  1183. // ...and to add the additional device interface GUIDs
  1184. key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
  1185. if (key != INVALID_HANDLE_VALUE) {
  1186. size = sizeof(guid_string_w);
  1187. s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, &reg_type,
  1188. (BYTE*)guid_string_w, &size);
  1189. pRegCloseKey(key);
  1190. if (s == ERROR_SUCCESS) {
  1191. if (nb_guids >= MAX_ENUM_GUIDS) {
  1192. // If this assert is ever reported, grow a GUID table dynamically
  1193. usbi_err(ctx, "program assertion failed: too many GUIDs");
  1194. LOOP_BREAK(LIBUSB_ERROR_OVERFLOW);
  1195. }
  1196. if_guid = (GUID*) calloc(1, sizeof(GUID));
  1197. pCLSIDFromString(guid_string_w, if_guid);
  1198. guid[nb_guids++] = if_guid;
  1199. usbi_dbg("extra GUID: %s", guid_to_string(if_guid));
  1200. }
  1201. }
  1202. break;
  1203. default:
  1204. // Get the API type (after checking that the driver installation is OK)
  1205. if ( (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
  1206. &reg_type, (BYTE*)&install_state, 4, &size))
  1207. || (size != 4) ){
  1208. usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
  1209. dev_id_path, windows_error_str(0));
  1210. } else if (install_state != 0) {
  1211. usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %d) - skipping",
  1212. dev_id_path, install_state);
  1213. continue;
  1214. }
  1215. api = get_api_type(ctx, &dev_info, &dev_info_data);
  1216. break;
  1217. }
  1218. // Find parent device (for the passes that need it)
  1219. switch (pass) {
  1220. case HCD_PASS:
  1221. case DEV_PASS:
  1222. case HUB_PASS:
  1223. break;
  1224. default:
  1225. // Go through the ancestors until we see a face we recognize
  1226. parent_dev = NULL;
  1227. for (ancestor = 1; parent_dev == NULL; ancestor++) {
  1228. session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor);
  1229. if (session_id == 0) {
  1230. break;
  1231. }
  1232. parent_dev = usbi_get_device_by_session_id(ctx, session_id);
  1233. }
  1234. if (parent_dev == NULL) {
  1235. usbi_dbg("unlisted ancestor for '%s' (newly connected, etc.) - ignoring", dev_id_path);
  1236. continue;
  1237. }
  1238. parent_priv = _device_priv(parent_dev);
  1239. // virtual USB devices are also listed during GEN - don't process these yet
  1240. if ( (pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB) ) {
  1241. continue;
  1242. }
  1243. break;
  1244. }
  1245. // Create new or match existing device, using the (hashed) device_id as session id
  1246. if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent
  1247. // These are the passes that create "new" devices
  1248. session_id = htab_hash(dev_id_path);
  1249. dev = usbi_get_device_by_session_id(ctx, session_id);
  1250. if (dev == NULL) {
  1251. if (pass == DEV_PASS) {
  1252. // This can occur if the OS only reports a newly plugged device after we started enum
  1253. usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)"
  1254. " - ignoring", dev_id_path);
  1255. continue;
  1256. }
  1257. usbi_dbg("allocating new device for session [%X]", session_id);
  1258. if ((dev = usbi_alloc_device(ctx, session_id)) == NULL) {
  1259. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1260. }
  1261. windows_device_priv_init(dev);
  1262. // Keep track of devices that need unref
  1263. unref_list[unref_cur++] = dev;
  1264. if (unref_cur >= unref_size) {
  1265. unref_size += 64;
  1266. unref_list = realloc(unref_list, unref_size*sizeof(libusb_device*));
  1267. if (unref_list == NULL) {
  1268. usbi_err(ctx, "could not realloc list for unref - aborting.");
  1269. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1270. }
  1271. }
  1272. } else {
  1273. usbi_dbg("found existing device for session [%X] (%d.%d)",
  1274. session_id, dev->bus_number, dev->device_address);
  1275. }
  1276. priv = _device_priv(dev);
  1277. }
  1278. // Setup device
  1279. switch (pass) {
  1280. case HCD_PASS:
  1281. dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected
  1282. dev->device_address = 0;
  1283. dev->num_configurations = 0;
  1284. priv->apib = &usb_api_backend[USB_API_HUB];
  1285. priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs
  1286. priv->path = dev_interface_path; dev_interface_path = NULL;
  1287. break;
  1288. case HUB_PASS:
  1289. case DEV_PASS:
  1290. // If the device has already been setup, don't do it again
  1291. if (priv->path != NULL)
  1292. break;
  1293. // Take care of API initialization
  1294. priv->path = dev_interface_path; dev_interface_path = NULL;
  1295. priv->apib = &usb_api_backend[api];
  1296. switch(api) {
  1297. case USB_API_COMPOSITE:
  1298. case USB_API_HUB:
  1299. break;
  1300. default:
  1301. // For other devices, the first interface is the same as the device
  1302. priv->usb_interface[0].path = (char*) calloc(safe_strlen(priv->path)+1, 1);
  1303. if (priv->usb_interface[0].path != NULL) {
  1304. safe_strcpy(priv->usb_interface[0].path, safe_strlen(priv->path)+1, priv->path);
  1305. } else {
  1306. usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path);
  1307. }
  1308. // The following is needed if we want API calls to work for both simple
  1309. // and composite devices.
  1310. for(j=0; j<USB_MAXINTERFACES; j++) {
  1311. priv->usb_interface[j].apib = &usb_api_backend[api];
  1312. }
  1313. break;
  1314. }
  1315. break;
  1316. case GEN_PASS:
  1317. r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst);
  1318. if (r == LIBUSB_SUCCESS) {
  1319. // Append device to the list of discovered devices
  1320. discdevs = discovered_devs_append(*_discdevs, dev);
  1321. if (!discdevs) {
  1322. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1323. }
  1324. *_discdevs = discdevs;
  1325. } else if (r == LIBUSB_ERROR_NO_DEVICE) {
  1326. // This can occur if the device was disconnected but Windows hasn't
  1327. // refreshed its enumeration yet - in that case, we ignore the device
  1328. r = LIBUSB_SUCCESS;
  1329. }
  1330. break;
  1331. default: // later passes
  1332. if (parent_priv->apib->id == USB_API_COMPOSITE) {
  1333. usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data);
  1334. switch (set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api)) {
  1335. case LIBUSB_SUCCESS:
  1336. dev_interface_path = NULL;
  1337. break;
  1338. case LIBUSB_ERROR_ACCESS:
  1339. // interface has already been set => make sure dev_interface_path is freed then
  1340. break;
  1341. default:
  1342. LOOP_BREAK(r);
  1343. break;
  1344. }
  1345. }
  1346. break;
  1347. }
  1348. }
  1349. }
  1350. // Free any additional GUIDs
  1351. for (pass = DEV_PASS+1; pass < nb_guids; pass++) {
  1352. safe_free(guid[pass]);
  1353. }
  1354. // Unref newly allocated devs
  1355. for (i=0; i<unref_cur; i++) {
  1356. safe_unref_device(unref_list[i]);
  1357. }
  1358. safe_free(unref_list);
  1359. return r;
  1360. }
  1361. /*
  1362. * exit: libusb backend deinitialization function
  1363. */
  1364. static void windows_exit(void)
  1365. {
  1366. int i;
  1367. HANDLE semaphore;
  1368. char sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
  1369. sprintf(sem_name, "libusb_init%08X", (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
  1370. semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name);
  1371. if (semaphore == NULL) {
  1372. return;
  1373. }
  1374. // A successful wait brings our semaphore count to 0 (unsignaled)
  1375. // => any concurent wait stalls until the semaphore release
  1376. if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
  1377. CloseHandle(semaphore);
  1378. return;
  1379. }
  1380. // Only works if exits and inits are balanced exactly
  1381. if (--concurrent_usage < 0) { // Last exit
  1382. for (i=0; i<USB_API_MAX; i++) {
  1383. usb_api_backend[i].exit();
  1384. }
  1385. exit_polling();
  1386. if (timer_thread) {
  1387. SetEvent(timer_request[1]); // actually the signal to quit the thread.
  1388. if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
  1389. usbi_dbg("could not wait for timer thread to quit");
  1390. TerminateThread(timer_thread, 1);
  1391. }
  1392. CloseHandle(timer_thread);
  1393. timer_thread = NULL;
  1394. }
  1395. for (i = 0; i < 2; i++) {
  1396. if (timer_request[i]) {
  1397. CloseHandle(timer_request[i]);
  1398. timer_request[i] = NULL;
  1399. }
  1400. }
  1401. if (timer_response) {
  1402. CloseHandle(timer_response);
  1403. timer_response = NULL;
  1404. }
  1405. if (timer_mutex) {
  1406. CloseHandle(timer_mutex);
  1407. timer_mutex = NULL;
  1408. }
  1409. htab_destroy();
  1410. }
  1411. ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
  1412. CloseHandle(semaphore);
  1413. }
  1414. static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian)
  1415. {
  1416. struct windows_device_priv *priv = _device_priv(dev);
  1417. memcpy(buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH);
  1418. *host_endian = 0;
  1419. return LIBUSB_SUCCESS;
  1420. }
  1421. static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
  1422. {
  1423. struct windows_device_priv *priv = _device_priv(dev);
  1424. PUSB_CONFIGURATION_DESCRIPTOR config_header;
  1425. size_t size;
  1426. // config index is zero based
  1427. if (config_index >= dev->num_configurations)
  1428. return LIBUSB_ERROR_INVALID_PARAM;
  1429. if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
  1430. return LIBUSB_ERROR_NOT_FOUND;
  1431. config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index];
  1432. size = min(config_header->wTotalLength, len);
  1433. memcpy(buffer, priv->config_descriptor[config_index], size);
  1434. return LIBUSB_SUCCESS;
  1435. }
  1436. /*
  1437. * return the cached copy of the active config descriptor
  1438. */
  1439. static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian)
  1440. {
  1441. struct windows_device_priv *priv = _device_priv(dev);
  1442. if (priv->active_config == 0)
  1443. return LIBUSB_ERROR_NOT_FOUND;
  1444. // config index is zero based
  1445. return windows_get_config_descriptor(dev, (uint8_t)(priv->active_config-1), buffer, len, host_endian);
  1446. }
  1447. static int windows_open(struct libusb_device_handle *dev_handle)
  1448. {
  1449. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1450. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  1451. if (priv->apib == NULL) {
  1452. usbi_err(ctx, "program assertion failed - device is not initialized");
  1453. return LIBUSB_ERROR_NO_DEVICE;
  1454. }
  1455. return priv->apib->open(dev_handle);
  1456. }
  1457. static void windows_close(struct libusb_device_handle *dev_handle)
  1458. {
  1459. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1460. priv->apib->close(dev_handle);
  1461. }
  1462. static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config)
  1463. {
  1464. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1465. if (priv->active_config == 0) {
  1466. *config = 0;
  1467. return LIBUSB_ERROR_NOT_FOUND;
  1468. }
  1469. *config = priv->active_config;
  1470. return LIBUSB_SUCCESS;
  1471. }
  1472. /*
  1473. * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
  1474. * does not currently expose a service that allows higher-level drivers to set
  1475. * the configuration."
  1476. */
  1477. static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config)
  1478. {
  1479. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1480. int r = LIBUSB_SUCCESS;
  1481. if (config >= USB_MAXCONFIG)
  1482. return LIBUSB_ERROR_INVALID_PARAM;
  1483. r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
  1484. LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
  1485. LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config,
  1486. 0, NULL, 0, 1000);
  1487. if (r == LIBUSB_SUCCESS) {
  1488. priv->active_config = (uint8_t)config;
  1489. }
  1490. return r;
  1491. }
  1492. static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface)
  1493. {
  1494. int r = LIBUSB_SUCCESS;
  1495. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1496. if (iface >= USB_MAXINTERFACES)
  1497. return LIBUSB_ERROR_INVALID_PARAM;
  1498. safe_free(priv->usb_interface[iface].endpoint);
  1499. priv->usb_interface[iface].nb_endpoints= 0;
  1500. r = priv->apib->claim_interface(dev_handle, iface);
  1501. if (r == LIBUSB_SUCCESS) {
  1502. r = windows_assign_endpoints(dev_handle, iface, 0);
  1503. }
  1504. return r;
  1505. }
  1506. static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
  1507. {
  1508. int r = LIBUSB_SUCCESS;
  1509. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1510. safe_free(priv->usb_interface[iface].endpoint);
  1511. priv->usb_interface[iface].nb_endpoints= 0;
  1512. r = priv->apib->set_interface_altsetting(dev_handle, iface, altsetting);
  1513. if (r == LIBUSB_SUCCESS) {
  1514. r = windows_assign_endpoints(dev_handle, iface, altsetting);
  1515. }
  1516. return r;
  1517. }
  1518. static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface)
  1519. {
  1520. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1521. return priv->apib->release_interface(dev_handle, iface);
  1522. }
  1523. static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
  1524. {
  1525. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1526. return priv->apib->clear_halt(dev_handle, endpoint);
  1527. }
  1528. static int windows_reset_device(struct libusb_device_handle *dev_handle)
  1529. {
  1530. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  1531. return priv->apib->reset_device(dev_handle);
  1532. }
  1533. // The 3 functions below are unlikely to ever get supported on Windows
  1534. static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface)
  1535. {
  1536. return LIBUSB_ERROR_NOT_SUPPORTED;
  1537. }
  1538. static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
  1539. {
  1540. return LIBUSB_ERROR_NOT_SUPPORTED;
  1541. }
  1542. static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface)
  1543. {
  1544. return LIBUSB_ERROR_NOT_SUPPORTED;
  1545. }
  1546. static void windows_destroy_device(struct libusb_device *dev)
  1547. {
  1548. windows_device_priv_release(dev);
  1549. }
  1550. static void windows_clear_transfer_priv(struct usbi_transfer *itransfer)
  1551. {
  1552. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  1553. usbi_free_fd(transfer_priv->pollable_fd.fd);
  1554. // When auto claim is in use, attempt to release the auto-claimed interface
  1555. auto_release(itransfer);
  1556. }
  1557. static int submit_bulk_transfer(struct usbi_transfer *itransfer)
  1558. {
  1559. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1560. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  1561. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  1562. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  1563. int r;
  1564. r = priv->apib->submit_bulk_transfer(itransfer);
  1565. if (r != LIBUSB_SUCCESS) {
  1566. return r;
  1567. }
  1568. usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
  1569. (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
  1570. itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
  1571. return LIBUSB_SUCCESS;
  1572. }
  1573. static int submit_iso_transfer(struct usbi_transfer *itransfer)
  1574. {
  1575. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1576. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  1577. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  1578. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  1579. int r;
  1580. r = priv->apib->submit_iso_transfer(itransfer);
  1581. if (r != LIBUSB_SUCCESS) {
  1582. return r;
  1583. }
  1584. usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd,
  1585. (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT));
  1586. itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
  1587. return LIBUSB_SUCCESS;
  1588. }
  1589. static int submit_control_transfer(struct usbi_transfer *itransfer)
  1590. {
  1591. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1592. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  1593. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  1594. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  1595. int r;
  1596. r = priv->apib->submit_control_transfer(itransfer);
  1597. if (r != LIBUSB_SUCCESS) {
  1598. return r;
  1599. }
  1600. usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN);
  1601. itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
  1602. return LIBUSB_SUCCESS;
  1603. }
  1604. static int windows_submit_transfer(struct usbi_transfer *itransfer)
  1605. {
  1606. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1607. switch (transfer->type) {
  1608. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1609. return submit_control_transfer(itransfer);
  1610. case LIBUSB_TRANSFER_TYPE_BULK:
  1611. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1612. return submit_bulk_transfer(itransfer);
  1613. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1614. return submit_iso_transfer(itransfer);
  1615. default:
  1616. usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1617. return LIBUSB_ERROR_INVALID_PARAM;
  1618. }
  1619. }
  1620. static int windows_abort_control(struct usbi_transfer *itransfer)
  1621. {
  1622. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1623. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  1624. return priv->apib->abort_control(itransfer);
  1625. }
  1626. static int windows_abort_transfers(struct usbi_transfer *itransfer)
  1627. {
  1628. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1629. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  1630. return priv->apib->abort_transfers(itransfer);
  1631. }
  1632. static int windows_cancel_transfer(struct usbi_transfer *itransfer)
  1633. {
  1634. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1635. switch (transfer->type) {
  1636. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1637. return windows_abort_control(itransfer);
  1638. case LIBUSB_TRANSFER_TYPE_BULK:
  1639. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1640. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1641. return windows_abort_transfers(itransfer);
  1642. default:
  1643. usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
  1644. return LIBUSB_ERROR_INVALID_PARAM;
  1645. }
  1646. }
  1647. static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
  1648. {
  1649. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1650. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  1651. int status;
  1652. usbi_dbg("handling I/O completion with errcode %d", io_result);
  1653. switch(io_result) {
  1654. case NO_ERROR:
  1655. status = priv->apib->copy_transfer_data(itransfer, io_size);
  1656. break;
  1657. case ERROR_GEN_FAILURE:
  1658. usbi_dbg("detected endpoint stall");
  1659. status = LIBUSB_TRANSFER_STALL;
  1660. break;
  1661. case ERROR_SEM_TIMEOUT:
  1662. usbi_dbg("detected semaphore timeout");
  1663. status = LIBUSB_TRANSFER_TIMED_OUT;
  1664. break;
  1665. case ERROR_OPERATION_ABORTED:
  1666. if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
  1667. usbi_dbg("detected timeout");
  1668. status = LIBUSB_TRANSFER_TIMED_OUT;
  1669. } else {
  1670. usbi_dbg("detected operation aborted");
  1671. status = LIBUSB_TRANSFER_CANCELLED;
  1672. }
  1673. break;
  1674. default:
  1675. usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(0));
  1676. status = LIBUSB_TRANSFER_ERROR;
  1677. break;
  1678. }
  1679. windows_clear_transfer_priv(itransfer); // Cancel polling
  1680. usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
  1681. }
  1682. static void windows_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
  1683. {
  1684. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1685. switch (transfer->type) {
  1686. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1687. case LIBUSB_TRANSFER_TYPE_BULK:
  1688. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1689. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1690. windows_transfer_callback (itransfer, io_result, io_size);
  1691. break;
  1692. default:
  1693. usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
  1694. }
  1695. }
  1696. static int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
  1697. {
  1698. struct windows_transfer_priv* transfer_priv = NULL;
  1699. POLL_NFDS_TYPE i = 0;
  1700. bool found = false;
  1701. struct usbi_transfer *transfer;
  1702. DWORD io_size, io_result;
  1703. usbi_mutex_lock(&ctx->open_devs_lock);
  1704. for (i = 0; i < nfds && num_ready > 0; i++) {
  1705. usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
  1706. if (!fds[i].revents) {
  1707. continue;
  1708. }
  1709. num_ready--;
  1710. // Because a Windows OVERLAPPED is used for poll emulation,
  1711. // a pollable fd is created and stored with each transfer
  1712. usbi_mutex_lock(&ctx->flying_transfers_lock);
  1713. list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
  1714. transfer_priv = usbi_transfer_get_os_priv(transfer);
  1715. if (transfer_priv->pollable_fd.fd == fds[i].fd) {
  1716. found = true;
  1717. break;
  1718. }
  1719. }
  1720. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  1721. if (found) {
  1722. // Handle async requests that completed synchronously first
  1723. if (HasOverlappedIoCompletedSync(transfer_priv->pollable_fd.overlapped)) {
  1724. io_result = NO_ERROR;
  1725. io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
  1726. // Regular async overlapped
  1727. } else if (GetOverlappedResult(transfer_priv->pollable_fd.handle,
  1728. transfer_priv->pollable_fd.overlapped, &io_size, false)) {
  1729. io_result = NO_ERROR;
  1730. } else {
  1731. io_result = GetLastError();
  1732. }
  1733. usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
  1734. // let handle_callback free the event using the transfer wfd
  1735. // If you don't use the transfer wfd, you run a risk of trying to free a
  1736. // newly allocated wfd that took the place of the one from the transfer.
  1737. windows_handle_callback(transfer, io_result, io_size);
  1738. } else {
  1739. usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
  1740. return LIBUSB_ERROR_NOT_FOUND;
  1741. }
  1742. }
  1743. usbi_mutex_unlock(&ctx->open_devs_lock);
  1744. return LIBUSB_SUCCESS;
  1745. }
  1746. /*
  1747. * Monotonic and real time functions
  1748. */
  1749. unsigned __stdcall windows_clock_gettime_threaded(void* param)
  1750. {
  1751. LARGE_INTEGER hires_counter, li_frequency;
  1752. LONG nb_responses;
  1753. int timer_index;
  1754. // Init - find out if we have access to a monotonic (hires) timer
  1755. if (!QueryPerformanceFrequency(&li_frequency)) {
  1756. usbi_dbg("no hires timer available on this platform");
  1757. hires_frequency = 0;
  1758. hires_ticks_to_ps = UINT64_C(0);
  1759. } else {
  1760. hires_frequency = li_frequency.QuadPart;
  1761. // The hires frequency can go as high as 4 GHz, so we'll use a conversion
  1762. // to picoseconds to compute the tv_nsecs part in clock_gettime
  1763. hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
  1764. usbi_dbg("hires timer available (Frequency: %I64u Hz)", hires_frequency);
  1765. }
  1766. // Main loop - wait for requests
  1767. while (1) {
  1768. timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
  1769. if ( (timer_index != 0) && (timer_index != 1) ) {
  1770. usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
  1771. continue;
  1772. }
  1773. if (request_count[timer_index] == 0) {
  1774. // Request already handled
  1775. ResetEvent(timer_request[timer_index]);
  1776. // There's still a possiblity that a thread sends a request between the
  1777. // time we test request_count[] == 0 and we reset the event, in which case
  1778. // the request would be ignored. The simple solution to that is to test
  1779. // request_count again and process requests if non zero.
  1780. if (request_count[timer_index] == 0)
  1781. continue;
  1782. }
  1783. switch (timer_index) {
  1784. case 0:
  1785. WaitForSingleObject(timer_mutex, INFINITE);
  1786. // Requests to this thread are for hires always
  1787. if (QueryPerformanceCounter(&hires_counter) != 0) {
  1788. timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
  1789. timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
  1790. } else {
  1791. // Fallback to real-time if we can't get monotonic value
  1792. // Note that real-time clock does not wait on the mutex or this thread.
  1793. windows_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
  1794. }
  1795. ReleaseMutex(timer_mutex);
  1796. nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
  1797. if ( (nb_responses)
  1798. && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
  1799. usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
  1800. }
  1801. continue;
  1802. case 1: // time to quit
  1803. usbi_dbg("timer thread quitting");
  1804. return 0;
  1805. }
  1806. }
  1807. usbi_dbg("ERROR: broken timer thread");
  1808. return 1;
  1809. }
  1810. static int windows_clock_gettime(int clk_id, struct timespec *tp)
  1811. {
  1812. FILETIME filetime;
  1813. ULARGE_INTEGER rtime;
  1814. DWORD r;
  1815. switch(clk_id) {
  1816. case USBI_CLOCK_MONOTONIC:
  1817. if (hires_frequency != 0) {
  1818. while (1) {
  1819. InterlockedIncrement((LONG*)&request_count[0]);
  1820. SetEvent(timer_request[0]);
  1821. r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
  1822. switch(r) {
  1823. case WAIT_OBJECT_0:
  1824. WaitForSingleObject(timer_mutex, INFINITE);
  1825. *tp = timer_tp;
  1826. ReleaseMutex(timer_mutex);
  1827. return LIBUSB_SUCCESS;
  1828. case WAIT_TIMEOUT:
  1829. usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
  1830. break; // Retry until successful
  1831. default:
  1832. usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
  1833. return LIBUSB_ERROR_OTHER;
  1834. }
  1835. }
  1836. }
  1837. // Fall through and return real-time if monotonic was not detected @ timer init
  1838. case USBI_CLOCK_REALTIME:
  1839. // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
  1840. // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
  1841. // Note however that our resolution is bounded by the Windows system time
  1842. // functions and is at best of the order of 1 ms (or, usually, worse)
  1843. GetSystemTimeAsFileTime(&filetime);
  1844. rtime.LowPart = filetime.dwLowDateTime;
  1845. rtime.HighPart = filetime.dwHighDateTime;
  1846. rtime.QuadPart -= epoch_time;
  1847. tp->tv_sec = (long)(rtime.QuadPart / 10000000);
  1848. tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
  1849. return LIBUSB_SUCCESS;
  1850. default:
  1851. return LIBUSB_ERROR_INVALID_PARAM;
  1852. }
  1853. }
  1854. // NB: MSVC6 does not support named initializers.
  1855. const struct usbi_os_backend windows_backend = {
  1856. "Windows",
  1857. windows_init,
  1858. windows_exit,
  1859. windows_get_device_list,
  1860. windows_open,
  1861. windows_close,
  1862. windows_get_device_descriptor,
  1863. windows_get_active_config_descriptor,
  1864. windows_get_config_descriptor,
  1865. windows_get_configuration,
  1866. windows_set_configuration,
  1867. windows_claim_interface,
  1868. windows_release_interface,
  1869. windows_set_interface_altsetting,
  1870. windows_clear_halt,
  1871. windows_reset_device,
  1872. windows_kernel_driver_active,
  1873. windows_detach_kernel_driver,
  1874. windows_attach_kernel_driver,
  1875. windows_destroy_device,
  1876. windows_submit_transfer,
  1877. windows_cancel_transfer,
  1878. windows_clear_transfer_priv,
  1879. windows_handle_events,
  1880. windows_clock_gettime,
  1881. #if defined(USBI_TIMERFD_AVAILABLE)
  1882. NULL,
  1883. #endif
  1884. sizeof(struct windows_device_priv),
  1885. sizeof(struct windows_device_handle_priv),
  1886. sizeof(struct windows_transfer_priv),
  1887. 0,
  1888. };
  1889. /*
  1890. * USB API backends
  1891. */
  1892. static int unsupported_init(struct libusb_context *ctx) {
  1893. return LIBUSB_SUCCESS;
  1894. }
  1895. static int unsupported_exit(void) {
  1896. return LIBUSB_SUCCESS;
  1897. }
  1898. static int unsupported_open(struct libusb_device_handle *dev_handle) {
  1899. PRINT_UNSUPPORTED_API(open);
  1900. }
  1901. static void unsupported_close(struct libusb_device_handle *dev_handle) {
  1902. usbi_dbg("unsupported API call for 'close'");
  1903. }
  1904. static int unsupported_claim_interface(struct libusb_device_handle *dev_handle, int iface) {
  1905. PRINT_UNSUPPORTED_API(claim_interface);
  1906. }
  1907. static int unsupported_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) {
  1908. PRINT_UNSUPPORTED_API(set_interface_altsetting);
  1909. }
  1910. static int unsupported_release_interface(struct libusb_device_handle *dev_handle, int iface) {
  1911. PRINT_UNSUPPORTED_API(release_interface);
  1912. }
  1913. static int unsupported_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
  1914. PRINT_UNSUPPORTED_API(clear_halt);
  1915. }
  1916. static int unsupported_reset_device(struct libusb_device_handle *dev_handle) {
  1917. PRINT_UNSUPPORTED_API(reset_device);
  1918. }
  1919. static int unsupported_submit_bulk_transfer(struct usbi_transfer *itransfer) {
  1920. PRINT_UNSUPPORTED_API(submit_bulk_transfer);
  1921. }
  1922. static int unsupported_submit_iso_transfer(struct usbi_transfer *itransfer) {
  1923. PRINT_UNSUPPORTED_API(submit_iso_transfer);
  1924. }
  1925. static int unsupported_submit_control_transfer(struct usbi_transfer *itransfer) {
  1926. PRINT_UNSUPPORTED_API(submit_control_transfer);
  1927. }
  1928. static int unsupported_abort_control(struct usbi_transfer *itransfer) {
  1929. PRINT_UNSUPPORTED_API(abort_control);
  1930. }
  1931. static int unsupported_abort_transfers(struct usbi_transfer *itransfer) {
  1932. PRINT_UNSUPPORTED_API(abort_transfers);
  1933. }
  1934. static int unsupported_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) {
  1935. PRINT_UNSUPPORTED_API(copy_transfer_data);
  1936. }
  1937. // These names must be uppercase
  1938. const char* hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30"};
  1939. const char* composite_driver_names[] = {"USBCCGP"};
  1940. const char* winusb_driver_names[] = {"WINUSB"};
  1941. const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
  1942. {
  1943. USB_API_UNSUPPORTED,
  1944. "Unsupported API",
  1945. &CLASS_GUID_UNSUPPORTED,
  1946. NULL,
  1947. 0,
  1948. unsupported_init,
  1949. unsupported_exit,
  1950. unsupported_open,
  1951. unsupported_close,
  1952. unsupported_claim_interface,
  1953. unsupported_set_interface_altsetting,
  1954. unsupported_release_interface,
  1955. unsupported_clear_halt,
  1956. unsupported_reset_device,
  1957. unsupported_submit_bulk_transfer,
  1958. unsupported_submit_iso_transfer,
  1959. unsupported_submit_control_transfer,
  1960. unsupported_abort_control,
  1961. unsupported_abort_transfers,
  1962. unsupported_copy_transfer_data,
  1963. }, {
  1964. USB_API_HUB,
  1965. "HUB API",
  1966. &CLASS_GUID_UNSUPPORTED,
  1967. hub_driver_names,
  1968. sizeof(hub_driver_names)/sizeof(hub_driver_names[0]),
  1969. unsupported_init,
  1970. unsupported_exit,
  1971. unsupported_open,
  1972. unsupported_close,
  1973. unsupported_claim_interface,
  1974. unsupported_set_interface_altsetting,
  1975. unsupported_release_interface,
  1976. unsupported_clear_halt,
  1977. unsupported_reset_device,
  1978. unsupported_submit_bulk_transfer,
  1979. unsupported_submit_iso_transfer,
  1980. unsupported_submit_control_transfer,
  1981. unsupported_abort_control,
  1982. unsupported_abort_transfers,
  1983. unsupported_copy_transfer_data,
  1984. }, {
  1985. USB_API_COMPOSITE,
  1986. "Composite API",
  1987. &CLASS_GUID_COMPOSITE,
  1988. composite_driver_names,
  1989. sizeof(composite_driver_names)/sizeof(composite_driver_names[0]),
  1990. composite_init,
  1991. composite_exit,
  1992. composite_open,
  1993. composite_close,
  1994. composite_claim_interface,
  1995. composite_set_interface_altsetting,
  1996. composite_release_interface,
  1997. composite_clear_halt,
  1998. composite_reset_device,
  1999. composite_submit_bulk_transfer,
  2000. composite_submit_iso_transfer,
  2001. composite_submit_control_transfer,
  2002. composite_abort_control,
  2003. composite_abort_transfers,
  2004. composite_copy_transfer_data,
  2005. }, {
  2006. USB_API_WINUSB,
  2007. "WinUSB API",
  2008. &CLASS_GUID_LIBUSB_WINUSB,
  2009. winusb_driver_names,
  2010. sizeof(winusb_driver_names)/sizeof(winusb_driver_names[0]),
  2011. winusb_init,
  2012. winusb_exit,
  2013. winusb_open,
  2014. winusb_close,
  2015. winusb_claim_interface,
  2016. winusb_set_interface_altsetting,
  2017. winusb_release_interface,
  2018. winusb_clear_halt,
  2019. winusb_reset_device,
  2020. winusb_submit_bulk_transfer,
  2021. unsupported_submit_iso_transfer,
  2022. winusb_submit_control_transfer,
  2023. winusb_abort_control,
  2024. winusb_abort_transfers,
  2025. winusb_copy_transfer_data,
  2026. },
  2027. };
  2028. /*
  2029. * WinUSB API functions
  2030. */
  2031. static int winusb_init(struct libusb_context *ctx)
  2032. {
  2033. DLL_LOAD(winusb.dll, WinUsb_Initialize, TRUE);
  2034. DLL_LOAD(winusb.dll, WinUsb_Free, TRUE);
  2035. DLL_LOAD(winusb.dll, WinUsb_GetAssociatedInterface, TRUE);
  2036. DLL_LOAD(winusb.dll, WinUsb_GetDescriptor, TRUE);
  2037. DLL_LOAD(winusb.dll, WinUsb_QueryInterfaceSettings, TRUE);
  2038. DLL_LOAD(winusb.dll, WinUsb_QueryDeviceInformation, TRUE);
  2039. DLL_LOAD(winusb.dll, WinUsb_SetCurrentAlternateSetting, TRUE);
  2040. DLL_LOAD(winusb.dll, WinUsb_GetCurrentAlternateSetting, TRUE);
  2041. DLL_LOAD(winusb.dll, WinUsb_QueryPipe, TRUE);
  2042. DLL_LOAD(winusb.dll, WinUsb_SetPipePolicy, TRUE);
  2043. DLL_LOAD(winusb.dll, WinUsb_GetPipePolicy, TRUE);
  2044. DLL_LOAD(winusb.dll, WinUsb_ReadPipe, TRUE);
  2045. DLL_LOAD(winusb.dll, WinUsb_WritePipe, TRUE);
  2046. DLL_LOAD(winusb.dll, WinUsb_ControlTransfer, TRUE);
  2047. DLL_LOAD(winusb.dll, WinUsb_ResetPipe, TRUE);
  2048. DLL_LOAD(winusb.dll, WinUsb_AbortPipe, TRUE);
  2049. DLL_LOAD(winusb.dll, WinUsb_FlushPipe, TRUE);
  2050. api_winusb_available = true;
  2051. return LIBUSB_SUCCESS;
  2052. }
  2053. static int winusb_exit(void)
  2054. {
  2055. return LIBUSB_SUCCESS;
  2056. }
  2057. // NB: open and close must ensure that they only handle interface of
  2058. // the right API type, as these functions can be called wholesale from
  2059. // composite_open(), with interfaces belonging to different APIs
  2060. static int winusb_open(struct libusb_device_handle *dev_handle)
  2061. {
  2062. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  2063. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2064. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2065. HANDLE file_handle;
  2066. int i;
  2067. CHECK_WINUSB_AVAILABLE;
  2068. // WinUSB requires a seperate handle for each interface
  2069. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2070. if ( (priv->usb_interface[i].path != NULL)
  2071. && (priv->usb_interface[i].apib->id == USB_API_WINUSB) ) {
  2072. file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ,
  2073. NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
  2074. if (file_handle == INVALID_HANDLE_VALUE) {
  2075. usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
  2076. switch(GetLastError()) {
  2077. case ERROR_FILE_NOT_FOUND: // The device was disconnected
  2078. return LIBUSB_ERROR_NO_DEVICE;
  2079. case ERROR_ACCESS_DENIED:
  2080. return LIBUSB_ERROR_ACCESS;
  2081. default:
  2082. return LIBUSB_ERROR_IO;
  2083. }
  2084. }
  2085. handle_priv->interface_handle[i].dev_handle = file_handle;
  2086. }
  2087. }
  2088. return LIBUSB_SUCCESS;
  2089. }
  2090. static void winusb_close(struct libusb_device_handle *dev_handle)
  2091. {
  2092. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2093. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2094. HANDLE file_handle;
  2095. int i;
  2096. if (!api_winusb_available)
  2097. return;
  2098. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2099. if (priv->usb_interface[i].apib->id == USB_API_WINUSB) {
  2100. file_handle = handle_priv->interface_handle[i].dev_handle;
  2101. if ( (file_handle != 0) && (file_handle != INVALID_HANDLE_VALUE)) {
  2102. CloseHandle(file_handle);
  2103. }
  2104. }
  2105. }
  2106. }
  2107. static int winusb_configure_endpoints(struct libusb_device_handle *dev_handle, int iface)
  2108. {
  2109. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2110. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2111. HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
  2112. UCHAR policy;
  2113. ULONG timeout = 0;
  2114. uint8_t endpoint_address;
  2115. int i;
  2116. CHECK_WINUSB_AVAILABLE;
  2117. // With handle and enpoints set (in parent), we can setup the default pipe properties
  2118. // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
  2119. for (i=-1; i<priv->usb_interface[iface].nb_endpoints; i++) {
  2120. endpoint_address =(i==-1)?0:priv->usb_interface[iface].endpoint[i];
  2121. if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
  2122. PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) {
  2123. usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
  2124. }
  2125. if (i == -1)
  2126. continue; // Other policies don't apply to control endpoint
  2127. policy = true;
  2128. if (!WinUsb_SetPipePolicy(winusb_handle, endpoint_address,
  2129. AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) {
  2130. usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
  2131. }
  2132. }
  2133. return LIBUSB_SUCCESS;
  2134. }
  2135. static int winusb_claim_interface(struct libusb_device_handle *dev_handle, int iface)
  2136. {
  2137. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  2138. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2139. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2140. bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
  2141. HANDLE file_handle, winusb_handle;
  2142. CHECK_WINUSB_AVAILABLE;
  2143. // If the device is composite, but using the default Windows composite parent driver (usbccgp)
  2144. // or if it's the first WinUSB interface, we get a handle through WinUsb_Initialize().
  2145. if ((is_using_usbccgp) || (iface == 0)) {
  2146. // composite device (independent interfaces) or interface 0
  2147. file_handle = handle_priv->interface_handle[iface].dev_handle;
  2148. if ((file_handle == 0) || (file_handle == INVALID_HANDLE_VALUE)) {
  2149. return LIBUSB_ERROR_NOT_FOUND;
  2150. }
  2151. if (!WinUsb_Initialize(file_handle, &winusb_handle)) {
  2152. usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0));
  2153. handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
  2154. switch(GetLastError()) {
  2155. case ERROR_BAD_COMMAND: // The device was disconnected
  2156. return LIBUSB_ERROR_NO_DEVICE;
  2157. default:
  2158. usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
  2159. return LIBUSB_ERROR_ACCESS;
  2160. }
  2161. }
  2162. handle_priv->interface_handle[iface].api_handle = winusb_handle;
  2163. } else {
  2164. // For all other interfaces, use WinUsb_GetAssociatedInterface()
  2165. winusb_handle = handle_priv->interface_handle[0].api_handle;
  2166. // It is a requirement for multiple interface devices using WinUSB that you
  2167. // must first claim the first interface before you claim any other
  2168. if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
  2169. file_handle = handle_priv->interface_handle[0].dev_handle;
  2170. if (WinUsb_Initialize(file_handle, &winusb_handle)) {
  2171. handle_priv->interface_handle[0].api_handle = winusb_handle;
  2172. usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface);
  2173. } else {
  2174. usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB)", iface);
  2175. return LIBUSB_ERROR_ACCESS;
  2176. }
  2177. }
  2178. if (!WinUsb_GetAssociatedInterface(winusb_handle, (UCHAR)(iface-1),
  2179. &handle_priv->interface_handle[iface].api_handle)) {
  2180. handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
  2181. switch(GetLastError()) {
  2182. case ERROR_NO_MORE_ITEMS: // invalid iface
  2183. return LIBUSB_ERROR_NOT_FOUND;
  2184. case ERROR_BAD_COMMAND: // The device was disconnected
  2185. return LIBUSB_ERROR_NO_DEVICE;
  2186. case ERROR_ALREADY_EXISTS: // already claimed
  2187. return LIBUSB_ERROR_BUSY;
  2188. default:
  2189. usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0));
  2190. return LIBUSB_ERROR_ACCESS;
  2191. }
  2192. }
  2193. }
  2194. usbi_dbg("claimed interface %d", iface);
  2195. handle_priv->active_interface = iface;
  2196. return LIBUSB_SUCCESS;
  2197. }
  2198. static int winusb_release_interface(struct libusb_device_handle *dev_handle, int iface)
  2199. {
  2200. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2201. HANDLE winusb_handle;
  2202. CHECK_WINUSB_AVAILABLE;
  2203. winusb_handle = handle_priv->interface_handle[iface].api_handle;
  2204. if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
  2205. return LIBUSB_ERROR_NOT_FOUND;
  2206. }
  2207. WinUsb_Free(winusb_handle);
  2208. handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
  2209. return LIBUSB_SUCCESS;
  2210. }
  2211. /*
  2212. * Return the first valid interface (of the same API type), for control transfers
  2213. */
  2214. static int winusb_get_valid_interface(struct libusb_device_handle *dev_handle)
  2215. {
  2216. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2217. int i;
  2218. for (i=0; i<USB_MAXINTERFACES; i++) {
  2219. if ( (handle_priv->interface_handle[i].dev_handle != 0)
  2220. && (handle_priv->interface_handle[i].dev_handle != INVALID_HANDLE_VALUE)
  2221. && (handle_priv->interface_handle[i].api_handle != 0)
  2222. && (handle_priv->interface_handle[i].api_handle != INVALID_HANDLE_VALUE) ) {
  2223. return i;
  2224. }
  2225. }
  2226. return -1;
  2227. }
  2228. /*
  2229. * Lookup interface by endpoint address. -1 if not found
  2230. */
  2231. static int interface_by_endpoint(struct windows_device_priv *priv,
  2232. struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address)
  2233. {
  2234. int i, j;
  2235. for (i=0; i<USB_MAXINTERFACES; i++) {
  2236. if (handle_priv->interface_handle[i].api_handle == INVALID_HANDLE_VALUE)
  2237. continue;
  2238. if (handle_priv->interface_handle[i].api_handle == 0)
  2239. continue;
  2240. if (priv->usb_interface[i].endpoint == NULL)
  2241. continue;
  2242. for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
  2243. if (priv->usb_interface[i].endpoint[j] == endpoint_address) {
  2244. return i;
  2245. }
  2246. }
  2247. }
  2248. return -1;
  2249. }
  2250. static int winusb_submit_control_transfer(struct usbi_transfer *itransfer)
  2251. {
  2252. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2253. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  2254. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2255. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  2256. struct windows_device_handle_priv *handle_priv = _device_handle_priv(
  2257. transfer->dev_handle);
  2258. WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *) transfer->buffer;
  2259. ULONG size;
  2260. HANDLE winusb_handle;
  2261. int current_interface;
  2262. struct winfd wfd;
  2263. CHECK_WINUSB_AVAILABLE;
  2264. transfer_priv->pollable_fd = INVALID_WINFD;
  2265. size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
  2266. if (size > MAX_CTRL_BUFFER_LENGTH)
  2267. return LIBUSB_ERROR_INVALID_PARAM;
  2268. current_interface = winusb_get_valid_interface(transfer->dev_handle);
  2269. if (current_interface < 0) {
  2270. if (auto_claim(transfer, &current_interface, USB_API_WINUSB) != LIBUSB_SUCCESS) {
  2271. return LIBUSB_ERROR_NOT_FOUND;
  2272. }
  2273. }
  2274. usbi_dbg("will use interface %d", current_interface);
  2275. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2276. wfd = usbi_create_fd(winusb_handle, _O_RDONLY);
  2277. // Always use the handle returned from usbi_create_fd (wfd.handle)
  2278. if (wfd.fd < 0) {
  2279. return LIBUSB_ERROR_NO_MEM;
  2280. }
  2281. // Sending of set configuration control requests from WinUSB creates issues
  2282. if ( ((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD)
  2283. && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION) ) {
  2284. if (setup->value != priv->active_config) {
  2285. usbi_warn(ctx, "cannot set configuration other than the default one");
  2286. usbi_free_fd(wfd.fd);
  2287. return LIBUSB_ERROR_INVALID_PARAM;
  2288. }
  2289. wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
  2290. wfd.overlapped->InternalHigh = 0;
  2291. } else {
  2292. if (!WinUsb_ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) {
  2293. if(GetLastError() != ERROR_IO_PENDING) {
  2294. usbi_err(ctx, "WinUsb_ControlTransfer failed: %s", windows_error_str(0));
  2295. usbi_free_fd(wfd.fd);
  2296. return LIBUSB_ERROR_IO;
  2297. }
  2298. } else {
  2299. wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
  2300. wfd.overlapped->InternalHigh = (DWORD)size;
  2301. }
  2302. }
  2303. // Use priv_transfer to store data needed for async polling
  2304. transfer_priv->pollable_fd = wfd;
  2305. transfer_priv->interface_number = (uint8_t)current_interface;
  2306. return LIBUSB_SUCCESS;
  2307. }
  2308. static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
  2309. {
  2310. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  2311. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2312. HANDLE winusb_handle;
  2313. CHECK_WINUSB_AVAILABLE;
  2314. if (altsetting > 255) {
  2315. return LIBUSB_ERROR_INVALID_PARAM;
  2316. }
  2317. winusb_handle = handle_priv->interface_handle[iface].api_handle;
  2318. if ((winusb_handle == 0) || (winusb_handle == INVALID_HANDLE_VALUE)) {
  2319. usbi_err(ctx, "interface must be claimed first");
  2320. return LIBUSB_ERROR_NOT_FOUND;
  2321. }
  2322. if (!WinUsb_SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) {
  2323. usbi_err(ctx, "WinUsb_SetCurrentAlternateSetting failed: %s", windows_error_str(0));
  2324. return LIBUSB_ERROR_IO;
  2325. }
  2326. return LIBUSB_SUCCESS;
  2327. }
  2328. static int winusb_submit_bulk_transfer(struct usbi_transfer *itransfer)
  2329. {
  2330. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2331. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  2332. struct windows_transfer_priv *transfer_priv = (struct windows_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  2333. struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
  2334. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2335. HANDLE winusb_handle;
  2336. bool ret;
  2337. int current_interface;
  2338. struct winfd wfd;
  2339. ULONG ppolicy = sizeof(UCHAR);
  2340. UCHAR policy;
  2341. CHECK_WINUSB_AVAILABLE;
  2342. transfer_priv->pollable_fd = INVALID_WINFD;
  2343. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  2344. if (current_interface < 0) {
  2345. usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
  2346. return LIBUSB_ERROR_NOT_FOUND;
  2347. }
  2348. usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
  2349. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2350. wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? _O_RDONLY : _O_WRONLY);
  2351. // Always use the handle returned from usbi_create_fd (wfd.handle)
  2352. if (wfd.fd < 0) {
  2353. return LIBUSB_ERROR_NO_MEM;
  2354. }
  2355. if (IS_XFERIN(transfer)) {
  2356. WinUsb_GetPipePolicy(wfd.handle, transfer->endpoint, AUTO_CLEAR_STALL, &ppolicy, &policy);
  2357. if (!policy) {
  2358. policy = TRUE;
  2359. WinUsb_SetPipePolicy(wfd.handle, transfer->endpoint, AUTO_CLEAR_STALL, ppolicy, &policy);
  2360. }
  2361. ret = WinUsb_ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
  2362. } else {
  2363. if (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
  2364. WinUsb_GetPipePolicy(wfd.handle, transfer->endpoint, SHORT_PACKET_TERMINATE, &ppolicy, &policy);
  2365. if (!policy) {
  2366. policy = TRUE;
  2367. WinUsb_SetPipePolicy(wfd.handle, transfer->endpoint, SHORT_PACKET_TERMINATE, ppolicy, &policy);
  2368. }
  2369. }
  2370. usbi_dbg("writing %d bytes", transfer->length);
  2371. ret = WinUsb_WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped);
  2372. }
  2373. if (!ret) {
  2374. if(GetLastError() != ERROR_IO_PENDING) {
  2375. usbi_err(ctx, "WinUsb_Pipe Transfer failed: %s", windows_error_str(0));
  2376. usbi_free_fd(wfd.fd);
  2377. return LIBUSB_ERROR_IO;
  2378. }
  2379. } else {
  2380. wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY;
  2381. wfd.overlapped->InternalHigh = (DWORD)transfer->length;
  2382. }
  2383. transfer_priv->pollable_fd = wfd;
  2384. transfer_priv->interface_number = (uint8_t)current_interface;
  2385. return LIBUSB_SUCCESS;
  2386. }
  2387. static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
  2388. {
  2389. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  2390. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2391. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2392. HANDLE winusb_handle;
  2393. int current_interface;
  2394. CHECK_WINUSB_AVAILABLE;
  2395. current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
  2396. if (current_interface < 0) {
  2397. usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
  2398. return LIBUSB_ERROR_NOT_FOUND;
  2399. }
  2400. usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface);
  2401. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2402. if (!WinUsb_ResetPipe(winusb_handle, endpoint)) {
  2403. usbi_err(ctx, "WinUsb_ResetPipe failed: %s", windows_error_str(0));
  2404. return LIBUSB_ERROR_NO_DEVICE;
  2405. }
  2406. return LIBUSB_SUCCESS;
  2407. }
  2408. /*
  2409. * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed
  2410. * through testing as well):
  2411. * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel
  2412. * the control transfer using CancelIo"
  2413. */
  2414. static int winusb_abort_control(struct usbi_transfer *itransfer)
  2415. {
  2416. // Cancelling of the I/O is done in the parent
  2417. return LIBUSB_SUCCESS;
  2418. }
  2419. static int winusb_abort_transfers(struct usbi_transfer *itransfer)
  2420. {
  2421. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2422. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  2423. struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
  2424. struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
  2425. HANDLE winusb_handle;
  2426. int current_interface;
  2427. CHECK_WINUSB_AVAILABLE;
  2428. current_interface = transfer_priv->interface_number;
  2429. if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
  2430. usbi_err(ctx, "program assertion failed: invalid interface_number");
  2431. return LIBUSB_ERROR_NOT_FOUND;
  2432. }
  2433. usbi_dbg("will use interface %d", current_interface);
  2434. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2435. if (!WinUsb_AbortPipe(winusb_handle, transfer->endpoint)) {
  2436. usbi_err(ctx, "WinUsb_AbortPipe failed: %s", windows_error_str(0));
  2437. return LIBUSB_ERROR_NO_DEVICE;
  2438. }
  2439. return LIBUSB_SUCCESS;
  2440. }
  2441. /*
  2442. * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
  2443. * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
  2444. * "WinUSB does not support host-initiated reset port and cycle port operations" and
  2445. * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
  2446. * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
  2447. * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
  2448. */
  2449. // TODO (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
  2450. static int winusb_reset_device(struct libusb_device_handle *dev_handle)
  2451. {
  2452. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  2453. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2454. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2455. struct winfd wfd;
  2456. HANDLE winusb_handle;
  2457. int i, j;
  2458. CHECK_WINUSB_AVAILABLE;
  2459. // Reset any available pipe (except control)
  2460. for (i=0; i<USB_MAXINTERFACES; i++) {
  2461. winusb_handle = handle_priv->interface_handle[i].api_handle;
  2462. for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0;)
  2463. {
  2464. // Cancel any pollable I/O
  2465. usbi_remove_pollfd(ctx, wfd.fd);
  2466. usbi_free_fd(wfd.fd);
  2467. wfd = handle_to_winfd(winusb_handle);
  2468. }
  2469. if ( (winusb_handle != 0) && (winusb_handle != INVALID_HANDLE_VALUE)) {
  2470. for (j=0; j<priv->usb_interface[i].nb_endpoints; j++) {
  2471. usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]);
  2472. if (!WinUsb_AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
  2473. usbi_err(ctx, "WinUsb_AbortPipe (pipe address %02X) failed: %s",
  2474. priv->usb_interface[i].endpoint[j], windows_error_str(0));
  2475. }
  2476. // FlushPipe seems to fail on OUT pipes
  2477. if (IS_EPIN(priv->usb_interface[i].endpoint[j])
  2478. && (!WinUsb_FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) ) {
  2479. usbi_err(ctx, "WinUsb_FlushPipe (pipe address %02X) failed: %s",
  2480. priv->usb_interface[i].endpoint[j], windows_error_str(0));
  2481. }
  2482. if (!WinUsb_ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) {
  2483. usbi_err(ctx, "WinUsb_ResetPipe (pipe address %02X) failed: %s",
  2484. priv->usb_interface[i].endpoint[j], windows_error_str(0));
  2485. }
  2486. }
  2487. }
  2488. }
  2489. return LIBUSB_SUCCESS;
  2490. }
  2491. static int winusb_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
  2492. {
  2493. itransfer->transferred += io_size;
  2494. return LIBUSB_TRANSFER_COMPLETED;
  2495. }
  2496. /*
  2497. * Composite API functions
  2498. */
  2499. static int composite_init(struct libusb_context *ctx)
  2500. {
  2501. return LIBUSB_SUCCESS;
  2502. }
  2503. static int composite_exit(void)
  2504. {
  2505. return LIBUSB_SUCCESS;
  2506. }
  2507. static int composite_open(struct libusb_device_handle *dev_handle)
  2508. {
  2509. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2510. unsigned api;
  2511. int r;
  2512. uint8_t flag = 1<<USB_API_WINUSB;
  2513. for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
  2514. if (priv->composite_api_flags & flag) {
  2515. r = usb_api_backend[api].open(dev_handle);
  2516. if (r != LIBUSB_SUCCESS) {
  2517. return r;
  2518. }
  2519. }
  2520. flag <<= 1;
  2521. }
  2522. return LIBUSB_SUCCESS;
  2523. }
  2524. static void composite_close(struct libusb_device_handle *dev_handle)
  2525. {
  2526. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2527. unsigned api;
  2528. uint8_t flag = 1<<USB_API_WINUSB;
  2529. for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
  2530. if (priv->composite_api_flags & flag) {
  2531. usb_api_backend[api].close(dev_handle);
  2532. }
  2533. flag <<= 1;
  2534. }
  2535. }
  2536. static int composite_claim_interface(struct libusb_device_handle *dev_handle, int iface)
  2537. {
  2538. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2539. return priv->usb_interface[iface].apib->claim_interface(dev_handle, iface);
  2540. }
  2541. static int composite_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting)
  2542. {
  2543. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2544. return priv->usb_interface[iface].apib->set_interface_altsetting(dev_handle, iface, altsetting);
  2545. }
  2546. static int composite_release_interface(struct libusb_device_handle *dev_handle, int iface)
  2547. {
  2548. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2549. return priv->usb_interface[iface].apib->release_interface(dev_handle, iface);
  2550. }
  2551. static int composite_submit_control_transfer(struct usbi_transfer *itransfer)
  2552. {
  2553. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2554. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  2555. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2556. int i;
  2557. for (i=0; i<USB_MAXINTERFACES; i++) {
  2558. if (priv->usb_interface[i].path != NULL) {
  2559. usbi_dbg("using interface %d", i);
  2560. return priv->usb_interface[i].apib->submit_control_transfer(itransfer);
  2561. }
  2562. }
  2563. usbi_err(ctx, "no libusb supported interfaces to complete request");
  2564. return LIBUSB_ERROR_NOT_FOUND;
  2565. }
  2566. static int composite_submit_bulk_transfer(struct usbi_transfer *itransfer) {
  2567. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2568. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  2569. struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
  2570. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2571. int current_interface;
  2572. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  2573. if (current_interface < 0) {
  2574. usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
  2575. return LIBUSB_ERROR_NOT_FOUND;
  2576. }
  2577. return priv->usb_interface[current_interface].apib->submit_bulk_transfer(itransfer);
  2578. }
  2579. static int composite_submit_iso_transfer(struct usbi_transfer *itransfer) {
  2580. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2581. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  2582. struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle);
  2583. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2584. int current_interface;
  2585. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  2586. if (current_interface < 0) {
  2587. usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer");
  2588. return LIBUSB_ERROR_NOT_FOUND;
  2589. }
  2590. return priv->usb_interface[current_interface].apib->submit_iso_transfer(itransfer);
  2591. }
  2592. static int composite_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
  2593. {
  2594. struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev);
  2595. struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle);
  2596. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2597. int current_interface;
  2598. current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
  2599. if (current_interface < 0) {
  2600. usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear");
  2601. return LIBUSB_ERROR_NOT_FOUND;
  2602. }
  2603. return priv->usb_interface[current_interface].apib->clear_halt(dev_handle, endpoint);
  2604. }
  2605. static int composite_abort_control(struct usbi_transfer *itransfer)
  2606. {
  2607. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2608. struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
  2609. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2610. return priv->usb_interface[transfer_priv->interface_number].apib->abort_control(itransfer);
  2611. }
  2612. static int composite_abort_transfers(struct usbi_transfer *itransfer)
  2613. {
  2614. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2615. struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
  2616. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2617. return priv->usb_interface[transfer_priv->interface_number].apib->abort_transfers(itransfer);
  2618. }
  2619. static int composite_reset_device(struct libusb_device_handle *dev_handle)
  2620. {
  2621. struct windows_device_priv *priv = _device_priv(dev_handle->dev);
  2622. unsigned api;
  2623. int r;
  2624. uint8_t flag = 1<<USB_API_WINUSB;
  2625. for (api=USB_API_WINUSB; api<USB_API_MAX; api++) {
  2626. if (priv->composite_api_flags & flag) {
  2627. r = usb_api_backend[api].reset_device(dev_handle);
  2628. if (r != LIBUSB_SUCCESS) {
  2629. return r;
  2630. }
  2631. }
  2632. flag <<= 1;
  2633. }
  2634. return LIBUSB_SUCCESS;
  2635. }
  2636. static int composite_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size)
  2637. {
  2638. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2639. struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer);
  2640. struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  2641. return priv->usb_interface[transfer_priv->interface_number].apib->copy_transfer_data(itransfer, io_size);
  2642. }