1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
4 * MMSYSTEM time functions
6 * Copyright 1993 Martin Ayotte
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "wine/port.h"
28 #ifdef HAVE_SYS_TIME_H
29 # include <sys/time.h>
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(mmtime);
45 static HANDLE TIME_hMMTimer;
46 static LPWINE_TIMERENTRY TIME_TimersList;
47 static HANDLE TIME_hKillEvent;
48 static HANDLE TIME_hWakeEvent;
49 static BOOL TIME_TimeToDie = TRUE;
52 * Some observations on the behavior of winmm on Windows.
53 * First, the call to timeBeginPeriod(xx) can never be used
54 * to raise the timer resolution, only lower it.
56 * Second, a brief survey of a variety of Win 2k and Win X
57 * machines showed that a 'standard' (aka default) timer
58 * resolution was 1 ms (Win9x is documented as being 1). However, one
59 * machine had a standard timer resolution of 10 ms.
61 * Further, if we set our default resolution to 1,
62 * the implementation of timeGetTime becomes GetTickCount(),
63 * and we can optimize the code to reduce overhead.
65 * Additionally, a survey of Event behaviors shows that
66 * if we request a Periodic event every 50 ms, then Windows
67 * makes sure to trigger that event 20 times in the next
68 * second. If delays prevent that from happening on exact
69 * schedule, Windows will trigger the events as close
70 * to the original schedule as is possible, and will eventually
71 * bring the event triggers back onto a schedule that is
72 * consistent with what would have happened if there were
75 * Jeremy White, October 2004
77 #define MMSYSTIME_MININTERVAL (1)
78 #define MMSYSTIME_MAXINTERVAL (65535)
81 static void TIME_TriggerCallBack(LPWINE_TIMERENTRY lpTimer)
83 TRACE("%04lx:CallBack => lpFunc=%p wTimerID=%04X dwUser=%08lX dwTriggerTime %ld(delta %ld)\n",
84 GetCurrentThreadId(), lpTimer->lpFunc, lpTimer->wTimerID, lpTimer->dwUser,
85 lpTimer->dwTriggerTime, GetTickCount() - lpTimer->dwTriggerTime);
87 /* - TimeProc callback that is called here is something strange, under Windows 3.1x it is called
88 * during interrupt time, is allowed to execute very limited number of API calls (like
89 * PostMessage), and must reside in DLL (therefore uses stack of active application). So I
90 * guess current implementation via SetTimer has to be improved upon.
92 switch (lpTimer->wFlags & 0x30) {
93 case TIME_CALLBACK_FUNCTION:
94 if (lpTimer->wFlags & WINE_TIMER_IS32)
95 (lpTimer->lpFunc)(lpTimer->wTimerID, 0, lpTimer->dwUser, 0, 0);
96 else if (pFnCallMMDrvFunc16)
97 pFnCallMMDrvFunc16((DWORD)lpTimer->lpFunc, lpTimer->wTimerID, 0,
98 lpTimer->dwUser, 0, 0);
100 case TIME_CALLBACK_EVENT_SET:
101 SetEvent((HANDLE)lpTimer->lpFunc);
103 case TIME_CALLBACK_EVENT_PULSE:
104 PulseEvent((HANDLE)lpTimer->lpFunc);
107 FIXME("Unknown callback type 0x%04x for mmtime callback (%p), ignored.\n",
108 lpTimer->wFlags, lpTimer->lpFunc);
113 /**************************************************************************
114 * TIME_MMSysTimeCallback
116 static DWORD CALLBACK TIME_MMSysTimeCallback(LPWINE_MM_IDATA iData)
118 static int nSizeLpTimers;
119 static LPWINE_TIMERENTRY lpTimers;
121 LPWINE_TIMERENTRY timer, *ptimer, *next_ptimer;
125 DWORD ret_time = INFINITE;
129 /* optimize for the most frequent case - no events */
130 if (! TIME_TimersList)
133 /* since timeSetEvent() and timeKillEvent() can be called
134 * from 16 bit code, there are cases where win16 lock is
135 * locked upon entering timeSetEvent(), and then the mm timer
136 * critical section is locked. This function cannot call the
137 * timer callback with the crit sect locked (because callback
138 * may need to acquire Win16 lock, thus providing a deadlock
140 * To cope with that, we just copy the WINE_TIMERENTRY struct
141 * that need to trigger the callback, and call it without the
142 * mm timer crit sect locked.
143 * the hKillTimeEvent is used to mark the section where we
144 * handle the callbacks so we can do synchronous kills.
145 * EPP 99/07/13, updated 04/01/10
148 cur_time = GetTickCount();
150 EnterCriticalSection(&iData->cs);
151 for (ptimer = &TIME_TimersList; *ptimer != NULL; ) {
153 next_ptimer = &timer->lpNext;
154 if (cur_time >= timer->dwTriggerTime)
157 if (idx == nSizeLpTimers) {
159 lpTimers = (LPWINE_TIMERENTRY)
160 HeapReAlloc(GetProcessHeap(), 0, lpTimers,
161 ++nSizeLpTimers * sizeof(WINE_TIMERENTRY));
163 lpTimers = (LPWINE_TIMERENTRY)
164 HeapAlloc(GetProcessHeap(), 0,
165 ++nSizeLpTimers * sizeof(WINE_TIMERENTRY));
167 lpTimers[idx++] = *timer;
171 /* Update the time after we make the copy to preserve
172 the original trigger time */
173 timer->dwTriggerTime += timer->wDelay;
175 /* TIME_ONESHOT is defined as 0 */
176 if (!(timer->wFlags & TIME_PERIODIC))
178 /* unlink timer from timers list */
179 *ptimer = *next_ptimer;
180 HeapFree(GetProcessHeap(), 0, timer);
182 /* We don't need to trigger oneshots again */
183 delta_time = INFINITE;
187 /* Compute when this event needs this function
188 to be called again */
189 if (timer->dwTriggerTime <= cur_time)
192 delta_time = timer->dwTriggerTime - cur_time;
196 delta_time = timer->dwTriggerTime - cur_time;
198 /* Determine when we need to return to this function */
199 ret_time = min(ret_time, delta_time);
201 ptimer = next_ptimer;
203 if (TIME_hKillEvent) ResetEvent(TIME_hKillEvent);
204 LeaveCriticalSection(&iData->cs);
206 while (idx > 0) TIME_TriggerCallBack(&lpTimers[--idx]);
207 if (TIME_hKillEvent) SetEvent(TIME_hKillEvent);
209 /* Finally, adjust the recommended wait time downward
210 by the amount of time the processing routines
212 adjust_time = GetTickCount() - cur_time;
213 if (adjust_time > ret_time)
216 ret_time -= adjust_time;
218 /* We return the amount of time our caller should sleep
219 before needing to check in on us again */
223 /**************************************************************************
224 * TIME_MMSysTimeThread
226 static DWORD CALLBACK TIME_MMSysTimeThread(LPVOID arg)
228 LPWINE_MM_IDATA iData = (LPWINE_MM_IDATA)arg;
232 TRACE("Starting main winmm thread\n");
234 /* FIXME: As an optimization, we could have
235 this thread die when there are no more requests
236 pending, and then get recreated on the first
237 new event; it's not clear if that would be worth
240 while (! TIME_TimeToDie)
242 sleep_time = TIME_MMSysTimeCallback(iData);
246 /* This Sleep is controversial; it was added to make
247 Wine able to replicate a high speed (e.g. 1 ms)
248 timer event where the called event routine chews
249 a lot of CPU. This is required because of the
250 bias some Linux kernel versions have against threads that
251 chew a lot of the CPU; this Sleep(0) yields enough
252 in that spin case doesn't trigger the bias.
253 Further, it should do no harm, but an fyi. */
258 rc = WaitForSingleObject(TIME_hWakeEvent, sleep_time);
259 if (rc != WAIT_TIMEOUT && rc != WAIT_OBJECT_0)
261 FIXME("Unexpected error %ld(%ld) in timer thread\n", rc, GetLastError());
265 TRACE("Exiting main winmm thread\n");
269 /**************************************************************************
272 void TIME_MMTimeStart(void)
274 if (!TIME_hMMTimer) {
275 TIME_TimersList = NULL;
276 TIME_hWakeEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
277 TIME_TimeToDie = FALSE;
278 TIME_hMMTimer = CreateThread(NULL, 0, TIME_MMSysTimeThread, WINMM_IData, 0, NULL);
282 /**************************************************************************
285 void TIME_MMTimeStop(void)
289 TIME_TimeToDie = TRUE;
290 SetEvent(TIME_hWakeEvent);
292 /* FIXME: in the worst case, we're going to wait 65 seconds here :-( */
293 WaitForSingleObject(TIME_hMMTimer, INFINITE);
295 CloseHandle(TIME_hMMTimer);
296 CloseHandle(TIME_hWakeEvent);
298 TIME_TimersList = NULL;
302 /**************************************************************************
303 * timeGetSystemTime [WINMM.@]
305 MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
308 if (wSize >= sizeof(*lpTime)) {
309 lpTime->wType = TIME_MS;
310 lpTime->u.ms = GetTickCount();
317 /**************************************************************************
318 * TIME_SetEventInternal [internal]
320 WORD TIME_SetEventInternal(UINT wDelay, UINT wResol,
321 LPTIMECALLBACK lpFunc, DWORD dwUser, UINT wFlags)
324 LPWINE_TIMERENTRY lpNewTimer;
325 LPWINE_TIMERENTRY lpTimer;
327 TRACE("(%u, %u, %p, %08lX, %04X);\n", wDelay, wResol, lpFunc, dwUser, wFlags);
329 lpNewTimer = (LPWINE_TIMERENTRY)HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
330 if (lpNewTimer == NULL)
333 if (wDelay < MMSYSTIME_MININTERVAL || wDelay > MMSYSTIME_MAXINTERVAL)
338 lpNewTimer->wDelay = wDelay;
339 lpNewTimer->dwTriggerTime = GetTickCount() + wDelay;
341 /* FIXME - wResol is not respected, although it is not clear
342 that we could change our precision meaningfully */
343 lpNewTimer->wResol = wResol;
344 lpNewTimer->lpFunc = lpFunc;
345 lpNewTimer->dwUser = dwUser;
346 lpNewTimer->wFlags = wFlags;
348 EnterCriticalSection(&WINMM_IData->cs);
350 if ((wFlags & TIME_KILL_SYNCHRONOUS) && !TIME_hKillEvent)
351 TIME_hKillEvent = CreateEventW(NULL, TRUE, TRUE, NULL);
353 for (lpTimer = TIME_TimersList; lpTimer != NULL; lpTimer = lpTimer->lpNext) {
354 wNewID = max(wNewID, lpTimer->wTimerID);
357 lpNewTimer->lpNext = TIME_TimersList;
358 TIME_TimersList = lpNewTimer;
359 lpNewTimer->wTimerID = wNewID + 1;
361 LeaveCriticalSection(&WINMM_IData->cs);
363 /* Wake the service thread in case there is work to be done */
364 SetEvent(TIME_hWakeEvent);
366 TRACE("=> %u\n", wNewID + 1);
371 /**************************************************************************
372 * timeSetEvent [WINMM.@]
374 MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
375 DWORD_PTR dwUser, UINT wFlags)
377 if (wFlags & WINE_TIMER_IS32)
378 WARN("Unknown windows flag... wine internally used.. ooch\n");
380 return TIME_SetEventInternal(wDelay, wResol, lpFunc,
381 dwUser, wFlags|WINE_TIMER_IS32);
384 /**************************************************************************
385 * timeKillEvent [WINMM.@]
387 MMRESULT WINAPI timeKillEvent(UINT wID)
389 LPWINE_TIMERENTRY lpSelf = NULL, *lpTimer;
391 TRACE("(%u)\n", wID);
392 EnterCriticalSection(&WINMM_IData->cs);
393 /* remove WINE_TIMERENTRY from list */
394 for (lpTimer = &TIME_TimersList; *lpTimer; lpTimer = &(*lpTimer)->lpNext) {
395 if (wID == (*lpTimer)->wTimerID) {
397 /* unlink timer of id 'wID' */
398 *lpTimer = (*lpTimer)->lpNext;
402 LeaveCriticalSection(&WINMM_IData->cs);
406 WARN("wID=%u is not a valid timer ID\n", wID);
407 return MMSYSERR_INVALPARAM;
409 if (lpSelf->wFlags & TIME_KILL_SYNCHRONOUS)
410 WaitForSingleObject(TIME_hKillEvent, INFINITE);
411 HeapFree(GetProcessHeap(), 0, lpSelf);
412 return TIMERR_NOERROR;
415 /**************************************************************************
416 * timeGetDevCaps [WINMM.@]
418 MMRESULT WINAPI timeGetDevCaps(LPTIMECAPS lpCaps, UINT wSize)
420 TRACE("(%p, %u)\n", lpCaps, wSize);
422 lpCaps->wPeriodMin = MMSYSTIME_MININTERVAL;
423 lpCaps->wPeriodMax = MMSYSTIME_MAXINTERVAL;
427 /**************************************************************************
428 * timeBeginPeriod [WINMM.@]
430 MMRESULT WINAPI timeBeginPeriod(UINT wPeriod)
432 if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
433 return TIMERR_NOCANDO;
435 if (wPeriod > MMSYSTIME_MININTERVAL)
437 FIXME("Stub; we set our timer resolution at minimum\n");
443 /**************************************************************************
444 * timeEndPeriod [WINMM.@]
446 MMRESULT WINAPI timeEndPeriod(UINT wPeriod)
448 if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
449 return TIMERR_NOCANDO;
451 if (wPeriod > MMSYSTIME_MININTERVAL)
453 FIXME("Stub; we set our timer resolution at minimum\n");
458 /**************************************************************************
459 * timeGetTime [MMSYSTEM.607]
460 * timeGetTime [WINMM.@]
462 DWORD WINAPI timeGetTime(void)
464 #if defined(COMMENTOUTPRIORTODELETING)
467 /* FIXME: releasing the win16 lock here is a temporary hack (I hope)
468 * that lets mciavi.drv run correctly
470 if (pFnReleaseThunkLock) pFnReleaseThunkLock(&count);
471 if (pFnRestoreThunkLock) pFnRestoreThunkLock(count);
474 return GetTickCount();