Windows: remove unused function
[platform/upstream/libusb.git] / libusb / os / poll_windows.c
1 /*
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.
6  *
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.
11  *
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.
16  *
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
20  *
21  */
22
23 /*
24  * poll() and pipe() Windows compatibility layer for libusbx 1.0
25  *
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.
28  *
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
31  *   OVERLAPPED mode
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
35  *   pollable fds
36  * - leave the core functions call the poll routine and flag POLLIN/POLLOUT
37  *
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
40  * context.
41  */
42 #include <errno.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45
46 #include <libusbi.h>
47
48 // Uncomment to debug the polling layer
49 //#define DEBUG_POLL_WINDOWS
50 #if defined(DEBUG_POLL_WINDOWS)
51 #define poll_dbg usbi_dbg
52 #else
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
56 #define poll_dbg
57 #else
58 #define poll_dbg(...)
59 #endif
60 #endif
61
62 #if defined(_PREFAST_)
63 #pragma warning(disable:28719)
64 #endif
65
66 #if defined(_WIN32_WCE)
67 #define usbi_sleep(ms) Sleep(ms)
68 #else
69 #define usbi_sleep(ms) SleepEx(ms, TRUE)
70 #endif
71
72 #define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0)
73
74 // public fd data
75 const struct winfd INVALID_WINFD = {-1, INVALID_HANDLE_VALUE, NULL, NULL, NULL, RW_NONE};
76 struct winfd poll_fd[MAX_FDS];
77 // internal fd data
78 struct {
79         CRITICAL_SECTION mutex; // lock for fds
80         // Additional variables for XP CancelIoEx partial emulation
81         HANDLE original_handle;
82         DWORD thread_id;
83 } _poll_fd[MAX_FDS];
84
85 // globals
86 BOOLEAN is_polling_set = FALSE;
87 LONG pipe_number = 0;
88 static volatile LONG compat_spinlock = 0;
89
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)
96
97 static inline void setup_cancel_io(void)
98 {
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");
103 }
104
105 static inline BOOL cancel_io(int _index)
106 {
107         if ((_index < 0) || (_index >= MAX_FDS)) {
108                 return FALSE;
109         }
110
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) ) {
113                 return TRUE;
114         }
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);
118                 return TRUE;
119         }
120         if (pCancelIoEx != NULL) {
121                 return (*pCancelIoEx)(poll_fd[_index].handle, poll_fd[_index].overlapped);
122         }
123         if (_poll_fd[_index].thread_id == GetCurrentThreadId()) {
124                 return CancelIo(poll_fd[_index].handle);
125         }
126         usbi_warn(NULL, "Unable to cancel I/O that was started from another thread");
127         return FALSE;
128 }
129 #else
130 #define Use_Duplicate_Handles FALSE
131
132 static __inline void setup_cancel_io()
133 {
134         // No setup needed on WinCE
135 }
136
137 static __inline BOOL cancel_io(int _index)
138 {
139         if ((_index < 0) || (_index >= MAX_FDS)) {
140                 return FALSE;
141         }
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) ) {
144                 return TRUE;
145         }
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);
149         }
150         return TRUE;
151 }
152 #endif
153
154 // Init
155 void init_polling(void)
156 {
157         int i;
158
159         while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) {
160                 usbi_sleep(0);
161         }
162         if (!is_polling_set) {
163                 setup_cancel_io();
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);
169                 }
170                 is_polling_set = TRUE;
171         }
172         InterlockedExchange((LONG *)&compat_spinlock, 0);
173 }
174
175 // Internal function to retrieve the table index (and lock the fd mutex)
176 static int _fd_to_index_and_lock(int fd)
177 {
178         int i;
179
180         if (fd < 0)
181                 return -1;
182
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);
189                                 continue;
190                         }
191                         return i;
192                 }
193         }
194         return -1;
195 }
196
197 static OVERLAPPED *create_overlapped(void)
198 {
199         OVERLAPPED *overlapped = (OVERLAPPED*) calloc(1, sizeof(OVERLAPPED));
200         if (overlapped == NULL) {
201                 return NULL;
202         }
203         overlapped->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
204         if(overlapped->hEvent == NULL) {
205                 free (overlapped);
206                 return NULL;
207         }
208         return overlapped;
209 }
210
211 static void free_overlapped(OVERLAPPED *overlapped)
212 {
213         if (overlapped == NULL)
214                 return;
215
216         if ( (overlapped->hEvent != 0)
217           && (overlapped->hEvent != INVALID_HANDLE_VALUE) ) {
218                 CloseHandle(overlapped->hEvent);
219         }
220         free(overlapped);
221 }
222
223 void exit_polling(void)
224 {
225         int i;
226
227         while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) {
228                 usbi_sleep(0);
229         }
230         if (is_polling_set) {
231                 is_polling_set = FALSE;
232
233                 for (i=0; i<MAX_FDS; i++) {
234                         // Cancel any async I/O (handle can be invalid)
235                         cancel_io(i);
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);
245                                 }
246                         }
247                         poll_fd[i] = INVALID_WINFD;
248                         LeaveCriticalSection(&_poll_fd[i].mutex);
249                         DeleteCriticalSection(&_poll_fd[i].mutex);
250                 }
251         }
252         InterlockedExchange((LONG *)&compat_spinlock, 0);
253 }
254
255 /*
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.
260  */
261 int usbi_pipe(int filedes[2])
262 {
263         int i;
264         OVERLAPPED* overlapped;
265
266         CHECK_INIT_POLLING;
267
268         overlapped = create_overlapped();
269
270         if (overlapped == NULL) {
271                 return -1;
272         }
273         // The overlapped must have status pending for signaling to work in poll
274         overlapped->Internal = STATUS_PENDING;
275         overlapped->InternalHigh = 0;
276
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);
283                                 continue;
284                         }
285
286                         // Use index as the unique fd number
287                         poll_fd[i].fd = i;
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];
292
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);
299                         return 0;
300                 }
301         }
302         free_overlapped(overlapped);
303         return -1;
304 }
305
306 /*
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
312  *
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
319  */
320 struct winfd usbi_create_fd(HANDLE handle, int access_mode, struct usbi_transfer *itransfer, cancel_transfer *cancel_fn)
321 {
322         int i;
323         struct winfd wfd = INVALID_WINFD;
324         OVERLAPPED* overlapped = NULL;
325
326         CHECK_INIT_POLLING;
327
328         if ((handle == 0) || (handle == INVALID_HANDLE_VALUE)) {
329                 return INVALID_WINFD;
330         }
331
332         wfd.itransfer = itransfer;
333         wfd.cancel_fn = cancel_fn;
334
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;
339         }
340         if (access_mode == RW_READ) {
341                 wfd.rw = RW_READ;
342         } else {
343                 wfd.rw = RW_WRITE;
344         }
345
346         overlapped = create_overlapped();
347         if(overlapped == NULL) {
348                 return INVALID_WINFD;
349         }
350
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);
357                                 continue;
358                         }
359                         // Use index as the unique fd number
360                         wfd.fd = i;
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");
368                                         wfd.handle = handle;
369                                         // Make sure we won't close the original handle on fd deletion then
370                                         _poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
371                                 } else {
372                                         _poll_fd[i].original_handle = handle;
373                                 }
374                         } else {
375                                 wfd.handle = handle;
376                         }
377                         wfd.overlapped = overlapped;
378                         memcpy(&poll_fd[i], &wfd, sizeof(struct winfd));
379                         LeaveCriticalSection(&_poll_fd[i].mutex);
380                         return wfd;
381                 }
382         }
383         free_overlapped(overlapped);
384         return INVALID_WINFD;
385 }
386
387 static void _free_index(int _index)
388 {
389         // Cancel any async IO (Don't care about the validity of our handles for this)
390         cancel_io(_index);
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);
395                 }
396                 _poll_fd[_index].original_handle = INVALID_HANDLE_VALUE;
397                 _poll_fd[_index].thread_id = 0;
398         }
399         free_overlapped(poll_fd[_index].overlapped);
400         poll_fd[_index] = INVALID_WINFD;
401 }
402
403 /*
404  * Release a pollable file descriptor.
405  *
406  * Note that the associated Windows handle is not closed by this call
407  */
408 void usbi_free_fd(int fd)
409 {
410         int _index;
411
412         CHECK_INIT_POLLING;
413
414         _index = _fd_to_index_and_lock(fd);
415         if (_index < 0) {
416                 return;
417         }
418         _free_index(_index);
419         LeaveCriticalSection(&_poll_fd[_index].mutex);
420 }
421
422 /*
423  * The functions below perform various conversions between fd, handle and OVERLAPPED
424  */
425 struct winfd fd_to_winfd(int fd)
426 {
427         int i;
428         struct winfd wfd;
429
430         CHECK_INIT_POLLING;
431
432         if (fd <= 0)
433                 return INVALID_WINFD;
434
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);
441                                 continue;
442                         }
443                         memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
444                         LeaveCriticalSection(&_poll_fd[i].mutex);
445                         return wfd;
446                 }
447         }
448         return INVALID_WINFD;
449 }
450
451 struct winfd handle_to_winfd(HANDLE handle)
452 {
453         int i;
454         struct winfd wfd;
455
456         CHECK_INIT_POLLING;
457
458         if ((handle == 0) || (handle == INVALID_HANDLE_VALUE))
459                 return INVALID_WINFD;
460
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);
467                                 continue;
468                         }
469                         memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
470                         LeaveCriticalSection(&_poll_fd[i].mutex);
471                         return wfd;
472                 }
473         }
474         return INVALID_WINFD;
475 }
476
477 struct winfd overlapped_to_winfd(OVERLAPPED* overlapped)
478 {
479         int i;
480         struct winfd wfd;
481
482         CHECK_INIT_POLLING;
483
484         if (overlapped == NULL)
485                 return INVALID_WINFD;
486
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);
493                                 continue;
494                         }
495                         memcpy(&wfd, &poll_fd[i], sizeof(struct winfd));
496                         LeaveCriticalSection(&_poll_fd[i].mutex);
497                         return wfd;
498                 }
499         }
500         return INVALID_WINFD;
501 }
502
503 /*
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)
507  */
508 int usbi_poll(struct pollfd *fds, unsigned int nfds, int timeout)
509 {
510         unsigned i;
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;
515         DWORD ret;
516
517         CHECK_INIT_POLLING;
518
519         triggered = 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)) {
523                 errno = ENOMEM;
524                 triggered = -1;
525                 goto poll_exit;
526         }
527
528         for (i = 0; i < nfds; ++i) {
529                 fds[i].revents = 0;
530
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;
534                         errno = EACCES;
535                         usbi_warn(NULL, "unsupported set of events");
536                         triggered = -1;
537                         goto poll_exit;
538                 }
539
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);
542
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;
546                         errno = EBADF;
547                         if (_index >= 0) {
548                                 LeaveCriticalSection(&_poll_fd[_index].mutex);
549                         }
550                         usbi_warn(NULL, "invalid fd");
551                         triggered = -1;
552                         goto poll_exit;
553                 }
554
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;
558                         errno = EBADF;
559                         usbi_warn(NULL, "attempted POLLIN on fd without READ access");
560                         LeaveCriticalSection(&_poll_fd[_index].mutex);
561                         triggered = -1;
562                         goto poll_exit;
563                 }
564
565                 if ((fds[i].events & POLLOUT) && (poll_fd[_index].rw != RW_WRITE)) {
566                         fds[i].revents |= POLLNVAL | POLLERR;
567                         errno = EBADF;
568                         usbi_warn(NULL, "attempted POLLOUT on fd without WRITE access");
569                         LeaveCriticalSection(&_poll_fd[_index].mutex);
570                         triggered = -1;
571                         goto poll_exit;
572                 }
573
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;
580                         triggered++;
581                 } else {
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++;
585                 }
586                 LeaveCriticalSection(&_poll_fd[_index].mutex);
587         }
588
589         // If nothing was triggered, wait on all fds that require it
590         if ((timeout != 0) && (triggered == 0) && (nb_handles_to_wait_on != 0)) {
591                 if (timeout < 0) {
592                         poll_dbg("starting infinite wait for %d handles...", (int)nb_handles_to_wait_on);
593                 } else {
594                         poll_dbg("starting %d ms wait for %d handles...", timeout, (int)nb_handles_to_wait_on);
595                 }
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;
604                         triggered++;
605                         if (_index >= 0) {
606                                 LeaveCriticalSection(&_poll_fd[_index].mutex);
607                         }
608                 } else if (ret == WAIT_TIMEOUT) {
609                         poll_dbg("  timed out");
610                         triggered = 0;  // 0 = timeout
611                 } else {
612                         errno = EIO;
613                         triggered = -1; // error
614                 }
615         }
616
617 poll_exit:
618         if (handles_to_wait_on != NULL) {
619                 free(handles_to_wait_on);
620         }
621         if (handle_to_index != NULL) {
622                 free(handle_to_index);
623         }
624         return triggered;
625 }
626
627 /*
628  * close a fake pipe fd
629  */
630 int usbi_close(int fd)
631 {
632         int _index;
633         int r = -1;
634
635         CHECK_INIT_POLLING;
636
637         _index = _fd_to_index_and_lock(fd);
638
639         if (_index < 0) {
640                 errno = EBADF;
641         } else {
642                 free_overlapped(poll_fd[_index].overlapped);
643                 poll_fd[_index] = INVALID_WINFD;
644                 LeaveCriticalSection(&_poll_fd[_index].mutex);
645         }
646         return r;
647 }
648
649 /*
650  * synchronous write for fake "pipe" signaling
651  */
652 ssize_t usbi_write(int fd, const void *buf, size_t count)
653 {
654         int _index;
655         UNUSED(buf);
656
657         CHECK_INIT_POLLING;
658
659         if (count != sizeof(unsigned char)) {
660                 usbi_err(NULL, "this function should only used for signaling");
661                 return -1;
662         }
663
664         _index = _fd_to_index_and_lock(fd);
665
666         if ( (_index < 0) || (poll_fd[_index].overlapped == NULL) ) {
667                 errno = EBADF;
668                 if (_index >= 0) {
669                         LeaveCriticalSection(&_poll_fd[_index].mutex);
670                 }
671                 return -1;
672         }
673
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++;
680
681         LeaveCriticalSection(&_poll_fd[_index].mutex);
682         return sizeof(unsigned char);
683 }
684
685 /*
686  * synchronous read for fake "pipe" signaling
687  */
688 ssize_t usbi_read(int fd, void *buf, size_t count)
689 {
690         int _index;
691         ssize_t r = -1;
692         UNUSED(buf);
693
694         CHECK_INIT_POLLING;
695
696         if (count != sizeof(unsigned char)) {
697                 usbi_err(NULL, "this function should only used for signaling");
698                 return -1;
699         }
700
701         _index = _fd_to_index_and_lock(fd);
702
703         if (_index < 0) {
704                 errno = EBADF;
705                 return -1;
706         }
707
708         if (WaitForSingleObject(poll_fd[_index].overlapped->hEvent, INFINITE) != WAIT_OBJECT_0) {
709                 usbi_warn(NULL, "waiting for event failed: %d", (int)GetLastError());
710                 errno = EIO;
711                 goto out;
712         }
713
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;
720         }
721
722         r = sizeof(unsigned char);
723
724 out:
725         LeaveCriticalSection(&_poll_fd[_index].mutex);
726         return r;
727 }