Home | History | Annotate | Download | only in os
      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 (at) 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 = NULL;
    345 	unsigned char bus_addr, dev_addr;
    346 	unsigned long session_id;
    347 	BOOL success;
    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 			libusb_ref_device(dev);
    370 			// Release just this element in the device list (as we already hold a
    371 			// reference to it).
    372 			UkwReleaseDeviceList(driver_handle, &devices[i], 1);
    373 			release_list_offset++;
    374 		} else {
    375 			usbi_dbg("allocating new device for %d/%d (session %ld)",
    376 					bus_addr, dev_addr, session_id);
    377 			dev = usbi_alloc_device(ctx, session_id);
    378 			if (!dev) {
    379 				r = LIBUSB_ERROR_NO_MEM;
    380 				goto err_out;
    381 			}
    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 		safe_unref_device(dev);
    395 	}
    396 	*discdevs = new_devices;
    397 	return r;
    398 err_out:
    399 	*discdevs = new_devices;
    400 	safe_unref_device(dev);
    401 	// Release the remainder of the unprocessed device list.
    402 	// The devices added to new_devices already will still be passed up to libusb,
    403 	// which can dispose of them at its leisure.
    404 	UkwReleaseDeviceList(driver_handle, &devices[release_list_offset], count - release_list_offset);
    405 	return r;
    406 }
    407 
    408 static int wince_open(struct libusb_device_handle *handle)
    409 {
    410 	// Nothing to do to open devices as a handle to it has
    411 	// been retrieved by wince_get_device_list
    412 	return LIBUSB_SUCCESS;
    413 }
    414 
    415 static void wince_close(struct libusb_device_handle *handle)
    416 {
    417 	// Nothing to do as wince_open does nothing.
    418 }
    419 
    420 static int wince_get_device_descriptor(
    421    struct libusb_device *device,
    422    unsigned char *buffer, int *host_endian)
    423 {
    424 	struct wince_device_priv *priv = _device_priv(device);
    425 
    426 	*host_endian = 1;
    427 	memcpy(buffer, &priv->desc, DEVICE_DESC_LENGTH);
    428 	return LIBUSB_SUCCESS;
    429 }
    430 
    431 static int wince_get_active_config_descriptor(
    432 	struct libusb_device *device,
    433 	unsigned char *buffer, size_t len, int *host_endian)
    434 {
    435 	struct wince_device_priv *priv = _device_priv(device);
    436 	DWORD actualSize = len;
    437 	*host_endian = 0;
    438 	if (!UkwGetConfigDescriptor(priv->dev, UKW_ACTIVE_CONFIGURATION, buffer, len, &actualSize)) {
    439 		return translate_driver_error(GetLastError());
    440 	}
    441 	return actualSize;
    442 }
    443 
    444 static int wince_get_config_descriptor(
    445 	struct libusb_device *device,
    446 	uint8_t config_index,
    447 	unsigned char *buffer, size_t len, int *host_endian)
    448 {
    449 	struct wince_device_priv *priv = _device_priv(device);
    450 	DWORD actualSize = len;
    451 	*host_endian = 0;
    452 	if (!UkwGetConfigDescriptor(priv->dev, config_index, buffer, len, &actualSize)) {
    453 		return translate_driver_error(GetLastError());
    454 	}
    455 	return actualSize;
    456 }
    457 
    458 static int wince_get_configuration(
    459    struct libusb_device_handle *handle,
    460    int *config)
    461 {
    462 	struct wince_device_priv *priv = _device_priv(handle->dev);
    463 	UCHAR cv = 0;
    464 	if (!UkwGetConfig(priv->dev, &cv)) {
    465 		return translate_driver_error(GetLastError());
    466 	}
    467 	(*config) = cv;
    468 	return LIBUSB_SUCCESS;
    469 }
    470 
    471 static int wince_set_configuration(
    472 	struct libusb_device_handle *handle,
    473 	int config)
    474 {
    475 	struct wince_device_priv *priv = _device_priv(handle->dev);
    476 	// Setting configuration 0 places the device in Address state.
    477 	// This should correspond to the "unconfigured state" required by
    478 	// libusb when the specified configuration is -1.
    479 	UCHAR cv = (config < 0) ? 0 : config;
    480 	if (!UkwSetConfig(priv->dev, cv)) {
    481 		return translate_driver_error(GetLastError());
    482 	}
    483 	return LIBUSB_SUCCESS;
    484 }
    485 
    486 static int wince_claim_interface(
    487 	struct libusb_device_handle *handle,
    488 	int interface_number)
    489 {
    490 	struct wince_device_priv *priv = _device_priv(handle->dev);
    491 	if (!UkwClaimInterface(priv->dev, interface_number)) {
    492 		return translate_driver_error(GetLastError());
    493 	}
    494 	return LIBUSB_SUCCESS;
    495 }
    496 
    497 static int wince_release_interface(
    498 	struct libusb_device_handle *handle,
    499 	int interface_number)
    500 {
    501 	struct wince_device_priv *priv = _device_priv(handle->dev);
    502 	if (!UkwSetInterfaceAlternateSetting(priv->dev, interface_number, 0)) {
    503 		return translate_driver_error(GetLastError());
    504 	}
    505 	if (!UkwReleaseInterface(priv->dev, interface_number)) {
    506 		return translate_driver_error(GetLastError());
    507 	}
    508 	return LIBUSB_SUCCESS;
    509 }
    510 
    511 static int wince_set_interface_altsetting(
    512 	struct libusb_device_handle *handle,
    513 	int interface_number, int altsetting)
    514 {
    515 	struct wince_device_priv *priv = _device_priv(handle->dev);
    516 	if (!UkwSetInterfaceAlternateSetting(priv->dev, interface_number, altsetting)) {
    517 		return translate_driver_error(GetLastError());
    518 	}
    519 	return LIBUSB_SUCCESS;
    520 }
    521 
    522 static int wince_clear_halt(
    523 	struct libusb_device_handle *handle,
    524 	unsigned char endpoint)
    525 {
    526 	struct wince_device_priv *priv = _device_priv(handle->dev);
    527 	if (!UkwClearHaltHost(priv->dev, endpoint)) {
    528 		return translate_driver_error(GetLastError());
    529 	}
    530 	if (!UkwClearHaltDevice(priv->dev, endpoint)) {
    531 		return translate_driver_error(GetLastError());
    532 	}
    533 	return LIBUSB_SUCCESS;
    534 }
    535 
    536 static int wince_reset_device(
    537 	struct libusb_device_handle *handle)
    538 {
    539 	struct wince_device_priv *priv = _device_priv(handle->dev);
    540 	if (!UkwResetDevice(priv->dev)) {
    541 		return translate_driver_error(GetLastError());
    542 	}
    543 	return LIBUSB_SUCCESS;
    544 }
    545 
    546 static int wince_kernel_driver_active(
    547 	struct libusb_device_handle *handle,
    548 	int interface_number)
    549 {
    550 	struct wince_device_priv *priv = _device_priv(handle->dev);
    551 	BOOL result = FALSE;
    552 	if (!UkwKernelDriverActive(priv->dev, interface_number, &result)) {
    553 		return translate_driver_error(GetLastError());
    554 	}
    555 	return result ? 1 : 0;
    556 }
    557 
    558 static int wince_detach_kernel_driver(
    559 	struct libusb_device_handle *handle,
    560 	int interface_number)
    561 {
    562 	struct wince_device_priv *priv = _device_priv(handle->dev);
    563 	if (!UkwDetachKernelDriver(priv->dev, interface_number)) {
    564 		return translate_driver_error(GetLastError());
    565 	}
    566 	return LIBUSB_SUCCESS;
    567 }
    568 
    569 static int wince_attach_kernel_driver(
    570 	struct libusb_device_handle *handle,
    571 	int interface_number)
    572 {
    573 	struct wince_device_priv *priv = _device_priv(handle->dev);
    574 	if (!UkwAttachKernelDriver(priv->dev, interface_number)) {
    575 		return translate_driver_error(GetLastError());
    576 	}
    577 	return LIBUSB_SUCCESS;
    578 }
    579 
    580 static void wince_destroy_device(
    581 	struct libusb_device *dev)
    582 {
    583 	struct wince_device_priv *priv = _device_priv(dev);
    584 	UkwReleaseDeviceList(driver_handle, &priv->dev, 1);
    585 }
    586 
    587 static void wince_clear_transfer_priv(
    588 	struct usbi_transfer *itransfer)
    589 {
    590 	struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
    591 	struct winfd wfd = fd_to_winfd(transfer_priv->pollable_fd.fd);
    592 	// No need to cancel transfer as it is either complete or abandoned
    593 	wfd.itransfer = NULL;
    594 	CloseHandle(wfd.handle);
    595 	usbi_free_fd(&transfer_priv->pollable_fd);
    596 }
    597 
    598 static int wince_cancel_transfer(
    599 	struct usbi_transfer *itransfer)
    600 {
    601 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    602 	struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev);
    603 	struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
    604 
    605 	if (!UkwCancelTransfer(priv->dev, transfer_priv->pollable_fd.overlapped, UKW_TF_NO_WAIT)) {
    606 		return translate_driver_error(GetLastError());
    607 	}
    608 	return LIBUSB_SUCCESS;
    609 }
    610 
    611 static int wince_submit_control_or_bulk_transfer(struct usbi_transfer *itransfer)
    612 {
    613 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    614 	struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev);
    615 	struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
    616 	struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev);
    617 	BOOL direction_in, ret;
    618 	struct winfd wfd;
    619 	DWORD flags;
    620 	HANDLE eventHandle;
    621 	PUKW_CONTROL_HEADER setup = NULL;
    622 	const BOOL control_transfer = transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL;
    623 
    624 	transfer_priv->pollable_fd = INVALID_WINFD;
    625 	if (control_transfer) {
    626 		setup = (PUKW_CONTROL_HEADER) transfer->buffer;
    627 		direction_in = setup->bmRequestType & LIBUSB_ENDPOINT_IN;
    628 	} else {
    629 		direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN;
    630 	}
    631 	flags = direction_in ? UKW_TF_IN_TRANSFER : UKW_TF_OUT_TRANSFER;
    632 	flags |= UKW_TF_SHORT_TRANSFER_OK;
    633 
    634 	eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
    635 	if (eventHandle == NULL) {
    636 		usbi_err(ctx, "Failed to create event for async transfer");
    637 		return LIBUSB_ERROR_NO_MEM;
    638 	}
    639 
    640 	wfd = usbi_create_fd(eventHandle, direction_in ? RW_READ : RW_WRITE, itransfer, &wince_cancel_transfer);
    641 	if (wfd.fd < 0) {
    642 		CloseHandle(eventHandle);
    643 		return LIBUSB_ERROR_NO_MEM;
    644 	}
    645 
    646 	transfer_priv->pollable_fd = wfd;
    647 	if (control_transfer) {
    648 		// Split out control setup header and data buffer
    649 		DWORD bufLen = transfer->length - sizeof(UKW_CONTROL_HEADER);
    650 		PVOID buf = (PVOID) &transfer->buffer[sizeof(UKW_CONTROL_HEADER)];
    651 
    652 		ret = UkwIssueControlTransfer(priv->dev, flags, setup, buf, bufLen, &transfer->actual_length, wfd.overlapped);
    653 	} else {
    654 		ret = UkwIssueBulkTransfer(priv->dev, flags, transfer->endpoint, transfer->buffer,
    655 			transfer->length, &transfer->actual_length, wfd.overlapped);
    656 	}
    657 	if (!ret) {
    658 		int libusbErr = translate_driver_error(GetLastError());
    659 		usbi_err(ctx, "UkwIssue%sTransfer failed: error %d",
    660 			control_transfer ? "Control" : "Bulk", GetLastError());
    661 		wince_clear_transfer_priv(itransfer);
    662 		return libusbErr;
    663 	}
    664 	usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, direction_in ? POLLIN : POLLOUT);
    665 	itransfer->flags |= USBI_TRANSFER_UPDATED_FDS;
    666 
    667 	return LIBUSB_SUCCESS;
    668 }
    669 
    670 static int wince_submit_iso_transfer(struct usbi_transfer *itransfer)
    671 {
    672 	return LIBUSB_ERROR_NOT_SUPPORTED;
    673 }
    674 
    675 static int wince_submit_transfer(
    676 	struct usbi_transfer *itransfer)
    677 {
    678 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    679 
    680 	switch (transfer->type) {
    681 	case LIBUSB_TRANSFER_TYPE_CONTROL:
    682 	case LIBUSB_TRANSFER_TYPE_BULK:
    683 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
    684 		return wince_submit_control_or_bulk_transfer(itransfer);
    685 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
    686 		return wince_submit_iso_transfer(itransfer);
    687 	default:
    688 		usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
    689 		return LIBUSB_ERROR_INVALID_PARAM;
    690 	}
    691 }
    692 
    693 static void wince_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
    694 {
    695 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    696 	struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer);
    697 	struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev);
    698 	int status;
    699 
    700 	usbi_dbg("handling I/O completion with errcode %d", io_result);
    701 
    702 	if (io_result == ERROR_NOT_SUPPORTED &&
    703 		transfer->type != LIBUSB_TRANSFER_TYPE_CONTROL) {
    704 		/* For functional stalls, the WinCE USB layer (and therefore the USB Kernel Wrapper
    705 		 * Driver) will report USB_ERROR_STALL/ERROR_NOT_SUPPORTED in situations where the
    706 		 * endpoint isn't actually stalled.
    707 		 *
    708 		 * One example of this is that some devices will occasionally fail to reply to an IN
    709 		 * token. The WinCE USB layer carries on with the transaction until it is completed
    710 		 * (or cancelled) but then completes it with USB_ERROR_STALL.
    711 		 *
    712 		 * This code therefore needs to confirm that there really is a stall error, by both
    713 		 * checking the pipe status and requesting the endpoint status from the device.
    714 		 */
    715 		BOOL halted = FALSE;
    716 		usbi_dbg("checking I/O completion with errcode ERROR_NOT_SUPPORTED is really a stall");
    717 		if (UkwIsPipeHalted(priv->dev, transfer->endpoint, &halted)) {
    718 			/* Pipe status retrieved, so now request endpoint status by sending a GET_STATUS
    719 			 * control request to the device. This is done synchronously, which is a bit
    720 			 * naughty, but this is a special corner case.
    721 			 */
    722 			WORD wStatus = 0;
    723 			DWORD written = 0;
    724 			UKW_CONTROL_HEADER ctrlHeader;
    725 			ctrlHeader.bmRequestType = LIBUSB_REQUEST_TYPE_STANDARD |
    726 				LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_ENDPOINT;
    727 			ctrlHeader.bRequest = LIBUSB_REQUEST_GET_STATUS;
    728 			ctrlHeader.wValue = 0;
    729 			ctrlHeader.wIndex = transfer->endpoint;
    730 			ctrlHeader.wLength = sizeof(wStatus);
    731 			if (UkwIssueControlTransfer(priv->dev,
    732 					UKW_TF_IN_TRANSFER | UKW_TF_SEND_TO_ENDPOINT,
    733 					&ctrlHeader, &wStatus, sizeof(wStatus), &written, NULL)) {
    734 				if (written == sizeof(wStatus) &&
    735 						(wStatus & STATUS_HALT_FLAG) == 0) {
    736 					if (!halted || UkwClearHaltHost(priv->dev, transfer->endpoint)) {
    737 						usbi_dbg("Endpoint doesn't appear to be stalled, overriding error with success");
    738 						io_result = ERROR_SUCCESS;
    739 					} else {
    740 						usbi_dbg("Endpoint doesn't appear to be stalled, but the host is halted, changing error");
    741 						io_result = ERROR_IO_DEVICE;
    742 					}
    743 				}
    744 			}
    745 		}
    746 	}
    747 
    748 	switch(io_result) {
    749 	case ERROR_SUCCESS:
    750 		itransfer->transferred += io_size;
    751 		status = LIBUSB_TRANSFER_COMPLETED;
    752 		break;
    753 	case ERROR_CANCELLED:
    754 		usbi_dbg("detected transfer cancel");
    755 		status = LIBUSB_TRANSFER_CANCELLED;
    756 		break;
    757 	case ERROR_NOT_SUPPORTED:
    758 	case ERROR_GEN_FAILURE:
    759 		usbi_dbg("detected endpoint stall");
    760 		status = LIBUSB_TRANSFER_STALL;
    761 		break;
    762 	case ERROR_SEM_TIMEOUT:
    763 		usbi_dbg("detected semaphore timeout");
    764 		status = LIBUSB_TRANSFER_TIMED_OUT;
    765 		break;
    766 	case ERROR_OPERATION_ABORTED:
    767 		if (itransfer->flags & USBI_TRANSFER_TIMED_OUT) {
    768 			usbi_dbg("detected timeout");
    769 			status = LIBUSB_TRANSFER_TIMED_OUT;
    770 		} else {
    771 			usbi_dbg("detected operation aborted");
    772 			status = LIBUSB_TRANSFER_CANCELLED;
    773 		}
    774 		break;
    775 	default:
    776 		usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(io_result));
    777 		status = LIBUSB_TRANSFER_ERROR;
    778 		break;
    779 	}
    780 	wince_clear_transfer_priv(itransfer);
    781 	if (status == LIBUSB_TRANSFER_CANCELLED) {
    782 		usbi_handle_transfer_cancellation(itransfer);
    783 	} else {
    784 		usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status);
    785 	}
    786 }
    787 
    788 static void wince_handle_callback (struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size)
    789 {
    790 	struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
    791 
    792 	switch (transfer->type) {
    793 	case LIBUSB_TRANSFER_TYPE_CONTROL:
    794 	case LIBUSB_TRANSFER_TYPE_BULK:
    795 	case LIBUSB_TRANSFER_TYPE_INTERRUPT:
    796 	case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
    797 		wince_transfer_callback (itransfer, io_result, io_size);
    798 		break;
    799 	default:
    800 		usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type);
    801 	}
    802 }
    803 
    804 static int wince_handle_events(
    805 	struct libusb_context *ctx,
    806 	struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
    807 {
    808 	struct wince_transfer_priv* transfer_priv = NULL;
    809 	POLL_NFDS_TYPE i = 0;
    810 	BOOL found = FALSE;
    811 	struct usbi_transfer *transfer;
    812 	DWORD io_size, io_result;
    813 
    814 	usbi_mutex_lock(&ctx->open_devs_lock);
    815 	for (i = 0; i < nfds && num_ready > 0; i++) {
    816 
    817 		usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents);
    818 
    819 		if (!fds[i].revents) {
    820 			continue;
    821 		}
    822 
    823 		num_ready--;
    824 
    825 		// Because a Windows OVERLAPPED is used for poll emulation,
    826 		// a pollable fd is created and stored with each transfer
    827 		usbi_mutex_lock(&ctx->flying_transfers_lock);
    828 		list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
    829 			transfer_priv = usbi_transfer_get_os_priv(transfer);
    830 			if (transfer_priv->pollable_fd.fd == fds[i].fd) {
    831 				found = TRUE;
    832 				break;
    833 			}
    834 		}
    835 		usbi_mutex_unlock(&ctx->flying_transfers_lock);
    836 
    837 		if (found && HasOverlappedIoCompleted(transfer_priv->pollable_fd.overlapped)) {
    838 			io_result = (DWORD)transfer_priv->pollable_fd.overlapped->Internal;
    839 			io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh;
    840 			usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd);
    841 			// let handle_callback free the event using the transfer wfd
    842 			// If you don't use the transfer wfd, you run a risk of trying to free a
    843 			// newly allocated wfd that took the place of the one from the transfer.
    844 			wince_handle_callback(transfer, io_result, io_size);
    845 		} else if (found) {
    846 			usbi_err(ctx, "matching transfer for fd %x has not completed", fds[i]);
    847 			return LIBUSB_ERROR_OTHER;
    848 		} else {
    849 			usbi_err(ctx, "could not find a matching transfer for fd %x", fds[i]);
    850 			return LIBUSB_ERROR_NOT_FOUND;
    851 		}
    852 	}
    853 
    854 	usbi_mutex_unlock(&ctx->open_devs_lock);
    855 	return LIBUSB_SUCCESS;
    856 }
    857 
    858 /*
    859  * Monotonic and real time functions
    860  */
    861 unsigned __stdcall wince_clock_gettime_threaded(void* param)
    862 {
    863 	LARGE_INTEGER hires_counter, li_frequency;
    864 	LONG nb_responses;
    865 	int timer_index;
    866 
    867 	// Init - find out if we have access to a monotonic (hires) timer
    868 	if (!QueryPerformanceFrequency(&li_frequency)) {
    869 		usbi_dbg("no hires timer available on this platform");
    870 		hires_frequency = 0;
    871 		hires_ticks_to_ps = UINT64_C(0);
    872 	} else {
    873 		hires_frequency = li_frequency.QuadPart;
    874 		// The hires frequency can go as high as 4 GHz, so we'll use a conversion
    875 		// to picoseconds to compute the tv_nsecs part in clock_gettime
    876 		hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency;
    877 		usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency);
    878 	}
    879 
    880 	// Main loop - wait for requests
    881 	while (1) {
    882 		timer_index = WaitForMultipleObjects(2, timer_request, FALSE, INFINITE) - WAIT_OBJECT_0;
    883 		if ( (timer_index != 0) && (timer_index != 1) ) {
    884 			usbi_dbg("failure to wait on requests: %s", windows_error_str(0));
    885 			continue;
    886 		}
    887 		if (request_count[timer_index] == 0) {
    888 			// Request already handled
    889 			ResetEvent(timer_request[timer_index]);
    890 			// There's still a possiblity that a thread sends a request between the
    891 			// time we test request_count[] == 0 and we reset the event, in which case
    892 			// the request would be ignored. The simple solution to that is to test
    893 			// request_count again and process requests if non zero.
    894 			if (request_count[timer_index] == 0)
    895 				continue;
    896 		}
    897 		switch (timer_index) {
    898 		case 0:
    899 			WaitForSingleObject(timer_mutex, INFINITE);
    900 			// Requests to this thread are for hires always
    901 			if (QueryPerformanceCounter(&hires_counter) != 0) {
    902 				timer_tp.tv_sec = (long)(hires_counter.QuadPart / hires_frequency);
    903 				timer_tp.tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency)/1000) * hires_ticks_to_ps);
    904 			} else {
    905 				// Fallback to real-time if we can't get monotonic value
    906 				// Note that real-time clock does not wait on the mutex or this thread.
    907 				wince_clock_gettime(USBI_CLOCK_REALTIME, &timer_tp);
    908 			}
    909 			ReleaseMutex(timer_mutex);
    910 
    911 			nb_responses = InterlockedExchange((LONG*)&request_count[0], 0);
    912 			if ( (nb_responses)
    913 			  && (ReleaseSemaphore(timer_response, nb_responses, NULL) == 0) ) {
    914 				usbi_dbg("unable to release timer semaphore %d: %s", windows_error_str(0));
    915 			}
    916 			continue;
    917 		case 1: // time to quit
    918 			usbi_dbg("timer thread quitting");
    919 			return 0;
    920 		}
    921 	}
    922 	usbi_dbg("ERROR: broken timer thread");
    923 	return 1;
    924 }
    925 
    926 static int wince_clock_gettime(int clk_id, struct timespec *tp)
    927 {
    928 	FILETIME filetime;
    929 	ULARGE_INTEGER rtime;
    930 	DWORD r;
    931 	SYSTEMTIME st;
    932 	switch(clk_id) {
    933 	case USBI_CLOCK_MONOTONIC:
    934 		if (hires_frequency != 0) {
    935 			while (1) {
    936 				InterlockedIncrement((LONG*)&request_count[0]);
    937 				SetEvent(timer_request[0]);
    938 				r = WaitForSingleObject(timer_response, TIMER_REQUEST_RETRY_MS);
    939 				switch(r) {
    940 				case WAIT_OBJECT_0:
    941 					WaitForSingleObject(timer_mutex, INFINITE);
    942 					*tp = timer_tp;
    943 					ReleaseMutex(timer_mutex);
    944 					return LIBUSB_SUCCESS;
    945 				case WAIT_TIMEOUT:
    946 					usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?");
    947 					break; // Retry until successful
    948 				default:
    949 					usbi_dbg("WaitForSingleObject failed: %s", windows_error_str(0));
    950 					return LIBUSB_ERROR_OTHER;
    951 				}
    952 			}
    953 		}
    954 		// Fall through and return real-time if monotonic was not detected @ timer init
    955 	case USBI_CLOCK_REALTIME:
    956 		// We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx
    957 		// with a predef epoch_time to have an epoch that starts at 1970.01.01 00:00
    958 		// Note however that our resolution is bounded by the Windows system time
    959 		// functions and is at best of the order of 1 ms (or, usually, worse)
    960 		GetSystemTime(&st);
    961 		SystemTimeToFileTime(&st, &filetime);
    962 		rtime.LowPart = filetime.dwLowDateTime;
    963 		rtime.HighPart = filetime.dwHighDateTime;
    964 		rtime.QuadPart -= epoch_time;
    965 		tp->tv_sec = (long)(rtime.QuadPart / 10000000);
    966 		tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
    967 		return LIBUSB_SUCCESS;
    968 	default:
    969 		return LIBUSB_ERROR_INVALID_PARAM;
    970 	}
    971 }
    972 
    973 const struct usbi_os_backend wince_backend = {
    974         "Windows CE",
    975         0,
    976         wince_init,
    977         wince_exit,
    978 
    979         wince_get_device_list,
    980 	NULL,				/* hotplug_poll */
    981         wince_open,
    982         wince_close,
    983 
    984         wince_get_device_descriptor,
    985         wince_get_active_config_descriptor,
    986         wince_get_config_descriptor,
    987 	NULL,				/* get_config_descriptor_by_value() */
    988 
    989         wince_get_configuration,
    990         wince_set_configuration,
    991         wince_claim_interface,
    992         wince_release_interface,
    993 
    994         wince_set_interface_altsetting,
    995         wince_clear_halt,
    996         wince_reset_device,
    997 
    998         wince_kernel_driver_active,
    999         wince_detach_kernel_driver,
   1000         wince_attach_kernel_driver,
   1001 
   1002         wince_destroy_device,
   1003 
   1004         wince_submit_transfer,
   1005         wince_cancel_transfer,
   1006         wince_clear_transfer_priv,
   1007 
   1008         wince_handle_events,
   1009 
   1010         wince_clock_gettime,
   1011         sizeof(struct wince_device_priv),
   1012         sizeof(struct wince_device_handle_priv),
   1013         sizeof(struct wince_transfer_priv),
   1014         0,
   1015 };
   1016