time.c 13.5 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2
/* -*- tab-width: 8; c-basic-offset: 4 -*- */

Alexandre Julliard's avatar
Alexandre Julliard committed
3
/*
Andreas Mohr's avatar
Andreas Mohr committed
4
 * MMSYSTEM time functions
Alexandre Julliard's avatar
Alexandre Julliard committed
5 6
 *
 * Copyright 1993 Martin Ayotte
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
Alexandre Julliard's avatar
Alexandre Julliard committed
21 22
 */

23 24 25
#include "config.h"
#include "wine/port.h"

26
#include <stdarg.h>
27
#include <errno.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
28
#include <time.h>
29 30 31 32 33 34
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
35 36 37 38 39 40
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#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"
Alexandre Julliard's avatar
Alexandre Julliard committed
50

51
WINE_DEFAULT_DEBUG_CHANNEL(mmtime);
52

53
typedef struct tagWINE_TIMERENTRY {
54
    struct list                 entry;
55 56 57 58 59 60 61 62 63
    UINT                        wDelay;
    UINT                        wResol;
    LPTIMECALLBACK              lpFunc; /* can be lots of things */
    DWORD                       dwUser;
    UINT16                      wFlags;
    UINT16                      wTimerID;
    DWORD                       dwTriggerTime;
} WINE_TIMERENTRY, *LPWINE_TIMERENTRY;

64
static struct list timer_list = LIST_INIT(timer_list);
65

66 67 68 69 70 71 72 73 74
static CRITICAL_SECTION TIME_cbcrst;
static CRITICAL_SECTION_DEBUG critsect_debug =
{
    0, 0, &TIME_cbcrst,
    { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": TIME_cbcrst") }
};
static CRITICAL_SECTION TIME_cbcrst = { &critsect_debug, -1, 0, 0, 0, 0 };

75
static    HANDLE                TIME_hMMTimer;
76
static    BOOL                  TIME_TimeToDie = TRUE;
77
static    int                   TIME_fdWake[2] = { -1, -1 };
78

79 80 81 82 83 84 85 86 87 88 89
/* link timer at the appropriate spot in the list */
static inline void link_timer( WINE_TIMERENTRY *timer )
{
    WINE_TIMERENTRY *next;

    LIST_FOR_EACH_ENTRY( next, &timer_list, WINE_TIMERENTRY, entry )
        if ((int)(next->dwTriggerTime - timer->dwTriggerTime) >= 0) break;

    list_add_before( &next->entry, &timer->entry );
}

Alexandre Julliard's avatar
Alexandre Julliard committed
90
/*
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
 * Some observations on the behavior of winmm on Windows.
 * First, the call to timeBeginPeriod(xx) can never be used
 * to raise the timer resolution, only lower it.
 *
 * Second, a brief survey of a variety of Win 2k and Win X
 * machines showed that a 'standard' (aka default) timer
 * resolution was 1 ms (Win9x is documented as being 1).  However, one 
 * machine had a standard timer resolution of 10 ms.
 *
 * Further, if we set our default resolution to 1,
 * the implementation of timeGetTime becomes GetTickCount(),
 * and we can optimize the code to reduce overhead.
 *
 * Additionally, a survey of Event behaviors shows that
 * if we request a Periodic event every 50 ms, then Windows
 * makes sure to trigger that event 20 times in the next
 * second.  If delays prevent that from happening on exact
 * schedule, Windows will trigger the events as close
 * to the original schedule as is possible, and will eventually
 * bring the event triggers back onto a schedule that is
 * consistent with what would have happened if there were
 * no delays.
 *
 *   Jeremy White, October 2004
Alexandre Julliard's avatar
Alexandre Julliard committed
115
 */
116
#define MMSYSTIME_MININTERVAL (1)
Alexandre Julliard's avatar
Alexandre Julliard committed
117 118
#define MMSYSTIME_MAXINTERVAL (65535)

119

Alexandre Julliard's avatar
Alexandre Julliard committed
120
/**************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
121
 *           TIME_MMSysTimeCallback
Alexandre Julliard's avatar
Alexandre Julliard committed
122
 */
