VirtualBox

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

Last change on this file since 12559 was 12549, checked in by vboxsync, 16 years ago

VMM: Implemented a TSC mode where it's tied to execution and halt (optionally). Fixes #3182.

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