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