VirtualBox

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

Last change on this file since 85112 was 83739, checked in by vboxsync, 5 years ago

IPRT: More VC++ 14.1 build fixes. bugref:8489

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 15.0 KB
Line 
1/* $Id: timer-win.cpp 83739 2020-04-17 08:51:27Z vboxsync $ */
2/** @file
3 * IPRT - Timer.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
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 <iprt/win/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
73RT_C_DECLS_BEGIN
74/* from sysinternals. */
75NTSYSAPI LONG NTAPI NtSetTimerResolution(IN ULONG DesiredResolution, IN BOOLEAN SetResolution, OUT PULONG CurrentResolution);
76NTSYSAPI LONG NTAPI NtQueryTimerResolution(OUT PULONG MaximumResolution, OUT PULONG MinimumResolution, OUT PULONG CurrentResolution);
77RT_C_DECLS_END
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 current tick. */
97 uint64_t iTick;
98 /** The interval. */
99 unsigned uMilliesInterval;
100#ifdef USE_WINMM
101 /** Win32 timer id. */
102 UINT TimerId;
103#else
104 /** Time handle. */
105 HANDLE hTimer;
106# ifdef USE_APC
107 /** Handle to wait on. */
108 HANDLE hevWait;
109# endif
110 /** USE_CATCH_UP: ns time of the next tick.
111 * !USE_CATCH_UP: -uMilliesInterval * 10000 */
112 LARGE_INTEGER llNext;
113 /** The thread handle of the timer thread. */
114 RTTHREAD Thread;
115 /** The error/status of the timer.
116 * Initially -1, set to 0 when the timer have been successfully started, and
117 * to errno on failure in starting the timer. */
118 volatile int iError;
119#endif
120} RTTIMER;
121
122
123
124#ifdef USE_WINMM
125/**
126 * Win32 callback wrapper.
127 */
128static void CALLBACK rttimerCallback(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
129{
130 PRTTIMER pTimer = (PRTTIMER)(void *)dwUser;
131 Assert(pTimer->TimerId == uTimerID);
132 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pTimer->iTick);
133 NOREF(uMsg); NOREF(dw1); NOREF(dw2); NOREF(uTimerID);
134}
135#else /* !USE_WINMM */
136
137#ifdef USE_APC
138/**
139 * Async callback.
140 *
141 * @param lpArgToCompletionRoutine Pointer to our timer structure.
142 */
143VOID CALLBACK rttimerAPCProc(LPVOID lpArgToCompletionRoutine, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
144{
145 PRTTIMER pTimer = (PRTTIMER)lpArgToCompletionRoutine;
146
147 /*
148 * Check if we're begin destroyed.
149 */
150 if (pTimer->u32Magic != RTTIMER_MAGIC)
151 return;
152
153 /*
154 * Callback the handler.
155 */
156 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pTimer->iTick);
157
158 /*
159 * Rearm the timer handler.
160 */
161#ifdef USE_CATCH_UP
162 pTimer->llNext.QuadPart += (int64_t)pTimer->uMilliesInterval * 10000;
163 LARGE_INTEGER ll;
164 ll.QuadPart = RTTimeNanoTS() - pTimer->llNext.QuadPart;
165 if (ll.QuadPart < -500000)
166 ll.QuadPart = ll.QuadPart / 100;
167 else
168 ll.QuadPart = -500000 / 100; /* need to catch up, do a minimum wait of 0.5ms. */
169#else
170 LARGE_INTEGER ll = pTimer->llNext;
171#endif
172 BOOL frc = SetWaitableTimer(pTimer->hTimer, &ll, 0, rttimerAPCProc, pTimer, FALSE);
173 AssertMsg(frc || pTimer->u32Magic != RTTIMER_MAGIC, ("last error %d\n", GetLastError()));
174}
175#endif /* USE_APC */
176
177/**
178 * Timer thread.
179 */
180static DECLCALLBACK(int) rttimerCallback(RTTHREAD Thread, void *pvArg)
181{
182 PRTTIMER pTimer = (PRTTIMER)(void *)pvArg;
183 Assert(pTimer->u32Magic == RTTIMER_MAGIC);
184
185 /*
186 * Bounce our priority up quite a bit.
187 */
188 if ( !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL)
189 /*&& !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)*/)
190 {
191 int rc = GetLastError();
192 AssertMsgFailed(("Failed to set priority class lasterror %d.\n", rc));
193 pTimer->iError = RTErrConvertFromWin32(rc);
194 return rc;
195 }
196
197 /*
198 * Start the waitable timer.
199 */
200
201#ifdef USE_CATCH_UP
202 const int64_t NSInterval = (int64_t)pTimer->uMilliesInterval * 1000000;
203 pTimer->llNext.QuadPart = RTTimeNanoTS() + NSInterval;
204#else
205 pTimer->llNext.QuadPart = -(int64_t)pTimer->uMilliesInterval * 10000;
206#endif
207 LARGE_INTEGER ll;
208 ll.QuadPart = -(int64_t)pTimer->uMilliesInterval * 10000;
209#ifdef USE_APC
210 if (!SetWaitableTimer(pTimer->hTimer, &ll, 0, rttimerAPCProc, pTimer, FALSE))
211#else
212 if (!SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE))
213#endif
214 {
215 int rc = GetLastError();
216 AssertMsgFailed(("Failed to set timer, lasterr %d.\n", rc));
217 pTimer->iError = RTErrConvertFromWin32(rc);
218 RTThreadUserSignal(Thread);
219 return rc;
220 }
221
222 /*
223 * Wait for the semaphore to be posted.
224 */
225 RTThreadUserSignal(Thread);
226 for (;pTimer->u32Magic == RTTIMER_MAGIC;)
227 {
228#ifdef USE_APC
229 int rc = WaitForSingleObjectEx(pTimer->hevWait, INFINITE, TRUE);
230 if (rc != WAIT_OBJECT_0 && rc != WAIT_IO_COMPLETION)
231#else
232 int rc = WaitForSingleObjectEx(pTimer->hTimer, INFINITE, FALSE);
233 if (pTimer->u32Magic != RTTIMER_MAGIC)
234 break;
235 if (rc == WAIT_OBJECT_0)
236 {
237 /*
238 * Callback the handler.
239 */
240 pTimer->pfnTimer(pTimer, pTimer->pvUser, ++pTimer->iTick);
241
242 /*
243 * Rearm the timer handler.
244 */
245# ifdef USE_CATCH_UP
246 pTimer->llNext.QuadPart += NSInterval;
247 ll.QuadPart = RTTimeNanoTS() - pTimer->llNext.QuadPart;
248 if (ll.QuadPart < -500000)
249 ll.QuadPart = ll.QuadPart / 100;
250 else
251 ll.QuadPart = -500000 / 100; /* need to catch up, do a minimum wait of 0.5ms. */
252# else
253 ll = pTimer->llNext;
254# endif
255 BOOL fRc = SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE);
256 AssertMsg(fRc || pTimer->u32Magic != RTTIMER_MAGIC, ("last error %d\n", GetLastError())); NOREF(fRc);
257 }
258 else
259#endif
260 {
261 /*
262 * We failed during wait, so just signal the destructor and exit.
263 */
264 int rc2 = GetLastError();
265 RTThreadUserSignal(Thread);
266 AssertMsgFailed(("Wait on hTimer failed, rc=%d lasterr=%d\n", rc, rc2)); NOREF(rc2);
267 return -1;
268 }
269 }
270
271 /*
272 * Exit.
273 */
274 RTThreadUserSignal(Thread);
275 return 0;
276}
277#endif /* !USE_WINMM */
278
279
280RTDECL(int) RTTimerCreate(PRTTIMER *ppTimer, unsigned uMilliesInterval, PFNRTTIMER pfnTimer, void *pvUser)
281{
282#ifndef USE_WINMM
283 /*
284 * On windows we'll have to set the timer resolution before
285 * we start the timer.
286 */
287 ULONG ulMax = UINT32_MAX;
288 ULONG ulMin = UINT32_MAX;
289 ULONG ulCur = UINT32_MAX;
290 NtQueryTimerResolution(&ulMax, &ulMin, &ulCur);
291 Log(("NtQueryTimerResolution -> ulMax=%lu00ns ulMin=%lu00ns ulCur=%lu00ns\n", ulMax, ulMin, ulCur));
292 if (ulCur > ulMin && ulCur > 10000 /* = 1ms */)
293 {
294 if (NtSetTimerResolution(10000, TRUE, &ulCur) >= 0)
295 Log(("Changed timer resolution to 1ms.\n"));
296 else if (NtSetTimerResolution(20000, TRUE, &ulCur) >= 0)
297 Log(("Changed timer resolution to 2ms.\n"));
298 else if (NtSetTimerResolution(40000, TRUE, &ulCur) >= 0)
299 Log(("Changed timer resolution to 4ms.\n"));
300 else if (ulMin <= 50000 && NtSetTimerResolution(ulMin, TRUE, &ulCur) >= 0)
301 Log(("Changed timer resolution to %lu *100ns.\n", ulMin));
302 else
303 {
304 AssertMsgFailed(("Failed to configure timer resolution!\n"));
305 return VERR_INTERNAL_ERROR;
306 }
307 }
308#endif /* !USE_WINN */
309
310 /*
311 * Create new timer.
312 */
313 int rc = VERR_IPE_UNINITIALIZED_STATUS;
314 PRTTIMER pTimer = (PRTTIMER)RTMemAlloc(sizeof(*pTimer));
315 if (pTimer)
316 {
317 pTimer->u32Magic = RTTIMER_MAGIC;
318 pTimer->pvUser = pvUser;
319 pTimer->pfnTimer = pfnTimer;
320 pTimer->iTick = 0;
321 pTimer->uMilliesInterval = uMilliesInterval;
322#ifdef USE_WINMM
323 /* sync kill doesn't work. */
324 pTimer->TimerId = timeSetEvent(uMilliesInterval, 0, rttimerCallback, (DWORD_PTR)pTimer, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
325 if (pTimer->TimerId)
326 {
327 ULONG ulMax = UINT32_MAX;
328 ULONG ulMin = UINT32_MAX;
329 ULONG ulCur = UINT32_MAX;
330 NtQueryTimerResolution(&ulMax, &ulMin, &ulCur);
331 Log(("NtQueryTimerResolution -> ulMax=%lu00ns ulMin=%lu00ns ulCur=%lu00ns\n", ulMax, ulMin, ulCur));
332
333 *ppTimer = pTimer;
334 return VINF_SUCCESS;
335 }
336 rc = VERR_INVALID_PARAMETER;
337
338#else /* !USE_WINMM */
339
340 /*
341 * Create Win32 event semaphore.
342 */
343 pTimer->iError = 0;
344 pTimer->hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
345 if (pTimer->hTimer)
346 {
347#ifdef USE_APC
348 /*
349 * Create wait semaphore.
350 */
351 pTimer->hevWait = CreateEvent(NULL, FALSE, FALSE, NULL);
352 if (pTimer->hevWait)
353#endif
354 {
355 /*
356 * Kick off the timer thread.
357 */
358 rc = RTThreadCreate(&pTimer->Thread, rttimerCallback, pTimer, 0, RTTHREADTYPE_TIMER, RTTHREADFLAGS_WAITABLE, "Timer");
359 if (RT_SUCCESS(rc))
360 {
361 /*
362 * Wait for the timer to successfully create the timer
363 * If we don't get a response in 10 secs, then we assume we're screwed.
364 */
365 rc = RTThreadUserWait(pTimer->Thread, 10000);
366 if (RT_SUCCESS(rc))
367 {
368 rc = pTimer->iError;
369 if (RT_SUCCESS(rc))
370 {
371 *ppTimer = pTimer;
372 return VINF_SUCCESS;
373 }
374 }
375 ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
376 RTThreadWait(pTimer->Thread, 250, NULL);
377 CancelWaitableTimer(pTimer->hTimer);
378 }
379#ifdef USE_APC
380 CloseHandle(pTimer->hevWait);
381#endif
382 }
383 CloseHandle(pTimer->hTimer);
384 }
385#endif /* !USE_WINMM */
386
387 AssertMsgFailed(("Failed to create timer uMilliesInterval=%d. rc=%d\n", uMilliesInterval, rc));
388 RTMemFree(pTimer);
389 }
390 else
391 rc = VERR_NO_MEMORY;
392 return rc;
393}
394
395
396RTR3DECL(int) RTTimerDestroy(PRTTIMER pTimer)
397{
398 /* NULL is ok. */
399 if (!pTimer)
400 return VINF_SUCCESS;
401
402 /*
403 * Validate handle first.
404 */
405 int rc;
406 if ( VALID_PTR(pTimer)
407 && pTimer->u32Magic == RTTIMER_MAGIC)
408 {
409#ifdef USE_WINMM
410 /*
411 * Kill the timer and exit.
412 */
413 rc = timeKillEvent(pTimer->TimerId);
414 AssertMsg(rc == TIMERR_NOERROR, ("timeKillEvent -> %d\n", rc));
415 ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
416 RTThreadSleep(1);
417
418#else /* !USE_WINMM */
419
420 /*
421 * Signal that we want the thread to exit.
422 */
423 ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
424#ifdef USE_APC
425 SetEvent(pTimer->hevWait);
426 CloseHandle(pTimer->hevWait);
427 rc = CancelWaitableTimer(pTimer->hTimer);
428 AssertMsg(rc, ("CancelWaitableTimer lasterr=%d\n", GetLastError()));
429#else
430 LARGE_INTEGER ll = {0};
431 ll.LowPart = 100;
432 rc = SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE);
433 AssertMsg(rc, ("CancelWaitableTimer lasterr=%d\n", GetLastError()));
434#endif
435
436 /*
437 * Wait for the thread to exit.
438 * And if it don't wanna exit, we'll get kill it.
439 */
440 rc = RTThreadWait(pTimer->Thread, 1000, NULL);
441 if (RT_FAILURE(rc))
442 TerminateThread((HANDLE)RTThreadGetNative(pTimer->Thread), UINT32_MAX);
443
444 /*
445 * Free resource.
446 */
447 rc = CloseHandle(pTimer->hTimer);
448 AssertMsg(rc, ("CloseHandle lasterr=%d\n", GetLastError()));
449
450#endif /* !USE_WINMM */
451 RTMemFree(pTimer);
452 return rc;
453 }
454
455 rc = VERR_INVALID_HANDLE;
456 AssertMsgFailed(("Failed to destroy timer %p. rc=%d\n", pTimer, rc));
457 return rc;
458}
459
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