VirtualBox

source: vbox/trunk/src/VBox/Runtime/generic/timerlr-generic.cpp@ 93943

Last change on this file since 93943 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 14.8 KB
Line 
1/* $Id: timerlr-generic.cpp 93115 2022-01-01 11:31:46Z vboxsync $ */
2/** @file
3 * IPRT - Low Resolution Timers, Generic.
4 *
5 * This code is more or less identical to timer-generic.cpp, so
6 * bugfixes goes into both files.
7 */
8
9/*
10 * Copyright (C) 2006-2022 Oracle Corporation
11 *
12 * This file is part of VirtualBox Open Source Edition (OSE), as
13 * available from http://www.virtualbox.org. This file is free software;
14 * you can redistribute it and/or modify it under the terms of the GNU
15 * General Public License (GPL) as published by the Free Software
16 * Foundation, in version 2 as it comes in the "COPYING" file of the
17 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19 *
20 * The contents of this file may alternatively be used under the terms
21 * of the Common Development and Distribution License Version 1.0
22 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
23 * VirtualBox OSE distribution, in which case the provisions of the
24 * CDDL are applicable instead of those of the GPL.
25 *
26 * You may elect to license modified versions of this file under the
27 * terms and conditions of either the GPL or the CDDL or both.
28 */
29
30
31/*********************************************************************************************************************************
32* Header Files *
33*********************************************************************************************************************************/
34#include <iprt/timer.h>
35#include "internal/iprt.h"
36
37#include <iprt/thread.h>
38#include <iprt/err.h>
39#include <iprt/assert.h>
40#include <iprt/alloc.h>
41#include <iprt/asm.h>
42#include <iprt/semaphore.h>
43#include <iprt/time.h>
44#include <iprt/log.h>
45#include "internal/magics.h"
46
47
48/*********************************************************************************************************************************
49* Defined Constants And Macros *
50*********************************************************************************************************************************/
51/** The smallest interval for low resolution timers. */
52#define RTTIMERLR_MIN_INTERVAL RT_NS_100MS
53
54
55/*********************************************************************************************************************************
56* Structures and Typedefs *
57*********************************************************************************************************************************/
58/**
59 * The internal representation of a timer handle.
60 */
61typedef struct RTTIMERLRINT
62{
63 /** Magic.
64 * This is RTTIMERRT_MAGIC, but changes to something else before the timer
65 * is destroyed to indicate clearly that thread should exit. */
66 uint32_t volatile u32Magic;
67 /** Flag indicating the timer is suspended. */
68 bool volatile fSuspended;
69 /** Flag indicating that the timer has been destroyed. */
70 bool volatile fDestroyed;
71 /** Set when the thread is blocked. */
72 bool volatile fBlocked;
73 bool fPadding;
74 /** The timer interval. 0 if one-shot. */
75 uint64_t volatile u64NanoInterval;
76 /** The start of the current run (ns).
77 * This is used to calculate when the timer ought to fire the next time. */
78 uint64_t volatile u64StartTS;
79 /** The start of the current run (ns).
80 * This is used to calculate when the timer ought to fire the next time. */
81 uint64_t volatile u64NextTS;
82 /** The current tick number (since u64StartTS). */
83 uint64_t volatile iTick;
84
85 /** Callback. */
86 PFNRTTIMERLR pfnTimer;
87 /** User argument. */
88 void *pvUser;
89 /** The timer thread. */
90 RTTHREAD hThread;
91 /** Event semaphore on which the thread is blocked. */
92 RTSEMEVENT hEvent;
93} RTTIMERLRINT;
94typedef RTTIMERLRINT *PRTTIMERLRINT;
95
96
97/*********************************************************************************************************************************
98* Internal Functions *
99*********************************************************************************************************************************/
100static DECLCALLBACK(int) rtTimerLRThread(RTTHREAD hThread, void *pvUser);
101
102
103RTDECL(int) RTTimerLRCreateEx(RTTIMERLR *phTimerLR, uint64_t u64NanoInterval, uint32_t fFlags, PFNRTTIMERLR pfnTimer, void *pvUser)
104{
105 AssertPtr(phTimerLR);
106 *phTimerLR = NIL_RTTIMERLR;
107
108 /*
109 * We don't support the fancy MP features, nor intervals lower than 100 ms.
110 */
111 AssertReturn(!(fFlags & RTTIMER_FLAGS_CPU_SPECIFIC), VERR_NOT_SUPPORTED);
112 AssertReturn(!u64NanoInterval || u64NanoInterval >= RTTIMERLR_MIN_INTERVAL, VERR_OUT_OF_RANGE);
113
114 /*
115 * Allocate and initialize the timer handle.
116 */
117 PRTTIMERLRINT pThis = (PRTTIMERLRINT)RTMemAlloc(sizeof(*pThis));
118 if (!pThis)
119 return VERR_NO_MEMORY;
120
121 pThis->u32Magic = RTTIMERLR_MAGIC;
122 pThis->fSuspended = true;
123 pThis->fDestroyed = false;
124 pThis->fBlocked = false;
125 pThis->fPadding = false;
126 pThis->pfnTimer = pfnTimer;
127 pThis->pvUser = pvUser;
128 pThis->hThread = NIL_RTTHREAD;
129 pThis->hEvent = NIL_RTSEMEVENT;
130 pThis->u64NanoInterval = u64NanoInterval;
131 pThis->u64StartTS = 0;
132
133 int rc = RTSemEventCreate(&pThis->hEvent);
134 if (RT_SUCCESS(rc))
135 {
136 rc = RTThreadCreate(&pThis->hThread, rtTimerLRThread, pThis, 0, RTTHREADTYPE_TIMER, RTTHREADFLAGS_WAITABLE, "TimerLR");
137 if (RT_SUCCESS(rc))
138 {
139 *phTimerLR = pThis;
140 return VINF_SUCCESS;
141 }
142
143 pThis->u32Magic = 0;
144 RTSemEventDestroy(pThis->hEvent);
145 pThis->hEvent = NIL_RTSEMEVENT;
146 }
147 RTMemFree(pThis);
148
149 return rc;
150}
151RT_EXPORT_SYMBOL(RTTimerLRCreateEx);
152
153
154RTDECL(int) RTTimerLRDestroy(RTTIMERLR hTimerLR)
155{
156 /*
157 * Validate input, NIL is fine though.
158 */
159 if (hTimerLR == NIL_RTTIMERLR)
160 return VINF_SUCCESS;
161 PRTTIMERLRINT pThis = hTimerLR;
162 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
163 AssertReturn(pThis->u32Magic == RTTIMERLR_MAGIC, VERR_INVALID_HANDLE);
164 AssertReturn(!pThis->fDestroyed, VERR_INVALID_HANDLE);
165
166 /*
167 * If the timer is active, we stop and destruct it in one go, to avoid
168 * unnecessary waiting for the next tick. If it's suspended we can safely
169 * set the destroy flag and signal it.
170 */
171 RTTHREAD hThread = pThis->hThread;
172 if (!pThis->fSuspended)
173 ASMAtomicWriteBool(&pThis->fSuspended, true);
174 ASMAtomicWriteBool(&pThis->fDestroyed, true);
175 int rc = RTSemEventSignal(pThis->hEvent);
176 if (rc == VERR_ALREADY_POSTED)
177 rc = VINF_SUCCESS;
178 AssertRC(rc);
179
180 RTThreadWait(hThread, 250, NULL);
181 return VINF_SUCCESS;
182}
183RT_EXPORT_SYMBOL(RTTimerLRDestroy);
184
185
186/**
187 * Internal worker fro RTTimerLRStart and RTTiemrLRChangeInterval.
188 */
189static int rtTimerLRStart(PRTTIMERLRINT pThis, uint64_t u64First)
190{
191 if (!pThis->fSuspended)
192 return VERR_TIMER_ACTIVE;
193
194 /*
195 * Calc when it should start firing and give the thread a kick so it get going.
196 */
197 u64First += RTTimeNanoTS();
198 ASMAtomicWriteU64(&pThis->iTick, 0);
199 ASMAtomicWriteU64(&pThis->u64StartTS, u64First);
200 ASMAtomicWriteU64(&pThis->u64NextTS, u64First);
201 ASMAtomicWriteBool(&pThis->fSuspended, false);
202 int rc = RTSemEventSignal(pThis->hEvent);
203 if (rc == VERR_ALREADY_POSTED)
204 rc = VINF_SUCCESS;
205 AssertRC(rc);
206 return rc;
207}
208
209
210RTDECL(int) RTTimerLRStart(RTTIMERLR hTimerLR, uint64_t u64First)
211{
212 /*
213 * Validate input.
214 */
215 PRTTIMERLRINT pThis = hTimerLR;
216 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
217 AssertReturn(pThis->u32Magic == RTTIMERLR_MAGIC, VERR_INVALID_HANDLE);
218 AssertReturn(!pThis->fDestroyed, VERR_INVALID_HANDLE);
219 AssertReturn(!u64First || u64First >= RTTIMERLR_MIN_INTERVAL, VERR_OUT_OF_RANGE);
220
221 /*
222 * Do the job.
223 */
224 return rtTimerLRStart(pThis, u64First);
225}
226RT_EXPORT_SYMBOL(RTTimerLRStart);
227
228
229/**
230 * Internal worker for RTTimerLRStop and RTTimerLRChangeInterval
231 */
232static int rtTimerLRStop(PRTTIMERLRINT pThis, bool fSynchronous)
233{
234 /*
235 * Fail if already suspended.
236 */
237 if (pThis->fSuspended)
238 return VERR_TIMER_SUSPENDED;
239
240 /*
241 * Mark it as suspended and kick the thread.
242 * It's simpler to always reset the thread user semaphore, so we do that first.
243 */
244 int rc = RTThreadUserReset(pThis->hThread);
245 AssertRC(rc);
246
247 ASMAtomicWriteBool(&pThis->fSuspended, true);
248 rc = RTSemEventSignal(pThis->hEvent);
249 if (rc == VERR_ALREADY_POSTED)
250 rc = VINF_SUCCESS;
251 AssertRC(rc);
252
253 /*
254 * Wait for the thread to stop running if synchronous.
255 */
256 if (fSynchronous && RT_SUCCESS(rc))
257 {
258 rc = RTThreadUserWait(pThis->hThread, RT_MS_1MIN);
259 AssertRC(rc);
260 }
261
262 return rc;
263}
264
265
266RTDECL(int) RTTimerLRStop(RTTIMERLR hTimerLR)
267{
268 /*
269 * Validate input.
270 */
271 PRTTIMERLRINT pThis = hTimerLR;
272 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
273 AssertReturn(pThis->u32Magic == RTTIMERLR_MAGIC, VERR_INVALID_HANDLE);
274 AssertReturn(!pThis->fDestroyed, VERR_INVALID_HANDLE);
275
276 /*
277 * Do the job.
278 */
279 return rtTimerLRStop(pThis, false);
280}
281RT_EXPORT_SYMBOL(RTTimerLRStop);
282
283
284RTDECL(int) RTTimerLRChangeInterval(RTTIMERLR hTimerLR, uint64_t u64NanoInterval)
285{
286 /*
287 * Validate input.
288 */
289 PRTTIMERLRINT pThis = hTimerLR;
290 AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
291 AssertReturn(pThis->u32Magic == RTTIMERLR_MAGIC, VERR_INVALID_HANDLE);
292 AssertReturn(!pThis->fDestroyed, VERR_INVALID_HANDLE);
293 AssertReturn(!u64NanoInterval || u64NanoInterval >= RTTIMERLR_MIN_INTERVAL, VERR_OUT_OF_RANGE);
294
295 /*
296 * Do the job accoring to state and caller.
297 */
298 int rc;
299 if (pThis->fSuspended)
300 {
301 /* Stopped: Just update the interval. */
302 ASMAtomicWriteU64(&pThis->u64NanoInterval, u64NanoInterval);
303 rc = VINF_SUCCESS;
304 }
305 else if (RTThreadSelf() == pThis->hThread)
306 {
307 /* Running: Updating interval from the callback. */
308 uint64_t u64Now = RTTimeNanoTS();
309 pThis->iTick = 0;
310 pThis->u64StartTS = u64Now;
311 pThis->u64NextTS = u64Now;
312 ASMAtomicWriteU64(&pThis->u64NanoInterval, u64NanoInterval);
313 rc = VINF_SUCCESS;
314 }
315 else
316 {
317 /* Running: Stopping */
318 rc = rtTimerLRStop(pThis, true);
319 if (RT_SUCCESS(rc))
320 {
321 ASMAtomicWriteU64(&pThis->u64NanoInterval, u64NanoInterval);
322 rc = rtTimerLRStart(pThis, 0);
323 }
324 }
325
326 return rc;
327}
328RT_EXPORT_SYMBOL(RTTimerLRChangeInterval);
329
330
331static DECLCALLBACK(int) rtTimerLRThread(RTTHREAD hThreadSelf, void *pvUser)
332{
333 PRTTIMERLRINT pThis = (PRTTIMERLRINT)pvUser;
334 NOREF(hThreadSelf);
335
336 /*
337 * The loop.
338 */
339 while (!ASMAtomicUoReadBool(&pThis->fDestroyed))
340 {
341 if (ASMAtomicUoReadBool(&pThis->fSuspended))
342 {
343 /* Signal rtTimerLRStop thread. */
344 int rc = RTThreadUserSignal(hThreadSelf);
345 AssertRC(rc);
346
347 ASMAtomicWriteBool(&pThis->fBlocked, true);
348 rc = RTSemEventWait(pThis->hEvent, RT_INDEFINITE_WAIT);
349 if (RT_FAILURE(rc) && rc != VERR_INTERRUPTED)
350 {
351 AssertRC(rc);
352 RTThreadSleep(1000); /* Don't cause trouble! */
353 }
354 ASMAtomicWriteBool(&pThis->fBlocked, false);
355 }
356 else
357 {
358 uint64_t cNanoSeconds;
359 const uint64_t u64NanoTS = RTTimeNanoTS();
360 uint64_t u64NextTS = pThis->u64NextTS;
361 if (u64NanoTS >= u64NextTS)
362 {
363 uint64_t iTick = ++pThis->iTick;
364 pThis->pfnTimer(pThis, pThis->pvUser, iTick);
365
366 /* status changed? */
367 if ( ASMAtomicUoReadBool(&pThis->fSuspended)
368 || ASMAtomicUoReadBool(&pThis->fDestroyed))
369 continue;
370
371 /*
372 * Read timer data (it's all volatile and better if we read it all at once):
373 */
374 iTick = pThis->iTick;
375 uint64_t const u64StartTS = pThis->u64StartTS;
376 uint64_t const u64NanoInterval = pThis->u64NanoInterval;
377 ASMCompilerBarrier();
378
379 /*
380 * Suspend if one shot.
381 */
382 if (!u64NanoInterval)
383 {
384 ASMAtomicWriteBool(&pThis->fSuspended, true);
385 continue;
386 }
387
388 /*
389 * Calc the next time we should fire.
390 *
391 * If we're more than 60 intervals behind, just skip ahead. We
392 * don't want the timer thread running wild just because the
393 * clock changed in an unexpected way. As seen in @bugref{3611} this
394 * does happen during suspend/resume, but it may also happen
395 * if we're using a non-monotonic clock as time source.
396 */
397 u64NextTS = u64StartTS + iTick * u64NanoInterval;
398 if (RT_LIKELY(u64NextTS > u64NanoTS))
399 cNanoSeconds = u64NextTS - u64NanoTS;
400 else
401 {
402 uint64_t iActualTick = (u64NanoTS - u64StartTS) / u64NanoInterval;
403 if (iActualTick - iTick > 60)
404 pThis->iTick = iActualTick - 1;
405#ifdef IN_RING0
406 cNanoSeconds = RTTimerGetSystemGranularity() / 2;
407#else
408 cNanoSeconds = RT_NS_1MS;
409#endif
410 u64NextTS = u64NanoTS + cNanoSeconds;
411 }
412
413 pThis->u64NextTS = u64NextTS;
414 }
415 else
416 cNanoSeconds = u64NextTS - u64NanoTS;
417
418 /* block. */
419 ASMAtomicWriteBool(&pThis->fBlocked, true);
420 int rc = RTSemEventWait(pThis->hEvent,
421 (RTMSINTERVAL)(cNanoSeconds < 1000000 ? 1 : cNanoSeconds / 1000000));
422 if (RT_FAILURE(rc) && rc != VERR_INTERRUPTED && rc != VERR_TIMEOUT)
423 {
424 AssertRC(rc);
425 RTThreadSleep(1000); /* Don't cause trouble! */
426 }
427 ASMAtomicWriteBool(&pThis->fBlocked, false);
428 }
429 }
430
431 /*
432 * Release the timer resources.
433 */
434 ASMAtomicWriteU32(&pThis->u32Magic, ~RTTIMERLR_MAGIC); /* make the handle invalid. */
435 int rc = RTSemEventDestroy(pThis->hEvent); AssertRC(rc);
436 pThis->hEvent = NIL_RTSEMEVENT;
437 pThis->hThread = NIL_RTTHREAD;
438 RTMemFree(pThis);
439
440 return VINF_SUCCESS;
441}
442
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