VirtualBox

source: vbox/trunk/src/VBox/VMM/TM.cpp@ 13371

Last change on this file since 13371 was 13005, checked in by vboxsync, 16 years ago

VMM/doxygen: More links.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 85.8 KB
Line 
1/* $Id: TM.cpp 13005 2008-10-06 12:35:21Z vboxsync $ */
2/** @file
3 * TM - Time Manager.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23/** @page pg_tm TM - The Time Manager
24 *
25 * The Time Manager abstracts the CPU clocks and manages timers used by the VMM,
26 * device and drivers.
27 *
28 * @see grp_tm
29 *
30 *
31 * @section sec_tm_clocks Clocks
32 *
33 * There are currently 4 clocks:
34 * - Virtual (guest).
35 * - Synchronous virtual (guest).
36 * - CPU Tick (TSC) (guest). Only current use is rdtsc emulation. Usually a
37 * function of the virtual clock.
38 * - Real (host). The only current use is display updates for not real
39 * good reason...
40 *
41 * The interesting clocks are two first ones, the virtual and synchronous virtual
42 * clock. The synchronous virtual clock is tied to the virtual clock except that
43 * it will take into account timer delivery lag caused by host scheduling. It will
44 * normally never advance beyond the header timer, and when lagging too far behind
45 * it will gradually speed up to catch up with the virtual clock.
46 *
47 * The CPU tick (TSC) is normally virtualized as a function of the virtual time,
48 * where the frequency defaults to the host cpu frequency (as we measure it). It
49 * can also use the host TSC as source and either present it with an offset or
50 * unmodified. It is of course possible to configure the TSC frequency and mode
51 * of operation.
52 *
53 * @subsection subsec_tm_timesync Guest Time Sync / UTC time
54 *
55 * Guest time syncing is primarily taken care of by the VMM device. The principle
56 * is very simple, the guest additions periodically asks the VMM device what the
57 * current UTC time is and makes adjustments accordingly. Now, because the
58 * synchronous virtual clock might be doing catchups and we would therefore
59 * deliver more than the normal rate for a little while, some adjusting of the
60 * UTC time is required before passing it on to the guest. This is why TM provides
61 * an API for query the current UTC time.
62 *
63 *
64 * @section sec_tm_timers Timers
65 *
66 * The timers can use any of the TM clocks described in the previous section. Each
67 * clock has its own scheduling facility, or timer queue if you like. There are
68 * a few factors which makes it a bit complex. First there is the usual R0 vs R3
69 * vs. GC thing. Then there is multiple threads, and then there is the timer thread
70 * that periodically checks whether any timers has expired without EMT noticing. On
71 * the API level, all but the create and save APIs must be mulithreaded. EMT will
72 * always run the timers.
73 *
74 * The design is using a doubly linked list of active timers which is ordered
75 * by expire date. This list is only modified by the EMT thread. Updates to the
76 * list are are batched in a singly linked list, which is then process by the EMT
77 * thread at the first opportunity (immediately, next time EMT modifies a timer
78 * on that clock, or next timer timeout). Both lists are offset based and all
79 * the elements therefore allocated from the hyper heap.
80 *
81 * For figuring out when there is need to schedule and run timers TM will:
82 * - Poll whenever somebody queries the virtual clock.
83 * - Poll the virtual clocks from the EM and REM loops.
84 * - Poll the virtual clocks from trap exit path.
85 * - Poll the virtual clocks and calculate first timeout from the halt loop.
86 * - Employ a thread which periodically (100Hz) polls all the timer queues.
87 *
88 *
89 * @section sec_tm_timer Logging
90 *
91 * Level 2: Logs a most of the timer state transitions and queue servicing.
92 * Level 3: Logs a few oddments.
93 * Level 4: Logs TMCLOCK_VIRTUAL_SYNC catch-up events.
94 *
95 */
96
97
98
99
100/*******************************************************************************
101* Header Files *
102*******************************************************************************/
103#define LOG_GROUP LOG_GROUP_TM
104#include <VBox/tm.h>
105#include <VBox/vmm.h>
106#include <VBox/mm.h>
107#include <VBox/ssm.h>
108#include <VBox/dbgf.h>
109#include <VBox/rem.h>
110#include <VBox/pdm.h>
111#include "TMInternal.h"
112#include <VBox/vm.h>
113
114#include <VBox/param.h>
115#include <VBox/err.h>
116
117#include <VBox/log.h>
118#include <iprt/asm.h>
119#include <iprt/assert.h>
120#include <iprt/thread.h>
121#include <iprt/time.h>
122#include <iprt/timer.h>
123#include <iprt/semaphore.h>
124#include <iprt/string.h>
125#include <iprt/env.h>
126
127
128/*******************************************************************************
129* Defined Constants And Macros *
130*******************************************************************************/
131/** The current saved state version.*/
132#define TM_SAVED_STATE_VERSION 3
133
134
135/*******************************************************************************
136* Internal Functions *
137*******************************************************************************/
138static bool tmR3HasFixedTSC(PVM pVM);
139static uint64_t tmR3CalibrateTSC(PVM pVM);
140static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM);
141static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
142static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
143static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue);
144static void tmR3TimerQueueRunVirtualSync(PVM pVM);
145static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
146static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
147static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
148
149
150/**
151 * Internal function for getting the clock time.
152 *
153 * @returns clock time.
154 * @param pVM The VM handle.
155 * @param enmClock The clock.
156 */
157DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
158{
159 switch (enmClock)
160 {
161 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
162 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
163 case TMCLOCK_REAL: return TMRealGet(pVM);
164 case TMCLOCK_TSC: return TMCpuTickGet(pVM);
165 default:
166 AssertMsgFailed(("enmClock=%d\n", enmClock));
167 return ~(uint64_t)0;
168 }
169}
170
171
172/**
173 * Initializes the TM.
174 *
175 * @returns VBox status code.
176 * @param pVM The VM to operate on.
177 */
178VMMR3DECL(int) TMR3Init(PVM pVM)
179{
180 LogFlow(("TMR3Init:\n"));
181
182 /*
183 * Assert alignment and sizes.
184 */
185 AssertRelease(!(RT_OFFSETOF(VM, tm.s) & 31));
186 AssertRelease(sizeof(pVM->tm.s) <= sizeof(pVM->tm.padding));
187
188 /*
189 * Init the structure.
190 */
191 void *pv;
192 int rc = MMHyperAlloc(pVM, sizeof(pVM->tm.s.paTimerQueuesR3[0]) * TMCLOCK_MAX, 0, MM_TAG_TM, &pv);
193 AssertRCReturn(rc, rc);
194 pVM->tm.s.paTimerQueuesR3 = (PTMTIMERQUEUE)pv;
195
196 pVM->tm.s.offVM = RT_OFFSETOF(VM, tm.s);
197 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].enmClock = TMCLOCK_VIRTUAL;
198 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].u64Expire = INT64_MAX;
199 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].enmClock = TMCLOCK_VIRTUAL_SYNC;
200 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].u64Expire = INT64_MAX;
201 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].enmClock = TMCLOCK_REAL;
202 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].u64Expire = INT64_MAX;
203 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].enmClock = TMCLOCK_TSC;
204 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].u64Expire = INT64_MAX;
205
206 /*
207 * We directly use the GIP to calculate the virtual time. We map the
208 * the GIP into the guest context so we can do this calculation there
209 * as well and save costly world switches.
210 */
211 pVM->tm.s.pvGIPR3 = (void *)g_pSUPGlobalInfoPage;
212 AssertMsgReturn(pVM->tm.s.pvGIPR3, ("GIP support is now required!\n"), VERR_INTERNAL_ERROR);
213 RTHCPHYS HCPhysGIP;
214 rc = SUPGipGetPhys(&HCPhysGIP);
215 AssertMsgRCReturn(rc, ("Failed to get GIP physical address!\n"), rc);
216
217 RTGCPTR GCPtr;
218 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, HCPhysGIP, PAGE_SIZE, "GIP", &GCPtr);
219 if (VBOX_FAILURE(rc))
220 {
221 AssertMsgFailed(("Failed to map GIP into GC, rc=%Vrc!\n", rc));
222 return rc;
223 }
224 pVM->tm.s.pvGIPGC = GCPtr;
225 LogFlow(("TMR3Init: HCPhysGIP=%RHp at %VGv\n", HCPhysGIP, pVM->tm.s.pvGIPGC));
226 MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);
227
228 /* Check assumptions made in TMAllVirtual.cpp about the GIP update interval. */
229 if ( g_pSUPGlobalInfoPage->u32Magic == SUPGLOBALINFOPAGE_MAGIC
230 && g_pSUPGlobalInfoPage->u32UpdateIntervalNS >= 250000000 /* 0.25s */)
231 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
232 N_("The GIP update interval is too big. u32UpdateIntervalNS=%RU32 (u32UpdateHz=%RU32)"),
233 g_pSUPGlobalInfoPage->u32UpdateIntervalNS, g_pSUPGlobalInfoPage->u32UpdateHz);
234
235 /*
236 * Setup the VirtualGetRaw backend.
237 */
238 pVM->tm.s.VirtualGetRawDataR3.pu64Prev = &pVM->tm.s.u64VirtualRawPrev;
239 pVM->tm.s.VirtualGetRawDataR3.pfnBad = tmVirtualNanoTSBad;
240 pVM->tm.s.VirtualGetRawDataR3.pfnRediscover = tmVirtualNanoTSRediscover;
241 if (ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2)
242 {
243 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
244 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceSync;
245 else
246 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceAsync;
247 }
248 else
249 {
250 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
251 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacySync;
252 else
253 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacyAsync;
254 }
255
256 pVM->tm.s.VirtualGetRawDataGC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
257 pVM->tm.s.VirtualGetRawDataR0.pu64Prev = MMHyperR3ToR0(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
258 AssertReturn(pVM->tm.s.VirtualGetRawDataR0.pu64Prev, VERR_INTERNAL_ERROR);
259 /* The rest is done in TMR3InitFinalize since it's too early to call PDM. */
260
261
262 /*
263 * Get our CFGM node, create it if necessary.
264 */
265 PCFGMNODE pCfgHandle = CFGMR3GetChild(CFGMR3GetRoot(pVM), "TM");
266 if (!pCfgHandle)
267 {
268 rc = CFGMR3InsertNode(CFGMR3GetRoot(pVM), "TM", &pCfgHandle);
269 AssertRCReturn(rc, rc);
270 }
271
272 /*
273 * Determin the TSC configuration and frequency.
274 */
275 /* mode */
276 rc = CFGMR3QueryBool(pCfgHandle, "TSCVirtualized", &pVM->tm.s.fTSCVirtualized);
277 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
278 pVM->tm.s.fTSCVirtualized = true; /* trap rdtsc */
279 else if (VBOX_FAILURE(rc))
280 return VMSetError(pVM, rc, RT_SRC_POS,
281 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
282
283 /* source */
284 rc = CFGMR3QueryBool(pCfgHandle, "UseRealTSC", &pVM->tm.s.fTSCUseRealTSC);
285 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
286 pVM->tm.s.fTSCUseRealTSC = false; /* use virtual time */
287 else if (VBOX_FAILURE(rc))
288 return VMSetError(pVM, rc, RT_SRC_POS,
289 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
290 if (!pVM->tm.s.fTSCUseRealTSC)
291 pVM->tm.s.fTSCVirtualized = true;
292
293 /* TSC reliability */
294 rc = CFGMR3QueryBool(pCfgHandle, "MaybeUseOffsettedHostTSC", &pVM->tm.s.fMaybeUseOffsettedHostTSC);
295 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
296 {
297 if (!pVM->tm.s.fTSCUseRealTSC)
298 pVM->tm.s.fMaybeUseOffsettedHostTSC = tmR3HasFixedTSC(pVM);
299 else
300 pVM->tm.s.fMaybeUseOffsettedHostTSC = true;
301 }
302
303 /** @cfgm{TM/TSCTicksPerSecond, uint32_t, Current TSC frequency from GIP}
304 * The number of TSC ticks per second (i.e. the TSC frequency). This will
305 * override TSCUseRealTSC, TSCVirtualized and MaybeUseOffsettedHostTSC.
306 */
307 rc = CFGMR3QueryU64(pCfgHandle, "TSCTicksPerSecond", &pVM->tm.s.cTSCTicksPerSecond);
308 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
309 {
310 pVM->tm.s.cTSCTicksPerSecond = tmR3CalibrateTSC(pVM);
311 if ( !pVM->tm.s.fTSCUseRealTSC
312 && pVM->tm.s.cTSCTicksPerSecond >= _4G)
313 {
314 pVM->tm.s.cTSCTicksPerSecond = _4G - 1; /* (A limitation of our math code) */
315 pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
316 }
317 }
318 else if (VBOX_FAILURE(rc))
319 return VMSetError(pVM, rc, RT_SRC_POS,
320 N_("Configuration error: Failed to querying uint64_t value \"TSCTicksPerSecond\""));
321 else if ( pVM->tm.s.cTSCTicksPerSecond < _1M
322 || pVM->tm.s.cTSCTicksPerSecond >= _4G)
323 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
324 N_("Configuration error: \"TSCTicksPerSecond\" = %RI64 is not in the range 1MHz..4GHz-1"),
325 pVM->tm.s.cTSCTicksPerSecond);
326 else
327 {
328 pVM->tm.s.fTSCUseRealTSC = pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
329 pVM->tm.s.fTSCVirtualized = true;
330 }
331
332 /** @cfgm{TM/TSCTiedToExecution, bool, false}
333 * Whether the TSC should be tied to execution. This will exclude most of the
334 * virtualization overhead, but will by default include the time spend in the
335 * halt state (see TM/TSCNotTiedToHalt). This setting will override all other
336 * TSC settings except for TSCTicksPerSecond and TSCNotTiedToHalt, which should
337 * be used avoided or used with great care. Note that this will only work right
338 * together with VT-x or AMD-V, and with a single virtual CPU. */
339 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCTiedToExecution", &pVM->tm.s.fTSCTiedToExecution, false);
340 if (RT_FAILURE(rc))
341 return VMSetError(pVM, rc, RT_SRC_POS,
342 N_("Configuration error: Failed to querying bool value \"TSCTiedToExecution\""));
343 if (pVM->tm.s.fTSCTiedToExecution)
344 {
345 /* tied to execution, override all other settings. */
346 pVM->tm.s.fTSCVirtualized = true;
347 pVM->tm.s.fTSCUseRealTSC = true;
348 pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
349 }
350
351 /** @cfgm{TM/TSCNotTiedToHalt, bool, true}
352 * For overriding the default of TM/TSCTiedToExecution, i.e. set this to false
353 * to make the TSC freeze during HLT. */
354 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCNotTiedToHalt", &pVM->tm.s.fTSCNotTiedToHalt, false);
355 if (RT_FAILURE(rc))
356 return VMSetError(pVM, rc, RT_SRC_POS,
357 N_("Configuration error: Failed to querying bool value \"TSCNotTiedToHalt\""));
358
359 /* setup and report */
360 if (pVM->tm.s.fTSCVirtualized)
361 CPUMR3SetCR4Feature(pVM, X86_CR4_TSD, ~X86_CR4_TSD);
362 else
363 CPUMR3SetCR4Feature(pVM, 0, ~X86_CR4_TSD);
364 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool\n"
365 "TM: fMaybeUseOffsettedHostTSC=%RTbool TSCTiedToExecution=%RTbool TSCNotTiedToHalt=%RTbool\n",
366 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC,
367 pVM->tm.s.fMaybeUseOffsettedHostTSC, pVM->tm.s.fTSCTiedToExecution, pVM->tm.s.fTSCNotTiedToHalt));
368
369 /*
370 * Configure the timer synchronous virtual time.
371 */
372 rc = CFGMR3QueryU32(pCfgHandle, "ScheduleSlack", &pVM->tm.s.u32VirtualSyncScheduleSlack);
373 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
374 pVM->tm.s.u32VirtualSyncScheduleSlack = 100000; /* 0.100ms (ASSUMES virtual time is nanoseconds) */
375 else if (VBOX_FAILURE(rc))
376 return VMSetError(pVM, rc, RT_SRC_POS,
377 N_("Configuration error: Failed to querying 32-bit integer value \"ScheduleSlack\""));
378
379 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStopThreshold", &pVM->tm.s.u64VirtualSyncCatchUpStopThreshold);
380 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
381 pVM->tm.s.u64VirtualSyncCatchUpStopThreshold = 500000; /* 0.5ms */
382 else if (VBOX_FAILURE(rc))
383 return VMSetError(pVM, rc, RT_SRC_POS,
384 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpStopThreshold\""));
385
386 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpGiveUpThreshold", &pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold);
387 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
388 pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold = UINT64_C(60000000000); /* 60 sec */
389 else if (VBOX_FAILURE(rc))
390 return VMSetError(pVM, rc, RT_SRC_POS,
391 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpGiveUpThreshold\""));
392
393
394#define TM_CFG_PERIOD(iPeriod, DefStart, DefPct) \
395 do \
396 { \
397 uint64_t u64; \
398 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStartThreshold" #iPeriod, &u64); \
399 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
400 u64 = UINT64_C(DefStart); \
401 else if (VBOX_FAILURE(rc)) \
402 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpThreshold" #iPeriod "\"")); \
403 if ( (iPeriod > 0 && u64 <= pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod - 1].u64Start) \
404 || u64 >= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold) \
405 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Configuration error: Invalid start of period #" #iPeriod ": %RU64"), u64); \
406 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u64Start = u64; \
407 rc = CFGMR3QueryU32(pCfgHandle, "CatchUpPrecentage" #iPeriod, &pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage); \
408 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
409 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage = (DefPct); \
410 else if (VBOX_FAILURE(rc)) \
411 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 32-bit integer value \"CatchUpPrecentage" #iPeriod "\"")); \
412 } while (0)
413 /* This needs more tuning. Not sure if we really need so many period and be so gentle. */
414 TM_CFG_PERIOD(0, 750000, 5); /* 0.75ms at 1.05x */
415 TM_CFG_PERIOD(1, 1500000, 10); /* 1.50ms at 1.10x */
416 TM_CFG_PERIOD(2, 8000000, 25); /* 8ms at 1.25x */
417 TM_CFG_PERIOD(3, 30000000, 50); /* 30ms at 1.50x */
418 TM_CFG_PERIOD(4, 75000000, 75); /* 75ms at 1.75x */
419 TM_CFG_PERIOD(5, 175000000, 100); /* 175ms at 2x */
420 TM_CFG_PERIOD(6, 500000000, 200); /* 500ms at 3x */
421 TM_CFG_PERIOD(7, 3000000000, 300); /* 3s at 4x */
422 TM_CFG_PERIOD(8,30000000000, 400); /* 30s at 5x */
423 TM_CFG_PERIOD(9,55000000000, 500); /* 55s at 6x */
424 AssertCompile(RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods) == 10);
425#undef TM_CFG_PERIOD
426
427 /*
428 * Configure real world time (UTC).
429 */
430 rc = CFGMR3QueryS64(pCfgHandle, "UTCOffset", &pVM->tm.s.offUTC);
431 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
432 pVM->tm.s.offUTC = 0; /* ns */
433 else if (VBOX_FAILURE(rc))
434 return VMSetError(pVM, rc, RT_SRC_POS,
435 N_("Configuration error: Failed to querying 64-bit integer value \"UTCOffset\""));
436
437 /*
438 * Setup the warp drive.
439 */
440 rc = CFGMR3QueryU32(pCfgHandle, "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage);
441 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
442 rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage); /* legacy */
443 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
444 pVM->tm.s.u32VirtualWarpDrivePercentage = 100;
445 else if (VBOX_FAILURE(rc))
446 return VMSetError(pVM, rc, RT_SRC_POS,
447 N_("Configuration error: Failed to querying uint32_t value \"WarpDrivePercent\""));
448 else if ( pVM->tm.s.u32VirtualWarpDrivePercentage < 2
449 || pVM->tm.s.u32VirtualWarpDrivePercentage > 20000)
450 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
451 N_("Configuration error: \"WarpDrivePercent\" = %RI32 is not in the range 2..20000"),
452 pVM->tm.s.u32VirtualWarpDrivePercentage);
453 pVM->tm.s.fVirtualWarpDrive = pVM->tm.s.u32VirtualWarpDrivePercentage != 100;
454 if (pVM->tm.s.fVirtualWarpDrive)
455 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32\n", pVM->tm.s.u32VirtualWarpDrivePercentage));
456
457 /*
458 * Start the timer (guard against REM not yielding).
459 */
460 uint32_t u32Millies;
461 rc = CFGMR3QueryU32(pCfgHandle, "TimerMillies", &u32Millies);
462 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
463 u32Millies = 10;
464 else if (VBOX_FAILURE(rc))
465 return VMSetError(pVM, rc, RT_SRC_POS,
466 N_("Configuration error: Failed to query uint32_t value \"TimerMillies\""));
467 rc = RTTimerCreate(&pVM->tm.s.pTimer, u32Millies, tmR3TimerCallback, pVM);
468 if (VBOX_FAILURE(rc))
469 {
470 AssertMsgFailed(("Failed to create timer, u32Millies=%d rc=%Vrc.\n", u32Millies, rc));
471 return rc;
472 }
473 Log(("TM: Created timer %p firing every %d millieseconds\n", pVM->tm.s.pTimer, u32Millies));
474 pVM->tm.s.u32TimerMillies = u32Millies;
475
476 /*
477 * Register saved state.
478 */
479 rc = SSMR3RegisterInternal(pVM, "tm", 1, TM_SAVED_STATE_VERSION, sizeof(uint64_t) * 8,
480 NULL, tmR3Save, NULL,
481 NULL, tmR3Load, NULL);
482 if (VBOX_FAILURE(rc))
483 return rc;
484
485 /*
486 * Register statistics.
487 */
488 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.VirtualGetRawDataR3.c1nsSteps, STAMTYPE_U32, "/TM/R3/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
489 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.VirtualGetRawDataR3.cBadPrev, STAMTYPE_U32, "/TM/R3/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
490 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.VirtualGetRawDataR0.c1nsSteps, STAMTYPE_U32, "/TM/R0/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
491 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.VirtualGetRawDataR0.cBadPrev, STAMTYPE_U32, "/TM/R0/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
492 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.VirtualGetRawDataGC.c1nsSteps, STAMTYPE_U32, "/TM/GC/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
493 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.VirtualGetRawDataGC.cBadPrev, STAMTYPE_U32, "/TM/GC/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
494 STAM_REL_REG( pVM, (void *)&pVM->tm.s.offVirtualSync, STAMTYPE_U64, "/TM/VirtualSync/CurrentOffset", STAMUNIT_NS, "The current offset. (subtract GivenUp to get the lag)");
495 STAM_REL_REG_USED(pVM, (void *)&pVM->tm.s.offVirtualSyncGivenUp, STAMTYPE_U64, "/TM/VirtualSync/GivenUp", STAMUNIT_NS, "Nanoseconds of the 'CurrentOffset' that's been given up and won't ever be attemted caught up with.");
496
497#ifdef VBOX_WITH_STATISTICS
498 STAM_REG_USED( pVM, (void *)&pVM->tm.s.VirtualGetRawDataR3.cExpired, STAMTYPE_U32, "/TM/R3/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
499 STAM_REG_USED( pVM, (void *)&pVM->tm.s.VirtualGetRawDataR3.cUpdateRaces,STAMTYPE_U32, "/TM/R3/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
500 STAM_REG_USED( pVM, (void *)&pVM->tm.s.VirtualGetRawDataR0.cExpired, STAMTYPE_U32, "/TM/R0/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
501 STAM_REG_USED( pVM, (void *)&pVM->tm.s.VirtualGetRawDataR0.cUpdateRaces,STAMTYPE_U32, "/TM/R0/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
502 STAM_REG_USED( pVM, (void *)&pVM->tm.s.VirtualGetRawDataGC.cExpired, STAMTYPE_U32, "/TM/GC/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
503 STAM_REG_USED( pVM, (void *)&pVM->tm.s.VirtualGetRawDataGC.cUpdateRaces,STAMTYPE_U32, "/TM/GC/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
504
505 STAM_REG(pVM, &pVM->tm.s.StatDoQueues, STAMTYPE_PROFILE, "/TM/DoQueues", STAMUNIT_TICKS_PER_CALL, "Profiling timer TMR3TimerQueuesDo.");
506 STAM_REG(pVM, &pVM->tm.s.StatDoQueuesSchedule, STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Schedule",STAMUNIT_TICKS_PER_CALL, "The scheduling part.");
507 STAM_REG(pVM, &pVM->tm.s.StatDoQueuesRun, STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Run", STAMUNIT_TICKS_PER_CALL, "The run part.");
508
509 STAM_REG(pVM, &pVM->tm.s.StatPollAlreadySet, STAMTYPE_COUNTER, "/TM/PollAlreadySet", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the FF was already set.");
510 STAM_REG(pVM, &pVM->tm.s.StatPollVirtual, STAMTYPE_COUNTER, "/TM/PollHitsVirtual", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL queue.");
511 STAM_REG(pVM, &pVM->tm.s.StatPollVirtualSync, STAMTYPE_COUNTER, "/TM/PollHitsVirtualSync",STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL_SYNC queue.");
512 STAM_REG(pVM, &pVM->tm.s.StatPollMiss, STAMTYPE_COUNTER, "/TM/PollMiss", STAMUNIT_OCCURENCES, "TMTimerPoll calls where nothing had expired.");
513
514 STAM_REG(pVM, &pVM->tm.s.StatPostponedR3, STAMTYPE_COUNTER, "/TM/PostponedR3", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-3.");
515 STAM_REG(pVM, &pVM->tm.s.StatPostponedR0, STAMTYPE_COUNTER, "/TM/PostponedR0", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-0.");
516 STAM_REG(pVM, &pVM->tm.s.StatPostponedGC, STAMTYPE_COUNTER, "/TM/PostponedGC", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in GC.");
517
518 STAM_REG(pVM, &pVM->tm.s.StatScheduleOneGC, STAMTYPE_PROFILE, "/TM/ScheduleOneGC", STAMUNIT_TICKS_PER_CALL, "Profiling the scheduling of one queue during a TMTimer* call in EMT.");
519 STAM_REG(pVM, &pVM->tm.s.StatScheduleOneR0, STAMTYPE_PROFILE, "/TM/ScheduleOneR0", STAMUNIT_TICKS_PER_CALL, "Profiling the scheduling of one queue during a TMTimer* call in EMT.");
520 STAM_REG(pVM, &pVM->tm.s.StatScheduleOneR3, STAMTYPE_PROFILE, "/TM/ScheduleOneR3", STAMUNIT_TICKS_PER_CALL, "Profiling the scheduling of one queue during a TMTimer* call in EMT.");
521 STAM_REG(pVM, &pVM->tm.s.StatScheduleSetFF, STAMTYPE_COUNTER, "/TM/ScheduleSetFF", STAMUNIT_OCCURENCES, "The number of times the timer FF was set instead of doing scheduling.");
522
523 STAM_REG(pVM, &pVM->tm.s.StatTimerSetGC, STAMTYPE_PROFILE, "/TM/TimerSetGC", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in GC.");
524 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR0, STAMTYPE_PROFILE, "/TM/TimerSetR0", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0.");
525 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR3, STAMTYPE_PROFILE, "/TM/TimerSetR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3.");
526
527 STAM_REG(pVM, &pVM->tm.s.StatTimerStopGC, STAMTYPE_PROFILE, "/TM/TimerStopGC", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in GC.");
528 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR0, STAMTYPE_PROFILE, "/TM/TimerStopR0", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-0.");
529 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR3, STAMTYPE_PROFILE, "/TM/TimerStopR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-3.");
530
531 STAM_REG(pVM, &pVM->tm.s.StatVirtualGet, STAMTYPE_COUNTER, "/TM/VirtualGet", STAMUNIT_OCCURENCES, "The number of times TMTimerGet was called when the clock was running.");
532 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualGetSetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGet.");
533 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSync, STAMTYPE_COUNTER, "/TM/VirtualGetSync", STAMUNIT_OCCURENCES, "The number of times TMTimerGetSync was called when the clock was running.");
534 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSyncSetFF,STAMTYPE_COUNTER, "/TM/VirtualGetSyncSetFF",STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGetSync.");
535 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/VirtualPause", STAMUNIT_OCCURENCES, "The number of times TMR3TimerPause was called.");
536 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/VirtualResume", STAMUNIT_OCCURENCES, "The number of times TMR3TimerResume was called.");
537
538 STAM_REG(pVM, &pVM->tm.s.StatTimerCallbackSetFF,STAMTYPE_COUNTER, "/TM/CallbackSetFF", STAMUNIT_OCCURENCES, "The number of times the timer callback set FF.");
539
540
541 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncCatchup, STAMTYPE_PROFILE_ADV, "/TM/VirtualSync/CatchUp", STAMUNIT_TICKS_PER_OCCURENCE, "Counting and measuring the times spent catching up.");
542 STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
543 STAM_REG(pVM, (void *)&pVM->tm.s.u32VirtualSyncCatchUpPercentage, STAMTYPE_U32, "/TM/VirtualSync/CatchUpPercentage", STAMUNIT_PCT, "The catch-up percentage. (+100/100 to get clock multiplier)");
544 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
545 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting,STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUpBeforeStarting", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned before even starting. (Typically debugging++.)");
546 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
547 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
548 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStop, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Stop", STAMUNIT_OCCURENCES, "Times the clock was stopped when calculating the current time before examining the timers.");
549 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
550 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunSlack, STAMTYPE_PROFILE, "/TM/VirtualSync/Run/Slack", STAMUNIT_NS_PER_OCCURENCE, "The scheduling slack. (Catch-up handed out when running timers.)");
551 for (unsigned i = 0; i < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods); i++)
552 {
553 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
554 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
555 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
556 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u64Start, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Start of this period (lag).", "/TM/VirtualSync/Periods/%u/Start", i);
557 }
558
559#endif /* VBOX_WITH_STATISTICS */
560
561 /*
562 * Register info handlers.
563 */
564 DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
565 DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
566 DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
567
568 return VINF_SUCCESS;
569}
570
571
572/**
573 * Checks if the host CPU has a fixed TSC frequency.
574 *
575 * @returns true if it has, false if it hasn't.
576 *
577 * @remark This test doesn't bother with very old CPUs that don't do power
578 * management or any other stuff that might influence the TSC rate.
579 * This isn't currently relevant.
580 */
581static bool tmR3HasFixedTSC(PVM pVM)
582{
583 if (ASMHasCpuId())
584 {
585 uint32_t uEAX, uEBX, uECX, uEDX;
586
587 if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_AMD)
588 {
589 /*
590 * AuthenticAMD - Check for APM support and that TscInvariant is set.
591 *
592 * This test isn't correct with respect to fixed/non-fixed TSC and
593 * older models, but this isn't relevant since the result is currently
594 * only used for making a descision on AMD-V models.
595 */
596 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
597 if (uEAX >= 0x80000007)
598 {
599 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
600
601 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
602 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
603 && pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* no fixed tsc if the gip timer is in async mode */)
604 return true;
605 }
606 }
607 else if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_INTEL)
608 {
609 /*
610 * GenuineIntel - Check the model number.
611 *
612 * This test is lacking in the same way and for the same reasons
613 * as the AMD test above.
614 */
615 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
616 unsigned uModel = (uEAX >> 4) & 0x0f;
617 unsigned uFamily = (uEAX >> 8) & 0x0f;
618 if (uFamily == 0x0f)
619 uFamily += (uEAX >> 20) & 0xff;
620 if (uFamily >= 0x06)
621 uModel += ((uEAX >> 16) & 0x0f) << 4;
622 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
623 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
624 return true;
625 }
626 }
627 return false;
628}
629
630
631/**
632 * Calibrate the CPU tick.
633 *
634 * @returns Number of ticks per second.
635 */
636static uint64_t tmR3CalibrateTSC(PVM pVM)
637{
638 /*
639 * Use GIP when available present.
640 */
641 uint64_t u64Hz;
642 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
643 if ( pGip
644 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC)
645 {
646 unsigned iCpu = pGip->u32Mode != SUPGIPMODE_ASYNC_TSC ? 0 : ASMGetApicId();
647 if (iCpu >= RT_ELEMENTS(pGip->aCPUs))
648 AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
649 else
650 {
651 if (tmR3HasFixedTSC(pVM))
652 /* Sleep a bit to get a more reliable CpuHz value. */
653 RTThreadSleep(32);
654 else
655 {
656 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
657 const uint64_t u64 = RTTimeMilliTS();
658 while ((RTTimeMilliTS() - u64) < 40 /*ms*/)
659 /* nothing */;
660 }
661
662 pGip = g_pSUPGlobalInfoPage;
663 if ( pGip
664 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC
665 && (u64Hz = pGip->aCPUs[iCpu].u64CpuHz)
666 && u64Hz != ~(uint64_t)0)
667 return u64Hz;
668 }
669 }
670
671 /* call this once first to make sure it's initialized. */
672 RTTimeNanoTS();
673
674 /*
675 * Yield the CPU to increase our chances of getting
676 * a correct value.
677 */
678 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
679 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
680 uint64_t au64Samples[5];
681 unsigned i;
682 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
683 {
684 unsigned cMillies;
685 int cTries = 5;
686 uint64_t u64Start = ASMReadTSC();
687 uint64_t u64End;
688 uint64_t StartTS = RTTimeNanoTS();
689 uint64_t EndTS;
690 do
691 {
692 RTThreadSleep(s_auSleep[i]);
693 u64End = ASMReadTSC();
694 EndTS = RTTimeNanoTS();
695 cMillies = (unsigned)((EndTS - StartTS + 500000) / 1000000);
696 } while ( cMillies == 0 /* the sleep may be interrupted... */
697 || (cMillies < 20 && --cTries > 0));
698 uint64_t u64Diff = u64End - u64Start;
699
700 au64Samples[i] = (u64Diff * 1000) / cMillies;
701 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
702 }
703
704 /*
705 * Discard the highest and lowest results and calculate the average.
706 */
707 unsigned iHigh = 0;
708 unsigned iLow = 0;
709 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
710 {
711 if (au64Samples[i] < au64Samples[iLow])
712 iLow = i;
713 if (au64Samples[i] > au64Samples[iHigh])
714 iHigh = i;
715 }
716 au64Samples[iLow] = 0;
717 au64Samples[iHigh] = 0;
718
719 u64Hz = au64Samples[0];
720 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
721 u64Hz += au64Samples[i];
722 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
723
724 return u64Hz;
725}
726
727
728/**
729 * Finalizes the TM initialization.
730 *
731 * @returns VBox status code.
732 * @param pVM The VM to operate on.
733 */
734VMMR3DECL(int) TMR3InitFinalize(PVM pVM)
735{
736 int rc;
737
738 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataGC.pfnBad);
739 AssertRCReturn(rc, rc);
740 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataGC.pfnRediscover);
741 AssertRCReturn(rc, rc);
742 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
743 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawGC);
744 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
745 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawGC);
746 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
747 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawGC);
748 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
749 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawGC);
750 else
751 AssertFatalFailed();
752 AssertRCReturn(rc, rc);
753
754 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
755 AssertRCReturn(rc, rc);
756 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
757 AssertRCReturn(rc, rc);
758 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
759 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawR0);
760 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
761 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawR0);
762 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
763 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawR0);
764 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
765 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawR0);
766 else
767 AssertFatalFailed();
768 AssertRCReturn(rc, rc);
769
770 return VINF_SUCCESS;
771}
772
773
774/**
775 * Applies relocations to data and code managed by this
776 * component. This function will be called at init and
777 * whenever the VMM need to relocate it self inside the GC.
778 *
779 * @param pVM The VM.
780 * @param offDelta Relocation delta relative to old location.
781 */
782VMMR3DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
783{
784 int rc;
785 LogFlow(("TMR3Relocate\n"));
786
787 pVM->tm.s.pvGIPGC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
788 pVM->tm.s.paTimerQueuesGC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
789 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
790
791 pVM->tm.s.VirtualGetRawDataGC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
792 AssertFatal(pVM->tm.s.VirtualGetRawDataGC.pu64Prev);
793 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataGC.pfnBad);
794 AssertFatalRC(rc);
795 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataGC.pfnRediscover);
796 AssertFatalRC(rc);
797
798 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
799 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawGC);
800 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
801 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawGC);
802 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
803 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawGC);
804 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
805 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawGC);
806 else
807 AssertFatalFailed();
808 AssertFatalRC(rc);
809
810 /*
811 * Iterate the timers updating the pVMGC pointers.
812 */
813 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
814 {
815 pTimer->pVMGC = pVM->pVMGC;
816 pTimer->pVMR0 = pVM->pVMR0;
817 }
818}
819
820
821/**
822 * Terminates the TM.
823 *
824 * Termination means cleaning up and freeing all resources,
825 * the VM it self is at this point powered off or suspended.
826 *
827 * @returns VBox status code.
828 * @param pVM The VM to operate on.
829 */
830VMMR3DECL(int) TMR3Term(PVM pVM)
831{
832 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
833 if (pVM->tm.s.pTimer)
834 {
835 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
836 AssertRC(rc);
837 pVM->tm.s.pTimer = NULL;
838 }
839
840 return VINF_SUCCESS;
841}
842
843
844/**
845 * The VM is being reset.
846 *
847 * For the TM component this means that a rescheduling is preformed,
848 * the FF is cleared and but without running the queues. We'll have to
849 * check if this makes sense or not, but it seems like a good idea now....
850 *
851 * @param pVM VM handle.
852 */
853VMMR3DECL(void) TMR3Reset(PVM pVM)
854{
855 LogFlow(("TMR3Reset:\n"));
856 VM_ASSERT_EMT(pVM);
857
858 /*
859 * Abort any pending catch up.
860 * This isn't perfect,
861 */
862 if (pVM->tm.s.fVirtualSyncCatchUp)
863 {
864 const uint64_t offVirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
865 const uint64_t offVirtualSyncNow = TMVirtualSyncGetEx(pVM, false /* don't check timers */);
866 if (pVM->tm.s.fVirtualSyncCatchUp)
867 {
868 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
869
870 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
871 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
872 Assert(offOld <= offNew);
873 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
874 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
875 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
876 LogRel(("TM: Aborting catch-up attempt on reset with a %RU64 ns lag on reset; new total: %RU64 ns\n", offNew - offOld, offNew));
877 }
878 }
879
880 /*
881 * Process the queues.
882 */
883 for (int i = 0; i < TMCLOCK_MAX; i++)
884 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
885#ifdef VBOX_STRICT
886 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
887#endif
888 VM_FF_CLEAR(pVM, VM_FF_TIMER);
889}
890
891
892/**
893 * Resolve a builtin GC symbol.
894 * Called by PDM when loading or relocating GC modules.
895 *
896 * @returns VBox status
897 * @param pVM VM Handle.
898 * @param pszSymbol Symbol to resolv
899 * @param pGCPtrValue Where to store the symbol value.
900 * @remark This has to work before TMR3Relocate() is called.
901 */
902VMMR3DECL(int) TMR3GetImportGC(PVM pVM, const char *pszSymbol, PRTGCPTR pGCPtrValue)
903{
904 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
905 *pGCPtrValue = MMHyperHC2GC(pVM, &pVM->tm.s.pvGIPGC);
906 //else if (..)
907 else
908 return VERR_SYMBOL_NOT_FOUND;
909 return VINF_SUCCESS;
910}
911
912
913/**
914 * Execute state save operation.
915 *
916 * @returns VBox status code.
917 * @param pVM VM Handle.
918 * @param pSSM SSM operation handle.
919 */
920static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
921{
922 LogFlow(("tmR3Save:\n"));
923 Assert(!pVM->tm.s.fTSCTicking);
924 Assert(!pVM->tm.s.fVirtualTicking);
925 Assert(!pVM->tm.s.fVirtualSyncTicking);
926
927 /*
928 * Save the virtual clocks.
929 */
930 /* the virtual clock. */
931 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
932 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
933
934 /* the virtual timer synchronous clock. */
935 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
936 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
937 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
938 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
939 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
940
941 /* real time clock */
942 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
943
944 /* the cpu tick clock. */
945 SSMR3PutU64(pSSM, TMCpuTickGet(pVM));
946 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
947}
948
949
950/**
951 * Execute state load operation.
952 *
953 * @returns VBox status code.
954 * @param pVM VM Handle.
955 * @param pSSM SSM operation handle.
956 * @param u32Version Data layout version.
957 */
958static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
959{
960 LogFlow(("tmR3Load:\n"));
961 Assert(!pVM->tm.s.fTSCTicking);
962 Assert(!pVM->tm.s.fVirtualTicking);
963 Assert(!pVM->tm.s.fVirtualSyncTicking);
964
965 /*
966 * Validate version.
967 */
968 if (u32Version != TM_SAVED_STATE_VERSION)
969 {
970 AssertMsgFailed(("tmR3Load: Invalid version u32Version=%d!\n", u32Version));
971 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
972 }
973
974 /*
975 * Load the virtual clock.
976 */
977 pVM->tm.s.fVirtualTicking = false;
978 /* the virtual clock. */
979 uint64_t u64Hz;
980 int rc = SSMR3GetU64(pSSM, &u64Hz);
981 if (VBOX_FAILURE(rc))
982 return rc;
983 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
984 {
985 AssertMsgFailed(("The virtual clock frequency differs! Saved: %RU64 Binary: %RU64\n",
986 u64Hz, TMCLOCK_FREQ_VIRTUAL));
987 return VERR_SSM_VIRTUAL_CLOCK_HZ;
988 }
989 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
990 pVM->tm.s.u64VirtualOffset = 0;
991
992 /* the virtual timer synchronous clock. */
993 pVM->tm.s.fVirtualSyncTicking = false;
994 uint64_t u64;
995 SSMR3GetU64(pSSM, &u64);
996 pVM->tm.s.u64VirtualSync = u64;
997 SSMR3GetU64(pSSM, &u64);
998 pVM->tm.s.offVirtualSync = u64;
999 SSMR3GetU64(pSSM, &u64);
1000 pVM->tm.s.offVirtualSyncGivenUp = u64;
1001 SSMR3GetU64(pSSM, &u64);
1002 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1003 bool f;
1004 SSMR3GetBool(pSSM, &f);
1005 pVM->tm.s.fVirtualSyncCatchUp = f;
1006
1007 /* the real clock */
1008 rc = SSMR3GetU64(pSSM, &u64Hz);
1009 if (VBOX_FAILURE(rc))
1010 return rc;
1011 if (u64Hz != TMCLOCK_FREQ_REAL)
1012 {
1013 AssertMsgFailed(("The real clock frequency differs! Saved: %RU64 Binary: %RU64\n",
1014 u64Hz, TMCLOCK_FREQ_REAL));
1015 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
1016 }
1017
1018 /* the cpu tick clock. */
1019 pVM->tm.s.fTSCTicking = false;
1020 SSMR3GetU64(pSSM, &pVM->tm.s.u64TSC);
1021 rc = SSMR3GetU64(pSSM, &u64Hz);
1022 if (VBOX_FAILURE(rc))
1023 return rc;
1024 if (pVM->tm.s.fTSCUseRealTSC)
1025 pVM->tm.s.u64TSCOffset = 0; /** @todo TSC restore stuff and HWACC. */
1026 else
1027 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1028 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1029 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1030
1031 /*
1032 * Make sure timers get rescheduled immediately.
1033 */
1034 VM_FF_SET(pVM, VM_FF_TIMER);
1035
1036 return VINF_SUCCESS;
1037}
1038
1039
1040/**
1041 * Internal TMR3TimerCreate worker.
1042 *
1043 * @returns VBox status code.
1044 * @param pVM The VM handle.
1045 * @param enmClock The timer clock.
1046 * @param pszDesc The timer description.
1047 * @param ppTimer Where to store the timer pointer on success.
1048 */
1049static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1050{
1051 VM_ASSERT_EMT(pVM);
1052
1053 /*
1054 * Allocate the timer.
1055 */
1056 PTMTIMERR3 pTimer = NULL;
1057 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1058 {
1059 pTimer = pVM->tm.s.pFree;
1060 pVM->tm.s.pFree = pTimer->pBigNext;
1061 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1062 }
1063
1064 if (!pTimer)
1065 {
1066 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1067 if (VBOX_FAILURE(rc))
1068 return rc;
1069 Log3(("TM: Allocated new timer %p\n", pTimer));
1070 }
1071
1072 /*
1073 * Initialize it.
1074 */
1075 pTimer->u64Expire = 0;
1076 pTimer->enmClock = enmClock;
1077 pTimer->pVMR3 = pVM;
1078 pTimer->pVMR0 = pVM->pVMR0;
1079 pTimer->pVMGC = pVM->pVMGC;
1080 pTimer->enmState = TMTIMERSTATE_STOPPED;
1081 pTimer->offScheduleNext = 0;
1082 pTimer->offNext = 0;
1083 pTimer->offPrev = 0;
1084 pTimer->pszDesc = pszDesc;
1085
1086 /* insert into the list of created timers. */
1087 pTimer->pBigPrev = NULL;
1088 pTimer->pBigNext = pVM->tm.s.pCreated;
1089 pVM->tm.s.pCreated = pTimer;
1090 if (pTimer->pBigNext)
1091 pTimer->pBigNext->pBigPrev = pTimer;
1092#ifdef VBOX_STRICT
1093 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1094#endif
1095
1096 *ppTimer = pTimer;
1097 return VINF_SUCCESS;
1098}
1099
1100
1101/**
1102 * Creates a device timer.
1103 *
1104 * @returns VBox status.
1105 * @param pVM The VM to create the timer in.
1106 * @param pDevIns Device instance.
1107 * @param enmClock The clock to use on this timer.
1108 * @param pfnCallback Callback function.
1109 * @param pszDesc Pointer to description string which must stay around
1110 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1111 * @param ppTimer Where to store the timer on success.
1112 */
1113VMMR3DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1114{
1115 /*
1116 * Allocate and init stuff.
1117 */
1118 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1119 if (VBOX_SUCCESS(rc))
1120 {
1121 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1122 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1123 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1124 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1125 }
1126
1127 return rc;
1128}
1129
1130
1131/**
1132 * Creates a driver timer.
1133 *
1134 * @returns VBox status.
1135 * @param pVM The VM to create the timer in.
1136 * @param pDrvIns Driver instance.
1137 * @param enmClock The clock to use on this timer.
1138 * @param pfnCallback Callback function.
1139 * @param pszDesc Pointer to description string which must stay around
1140 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1141 * @param ppTimer Where to store the timer on success.
1142 */
1143VMMR3DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1144{
1145 /*
1146 * Allocate and init stuff.
1147 */
1148 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1149 if (VBOX_SUCCESS(rc))
1150 {
1151 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1152 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1153 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1154 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1155 }
1156
1157 return rc;
1158}
1159
1160
1161/**
1162 * Creates an internal timer.
1163 *
1164 * @returns VBox status.
1165 * @param pVM The VM to create the timer in.
1166 * @param enmClock The clock to use on this timer.
1167 * @param pfnCallback Callback function.
1168 * @param pvUser User argument to be passed to the callback.
1169 * @param pszDesc Pointer to description string which must stay around
1170 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1171 * @param ppTimer Where to store the timer on success.
1172 */
1173VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1174{
1175 /*
1176 * Allocate and init stuff.
1177 */
1178 PTMTIMER pTimer;
1179 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1180 if (VBOX_SUCCESS(rc))
1181 {
1182 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1183 pTimer->u.Internal.pfnTimer = pfnCallback;
1184 pTimer->u.Internal.pvUser = pvUser;
1185 *ppTimer = pTimer;
1186 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1187 }
1188
1189 return rc;
1190}
1191
1192/**
1193 * Creates an external timer.
1194 *
1195 * @returns Timer handle on success.
1196 * @returns NULL on failure.
1197 * @param pVM The VM to create the timer in.
1198 * @param enmClock The clock to use on this timer.
1199 * @param pfnCallback Callback function.
1200 * @param pvUser User argument.
1201 * @param pszDesc Pointer to description string which must stay around
1202 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1203 */
1204VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1205{
1206 /*
1207 * Allocate and init stuff.
1208 */
1209 PTMTIMERR3 pTimer;
1210 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1211 if (VBOX_SUCCESS(rc))
1212 {
1213 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1214 pTimer->u.External.pfnTimer = pfnCallback;
1215 pTimer->u.External.pvUser = pvUser;
1216 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1217 return pTimer;
1218 }
1219
1220 return NULL;
1221}
1222
1223
1224/**
1225 * Destroy all timers owned by a device.
1226 *
1227 * @returns VBox status.
1228 * @param pVM VM handle.
1229 * @param pDevIns Device which timers should be destroyed.
1230 */
1231VMMR3DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1232{
1233 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1234 if (!pDevIns)
1235 return VERR_INVALID_PARAMETER;
1236
1237 PTMTIMER pCur = pVM->tm.s.pCreated;
1238 while (pCur)
1239 {
1240 PTMTIMER pDestroy = pCur;
1241 pCur = pDestroy->pBigNext;
1242 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1243 && pDestroy->u.Dev.pDevIns == pDevIns)
1244 {
1245 int rc = TMTimerDestroy(pDestroy);
1246 AssertRC(rc);
1247 }
1248 }
1249 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1250 return VINF_SUCCESS;
1251}
1252
1253
1254/**
1255 * Destroy all timers owned by a driver.
1256 *
1257 * @returns VBox status.
1258 * @param pVM VM handle.
1259 * @param pDrvIns Driver which timers should be destroyed.
1260 */
1261VMMR3DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1262{
1263 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1264 if (!pDrvIns)
1265 return VERR_INVALID_PARAMETER;
1266
1267 PTMTIMER pCur = pVM->tm.s.pCreated;
1268 while (pCur)
1269 {
1270 PTMTIMER pDestroy = pCur;
1271 pCur = pDestroy->pBigNext;
1272 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1273 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1274 {
1275 int rc = TMTimerDestroy(pDestroy);
1276 AssertRC(rc);
1277 }
1278 }
1279 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1280 return VINF_SUCCESS;
1281}
1282
1283
1284/**
1285 * Checks if the sync queue has one or more expired timers.
1286 *
1287 * @returns true / false.
1288 *
1289 * @param pVM The VM handle.
1290 * @param enmClock The queue.
1291 */
1292DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1293{
1294 const uint64_t u64Expire = pVM->tm.s.CTXALLSUFF(paTimerQueues)[enmClock].u64Expire;
1295 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1296}
1297
1298
1299/**
1300 * Checks for expired timers in all the queues.
1301 *
1302 * @returns true / false.
1303 * @param pVM The VM handle.
1304 */
1305DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1306{
1307 /*
1308 * Combine the time calculation for the first two since we're not on EMT
1309 * TMVirtualSyncGet only permits EMT.
1310 */
1311 uint64_t u64Now = TMVirtualGet(pVM);
1312 if (pVM->tm.s.CTXALLSUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1313 return true;
1314 u64Now = pVM->tm.s.fVirtualSyncTicking
1315 ? u64Now - pVM->tm.s.offVirtualSync
1316 : pVM->tm.s.u64VirtualSync;
1317 if (pVM->tm.s.CTXALLSUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1318 return true;
1319
1320 /*
1321 * The remaining timers.
1322 */
1323 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1324 return true;
1325 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1326 return true;
1327 return false;
1328}
1329
1330
1331/**
1332 * Schedulation timer callback.
1333 *
1334 * @param pTimer Timer handle.
1335 * @param pvUser VM handle.
1336 * @thread Timer thread.
1337 *
1338 * @remark We cannot do the scheduling and queues running from a timer handler
1339 * since it's not executing in EMT, and even if it was it would be async
1340 * and we wouldn't know the state of the affairs.
1341 * So, we'll just raise the timer FF and force any REM execution to exit.
1342 */
1343static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1344{
1345 PVM pVM = (PVM)pvUser;
1346 AssertCompile(TMCLOCK_MAX == 4);
1347#ifdef DEBUG_Sander /* very annoying, keep it private. */
1348 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
1349 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1350#endif
1351 if ( !VM_FF_ISSET(pVM, VM_FF_TIMER)
1352 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule
1353 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1354 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1355 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1356 || tmR3AnyExpiredTimers(pVM)
1357 )
1358 && !VM_FF_ISSET(pVM, VM_FF_TIMER)
1359 )
1360 {
1361 VM_FF_SET(pVM, VM_FF_TIMER);
1362 REMR3NotifyTimerPending(pVM);
1363 VMR3NotifyFF(pVM, true);
1364 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1365 }
1366}
1367
1368
1369/**
1370 * Schedules and runs any pending timers.
1371 *
1372 * This is normally called from a forced action handler in EMT.
1373 *
1374 * @param pVM The VM to run the timers for.
1375 */
1376VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1377{
1378 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1379 Log2(("TMR3TimerQueuesDo:\n"));
1380
1381 /*
1382 * Process the queues.
1383 */
1384 AssertCompile(TMCLOCK_MAX == 4);
1385
1386 /* TMCLOCK_VIRTUAL_SYNC */
1387 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesSchedule, s1);
1388 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
1389 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s1);
1390 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesRun, r1);
1391 tmR3TimerQueueRunVirtualSync(pVM);
1392 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r1);
1393
1394 /* TMCLOCK_VIRTUAL */
1395 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s1);
1396 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1397 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s2);
1398 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r1);
1399 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1400 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r2);
1401
1402#if 0 /** @todo if ever used, remove this and fix the stam prefixes on TMCLOCK_REAL below. */
1403 /* TMCLOCK_TSC */
1404 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1405 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1406 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s3);
1407 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1408 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1409 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r3);
1410#endif
1411
1412 /* TMCLOCK_REAL */
1413 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1414 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1415 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesSchedule, s3);
1416 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1417 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1418 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesRun, r3);
1419
1420 /* done. */
1421 VM_FF_CLEAR(pVM, VM_FF_TIMER);
1422
1423#ifdef VBOX_STRICT
1424 /* check that we didn't screwup. */
1425 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1426#endif
1427
1428 Log2(("TMR3TimerQueuesDo: returns void\n"));
1429 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1430}
1431
1432
1433/**
1434 * Schedules and runs any pending times in the specified queue.
1435 *
1436 * This is normally called from a forced action handler in EMT.
1437 *
1438 * @param pVM The VM to run the timers for.
1439 * @param pQueue The queue to run.
1440 */
1441static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1442{
1443 VM_ASSERT_EMT(pVM);
1444
1445 /*
1446 * Run timers.
1447 *
1448 * We check the clock once and run all timers which are ACTIVE
1449 * and have an expire time less or equal to the time we read.
1450 *
1451 * N.B. A generic unlink must be applied since other threads
1452 * are allowed to mess with any active timer at any time.
1453 * However, we only allow EMT to handle EXPIRED_PENDING
1454 * timers, thus enabling the timer handler function to
1455 * arm the timer again.
1456 */
1457 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1458 if (!pNext)
1459 return;
1460 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1461 while (pNext && pNext->u64Expire <= u64Now)
1462 {
1463 PTMTIMER pTimer = pNext;
1464 pNext = TMTIMER_GET_NEXT(pTimer);
1465 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1466 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1467 bool fRc;
1468 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1469 if (fRc)
1470 {
1471 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1472
1473 /* unlink */
1474 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1475 if (pPrev)
1476 TMTIMER_SET_NEXT(pPrev, pNext);
1477 else
1478 {
1479 TMTIMER_SET_HEAD(pQueue, pNext);
1480 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1481 }
1482 if (pNext)
1483 TMTIMER_SET_PREV(pNext, pPrev);
1484 pTimer->offNext = 0;
1485 pTimer->offPrev = 0;
1486
1487
1488 /* fire */
1489 switch (pTimer->enmType)
1490 {
1491 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1492 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1493 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1494 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1495 default:
1496 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1497 break;
1498 }
1499
1500 /* change the state if it wasn't changed already in the handler. */
1501 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1502 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1503 }
1504 } /* run loop */
1505}
1506
1507
1508/**
1509 * Schedules and runs any pending times in the timer queue for the
1510 * synchronous virtual clock.
1511 *
1512 * This scheduling is a bit different from the other queues as it need
1513 * to implement the special requirements of the timer synchronous virtual
1514 * clock, thus this 2nd queue run funcion.
1515 *
1516 * @param pVM The VM to run the timers for.
1517 */
1518static void tmR3TimerQueueRunVirtualSync(PVM pVM)
1519{
1520 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
1521 VM_ASSERT_EMT(pVM);
1522
1523 /*
1524 * Any timers?
1525 */
1526 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1527 if (RT_UNLIKELY(!pNext))
1528 {
1529 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.fVirtualTicking);
1530 return;
1531 }
1532 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
1533
1534 /*
1535 * Calculate the time frame for which we will dispatch timers.
1536 *
1537 * We use a time frame ranging from the current sync time (which is most likely the
1538 * same as the head timer) and some configurable period (100000ns) up towards the
1539 * current virtual time. This period might also need to be restricted by the catch-up
1540 * rate so frequent calls to this function won't accelerate the time too much, however
1541 * this will be implemented at a later point if neccessary.
1542 *
1543 * Without this frame we would 1) having to run timers much more frequently
1544 * and 2) lag behind at a steady rate.
1545 */
1546 const uint64_t u64VirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
1547 uint64_t u64Now;
1548 if (!pVM->tm.s.fVirtualSyncTicking)
1549 {
1550 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
1551 u64Now = pVM->tm.s.u64VirtualSync;
1552 Assert(u64Now <= pNext->u64Expire);
1553 }
1554 else
1555 {
1556 /* Calc 'now'. (update order doesn't really matter here) */
1557 uint64_t off = pVM->tm.s.offVirtualSync;
1558 if (pVM->tm.s.fVirtualSyncCatchUp)
1559 {
1560 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
1561 if (RT_LIKELY(!(u64Delta >> 32)))
1562 {
1563 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
1564 if (off > u64Sub + pVM->tm.s.offVirtualSyncGivenUp)
1565 {
1566 off -= u64Sub;
1567 Log4(("TM: %RU64/%RU64: sub %RU64 (run)\n", u64VirtualNow - off, off - pVM->tm.s.offVirtualSyncGivenUp, u64Sub));
1568 }
1569 else
1570 {
1571 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1572 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1573 off = pVM->tm.s.offVirtualSyncGivenUp;
1574 Log4(("TM: %RU64/0: caught up (run)\n", u64VirtualNow));
1575 }
1576 }
1577 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, off);
1578 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow;
1579 }
1580 u64Now = u64VirtualNow - off;
1581
1582 /* Check if stopped by expired timer. */
1583 if (u64Now >= pNext->u64Expire)
1584 {
1585 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
1586 u64Now = pNext->u64Expire;
1587 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, u64Now);
1588 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, false);
1589 Log4(("TM: %RU64/%RU64: exp tmr (run)\n", u64Now, u64VirtualNow - u64Now - pVM->tm.s.offVirtualSyncGivenUp));
1590
1591 }
1592 }
1593
1594 /* calc end of frame. */
1595 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
1596 if (u64Max > u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp)
1597 u64Max = u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp;
1598
1599 /* assert sanity */
1600 Assert(u64Now <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1601 Assert(u64Max <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1602 Assert(u64Now <= u64Max);
1603
1604 /*
1605 * Process the expired timers moving the clock along as we progress.
1606 */
1607#ifdef VBOX_STRICT
1608 uint64_t u64Prev = u64Now; NOREF(u64Prev);
1609#endif
1610 while (pNext && pNext->u64Expire <= u64Max)
1611 {
1612 PTMTIMER pTimer = pNext;
1613 pNext = TMTIMER_GET_NEXT(pTimer);
1614 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1615 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1616 bool fRc;
1617 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1618 if (fRc)
1619 {
1620 /* unlink */
1621 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1622 if (pPrev)
1623 TMTIMER_SET_NEXT(pPrev, pNext);
1624 else
1625 {
1626 TMTIMER_SET_HEAD(pQueue, pNext);
1627 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1628 }
1629 if (pNext)
1630 TMTIMER_SET_PREV(pNext, pPrev);
1631 pTimer->offNext = 0;
1632 pTimer->offPrev = 0;
1633
1634 /* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
1635#ifdef VBOX_STRICT
1636 AssertMsg(pTimer->u64Expire >= u64Prev, ("%RU64 < %RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
1637 u64Prev = pTimer->u64Expire;
1638#endif
1639 ASMAtomicXchgSize(&pVM->tm.s.fVirtualSyncTicking, false);
1640 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
1641
1642 /* fire */
1643 switch (pTimer->enmType)
1644 {
1645 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1646 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1647 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1648 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1649 default:
1650 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1651 break;
1652 }
1653
1654 /* change the state if it wasn't changed already in the handler. */
1655 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1656 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1657 }
1658 } /* run loop */
1659
1660 /*
1661 * Restart the clock if it was stopped to serve any timers,
1662 * and start/adjust catch-up if necessary.
1663 */
1664 if ( !pVM->tm.s.fVirtualSyncTicking
1665 && pVM->tm.s.fVirtualTicking)
1666 {
1667 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
1668
1669 /* calc the slack we've handed out. */
1670 const uint64_t u64VirtualNow2 = TMVirtualGetEx(pVM, false /* don't check timers */);
1671 Assert(u64VirtualNow2 >= u64VirtualNow);
1672 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%RU64 < %RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
1673 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
1674 STAM_STATS({
1675 if (offSlack)
1676 {
1677 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
1678 p->cPeriods++;
1679 p->cTicks += offSlack;
1680 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
1681 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
1682 }
1683 });
1684
1685 /* Let the time run a little bit while we were busy running timers(?). */
1686 uint64_t u64Elapsed;
1687#define MAX_ELAPSED 30000 /* ns */
1688 if (offSlack > MAX_ELAPSED)
1689 u64Elapsed = 0;
1690 else
1691 {
1692 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
1693 if (u64Elapsed > MAX_ELAPSED)
1694 u64Elapsed = MAX_ELAPSED;
1695 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
1696 }
1697#undef MAX_ELAPSED
1698
1699 /* Calc the current offset. */
1700 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
1701 Assert(!(offNew & RT_BIT_64(63)));
1702 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
1703 Assert(!(offLag & RT_BIT_64(63)));
1704
1705 /*
1706 * Deal with starting, adjusting and stopping catchup.
1707 */
1708 if (pVM->tm.s.fVirtualSyncCatchUp)
1709 {
1710 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
1711 {
1712 /* stop */
1713 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1714 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1715 Log4(("TM: %RU64/%RU64: caught up\n", u64VirtualNow2 - offNew, offLag));
1716 }
1717 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1718 {
1719 /* adjust */
1720 unsigned i = 0;
1721 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1722 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1723 i++;
1724 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
1725 {
1726 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
1727 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1728 Log4(("TM: %RU64/%RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1729 }
1730 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
1731 }
1732 else
1733 {
1734 /* give up */
1735 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
1736 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1737 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1738 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1739 Log4(("TM: %RU64/%RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1740 LogRel(("TM: Giving up catch-up attempt at a %RU64 ns lag; new total: %RU64 ns\n", offLag, offNew));
1741 }
1742 }
1743 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
1744 {
1745 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1746 {
1747 /* start */
1748 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
1749 unsigned i = 0;
1750 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1751 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1752 i++;
1753 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
1754 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1755 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
1756 Log4(("TM: %RU64/%RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1757 }
1758 else
1759 {
1760 /* don't bother */
1761 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
1762 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1763 Log4(("TM: %RU64/%RU64: give up\n", u64VirtualNow2 - offNew, offLag));
1764 LogRel(("TM: Not bothering to attempt catching up a %RU64 ns lag; new total: %RU64\n", offLag, offNew));
1765 }
1766 }
1767
1768 /*
1769 * Update the offset and restart the clock.
1770 */
1771 Assert(!(offNew & RT_BIT_64(63)));
1772 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, offNew);
1773 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, true);
1774 }
1775}
1776
1777
1778/**
1779 * Saves the state of a timer to a saved state.
1780 *
1781 * @returns VBox status.
1782 * @param pTimer Timer to save.
1783 * @param pSSM Save State Manager handle.
1784 */
1785VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1786{
1787 LogFlow(("TMR3TimerSave: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1788 switch (pTimer->enmState)
1789 {
1790 case TMTIMERSTATE_STOPPED:
1791 case TMTIMERSTATE_PENDING_STOP:
1792 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1793 return SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_STOP);
1794
1795 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1796 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1797 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
1798 if (!RTThreadYield())
1799 RTThreadSleep(1);
1800 /* fall thru */
1801 case TMTIMERSTATE_ACTIVE:
1802 case TMTIMERSTATE_PENDING_SCHEDULE:
1803 case TMTIMERSTATE_PENDING_RESCHEDULE:
1804 SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_SCHEDULE);
1805 return SSMR3PutU64(pSSM, pTimer->u64Expire);
1806
1807 case TMTIMERSTATE_EXPIRED:
1808 case TMTIMERSTATE_PENDING_DESTROY:
1809 case TMTIMERSTATE_PENDING_STOP_DESTROY:
1810 case TMTIMERSTATE_FREE:
1811 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
1812 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
1813 }
1814
1815 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
1816 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
1817}
1818
1819
1820/**
1821 * Loads the state of a timer from a saved state.
1822 *
1823 * @returns VBox status.
1824 * @param pTimer Timer to restore.
1825 * @param pSSM Save State Manager handle.
1826 */
1827VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1828{
1829 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
1830 LogFlow(("TMR3TimerLoad: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1831
1832 /*
1833 * Load the state and validate it.
1834 */
1835 uint8_t u8State;
1836 int rc = SSMR3GetU8(pSSM, &u8State);
1837 if (VBOX_FAILURE(rc))
1838 return rc;
1839 TMTIMERSTATE enmState = (TMTIMERSTATE)u8State;
1840 if ( enmState != TMTIMERSTATE_PENDING_STOP
1841 && enmState != TMTIMERSTATE_PENDING_SCHEDULE
1842 && enmState != TMTIMERSTATE_PENDING_STOP_SCHEDULE)
1843 {
1844 AssertMsgFailed(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1845 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
1846 }
1847
1848 if (enmState == TMTIMERSTATE_PENDING_SCHEDULE)
1849 {
1850 /*
1851 * Load the expire time.
1852 */
1853 uint64_t u64Expire;
1854 rc = SSMR3GetU64(pSSM, &u64Expire);
1855 if (VBOX_FAILURE(rc))
1856 return rc;
1857
1858 /*
1859 * Set it.
1860 */
1861 Log(("enmState=%d %s u64Expire=%llu\n", enmState, tmTimerState(enmState), u64Expire));
1862 rc = TMTimerSet(pTimer, u64Expire);
1863 }
1864 else
1865 {
1866 /*
1867 * Stop it.
1868 */
1869 Log(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1870 rc = TMTimerStop(pTimer);
1871 }
1872
1873 /*
1874 * On failure set SSM status.
1875 */
1876 if (VBOX_FAILURE(rc))
1877 rc = SSMR3HandleSetStatus(pSSM, rc);
1878 return rc;
1879}
1880
1881
1882/**
1883 * Get the real world UTC time adjusted for VM lag.
1884 *
1885 * @returns pTime.
1886 * @param pVM The VM instance.
1887 * @param pTime Where to store the time.
1888 */
1889VMMR3DECL(PRTTIMESPEC) TMR3UTCNow(PVM pVM, PRTTIMESPEC pTime)
1890{
1891 RTTimeNow(pTime);
1892 RTTimeSpecSubNano(pTime, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp);
1893 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
1894 return pTime;
1895}
1896
1897
1898/**
1899 * Display all timers.
1900 *
1901 * @param pVM VM Handle.
1902 * @param pHlp The info helpers.
1903 * @param pszArgs Arguments, ignored.
1904 */
1905static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1906{
1907 NOREF(pszArgs);
1908 pHlp->pfnPrintf(pHlp,
1909 "Timers (pVM=%p)\n"
1910 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1911 pVM,
1912 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1913 sizeof(int32_t) * 2, "offNext ",
1914 sizeof(int32_t) * 2, "offPrev ",
1915 sizeof(int32_t) * 2, "offSched ",
1916 "Time",
1917 "Expire",
1918 "State");
1919 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1920 {
1921 pHlp->pfnPrintf(pHlp,
1922 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1923 pTimer,
1924 pTimer->offNext,
1925 pTimer->offPrev,
1926 pTimer->offScheduleNext,
1927 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
1928 TMTimerGet(pTimer),
1929 pTimer->u64Expire,
1930 tmTimerState(pTimer->enmState),
1931 pTimer->pszDesc);
1932 }
1933}
1934
1935
1936/**
1937 * Display all active timers.
1938 *
1939 * @param pVM VM Handle.
1940 * @param pHlp The info helpers.
1941 * @param pszArgs Arguments, ignored.
1942 */
1943static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1944{
1945 NOREF(pszArgs);
1946 pHlp->pfnPrintf(pHlp,
1947 "Active Timers (pVM=%p)\n"
1948 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1949 pVM,
1950 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1951 sizeof(int32_t) * 2, "offNext ",
1952 sizeof(int32_t) * 2, "offPrev ",
1953 sizeof(int32_t) * 2, "offSched ",
1954 "Time",
1955 "Expire",
1956 "State");
1957 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
1958 {
1959 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
1960 pTimer;
1961 pTimer = TMTIMER_GET_NEXT(pTimer))
1962 {
1963 pHlp->pfnPrintf(pHlp,
1964 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1965 pTimer,
1966 pTimer->offNext,
1967 pTimer->offPrev,
1968 pTimer->offScheduleNext,
1969 pTimer->enmClock == TMCLOCK_REAL
1970 ? "Real "
1971 : pTimer->enmClock == TMCLOCK_VIRTUAL
1972 ? "Virt "
1973 : pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC
1974 ? "VrSy "
1975 : "TSC ",
1976 TMTimerGet(pTimer),
1977 pTimer->u64Expire,
1978 tmTimerState(pTimer->enmState),
1979 pTimer->pszDesc);
1980 }
1981 }
1982}
1983
1984
1985/**
1986 * Display all clocks.
1987 *
1988 * @param pVM VM Handle.
1989 * @param pHlp The info helpers.
1990 * @param pszArgs Arguments, ignored.
1991 */
1992static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1993{
1994 NOREF(pszArgs);
1995
1996 /*
1997 * Read the times first to avoid more than necessary time variation.
1998 */
1999 const uint64_t u64TSC = TMCpuTickGet(pVM);
2000 const uint64_t u64Virtual = TMVirtualGet(pVM);
2001 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
2002 const uint64_t u64Real = TMRealGet(pVM);
2003
2004 /*
2005 * TSC
2006 */
2007 pHlp->pfnPrintf(pHlp,
2008 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
2009 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
2010 pVM->tm.s.fTSCTicking ? "ticking" : "paused",
2011 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
2012 if (pVM->tm.s.fTSCUseRealTSC)
2013 {
2014 pHlp->pfnPrintf(pHlp, " - real tsc");
2015 if (pVM->tm.s.u64TSCOffset)
2016 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.u64TSCOffset);
2017 }
2018 else
2019 pHlp->pfnPrintf(pHlp, " - virtual clock");
2020 pHlp->pfnPrintf(pHlp, "\n");
2021
2022 /*
2023 * virtual
2024 */
2025 pHlp->pfnPrintf(pHlp,
2026 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
2027 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
2028 pVM->tm.s.fVirtualTicking ? "ticking" : "paused");
2029 if (pVM->tm.s.fVirtualWarpDrive)
2030 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
2031 pHlp->pfnPrintf(pHlp, "\n");
2032
2033 /*
2034 * virtual sync
2035 */
2036 pHlp->pfnPrintf(pHlp,
2037 "VirtSync: %18RU64 (%#016RX64) %s%s",
2038 u64VirtualSync, u64VirtualSync,
2039 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
2040 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
2041 if (pVM->tm.s.offVirtualSync)
2042 {
2043 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
2044 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
2045 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
2046 }
2047 pHlp->pfnPrintf(pHlp, "\n");
2048
2049 /*
2050 * real
2051 */
2052 pHlp->pfnPrintf(pHlp,
2053 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
2054 u64Real, u64Real, TMRealGetFreq(pVM));
2055}
2056
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