VirtualBox

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

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

No fixed tsc if the GIP timer is in async mode. (TM; AMD cpus with invariant cpuid bit set)

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