VirtualBox

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

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

Attempt at fixing (most of) the concurrency issues in tmTimerQueueScheduleOne.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 84.0 KB
Line 
1/* $Id: TM.cpp 6085 2007-12-15 15:03:19Z 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)\n"),
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\". (%Vrc)"), rc);
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\". (%Vrc)"), rc);
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\". (%Vrc)"), rc);
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\". (%Vrc)"), rc);
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\". (%Vrc)"), rc);
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\". (%Vrc)"), rc);
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 "\". (%Vrc)"), rc); \
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 "\". (%Vrc)"), rc); \
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\". (%Vrc)"), rc);
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\". (%Vrc)"), rc);
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\", rc=%Vrc.\n"), rc);
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.fRunningTimers
1317 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule
1318 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1319 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1320 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1321 || tmR3AnyExpiredTimers(pVM)
1322 )
1323 && !VM_FF_ISSET(pVM, VM_FF_TIMER)
1324 && !pVM->tm.s.fRunningTimers
1325 )
1326 {
1327 VM_FF_SET(pVM, VM_FF_TIMER);
1328 REMR3NotifyTimerPending(pVM);
1329 VMR3NotifyFF(pVM, true);
1330 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1331 }
1332}
1333
1334
1335/**
1336 * Schedules and runs any pending timers.
1337 *
1338 * This is normally called from a forced action handler in EMT.
1339 *
1340 * @param pVM The VM to run the timers for.
1341 */
1342TMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1343{
1344 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1345 Log2(("TMR3TimerQueuesDo:\n"));
1346
1347 /*
1348 * Process the queues.
1349 */
1350 AssertCompile(TMCLOCK_MAX == 4);
1351 ASMAtomicXchgBool(&pVM->tm.s.fRunningTimers, true);
1352 VM_FF_CLEAR(pVM, VM_FF_TIMER);
1353
1354 /* TMCLOCK_VIRTUAL_SYNC */
1355 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesSchedule, s1);
1356 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
1357 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s1);
1358 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesRun, r1);
1359 tmR3TimerQueueRunVirtualSync(pVM);
1360 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r1);
1361
1362 /* TMCLOCK_VIRTUAL */
1363 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s1);
1364 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1365 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s2);
1366 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r1);
1367 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1368 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r2);
1369
1370#if 0 /** @todo if ever used, remove this and fix the stam prefixes on TMCLOCK_REAL below. */
1371 /* TMCLOCK_TSC */
1372 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1373 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1374 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s3);
1375 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1376 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1377 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r3);
1378#endif
1379
1380 /* TMCLOCK_REAL */
1381 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1382 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1383 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesSchedule, s3);
1384 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1385 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1386 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesRun, r3);
1387
1388 /* done. */
1389 ASMAtomicXchgBool(&pVM->tm.s.fRunningTimers, false);
1390
1391#ifdef VBOX_STRICT
1392 /* check that we didn't screwup. */
1393 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1394#endif
1395
1396 Log2(("TMR3TimerQueuesDo: returns void\n"));
1397 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1398}
1399
1400
1401/**
1402 * Schedules and runs any pending times in the specified queue.
1403 *
1404 * This is normally called from a forced action handler in EMT.
1405 *
1406 * @param pVM The VM to run the timers for.
1407 * @param pQueue The queue to run.
1408 */
1409static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1410{
1411 VM_ASSERT_EMT(pVM);
1412
1413 /*
1414 * Run timers.
1415 *
1416 * We check the clock once and run all timers which are ACTIVE
1417 * and have an expire time less or equal to the time we read.
1418 *
1419 * N.B. A generic unlink must be applied since other threads
1420 * are allowed to mess with any active timer at any time.
1421 * However, we only allow EMT to handle EXPIRED_PENDING
1422 * timers, thus enabling the timer handler function to
1423 * arm the timer again.
1424 */
1425 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1426 if (!pNext)
1427 return;
1428 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1429 while (pNext && pNext->u64Expire <= u64Now)
1430 {
1431 PTMTIMER pTimer = pNext;
1432 pNext = TMTIMER_GET_NEXT(pTimer);
1433 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1434 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1435 bool fRc;
1436 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1437 if (fRc)
1438 {
1439 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1440
1441 /* unlink */
1442 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1443 if (pPrev)
1444 TMTIMER_SET_NEXT(pPrev, pNext);
1445 else
1446 {
1447 TMTIMER_SET_HEAD(pQueue, pNext);
1448 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1449 }
1450 if (pNext)
1451 TMTIMER_SET_PREV(pNext, pPrev);
1452 pTimer->offNext = 0;
1453 pTimer->offPrev = 0;
1454
1455
1456 /* fire */
1457 switch (pTimer->enmType)
1458 {
1459 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1460 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1461 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1462 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1463 default:
1464 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1465 break;
1466 }
1467
1468 /* change the state if it wasn't changed already in the handler. */
1469 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1470 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1471 }
1472 } /* run loop */
1473}
1474
1475
1476/**
1477 * Schedules and runs any pending times in the timer queue for the
1478 * synchronous virtual clock.
1479 *
1480 * This scheduling is a bit different from the other queues as it need
1481 * to implement the special requirements of the timer synchronous virtual
1482 * clock, thus this 2nd queue run funcion.
1483 *
1484 * @param pVM The VM to run the timers for.
1485 */
1486static void tmR3TimerQueueRunVirtualSync(PVM pVM)
1487{
1488 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
1489 VM_ASSERT_EMT(pVM);
1490
1491 /*
1492 * Any timers?
1493 */
1494 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1495 if (RT_UNLIKELY(!pNext))
1496 {
1497 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.fVirtualTicking);
1498 return;
1499 }
1500 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
1501
1502 /*
1503 * Calculate the time frame for which we will dispatch timers.
1504 *
1505 * We use a time frame ranging from the current sync time (which is most likely the
1506 * same as the head timer) and some configurable period (100000ns) up towards the
1507 * current virtual time. This period might also need to be restricted by the catch-up
1508 * rate so frequent calls to this function won't accelerate the time too much, however
1509 * this will be implemented at a later point if neccessary.
1510 *
1511 * Without this frame we would 1) having to run timers much more frequently
1512 * and 2) lag behind at a steady rate.
1513 */
1514 const uint64_t u64VirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
1515 uint64_t u64Now;
1516 if (!pVM->tm.s.fVirtualSyncTicking)
1517 {
1518 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
1519 u64Now = pVM->tm.s.u64VirtualSync;
1520 Assert(u64Now <= pNext->u64Expire);
1521 }
1522 else
1523 {
1524 /* Calc 'now'. (update order doesn't really matter here) */
1525 uint64_t off = pVM->tm.s.offVirtualSync;
1526 if (pVM->tm.s.fVirtualSyncCatchUp)
1527 {
1528 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
1529 if (RT_LIKELY(!(u64Delta >> 32)))
1530 {
1531 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
1532 if (off > u64Sub + pVM->tm.s.offVirtualSyncGivenUp)
1533 {
1534 off -= u64Sub;
1535 Log4(("TM: %RU64/%RU64: sub %RU64 (run)\n", u64VirtualNow - off, off - pVM->tm.s.offVirtualSyncGivenUp, u64Sub));
1536 }
1537 else
1538 {
1539 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1540 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1541 off = pVM->tm.s.offVirtualSyncGivenUp;
1542 Log4(("TM: %RU64/0: caught up (run)\n", u64VirtualNow));
1543 }
1544 }
1545 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, off);
1546 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow;
1547 }
1548 u64Now = u64VirtualNow - off;
1549
1550 /* Check if stopped by expired timer. */
1551 if (u64Now >= pNext->u64Expire)
1552 {
1553 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
1554 u64Now = pNext->u64Expire;
1555 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, u64Now);
1556 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, false);
1557 Log4(("TM: %RU64/%RU64: exp tmr (run)\n", u64Now, u64VirtualNow - u64Now - pVM->tm.s.offVirtualSyncGivenUp));
1558
1559 }
1560 }
1561
1562 /* calc end of frame. */
1563 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
1564 if (u64Max > u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp)
1565 u64Max = u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp;
1566
1567 /* assert sanity */
1568 Assert(u64Now <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1569 Assert(u64Max <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1570 Assert(u64Now <= u64Max);
1571
1572 /*
1573 * Process the expired timers moving the clock along as we progress.
1574 */
1575#ifdef VBOX_STRICT
1576 uint64_t u64Prev = u64Now; NOREF(u64Prev);
1577#endif
1578 while (pNext && pNext->u64Expire <= u64Max)
1579 {
1580 PTMTIMER pTimer = pNext;
1581 pNext = TMTIMER_GET_NEXT(pTimer);
1582 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1583 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1584 bool fRc;
1585 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1586 if (fRc)
1587 {
1588 /* unlink */
1589 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1590 if (pPrev)
1591 TMTIMER_SET_NEXT(pPrev, pNext);
1592 else
1593 {
1594 TMTIMER_SET_HEAD(pQueue, pNext);
1595 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1596 }
1597 if (pNext)
1598 TMTIMER_SET_PREV(pNext, pPrev);
1599 pTimer->offNext = 0;
1600 pTimer->offPrev = 0;
1601
1602 /* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
1603#ifdef VBOX_STRICT
1604 AssertMsg(pTimer->u64Expire >= u64Prev, ("%RU64 < %RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
1605 u64Prev = pTimer->u64Expire;
1606#endif
1607 ASMAtomicXchgSize(&pVM->tm.s.fVirtualSyncTicking, false);
1608 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
1609
1610 /* fire */
1611 switch (pTimer->enmType)
1612 {
1613 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1614 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1615 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1616 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1617 default:
1618 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1619 break;
1620 }
1621
1622 /* change the state if it wasn't changed already in the handler. */
1623 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1624 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1625 }
1626 } /* run loop */
1627
1628 /*
1629 * Restart the clock if it was stopped to serve any timers,
1630 * and start/adjust catch-up if necessary.
1631 */
1632 if ( !pVM->tm.s.fVirtualSyncTicking
1633 && pVM->tm.s.fVirtualTicking)
1634 {
1635 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
1636
1637 /* calc the slack we've handed out. */
1638 const uint64_t u64VirtualNow2 = TMVirtualGetEx(pVM, false /* don't check timers */);
1639 Assert(u64VirtualNow2 >= u64VirtualNow);
1640 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%RU64 < %RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
1641 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
1642 STAM_STATS({
1643 if (offSlack)
1644 {
1645 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
1646 p->cPeriods++;
1647 p->cTicks += offSlack;
1648 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
1649 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
1650 }
1651 });
1652
1653 /* Let the time run a little bit while we were busy running timers(?). */
1654 uint64_t u64Elapsed;
1655#define MAX_ELAPSED 30000 /* ns */
1656 if (offSlack > MAX_ELAPSED)
1657 u64Elapsed = 0;
1658 else
1659 {
1660 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
1661 if (u64Elapsed > MAX_ELAPSED)
1662 u64Elapsed = MAX_ELAPSED;
1663 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
1664 }
1665#undef MAX_ELAPSED
1666
1667 /* Calc the current offset. */
1668 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
1669 Assert(!(offNew & RT_BIT_64(63)));
1670 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
1671 Assert(!(offLag & RT_BIT_64(63)));
1672
1673 /*
1674 * Deal with starting, adjusting and stopping catchup.
1675 */
1676 if (pVM->tm.s.fVirtualSyncCatchUp)
1677 {
1678 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
1679 {
1680 /* stop */
1681 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1682 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1683 Log4(("TM: %RU64/%RU64: caught up\n", u64VirtualNow2 - offNew, offLag));
1684 }
1685 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1686 {
1687 /* adjust */
1688 unsigned i = 0;
1689 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1690 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1691 i++;
1692 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
1693 {
1694 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
1695 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1696 Log4(("TM: %RU64/%RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1697 }
1698 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
1699 }
1700 else
1701 {
1702 /* give up */
1703 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
1704 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1705 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1706 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1707 Log4(("TM: %RU64/%RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1708 LogRel(("TM: Giving up catch-up attempt at a %RU64 ns lag; new total: %RU64 ns\n", offLag, offNew));
1709 }
1710 }
1711 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
1712 {
1713 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1714 {
1715 /* start */
1716 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
1717 unsigned i = 0;
1718 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1719 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1720 i++;
1721 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
1722 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1723 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
1724 Log4(("TM: %RU64/%RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1725 }
1726 else
1727 {
1728 /* don't bother */
1729 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
1730 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1731 Log4(("TM: %RU64/%RU64: give up\n", u64VirtualNow2 - offNew, offLag));
1732 LogRel(("TM: Not bothering to attempt catching up a %RU64 ns lag; new total: %RU64\n", offLag, offNew));
1733 }
1734 }
1735
1736 /*
1737 * Update the offset and restart the clock.
1738 */
1739 Assert(!(offNew & RT_BIT_64(63)));
1740 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, offNew);
1741 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, true);
1742 }
1743}
1744
1745
1746/**
1747 * Saves the state of a timer to a saved state.
1748 *
1749 * @returns VBox status.
1750 * @param pTimer Timer to save.
1751 * @param pSSM Save State Manager handle.
1752 */
1753TMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1754{
1755 LogFlow(("TMR3TimerSave: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1756 switch (pTimer->enmState)
1757 {
1758 case TMTIMERSTATE_STOPPED:
1759 case TMTIMERSTATE_PENDING_STOP:
1760 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1761 return SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_STOP);
1762
1763 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1764 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1765 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
1766 if (!RTThreadYield())
1767 RTThreadSleep(1);
1768 /* fall thru */
1769 case TMTIMERSTATE_ACTIVE:
1770 case TMTIMERSTATE_PENDING_SCHEDULE:
1771 case TMTIMERSTATE_PENDING_RESCHEDULE:
1772 SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_SCHEDULE);
1773 return SSMR3PutU64(pSSM, pTimer->u64Expire);
1774
1775 case TMTIMERSTATE_EXPIRED:
1776 case TMTIMERSTATE_PENDING_DESTROY:
1777 case TMTIMERSTATE_PENDING_STOP_DESTROY:
1778 case TMTIMERSTATE_FREE:
1779 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
1780 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
1781 }
1782
1783 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
1784 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
1785}
1786
1787
1788/**
1789 * Loads the state of a timer from a saved state.
1790 *
1791 * @returns VBox status.
1792 * @param pTimer Timer to restore.
1793 * @param pSSM Save State Manager handle.
1794 */
1795TMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1796{
1797 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
1798 LogFlow(("TMR3TimerLoad: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1799
1800 /*
1801 * Load the state and validate it.
1802 */
1803 uint8_t u8State;
1804 int rc = SSMR3GetU8(pSSM, &u8State);
1805 if (VBOX_FAILURE(rc))
1806 return rc;
1807 TMTIMERSTATE enmState = (TMTIMERSTATE)u8State;
1808 if ( enmState != TMTIMERSTATE_PENDING_STOP
1809 && enmState != TMTIMERSTATE_PENDING_SCHEDULE
1810 && enmState != TMTIMERSTATE_PENDING_STOP_SCHEDULE)
1811 {
1812 AssertMsgFailed(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1813 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
1814 }
1815
1816 if (enmState == TMTIMERSTATE_PENDING_SCHEDULE)
1817 {
1818 /*
1819 * Load the expire time.
1820 */
1821 uint64_t u64Expire;
1822 rc = SSMR3GetU64(pSSM, &u64Expire);
1823 if (VBOX_FAILURE(rc))
1824 return rc;
1825
1826 /*
1827 * Set it.
1828 */
1829 Log(("enmState=%d %s u64Expire=%llu\n", enmState, tmTimerState(enmState), u64Expire));
1830 rc = TMTimerSet(pTimer, u64Expire);
1831 }
1832 else
1833 {
1834 /*
1835 * Stop it.
1836 */
1837 Log(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1838 rc = TMTimerStop(pTimer);
1839 }
1840
1841 /*
1842 * On failure set SSM status.
1843 */
1844 if (VBOX_FAILURE(rc))
1845 rc = SSMR3HandleSetStatus(pSSM, rc);
1846 return rc;
1847}
1848
1849
1850/**
1851 * Get the real world UTC time adjusted for VM lag.
1852 *
1853 * @returns pTime.
1854 * @param pVM The VM instance.
1855 * @param pTime Where to store the time.
1856 */
1857TMR3DECL(PRTTIMESPEC) TMR3UTCNow(PVM pVM, PRTTIMESPEC pTime)
1858{
1859 RTTimeNow(pTime);
1860 RTTimeSpecSubNano(pTime, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp);
1861 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
1862 return pTime;
1863}
1864
1865
1866/**
1867 * Display all timers.
1868 *
1869 * @param pVM VM Handle.
1870 * @param pHlp The info helpers.
1871 * @param pszArgs Arguments, ignored.
1872 */
1873static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1874{
1875 NOREF(pszArgs);
1876 pHlp->pfnPrintf(pHlp,
1877 "Timers (pVM=%p)\n"
1878 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1879 pVM,
1880 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1881 sizeof(int32_t) * 2, "offNext ",
1882 sizeof(int32_t) * 2, "offPrev ",
1883 sizeof(int32_t) * 2, "offSched ",
1884 "Time",
1885 "Expire",
1886 "State");
1887 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1888 {
1889 pHlp->pfnPrintf(pHlp,
1890 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1891 pTimer,
1892 pTimer->offNext,
1893 pTimer->offPrev,
1894 pTimer->offScheduleNext,
1895 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
1896 TMTimerGet(pTimer),
1897 pTimer->u64Expire,
1898 tmTimerState(pTimer->enmState),
1899 pTimer->pszDesc);
1900 }
1901}
1902
1903
1904/**
1905 * Display all active timers.
1906 *
1907 * @param pVM VM Handle.
1908 * @param pHlp The info helpers.
1909 * @param pszArgs Arguments, ignored.
1910 */
1911static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1912{
1913 NOREF(pszArgs);
1914 pHlp->pfnPrintf(pHlp,
1915 "Active Timers (pVM=%p)\n"
1916 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1917 pVM,
1918 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1919 sizeof(int32_t) * 2, "offNext ",
1920 sizeof(int32_t) * 2, "offPrev ",
1921 sizeof(int32_t) * 2, "offSched ",
1922 "Time",
1923 "Expire",
1924 "State");
1925 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
1926 {
1927 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
1928 pTimer;
1929 pTimer = TMTIMER_GET_NEXT(pTimer))
1930 {
1931 pHlp->pfnPrintf(pHlp,
1932 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1933 pTimer,
1934 pTimer->offNext,
1935 pTimer->offPrev,
1936 pTimer->offScheduleNext,
1937 pTimer->enmClock == TMCLOCK_REAL
1938 ? "Real "
1939 : pTimer->enmClock == TMCLOCK_VIRTUAL
1940 ? "Virt "
1941 : pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC
1942 ? "VrSy "
1943 : "TSC ",
1944 TMTimerGet(pTimer),
1945 pTimer->u64Expire,
1946 tmTimerState(pTimer->enmState),
1947 pTimer->pszDesc);
1948 }
1949 }
1950}
1951
1952
1953/**
1954 * Display all clocks.
1955 *
1956 * @param pVM VM Handle.
1957 * @param pHlp The info helpers.
1958 * @param pszArgs Arguments, ignored.
1959 */
1960static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1961{
1962 NOREF(pszArgs);
1963
1964 /*
1965 * Read the times first to avoid more than necessary time variation.
1966 */
1967 const uint64_t u64TSC = TMCpuTickGet(pVM);
1968 const uint64_t u64Virtual = TMVirtualGet(pVM);
1969 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
1970 const uint64_t u64Real = TMRealGet(pVM);
1971
1972 /*
1973 * TSC
1974 */
1975 pHlp->pfnPrintf(pHlp,
1976 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
1977 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
1978 pVM->tm.s.fTSCTicking ? "ticking" : "paused",
1979 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
1980 if (pVM->tm.s.fTSCUseRealTSC)
1981 {
1982 pHlp->pfnPrintf(pHlp, " - real tsc");
1983 if (pVM->tm.s.u64TSCOffset)
1984 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.u64TSCOffset);
1985 }
1986 else
1987 pHlp->pfnPrintf(pHlp, " - virtual clock");
1988 pHlp->pfnPrintf(pHlp, "\n");
1989
1990 /*
1991 * virtual
1992 */
1993 pHlp->pfnPrintf(pHlp,
1994 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
1995 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
1996 pVM->tm.s.fVirtualTicking ? "ticking" : "paused");
1997 if (pVM->tm.s.fVirtualWarpDrive)
1998 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
1999 pHlp->pfnPrintf(pHlp, "\n");
2000
2001 /*
2002 * virtual sync
2003 */
2004 pHlp->pfnPrintf(pHlp,
2005 "VirtSync: %18RU64 (%#016RX64) %s%s",
2006 u64VirtualSync, u64VirtualSync,
2007 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
2008 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
2009 if (pVM->tm.s.offVirtualSync)
2010 {
2011 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
2012 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
2013 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
2014 }
2015 pHlp->pfnPrintf(pHlp, "\n");
2016
2017 /*
2018 * real
2019 */
2020 pHlp->pfnPrintf(pHlp,
2021 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
2022 u64Real, u64Real, TMRealGetFreq(pVM));
2023}
2024
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