VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/win32/timer-win32.cpp@ 729

Last change on this file since 729 was 197, checked in by vboxsync, 18 years ago

A stab at generic timers (untested).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 14.8 KB
Line 
1/* $Id: timer-win32.cpp 197 2007-01-20 01:22:45Z vboxsync $ */
2/** @file
3 * InnoTek Portable Runtime - Timer.
4 */
5
6/*
7 * Copyright (C) 2006 InnoTek Systemberatung GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22
23/* Which code to use is determined here...
24 *
25 * The default is to use wait on NT timers directly with no APC since this
26 * is supposed to give the shortest kernel code paths.
27 *
28 * The USE_APC variation will do as above except that an APC routine is
29 * handling the callback action.
30 *
31 * The USE_WINMM version will use the NT timer wrappers in WinMM which may
32 * result in some 0.1% better correctness in number of delivered ticks. However,
33 * this codepath have more overhead (it uses APC among other things), and I'm not
34 * quite sure if it's actually any more correct.
35 *
36 * The USE_CATCH_UP will play catch up when the timer lags behind. However this
37 * requires a monotonous time source.
38 *
39 * The default mode which we are using is using relative periods of time and thus
40 * will never suffer from errors in the time source. Neither will it try catch up
41 * missed ticks. This suits our current purposes best I'd say.
42 */
43#undef USE_APC
44#undef USE_WINMM
45#undef USE_CATCH_UP
46
47
48/*******************************************************************************
49* Header Files *
50*******************************************************************************/
51#define LOG_GROUP RTLOGGROUP_TIMER
52#define _WIN32_WINNT 0x0500
53#include <Windows.h>
54
55#include <iprt/timer.h>
56#ifdef USE_CATCH_UP
57# include <iprt/time.h>
58#endif
59#include <iprt/alloc.h>
60#include <iprt/assert.h>
61#include <iprt/thread.h>
62#include <iprt/log.h>
63#include <iprt/asm.h>
64#include <iprt/semaphore.h>
65#include <iprt/err.h>
66
67#include <errno.h>
68
69__BEGIN_DECLS
70/* from sysinternals. */
71NTSYSAPI LONG NTAPI NtSetTimerResolution(IN ULONG DesiredResolution, IN BOOLEAN SetResolution, OUT PULONG CurrentResolution);
72NTSYSAPI LONG NTAPI NtQueryTimerResolution(OUT PULONG MinimumResolution, OUT PULONG MaximumResolution, OUT PULONG CurrentResolution);
73__END_DECLS
74
75
76/*******************************************************************************
77* Structures and Typedefs *
78*******************************************************************************/
79/**
80 * The internal representation of a timer handle.
81 */
82typedef struct RTTIMER
83{
84 /** Magic.
85 * This is RTTIMER_MAGIC, but changes to something else before the timer
86 * is destroyed to indicate clearly that thread should exit. */
87 volatile uint32_t u32Magic;
88 /** User argument. */
89 void *pvUser;
90 /** Callback. */
91 PFNRTTIMER pfnTimer;
92 /** The interval. */
93 unsigned uMilliesInterval;
94#ifdef USE_WINMM
95 /** Win32 timer id. */
96 UINT TimerId;
97#else
98 /** Time handle. */
99 HANDLE hTimer;
100#ifdef USE_APC
101 /** Handle to wait on. */
102 HANDLE hevWait;
103#endif
104 /** USE_CATCH_UP: ns time of the next tick.
105 * !USE_CATCH_UP: -uMilliesInterval * 10000 */
106 LARGE_INTEGER llNext;
107 /** The thread handle of the timer thread. */
108 RTTHREAD Thread;
109 /** The error/status of the timer.
110 * Initially -1, set to 0 when the timer have been successfully started, and
111 * to errno on failure in starting the timer. */
112 volatile int iError;
113#endif
114} RTTIMER;
115
116/** Timer handle magic. */
117#define RTTIMER_MAGIC 0x42424242
118
119
120
121
122#ifdef USE_WINMM
123/**
124 * Win32 callback wrapper.
125 */
126static void CALLBACK rttimerCallback(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
127{
128 PRTTIMER pTimer = (PRTTIMER)(void *)dwUser;
129 Assert(pTimer->TimerId == uTimerID);
130 pTimer->pfnTimer(pTimer, pTimer->pvUser);
131 NOREF(uMsg); NOREF(dw1); NOREF(dw2); NOREF(uTimerID);
132}
133#else /* !USE_WINMM */
134
135#ifdef USE_APC
136/**
137 * Async callback.
138 *
139 * @param lpArgToCompletionRoutine Pointer to our timer structure.
140 */
141VOID CALLBACK rttimerAPCProc(LPVOID lpArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
142{
143 PRTTIMER pTimer = (PRTTIMER)lpArgToCompletionRoutine;
144
145 /*
146 * Check if we're begin destroyed.
147 */
148 if (pTimer->u32Magic != RTTIMER_MAGIC)
149 return;
150
151 /*
152 * Callback the handler.
153 */
154 pTimer->pfnTimer(pTimer, pTimer->pvUser);
155
156 /*
157 * Rearm the timer handler.
158 */
159#ifdef USE_CATCH_UP
160 pTimer->llNext.QuadPart += (int64_t)pTimer->uMilliesInterval * 10000;
161 LARGE_INTEGER ll;
162 ll.QuadPart = RTTimeNanoTS() - pTimer->llNext.QuadPart;
163 if (ll.QuadPart < -500000)
164 ll.QuadPart = ll.QuadPart / 100;
165 else
166 ll.QuadPart = -500000 / 100; /* need to catch up, do a minimum wait of 0.5ms. */
167#else
168 LARGE_INTEGER ll = pTimer->llNext;
169#endif
170 BOOL frc = SetWaitableTimer(pTimer->hTimer, &ll, 0, rttimerAPCProc, pTimer, FALSE);
171 AssertMsg(frc || pTimer->u32Magic != RTTIMER_MAGIC, ("last error %d\n", GetLastError()));
172}
173#endif /* USE_APC */
174
175/**
176 * Timer thread.
177 */
178static DECLCALLBACK(int) rttimerCallback(RTTHREAD Thread, void *pvArg)
179{
180 PRTTIMER pTimer = (PRTTIMER)(void *)pvArg;
181 Assert(pTimer->u32Magic == RTTIMER_MAGIC);
182
183 /*
184 * Bounce our priority up quite a bit.
185 */
186 if ( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL)
187 /*&& !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)*/)
188 {
189 int rc = GetLastError();
190 AssertMsgFailed(("Failed to set priority class lasterror %d.\n", rc));
191 pTimer->iError = RTErrConvertFromWin32(rc);
192 return rc;
193 }
194
195 /*
196 * Start the waitable timer.
197 */
198
199#ifdef USE_CATCH_UP
200 const int64_t NSInterval = (int64_t)pTimer->uMilliesInterval * 1000000;
201 pTimer->llNext.QuadPart = RTTimeNanoTS() + NSInterval;
202#else
203 pTimer->llNext.QuadPart = -(int64_t)pTimer->uMilliesInterval * 10000;
204#endif
205 LARGE_INTEGER ll;
206 ll.QuadPart = -(int64_t)pTimer->uMilliesInterval * 10000;
207#ifdef USE_APC
208 if (!SetWaitableTimer(pTimer->hTimer, &ll, 0, rttimerAPCProc, pTimer, FALSE))
209#else
210 if (!SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE))
211#endif
212 {
213 int rc = GetLastError();
214 AssertMsgFailed(("Failed to set timer, lasterr %d.\n", rc));
215 pTimer->iError = RTErrConvertFromWin32(rc);
216 RTThreadUserSignal(Thread);
217 return rc;
218 }
219
220 /*
221 * Wait for the semaphore to be posted.
222 */
223 RTThreadUserSignal(Thread);
224 for (;pTimer->u32Magic == RTTIMER_MAGIC;)
225 {
226#ifdef USE_APC
227 int rc = WaitForSingleObjectEx(pTimer->hevWait, INFINITE, TRUE);
228 if (rc != WAIT_OBJECT_0 && rc != WAIT_IO_COMPLETION)
229#else
230 int rc = WaitForSingleObjectEx(pTimer->hTimer, INFINITE, FALSE);
231 if (pTimer->u32Magic != RTTIMER_MAGIC)
232 break;
233 if (rc == WAIT_OBJECT_0)
234 {
235 /*
236 * Callback the handler.
237 */
238 pTimer->pfnTimer(pTimer, pTimer->pvUser);
239
240 /*
241 * Rearm the timer handler.
242 */
243#ifdef USE_CATCH_UP
244 pTimer->llNext.QuadPart += NSInterval;
245 LARGE_INTEGER ll;
246 ll.QuadPart = RTTimeNanoTS() - pTimer->llNext.QuadPart;
247 if (ll.QuadPart < -500000)
248 ll.QuadPart = ll.QuadPart / 100;
249 else
250 ll.QuadPart = -500000 / 100; /* need to catch up, do a minimum wait of 0.5ms. */
251#else
252 LARGE_INTEGER ll = pTimer->llNext;
253#endif
254 BOOL frc = SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE);
255 AssertMsg(frc || pTimer->u32Magic != RTTIMER_MAGIC, ("last error %d\n", GetLastError()));
256 }
257 else
258#endif
259 {
260 /*
261 * We failed during wait, so just signal the destructor and exit.
262 */
263 int rc2 = GetLastError();
264 RTThreadUserSignal(Thread);
265 AssertMsgFailed(("Wait on hTimer failed, rc=%d lasterr=%d\n", rc, rc2));
266 return -1;
267 }
268 }
269
270 /*
271 * Exit.
272 */
273 RTThreadUserSignal(Thread);
274 return 0;
275}
276#endif /* !USE_WINMM */
277
278
279/**
280 * Create a recurring timer.
281 *
282 * @returns iprt status code.
283 * @param ppTimer Where to store the timer handle.
284 * @param uMilliesInterval Milliseconds between the timer ticks.
285 * This is rounded up to the system granularity.
286 * @param pfnTimer Callback function which shall be scheduled for execution
287 * on every timer tick.
288 * @param pvUser User argument for the callback.
289 */
290RTR3DECL(int) RTTimerCreate(PRTTIMER *ppTimer, unsigned uMilliesInterval, PFNRTTIMER pfnTimer, void *pvUser)
291{
292#ifndef USE_WINMM
293 /*
294 * On windows we'll have to set the timer resolution before
295 * we start the timer.
296 */
297 ULONG Min = ~0;
298 ULONG Max = ~0;
299 ULONG Cur = ~0;
300 NtQueryTimerResolution(&Min, &Max, &Cur);
301 Log(("NtQueryTimerResolution -> Min=%lu Max=%lu Cur=%lu (100ns)\n", Min, Max, Cur));
302 if (Cur > Max && Cur > 10000 /* = 1ms */)
303 {
304 if (NtSetTimerResolution(10000, TRUE, &Cur) >= 0)
305 Log(("Changed timer resolution to 1ms.\n"));
306 else if (NtSetTimerResolution(20000, TRUE, &Cur) >= 0)
307 Log(("Changed timer resolution to 2ms.\n"));
308 else if (NtSetTimerResolution(40000, TRUE, &Cur) >= 0)
309 Log(("Changed timer resolution to 4ms.\n"));
310 else if (Max <= 50000 && NtSetTimerResolution(Max, TRUE, &Cur) >= 0)
311 Log(("Changed timer resolution to %lu *100ns.\n", Max));
312 else
313 {
314 AssertMsgFailed(("Failed to configure timer resolution!\n"));
315 return VERR_INTERNAL_ERROR;
316 }
317 }
318#endif /* !USE_WINN */
319
320 /*
321 * Create new timer.
322 */
323 int rc;
324 PRTTIMER pTimer = (PRTTIMER)RTMemAlloc(sizeof(*pTimer));
325 if (pTimer)
326 {
327 pTimer->u32Magic = RTTIMER_MAGIC;
328 pTimer->pvUser = pvUser;
329 pTimer->pfnTimer = pfnTimer;
330 pTimer->uMilliesInterval = uMilliesInterval;
331#ifdef USE_WINMM
332 /* sync kill doesn't work. */
333 pTimer->TimerId = timeSetEvent(uMilliesInterval, 0, rttimerCallback, (DWORD_PTR)pTimer, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
334 if (pTimer->TimerId)
335 {
336 ULONG Min = ~0;
337 ULONG Max = ~0;
338 ULONG Cur = ~0;
339 NtQueryTimerResolution(&Min, &Max, &Cur);
340 Log(("NtQueryTimerResolution -> Min=%lu Max=%lu Cur=%lu (100ns)\n", Min, Max, Cur));
341
342 *ppTimer = pTimer;
343 return VINF_SUCCESS;
344 }
345 rc = VERR_INVALID_PARAMETER;
346
347#else /* !USE_WINMM */
348
349 /*
350 * Create Win32 event semaphore.
351 */
352 pTimer->iError = 0;
353 pTimer->hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
354 if (pTimer->hTimer)
355 {
356#ifdef USE_APC
357 /*
358 * Create wait semaphore.
359 */
360 pTimer->hevWait = CreateEvent(NULL, FALSE, FALSE, NULL);
361 if (pTimer->hevWait)
362#endif
363 {
364 /*
365 * Kick off the timer thread.
366 */
367 rc = RTThreadCreate(&pTimer->Thread, rttimerCallback, pTimer, 0, RTTHREADTYPE_TIMER, RTTHREADFLAGS_WAITABLE, "Timer");
368 if (RT_SUCCESS(rc))
369 {
370 /*
371 * Wait for the timer to successfully create the timer
372 * If we don't get a response in 10 secs, then we assume we're screwed.
373 */
374 rc = RTThreadUserWait(pTimer->Thread, 10000);
375 if (RT_SUCCESS(rc))
376 {
377 rc = pTimer->iError;
378 if (RT_SUCCESS(rc))
379 {
380 *ppTimer = pTimer;
381 return VINF_SUCCESS;
382 }
383 }
384 ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
385 RTThreadWait(pTimer->Thread, 250, NULL);
386 CancelWaitableTimer(pTimer->hTimer);
387 }
388#ifdef USE_APC
389 CloseHandle(pTimer->hevWait);
390#endif
391 }
392 CloseHandle(pTimer->hTimer);
393 }
394#endif /* !USE_WINMM */
395
396 AssertMsgFailed(("Failed to create timer uMilliesInterval=%d. rc=%d\n", uMilliesInterval, rc));
397 RTMemFree(pTimer);
398 }
399 else
400 rc = VERR_NO_MEMORY;
401 return rc;
402}
403
404
405
406/**
407 * Stops and destroys a running timer.
408 *
409 * @returns iprt status code.
410 * @param pTimer Timer to stop and destroy.
411 */
412RTR3DECL(int) RTTimerDestroy(PRTTIMER pTimer)
413{
414 /* NULL is ok. */
415 if (!pTimer)
416 return VINF_SUCCESS;
417
418 /*
419 * Validate handle first.
420 */
421 int rc;
422 if ( VALID_PTR(pTimer)
423 && pTimer->u32Magic == RTTIMER_MAGIC)
424 {
425#ifdef USE_WINMM
426 /*
427 * Kill the timer and exit.
428 */
429 rc = timeKillEvent(pTimer->TimerId);
430 AssertMsg(rc == TIMERR_NOERROR, ("timeKillEvent -> %d\n", rc));
431 ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
432 RTThreadSleep(1);
433
434#else /* !USE_WINMM */
435
436 /*
437 * Signal that we want the thread to exit.
438 */
439 ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
440#ifdef USE_APC
441 SetEvent(pTimer->hevWait);
442 CloseHandle(pTimer->hevWait);
443 rc = CancelWaitableTimer(pTimer->hTimer);
444 AssertMsg(rc, ("CancelWaitableTimer lasterr=%d\n", GetLastError()));
445#else
446 LARGE_INTEGER ll = {0};
447 ll.LowPart = 100;
448 rc = SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE);
449 AssertMsg(rc, ("CancelWaitableTimer lasterr=%d\n", GetLastError()));
450#endif
451
452 /*
453 * Wait for the thread to exit.
454 * And if it don't wanna exit, we'll get kill it.
455 */
456 rc = RTThreadWait(pTimer->Thread, 1000, NULL);
457 if (RT_FAILURE(rc))
458 TerminateThread((HANDLE)RTThreadGetNative(pTimer->Thread), -1);
459
460 /*
461 * Free resource.
462 */
463 rc = CloseHandle(pTimer->hTimer);
464 AssertMsg(rc, ("CloseHandle lasterr=%d\n", GetLastError()));
465
466#endif /* !USE_WINMM */
467 RTMemFree(pTimer);
468 return rc;
469 }
470
471 rc = VERR_INVALID_HANDLE;
472 AssertMsgFailed(("Failed to destroy timer %p. rc=%d\n", pTimer, rc));
473 return rc;
474}
475
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette