winmm: Maintain the timer list sorted by expiration time.
[wine] / dlls / winmm / time.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2
3 /*
4  * MMSYSTEM time functions
5  *
6  * Copyright 1993 Martin Ayotte
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <errno.h>
28 #include <time.h>
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38 #ifdef HAVE_SYS_POLL_H
39 #include <sys/poll.h>
40 #endif
41
42 #include "windef.h"
43 #include "winbase.h"
44 #include "mmsystem.h"
45
46 #include "winemm.h"
47
48 #include "wine/list.h"
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(mmtime);
52
53 typedef struct tagWINE_TIMERENTRY {
54     struct list                 entry;
55     UINT                        wDelay;
56     UINT                        wResol;
57     LPTIMECALLBACK              lpFunc; /* can be lots of things */
58     DWORD                       dwUser;
59     UINT16                      wFlags;
60     UINT16                      wTimerID;
61     DWORD                       dwTriggerTime;
62 } WINE_TIMERENTRY, *LPWINE_TIMERENTRY;
63
64 static struct list timer_list = LIST_INIT(timer_list);
65
66 static    HANDLE                TIME_hMMTimer;
67 static    CRITICAL_SECTION      TIME_cbcrst;
68 static    BOOL                  TIME_TimeToDie = TRUE;
69 static    int                   TIME_fdWake[2] = { -1, -1 };
70
71 /* link timer at the appropriate spot in the list */
72 static inline void link_timer( WINE_TIMERENTRY *timer )
73 {
74     WINE_TIMERENTRY *next;
75
76     LIST_FOR_EACH_ENTRY( next, &timer_list, WINE_TIMERENTRY, entry )
77         if ((int)(next->dwTriggerTime - timer->dwTriggerTime) >= 0) break;
78
79     list_add_before( &next->entry, &timer->entry );
80 }
81
82 /*
83  * Some observations on the behavior of winmm on Windows.
84  * First, the call to timeBeginPeriod(xx) can never be used
85  * to raise the timer resolution, only lower it.
86  *
87  * Second, a brief survey of a variety of Win 2k and Win X
88  * machines showed that a 'standard' (aka default) timer
89  * resolution was 1 ms (Win9x is documented as being 1).  However, one 
90  * machine had a standard timer resolution of 10 ms.
91  *
92  * Further, if we set our default resolution to 1,
93  * the implementation of timeGetTime becomes GetTickCount(),
94  * and we can optimize the code to reduce overhead.
95  *
96  * Additionally, a survey of Event behaviors shows that
97  * if we request a Periodic event every 50 ms, then Windows
98  * makes sure to trigger that event 20 times in the next
99  * second.  If delays prevent that from happening on exact
100  * schedule, Windows will trigger the events as close
101  * to the original schedule as is possible, and will eventually
102  * bring the event triggers back onto a schedule that is
103  * consistent with what would have happened if there were
104  * no delays.
105  *
106  *   Jeremy White, October 2004
107  */
108 #define MMSYSTIME_MININTERVAL (1)
109 #define MMSYSTIME_MAXINTERVAL (65535)
110
111
112 /**************************************************************************
113  *           TIME_MMSysTimeCallback
114  */
115 static int TIME_MMSysTimeCallback(void)
116 {
117     WINE_TIMERENTRY *timer, *to_free;
118     int delta_time;
119
120     /* since timeSetEvent() and timeKillEvent() can be called
121      * from 16 bit code, there are cases where win16 lock is
122      * locked upon entering timeSetEvent(), and then the mm timer
123      * critical section is locked. This function cannot call the
124      * timer callback with the crit sect locked (because callback
125      * may need to acquire Win16 lock, thus providing a deadlock
126      * situation).
127      * To cope with that, we just copy the WINE_TIMERENTRY struct
128      * that need to trigger the callback, and call it without the
129      * mm timer crit sect locked.
130      */
131
132     EnterCriticalSection(&WINMM_cs);
133     for (;;)
134     {
135         struct list *ptr = list_head( &timer_list );
136         if (!ptr)
137         {
138             delta_time = -1;
139             break;
140         }
141
142         timer = LIST_ENTRY( ptr, WINE_TIMERENTRY, entry );
143         delta_time = timer->dwTriggerTime - GetTickCount();
144         if (delta_time > 0) break;
145
146         list_remove( &timer->entry );
147         if (timer->wFlags & TIME_PERIODIC)
148         {
149             timer->dwTriggerTime += timer->wDelay;
150             link_timer( timer );  /* restart it */
151             to_free = NULL;
152         }
153         else to_free = timer;
154
155         switch(timer->wFlags & (TIME_CALLBACK_EVENT_SET|TIME_CALLBACK_EVENT_PULSE))
156         {
157         case TIME_CALLBACK_EVENT_SET:
158             SetEvent((HANDLE)timer->lpFunc);
159             break;
160         case TIME_CALLBACK_EVENT_PULSE:
161             PulseEvent((HANDLE)timer->lpFunc);
162             break;
163         case TIME_CALLBACK_FUNCTION:
164             {
165                 DWORD user = timer->dwUser;
166                 UINT16 id = timer->wTimerID;
167                 UINT16 flags = timer->wFlags;
168                 LPTIMECALLBACK func = timer->lpFunc;
169
170                 if (flags & TIME_KILL_SYNCHRONOUS) EnterCriticalSection(&TIME_cbcrst);
171                 LeaveCriticalSection(&WINMM_cs);
172
173                 if (flags & WINE_TIMER_IS32) func(id, 0, user, 0, 0);
174                 else if (pFnCallMMDrvFunc16) pFnCallMMDrvFunc16((DWORD)func, id, 0, user, 0, 0);
175
176                 EnterCriticalSection(&WINMM_cs);
177                 if (flags & TIME_KILL_SYNCHRONOUS) LeaveCriticalSection(&TIME_cbcrst);
178             }
179             break;
180         }
181         HeapFree( GetProcessHeap(), 0, to_free );
182     }
183     LeaveCriticalSection(&WINMM_cs);
184     return delta_time;
185 }
186
187 /**************************************************************************
188  *           TIME_MMSysTimeThread
189  */
190 static DWORD CALLBACK TIME_MMSysTimeThread(LPVOID arg)
191 {
192     int sleep_time, ret;
193     char readme[16];
194     struct pollfd pfd;
195
196     pfd.fd = TIME_fdWake[0];
197     pfd.events = POLLIN;
198
199     TRACE("Starting main winmm thread\n");
200
201     /* FIXME:  As an optimization, we could have
202                this thread die when there are no more requests
203                pending, and then get recreated on the first
204                new event; it's not clear if that would be worth
205                it or not.                 */
206
207     while (! TIME_TimeToDie) 
208     {
209         sleep_time = TIME_MMSysTimeCallback();
210
211         if (sleep_time == 0)
212             continue;
213
214         if ((ret = poll(&pfd, 1, sleep_time)) < 0)
215         {
216             if (errno != EINTR && errno != EAGAIN)
217             {
218                 ERR("Unexpected error in poll: %s(%d)\n", strerror(errno), errno);
219                 break;
220             }
221          }
222
223         while (ret > 0) ret = read(TIME_fdWake[0], readme, sizeof(readme));
224     }
225     TRACE("Exiting main winmm thread\n");
226     return 0;
227 }
228
229 /**************************************************************************
230  *                              TIME_MMTimeStart
231  */
232 static void TIME_MMTimeStart(void)
233 {
234     if (!TIME_hMMTimer) {
235         if (pipe(TIME_fdWake) < 0)
236         {
237             TIME_fdWake[0] = TIME_fdWake[1] = -1;
238             ERR("Cannot create pipe: %s\n", strerror(errno));
239         } else {
240             fcntl(TIME_fdWake[0], F_SETFL, O_NONBLOCK);
241             fcntl(TIME_fdWake[1], F_SETFL, O_NONBLOCK);
242         }
243         TIME_TimeToDie = FALSE;
244         TIME_hMMTimer = CreateThread(NULL, 0, TIME_MMSysTimeThread, NULL, 0, NULL);
245         SetThreadPriority(TIME_hMMTimer, THREAD_PRIORITY_TIME_CRITICAL);
246         InitializeCriticalSection(&TIME_cbcrst);
247         TIME_cbcrst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": WINMM.TIME_cbcrst");
248     }
249 }
250
251 /**************************************************************************
252  *                              TIME_MMTimeStop
253  */
254 void    TIME_MMTimeStop(void)
255 {
256     if (TIME_hMMTimer) {
257         const char a='a';
258
259         TIME_TimeToDie = TRUE;
260         write(TIME_fdWake[1], &a, sizeof(a));
261
262         WaitForSingleObject(TIME_hMMTimer, INFINITE);
263         close(TIME_fdWake[0]);
264         close(TIME_fdWake[1]);
265         TIME_fdWake[0] = TIME_fdWake[1] = -1;
266         CloseHandle(TIME_hMMTimer);
267         TIME_hMMTimer = 0;
268         TIME_cbcrst.DebugInfo->Spare[0] = 0;
269         DeleteCriticalSection(&TIME_cbcrst);
270     }
271 }
272
273 /**************************************************************************
274  *                              timeGetSystemTime       [WINMM.@]
275  */
276 MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
277 {
278
279     if (wSize >= sizeof(*lpTime)) {
280         lpTime->wType = TIME_MS;
281         lpTime->u.ms = GetTickCount();
282
283     }
284
285     return 0;
286 }
287
288 /**************************************************************************
289  *                              TIME_SetEventInternal   [internal]
290  */
291 WORD    TIME_SetEventInternal(UINT wDelay, UINT wResol,
292                               LPTIMECALLBACK lpFunc, DWORD dwUser, UINT wFlags)
293 {
294     WORD                wNewID = 0;
295     LPWINE_TIMERENTRY   lpNewTimer;
296     LPWINE_TIMERENTRY   lpTimer;
297     const char c = 'c';
298
299     TRACE("(%u, %u, %p, %08X, %04X);\n", wDelay, wResol, lpFunc, dwUser, wFlags);
300
301     if (wDelay < MMSYSTIME_MININTERVAL || wDelay > MMSYSTIME_MAXINTERVAL)
302         return 0;
303
304     lpNewTimer = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
305     if (lpNewTimer == NULL)
306         return 0;
307
308     lpNewTimer->wDelay = wDelay;
309     lpNewTimer->dwTriggerTime = GetTickCount() + wDelay;
310
311     /* FIXME - wResol is not respected, although it is not clear
312                that we could change our precision meaningfully  */
313     lpNewTimer->wResol = wResol;
314     lpNewTimer->lpFunc = lpFunc;
315     lpNewTimer->dwUser = dwUser;
316     lpNewTimer->wFlags = wFlags;
317
318     EnterCriticalSection(&WINMM_cs);
319
320     LIST_FOR_EACH_ENTRY( lpTimer, &timer_list, WINE_TIMERENTRY, entry )
321         wNewID = max(wNewID, lpTimer->wTimerID);
322
323     link_timer( lpNewTimer );
324     lpNewTimer->wTimerID = wNewID + 1;
325
326     TIME_MMTimeStart();
327
328     LeaveCriticalSection(&WINMM_cs);
329
330     /* Wake the service thread in case there is work to be done */
331     write(TIME_fdWake[1], &c, sizeof(c));
332
333     TRACE("=> %u\n", wNewID + 1);
334
335     return wNewID + 1;
336 }
337
338 /**************************************************************************
339  *                              timeSetEvent            [WINMM.@]
340  */
341 MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
342                             DWORD_PTR dwUser, UINT wFlags)
343 {
344     if (wFlags & WINE_TIMER_IS32)
345         WARN("Unknown windows flag... wine internally used.. ooch\n");
346
347     return TIME_SetEventInternal(wDelay, wResol, lpFunc,
348                                  dwUser, wFlags|WINE_TIMER_IS32);
349 }
350
351 /**************************************************************************
352  *                              timeKillEvent           [WINMM.@]
353  */
354 MMRESULT WINAPI timeKillEvent(UINT wID)
355 {
356     WINE_TIMERENTRY *lpSelf = NULL, *lpTimer;
357
358     TRACE("(%u)\n", wID);
359     EnterCriticalSection(&WINMM_cs);
360     /* remove WINE_TIMERENTRY from list */
361     LIST_FOR_EACH_ENTRY( lpTimer, &timer_list, WINE_TIMERENTRY, entry )
362     {
363         if (wID == lpTimer->wTimerID) {
364             lpSelf = lpTimer;
365             list_remove( &lpTimer->entry );
366             break;
367         }
368     }
369     LeaveCriticalSection(&WINMM_cs);
370
371     if (!lpSelf)
372     {
373         WARN("wID=%u is not a valid timer ID\n", wID);
374         return MMSYSERR_INVALPARAM;
375     }
376     if (lpSelf->wFlags & TIME_KILL_SYNCHRONOUS)
377         EnterCriticalSection(&TIME_cbcrst);
378     HeapFree(GetProcessHeap(), 0, lpSelf);
379     if (lpSelf->wFlags & TIME_KILL_SYNCHRONOUS)
380         LeaveCriticalSection(&TIME_cbcrst);
381     return TIMERR_NOERROR;
382 }
383
384 /**************************************************************************
385  *                              timeGetDevCaps          [WINMM.@]
386  */
387 MMRESULT WINAPI timeGetDevCaps(LPTIMECAPS lpCaps, UINT wSize)
388 {
389     TRACE("(%p, %u)\n", lpCaps, wSize);
390
391     if (lpCaps == 0) {
392         WARN("invalid lpCaps\n");
393         return TIMERR_NOCANDO;
394     }
395
396     if (wSize < sizeof(TIMECAPS)) {
397         WARN("invalid wSize\n");
398         return TIMERR_NOCANDO;
399     }
400
401     lpCaps->wPeriodMin = MMSYSTIME_MININTERVAL;
402     lpCaps->wPeriodMax = MMSYSTIME_MAXINTERVAL;
403     return TIMERR_NOERROR;
404 }
405
406 /**************************************************************************
407  *                              timeBeginPeriod         [WINMM.@]
408  */
409 MMRESULT WINAPI timeBeginPeriod(UINT wPeriod)
410 {
411     if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
412         return TIMERR_NOCANDO;
413
414     if (wPeriod > MMSYSTIME_MININTERVAL)
415     {
416         WARN("Stub; we set our timer resolution at minimum\n");
417     }
418
419     return 0;
420 }
421
422 /**************************************************************************
423  *                              timeEndPeriod           [WINMM.@]
424  */
425 MMRESULT WINAPI timeEndPeriod(UINT wPeriod)
426 {
427     if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
428         return TIMERR_NOCANDO;
429
430     if (wPeriod > MMSYSTIME_MININTERVAL)
431     {
432         WARN("Stub; we set our timer resolution at minimum\n");
433     }
434     return 0;
435 }
436
437 /**************************************************************************
438  *                              timeGetTime    [MMSYSTEM.607]
439  *                              timeGetTime    [WINMM.@]
440  */
441 DWORD WINAPI timeGetTime(void)
442 {
443 #if defined(COMMENTOUTPRIORTODELETING)
444     DWORD       count;
445
446     /* FIXME: releasing the win16 lock here is a temporary hack (I hope)
447      * that lets mciavi32.dll run correctly
448      */
449     if (pFnReleaseThunkLock) pFnReleaseThunkLock(&count);
450     if (pFnRestoreThunkLock) pFnRestoreThunkLock(count);
451 #endif
452
453     return GetTickCount();
454 }