123
static int TIME_MMSysTimeCallback(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
124
{
125 126
    WINE_TIMERENTRY *timer, *to_free;
    int delta_time;
127 128 129 130 131 132 133 134 135 136 137 138 139

    /* since timeSetEvent() and timeKillEvent() can be called
     * from 16 bit code, there are cases where win16 lock is
     * locked upon entering timeSetEvent(), and then the mm timer
     * critical section is locked. This function cannot call the
     * timer callback with the crit sect locked (because callback
     * may need to acquire Win16 lock, thus providing a deadlock
     * situation).
     * To cope with that, we just copy the WINE_TIMERENTRY struct
     * that need to trigger the callback, and call it without the
     * mm timer crit sect locked.
     */

140
    EnterCriticalSection(&WINMM_cs);
141
    for (;;)
142
    {
143 144
        struct list *ptr = list_head( &timer_list );
        if (!ptr)
145
        {
146 147 148
            delta_time = -1;
            break;
        }
149

150 151 152
        timer = LIST_ENTRY( ptr, WINE_TIMERENTRY, entry );
        delta_time = timer->dwTriggerTime - GetTickCount();
        if (delta_time > 0) break;
153

154 155 156
        list_remove( &timer->entry );
        if (timer->wFlags & TIME_PERIODIC)
        {
157
            timer->dwTriggerTime += timer->wDelay;
158 159 160 161
            link_timer( timer );  /* restart it */
            to_free = NULL;
        }
        else to_free = timer;
162

163 164 165 166 167 168 169 170 171
        switch(timer->wFlags & (TIME_CALLBACK_EVENT_SET|TIME_CALLBACK_EVENT_PULSE))
        {
        case TIME_CALLBACK_EVENT_SET:
            SetEvent((HANDLE)timer->lpFunc);
            break;
        case TIME_CALLBACK_EVENT_PULSE:
            PulseEvent((HANDLE)timer->lpFunc);
            break;
        case TIME_CALLBACK_FUNCTION:
172
            {
173 174 175 176
                DWORD user = timer->dwUser;
                UINT16 id = timer->wTimerID;
                UINT16 flags = timer->wFlags;
                LPTIMECALLBACK func = timer->lpFunc;
177

178 179
                if (flags & TIME_KILL_SYNCHRONOUS) EnterCriticalSection(&TIME_cbcrst);
                LeaveCriticalSection(&WINMM_cs);
180

181 182 183 184 185 186 187
                if (flags & WINE_TIMER_IS32) func(id, 0, user, 0, 0);
                else if (pFnCallMMDrvFunc16) pFnCallMMDrvFunc16((DWORD)func, id, 0, user, 0, 0);

                EnterCriticalSection(&WINMM_cs);
                if (flags & TIME_KILL_SYNCHRONOUS) LeaveCriticalSection(&TIME_cbcrst);
            }
            break;
188
        }
189
        HeapFree( GetProcessHeap(), 0, to_free );
190
    }
191
    LeaveCriticalSection(&WINMM_cs);
192
    return delta_time;
Alexandre Julliard's avatar
Alexandre Julliard committed
193 194
}

Eric Pouech's avatar
Eric Pouech committed
195
/**************************************************************************
196 197 198 199
 *           TIME_MMSysTimeThread
 */
static DWORD CALLBACK TIME_MMSysTimeThread(LPVOID arg)
{
200 201 202 203 204 205
    int sleep_time, ret;
    char readme[16];
    struct pollfd pfd;

    pfd.fd = TIME_fdWake[0];
    pfd.events = POLLIN;
206 207 208 209 210 211 212 213 214 215 216

    TRACE("Starting main winmm thread\n");

    /* FIXME:  As an optimization, we could have
               this thread die when there are no more requests
               pending, and then get recreated on the first
               new event; it's not clear if that would be worth
               it or not.                 */

    while (! TIME_TimeToDie) 
    {
217
        sleep_time = TIME_MMSysTimeCallback();
218 219 220 221

        if (sleep_time == 0)
            continue;

222 223 224 225 226 227 228 229 230 231
        if ((ret = poll(&pfd, 1, sleep_time)) < 0)
        {
            if (errno != EINTR && errno != EAGAIN)
            {
                ERR("Unexpected error in poll: %s(%d)\n", strerror(errno), errno);
                break;
            }
         }

        while (ret > 0) ret = read(TIME_fdWake[0], readme, sizeof(readme));
232
    }
233
    TRACE("Exiting main winmm thread\n");
234 235 236 237 238
    return 0;
}

/**************************************************************************
 * 				TIME_MMTimeStart
Eric Pouech's avatar
Eric Pouech committed
239
 */
240
static void TIME_MMTimeStart(void)
Eric Pouech's avatar
Eric Pouech committed
241
{
242
    if (!TIME_hMMTimer) {
243 244 245 246 247 248 249 250
        if (pipe(TIME_fdWake) < 0)
        {
            TIME_fdWake[0] = TIME_fdWake[1] = -1;
            ERR("Cannot create pipe: %s\n", strerror(errno));
        } else {
            fcntl(TIME_fdWake[0], F_SETFL, O_NONBLOCK);
            fcntl(TIME_fdWake[1], F_SETFL, O_NONBLOCK);
        }
251
        TIME_TimeToDie = FALSE;
252
        TIME_hMMTimer = CreateThread(NULL, 0, TIME_MMSysTimeThread, NULL, 0, NULL);
253
        SetThreadPriority(TIME_hMMTimer, THREAD_PRIORITY_TIME_CRITICAL);
Eric Pouech's avatar
Eric Pouech committed
254 255 256
    }
}

257 258 259 260 261
/**************************************************************************
 * 				TIME_MMTimeStop
 */
void	TIME_MMTimeStop(void)
{
262
    if (TIME_hMMTimer) {
263
        const char a='a';
264 265

        TIME_TimeToDie = TRUE;
266 267 268 269 270 271 272 273
        write(TIME_fdWake[1], &a, sizeof(a));

        WaitForSingleObject(TIME_hMMTimer, INFINITE);
        close(TIME_fdWake[0]);
        close(TIME_fdWake[1]);
        TIME_fdWake[0] = TIME_fdWake[1] = -1;
        CloseHandle(TIME_hMMTimer);
        TIME_hMMTimer = 0;
274
        DeleteCriticalSection(&TIME_cbcrst);
275 276 277
    }
}

Alexandre Julliard's avatar
Alexandre Julliard committed
278
/**************************************************************************
279
 * 				timeGetSystemTime	[WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
280
 */
281
MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
282
{
283

Eric Pouech's avatar
Eric Pouech committed
284 285
    if (wSize >= sizeof(*lpTime)) {
	lpTime->wType = TIME_MS;
286
	lpTime->u.ms = GetTickCount();
287

Eric Pouech's avatar
Eric Pouech committed
288
    }
289

Alexandre Julliard's avatar
Alexandre Julliard committed
290 291 292
    return 0;
}

293
/**************************************************************************
294
 * 				TIME_SetEventInternal	[internal]
295
 */
296
WORD	TIME_SetEventInternal(UINT wDelay, UINT wResol,
297
                              LPTIMECALLBACK lpFunc, DWORD dwUser, UINT wFlags)
Alexandre Julliard's avatar
Alexandre Julliard committed
298
{
Alexandre Julliard's avatar
Alexandre Julliard committed
299
    WORD 		wNewID = 0;
300 301
    LPWINE_TIMERENTRY	lpNewTimer;
    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)
Alexandre Julliard's avatar
Alexandre Julliard committed
307
	return 0;
Eric Pouech's avatar
Eric Pouech committed
308

309 310
    lpNewTimer = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
    if (lpNewTimer == NULL)
311 312
	return 0;

Alexandre Julliard's avatar
Alexandre Julliard committed
313
    lpNewTimer->wDelay = wDelay;
314 315 316 317
    lpNewTimer->dwTriggerTime = GetTickCount() + wDelay;

    /* FIXME - wResol is not respected, although it is not clear
               that we could change our precision meaningfully  */
Alexandre Julliard's avatar
Alexandre Julliard committed
318
    lpNewTimer->wResol = wResol;
Alexandre Julliard's avatar
Alexandre Julliard committed
319
    lpNewTimer->lpFunc = lpFunc;
Alexandre Julliard's avatar
Alexandre Julliard committed
320 321
    lpNewTimer->dwUser = dwUser;
    lpNewTimer->wFlags = wFlags;
Eric Pouech's avatar
Eric Pouech committed
322

323
    EnterCriticalSection(&WINMM_cs);
Eric Pouech's avatar
Eric Pouech committed
324

325 326
    LIST_FOR_EACH_ENTRY( lpTimer, &timer_list, WINE_TIMERENTRY, entry )
        wNewID = max(wNewID, lpTimer->wTimerID);
327

328
    link_timer( lpNewTimer );
Eric Pouech's avatar
Eric Pouech committed
329 330
    lpNewTimer->wTimerID = wNewID + 1;

331 332
    TIME_MMTimeStart();

333
    LeaveCriticalSection(&WINMM_cs);
Eric Pouech's avatar
Eric Pouech committed
334

335
    /* Wake the service thread in case there is work to be done */
336
    write(TIME_fdWake[1], &c, sizeof(c));
337

338 339
    TRACE("=> %u\n", wNewID + 1);

Eric Pouech's avatar
Eric Pouech committed
340
    return wNewID + 1;
Alexandre Julliard's avatar
Alexandre Julliard committed
341 342
}

