Keep on moving 16 bit code out of winmm.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <time.h>
27 #ifdef HAVE_SYS_TIME_H
28 # include <sys/time.h>
29 #endif
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33
34 #include "mmsystem.h"
35 #include "windef.h"
36 #include "winbase.h"
37
38 #include "winemm.h"
39
40 #include "wine/debug.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(mmtime);
43
44 /*
45  * FIXME
46  * We're using "1" as the mininum resolution to the timer,
47  * as Windows 95 does, according to the docs. Maybe it should
48  * depend on the computers resources!
49  */
50 #define MMSYSTIME_MININTERVAL (1)
51 #define MMSYSTIME_MAXINTERVAL (65535)
52
53 #define MMSYSTIME_STDINTERVAL (10) /* reasonable value? */
54
55 /* ### start build ### */
56 extern WORD CALLBACK TIME_CallTo16_word_wwlll(FARPROC16,WORD,WORD,LONG,LONG,LONG);
57 /* ### stop build ### */
58
59 static  void    TIME_TriggerCallBack(LPWINE_TIMERENTRY lpTimer)
60 {
61     TRACE("before CallBack => lpFunc=%p wTimerID=%04X dwUser=%08lX !\n",
62           lpTimer->lpFunc, lpTimer->wTimerID, lpTimer->dwUser);
63
64     /* - TimeProc callback that is called here is something strange, under Windows 3.1x it is called
65      *          during interrupt time,  is allowed to execute very limited number of API calls (like
66      *          PostMessage), and must reside in DLL (therefore uses stack of active application). So I
67      *       guess current implementation via SetTimer has to be improved upon.
68      */
69     switch (lpTimer->wFlags & 0x30) {
70     case TIME_CALLBACK_FUNCTION:
71         if (lpTimer->wFlags & WINE_TIMER_IS32)
72             ((LPTIMECALLBACK)lpTimer->lpFunc)(lpTimer->wTimerID, 0, lpTimer->dwUser, 0, 0);
73         else
74             TIME_CallTo16_word_wwlll(lpTimer->lpFunc, lpTimer->wTimerID, 0,
75                                      lpTimer->dwUser, 0, 0);
76         break;
77     case TIME_CALLBACK_EVENT_SET:
78         SetEvent((HANDLE)lpTimer->lpFunc);
79         break;
80     case TIME_CALLBACK_EVENT_PULSE:
81         PulseEvent((HANDLE)lpTimer->lpFunc);
82         break;
83     default:
84         FIXME("Unknown callback type 0x%04x for mmtime callback (%p), ignored.\n",
85               lpTimer->wFlags, lpTimer->lpFunc);
86         break;
87     }
88     TRACE("after CallBack !\n");
89 }
90
91 /**************************************************************************
92  *           TIME_MMSysTimeCallback
93  */
94 static void CALLBACK TIME_MMSysTimeCallback(LPWINE_MM_IDATA iData)
95 {
96     LPWINE_TIMERENTRY   lpTimer, lpNextTimer;
97     DWORD               delta = GetTickCount() - iData->mmSysTimeMS;
98     int                 idx;
99
100     TRACE("Time delta: %ld\n", delta);
101
102     while (delta >= MMSYSTIME_MININTERVAL) {
103         delta -= MMSYSTIME_MININTERVAL;
104         iData->mmSysTimeMS += MMSYSTIME_MININTERVAL;
105
106         /* since timeSetEvent() and timeKillEvent() can be called
107          * from 16 bit code, there are cases where win16 lock is
108          * locked upon entering timeSetEvent(), and then the mm timer
109          * critical section is locked. This function cannot call the
110          * timer callback with the crit sect locked (because callback
111          * may need to acquire Win16 lock, thus providing a deadlock
112          * situation).
113          * To cope with that, we just copy the WINE_TIMERENTRY struct
114          * that need to trigger the callback, and call it without the
115          * mm timer crit sect locked. The bad side of this
116          * implementation is that, in some cases, the callback may be
117          * invoked *after* a timer has been destroyed...
118          * EPP 99/07/13
119          */
120         idx = 0;
121
122         EnterCriticalSection(&iData->cs);
123         for (lpTimer = iData->lpTimerList; lpTimer != NULL; ) {
124             lpNextTimer = lpTimer->lpNext;
125             if (lpTimer->uCurTime < MMSYSTIME_MININTERVAL) {
126                 /* since lpTimer->wDelay is >= MININTERVAL, wCurTime value
127                  * shall be correct (>= 0)
128                  */
129                 lpTimer->uCurTime += lpTimer->wDelay - MMSYSTIME_MININTERVAL;
130                 if (lpTimer->lpFunc) {
131                     if (idx == iData->nSizeLpTimers) {
132                         iData->lpTimers = (LPWINE_TIMERENTRY)
133                             HeapReAlloc(GetProcessHeap(), 0,
134                                         iData->lpTimers,
135                                         ++iData->nSizeLpTimers * sizeof(WINE_TIMERENTRY));
136                     }
137                     iData->lpTimers[idx++] = *lpTimer;
138                 }
139                 /* TIME_ONESHOT is defined as 0 */
140                 if (!(lpTimer->wFlags & TIME_PERIODIC))
141                     timeKillEvent(lpTimer->wTimerID);
142             } else {
143                 lpTimer->uCurTime -= MMSYSTIME_MININTERVAL;
144             }
145             lpTimer = lpNextTimer;
146         }
147         LeaveCriticalSection(&iData->cs);
148
149         while (idx > 0) {
150             TIME_TriggerCallBack(&iData->lpTimers[--idx]);
151         }
152     }
153 }
154
155 /**************************************************************************
156  *           TIME_MMSysTimeThread
157  */
158 static DWORD CALLBACK TIME_MMSysTimeThread(LPVOID arg)
159 {
160     LPWINE_MM_IDATA iData = (LPWINE_MM_IDATA)arg;
161     volatile HANDLE *pActive = (volatile HANDLE *)&iData->hMMTimer;
162     DWORD last_time, cur_time;
163
164     usleep(MMSYSTIME_STDINTERVAL * 1000);
165     last_time = GetTickCount();
166     while (*pActive) {
167         TIME_MMSysTimeCallback(iData);
168         cur_time = GetTickCount();
169         while (last_time < cur_time)
170             last_time += MMSYSTIME_STDINTERVAL;
171         usleep((last_time - cur_time) * 1000);
172     }
173     return 0;
174 }
175
176 /**************************************************************************
177  *                              TIME_MMTimeStart
178  */
179 LPWINE_MM_IDATA TIME_MMTimeStart(void)
180 {
181     LPWINE_MM_IDATA     iData = MULTIMEDIA_GetIData();
182
183     if (IsBadWritePtr(iData, sizeof(WINE_MM_IDATA))) {
184         ERR("iData is not correctly set, please report. Expect failure.\n");
185         return 0;
186     }
187     /* one could think it's possible to stop the service thread activity when no more
188      * mm timers are active, but this would require to keep mmSysTimeMS up-to-date
189      * without being incremented within the service thread callback.
190      */
191     if (!iData->hMMTimer) {
192         iData->mmSysTimeMS = GetTickCount();
193         iData->lpTimerList = NULL;
194         iData->hMMTimer = CreateThread(NULL, 0, TIME_MMSysTimeThread, iData, 0, NULL);
195     }
196
197     return iData;
198 }
199
200 /**************************************************************************
201  *                              TIME_MMTimeStop
202  */
203 void    TIME_MMTimeStop(void)
204 {
205     LPWINE_MM_IDATA     iData = MULTIMEDIA_GetIData();
206
207     if (IsBadWritePtr(iData, sizeof(WINE_MM_IDATA))) {
208         ERR("iData is not correctly set, please report. Expect failure.\n");
209         return;
210     }
211     if (iData->hMMTimer) {
212         HANDLE hMMTimer = iData->hMMTimer;
213         iData->hMMTimer = 0;
214         WaitForSingleObject(hMMTimer, INFINITE);
215         CloseHandle(hMMTimer);
216     }
217 }
218
219 /**************************************************************************
220  *                              timeGetSystemTime       [WINMM.@]
221  */
222 MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
223 {
224     TRACE("(%p, %u);\n", lpTime, wSize);
225
226     if (wSize >= sizeof(*lpTime)) {
227         lpTime->wType = TIME_MS;
228         lpTime->u.ms = TIME_MMTimeStart()->mmSysTimeMS;
229
230         TRACE("=> %lu\n", lpTime->u.ms);
231     }
232
233     return 0;
234 }
235
236 /**************************************************************************
237  *                              timeSetEventInternal    [internal]
238  */
239 WORD    timeSetEventInternal(UINT wDelay, UINT wResol,
240                              FARPROC16 lpFunc, DWORD dwUser, UINT wFlags)
241 {
242     WORD                wNewID = 0;
243     LPWINE_TIMERENTRY   lpNewTimer;
244     LPWINE_TIMERENTRY   lpTimer;
245     LPWINE_MM_IDATA     iData;
246
247     TRACE("(%u, %u, %p, %08lX, %04X);\n", wDelay, wResol, lpFunc, dwUser, wFlags);
248
249     lpNewTimer = (LPWINE_TIMERENTRY)HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
250     if (lpNewTimer == NULL)
251         return 0;
252
253     if (wDelay < MMSYSTIME_MININTERVAL || wDelay > MMSYSTIME_MAXINTERVAL)
254         return 0;
255
256     iData = TIME_MMTimeStart();
257
258     lpNewTimer->uCurTime = wDelay;
259     lpNewTimer->wDelay = wDelay;
260     lpNewTimer->wResol = wResol;
261     lpNewTimer->lpFunc = lpFunc;
262     lpNewTimer->dwUser = dwUser;
263     lpNewTimer->wFlags = wFlags;
264
265     EnterCriticalSection(&iData->cs);
266
267     for (lpTimer = iData->lpTimerList; lpTimer != NULL; lpTimer = lpTimer->lpNext) {
268         wNewID = max(wNewID, lpTimer->wTimerID);
269     }
270
271     lpNewTimer->lpNext = iData->lpTimerList;
272     iData->lpTimerList = lpNewTimer;
273     lpNewTimer->wTimerID = wNewID + 1;
274
275     LeaveCriticalSection(&iData->cs);
276
277     TRACE("=> %u\n", wNewID + 1);
278
279     return wNewID + 1;
280 }
281
282 /**************************************************************************
283  *                              timeSetEvent            [WINMM.@]
284  */
285 MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
286                              DWORD dwUser, UINT wFlags)
287 {
288     if (wFlags & WINE_TIMER_IS32)
289         WARN("Unknown windows flag... wine internally used.. ooch\n");
290
291     return timeSetEventInternal(wDelay, wResol, (FARPROC16)lpFunc,
292                                 dwUser, wFlags|WINE_TIMER_IS32);
293 }
294
295 /**************************************************************************
296  *                              timeKillEvent           [WINMM.@]
297  */
298 MMRESULT WINAPI timeKillEvent(UINT wID)
299 {
300     LPWINE_TIMERENTRY*  lpTimer;
301     LPWINE_MM_IDATA     iData = MULTIMEDIA_GetIData();
302     MMRESULT            ret = MMSYSERR_INVALPARAM;
303
304     TRACE("(%u)\n", wID);
305     EnterCriticalSection(&iData->cs);
306     /* remove WINE_TIMERENTRY from list */
307     for (lpTimer = &iData->lpTimerList; *lpTimer; lpTimer = &(*lpTimer)->lpNext) {
308         if (wID == (*lpTimer)->wTimerID) {
309             break;
310         }
311     }
312     LeaveCriticalSection(&iData->cs);
313
314     if (*lpTimer) {
315         LPWINE_TIMERENTRY       lpTemp = *lpTimer;
316
317         /* unlink timer of id 'wID' */
318         *lpTimer = (*lpTimer)->lpNext;
319         HeapFree(GetProcessHeap(), 0, lpTemp);
320         ret = TIMERR_NOERROR;
321     } else {
322         WARN("wID=%u is not a valid timer ID\n", wID);
323     }
324
325     return ret;
326 }
327
328 /**************************************************************************
329  *                              timeGetDevCaps          [WINMM.@]
330  */
331 MMRESULT WINAPI timeGetDevCaps(LPTIMECAPS lpCaps, UINT wSize)
332 {
333     TRACE("(%p, %u) !\n", lpCaps, wSize);
334
335     lpCaps->wPeriodMin = MMSYSTIME_MININTERVAL;
336     lpCaps->wPeriodMax = MMSYSTIME_MAXINTERVAL;
337     return 0;
338 }
339
340 /**************************************************************************
341  *                              timeBeginPeriod         [WINMM.@]
342  */
343 MMRESULT WINAPI timeBeginPeriod(UINT wPeriod)
344 {
345     TRACE("(%u) !\n", wPeriod);
346
347     if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
348         return TIMERR_NOCANDO;
349     return 0;
350 }
351
352 /**************************************************************************
353  *                              timeEndPeriod           [WINMM.@]
354  */
355 MMRESULT WINAPI timeEndPeriod(UINT wPeriod)
356 {
357     TRACE("(%u) !\n", wPeriod);
358
359     if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
360         return TIMERR_NOCANDO;
361     return 0;
362 }
363
364 /**************************************************************************
365  *                              timeGetTime    [MMSYSTEM.607]
366  *                              timeGetTime    [WINMM.@]
367  */
368 DWORD WINAPI timeGetTime(void)
369 {
370     /* FIXME: releasing the win16 lock here is a temporary hack (I hope)
371      * that lets mciavi.drv run correctly
372      */
373     DWORD count;
374     ReleaseThunkLock(&count);
375     RestoreThunkLock(count);
376     return TIME_MMTimeStart()->mmSysTimeMS;
377 }