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