VirtualBox

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

Last change on this file since 8188 was 8170, checked in by vboxsync, 17 years ago

Rebranding: replacing more innotek strings.

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