wince_usb.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. /*
  2. * Windows CE backend for libusbx 1.0
  3. * Copyright © 2011-2013 RealVNC Ltd.
  4. * Large portions taken from Windows backend, which is
  5. * Copyright © 2009-2010 Pete Batard <pbatard@gmail.com>
  6. * With contributions from Michael Plante, Orin Eman et al.
  7. * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
  8. * Major code testing contribution by Xiaofan Chen
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this library; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. #include <libusbi.h>
  25. #include <stdint.h>
  26. #include <errno.h>
  27. #include <inttypes.h>
  28. #include "wince_usb.h"
  29. // Forward declares
  30. static int wince_clock_gettime(int clk_id, struct timespec *tp);
  31. unsigned __stdcall wince_clock_gettime_threaded(void* param);
  32. // Global variables
  33. uint64_t hires_frequency, hires_ticks_to_ps;
  34. int errno;
  35. const uint64_t epoch_time = UINT64_C(116444736000000000); // 1970.01.01 00:00:000 in MS Filetime
  36. enum windows_version windows_version = WINDOWS_CE;
  37. static int concurrent_usage = -1;
  38. // Timer thread
  39. // NB: index 0 is for monotonic and 1 is for the thread exit event
  40. HANDLE timer_thread = NULL;
  41. HANDLE timer_mutex = NULL;
  42. struct timespec timer_tp;
  43. volatile LONG request_count[2] = {0, 1}; // last one must be > 0
  44. HANDLE timer_request[2] = { NULL, NULL };
  45. HANDLE timer_response = NULL;
  46. HANDLE driver_handle = INVALID_HANDLE_VALUE;
  47. /*
  48. * Converts a windows error to human readable string
  49. * uses retval as errorcode, or, if 0, use GetLastError()
  50. */
  51. #if defined(ENABLE_LOGGING)
  52. static char* windows_error_str(uint32_t retval)
  53. {
  54. static TCHAR wErr_string[ERR_BUFFER_SIZE];
  55. static char err_string[ERR_BUFFER_SIZE];
  56. DWORD size;
  57. size_t i;
  58. uint32_t error_code, format_error;
  59. error_code = retval?retval:GetLastError();
  60. safe_stprintf(wErr_string, ERR_BUFFER_SIZE, _T("[%d] "), error_code);
  61. size = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error_code,
  62. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &wErr_string[safe_tcslen(wErr_string)],
  63. ERR_BUFFER_SIZE - (DWORD)safe_tcslen(wErr_string), NULL);
  64. if (size == 0) {
  65. format_error = GetLastError();
  66. if (format_error)
  67. safe_stprintf(wErr_string, ERR_BUFFER_SIZE,
  68. _T("Windows error code %u (FormatMessage error code %u)"), error_code, format_error);
  69. else
  70. safe_stprintf(wErr_string, ERR_BUFFER_SIZE, _T("Unknown error code %u"), error_code);
  71. } else {
  72. // Remove CR/LF terminators
  73. for (i=safe_tcslen(wErr_string)-1; ((wErr_string[i]==0x0A) || (wErr_string[i]==0x0D)); i--) {
  74. wErr_string[i] = 0;
  75. }
  76. }
  77. if (WideCharToMultiByte(CP_ACP, 0, wErr_string, -1, err_string, ERR_BUFFER_SIZE, NULL, NULL) < 0)
  78. {
  79. strcpy(err_string, "Unable to convert error string");
  80. }
  81. return err_string;
  82. }
  83. #endif
  84. static struct wince_device_priv *_device_priv(struct libusb_device *dev)
  85. {
  86. return (struct wince_device_priv *) dev->os_priv;
  87. }
  88. // ceusbkwrapper to libusb error code mapping
  89. static int translate_driver_error(int error)
  90. {
  91. switch (error) {
  92. case ERROR_INVALID_PARAMETER:
  93. return LIBUSB_ERROR_INVALID_PARAM;
  94. case ERROR_CALL_NOT_IMPLEMENTED:
  95. case ERROR_NOT_SUPPORTED:
  96. return LIBUSB_ERROR_NOT_SUPPORTED;
  97. case ERROR_NOT_ENOUGH_MEMORY:
  98. return LIBUSB_ERROR_NO_MEM;
  99. case ERROR_INVALID_HANDLE:
  100. return LIBUSB_ERROR_NO_DEVICE;
  101. case ERROR_BUSY:
  102. return LIBUSB_ERROR_BUSY;
  103. // Error codes that are either unexpected, or have
  104. // no suitable LIBUSB_ERROR equivilant.
  105. case ERROR_CANCELLED:
  106. case ERROR_INTERNAL_ERROR:
  107. default:
  108. return LIBUSB_ERROR_OTHER;
  109. }
  110. }
  111. static int init_dllimports()
  112. {
  113. DLL_LOAD(ceusbkwrapper.dll, UkwOpenDriver, TRUE);
  114. DLL_LOAD(ceusbkwrapper.dll, UkwGetDeviceList, TRUE);
  115. DLL_LOAD(ceusbkwrapper.dll, UkwReleaseDeviceList, TRUE);
  116. DLL_LOAD(ceusbkwrapper.dll, UkwGetDeviceAddress, TRUE);
  117. DLL_LOAD(ceusbkwrapper.dll, UkwGetDeviceDescriptor, TRUE);
  118. DLL_LOAD(ceusbkwrapper.dll, UkwGetConfigDescriptor, TRUE);
  119. DLL_LOAD(ceusbkwrapper.dll, UkwCloseDriver, TRUE);
  120. DLL_LOAD(ceusbkwrapper.dll, UkwCancelTransfer, TRUE);
  121. DLL_LOAD(ceusbkwrapper.dll, UkwIssueControlTransfer, TRUE);
  122. DLL_LOAD(ceusbkwrapper.dll, UkwClaimInterface, TRUE);
  123. DLL_LOAD(ceusbkwrapper.dll, UkwReleaseInterface, TRUE);
  124. DLL_LOAD(ceusbkwrapper.dll, UkwSetInterfaceAlternateSetting, TRUE);
  125. DLL_LOAD(ceusbkwrapper.dll, UkwClearHaltHost, TRUE);
  126. DLL_LOAD(ceusbkwrapper.dll, UkwClearHaltDevice, TRUE);
  127. DLL_LOAD(ceusbkwrapper.dll, UkwGetConfig, TRUE);
  128. DLL_LOAD(ceusbkwrapper.dll, UkwSetConfig, TRUE);
  129. DLL_LOAD(ceusbkwrapper.dll, UkwResetDevice, TRUE);
  130. DLL_LOAD(ceusbkwrapper.dll, UkwKernelDriverActive, TRUE);
  131. DLL_LOAD(ceusbkwrapper.dll, UkwAttachKernelDriver, TRUE);
  132. DLL_LOAD(ceusbkwrapper.dll, UkwDetachKernelDriver, TRUE);
  133. DLL_LOAD(ceusbkwrapper.dll, UkwIssueBulkTransfer, TRUE);
  134. DLL_LOAD(ceusbkwrapper.dll, UkwIsPipeHalted, TRUE);
  135. return LIBUSB_SUCCESS;
  136. }
  137. static int init_device(struct libusb_device *dev, UKW_DEVICE drv_dev,
  138. unsigned char bus_addr, unsigned char dev_addr)
  139. {
  140. struct wince_device_priv *priv = _device_priv(dev);
  141. int r = LIBUSB_SUCCESS;
  142. dev->bus_number = bus_addr;
  143. dev->device_address = dev_addr;
  144. priv->dev = drv_dev;
  145. if (!UkwGetDeviceDescriptor(priv->dev, &(priv->desc))) {
  146. r = translate_driver_error(GetLastError());
  147. }
  148. return r;
  149. }
  150. // Internal API functions
  151. static int wince_init(struct libusb_context *ctx)
  152. {
  153. int i, r = LIBUSB_ERROR_OTHER;
  154. HANDLE semaphore;
  155. TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
  156. _stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
  157. semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
  158. if (semaphore == NULL) {
  159. usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
  160. return LIBUSB_ERROR_NO_MEM;
  161. }
  162. // A successful wait brings our semaphore count to 0 (unsignaled)
  163. // => any concurent wait stalls until the semaphore's release
  164. if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
  165. usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
  166. CloseHandle(semaphore);
  167. return LIBUSB_ERROR_NO_MEM;
  168. }
  169. // NB: concurrent usage supposes that init calls are equally balanced with
  170. // exit calls. If init is called more than exit, we will not exit properly
  171. if ( ++concurrent_usage == 0 ) { // First init?
  172. // Initialize pollable file descriptors
  173. init_polling();
  174. // Load DLL imports
  175. if (init_dllimports() != LIBUSB_SUCCESS) {
  176. usbi_err(ctx, "could not resolve DLL functions");
  177. r = LIBUSB_ERROR_NOT_SUPPORTED;
  178. goto init_exit;
  179. }
  180. // try to open a handle to the driver
  181. driver_handle = UkwOpenDriver();
  182. if (driver_handle == INVALID_HANDLE_VALUE) {
  183. usbi_err(ctx, "could not connect to driver");
  184. r = LIBUSB_ERROR_NOT_SUPPORTED;
  185. goto init_exit;
  186. }
  187. // Windows CE doesn't have a way of specifying thread affinity, so this code
  188. // just has to hope QueryPerformanceCounter doesn't report different values when
  189. // running on different cores.
  190. r = LIBUSB_ERROR_NO_MEM;
  191. for (i = 0; i < 2; i++) {
  192. timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
  193. if (timer_request[i] == NULL) {
  194. usbi_err(ctx, "could not create timer request event %d - aborting", i);
  195. goto init_exit;
  196. }
  197. }
  198. timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
  199. if (timer_response == NULL) {
  200. usbi_err(ctx, "could not create timer response semaphore - aborting");
  201. goto init_exit;
  202. }
  203. timer_mutex = CreateMutex(NULL, FALSE, NULL);
  204. if (timer_mutex == NULL) {
  205. usbi_err(ctx, "could not create timer mutex - aborting");
  206. goto init_exit;
  207. }
  208. timer_thread = CreateThread(NULL, 0, wince_clock_gettime_threaded, NULL, 0, NULL);
  209. if (timer_thread == NULL) {
  210. usbi_err(ctx, "Unable to create timer thread - aborting");
  211. goto init_exit;
  212. }
  213. // Wait for timer thread to init before continuing.
  214. if (WaitForSingleObject(timer_response, INFINITE) != WAIT_OBJECT_0) {
  215. usbi_err(ctx, "Failed to wait for timer thread to become ready - aborting");
  216. goto init_exit;
  217. }
  218. }
  219. // At this stage, either we went through full init successfully, or didn't need to
  220. r = LIBUSB_SUCCESS;
  221. init_exit: // Holds semaphore here.
  222. if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
  223. if (driver_handle != INVALID_HANDLE_VALUE) {
  224. UkwCloseDriver(driver_handle);
  225. driver_handle = INVALID_HANDLE_VALUE;
  226. }
  227. if (timer_thread) {
  228. SetEvent(timer_request[1]); // actually the signal to quit the thread.
  229. if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
  230. usbi_warn(ctx, "could not wait for timer thread to quit");
  231. TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
  232. // all objects it might have held anyway.
  233. }
  234. CloseHandle(timer_thread);
  235. timer_thread = NULL;
  236. }
  237. for (i = 0; i < 2; i++) {
  238. if (timer_request[i]) {
  239. CloseHandle(timer_request[i]);
  240. timer_request[i] = NULL;
  241. }
  242. }
  243. if (timer_response) {
  244. CloseHandle(timer_response);
  245. timer_response = NULL;
  246. }
  247. if (timer_mutex) {
  248. CloseHandle(timer_mutex);
  249. timer_mutex = NULL;
  250. }
  251. }
  252. if (r != LIBUSB_SUCCESS)
  253. --concurrent_usage; // Not expected to call libusb_exit if we failed.
  254. ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
  255. CloseHandle(semaphore);
  256. return r;
  257. }
  258. static void wince_exit(void)
  259. {
  260. int i;
  261. HANDLE semaphore;
  262. TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)
  263. _stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
  264. semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
  265. if (semaphore == NULL) {
  266. return;
  267. }
  268. // A successful wait brings our semaphore count to 0 (unsignaled)
  269. // => any concurent wait stalls until the semaphore release
  270. if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
  271. CloseHandle(semaphore);
  272. return;
  273. }
  274. // Only works if exits and inits are balanced exactly
  275. if (--concurrent_usage < 0) { // Last exit
  276. exit_polling();
  277. if (timer_thread) {
  278. SetEvent(timer_request[1]); // actually the signal to quit the thread.
  279. if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
  280. usbi_dbg("could not wait for timer thread to quit");
  281. TerminateThread(timer_thread, 1);
  282. }
  283. CloseHandle(timer_thread);
  284. timer_thread = NULL;
  285. }
  286. for (i = 0; i < 2; i++) {
  287. if (timer_request[i]) {
  288. CloseHandle(timer_request[i]);
  289. timer_request[i] = NULL;
  290. }
  291. }
  292. if (timer_response) {
  293. CloseHandle(timer_response);
  294. timer_response = NULL;
  295. }
  296. if (timer_mutex) {
  297. CloseHandle(timer_mutex);
  298. timer_mutex = NULL;
  299. }
  300. if (driver_handle != INVALID_HANDLE_VALUE) {
  301. UkwCloseDriver(driver_handle);
  302. driver_handle = INVALID_HANDLE_VALUE;
  303. }
  304. }
  305. ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1
  306. CloseHandle(semaphore);
  307. }
  308. static int wince_get_device_list(
  309. struct libusb_context *ctx,
  310. struct discovered_devs **discdevs)
  311. {
  312. UKW_DEVICE devices[MAX_DEVICE_COUNT];
  313. struct discovered_devs * new_devices = *discdevs;
  314. DWORD count = 0, i;
  315. struct libusb_device *dev = NULL;
  316. unsigned char bus_addr, dev_addr;
  317. unsigned long session_id;
  318. BOOL success;
  319. DWORD release_list_offset = 0;
  320. int r = LIBUSB_SUCCESS;
  321. success = UkwGetDeviceList(driver_handle, devices, MAX_DEVICE_COUNT, &count);
  322. if (!success) {
  323. int libusbErr = translate_driver_error(GetLastError());
  324. usbi_err(ctx, "could not get devices: %s", windows_error_str(0));
  325. return libusbErr;
  326. }
  327. for(i = 0; i < count; ++i) {
  328. release_list_offset = i;
  329. success = UkwGetDeviceAddress(devices[i], &bus_addr, &dev_addr, &session_id);
  330. if (!success) {
  331. r = translate_driver_error(GetLastError());
  332. usbi_err(ctx, "could not get device address for %d: %s", i, windows_error_str(0));
  333. goto err_out;
  334. }
  335. dev = usbi_get_device_by_session_id(ctx, session_id);
  336. if (dev) {
  337. usbi_dbg("using existing device for %d/%d (session %ld)",
  338. bus_addr, dev_addr, session_id);
  339. libusb_ref_device(dev);
  340. // Release just this element in the device list (as we already hold a
  341. // reference to it).
  342. UkwReleaseDeviceList(driver_handle, &devices[i], 1);
  343. release_list_offset++;
  344. } else {
  345. usbi_dbg("allocating new device for %d/%d (session %ld)",
  346. bus_addr, dev_addr, session_id);
  347. dev = usbi_alloc_device(ctx, session_id);
  348. if (!dev) {
  349. r = LIBUSB_ERROR_NO_MEM;
  350. goto err_out;
  351. }
  352. r = init_device(dev, devices[i], bus_addr, dev_addr);
  353. if (r < 0)
  354. goto err_out;
  355. r = usbi_sanitize_device(dev);
  356. if (r < 0)
  357. goto err_out;
  358. }
  359. new_devices = discovered_devs_append(new_devices, dev);
  360. if (!discdevs) {
  361. r = LIBUSB_ERROR_NO_MEM;
  362. goto err_out;
  363. }
  364. safe_unref_device(dev);
  365. }
  366. *discdevs = new_devices;
  367. return r;
  368. err_out:
  369. *discdevs = new_devices;
  370. safe_unref_device(dev);
  371. // Release the remainder of the unprocessed device list.
  372. // The devices added to new_devices already will still be passed up to libusb,
  373. // which can dispose of them at its leisure.
  374. UkwReleaseDeviceList(driver_handle, &devices[release_list_offset], count - release_list_offset);
  375. return r;
  376. }
  377. static int wince_open(struct libusb_device_handle *handle)
  378. {
  379. // Nothing to do to open devices as a handle to it has
  380. // been retrieved by wince_get_device_list
  381. return LIBUSB_SUCCESS;
  382. }
  383. static void wince_close(struct libusb_device_handle *handle)
  384. {
  385. // Nothing to do as wince_open does nothing.
  386. }
  387. static int wince_get_device_descriptor(
  388. struct libusb_device *device,
  389. unsigned char *buffer, int *host_endian)
  390. {
  391. struct wince_device_priv *priv = _device_priv(device);
  392. *host_endian = 1;
  393. memcpy(buffer, &priv->desc, DEVICE_DESC_LENGTH);
  394. return LIBUSB_SUCCESS;
  395. }
  396. static int wince_get_active_config_descriptor(
  397. struct libusb_device *device,
  398. unsigned char *buffer, size_t len, int *host_endian)
  399. {
  400. struct wince_device_priv *priv = _device_priv(device);
  401. DWORD actualSize = len;
  402. *host_endian = 0;
  403. if (!UkwGetConfigDescriptor(priv->dev, UKW_ACTIVE_CONFIGURATION, buffer, len, &actualSize)) {
  404. return translate_driver_error(GetLastError());
  405. }
  406. return actualSize;
  407. }
  408. static int wince_get_config_descriptor(
  409. struct libusb_device *device,
  410. uint8_t config_index,
  411. unsigned char *buffer, size_t len, int *host_endian)
  412. {
  413. struct wince_device_priv *priv = _device_priv(device);
  414. DWORD actualSize = len;
  415. *host_endian = 0;
  416. if (!UkwGetConfigDescriptor(priv->dev, config_index, buffer, len, &actualSize)) {
  417. return translate_driver_error(GetLastError());
  418. }
  419. return actualSize;
  420. }
  421. static int wince_get_configuration(
  422. struct libusb_device_handle *handle,
  423. int *config)
  424. {
  425. struct wince_device_priv *priv = _device_priv(handle->dev);
  426. UCHAR cv = 0;
  427. if (!UkwGetConfig(priv->dev, &cv)) {
  428. return translate_driver_error(GetLastError());
  429. }
  430. (*config) = cv;
  431. return LIBUSB_SUCCESS;
  432. }
  433. static int wince_set_configuration(
  434. struct libusb_device_handle *handle,
  435. int config)
  436. {
  437. struct wince_device_priv *priv = _device_priv(handle->dev);
  438. // Setting configuration 0 places the device in Address state.
  439. // This should correspond to the "unconfigured state" required by
  440. // libusb when the specified configuration is -1.
  441. UCHAR cv = (config < 0) ? 0 : config;
  442. if (!UkwSetConfig(priv->dev, cv)) {
  443. return translate_driver_error(GetLastError());
  444. }
  445. return LIBUSB_SUCCESS;
  446. }
  447. static int wince_claim_interface(
  448. struct libusb_device_handle *handle,
  449. int interface_number)
  450. {
  451. struct wince_device_priv *priv = _device_priv(handle->dev);
  452. if (!UkwClaimInterface(priv->dev, interface_number)) {
  453. return translate_driver_error(GetLastError());
  454. }
  455. return LIBUSB_SUCCESS;
  456. }
  457. static int wince_release_interface(
  458. struct libusb_device_handle *handle,
  459. int interface_number)
  460. {
  461. struct wince_device_priv *priv = _device_priv(handle->dev);
  462. if (!UkwSetInterfaceAlternateSetting(priv->dev, interface_number, 0)) {
  463. return translate_driver_error(GetLastError());
  464. }
  465. if (!UkwReleaseInterface(priv->dev, interface_number)) {
  466. return translate_driver_error(GetLastError());
  467. }
  468. return LIBUSB_SUCCESS;
  469. }
  470. static int wince_set_interface_altsetting(
  471. struct libusb_device_handle *handle,
  472. int interface_number, int altsetting)
  473. {
  474. struct wince_device_priv *priv = _device_priv(handle->dev);
  475. if (!UkwSetInterfaceAlternateSetting(priv->dev, interface_number, altsetting)) {
  476. return translate_driver_error(GetLastError());
  477. }
  478. return LIBUSB_SUCCESS;
  479. }
  480. static int wince_clear_halt(
  481. struct libusb_device_handle *handle,
  482. unsigned char endpoint)
  483. {
  484. struct wince_device_priv *priv = _device_priv(handle->dev);
  485. if (!UkwClearHaltHost(priv->dev, endpoint)) {
  486. return translate_driver_error(GetLastError());
  487. }
  488. if (!UkwClearHaltDevice(priv->dev, endpoint)) {
  489. return translate_driver_error(GetLastError());
  490. }
  491. return LIBUSB_SUCCESS;
  492. }
  493. static int wince_reset_device(
  494. struct libusb_device_handle *handle)
  495. {
  496. struct wince_device_priv *priv = _device_priv(handle->dev);
  497. if (!UkwResetDevice(priv->dev)) {
  498. return translate_driver_error(GetLastError());
  499. }
  500. return LIBUSB_SUCCESS;
  501. }
  502. static int wince_kernel_driver_active(
  503. struct libusb_device_handle *handle,
  504. int interface_number)
  505. {
  506. struct wince_device_priv *priv = _device_priv(handle->dev);
  507. BOOL result = FALSE;
  508. if (!UkwKernelDriverActive(priv->dev, interface_number, &result)) {
  509. return translate_driver_error(GetLastError());
  510. }
  511. return result ? 1 : 0;
  512. }
  513. static int wince_detach_kernel_driver(
  514. struct libusb_device_handle *handle,
  515. int interface_number)
  516. {
  517. struct wince_device_priv *priv = _device_priv(handle->dev);
  518. if (!UkwDetachKernelDriver(priv->dev, interface_number)) {
  519. return translate_driver_error(GetLastError());
  520. }
  521. return LIBUSB_SUCCESS;
  522. }
  523. static int wince_attach_kernel_driver(
  524. struct libusb_device_handle *handle,
  525. int interface_number)
  526. {
  527. struct wince_device_priv *priv = _device_priv(handle->dev);
  528. if (!UkwAttachKernelDriver(priv->dev, interface_number)) {
  529. return translate_driver_error(GetLastError());
  530. }
  531. return LIBUSB_SUCCESS;
  532. }
  533. static void wince_destroy_device(
  534. struct libusb_device *dev)
  535. {
  536. struct wince_device_priv *priv = _device_priv(dev);
  537. UkwReleaseDeviceList(driver_handle, &priv->dev, 1);
  538. }
  539. static void wince_clear_transfer_priv(
  540. struct usbi_transfer *itransfer)
  541. {
  542. struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  543. struct winfd wfd = fd_to_winfd(transfer_priv->pollable_fd.fd);
  544. // No need to cancel transfer as it is either complete or abandoned
  545. wfd.itransfer = NULL;
  546. CloseHandle(wfd.handle);
  547. usbi_free_fd(&transfer_priv->pollable_fd);
  548. }
  549. static int wince_cancel_transfer(
  550. struct usbi_transfer *itransfer)
  551. {
  552. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  553. struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  554. struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  555. if (!UkwCancelTransfer(priv->dev, transfer_priv->pollable_fd.overlapped, UKW_TF_NO_WAIT)) {
  556. return translate_driver_error(GetLastError());
  557. }
  558. return LIBUSB_SUCCESS;
  559. }
  560. static int wince_submit_control_or_bulk_transfer(struct usbi_transfer *itransfer)
  561. {
  562. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  563. struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
  564. struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  565. struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  566. BOOL direction_in, ret;
  567. struct winfd wfd;
  568. DWORD flags;
  569. HANDLE eventHandle;
  570. PUKW_CONTROL_HEADER setup = NULL;
  571. const BOOL control_transfer = transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL;
  572. transfer_priv->pollable_fd = INVALID_WINFD;
  573. if (control_transfer) {
  574. setup = (PUKW_CONTROL_HEADER) transfer->buffer;
  575. direction_in = setup->bmRequestType & LIBUSB_ENDPOINT_IN;
  576. } else {
  577. direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
  578. }
  579. flags = direction_in ? UKW_TF_IN_TRANSFER : UKW_TF_OUT_TRANSFER;
  580. flags |= UKW_TF_SHORT_TRANSFER_OK;
  581. eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
  582. if (eventHandle == NULL) {
  583. usbi_err(ctx, "Failed to create event for async transfer");
  584. return LIBUSB_ERROR_NO_MEM;
  585. }
  586. wfd = usbi_create_fd(eventHandle, direction_in ? RW_READ : RW_WRITE, itransfer, &wince_cancel_transfer);
  587. if (wfd.fd < 0) {
  588. CloseHandle(eventHandle);
  589. return LIBUSB_ERROR_NO_MEM;
  590. }
  591. transfer_priv->pollable_fd = wfd;
  592. if (control_transfer) {
  593. // Split out control setup header and data buffer
  594. DWORD bufLen = transfer->length - sizeof(UKW_CONTROL_HEADER);
  595. PVOID buf = (PVOID) &transfer->buffer[sizeof(UKW_CONTROL_HEADER)];
  596. ret = UkwIssueControlTransfer(priv->dev, flags, setup, buf, bufLen, &transfer->actual_length, wfd.overlapped);
  597. } else {
  598. ret = UkwIssueBulkTransfer(priv->dev, flags, transfer->endpoint, transfer->buffer,
  599. transfer->length, &transfer->actual_length, wfd.overlapped);
  600. }
  601. if (!ret) {
  602. int libusbErr = translate_driver_error(GetLastError());
  603. usbi_err(ctx, "UkwIssue%sTransfer failed: error %d",
  604. control_transfer ? "Control" : "Bulk", GetLastError());
  605. wince_clear_transfer_priv(itransfer);
  606. return libusbErr;
  607. }
  608. usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, direction_in ? POLLIN : POLLOUT);
  609. itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
  610. return LIBUSB_SUCCESS;
  611. }
  612. static int wince_submit_iso_transfer(struct usbi_transfer *itransfer)
  613. {
  614. return LIBUSB_ERROR_NOT_SUPPORTED;
  615. }
  616. static int wince_submit_transfer(
  617. struct usbi_transfer *itransfer)
  618. {
  619. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  620. switch (transfer->type) {
  621. case LIBUSB_TRANSFER_TYPE_CONTROL:
  622. case LIBUSB_TRANSFER_TYPE_BULK:
  623. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  624. return wince_submit_control_or_bulk_transfer(itransfer);
  625. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  626. return wince_submit_iso_transfer(itransfer);
  627. default:
  628. usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  629. return LIBUSB_ERROR_INVALID_PARAM;
  630. }
  631. }
  632. static void wince_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
  633. {
  634. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  635. struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
  636. struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev);
  637. int status;
  638. usbi_dbg("handling I/O completion with errcode %d", io_result);
  639. if (io_result == ERROR_NOT_SUPPORTED &&
  640. transfer->type != LIBUSB_TRANSFER_TYPE_CONTROL) {
  641. /* For functional stalls, the WinCE USB layer (and therefore the USB Kernel Wrapper
  642. * Driver) will report USB_ERROR_STALL/ERROR_NOT_SUPPORTED in situations where the
  643. * endpoint isn't actually stalled.
  644. *
  645. * One example of this is that some devices will occasionally fail to reply to an IN
  646. * token. The WinCE USB layer carries on with the transaction until it is completed
  647. * (or cancelled) but then completes it with USB_ERROR_STALL.
  648. *
  649. * This code therefore needs to confirm that there really is a stall error, by both
  650. * checking the pipe status and requesting the endpoint status from the device.
  651. */
  652. BOOL halted = FALSE;
  653. usbi_dbg("checking I/O completion with errcode ERROR_NOT_SUPPORTED is really a stall");
  654. if (UkwIsPipeHalted(priv->dev, transfer->endpoint, &halted)) {
  655. /* Pipe status retrieved, so now request endpoint status by sending a GET_STATUS
  656. * control request to the device. This is done synchronously, which is a bit
  657. * naughty, but this is a special corner case.
  658. */
  659. WORD wStatus = 0;
  660. DWORD written = 0;
  661. UKW_CONTROL_HEADER ctrlHeader;
  662. ctrlHeader.bmRequestType = LIBUSB_REQUEST_TYPE_STANDARD |
  663. LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_ENDPOINT;
  664. ctrlHeader.bRequest = LIBUSB_REQUEST_GET_STATUS;
  665. ctrlHeader.wValue = 0;
  666. ctrlHeader.wIndex = transfer->endpoint;
  667. ctrlHeader.wLength = sizeof(wStatus);
  668. if (UkwIssueControlTransfer(priv->dev,
  669. UKW_TF_IN_TRANSFER | UKW_TF_SEND_TO_ENDPOINT,
  670. &ctrlHeader, &wStatus, sizeof(wStatus), &written, NULL)) {
  671. if (written == sizeof(wStatus) &&
  672. (wStatus & STATUS_HALT_FLAG) == 0) {
  673. if (!halted || UkwClearHaltHost(priv->dev, transfer->endpoint)) {
  674. usbi_dbg("Endpoint doesn't appear to be stalled, overriding error with success");
  675. io_result = ERROR_SUCCESS;
  676. } else {
  677. usbi_dbg("Endpoint doesn't appear to be stalled, but the host is halted, changing error");
  678. io_result = ERROR_IO_DEVICE;
  679. }
  680. }
  681. }
  682. }
  683. }
  684. switch(io_result) {
  685. case ERROR_SUCCESS:
  686. itransfer->transferred += io_size;
  687. status = LIBUSB_TRANSFER_COMPLETED;
  688. break;
  689. case ERROR_CANCELLED:
  690. usbi_dbg("detected transfer cancel");
  691. status = LIBUSB_TRANSFER_CANCELLED;
  692. break;
  693. case ERROR_NOT_SUPPORTED:
  694. case ERROR_GEN_FAILURE:
  695. usbi_dbg("detected endpoint stall");
  696. status = LIBUSB_TRANSFER_STALL;
  697. break;
  698. case ERROR_SEM_TIMEOUT:
  699. usbi_dbg("detected semaphore timeout");
  700. status = LIBUSB_TRANSFER_TIMED_OUT;
  701. break;
  702. case ERROR_OPERATION_ABORTED:
  703. if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
  704. usbi_dbg("detected timeout");
  705. status = LIBUSB_TRANSFER_TIMED_OUT;
  706. } else {
  707. usbi_dbg("detected operation aborted");
  708. status = LIBUSB_TRANSFER_CANCELLED;
  709. }
  710. break;
  711. default:
  712. usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(io_result));
  713. status = LIBUSB_TRANSFER_ERROR;
  714. break;
  715. }
  716. wince_clear_transfer_priv(itransfer);
  717. if (status == LIBUSB_TRANSFER_CANCELLED) {
  718. usbi_handle_transfer_cancellation(itransfer);
  719. } else {
  720. usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
  721. }
  722. }
  723. static void wince_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
  724. {
  725. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  726. switch (transfer->type) {
  727. case LIBUSB_TRANSFER_TYPE_CONTROL:
  728. case LIBUSB_TRANSFER_TYPE_BULK:
  729. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  730. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  731. wince_transfer_callback (itransfer, io_result, io_size);
  732. break;
  733. default:
  734. usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
  735. }
  736. }
  737. static int wince_handle_events(
  738. struct libusb_context *ctx,
  739. struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
  740. {
  741. struct wince_transfer_priv* transfer_priv = NULL;
  742. POLL_NFDS_TYPE i = 0;
  743. BOOL found = FALSE;
  744. struct usbi_transfer *transfer;
  745. DWORD io_size, io_result;
  746. usbi_mutex_lock(&ctx->open_devs_lock);
  747. for (i = 0; i < nfds && num_ready > 0; i++) {
  748. usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
  749. if (!fds[i].revents) {
  750. continue;
  751. }
  752. num_ready--;
  753. // Because a Windows OVERLAPPED is used for poll emulation,
  754. // a pollable fd is created and stored with each transfer
  755. usbi_mutex_lock(&ctx->flying_transfers_lock);
  756. list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
  757. transfer_priv = usbi_transfer_get_os_priv(transfer);
  758. if (transfer_priv->pollable_fd.fd == fds[i].fd) {
  759. found = TRUE;
  760. break;
  761. }
  762. }
  763. usbi_mutex_unlock(&ctx->flying_transfers_lock);
  764. if (found && HasOverlappedIoCompleted(transfer_priv->pollable_fd.overlapped)) {
  765. io_result = (DWORD)transfer_priv->pollable_fd.overlapped->Internal;
  766. io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
  767. usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
  768. // let handle_callback free the event using the transfer wfd
  769. // If you don't use the transfer wfd, you run a risk of trying to free a
  770. // newly allocated wfd that took the place of the one from the transfer.
  771. wince_handle_callback(transfer, io_result, io_size);
  772. } else if (found) {
  773. usbi_err(ctx, "matching transfer for fd %x has not completed", fds[i]);
  774. return LIBUSB_ERROR_OTHER;
  775. } else {
  776. usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
  777. return LIBUSB_ERROR_NOT_FOUND;
  778. }
  779. }
  780. usbi_mutex_unlock(&ctx->open_devs_lock);
  781. return LIBUSB_SUCCESS;
  782. }
  783. /*
  784. * Monotonic and real time functions
  785. */
  786. unsigned __stdcall wince_clock_gettime_threaded(void* param)
  787. {
  788. LARGE_INTEGER hires_counter, li_frequency;
  789. LONG nb_responses;
  790. int timer_index;
  791. // Init - find out if we have access to a monotonic (hires) timer
  792. if (!QueryPerformanceFrequency(&li_frequency)) {
  793. usbi_dbg("no hires timer available on this platform");
  794. hires_frequency = 0;
  795. hires_ticks_to_ps = UINT64_C(0);
  796. } else {
  797. hires_frequency = li_frequency.QuadPart;
  798. // The hires frequency can go as high as 4 GHz, so we'll use a conversion
  799. // to picoseconds to compute the tv_nsecs part in clock_gettime
  800. hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
  801. usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
  802. }
  803. // Signal wince_init() that we're ready to service requests
  804. if (ReleaseSemaphore(timer_response, 1, NULL) == 0) {
  805. usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
  806. }
  807. // Main loop - wait for requests
  808. while (1) {
  809. timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
  810. if ( (timer_index != 0) && (timer_index != 1) ) {
  811. usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
  812. continue;
  813. }
  814. if (request_count[timer_index] == 0) {
  815. // Request already handled
  816. ResetEvent(timer_request[timer_index]);
  817. // There's still a possiblity that a thread sends a request between the
  818. // time we test request_count[] == 0 and we reset the event, in which case
  819. // the request would be ignored. The simple solution to that is to test
  820. // request_count again and process requests if non zero.
  821. if (request_count[timer_index] == 0)
  822. continue;
  823. }
  824. switch (timer_index) {
  825. case 0:
  826. WaitForSingleObject(timer_mutex, INFINITE);
  827. // Requests to this thread are for hires always
  828. if (QueryPerformanceCounter(&hires_counter) != 0) {
  829. timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
  830. timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
  831. } else {
  832. // Fallback to real-time if we can't get monotonic value
  833. // Note that real-time clock does not wait on the mutex or this thread.
  834. wince_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
  835. }
  836. ReleaseMutex(timer_mutex);
  837. nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
  838. if ( (nb_responses)
  839. && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
  840. usbi_dbg("unable to release timer semaphore: %s", windows_error_str(0));
  841. }
  842. continue;
  843. case 1: // time to quit
  844. usbi_dbg("timer thread quitting");
  845. return 0;
  846. }
  847. }
  848. usbi_dbg("ERROR: broken timer thread");
  849. return 1;
  850. }
  851. static int wince_clock_gettime(int clk_id, struct timespec *tp)
  852. {
  853. FILETIME filetime;
  854. ULARGE_INTEGER rtime;
  855. DWORD r;
  856. SYSTEMTIME st;
  857. switch(clk_id) {
  858. case USBI_CLOCK_MONOTONIC:
  859. if (hires_frequency != 0) {
  860. while (1) {
  861. InterlockedIncrement((LONG*)&request_count[0]);
  862. SetEvent(timer_request[0]);
  863. r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
  864. switch(r) {
  865. case WAIT_OBJECT_0:
  866. WaitForSingleObject(timer_mutex, INFINITE);
  867. *tp = timer_tp;
  868. ReleaseMutex(timer_mutex);
  869. return LIBUSB_SUCCESS;
  870. case WAIT_TIMEOUT:
  871. usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
  872. break; // Retry until successful
  873. default:
  874. usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
  875. return LIBUSB_ERROR_OTHER;
  876. }
  877. }
  878. }
  879. // Fall through and return real-time if monotonic was not detected @ timer init
  880. case USBI_CLOCK_REALTIME:
  881. // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
  882. // with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
  883. // Note however that our resolution is bounded by the Windows system time
  884. // functions and is at best of the order of 1 ms (or, usually, worse)
  885. GetSystemTime(&st);
  886. SystemTimeToFileTime(&st, &filetime);
  887. rtime.LowPart = filetime.dwLowDateTime;
  888. rtime.HighPart = filetime.dwHighDateTime;
  889. rtime.QuadPart -= epoch_time;
  890. tp->tv_sec = (long)(rtime.QuadPart / 10000000);
  891. tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
  892. return LIBUSB_SUCCESS;
  893. default:
  894. return LIBUSB_ERROR_INVALID_PARAM;
  895. }
  896. }
  897. const struct usbi_os_backend wince_backend = {
  898. "Windows CE",
  899. 0,
  900. wince_init,
  901. wince_exit,
  902. wince_get_device_list,
  903. NULL, /* hotplug_poll */
  904. wince_open,
  905. wince_close,
  906. wince_get_device_descriptor,
  907. wince_get_active_config_descriptor,
  908. wince_get_config_descriptor,
  909. NULL, /* get_config_descriptor_by_value() */
  910. wince_get_configuration,
  911. wince_set_configuration,
  912. wince_claim_interface,
  913. wince_release_interface,
  914. wince_set_interface_altsetting,
  915. wince_clear_halt,
  916. wince_reset_device,
  917. wince_kernel_driver_active,
  918. wince_detach_kernel_driver,
  919. wince_attach_kernel_driver,
  920. wince_destroy_device,
  921. wince_submit_transfer,
  922. wince_cancel_transfer,
  923. wince_clear_transfer_priv,
  924. wince_handle_events,
  925. wince_clock_gettime,
  926. sizeof(struct wince_device_priv),
  927. sizeof(struct wince_device_handle_priv),
  928. sizeof(struct wince_transfer_priv),
  929. 0,
  930. };