VirtualBox

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

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

Statistics for rdtsc intercepts

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 86.8 KB
Line 
1/* $Id: TM.cpp 13572 2008-10-27 11:02:33Z 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 STAM_REG(pVM, &pVM->tm.s.StatTSCNotFixed, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotFixed", STAMUNIT_OCCURENCES, "The number of times TMCpuTickCanUseRealTSC forced rdtsc intercept.");
541 STAM_REG(pVM, &pVM->tm.s.StatTSCNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotTicking", STAMUNIT_OCCURENCES, "The number of times TMCpuTickCanUseRealTSC forced rdtsc intercept.");
542 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchup, STAMTYPE_COUNTER, "/TM/TSC/Intercept/Catchup", STAMUNIT_OCCURENCES, "The number of times TMCpuTickCanUseRealTSC forced rdtsc intercept.");
543 STAM_REG(pVM, &pVM->tm.s.StatTSCWarp, STAMTYPE_COUNTER, "/TM/TSC/Intercept/Warp", STAMUNIT_OCCURENCES, "The number of times TMCpuTickCanUseRealTSC forced rdtsc intercept.");
544 STAM_REG(pVM, &pVM->tm.s.StatTSCSyncNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/SyncNotTicking", STAMUNIT_OCCURENCES, "The number of times TMCpuTickCanUseRealTSC forced rdtsc intercept.");
545
546
547 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.");
548 STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
549 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)");
550 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
551 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++.)");
552 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
553 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
554 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.");
555 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
556 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.)");
557 for (unsigned i = 0; i < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods); i++)
558 {
559 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
560 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
561 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
562 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);
563 }
564
565#endif /* VBOX_WITH_STATISTICS */
566
567 /*
568 * Register info handlers.
569 */
570 DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
571 DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
572 DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
573
574 return VINF_SUCCESS;
575}
576
577
578/**
579 * Checks if the host CPU has a fixed TSC frequency.
580 *
581 * @returns true if it has, false if it hasn't.
582 *
583 * @remark This test doesn't bother with very old CPUs that don't do power
584 * management or any other stuff that might influence the TSC rate.
585 * This isn't currently relevant.
586 */
587static bool tmR3HasFixedTSC(PVM pVM)
588{
589 if (ASMHasCpuId())
590 {
591 uint32_t uEAX, uEBX, uECX, uEDX;
592
593 if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_AMD)
594 {
595 /*
596 * AuthenticAMD - Check for APM support and that TscInvariant is set.
597 *
598 * This test isn't correct with respect to fixed/non-fixed TSC and
599 * older models, but this isn't relevant since the result is currently
600 * only used for making a descision on AMD-V models.
601 */
602 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
603 if (uEAX >= 0x80000007)
604 {
605 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
606
607 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
608 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
609 && pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* no fixed tsc if the gip timer is in async mode */)
610 return true;
611 }
612 }
613 else if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_INTEL)
614 {
615 /*
616 * GenuineIntel - Check the model number.
617 *
618 * This test is lacking in the same way and for the same reasons
619 * as the AMD test above.
620 */
621 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
622 unsigned uModel = (uEAX >> 4) & 0x0f;
623 unsigned uFamily = (uEAX >> 8) & 0x0f;
624 if (uFamily == 0x0f)
625 uFamily += (uEAX >> 20) & 0xff;
626 if (uFamily >= 0x06)
627 uModel += ((uEAX >> 16) & 0x0f) << 4;
628 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
629 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
630 return true;
631 }
632 }
633 return false;
634}
635
636
637/**
638 * Calibrate the CPU tick.
639 *
640 * @returns Number of ticks per second.
641 */
642static uint64_t tmR3CalibrateTSC(PVM pVM)
643{
644 /*
645 * Use GIP when available present.
646 */
647 uint64_t u64Hz;
648 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
649 if ( pGip
650 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC)
651 {
652 unsigned iCpu = pGip->u32Mode != SUPGIPMODE_ASYNC_TSC ? 0 : ASMGetApicId();
653 if (iCpu >= RT_ELEMENTS(pGip->aCPUs))
654 AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
655 else
656 {
657 if (tmR3HasFixedTSC(pVM))
658 /* Sleep a bit to get a more reliable CpuHz value. */
659 RTThreadSleep(32);
660 else
661 {
662 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
663 const uint64_t u64 = RTTimeMilliTS();
664 while ((RTTimeMilliTS() - u64) < 40 /*ms*/)
665 /* nothing */;
666 }
667
668 pGip = g_pSUPGlobalInfoPage;
669 if ( pGip
670 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC
671 && (u64Hz = pGip->aCPUs[iCpu].u64CpuHz)
672 && u64Hz != ~(uint64_t)0)
673 return u64Hz;
674 }
675 }
676
677 /* call this once first to make sure it's initialized. */
678 RTTimeNanoTS();
679
680 /*
681 * Yield the CPU to increase our chances of getting
682 * a correct value.
683 */
684 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
685 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
686 uint64_t au64Samples[5];
687 unsigned i;
688 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
689 {
690 unsigned cMillies;
691 int cTries = 5;
692 uint64_t u64Start = ASMReadTSC();
693 uint64_t u64End;
694 uint64_t StartTS = RTTimeNanoTS();
695 uint64_t EndTS;
696 do
697 {
698 RTThreadSleep(s_auSleep[i]);
699 u64End = ASMReadTSC();
700 EndTS = RTTimeNanoTS();
701 cMillies = (unsigned)((EndTS - StartTS + 500000) / 1000000);
702 } while ( cMillies == 0 /* the sleep may be interrupted... */
703 || (cMillies < 20 && --cTries > 0));
704 uint64_t u64Diff = u64End - u64Start;
705
706 au64Samples[i] = (u64Diff * 1000) / cMillies;
707 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
708 }
709
710 /*
711 * Discard the highest and lowest results and calculate the average.
712 */
713 unsigned iHigh = 0;
714 unsigned iLow = 0;
715 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
716 {
717 if (au64Samples[i] < au64Samples[iLow])
718 iLow = i;
719 if (au64Samples[i] > au64Samples[iHigh])
720 iHigh = i;
721 }
722 au64Samples[iLow] = 0;
723 au64Samples[iHigh] = 0;
724
725 u64Hz = au64Samples[0];
726 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
727 u64Hz += au64Samples[i];
728 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
729
730 return u64Hz;
731}
732
733
734/**
735 * Finalizes the TM initialization.
736 *
737 * @returns VBox status code.
738 * @param pVM The VM to operate on.
739 */
740VMMR3DECL(int) TMR3InitFinalize(PVM pVM)
741{
742 int rc;
743
744 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataGC.pfnBad);
745 AssertRCReturn(rc, rc);
746 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataGC.pfnRediscover);
747 AssertRCReturn(rc, rc);
748 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
749 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawGC);
750 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
751 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawGC);
752 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
753 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawGC);
754 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
755 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawGC);
756 else
757 AssertFatalFailed();
758 AssertRCReturn(rc, rc);
759
760 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
761 AssertRCReturn(rc, rc);
762 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
763 AssertRCReturn(rc, rc);
764 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
765 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawR0);
766 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
767 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawR0);
768 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
769 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawR0);
770 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
771 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawR0);
772 else
773 AssertFatalFailed();
774 AssertRCReturn(rc, rc);
775
776 return VINF_SUCCESS;
777}
778
779
780/**
781 * Applies relocations to data and code managed by this
782 * component. This function will be called at init and
783 * whenever the VMM need to relocate it self inside the GC.
784 *
785 * @param pVM The VM.
786 * @param offDelta Relocation delta relative to old location.
787 */
788VMMR3DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
789{
790 int rc;
791 LogFlow(("TMR3Relocate\n"));
792
793 pVM->tm.s.pvGIPGC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
794 pVM->tm.s.paTimerQueuesGC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
795 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
796
797 pVM->tm.s.VirtualGetRawDataGC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
798 AssertFatal(pVM->tm.s.VirtualGetRawDataGC.pu64Prev);
799 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataGC.pfnBad);
800 AssertFatalRC(rc);
801 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataGC.pfnRediscover);
802 AssertFatalRC(rc);
803
804 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
805 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawGC);
806 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
807 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawGC);
808 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
809 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawGC);
810 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
811 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawGC);
812 else
813 AssertFatalFailed();
814 AssertFatalRC(rc);
815
816 /*
817 * Iterate the timers updating the pVMGC pointers.
818 */
819 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
820 {
821 pTimer->pVMGC = pVM->pVMGC;
822 pTimer->pVMR0 = pVM->pVMR0;
823 }
824}
825
826
827/**
828 * Terminates the TM.
829 *
830 * Termination means cleaning up and freeing all resources,
831 * the VM it self is at this point powered off or suspended.
832 *
833 * @returns VBox status code.
834 * @param pVM The VM to operate on.
835 */
836VMMR3DECL(int) TMR3Term(PVM pVM)
837{
838 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
839 if (pVM->tm.s.pTimer)
840 {
841 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
842 AssertRC(rc);
843 pVM->tm.s.pTimer = NULL;
844 }
845
846 return VINF_SUCCESS;
847}
848
849
850/**
851 * The VM is being reset.
852 *
853 * For the TM component this means that a rescheduling is preformed,
854 * the FF is cleared and but without running the queues. We'll have to
855 * check if this makes sense or not, but it seems like a good idea now....
856 *
857 * @param pVM VM handle.
858 */
859VMMR3DECL(void) TMR3Reset(PVM pVM)
860{
861 LogFlow(("TMR3Reset:\n"));
862 VM_ASSERT_EMT(pVM);
863
864 /*
865 * Abort any pending catch up.
866 * This isn't perfect,
867 */
868 if (pVM->tm.s.fVirtualSyncCatchUp)
869 {
870 const uint64_t offVirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
871 const uint64_t offVirtualSyncNow = TMVirtualSyncGetEx(pVM, false /* don't check timers */);
872 if (pVM->tm.s.fVirtualSyncCatchUp)
873 {
874 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
875
876 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
877 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
878 Assert(offOld <= offNew);
879 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
880 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
881 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
882 LogRel(("TM: Aborting catch-up attempt on reset with a %RU64 ns lag on reset; new total: %RU64 ns\n", offNew - offOld, offNew));
883 }
884 }
885
886 /*
887 * Process the queues.
888 */
889 for (int i = 0; i < TMCLOCK_MAX; i++)
890 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
891#ifdef VBOX_STRICT
892 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
893#endif
894 VM_FF_CLEAR(pVM, VM_FF_TIMER);
895}
896
897
898/**
899 * Resolve a builtin GC symbol.
900 * Called by PDM when loading or relocating GC modules.
901 *
902 * @returns VBox status
903 * @param pVM VM Handle.
904 * @param pszSymbol Symbol to resolv
905 * @param pGCPtrValue Where to store the symbol value.
906 * @remark This has to work before TMR3Relocate() is called.
907 */
908VMMR3DECL(int) TMR3GetImportGC(PVM pVM, const char *pszSymbol, PRTGCPTR pGCPtrValue)
909{
910 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
911 *pGCPtrValue = MMHyperHC2GC(pVM, &pVM->tm.s.pvGIPGC);
912 //else if (..)
913 else
914 return VERR_SYMBOL_NOT_FOUND;
915 return VINF_SUCCESS;
916}
917
918
919/**
920 * Execute state save operation.
921 *
922 * @returns VBox status code.
923 * @param pVM VM Handle.
924 * @param pSSM SSM operation handle.
925 */
926static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
927{
928 LogFlow(("tmR3Save:\n"));
929 Assert(!pVM->tm.s.fTSCTicking);
930 Assert(!pVM->tm.s.fVirtualTicking);
931 Assert(!pVM->tm.s.fVirtualSyncTicking);
932
933 /*
934 * Save the virtual clocks.
935 */
936 /* the virtual clock. */
937 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
938 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
939
940 /* the virtual timer synchronous clock. */
941 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
942 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
943 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
944 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
945 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
946
947 /* real time clock */
948 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
949
950 /* the cpu tick clock. */
951 SSMR3PutU64(pSSM, TMCpuTickGet(pVM));
952 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
953}
954
955
956/**
957 * Execute state load operation.
958 *
959 * @returns VBox status code.
960 * @param pVM VM Handle.
961 * @param pSSM SSM operation handle.
962 * @param u32Version Data layout version.
963 */
964static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
965{
966 LogFlow(("tmR3Load:\n"));
967 Assert(!pVM->tm.s.fTSCTicking);
968 Assert(!pVM->tm.s.fVirtualTicking);
969 Assert(!pVM->tm.s.fVirtualSyncTicking);
970
971 /*
972 * Validate version.
973 */
974 if (u32Version != TM_SAVED_STATE_VERSION)
975 {
976 AssertMsgFailed(("tmR3Load: Invalid version u32Version=%d!\n", u32Version));
977 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
978 }
979
980 /*
981 * Load the virtual clock.
982 */
983 pVM->tm.s.fVirtualTicking = false;
984 /* the virtual clock. */
985 uint64_t u64Hz;
986 int rc = SSMR3GetU64(pSSM, &u64Hz);
987 if (VBOX_FAILURE(rc))
988 return rc;
989 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
990 {
991 AssertMsgFailed(("The virtual clock frequency differs! Saved: %RU64 Binary: %RU64\n",
992 u64Hz, TMCLOCK_FREQ_VIRTUAL));
993 return VERR_SSM_VIRTUAL_CLOCK_HZ;
994 }
995 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
996 pVM->tm.s.u64VirtualOffset = 0;
997
998 /* the virtual timer synchronous clock. */
999 pVM->tm.s.fVirtualSyncTicking = false;
1000 uint64_t u64;
1001 SSMR3GetU64(pSSM, &u64);
1002 pVM->tm.s.u64VirtualSync = u64;
1003 SSMR3GetU64(pSSM, &u64);
1004 pVM->tm.s.offVirtualSync = u64;
1005 SSMR3GetU64(pSSM, &u64);
1006 pVM->tm.s.offVirtualSyncGivenUp = u64;
1007 SSMR3GetU64(pSSM, &u64);
1008 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1009 bool f;
1010 SSMR3GetBool(pSSM, &f);
1011 pVM->tm.s.fVirtualSyncCatchUp = f;
1012
1013 /* the real clock */
1014 rc = SSMR3GetU64(pSSM, &u64Hz);
1015 if (VBOX_FAILURE(rc))
1016 return rc;
1017 if (u64Hz != TMCLOCK_FREQ_REAL)
1018 {
1019 AssertMsgFailed(("The real clock frequency differs! Saved: %RU64 Binary: %RU64\n",
1020 u64Hz, TMCLOCK_FREQ_REAL));
1021 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
1022 }
1023
1024 /* the cpu tick clock. */
1025 pVM->tm.s.fTSCTicking = false;
1026 SSMR3GetU64(pSSM, &pVM->tm.s.u64TSC);
1027 rc = SSMR3GetU64(pSSM, &u64Hz);
1028 if (VBOX_FAILURE(rc))
1029 return rc;
1030 if (pVM->tm.s.fTSCUseRealTSC)
1031 pVM->tm.s.u64TSCOffset = 0; /** @todo TSC restore stuff and HWACC. */
1032 else
1033 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1034 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1035 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1036
1037 /*
1038 * Make sure timers get rescheduled immediately.
1039 */
1040 VM_FF_SET(pVM, VM_FF_TIMER);
1041
1042 return VINF_SUCCESS;
1043}
1044
1045
1046/**
1047 * Internal TMR3TimerCreate worker.
1048 *
1049 * @returns VBox status code.
1050 * @param pVM The VM handle.
1051 * @param enmClock The timer clock.
1052 * @param pszDesc The timer description.
1053 * @param ppTimer Where to store the timer pointer on success.
1054 */
1055static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1056{
1057 VM_ASSERT_EMT(pVM);
1058
1059 /*
1060 * Allocate the timer.
1061 */
1062 PTMTIMERR3 pTimer = NULL;
1063 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1064 {
1065 pTimer = pVM->tm.s.pFree;
1066 pVM->tm.s.pFree = pTimer->pBigNext;
1067 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1068 }
1069
1070 if (!pTimer)
1071 {
1072 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1073 if (VBOX_FAILURE(rc))
1074 return rc;
1075 Log3(("TM: Allocated new timer %p\n", pTimer));
1076 }
1077
1078 /*
1079 * Initialize it.
1080 */
1081 pTimer->u64Expire = 0;
1082 pTimer->enmClock = enmClock;
1083 pTimer->pVMR3 = pVM;
1084 pTimer->pVMR0 = pVM->pVMR0;
1085 pTimer->pVMGC = pVM->pVMGC;
1086 pTimer->enmState = TMTIMERSTATE_STOPPED;
1087 pTimer->offScheduleNext = 0;
1088 pTimer->offNext = 0;
1089 pTimer->offPrev = 0;
1090 pTimer->pszDesc = pszDesc;
1091
1092 /* insert into the list of created timers. */
1093 pTimer->pBigPrev = NULL;
1094 pTimer->pBigNext = pVM->tm.s.pCreated;
1095 pVM->tm.s.pCreated = pTimer;
1096 if (pTimer->pBigNext)
1097 pTimer->pBigNext->pBigPrev = pTimer;
1098#ifdef VBOX_STRICT
1099 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1100#endif
1101
1102 *ppTimer = pTimer;
1103 return VINF_SUCCESS;
1104}
1105
1106
1107/**
1108 * Creates a device timer.
1109 *
1110 * @returns VBox status.
1111 * @param pVM The VM to create the timer in.
1112 * @param pDevIns Device instance.
1113 * @param enmClock The clock to use on this timer.
1114 * @param pfnCallback Callback function.
1115 * @param pszDesc Pointer to description string which must stay around
1116 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1117 * @param ppTimer Where to store the timer on success.
1118 */
1119VMMR3DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1120{
1121 /*
1122 * Allocate and init stuff.
1123 */
1124 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1125 if (VBOX_SUCCESS(rc))
1126 {
1127 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1128 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1129 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1130 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1131 }
1132
1133 return rc;
1134}
1135
1136
1137/**
1138 * Creates a driver timer.
1139 *
1140 * @returns VBox status.
1141 * @param pVM The VM to create the timer in.
1142 * @param pDrvIns Driver instance.
1143 * @param enmClock The clock to use on this timer.
1144 * @param pfnCallback Callback function.
1145 * @param pszDesc Pointer to description string which must stay around
1146 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1147 * @param ppTimer Where to store the timer on success.
1148 */
1149VMMR3DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1150{
1151 /*
1152 * Allocate and init stuff.
1153 */
1154 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1155 if (VBOX_SUCCESS(rc))
1156 {
1157 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1158 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1159 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1160 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1161 }
1162
1163 return rc;
1164}
1165
1166
1167/**
1168 * Creates an internal timer.
1169 *
1170 * @returns VBox status.
1171 * @param pVM The VM to create the timer in.
1172 * @param enmClock The clock to use on this timer.
1173 * @param pfnCallback Callback function.
1174 * @param pvUser User argument to be passed to the callback.
1175 * @param pszDesc Pointer to description string which must stay around
1176 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1177 * @param ppTimer Where to store the timer on success.
1178 */
1179VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1180{
1181 /*
1182 * Allocate and init stuff.
1183 */
1184 PTMTIMER pTimer;
1185 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1186 if (VBOX_SUCCESS(rc))
1187 {
1188 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1189 pTimer->u.Internal.pfnTimer = pfnCallback;
1190 pTimer->u.Internal.pvUser = pvUser;
1191 *ppTimer = pTimer;
1192 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1193 }
1194
1195 return rc;
1196}
1197
1198/**
1199 * Creates an external timer.
1200 *
1201 * @returns Timer handle on success.
1202 * @returns NULL on failure.
1203 * @param pVM The VM to create the timer in.
1204 * @param enmClock The clock to use on this timer.
1205 * @param pfnCallback Callback function.
1206 * @param pvUser User argument.
1207 * @param pszDesc Pointer to description string which must stay around
1208 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1209 */
1210VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1211{
1212 /*
1213 * Allocate and init stuff.
1214 */
1215 PTMTIMERR3 pTimer;
1216 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1217 if (VBOX_SUCCESS(rc))
1218 {
1219 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1220 pTimer->u.External.pfnTimer = pfnCallback;
1221 pTimer->u.External.pvUser = pvUser;
1222 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1223 return pTimer;
1224 }
1225
1226 return NULL;
1227}
1228
1229
1230/**
1231 * Destroy all timers owned by a device.
1232 *
1233 * @returns VBox status.
1234 * @param pVM VM handle.
1235 * @param pDevIns Device which timers should be destroyed.
1236 */
1237VMMR3DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1238{
1239 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1240 if (!pDevIns)
1241 return VERR_INVALID_PARAMETER;
1242
1243 PTMTIMER pCur = pVM->tm.s.pCreated;
1244 while (pCur)
1245 {
1246 PTMTIMER pDestroy = pCur;
1247 pCur = pDestroy->pBigNext;
1248 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1249 && pDestroy->u.Dev.pDevIns == pDevIns)
1250 {
1251 int rc = TMTimerDestroy(pDestroy);
1252 AssertRC(rc);
1253 }
1254 }
1255 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1256 return VINF_SUCCESS;
1257}
1258
1259
1260/**
1261 * Destroy all timers owned by a driver.
1262 *
1263 * @returns VBox status.
1264 * @param pVM VM handle.
1265 * @param pDrvIns Driver which timers should be destroyed.
1266 */
1267VMMR3DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1268{
1269 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1270 if (!pDrvIns)
1271 return VERR_INVALID_PARAMETER;
1272
1273 PTMTIMER pCur = pVM->tm.s.pCreated;
1274 while (pCur)
1275 {
1276 PTMTIMER pDestroy = pCur;
1277 pCur = pDestroy->pBigNext;
1278 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1279 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1280 {
1281 int rc = TMTimerDestroy(pDestroy);
1282 AssertRC(rc);
1283 }
1284 }
1285 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1286 return VINF_SUCCESS;
1287}
1288
1289
1290/**
1291 * Checks if the sync queue has one or more expired timers.
1292 *
1293 * @returns true / false.
1294 *
1295 * @param pVM The VM handle.
1296 * @param enmClock The queue.
1297 */
1298DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1299{
1300 const uint64_t u64Expire = pVM->tm.s.CTXALLSUFF(paTimerQueues)[enmClock].u64Expire;
1301 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1302}
1303
1304
1305/**
1306 * Checks for expired timers in all the queues.
1307 *
1308 * @returns true / false.
1309 * @param pVM The VM handle.
1310 */
1311DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1312{
1313 /*
1314 * Combine the time calculation for the first two since we're not on EMT
1315 * TMVirtualSyncGet only permits EMT.
1316 */
1317 uint64_t u64Now = TMVirtualGet(pVM);
1318 if (pVM->tm.s.CTXALLSUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1319 return true;
1320 u64Now = pVM->tm.s.fVirtualSyncTicking
1321 ? u64Now - pVM->tm.s.offVirtualSync
1322 : pVM->tm.s.u64VirtualSync;
1323 if (pVM->tm.s.CTXALLSUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1324 return true;
1325
1326 /*
1327 * The remaining timers.
1328 */
1329 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1330 return true;
1331 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1332 return true;
1333 return false;
1334}
1335
1336
1337/**
1338 * Schedulation timer callback.
1339 *
1340 * @param pTimer Timer handle.
1341 * @param pvUser VM handle.
1342 * @thread Timer thread.
1343 *
1344 * @remark We cannot do the scheduling and queues running from a timer handler
1345 * since it's not executing in EMT, and even if it was it would be async
1346 * and we wouldn't know the state of the affairs.
1347 * So, we'll just raise the timer FF and force any REM execution to exit.
1348 */
1349static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1350{
1351 PVM pVM = (PVM)pvUser;
1352 AssertCompile(TMCLOCK_MAX == 4);
1353#ifdef DEBUG_Sander /* very annoying, keep it private. */
1354 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
1355 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1356#endif
1357 if ( !VM_FF_ISSET(pVM, VM_FF_TIMER)
1358 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule
1359 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1360 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1361 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1362 || tmR3AnyExpiredTimers(pVM)
1363 )
1364 && !VM_FF_ISSET(pVM, VM_FF_TIMER)
1365 )
1366 {
1367 VM_FF_SET(pVM, VM_FF_TIMER);
1368 REMR3NotifyTimerPending(pVM);
1369 VMR3NotifyFF(pVM, true);
1370 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1371 }
1372}
1373
1374
1375/**
1376 * Schedules and runs any pending timers.
1377 *
1378 * This is normally called from a forced action handler in EMT.
1379 *
1380 * @param pVM The VM to run the timers for.
1381 */
1382VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1383{
1384 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1385 Log2(("TMR3TimerQueuesDo:\n"));
1386
1387 /*
1388 * Process the queues.
1389 */
1390 AssertCompile(TMCLOCK_MAX == 4);
1391
1392 /* TMCLOCK_VIRTUAL_SYNC */
1393 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesSchedule, s1);
1394 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
1395 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s1);
1396 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesRun, r1);
1397 tmR3TimerQueueRunVirtualSync(pVM);
1398 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r1);
1399
1400 /* TMCLOCK_VIRTUAL */
1401 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s1);
1402 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1403 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s2);
1404 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r1);
1405 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1406 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r2);
1407
1408#if 0 /** @todo if ever used, remove this and fix the stam prefixes on TMCLOCK_REAL below. */
1409 /* TMCLOCK_TSC */
1410 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1411 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1412 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s3);
1413 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1414 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1415 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r3);
1416#endif
1417
1418 /* TMCLOCK_REAL */
1419 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1420 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1421 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesSchedule, s3);
1422 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1423 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1424 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesRun, r3);
1425
1426 /* done. */
1427 VM_FF_CLEAR(pVM, VM_FF_TIMER);
1428
1429#ifdef VBOX_STRICT
1430 /* check that we didn't screwup. */
1431 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1432#endif
1433
1434 Log2(("TMR3TimerQueuesDo: returns void\n"));
1435 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1436}
1437
1438
1439/**
1440 * Schedules and runs any pending times in the specified queue.
1441 *
1442 * This is normally called from a forced action handler in EMT.
1443 *
1444 * @param pVM The VM to run the timers for.
1445 * @param pQueue The queue to run.
1446 */
1447static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1448{
1449 VM_ASSERT_EMT(pVM);
1450
1451 /*
1452 * Run timers.
1453 *
1454 * We check the clock once and run all timers which are ACTIVE
1455 * and have an expire time less or equal to the time we read.
1456 *
1457 * N.B. A generic unlink must be applied since other threads
1458 * are allowed to mess with any active timer at any time.
1459 * However, we only allow EMT to handle EXPIRED_PENDING
1460 * timers, thus enabling the timer handler function to
1461 * arm the timer again.
1462 */
1463 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1464 if (!pNext)
1465 return;
1466 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1467 while (pNext && pNext->u64Expire <= u64Now)
1468 {
1469 PTMTIMER pTimer = pNext;
1470 pNext = TMTIMER_GET_NEXT(pTimer);
1471 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1472 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1473 bool fRc;
1474 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1475 if (fRc)
1476 {
1477 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1478
1479 /* unlink */
1480 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1481 if (pPrev)
1482 TMTIMER_SET_NEXT(pPrev, pNext);
1483 else
1484 {
1485 TMTIMER_SET_HEAD(pQueue, pNext);
1486 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1487 }
1488 if (pNext)
1489 TMTIMER_SET_PREV(pNext, pPrev);
1490 pTimer->offNext = 0;
1491 pTimer->offPrev = 0;
1492
1493
1494 /* fire */
1495 switch (pTimer->enmType)
1496 {
1497 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1498 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1499 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1500 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1501 default:
1502 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1503 break;
1504 }
1505
1506 /* change the state if it wasn't changed already in the handler. */
1507 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1508 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1509 }
1510 } /* run loop */
1511}
1512
1513
1514/**
1515 * Schedules and runs any pending times in the timer queue for the
1516 * synchronous virtual clock.
1517 *
1518 * This scheduling is a bit different from the other queues as it need
1519 * to implement the special requirements of the timer synchronous virtual
1520 * clock, thus this 2nd queue run funcion.
1521 *
1522 * @param pVM The VM to run the timers for.
1523 */
1524static void tmR3TimerQueueRunVirtualSync(PVM pVM)
1525{
1526 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
1527 VM_ASSERT_EMT(pVM);
1528
1529 /*
1530 * Any timers?
1531 */
1532 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1533 if (RT_UNLIKELY(!pNext))
1534 {
1535 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.fVirtualTicking);
1536 return;
1537 }
1538 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
1539
1540 /*
1541 * Calculate the time frame for which we will dispatch timers.
1542 *
1543 * We use a time frame ranging from the current sync time (which is most likely the
1544 * same as the head timer) and some configurable period (100000ns) up towards the
1545 * current virtual time. This period might also need to be restricted by the catch-up
1546 * rate so frequent calls to this function won't accelerate the time too much, however
1547 * this will be implemented at a later point if neccessary.
1548 *
1549 * Without this frame we would 1) having to run timers much more frequently
1550 * and 2) lag behind at a steady rate.
1551 */
1552 const uint64_t u64VirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
1553 uint64_t u64Now;
1554 if (!pVM->tm.s.fVirtualSyncTicking)
1555 {
1556 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
1557 u64Now = pVM->tm.s.u64VirtualSync;
1558 Assert(u64Now <= pNext->u64Expire);
1559 }
1560 else
1561 {
1562 /* Calc 'now'. (update order doesn't really matter here) */
1563 uint64_t off = pVM->tm.s.offVirtualSync;
1564 if (pVM->tm.s.fVirtualSyncCatchUp)
1565 {
1566 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
1567 if (RT_LIKELY(!(u64Delta >> 32)))
1568 {
1569 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
1570 if (off > u64Sub + pVM->tm.s.offVirtualSyncGivenUp)
1571 {
1572 off -= u64Sub;
1573 Log4(("TM: %RU64/%RU64: sub %RU64 (run)\n", u64VirtualNow - off, off - pVM->tm.s.offVirtualSyncGivenUp, u64Sub));
1574 }
1575 else
1576 {
1577 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1578 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1579 off = pVM->tm.s.offVirtualSyncGivenUp;
1580 Log4(("TM: %RU64/0: caught up (run)\n", u64VirtualNow));
1581 }
1582 }
1583 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, off);
1584 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow;
1585 }
1586 u64Now = u64VirtualNow - off;
1587
1588 /* Check if stopped by expired timer. */
1589 if (u64Now >= pNext->u64Expire)
1590 {
1591 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
1592 u64Now = pNext->u64Expire;
1593 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, u64Now);
1594 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, false);
1595 Log4(("TM: %RU64/%RU64: exp tmr (run)\n", u64Now, u64VirtualNow - u64Now - pVM->tm.s.offVirtualSyncGivenUp));
1596
1597 }
1598 }
1599
1600 /* calc end of frame. */
1601 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
1602 if (u64Max > u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp)
1603 u64Max = u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp;
1604
1605 /* assert sanity */
1606 Assert(u64Now <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1607 Assert(u64Max <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1608 Assert(u64Now <= u64Max);
1609
1610 /*
1611 * Process the expired timers moving the clock along as we progress.
1612 */
1613#ifdef VBOX_STRICT
1614 uint64_t u64Prev = u64Now; NOREF(u64Prev);
1615#endif
1616 while (pNext && pNext->u64Expire <= u64Max)
1617 {
1618 PTMTIMER pTimer = pNext;
1619 pNext = TMTIMER_GET_NEXT(pTimer);
1620 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1621 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1622 bool fRc;
1623 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1624 if (fRc)
1625 {
1626 /* unlink */
1627 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1628 if (pPrev)
1629 TMTIMER_SET_NEXT(pPrev, pNext);
1630 else
1631 {
1632 TMTIMER_SET_HEAD(pQueue, pNext);
1633 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1634 }
1635 if (pNext)
1636 TMTIMER_SET_PREV(pNext, pPrev);
1637 pTimer->offNext = 0;
1638 pTimer->offPrev = 0;
1639
1640 /* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
1641#ifdef VBOX_STRICT
1642 AssertMsg(pTimer->u64Expire >= u64Prev, ("%RU64 < %RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
1643 u64Prev = pTimer->u64Expire;
1644#endif
1645 ASMAtomicXchgSize(&pVM->tm.s.fVirtualSyncTicking, false);
1646 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
1647
1648 /* fire */
1649 switch (pTimer->enmType)
1650 {
1651 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1652 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1653 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1654 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1655 default:
1656 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1657 break;
1658 }
1659
1660 /* change the state if it wasn't changed already in the handler. */
1661 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1662 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1663 }
1664 } /* run loop */
1665
1666 /*
1667 * Restart the clock if it was stopped to serve any timers,
1668 * and start/adjust catch-up if necessary.
1669 */
1670 if ( !pVM->tm.s.fVirtualSyncTicking
1671 && pVM->tm.s.fVirtualTicking)
1672 {
1673 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
1674
1675 /* calc the slack we've handed out. */
1676 const uint64_t u64VirtualNow2 = TMVirtualGetEx(pVM, false /* don't check timers */);
1677 Assert(u64VirtualNow2 >= u64VirtualNow);
1678 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%RU64 < %RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
1679 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
1680 STAM_STATS({
1681 if (offSlack)
1682 {
1683 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
1684 p->cPeriods++;
1685 p->cTicks += offSlack;
1686 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
1687 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
1688 }
1689 });
1690
1691 /* Let the time run a little bit while we were busy running timers(?). */
1692 uint64_t u64Elapsed;
1693#define MAX_ELAPSED 30000 /* ns */
1694 if (offSlack > MAX_ELAPSED)
1695 u64Elapsed = 0;
1696 else
1697 {
1698 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
1699 if (u64Elapsed > MAX_ELAPSED)
1700 u64Elapsed = MAX_ELAPSED;
1701 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
1702 }
1703#undef MAX_ELAPSED
1704
1705 /* Calc the current offset. */
1706 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
1707 Assert(!(offNew & RT_BIT_64(63)));
1708 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
1709 Assert(!(offLag & RT_BIT_64(63)));
1710
1711 /*
1712 * Deal with starting, adjusting and stopping catchup.
1713 */
1714 if (pVM->tm.s.fVirtualSyncCatchUp)
1715 {
1716 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
1717 {
1718 /* stop */
1719 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1720 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1721 Log4(("TM: %RU64/%RU64: caught up\n", u64VirtualNow2 - offNew, offLag));
1722 }
1723 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1724 {
1725 /* adjust */
1726 unsigned i = 0;
1727 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1728 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1729 i++;
1730 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
1731 {
1732 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
1733 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1734 Log4(("TM: %RU64/%RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1735 }
1736 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
1737 }
1738 else
1739 {
1740 /* give up */
1741 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
1742 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1743 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1744 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1745 Log4(("TM: %RU64/%RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1746 LogRel(("TM: Giving up catch-up attempt at a %RU64 ns lag; new total: %RU64 ns\n", offLag, offNew));
1747 }
1748 }
1749 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
1750 {
1751 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1752 {
1753 /* start */
1754 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
1755 unsigned i = 0;
1756 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1757 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1758 i++;
1759 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
1760 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1761 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
1762 Log4(("TM: %RU64/%RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1763 }
1764 else
1765 {
1766 /* don't bother */
1767 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
1768 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1769 Log4(("TM: %RU64/%RU64: give up\n", u64VirtualNow2 - offNew, offLag));
1770 LogRel(("TM: Not bothering to attempt catching up a %RU64 ns lag; new total: %RU64\n", offLag, offNew));
1771 }
1772 }
1773
1774 /*
1775 * Update the offset and restart the clock.
1776 */
1777 Assert(!(offNew & RT_BIT_64(63)));
1778 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, offNew);
1779 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, true);
1780 }
1781}
1782
1783
1784/**
1785 * Saves the state of a timer to a saved state.
1786 *
1787 * @returns VBox status.
1788 * @param pTimer Timer to save.
1789 * @param pSSM Save State Manager handle.
1790 */
1791VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1792{
1793 LogFlow(("TMR3TimerSave: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1794 switch (pTimer->enmState)
1795 {
1796 case TMTIMERSTATE_STOPPED:
1797 case TMTIMERSTATE_PENDING_STOP:
1798 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1799 return SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_STOP);
1800
1801 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1802 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1803 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
1804 if (!RTThreadYield())
1805 RTThreadSleep(1);
1806 /* fall thru */
1807 case TMTIMERSTATE_ACTIVE:
1808 case TMTIMERSTATE_PENDING_SCHEDULE:
1809 case TMTIMERSTATE_PENDING_RESCHEDULE:
1810 SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_SCHEDULE);
1811 return SSMR3PutU64(pSSM, pTimer->u64Expire);
1812
1813 case TMTIMERSTATE_EXPIRED:
1814 case TMTIMERSTATE_PENDING_DESTROY:
1815 case TMTIMERSTATE_PENDING_STOP_DESTROY:
1816 case TMTIMERSTATE_FREE:
1817 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
1818 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
1819 }
1820
1821 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
1822 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
1823}
1824
1825
1826/**
1827 * Loads the state of a timer from a saved state.
1828 *
1829 * @returns VBox status.
1830 * @param pTimer Timer to restore.
1831 * @param pSSM Save State Manager handle.
1832 */
1833VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1834{
1835 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
1836 LogFlow(("TMR3TimerLoad: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1837
1838 /*
1839 * Load the state and validate it.
1840 */
1841 uint8_t u8State;
1842 int rc = SSMR3GetU8(pSSM, &u8State);
1843 if (VBOX_FAILURE(rc))
1844 return rc;
1845 TMTIMERSTATE enmState = (TMTIMERSTATE)u8State;
1846 if ( enmState != TMTIMERSTATE_PENDING_STOP
1847 && enmState != TMTIMERSTATE_PENDING_SCHEDULE
1848 && enmState != TMTIMERSTATE_PENDING_STOP_SCHEDULE)
1849 {
1850 AssertMsgFailed(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1851 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
1852 }
1853
1854 if (enmState == TMTIMERSTATE_PENDING_SCHEDULE)
1855 {
1856 /*
1857 * Load the expire time.
1858 */
1859 uint64_t u64Expire;
1860 rc = SSMR3GetU64(pSSM, &u64Expire);
1861 if (VBOX_FAILURE(rc))
1862 return rc;
1863
1864 /*
1865 * Set it.
1866 */
1867 Log(("enmState=%d %s u64Expire=%llu\n", enmState, tmTimerState(enmState), u64Expire));
1868 rc = TMTimerSet(pTimer, u64Expire);
1869 }
1870 else
1871 {
1872 /*
1873 * Stop it.
1874 */
1875 Log(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1876 rc = TMTimerStop(pTimer);
1877 }
1878
1879 /*
1880 * On failure set SSM status.
1881 */
1882 if (VBOX_FAILURE(rc))
1883 rc = SSMR3HandleSetStatus(pSSM, rc);
1884 return rc;
1885}
1886
1887
1888/**
1889 * Get the real world UTC time adjusted for VM lag.
1890 *
1891 * @returns pTime.
1892 * @param pVM The VM instance.
1893 * @param pTime Where to store the time.
1894 */
1895VMMR3DECL(PRTTIMESPEC) TMR3UTCNow(PVM pVM, PRTTIMESPEC pTime)
1896{
1897 RTTimeNow(pTime);
1898 RTTimeSpecSubNano(pTime, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp);
1899 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
1900 return pTime;
1901}
1902
1903
1904/**
1905 * Display all timers.
1906 *
1907 * @param pVM VM Handle.
1908 * @param pHlp The info helpers.
1909 * @param pszArgs Arguments, ignored.
1910 */
1911static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1912{
1913 NOREF(pszArgs);
1914 pHlp->pfnPrintf(pHlp,
1915 "Timers (pVM=%p)\n"
1916 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1917 pVM,
1918 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1919 sizeof(int32_t) * 2, "offNext ",
1920 sizeof(int32_t) * 2, "offPrev ",
1921 sizeof(int32_t) * 2, "offSched ",
1922 "Time",
1923 "Expire",
1924 "State");
1925 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1926 {
1927 pHlp->pfnPrintf(pHlp,
1928 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1929 pTimer,
1930 pTimer->offNext,
1931 pTimer->offPrev,
1932 pTimer->offScheduleNext,
1933 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
1934 TMTimerGet(pTimer),
1935 pTimer->u64Expire,
1936 tmTimerState(pTimer->enmState),
1937 pTimer->pszDesc);
1938 }
1939}
1940
1941
1942/**
1943 * Display all active timers.
1944 *
1945 * @param pVM VM Handle.
1946 * @param pHlp The info helpers.
1947 * @param pszArgs Arguments, ignored.
1948 */
1949static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1950{
1951 NOREF(pszArgs);
1952 pHlp->pfnPrintf(pHlp,
1953 "Active Timers (pVM=%p)\n"
1954 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1955 pVM,
1956 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1957 sizeof(int32_t) * 2, "offNext ",
1958 sizeof(int32_t) * 2, "offPrev ",
1959 sizeof(int32_t) * 2, "offSched ",
1960 "Time",
1961 "Expire",
1962 "State");
1963 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
1964 {
1965 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
1966 pTimer;
1967 pTimer = TMTIMER_GET_NEXT(pTimer))
1968 {
1969 pHlp->pfnPrintf(pHlp,
1970 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1971 pTimer,
1972 pTimer->offNext,
1973 pTimer->offPrev,
1974 pTimer->offScheduleNext,
1975 pTimer->enmClock == TMCLOCK_REAL
1976 ? "Real "
1977 : pTimer->enmClock == TMCLOCK_VIRTUAL
1978 ? "Virt "
1979 : pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC
1980 ? "VrSy "
1981 : "TSC ",
1982 TMTimerGet(pTimer),
1983 pTimer->u64Expire,
1984 tmTimerState(pTimer->enmState),
1985 pTimer->pszDesc);
1986 }
1987 }
1988}
1989
1990
1991/**
1992 * Display all clocks.
1993 *
1994 * @param pVM VM Handle.
1995 * @param pHlp The info helpers.
1996 * @param pszArgs Arguments, ignored.
1997 */
1998static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1999{
2000 NOREF(pszArgs);
2001
2002 /*
2003 * Read the times first to avoid more than necessary time variation.
2004 */
2005 const uint64_t u64TSC = TMCpuTickGet(pVM);
2006 const uint64_t u64Virtual = TMVirtualGet(pVM);
2007 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
2008 const uint64_t u64Real = TMRealGet(pVM);
2009
2010 /*
2011 * TSC
2012 */
2013 pHlp->pfnPrintf(pHlp,
2014 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
2015 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
2016 pVM->tm.s.fTSCTicking ? "ticking" : "paused",
2017 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
2018 if (pVM->tm.s.fTSCUseRealTSC)
2019 {
2020 pHlp->pfnPrintf(pHlp, " - real tsc");
2021 if (pVM->tm.s.u64TSCOffset)
2022 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.u64TSCOffset);
2023 }
2024 else
2025 pHlp->pfnPrintf(pHlp, " - virtual clock");
2026 pHlp->pfnPrintf(pHlp, "\n");
2027
2028 /*
2029 * virtual
2030 */
2031 pHlp->pfnPrintf(pHlp,
2032 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
2033 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
2034 pVM->tm.s.fVirtualTicking ? "ticking" : "paused");
2035 if (pVM->tm.s.fVirtualWarpDrive)
2036 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
2037 pHlp->pfnPrintf(pHlp, "\n");
2038
2039 /*
2040 * virtual sync
2041 */
2042 pHlp->pfnPrintf(pHlp,
2043 "VirtSync: %18RU64 (%#016RX64) %s%s",
2044 u64VirtualSync, u64VirtualSync,
2045 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
2046 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
2047 if (pVM->tm.s.offVirtualSync)
2048 {
2049 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
2050 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
2051 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
2052 }
2053 pHlp->pfnPrintf(pHlp, "\n");
2054
2055 /*
2056 * real
2057 */
2058 pHlp->pfnPrintf(pHlp,
2059 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
2060 u64Real, u64Real, TMRealGetFreq(pVM));
2061}
2062
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