VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/win/timer-win.cpp@ 6267

Last change on this file since 6267 was 5999, checked in by vboxsync, 17 years ago

The Giant CDDL Dual-License Header Change.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 15.0 KB
Line 
1/* $Id: timer-win.cpp 5999 2007-12-07 15:05:06Z vboxsync $ */
2/** @file
3 * innotek Portable Runtime - Timer.
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek 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 (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/* Which code to use is determined here...
29 *
30 * The default is to use wait on NT timers directly with no APC since this
31 * is supposed to give the shortest kernel code paths.
32 *
33 * The USE_APC variation will do as above except that an APC routine is
34 * handling the callback action.
35 *
36 * The USE_WINMM version will use the NT timer wrappers in WinMM which may
37 * result in some 0.1% better correctness in number of delivered ticks. However,
38 * this codepath have more overhead (it uses APC among other things), and I'm not
39 * quite sure if it's actually any more correct.
40 *
41 * The USE_CATCH_UP will play catch up when the timer lags behind. However this
42 * requires a monotonous time source.
43 *
44 * The default mode which we are using is using relative periods of time and thus
45 * will never suffer from errors in the time source. Neither will it try catch up
46 * missed ticks. This suits our current purposes best I'd say.
47 */
48#undef USE_APC
49#undef USE_WINMM
50#undef USE_CATCH_UP
51
52
53/*******************************************************************************
54* Header Files *
55*******************************************************************************/
56#define LOG_GROUP RTLOGGROUP_TIMER
57#define _WIN32_WINNT 0x0500
58#include <Windows.h>
59
60#include <iprt/timer.h>
61#ifdef USE_CATCH_UP
62# include <iprt/time.h>
63#endif
64#include <iprt/alloc.h>
65#include <iprt/assert.h>
66#include <iprt/thread.h>
67#include <iprt/log.h>
68#include <iprt/asm.h>
69#include <iprt/semaphore.h>
70#include <iprt/err.h>
71#include "internal/magics.h"
72
73__BEGIN_DECLS
74/* from sysinternals. */
75NTSYSAPI LONG NTAPI NtSetTimerResolution(IN ULONG DesiredResolution, IN BOOLEAN SetResolution, OUT PULONG CurrentResolution);
76NTSYSAPI LONG NTAPI NtQueryTimerResolution(OUT PULONG MinimumResolution, OUT PULONG MaximumResolution, OUT PULONG CurrentResolution);
77__END_DECLS
78
79
80/*******************************************************************************
81* Structures and Typedefs *
82*******************************************************************************/
83/**
84 * The internal representation of a timer handle.
85 */
86typedef struct RTTIMER
87{
88 /** Magic.
89 * This is RTTIMER_MAGIC, but changes to something else before the timer
90 * is destroyed to indicate clearly that thread should exit. */
91 volatile uint32_t u32Magic;
92 /** User argument. */
93 void *pvUser;
94 /** Callback. */
95 PFNRTTIMER pfnTimer;
96 /** The interval. */
97 unsigned uMilliesInterval;
98#ifdef USE_WINMM
99 /** Win32 timer id. */
100 UINT TimerId;
101#else
102 /** Time handle. */
103 HANDLE hTimer;
104#ifdef USE_APC
105 /** Handle to wait on. */
106 HANDLE hevWait;
107#endif
108 /** USE_CATCH_UP: ns time of the next tick.
109 * !USE_CATCH_UP: -uMilliesInterval * 10000 */
110 LARGE_INTEGER llNext;
111 /** The thread handle of the timer thread. */
112 RTTHREAD Thread;
113 /** The error/status of the timer.
114 * Initially -1, set to 0 when the timer have been successfully started, and
115 * to errno on failure in starting the timer. */
116 volatile int iError;
117#endif
118} RTTIMER;
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.

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