Alexandre Julliard's avatar
Alexandre Julliard committed
343
/**************************************************************************
Patrik Stridvall's avatar
Patrik Stridvall committed
344
 * 				timeSetEvent		[WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
345
 */
Eric Pouech's avatar
Eric Pouech committed
346
MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
347
                            DWORD_PTR dwUser, UINT wFlags)
Alexandre Julliard's avatar
Alexandre Julliard committed
348
{
349 350 351
    if (wFlags & WINE_TIMER_IS32)
	WARN("Unknown windows flag... wine internally used.. ooch\n");

352
    return TIME_SetEventInternal(wDelay, wResol, lpFunc,
353
                                 dwUser, wFlags|WINE_TIMER_IS32);
Alexandre Julliard's avatar
Alexandre Julliard committed
354 355
}

Alexandre Julliard's avatar
Alexandre Julliard committed
356
/**************************************************************************
357
 * 				timeKillEvent		[WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
358
 */
359
MMRESULT WINAPI timeKillEvent(UINT wID)
Alexandre Julliard's avatar
Alexandre Julliard committed
360
{
361
    WINE_TIMERENTRY *lpSelf = NULL, *lpTimer;
362
    DWORD wFlags;
Eric Pouech's avatar
Eric Pouech committed
363

364
    TRACE("(%u)\n", wID);
365
    EnterCriticalSection(&WINMM_cs);
366
    /* remove WINE_TIMERENTRY from list */
367 368 369 370 371
    LIST_FOR_EACH_ENTRY( lpTimer, &timer_list, WINE_TIMERENTRY, entry )
    {
	if (wID == lpTimer->wTimerID) {
            lpSelf = lpTimer;
            list_remove( &lpTimer->entry );
Eric Pouech's avatar
Eric Pouech committed
372
	    break;
Alexandre Julliard's avatar
Alexandre Julliard committed
373 374
	}
    }
375
    LeaveCriticalSection(&WINMM_cs);
376

377 378 379 380
    if (!lpSelf)
    {
        WARN("wID=%u is not a valid timer ID\n", wID);
        return MMSYSERR_INVALPARAM;
381
    }
382 383
    wFlags = lpSelf->wFlags;
    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;
Alexandre Julliard's avatar
Alexandre Julliard committed
389 390
}

