Windows: Simplify poll_windows and add provisions for WinCE
[platform/upstream/libusb.git] / libusb / os / threads_windows.c
1 /*
2  * libusbx synchronization on Microsoft Windows
3  *
4  * Copyright © 2010 Michael Plante <michael.plante@gmail.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <config.h>
22 #include <objbase.h>
23 #include <errno.h>
24 #include <stdarg.h>
25
26 #include "libusbi.h"
27
28 #if defined(_WIN32_WCE)
29 #define usbi_sleep(ms) Sleep(ms)
30 #else
31 #define usbi_sleep(ms) SleepEx(ms, TRUE)
32 #endif
33
34 int usbi_mutex_init(usbi_mutex_t *mutex,
35                                         const usbi_mutexattr_t *attr) {
36         UNUSED(attr);
37         if(! mutex) return ((errno=EINVAL));
38         *mutex = CreateMutex(NULL, FALSE, NULL);
39         if(!*mutex) return ((errno=ENOMEM));
40         return 0;
41 }
42 int usbi_mutex_destroy(usbi_mutex_t *mutex) {
43         // It is not clear if CloseHandle failure is due to failure to unlock.
44         //   If so, this should be errno=EBUSY.
45         if(!mutex || !CloseHandle(*mutex)) return ((errno=EINVAL));
46         *mutex = NULL;
47         return 0;
48 }
49 int usbi_mutex_trylock(usbi_mutex_t *mutex) {
50         DWORD result;
51         if(!mutex) return ((errno=EINVAL));
52         result = WaitForSingleObject(*mutex, 0);
53         if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
54                 return 0; // acquired (ToDo: check that abandoned is ok)
55         if(result == WAIT_TIMEOUT)
56                 return ((errno=EBUSY));
57         return ((errno=EINVAL)); // don't know how this would happen
58                                                          //   so don't know proper errno
59 }
60 int usbi_mutex_lock(usbi_mutex_t *mutex) {
61         DWORD result;
62         if(!mutex) return ((errno=EINVAL));
63         result = WaitForSingleObject(*mutex, INFINITE);
64         if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
65                 return 0; // acquired (ToDo: check that abandoned is ok)
66         return ((errno=EINVAL)); // don't know how this would happen
67                                                          //   so don't know proper errno
68 }
69 int usbi_mutex_unlock(usbi_mutex_t *mutex) {
70         if(!mutex)                return ((errno=EINVAL));
71         if(!ReleaseMutex(*mutex)) return ((errno=EPERM ));
72         return 0;
73 }
74
75 int usbi_mutex_static_lock(usbi_mutex_static_t *mutex) {
76         if(!mutex)               return ((errno=EINVAL));
77         while (InterlockedExchange((LONG *)mutex, 1) == 1) {
78                 usbi_sleep(0);
79         }
80         return 0;
81 }
82 int usbi_mutex_static_unlock(usbi_mutex_static_t *mutex) {
83         if(!mutex)               return ((errno=EINVAL));
84         *mutex = 0;
85         return 0;
86 }
87
88
89
90 int usbi_cond_init(usbi_cond_t *cond,
91                                    const usbi_condattr_t *attr) {
92         UNUSED(attr);
93         if(!cond)           return ((errno=EINVAL));
94         list_init(&cond->waiters    );
95         list_init(&cond->not_waiting);
96         return 0;
97 }
98 int usbi_cond_destroy(usbi_cond_t *cond) {
99         // This assumes no one is using this anymore.  The check MAY NOT BE safe.
100         struct usbi_cond_perthread *pos, *next_pos = NULL;
101         if(!cond) return ((errno=EINVAL));
102         if(!list_empty(&cond->waiters)) return ((errno=EBUSY )); // (!see above!)
103         list_for_each_entry_safe(pos, next_pos, &cond->not_waiting, list, struct usbi_cond_perthread) {
104                 CloseHandle(pos->event);
105                 list_del(&pos->list);
106                 free(pos);
107         }
108
109         return 0;
110 }
111
112 int usbi_cond_broadcast(usbi_cond_t *cond) {
113         // Assumes mutex is locked; this is not in keeping with POSIX spec, but
114         //   libusb does this anyway, so we simplify by not adding more sync
115         //   primitives to the CV definition!
116         int fail = 0;
117         struct usbi_cond_perthread *pos;
118         if(!cond)                      return ((errno=EINVAL));
119         list_for_each_entry(pos, &cond->waiters, list, struct usbi_cond_perthread) {
120                 if(!SetEvent(pos->event))
121                         fail = 1;
122         }
123         // The wait function will remove its respective item from the list.
124         return fail ? ((errno=EINVAL)) : 0;
125 }
126 int usbi_cond_signal(usbi_cond_t *cond) {
127         // Assumes mutex is locked; this is not in keeping with POSIX spec, but
128         //   libusb does this anyway, so we simplify by not adding more sync
129         //   primitives to the CV definition!
130         struct usbi_cond_perthread *pos;
131         if(!cond)                      return ((errno=EINVAL));
132         if(list_empty(&cond->waiters)) return 0; // no one to wakeup.
133         pos = list_entry(&cond->waiters.next, struct usbi_cond_perthread, list);
134         // The wait function will remove its respective item from the list.
135         return SetEvent(pos->event) ? 0 : ((errno=EINVAL));
136 }
137 static int __inline usbi_cond_intwait(usbi_cond_t *cond,
138                                                                           usbi_mutex_t *mutex,
139                                                                           DWORD timeout_ms) {
140         struct usbi_cond_perthread *pos;
141         int found = 0, r;
142         DWORD r2,tid = GetCurrentThreadId();
143         if(!cond || !mutex) return ((errno=EINVAL));
144         list_for_each_entry(pos, &cond->not_waiting, list, struct usbi_cond_perthread) {
145                 if(tid == pos->tid) {
146                         found = 1;
147                         break;
148                 }
149         }
150         if(!found) {
151                 pos      = (struct usbi_cond_perthread*) calloc(1, sizeof(struct usbi_cond_perthread));
152                 if(!pos) return ((errno=ENOMEM)); // This errno is not POSIX-allowed.
153                 pos->tid = tid;
154                 pos->event = CreateEvent(NULL, FALSE, FALSE, NULL); // auto-reset.
155                 if(!pos->event) {
156                         free(pos);
157                         return      ((errno=ENOMEM));
158                 }
159                 list_add(&pos->list, &cond->not_waiting);
160         }
161
162         list_del(&pos->list); // remove from not_waiting list.
163         list_add(&pos->list, &cond->waiters);
164
165         r  = usbi_mutex_unlock(mutex);
166         if(r) return r;
167         r2 = WaitForSingleObject(pos->event, timeout_ms);
168         r  = usbi_mutex_lock(mutex);
169         if(r) return r;
170
171         list_del(&pos->list);
172         list_add(&pos->list, &cond->not_waiting);
173
174         if(r2 == WAIT_TIMEOUT) return ((errno=ETIMEDOUT));
175
176         return 0;
177 }
178 // N.B.: usbi_cond_*wait() can also return ENOMEM, even though pthread_cond_*wait cannot!
179 int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex) {
180         return usbi_cond_intwait(cond, mutex, INFINITE);
181 }
182 int usbi_cond_timedwait(usbi_cond_t *cond,
183                                                 usbi_mutex_t *mutex,
184                                                 const struct timespec *abstime) {
185         FILETIME filetime;
186         ULARGE_INTEGER rtime;
187         struct timeval targ_time, cur_time, delta_time;
188         struct timespec cur_time_ns;
189         DWORD millis;
190         extern const uint64_t epoch_time;
191
192 #ifdef _WIN32_WCE
193         SYSTEMTIME st;
194         GetSystemTime(&st);
195         SystemTimeToFileTime(&st, &filetime);
196 #else
197         GetSystemTimeAsFileTime(&filetime);
198 #endif
199         rtime.LowPart   = filetime.dwLowDateTime;
200         rtime.HighPart  = filetime.dwHighDateTime;
201         rtime.QuadPart -= epoch_time;
202         cur_time_ns.tv_sec = (long)(rtime.QuadPart / 10000000);
203         cur_time_ns.tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
204         TIMESPEC_TO_TIMEVAL(&cur_time, &cur_time_ns);
205
206         TIMESPEC_TO_TIMEVAL(&targ_time, abstime);
207         timersub(&targ_time, &cur_time, &delta_time);
208         if(delta_time.tv_sec < 0) // abstime already passed?
209                 millis = 0;
210         else {
211                 millis  = delta_time.tv_usec/1000;
212                 millis += delta_time.tv_sec *1000;
213                 if (delta_time.tv_usec % 1000) // round up to next millisecond
214                         millis++;
215         }
216
217         return usbi_cond_intwait(cond, mutex, millis);
218 }
219
220 int usbi_get_tid(void) {
221         return GetCurrentThreadId();
222 }