2 * poll_windows: poll compatibility wrapper for Windows
3 * Copyright © 2009-2010 Pete Batard <pbatard@gmail.com>
4 * With contributions from Michael Plante, Orin Eman et al.
5 * Parts of poll implementation from libusb-win32, by Stephan Meyer et al.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * poll() and pipe() Windows compatibility layer for libusbx 1.0
26 * The way this layer works is by using OVERLAPPED with async I/O transfers, as
27 * OVERLAPPED have an associated event which is flagged for I/O completion.
29 * For USB pollable async I/O, you would typically:
30 * - obtain a Windows HANDLE to a file or device that has been opened in
32 * - call usbi_create_fd with this handle to obtain a custom fd.
33 * Note that if you need simultaneous R/W access, you need to call create_fd
34 * twice, once in RW_READ and once in RW_WRITE mode to obtain 2 separate
36 * - leave the core functions call the poll routine and flag POLLIN/POLLOUT
38 * The pipe pollable synchronous I/O works using the overlapped event associated
39 * with a fake pipe. The read/write functions are only meant to be used in that
48 // Uncomment to debug the polling layer
49 //#define DEBUG_POLL_WINDOWS
50 #if defined(DEBUG_POLL_WINDOWS)
51 #define poll_dbg usbi_dbg
53 // MSVC++ < 2005 cannot use a variadic argument and non MSVC
54 // compilers produce warnings if parenthesis are ommitted.
55 #if defined(_MSC_VER) && _MSC_VER < 1400
62 #if defined(_PREFAST_)
63 #pragma warning(disable:28719)
66 #if defined(_WIN32_WCE)
67 #define usbi_sleep(ms) Sleep(ms)
69 #define usbi_sleep(ms) SleepEx(ms, TRUE)
72 #define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0)
75 const struct winfd INVALID_WINFD = {-1, INVALID_HANDLE_VALUE, NULL, NULL, NULL, RW_NONE};
76 struct winfd poll_fd[MAX_FDS];
79 CRITICAL_SECTION mutex; // lock for fds
80 // Additional variables for XP CancelIoEx partial emulation
81 HANDLE original_handle;
86 BOOLEAN is_polling_set = FALSE;
88 static volatile LONG compat_spinlock = 0;
90 #if !defined(_WIN32_WCE)
91 // CancelIoEx, available on Vista and later only, provides the ability to cancel
92 // a single transfer (OVERLAPPED) when used. As it may not be part of any of the
93 // platform headers, we hook into the Kernel32 system DLL directly to seek it.
94 static BOOL (__stdcall *pCancelIoEx)(HANDLE, LPOVERLAPPED) = NULL;
95 #define Use_Duplicate_Handles (pCancelIoEx == NULL)
97 static inline void setup_cancel_io(void)
99 pCancelIoEx = (BOOL (__stdcall *)(HANDLE,LPOVERLAPPED))
100 GetProcAddress(GetModuleHandleA("KERNEL32"), "CancelIoEx");
101 usbi_dbg("Will use CancelIo%s for I/O cancellation",
102 Use_Duplicate_Handles?"":"Ex");
105 static inline BOOL cancel_io(int _index)
107 if ((_index < 0) || (_index >= MAX_FDS)) {
111 if ( (poll_fd[_index].fd < 0) || (poll_fd[_index].handle == INVALID_HANDLE_VALUE)
112 || (poll_fd[_index].handle == 0) || (poll_fd[_index].overlapped == NULL) ) {
115 if (poll_fd[_index].itransfer && poll_fd[_index].cancel_fn) {
116 // Cancel outstanding transfer via the specific callback
117 (*poll_fd[_index].cancel_fn)(poll_fd[_index].itransfer);
120 if (pCancelIoEx != NULL) {
121 return (*pCancelIoEx)(poll_fd[_index].handle, poll_fd[_index].overlapped);
123 if (_poll_fd[_index].thread_id == GetCurrentThreadId()) {
124 return CancelIo(poll_fd[_index].handle);
126 usbi_warn(NULL, "Unable to cancel I/O that was started from another thread");
130 #define Use_Duplicate_Handles FALSE
132 static __inline void setup_cancel_io()
134 // No setup needed on WinCE
137 static __inline BOOL cancel_io(int _index)
139 if ((_index < 0) || (_index >= MAX_FDS)) {
142 if ( (poll_fd[_index].fd < 0) || (poll_fd[_index].handle == INVALID_HANDLE_VALUE)
143 || (poll_fd[_index].handle == 0) || (poll_fd[_index].overlapped == NULL) ) {
146 if (poll_fd[_index].itransfer && poll_fd[_index].cancel_fn) {
147 // Cancel outstanding transfer via the specific callback
148 (*poll_fd[_index].cancel_fn)(poll_fd[_index].itransfer);
155 void init_polling(void)
159 while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) {
162 if (!is_polling_set) {
164 for (i=0; i<MAX_FDS; i++) {
165 poll_fd[i] = INVALID_WINFD;
166 _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
167 _poll_fd[i].thread_id = 0;
168 InitializeCriticalSection(&_poll_fd[i].mutex);
170 is_polling_set = TRUE;
172 InterlockedExchange((LONG *)&compat_spinlock, 0);
175 // Internal function to retrieve the table index (and lock the fd mutex)
176 static int _fd_to_index_and_lock(int fd)
183 for (i=0; i<MAX_FDS; i++) {
184 if (poll_fd[i].fd == fd) {
185 EnterCriticalSection(&_poll_fd[i].mutex);
186 // fd might have changed before we got to critical
187 if (poll_fd[i].fd != fd) {
188 LeaveCriticalSection(&_poll_fd[i].mutex);
197 static OVERLAPPED *create_overlapped(void)
199 OVERLAPPED *overlapped = (OVERLAPPED*) calloc(1, sizeof(OVERLAPPED));
200 if (overlapped == NULL) {
203 overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
204 if(overlapped->hEvent == NULL) {
211 static void free_overlapped(OVERLAPPED *overlapped)
213 if (overlapped == NULL)
216 if ( (overlapped->hEvent != 0)
217 && (overlapped->hEvent != INVALID_HANDLE_VALUE) ) {
218 CloseHandle(overlapped->hEvent);
223 void exit_polling(void)
227 while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) {
230 if (is_polling_set) {
231 is_polling_set = FALSE;
233 for (i=0; i<MAX_FDS; i++) {
234 // Cancel any async I/O (handle can be invalid)
236 // If anything was pending on that I/O, it should be
237 // terminating, and we should be able to access the fd
238 // mutex lock before too long
239 EnterCriticalSection(&_poll_fd[i].mutex);
240 free_overlapped(poll_fd[i].overlapped);
241 if (Use_Duplicate_Handles) {
242 // Close duplicate handle
243 if (_poll_fd[i].original_handle != INVALID_HANDLE_VALUE) {
244 CloseHandle(poll_fd[i].handle);
247 poll_fd[i] = INVALID_WINFD;
248 LeaveCriticalSection(&_poll_fd[i].mutex);
249 DeleteCriticalSection(&_poll_fd[i].mutex);
252 InterlockedExchange((LONG *)&compat_spinlock, 0);
256 * Create a fake pipe.
257 * As libusbx only uses pipes for signaling, all we need from a pipe is an
258 * event. To that extent, we create a single wfd and overlapped as a means
259 * to access that event.
261 int usbi_pipe(int filedes[2])
264 OVERLAPPED* overlapped;
268 overlapped = create_overlapped();
270 if (overlapped == NULL) {
273 // The overlapped must have status pending for signaling to work in poll
274 overlapped->Internal = STATUS_PENDING;
275 overlapped->InternalHigh = 0;
277 for (i=0; i<MAX_FDS; i++) {
278 if (poll_fd[i].fd < 0) {
279 EnterCriticalSection(&_poll_fd[i].mutex);
280 // fd might have been allocated before we got to critical
281 if (poll_fd[i].fd >= 0) {
282 LeaveCriticalSection(&_poll_fd[i].mutex);
286 // Use index as the unique fd number
288 // Read end of the "pipe"
289 filedes[0] = poll_fd[i].fd;
290 // We can use the same handle for both ends
291 filedes[1] = filedes[0];
293 poll_fd[i].handle = DUMMY_HANDLE;
294 poll_fd[i].overlapped = overlapped;
295 // There's no polling on the write end, so we just use READ for our needs
296 poll_fd[i].rw = RW_READ;
297 _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
298 LeaveCriticalSection(&_poll_fd[i].mutex);
302 free_overlapped(overlapped);
307 * Create both an fd and an OVERLAPPED from an open Windows handle, so that
308 * it can be used with our polling function
309 * The handle MUST support overlapped transfers (usually requires CreateFile
310 * with FILE_FLAG_OVERLAPPED)
311 * Return a pollable file descriptor struct, or INVALID_WINFD on error
313 * Note that the fd returned by this function is a per-transfer fd, rather
314 * than a per-session fd and cannot be used for anything else but our
315 * custom functions (the fd itself points to the NUL: device)
316 * if you plan to do R/W on the same handle, you MUST create 2 fds: one for
317 * read and one for write. Using a single R/W fd is unsupported and will
318 * produce unexpected results
320 struct winfd usbi_create_fd(HANDLE handle, int access_mode, struct usbi_transfer *itransfer, cancel_transfer *cancel_fn)
323 struct winfd wfd = INVALID_WINFD;
324 OVERLAPPED* overlapped = NULL;
328 if ((handle == 0) || (handle == INVALID_HANDLE_VALUE)) {
329 return INVALID_WINFD;
332 wfd.itransfer = itransfer;
333 wfd.cancel_fn = cancel_fn;
335 if ((access_mode != RW_READ) && (access_mode != RW_WRITE)) {
336 usbi_warn(NULL, "only one of RW_READ or RW_WRITE are supported.\n"
337 "If you want to poll for R/W simultaneously, create multiple fds from the same handle.");
338 return INVALID_WINFD;
340 if (access_mode == RW_READ) {
346 overlapped = create_overlapped();
347 if(overlapped == NULL) {
348 return INVALID_WINFD;
351 for (i=0; i<MAX_FDS; i++) {
352 if (poll_fd[i].fd < 0) {
353 EnterCriticalSection(&_poll_fd[i].mutex);
354 // fd might have been removed before we got to critical
355 if (poll_fd[i].fd >= 0) {
356 LeaveCriticalSection(&_poll_fd[i].mutex);
359 // Use index as the unique fd number
361 // Attempt to emulate some of the CancelIoEx behaviour on platforms
362 // that don't have it
363 if (Use_Duplicate_Handles) {
364 _poll_fd[i].thread_id = GetCurrentThreadId();
365 if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(),
366 &wfd.handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
367 usbi_dbg("could not duplicate handle for CancelIo - using original one");
369 // Make sure we won't close the original handle on fd deletion then
370 _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
372 _poll_fd[i].original_handle = handle;
377 wfd.overlapped = overlapped;
378 memcpy(&poll_fd[i], &wfd, sizeof(struct winfd));
379 LeaveCriticalSection(&_poll_fd[i].mutex);
383 free_overlapped(overlapped);
384 return INVALID_WINFD;
387 static void _free_index(int _index)
389 // Cancel any async IO (Don't care about the validity of our handles for this)
391 // close the duplicate handle (if we have an actual duplicate)
392 if (Use_Duplicate_Handles) {
393 if (_poll_fd[_index].original_handle != INVALID_HANDLE_VALUE) {
394 CloseHandle(poll_fd[_index].handle);
396 _poll_fd[_index].original_handle = INVALID_HANDLE_VALUE;
397 _poll_fd[_index].thread_id = 0;
399 free_overlapped(poll_fd[_index].overlapped);
400 poll_fd[_index] = INVALID_WINFD;
404 * Release a pollable file descriptor.
406 * Note that the associated Windows handle is not closed by this call
408 void usbi_free_fd(int fd)
414 _index = _fd_to_index_and_lock(fd);
419 LeaveCriticalSection(&_poll_fd[_index].mutex);
423 * The functions below perform various conversions between fd, handle and OVERLAPPED
425 struct winfd fd_to_winfd(int fd)
433 return INVALID_WINFD;
435 for (i=0; i<MAX_FDS; i++) {
436 if (poll_fd[i].fd == fd) {
437 EnterCriticalSection(&_poll_fd[i].mutex);
438 // fd might have been deleted before we got to critical
439 if (poll_fd[i].fd != fd) {
440 LeaveCriticalSection(&_poll_fd[i].mutex);
443 memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
444 LeaveCriticalSection(&_poll_fd[i].mutex);
448 return INVALID_WINFD;
451 struct winfd handle_to_winfd(HANDLE handle)
458 if ((handle == 0) || (handle == INVALID_HANDLE_VALUE))
459 return INVALID_WINFD;
461 for (i=0; i<MAX_FDS; i++) {
462 if (poll_fd[i].handle == handle) {
463 EnterCriticalSection(&_poll_fd[i].mutex);
464 // fd might have been deleted before we got to critical
465 if (poll_fd[i].handle != handle) {
466 LeaveCriticalSection(&_poll_fd[i].mutex);
469 memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
470 LeaveCriticalSection(&_poll_fd[i].mutex);
474 return INVALID_WINFD;
477 struct winfd overlapped_to_winfd(OVERLAPPED* overlapped)
484 if (overlapped == NULL)
485 return INVALID_WINFD;
487 for (i=0; i<MAX_FDS; i++) {
488 if (poll_fd[i].overlapped == overlapped) {
489 EnterCriticalSection(&_poll_fd[i].mutex);
490 // fd might have been deleted before we got to critical
491 if (poll_fd[i].overlapped != overlapped) {
492 LeaveCriticalSection(&_poll_fd[i].mutex);
495 memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
496 LeaveCriticalSection(&_poll_fd[i].mutex);
500 return INVALID_WINFD;
504 * POSIX poll equivalent, using Windows OVERLAPPED
505 * Currently, this function only accepts one of POLLIN or POLLOUT per fd
506 * (but you can create multiple fds from the same handle for read and write)
508 int usbi_poll(struct pollfd *fds, unsigned int nfds, int timeout)
511 int _index, object_index, triggered;
512 HANDLE *handles_to_wait_on;
513 int *handle_to_index;
514 DWORD nb_handles_to_wait_on = 0;
520 handles_to_wait_on = (HANDLE*) calloc(nfds+1, sizeof(HANDLE)); // +1 for fd_update
521 handle_to_index = (int*) calloc(nfds, sizeof(int));
522 if ((handles_to_wait_on == NULL) || (handle_to_index == NULL)) {
528 for (i = 0; i < nfds; ++i) {
531 // Only one of POLLIN or POLLOUT can be selected with this version of poll (not both)
532 if ((fds[i].events & ~POLLIN) && (!(fds[i].events & POLLOUT))) {
533 fds[i].revents |= POLLERR;
535 usbi_warn(NULL, "unsupported set of events");
540 _index = _fd_to_index_and_lock(fds[i].fd);
541 poll_dbg("fd[%d]=%d: (overlapped=%p) got events %04X", i, poll_fd[_index].fd, poll_fd[_index].overlapped, fds[i].events);
543 if ( (_index < 0) || (poll_fd[_index].handle == INVALID_HANDLE_VALUE)
544 || (poll_fd[_index].handle == 0) || (poll_fd[_index].overlapped == NULL)) {
545 fds[i].revents |= POLLNVAL | POLLERR;
548 LeaveCriticalSection(&_poll_fd[_index].mutex);
550 usbi_warn(NULL, "invalid fd");
555 // IN or OUT must match our fd direction
556 if ((fds[i].events & POLLIN) && (poll_fd[_index].rw != RW_READ)) {
557 fds[i].revents |= POLLNVAL | POLLERR;
559 usbi_warn(NULL, "attempted POLLIN on fd without READ access");
560 LeaveCriticalSection(&_poll_fd[_index].mutex);
565 if ((fds[i].events & POLLOUT) && (poll_fd[_index].rw != RW_WRITE)) {
566 fds[i].revents |= POLLNVAL | POLLERR;
568 usbi_warn(NULL, "attempted POLLOUT on fd without WRITE access");
569 LeaveCriticalSection(&_poll_fd[_index].mutex);
574 // The following macro only works if overlapped I/O was reported pending
575 if ( (HasOverlappedIoCompleted(poll_fd[_index].overlapped))
576 || (HasOverlappedIoCompletedSync(poll_fd[_index].overlapped)) ) {
577 poll_dbg(" completed");
578 // checks above should ensure this works:
579 fds[i].revents = fds[i].events;
582 handles_to_wait_on[nb_handles_to_wait_on] = poll_fd[_index].overlapped->hEvent;
583 handle_to_index[nb_handles_to_wait_on] = i;
584 nb_handles_to_wait_on++;
586 LeaveCriticalSection(&_poll_fd[_index].mutex);
589 // If nothing was triggered, wait on all fds that require it
590 if ((timeout != 0) && (triggered == 0) && (nb_handles_to_wait_on != 0)) {
592 poll_dbg("starting infinite wait for %d handles...", (int)nb_handles_to_wait_on);
594 poll_dbg("starting %d ms wait for %d handles...", timeout, (int)nb_handles_to_wait_on);
596 ret = WaitForMultipleObjects(nb_handles_to_wait_on, handles_to_wait_on,
597 FALSE, (timeout<0)?INFINITE:(DWORD)timeout);
598 object_index = ret-WAIT_OBJECT_0;
599 if ((object_index >= 0) && ((DWORD)object_index < nb_handles_to_wait_on)) {
600 poll_dbg(" completed after wait");
601 i = handle_to_index[object_index];
602 _index = _fd_to_index_and_lock(fds[i].fd);
603 fds[i].revents = fds[i].events;
606 LeaveCriticalSection(&_poll_fd[_index].mutex);
608 } else if (ret == WAIT_TIMEOUT) {
609 poll_dbg(" timed out");
610 triggered = 0; // 0 = timeout
613 triggered = -1; // error
618 if (handles_to_wait_on != NULL) {
619 free(handles_to_wait_on);
621 if (handle_to_index != NULL) {
622 free(handle_to_index);
628 * close a fake pipe fd
630 int usbi_close(int fd)
637 _index = _fd_to_index_and_lock(fd);
642 free_overlapped(poll_fd[_index].overlapped);
643 poll_fd[_index] = INVALID_WINFD;
644 LeaveCriticalSection(&_poll_fd[_index].mutex);
650 * synchronous write for fake "pipe" signaling
652 ssize_t usbi_write(int fd, const void *buf, size_t count)
659 if (count != sizeof(unsigned char)) {
660 usbi_err(NULL, "this function should only used for signaling");
664 _index = _fd_to_index_and_lock(fd);
666 if ( (_index < 0) || (poll_fd[_index].overlapped == NULL) ) {
669 LeaveCriticalSection(&_poll_fd[_index].mutex);
674 poll_dbg("set pipe event (fd = %d, thread = %08X)", _index, GetCurrentThreadId());
675 SetEvent(poll_fd[_index].overlapped->hEvent);
676 poll_fd[_index].overlapped->Internal = STATUS_WAIT_0;
677 // If two threads write on the pipe at the same time, we need to
678 // process two separate reads => use the overlapped as a counter
679 poll_fd[_index].overlapped->InternalHigh++;
681 LeaveCriticalSection(&_poll_fd[_index].mutex);
682 return sizeof(unsigned char);
686 * synchronous read for fake "pipe" signaling
688 ssize_t usbi_read(int fd, void *buf, size_t count)
696 if (count != sizeof(unsigned char)) {
697 usbi_err(NULL, "this function should only used for signaling");
701 _index = _fd_to_index_and_lock(fd);
708 if (WaitForSingleObject(poll_fd[_index].overlapped->hEvent, INFINITE) != WAIT_OBJECT_0) {
709 usbi_warn(NULL, "waiting for event failed: %d", (int)GetLastError());
714 poll_dbg("clr pipe event (fd = %d, thread = %08X)", _index, GetCurrentThreadId());
715 poll_fd[_index].overlapped->InternalHigh--;
716 // Don't reset unless we don't have any more events to process
717 if (poll_fd[_index].overlapped->InternalHigh <= 0) {
718 ResetEvent(poll_fd[_index].overlapped->hEvent);
719 poll_fd[_index].overlapped->Internal = STATUS_PENDING;
722 r = sizeof(unsigned char);
725 LeaveCriticalSection(&_poll_fd[_index].mutex);