Alexandre Julliard's avatar
Alexandre Julliard committed
391
/**************************************************************************
392
 * 				timeGetDevCaps		[WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
393
 */
394
MMRESULT WINAPI timeGetDevCaps(LPTIMECAPS lpCaps, UINT wSize)
Alexandre Julliard's avatar
Alexandre Julliard committed
395
{
396
    TRACE("(%p, %u)\n", lpCaps, wSize);
397

398 399 400 401 402 403 404 405 406 407
    if (lpCaps == 0) {
        WARN("invalid lpCaps\n");
        return TIMERR_NOCANDO;
    }

    if (wSize < sizeof(TIMECAPS)) {
        WARN("invalid wSize\n");
        return TIMERR_NOCANDO;
    }

Alexandre Julliard's avatar
Alexandre Julliard committed
408 409
    lpCaps->wPeriodMin = MMSYSTIME_MININTERVAL;
    lpCaps->wPeriodMax = MMSYSTIME_MAXINTERVAL;
410
    return TIMERR_NOERROR;
Alexandre Julliard's avatar
Alexandre Julliard committed
411 412 413
}

/**************************************************************************
414
 * 				timeBeginPeriod		[WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
415
 */
416
MMRESULT WINAPI timeBeginPeriod(UINT wPeriod)
Alexandre Julliard's avatar
Alexandre Julliard committed
417
{
418
    if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
Alexandre Julliard's avatar
Alexandre Julliard committed
419
	return TIMERR_NOCANDO;
420 421 422

    if (wPeriod > MMSYSTIME_MININTERVAL)
    {
Robert Reif's avatar
Robert Reif committed
423
        WARN("Stub; we set our timer resolution at minimum\n");
424 425
    }

Alexandre Julliard's avatar
Alexandre Julliard committed
426 427
    return 0;
}
Eric Pouech's avatar
Eric Pouech committed
428

Alexandre Julliard's avatar
Alexandre Julliard committed
429
/**************************************************************************
430
 * 				timeEndPeriod		[WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
431
 */
432
MMRESULT WINAPI timeEndPeriod(UINT wPeriod)
Alexandre Julliard's avatar
Alexandre Julliard committed
433
{
434
    if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
Alexandre Julliard's avatar
Alexandre Julliard committed
435
	return TIMERR_NOCANDO;
436 437 438

    if (wPeriod > MMSYSTIME_MININTERVAL)
    {
Robert Reif's avatar
Robert Reif committed
439
        WARN("Stub; we set our timer resolution at minimum\n");
440
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
441 442 443
    return 0;
}

Alexandre Julliard's avatar
Alexandre Julliard committed
444
/**************************************************************************
445 446
 * 				timeGetTime    [MMSYSTEM.607]
 * 				timeGetTime    [WINMM.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
447
 */
448
DWORD WINAPI timeGetTime(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
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 457
    if (pFnReleaseThunkLock) pFnReleaseThunkLock(&count);
    if (pFnRestoreThunkLock) pFnRestoreThunkLock(count);
458 459 460
#endif

    return GetTickCount();
Alexandre Julliard's avatar
Alexandre Julliard committed
461
}