VirtualBox

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

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

TM: extended the statistics to get an idea about the normal catchup rate.

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