7c09e7dc558a163322faa6f4b8349dac8a937075
[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
29 int usbi_mutex_init(usbi_mutex_t *mutex,
30                                         const usbi_mutexattr_t *attr) {
31         UNUSED(attr);
32         if(! mutex) return ((errno=EINVAL));
33         *mutex = CreateMutex(NULL, FALSE, NULL);
34         if(!*mutex) return ((errno=ENOMEM));
35         return 0;
36 }
37 int usbi_mutex_destroy(usbi_mutex_t *mutex) {
38         // It is not clear if CloseHandle failure is due to failure to unlock.
39         //   If so, this should be errno=EBUSY.
40         if(!mutex || !CloseHandle(*mutex)) return ((errno=EINVAL));
41         *mutex = NULL;
42         return 0;
43 }
44 int usbi_mutex_trylock(usbi_mutex_t *mutex) {
45         DWORD result;
46         if(!mutex) return ((errno=EINVAL));
47         result = WaitForSingleObject(*mutex, 0);
48         if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
49                 return 0; // acquired (ToDo: check that abandoned is ok)
50         if(result == WAIT_TIMEOUT)
51                 return ((errno=EBUSY));
52         return ((errno=EINVAL)); // don't know how this would happen
53                                                          //   so don't know proper errno
54 }
55 int usbi_mutex_lock(usbi_mutex_t *mutex) {
56         DWORD result;
57         if(!mutex) return ((errno=EINVAL));
58         result = WaitForSingleObject(*mutex, INFINITE);
59         if(result == WAIT_OBJECT_0 || result == WAIT_ABANDONED)
60                 return 0; // acquired (ToDo: check that abandoned is ok)
61         return ((errno=EINVAL)); // don't know how this would happen
62                                                          //   so don't know proper errno
63 }
64 int usbi_mutex_unlock(usbi_mutex_t *mutex) {
65         if(!mutex)                return ((errno=EINVAL));
66         if(!ReleaseMutex(*mutex)) return ((errno=EPERM ));
67         return 0;
68 }
69
70 int usbi_mutex_static_lock(usbi_mutex_static_t *mutex) {
71         if(!mutex)               return ((errno=EINVAL));
72         while (InterlockedExchange((LONG *)mutex, 1) == 1) {
73                 SleepEx(0, TRUE);
74         }
75         return 0;
76 }
77 int usbi_mutex_static_unlock(usbi_mutex_static_t *mutex) {
78         if(!mutex)               return ((errno=EINVAL));
79         *mutex = 0;
80         return 0;
81 }
82
83
84
85 int usbi_cond_init(usbi_cond_t *cond,
86                                    const usbi_condattr_t *attr) {
87         UNUSED(attr);
88         if(!cond)           return ((errno=EINVAL));
89         list_init(&cond->waiters    );
90         list_init(&cond->not_waiting);
91         return 0;
92 }
93 int usbi_cond_destroy(usbi_cond_t *cond) {
94         // This assumes no one is using this anymore.  The check MAY NOT BE safe.
95         struct usbi_cond_perthread *pos, *next_pos = NULL;
96         if(!cond) return ((errno=EINVAL));
97         if(!list_empty(&cond->waiters)) return ((errno=EBUSY )); // (!see above!)
98         list_for_each_entry_safe(pos, next_pos, &cond->not_waiting, list, struct usbi_cond_perthread) {
99                 CloseHandle(pos->event);
100                 list_del(&pos->list);
101                 free(pos);
102         }
103
104         return 0;
105 }
106
107 int usbi_cond_broadcast(usbi_cond_t *cond) {
108         // Assumes mutex is locked; this is not in keeping with POSIX spec, but
109         //   libusb does this anyway, so we simplify by not adding more sync
110         //   primitives to the CV definition!
111         int fail = 0;
112         struct usbi_cond_perthread *pos;
113         if(!cond)                      return ((errno=EINVAL));
114         list_for_each_entry(pos, &cond->waiters, list, struct usbi_cond_perthread) {
115                 if(!SetEvent(pos->event))
116                         fail = 1;
117         }
118         // The wait function will remove its respective item from the list.
119         return fail ? ((errno=EINVAL)) : 0;
120 }
121 int usbi_cond_signal(usbi_cond_t *cond) {
122         // Assumes mutex is locked; this is not in keeping with POSIX spec, but
123         //   libusb does this anyway, so we simplify by not adding more sync
124         //   primitives to the CV definition!
125         struct usbi_cond_perthread *pos;
126         if(!cond)                      return ((errno=EINVAL));
127         if(list_empty(&cond->waiters)) return 0; // no one to wakeup.
128         pos = list_entry(&cond->waiters.next, struct usbi_cond_perthread, list);
129         // The wait function will remove its respective item from the list.
130         return SetEvent(pos->event) ? 0 : ((errno=EINVAL));
131 }
132 static int __inline usbi_cond_intwait(usbi_cond_t *cond,
133                                                                           usbi_mutex_t *mutex,
134                                                                           DWORD timeout_ms) {
135         struct usbi_cond_perthread *pos;
136         int found = 0, r;
137         DWORD r2,tid = GetCurrentThreadId();
138         if(!cond || !mutex) return ((errno=EINVAL));
139         list_for_each_entry(pos, &cond->not_waiting, list, struct usbi_cond_perthread) {
140                 if(tid == pos->tid) {
141                         found = 1;
142                         break;
143                 }
144         }
145         if(!found) {
146                 pos      = (struct usbi_cond_perthread*) calloc(1, sizeof(struct usbi_cond_perthread));
147                 if(!pos) return ((errno=ENOMEM)); // This errno is not POSIX-allowed.
148                 pos->tid = tid;
149                 pos->event = CreateEvent(NULL, FALSE, FALSE, NULL); // auto-reset.
150                 if(!pos->event) {
151                         free(pos);
152                         return      ((errno=ENOMEM));
153                 }
154                 list_add(&pos->list, &cond->not_waiting);
155         }
156
157         list_del(&pos->list); // remove from not_waiting list.
158         list_add(&pos->list, &cond->waiters);
159
160         r  = usbi_mutex_unlock(mutex);
161         if(r) return r;
162         r2 = WaitForSingleObject(pos->event, timeout_ms);
163         r  = usbi_mutex_lock(mutex);
164         if(r) return r;
165
166         list_del(&pos->list);
167         list_add(&pos->list, &cond->not_waiting);
168
169         if(r2 == WAIT_TIMEOUT) return ((errno=ETIMEDOUT));
170
171         return 0;
172 }
173 // N.B.: usbi_cond_*wait() can also return ENOMEM, even though pthread_cond_*wait cannot!
174 int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex) {
175         return usbi_cond_intwait(cond, mutex, INFINITE);
176 }
177 int usbi_cond_timedwait(usbi_cond_t *cond,
178                                                 usbi_mutex_t *mutex,
179                                                 const struct timespec *abstime) {
180         FILETIME filetime;
181         ULARGE_INTEGER rtime;
182         struct timeval targ_time, cur_time, delta_time;
183         struct timespec cur_time_ns;
184         DWORD millis;
185         extern const uint64_t epoch_time;
186
187         GetSystemTimeAsFileTime(&filetime);
188         rtime.LowPart   = filetime.dwLowDateTime;
189         rtime.HighPart  = filetime.dwHighDateTime;
190         rtime.QuadPart -= epoch_time;
191         cur_time_ns.tv_sec = (long)(rtime.QuadPart / 10000000);
192         cur_time_ns.tv_nsec = (long)((rtime.QuadPart % 10000000)*100);
193         TIMESPEC_TO_TIMEVAL(&cur_time, &cur_time_ns);
194
195         TIMESPEC_TO_TIMEVAL(&targ_time, abstime);
196         timersub(&targ_time, &cur_time, &delta_time);
197         if(delta_time.tv_sec < 0) // abstime already passed?
198                 millis = 0;
199         else {
200                 millis  = delta_time.tv_usec/1000;
201                 millis += delta_time.tv_sec *1000;
202                 if (delta_time.tv_usec % 1000) // round up to next millisecond
203                         millis++;
204         }
205
206         return usbi_cond_intwait(cond, mutex, millis);
207 }
208
209 int usbi_get_tid(void) {
210         return GetCurrentThreadId();
211 }