VirtualBox

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

Last change on this file since 6300 was 6300, checked in by vboxsync, 17 years ago

no "\n", ".", nor "!" at end of an error message

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