VirtualBox

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

Last change on this file since 54214 was 54214, checked in by vboxsync, 10 years ago

HostDrivers/Support, testcase, TM: Add fTscDeltasRoughlyInSync.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 152.2 KB
Line 
1/* $Id: TM.cpp 54214 2015-02-16 11:08:27Z vboxsync $ */
2/** @file
3 * TM - Time Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2015 Oracle Corporation
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/** @page pg_tm TM - The Time Manager
19 *
20 * The Time Manager abstracts the CPU clocks and manages timers used by the VMM,
21 * device and drivers.
22 *
23 * @see grp_tm
24 *
25 *
26 * @section sec_tm_clocks Clocks
27 *
28 * There are currently 4 clocks:
29 * - Virtual (guest).
30 * - Synchronous virtual (guest).
31 * - CPU Tick (TSC) (guest). Only current use is rdtsc emulation. Usually a
32 * function of the virtual clock.
33 * - Real (host). This is only used for display updates atm.
34 *
35 * The most important clocks are the three first ones and of these the second is
36 * the most interesting.
37 *
38 *
39 * The synchronous virtual clock is tied to the virtual clock except that it
40 * will take into account timer delivery lag caused by host scheduling. It will
41 * normally never advance beyond the head timer, and when lagging too far behind
42 * it will gradually speed up to catch up with the virtual clock. All devices
43 * implementing time sources accessible to and used by the guest is using this
44 * clock (for timers and other things). This ensures consistency between the
45 * time sources.
46 *
47 * The virtual clock is implemented as an offset to a monotonic, high
48 * resolution, wall clock. The current time source is using the RTTimeNanoTS()
49 * machinery based upon the Global Info Pages (GIP), that is, we're using TSC
50 * deltas (usually 10 ms) to fill the gaps between GIP updates. The result is
51 * a fairly high res clock that works in all contexts and on all hosts. The
52 * virtual clock is paused when the VM isn't in the running state.
53 *
54 * The CPU tick (TSC) is normally virtualized as a function of the synchronous
55 * virtual clock, where the frequency defaults to the host cpu frequency (as we
56 * measure it). In this mode it is possible to configure the frequency. Another
57 * (non-default) option is to use the raw unmodified host TSC values. And yet
58 * another, to tie it to time spent executing guest code. All these things are
59 * configurable should non-default behavior be desirable.
60 *
61 * The real clock is a monotonic clock (when available) with relatively low
62 * resolution, though this a bit host specific. Note that we're currently not
63 * servicing timers using the real clock when the VM is not running, this is
64 * simply because it has not been needed yet therefore not implemented.
65 *
66 *
67 * @subsection subsec_tm_timesync Guest Time Sync / UTC time
68 *
69 * Guest time syncing is primarily taken care of by the VMM device. The
70 * principle is very simple, the guest additions periodically asks the VMM
71 * device what the current UTC time is and makes adjustments accordingly.
72 *
73 * A complicating factor is that the synchronous virtual clock might be doing
74 * catchups and the guest perception is currently a little bit behind the world
75 * but it will (hopefully) be catching up soon as we're feeding timer interrupts
76 * at a slightly higher rate. Adjusting the guest clock to the current wall
77 * time in the real world would be a bad idea then because the guest will be
78 * advancing too fast and run ahead of world time (if the catchup works out).
79 * To solve this problem TM provides the VMM device with an UTC time source that
80 * gets adjusted with the current lag, so that when the guest eventually catches
81 * up the lag it will be showing correct real world time.
82 *
83 *
84 * @section sec_tm_timers Timers
85 *
86 * The timers can use any of the TM clocks described in the previous section.
87 * Each clock has its own scheduling facility, or timer queue if you like.
88 * There are a few factors which makes it a bit complex. First, there is the
89 * usual R0 vs R3 vs. RC thing. Then there are multiple threads, and then there
90 * is the timer thread that periodically checks whether any timers has expired
91 * without EMT noticing. On the API level, all but the create and save APIs
92 * must be multithreaded. EMT will always run the timers.
93 *
94 * The design is using a doubly linked list of active timers which is ordered
95 * by expire date. This list is only modified by the EMT thread. Updates to
96 * the list are batched in a singly linked list, which is then processed by the
97 * EMT thread at the first opportunity (immediately, next time EMT modifies a
98 * timer on that clock, or next timer timeout). Both lists are offset based and
99 * all the elements are therefore allocated from the hyper heap.
100 *
101 * For figuring out when there is need to schedule and run timers TM will:
102 * - Poll whenever somebody queries the virtual clock.
103 * - Poll the virtual clocks from the EM and REM loops.
104 * - Poll the virtual clocks from trap exit path.
105 * - Poll the virtual clocks and calculate first timeout from the halt loop.
106 * - Employ a thread which periodically (100Hz) polls all the timer queues.
107 *
108 *
109 * @image html TMTIMER-Statechart-Diagram.gif
110 *
111 * @section sec_tm_timer Logging
112 *
113 * Level 2: Logs a most of the timer state transitions and queue servicing.
114 * Level 3: Logs a few oddments.
115 * Level 4: Logs TMCLOCK_VIRTUAL_SYNC catch-up events.
116 *
117 */
118
119/*******************************************************************************
120* Header Files *
121*******************************************************************************/
122#define LOG_GROUP LOG_GROUP_TM
123#include <VBox/vmm/tm.h>
124#include <iprt/asm-amd64-x86.h> /* for SUPGetCpuHzFromGIP from sup.h */
125#include <VBox/vmm/vmm.h>
126#include <VBox/vmm/mm.h>
127#include <VBox/vmm/hm.h>
128#include <VBox/vmm/gim.h>
129#include <VBox/vmm/ssm.h>
130#include <VBox/vmm/dbgf.h>
131#include <VBox/vmm/dbgftrace.h>
132#ifdef VBOX_WITH_REM
133# include <VBox/vmm/rem.h>
134#endif
135#include <VBox/vmm/pdmapi.h>
136#include <VBox/vmm/iom.h>
137#include "TMInternal.h"
138#include <VBox/vmm/vm.h>
139#include <VBox/vmm/uvm.h>
140
141#include <VBox/vmm/pdmdev.h>
142#include <VBox/param.h>
143#include <VBox/err.h>
144
145#include <VBox/log.h>
146#include <iprt/asm.h>
147#include <iprt/asm-math.h>
148#include <iprt/assert.h>
149#include <iprt/thread.h>
150#include <iprt/time.h>
151#include <iprt/timer.h>
152#include <iprt/semaphore.h>
153#include <iprt/string.h>
154#include <iprt/env.h>
155
156#include "TMInline.h"
157
158
159/*******************************************************************************
160* Defined Constants And Macros *
161*******************************************************************************/
162/** The current saved state version.*/
163#define TM_SAVED_STATE_VERSION 3
164
165
166/*******************************************************************************
167* Internal Functions *
168*******************************************************************************/
169static bool tmR3HasFixedTSC(PVM pVM);
170static bool tmR3ReallyNeedDeltas(PSUPGLOBALINFOPAGE pGip);
171static const char * tmR3GetTSCModeName(PVM pVM);
172static uint64_t tmR3CalibrateTSC(PVM pVM);
173static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM);
174static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
175static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
176static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue);
177static void tmR3TimerQueueRunVirtualSync(PVM pVM);
178static DECLCALLBACK(int) tmR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent);
179#ifndef VBOX_WITHOUT_NS_ACCOUNTING
180static DECLCALLBACK(void) tmR3CpuLoadTimer(PVM pVM, PTMTIMER pTimer, void *pvUser);
181#endif
182static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
183static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
184static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
185static DECLCALLBACK(VBOXSTRICTRC) tmR3CpuTickParavirtToggle(PVM pVM, PVMCPU pVCpu, void *pvData);
186
187
188/**
189 * Initializes the TM.
190 *
191 * @returns VBox status code.
192 * @param pVM Pointer to the VM.
193 */
194VMM_INT_DECL(int) TMR3Init(PVM pVM)
195{
196 LogFlow(("TMR3Init:\n"));
197
198 /*
199 * Assert alignment and sizes.
200 */
201 AssertCompileMemberAlignment(VM, tm.s, 32);
202 AssertCompile(sizeof(pVM->tm.s) <= sizeof(pVM->tm.padding));
203 AssertCompileMemberAlignment(TM, TimerCritSect, 8);
204 AssertCompileMemberAlignment(TM, VirtualSyncLock, 8);
205
206 /*
207 * Init the structure.
208 */
209 void *pv;
210 int rc = MMHyperAlloc(pVM, sizeof(pVM->tm.s.paTimerQueuesR3[0]) * TMCLOCK_MAX, 0, MM_TAG_TM, &pv);
211 AssertRCReturn(rc, rc);
212 pVM->tm.s.paTimerQueuesR3 = (PTMTIMERQUEUE)pv;
213 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pv);
214 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pv);
215
216 pVM->tm.s.offVM = RT_OFFSETOF(VM, tm.s);
217 pVM->tm.s.idTimerCpu = pVM->cCpus - 1; /* The last CPU. */
218 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].enmClock = TMCLOCK_VIRTUAL;
219 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].u64Expire = INT64_MAX;
220 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].enmClock = TMCLOCK_VIRTUAL_SYNC;
221 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].u64Expire = INT64_MAX;
222 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].enmClock = TMCLOCK_REAL;
223 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].u64Expire = INT64_MAX;
224 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].enmClock = TMCLOCK_TSC;
225 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].u64Expire = INT64_MAX;
226
227
228 /*
229 * We directly use the GIP to calculate the virtual time. We map the
230 * the GIP into the guest context so we can do this calculation there
231 * as well and save costly world switches.
232 */
233 pVM->tm.s.pvGIPR3 = (void *)g_pSUPGlobalInfoPage;
234 AssertMsgReturn(pVM->tm.s.pvGIPR3, ("GIP support is now required!\n"), VERR_TM_GIP_REQUIRED);
235 AssertMsgReturn((g_pSUPGlobalInfoPage->u32Version >> 16) == (SUPGLOBALINFOPAGE_VERSION >> 16),
236 ("Unsupported GIP version!\n"), VERR_TM_GIP_VERSION);
237
238 RTHCPHYS HCPhysGIP;
239 rc = SUPR3GipGetPhys(&HCPhysGIP);
240 AssertMsgRCReturn(rc, ("Failed to get GIP physical address!\n"), rc);
241
242 RTGCPTR GCPtr;
243#ifdef SUP_WITH_LOTS_OF_CPUS
244 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, NIL_RTR0PTR, HCPhysGIP, (size_t)g_pSUPGlobalInfoPage->cPages * PAGE_SIZE,
245 "GIP", &GCPtr);
246#else
247 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, NIL_RTR0PTR, HCPhysGIP, PAGE_SIZE, "GIP", &GCPtr);
248#endif
249 if (RT_FAILURE(rc))
250 {
251 AssertMsgFailed(("Failed to map GIP into GC, rc=%Rrc!\n", rc));
252 return rc;
253 }
254 pVM->tm.s.pvGIPRC = GCPtr;
255 LogFlow(("TMR3Init: HCPhysGIP=%RHp at %RRv\n", HCPhysGIP, pVM->tm.s.pvGIPRC));
256 MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);
257
258 /* Check assumptions made in TMAllVirtual.cpp about the GIP update interval. */
259 if ( g_pSUPGlobalInfoPage->u32Magic == SUPGLOBALINFOPAGE_MAGIC
260 && g_pSUPGlobalInfoPage->u32UpdateIntervalNS >= 250000000 /* 0.25s */)
261 return VMSetError(pVM, VERR_TM_GIP_UPDATE_INTERVAL_TOO_BIG, RT_SRC_POS,
262 N_("The GIP update interval is too big. u32UpdateIntervalNS=%RU32 (u32UpdateHz=%RU32)"),
263 g_pSUPGlobalInfoPage->u32UpdateIntervalNS, g_pSUPGlobalInfoPage->u32UpdateHz);
264 LogRel(("TM: GIP - u32Mode=%d (%s) u32UpdateHz=%u u32UpdateIntervalNS=%u\n", g_pSUPGlobalInfoPage->u32Mode,
265 SUPGetGIPModeName(g_pSUPGlobalInfoPage), g_pSUPGlobalInfoPage->u32UpdateHz,
266 g_pSUPGlobalInfoPage->u32UpdateIntervalNS));
267 LogRel(("TM: GIP - u64CpuHz=%#RX64 (%'RU64)\n", g_pSUPGlobalInfoPage->u64CpuHz, g_pSUPGlobalInfoPage->u64CpuHz));
268
269 /*
270 * Setup the VirtualGetRaw backend.
271 */
272 pVM->tm.s.VirtualGetRawDataR3.pu64Prev = &pVM->tm.s.u64VirtualRawPrev;
273 pVM->tm.s.VirtualGetRawDataR3.pfnBad = tmVirtualNanoTSBad;
274 pVM->tm.s.VirtualGetRawDataR3.pfnRediscover = tmVirtualNanoTSRediscover;
275 if (ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2)
276 {
277 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_INVARIANT_TSC)
278 pVM->tm.s.pfnVirtualGetRawR3 = tmR3ReallyNeedDeltas(g_pSUPGlobalInfoPage)
279 ? RTTimeNanoTSLFenceInvariantWithDelta : RTTimeNanoTSLFenceInvariantNoDelta;
280 else if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
281 pVM->tm.s.pfnVirtualGetRawR3 = false /** @todo tmR3ReallyNeedDeltas(g_pSUPGlobalInfoPage) */
282 ? RTTimeNanoTSLFenceSyncWithDelta : RTTimeNanoTSLFenceSyncNoDelta;
283 else
284 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceAsync;
285 }
286 else
287 {
288 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_INVARIANT_TSC)
289 pVM->tm.s.pfnVirtualGetRawR3 = tmR3ReallyNeedDeltas(g_pSUPGlobalInfoPage)
290 ? RTTimeNanoTSLegacyInvariantWithDelta : RTTimeNanoTSLegacyInvariantNoDelta;
291 else if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
292 pVM->tm.s.pfnVirtualGetRawR3 = false /** @todo tmR3ReallyNeedDeltas(g_pSUPGlobalInfoPage) */
293 ? RTTimeNanoTSLegacySyncWithDelta : RTTimeNanoTSLegacySyncNoDelta;
294 else
295 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacyAsync;
296 }
297
298 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
299 pVM->tm.s.VirtualGetRawDataR0.pu64Prev = MMHyperR3ToR0(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
300 AssertRelease(pVM->tm.s.VirtualGetRawDataR0.pu64Prev);
301 /* The rest is done in TMR3InitFinalize since it's too early to call PDM. */
302
303 /*
304 * Init the locks.
305 */
306 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.TimerCritSect, RT_SRC_POS, "TM Timer Lock");
307 if (RT_FAILURE(rc))
308 return rc;
309 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.VirtualSyncLock, RT_SRC_POS, "TM VirtualSync Lock");
310 if (RT_FAILURE(rc))
311 return rc;
312
313 /*
314 * Get our CFGM node, create it if necessary.
315 */
316 PCFGMNODE pCfgHandle = CFGMR3GetChild(CFGMR3GetRoot(pVM), "TM");
317 if (!pCfgHandle)
318 {
319 rc = CFGMR3InsertNode(CFGMR3GetRoot(pVM), "TM", &pCfgHandle);
320 AssertRCReturn(rc, rc);
321 }
322
323 /*
324 * Specific errors about some obsolete TM settings (remove after 2015-12-03).
325 */
326 if (CFGMR3Exists(pCfgHandle, "TSCVirtualized"))
327 return VMSetError(pVM, VERR_CFGM_CONFIG_UNKNOWN_VALUE, RT_SRC_POS,
328 N_("Configuration error: TM setting \"TSCVirtualized\" is no longer supported. Use the \"Mode\" setting instead."));
329 if (CFGMR3Exists(pCfgHandle, "UseRealTSC"))
330 return VMSetError(pVM, VERR_CFGM_CONFIG_UNKNOWN_VALUE, RT_SRC_POS,
331 N_("Configuration error: TM setting \"UseRealTSC\" is no longer supported. Use the \"Mode\" setting instead."));
332
333 if (CFGMR3Exists(pCfgHandle, "MaybeUseOffsettedHostTSC"))
334 return VMSetError(pVM, VERR_CFGM_CONFIG_UNKNOWN_VALUE, RT_SRC_POS,
335 N_("Configuration error: TM setting \"MaybeUseOffsettedHostTSC\" is no longer supported. Use the \"Mode\" setting instead."));
336
337 /*
338 * Validate the rest of the TM settings.
339 */
340 rc = CFGMR3ValidateConfig(pCfgHandle, "/TM/",
341 "TSCMode|"
342 "TSCModeSwitchAllowed|"
343 "TSCTicksPerSecond|"
344 "TSCTiedToExecution|"
345 "TSCNotTiedToHalt|"
346 "ScheduleSlack|"
347 "CatchUpStopThreshold|"
348 "CatchUpGiveUpThreshold|"
349 "CatchUpStartThreshold0|CatchUpStartThreshold1|CatchUpStartThreshold2|CatchUpStartThreshold3|"
350 "CatchUpStartThreshold4|CatchUpStartThreshold5|CatchUpStartThreshold6|CatchUpStartThreshold7|"
351 "CatchUpStartThreshold8|CatchUpStartThreshold9|"
352 "CatchUpPrecentage0|CatchUpPrecentage1|CatchUpPrecentage2|CatchUpPrecentage3|"
353 "CatchUpPrecentage4|CatchUpPrecentage5|CatchUpPrecentage6|CatchUpPrecentage7|"
354 "CatchUpPrecentage8|CatchUpPrecentage9|"
355 "UTCOffset|"
356 "WarpDrivePercentage|"
357 "HostHzMax|"
358 "HostHzFudgeFactorTimerCpu|"
359 "HostHzFudgeFactorOtherCpu|"
360 "HostHzFudgeFactorCatchUp100|"
361 "HostHzFudgeFactorCatchUp200|"
362 "HostHzFudgeFactorCatchUp400|"
363 "TimerMillies",
364 "",
365 "TM", 0);
366 if (RT_FAILURE(rc))
367 return rc;
368
369 /*
370 * Determine the TSC configuration and frequency.
371 */
372 /** @cfgm{/TM/TSCMode, string, Depends on the CPU and VM config}
373 * The name of the TSC mode to use: VirtTSCEmulated, RealTSCOffset or Dynamic.
374 * The default depends on the VM configuration and the capabilities of the
375 * host CPU. Other config options or runtime changes may override the TSC
376 * mode specified here.
377 */
378 char szTSCMode[32];
379 rc = CFGMR3QueryString(pCfgHandle, "TSCMode", szTSCMode, sizeof(szTSCMode));
380 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
381 {
382 /** @todo Rainy-day/never: Dynamic mode isn't currently suitable for SMP VMs, so
383 * fall back on the more expensive emulated mode. With the current TSC handling
384 * (frequent switching between offsetted mode and taking VM exits, on all VCPUs
385 * without any kind of coordination) will lead to inconsistent TSC behavior with
386 * guest SMP, including TSC going backwards. */
387 pVM->tm.s.enmTSCMode = pVM->cCpus == 1 && tmR3HasFixedTSC(pVM) ? TMTSCMODE_DYNAMIC : TMTSCMODE_VIRT_TSC_EMULATED;
388 }
389 else if (RT_FAILURE(rc))
390 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying string value \"TSCMode\""));
391 else
392 {
393 if (!RTStrCmp(szTSCMode, "VirtTSCEmulated"))
394 pVM->tm.s.enmTSCMode = TMTSCMODE_VIRT_TSC_EMULATED;
395 else if (!RTStrCmp(szTSCMode, "RealTSCOffset"))
396 pVM->tm.s.enmTSCMode = TMTSCMODE_REAL_TSC_OFFSET;
397 else if (!RTStrCmp(szTSCMode, "Dynamic"))
398 pVM->tm.s.enmTSCMode = TMTSCMODE_DYNAMIC;
399 else
400 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Unrecognized TM TSC mode value \"%s\""), szTSCMode);
401 }
402
403 /**
404 * @cfgm{/TM/TSCModeSwitchAllowed, bool, Whether TM TSC mode switch is allowed
405 * at runtime}
406 * When using paravirtualized guests, we dynamically switch TSC modes to a more
407 * optimal one for performance. This setting allows overriding this behaviour.
408 */
409 rc = CFGMR3QueryBool(pCfgHandle, "TSCModeSwitchAllowed", &pVM->tm.s.fTSCModeSwitchAllowed);
410 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
411 {
412 /* This is finally determined in TMR3InitFinalize() as GIM isn't initialized yet. */
413 pVM->tm.s.fTSCModeSwitchAllowed = true;
414 }
415 else if (RT_FAILURE(rc))
416 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying bool value \"TSCModeSwitchAllowed\""));
417
418 /** @cfgm{/TM/TSCTicksPerSecond, uint32_t, Current TSC frequency from GIP}
419 * The number of TSC ticks per second (i.e. the TSC frequency). This will
420 * override enmTSCMode.
421 */
422 rc = CFGMR3QueryU64(pCfgHandle, "TSCTicksPerSecond", &pVM->tm.s.cTSCTicksPerSecond);
423 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
424 {
425 pVM->tm.s.cTSCTicksPerSecond = tmR3CalibrateTSC(pVM);
426 if ( pVM->tm.s.enmTSCMode != TMTSCMODE_REAL_TSC_OFFSET
427 && pVM->tm.s.cTSCTicksPerSecond >= _4G)
428 {
429 pVM->tm.s.cTSCTicksPerSecond = _4G - 1; /* (A limitation of our math code) */
430 pVM->tm.s.enmTSCMode = TMTSCMODE_VIRT_TSC_EMULATED;
431 }
432 }
433 else if (RT_FAILURE(rc))
434 return VMSetError(pVM, rc, RT_SRC_POS,
435 N_("Configuration error: Failed to querying uint64_t value \"TSCTicksPerSecond\""));
436 else if ( pVM->tm.s.cTSCTicksPerSecond < _1M
437 || pVM->tm.s.cTSCTicksPerSecond >= _4G)
438 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
439 N_("Configuration error: \"TSCTicksPerSecond\" = %RI64 is not in the range 1MHz..4GHz-1"),
440 pVM->tm.s.cTSCTicksPerSecond);
441 else
442 {
443 pVM->tm.s.enmTSCMode = TMTSCMODE_VIRT_TSC_EMULATED;
444 }
445
446 /** @cfgm{/TM/TSCTiedToExecution, bool, false}
447 * Whether the TSC should be tied to execution. This will exclude most of the
448 * virtualization overhead, but will by default include the time spent in the
449 * halt state (see TM/TSCNotTiedToHalt). This setting will override all other
450 * TSC settings except for TSCTicksPerSecond and TSCNotTiedToHalt, which should
451 * be used avoided or used with great care. Note that this will only work right
452 * together with VT-x or AMD-V, and with a single virtual CPU. */
453 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCTiedToExecution", &pVM->tm.s.fTSCTiedToExecution, false);
454 if (RT_FAILURE(rc))
455 return VMSetError(pVM, rc, RT_SRC_POS,
456 N_("Configuration error: Failed to querying bool value \"TSCTiedToExecution\""));
457 if (pVM->tm.s.fTSCTiedToExecution)
458 pVM->tm.s.enmTSCMode = TMTSCMODE_VIRT_TSC_EMULATED;
459
460 /** @cfgm{/TM/TSCNotTiedToHalt, bool, true}
461 * For overriding the default of TM/TSCTiedToExecution, i.e. set this to false
462 * to make the TSC freeze during HLT. */
463 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCNotTiedToHalt", &pVM->tm.s.fTSCNotTiedToHalt, false);
464 if (RT_FAILURE(rc))
465 return VMSetError(pVM, rc, RT_SRC_POS,
466 N_("Configuration error: Failed to querying bool value \"TSCNotTiedToHalt\""));
467
468 /*
469 * Configure the timer synchronous virtual time.
470 */
471 /** @cfgm{/TM/ScheduleSlack, uint32_t, ns, 0, UINT32_MAX, 100000}
472 * Scheduling slack when processing timers. */
473 rc = CFGMR3QueryU32(pCfgHandle, "ScheduleSlack", &pVM->tm.s.u32VirtualSyncScheduleSlack);
474 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
475 pVM->tm.s.u32VirtualSyncScheduleSlack = 100000; /* 0.100ms (ASSUMES virtual time is nanoseconds) */
476 else if (RT_FAILURE(rc))
477 return VMSetError(pVM, rc, RT_SRC_POS,
478 N_("Configuration error: Failed to querying 32-bit integer value \"ScheduleSlack\""));
479
480 /** @cfgm{/TM/CatchUpStopThreshold, uint64_t, ns, 0, UINT64_MAX, 500000}
481 * When to stop a catch-up, considering it successful. */
482 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStopThreshold", &pVM->tm.s.u64VirtualSyncCatchUpStopThreshold);
483 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
484 pVM->tm.s.u64VirtualSyncCatchUpStopThreshold = 500000; /* 0.5ms */
485 else if (RT_FAILURE(rc))
486 return VMSetError(pVM, rc, RT_SRC_POS,
487 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpStopThreshold\""));
488
489 /** @cfgm{/TM/CatchUpGiveUpThreshold, uint64_t, ns, 0, UINT64_MAX, 60000000000}
490 * When to give up a catch-up attempt. */
491 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpGiveUpThreshold", &pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold);
492 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
493 pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold = UINT64_C(60000000000); /* 60 sec */
494 else if (RT_FAILURE(rc))
495 return VMSetError(pVM, rc, RT_SRC_POS,
496 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpGiveUpThreshold\""));
497
498
499 /** @cfgm{/TM/CatchUpPrecentage[0..9], uint32_t, %, 1, 2000, various}
500 * The catch-up percent for a given period. */
501 /** @cfgm{/TM/CatchUpStartThreshold[0..9], uint64_t, ns, 0, UINT64_MAX}
502 * The catch-up period threshold, or if you like, when a period starts. */
503#define TM_CFG_PERIOD(iPeriod, DefStart, DefPct) \
504 do \
505 { \
506 uint64_t u64; \
507 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStartThreshold" #iPeriod, &u64); \
508 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
509 u64 = UINT64_C(DefStart); \
510 else if (RT_FAILURE(rc)) \
511 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpThreshold" #iPeriod "\"")); \
512 if ( (iPeriod > 0 && u64 <= pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod - 1].u64Start) \
513 || u64 >= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold) \
514 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Configuration error: Invalid start of period #" #iPeriod ": %'RU64"), u64); \
515 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u64Start = u64; \
516 rc = CFGMR3QueryU32(pCfgHandle, "CatchUpPrecentage" #iPeriod, &pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage); \
517 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
518 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage = (DefPct); \
519 else if (RT_FAILURE(rc)) \
520 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 32-bit integer value \"CatchUpPrecentage" #iPeriod "\"")); \
521 } while (0)
522 /* This needs more tuning. Not sure if we really need so many period and be so gentle. */
523 TM_CFG_PERIOD(0, 750000, 5); /* 0.75ms at 1.05x */
524 TM_CFG_PERIOD(1, 1500000, 10); /* 1.50ms at 1.10x */
525 TM_CFG_PERIOD(2, 8000000, 25); /* 8ms at 1.25x */
526 TM_CFG_PERIOD(3, 30000000, 50); /* 30ms at 1.50x */
527 TM_CFG_PERIOD(4, 75000000, 75); /* 75ms at 1.75x */
528 TM_CFG_PERIOD(5, 175000000, 100); /* 175ms at 2x */
529 TM_CFG_PERIOD(6, 500000000, 200); /* 500ms at 3x */
530 TM_CFG_PERIOD(7, 3000000000, 300); /* 3s at 4x */
531 TM_CFG_PERIOD(8,30000000000, 400); /* 30s at 5x */
532 TM_CFG_PERIOD(9,55000000000, 500); /* 55s at 6x */
533 AssertCompile(RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods) == 10);
534#undef TM_CFG_PERIOD
535
536 /*
537 * Configure real world time (UTC).
538 */
539 /** @cfgm{/TM/UTCOffset, int64_t, ns, INT64_MIN, INT64_MAX, 0}
540 * The UTC offset. This is used to put the guest back or forwards in time. */
541 rc = CFGMR3QueryS64(pCfgHandle, "UTCOffset", &pVM->tm.s.offUTC);
542 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
543 pVM->tm.s.offUTC = 0; /* ns */
544 else if (RT_FAILURE(rc))
545 return VMSetError(pVM, rc, RT_SRC_POS,
546 N_("Configuration error: Failed to querying 64-bit integer value \"UTCOffset\""));
547
548 /*
549 * Setup the warp drive.
550 */
551 /** @cfgm{/TM/WarpDrivePercentage, uint32_t, %, 0, 20000, 100}
552 * The warp drive percentage, 100% is normal speed. This is used to speed up
553 * or slow down the virtual clock, which can be useful for fast forwarding
554 * borring periods during tests. */
555 rc = CFGMR3QueryU32(pCfgHandle, "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage);
556 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
557 rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage); /* legacy */
558 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
559 pVM->tm.s.u32VirtualWarpDrivePercentage = 100;
560 else if (RT_FAILURE(rc))
561 return VMSetError(pVM, rc, RT_SRC_POS,
562 N_("Configuration error: Failed to querying uint32_t value \"WarpDrivePercent\""));
563 else if ( pVM->tm.s.u32VirtualWarpDrivePercentage < 2
564 || pVM->tm.s.u32VirtualWarpDrivePercentage > 20000)
565 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
566 N_("Configuration error: \"WarpDrivePercent\" = %RI32 is not in the range 2..20000"),
567 pVM->tm.s.u32VirtualWarpDrivePercentage);
568 pVM->tm.s.fVirtualWarpDrive = pVM->tm.s.u32VirtualWarpDrivePercentage != 100;
569 if (pVM->tm.s.fVirtualWarpDrive)
570 {
571 pVM->tm.s.enmTSCMode = TMTSCMODE_VIRT_TSC_EMULATED;
572 LogRel(("TM: Warp-drive active. u32VirtualWarpDrivePercentage=%RI32\n", pVM->tm.s.u32VirtualWarpDrivePercentage));
573 }
574
575 /*
576 * Gather the Host Hz configuration values.
577 */
578 rc = CFGMR3QueryU32Def(pCfgHandle, "HostHzMax", &pVM->tm.s.cHostHzMax, 20000);
579 if (RT_FAILURE(rc))
580 return VMSetError(pVM, rc, RT_SRC_POS,
581 N_("Configuration error: Failed to querying uint32_t value \"HostHzMax\""));
582
583 rc = CFGMR3QueryU32Def(pCfgHandle, "HostHzFudgeFactorTimerCpu", &pVM->tm.s.cPctHostHzFudgeFactorTimerCpu, 111);
584 if (RT_FAILURE(rc))
585 return VMSetError(pVM, rc, RT_SRC_POS,
586 N_("Configuration error: Failed to querying uint32_t value \"HostHzFudgeFactorTimerCpu\""));
587
588 rc = CFGMR3QueryU32Def(pCfgHandle, "HostHzFudgeFactorOtherCpu", &pVM->tm.s.cPctHostHzFudgeFactorOtherCpu, 110);
589 if (RT_FAILURE(rc))
590 return VMSetError(pVM, rc, RT_SRC_POS,
591 N_("Configuration error: Failed to querying uint32_t value \"HostHzFudgeFactorOtherCpu\""));
592
593 rc = CFGMR3QueryU32Def(pCfgHandle, "HostHzFudgeFactorCatchUp100", &pVM->tm.s.cPctHostHzFudgeFactorCatchUp100, 300);
594 if (RT_FAILURE(rc))
595 return VMSetError(pVM, rc, RT_SRC_POS,
596 N_("Configuration error: Failed to querying uint32_t value \"HostHzFudgeFactorCatchUp100\""));
597
598 rc = CFGMR3QueryU32Def(pCfgHandle, "HostHzFudgeFactorCatchUp200", &pVM->tm.s.cPctHostHzFudgeFactorCatchUp200, 250);
599 if (RT_FAILURE(rc))
600 return VMSetError(pVM, rc, RT_SRC_POS,
601 N_("Configuration error: Failed to querying uint32_t value \"HostHzFudgeFactorCatchUp200\""));
602
603 rc = CFGMR3QueryU32Def(pCfgHandle, "HostHzFudgeFactorCatchUp400", &pVM->tm.s.cPctHostHzFudgeFactorCatchUp400, 200);
604 if (RT_FAILURE(rc))
605 return VMSetError(pVM, rc, RT_SRC_POS,
606 N_("Configuration error: Failed to querying uint32_t value \"HostHzFudgeFactorCatchUp400\""));
607
608 /*
609 * Finally, setup and report.
610 */
611 pVM->tm.s.enmOriginalTSCMode = pVM->tm.s.enmTSCMode;
612 CPUMR3SetCR4Feature(pVM, X86_CR4_TSD, ~X86_CR4_TSD);
613 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%'RU64) enmTSCMode=%d (%s)\n"
614 "TM: TSCTiedToExecution=%RTbool TSCNotTiedToHalt=%RTbool\n",
615 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.enmTSCMode, tmR3GetTSCModeName(pVM),
616 pVM->tm.s.fTSCTiedToExecution, pVM->tm.s.fTSCNotTiedToHalt));
617
618 /*
619 * Dump the GIPCPU TSC-deltas, iterate using the Apic Id to get master at the beginning in most cases.
620 */
621 LogRel(("TM: GIP - fTscDeltasRoughlyInSync=%RTbool\n", g_pSUPGlobalInfoPage->fTscDeltasRoughlyInSync));
622 unsigned cGipCpus = RT_ELEMENTS(g_pSUPGlobalInfoPage->aiCpuFromApicId);
623 for (unsigned i = 0; i < cGipCpus; i++)
624 {
625 uint16_t iCpu = g_pSUPGlobalInfoPage->aiCpuFromApicId[i];
626#if 1
627 if (iCpu != UINT16_MAX)
628 LogRel(("TM: GIP - CPU[%d]: idApic=%d i64TSCDelta=%RI64\n", g_pSUPGlobalInfoPage->aCPUs[iCpu].idCpu,
629 g_pSUPGlobalInfoPage->aCPUs[iCpu].idApic, g_pSUPGlobalInfoPage->aCPUs[iCpu].i64TSCDelta));
630#else
631 /* Dump 2 entries per line, saves vertical space in release log but more dumps bytes due to formatting. */
632 uint16_t iCpu2 = UINT16_MAX;
633 for (unsigned k = i + 1; k < cGipCpus; k++)
634 {
635 iCpu2 = g_pSUPGlobalInfoPage->aiCpuFromApicId[k];
636 if (iCpu2 != UINT16_MAX)
637 {
638 i = k + 1;
639 break;
640 }
641 }
642 if ( iCpu != UINT16_MAX
643 && iCpu2 != UINT16_MAX)
644 {
645 LogRel(("TM: GIP - CPU[%d]: idApic=%d i64TSCDelta=%-4lld CPU[%d]: idApic=%d i64TSCDelta=%lld\n",
646 g_pSUPGlobalInfoPage->aCPUs[iCpu].idCpu, g_pSUPGlobalInfoPage->aCPUs[iCpu].idApic,
647 g_pSUPGlobalInfoPage->aCPUs[iCpu].i64TSCDelta, g_pSUPGlobalInfoPage->aCPUs[iCpu2].idCpu,
648 g_pSUPGlobalInfoPage->aCPUs[iCpu2].idApic, g_pSUPGlobalInfoPage->aCPUs[iCpu2].i64TSCDelta));
649 }
650 else if (iCpu != UINT16_MAX)
651 LogRel(("TM: GIP - CPU[%d]: idApic=%d i64TSCDelta=%lld\n", g_pSUPGlobalInfoPage->aCPUs[iCpu].idCpu,
652 g_pSUPGlobalInfoPage->aCPUs[iCpu].idApic));
653#endif
654 }
655
656 /*
657 * Start the timer (guard against REM not yielding).
658 */
659 /** @cfgm{/TM/TimerMillies, uint32_t, ms, 1, 1000, 10}
660 * The watchdog timer interval. */
661 uint32_t u32Millies;
662 rc = CFGMR3QueryU32(pCfgHandle, "TimerMillies", &u32Millies);
663 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
664 u32Millies = 10;
665 else if (RT_FAILURE(rc))
666 return VMSetError(pVM, rc, RT_SRC_POS,
667 N_("Configuration error: Failed to query uint32_t value \"TimerMillies\""));
668 rc = RTTimerCreate(&pVM->tm.s.pTimer, u32Millies, tmR3TimerCallback, pVM);
669 if (RT_FAILURE(rc))
670 {
671 AssertMsgFailed(("Failed to create timer, u32Millies=%d rc=%Rrc.\n", u32Millies, rc));
672 return rc;
673 }
674 Log(("TM: Created timer %p firing every %d milliseconds\n", pVM->tm.s.pTimer, u32Millies));
675 pVM->tm.s.u32TimerMillies = u32Millies;
676
677 /*
678 * Register saved state.
679 */
680 rc = SSMR3RegisterInternal(pVM, "tm", 1, TM_SAVED_STATE_VERSION, sizeof(uint64_t) * 8,
681 NULL, NULL, NULL,
682 NULL, tmR3Save, NULL,
683 NULL, tmR3Load, NULL);
684 if (RT_FAILURE(rc))
685 return rc;
686
687 /*
688 * Register statistics.
689 */
690 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).");
691 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).");
692 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).");
693 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).");
694 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.c1nsSteps,STAMTYPE_U32, "/TM/RC/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
695 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.cBadPrev, STAMTYPE_U32, "/TM/RC/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
696 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)");
697 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 attempted caught up with.");
698 STAM_REL_REG( pVM,(void*)&pVM->tm.s.uMaxHzHint, STAMTYPE_U32, "/TM/MaxHzHint", STAMUNIT_HZ, "Max guest timer frequency hint.");
699
700#ifdef VBOX_WITH_STATISTICS
701 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).");
702 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR3.cUpdateRaces,STAMTYPE_U32, "/TM/R3/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
703 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).");
704 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR0.cUpdateRaces,STAMTYPE_U32, "/TM/R0/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
705 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cExpired, STAMTYPE_U32, "/TM/RC/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
706 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cUpdateRaces,STAMTYPE_U32, "/TM/RC/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
707 STAM_REG(pVM, &pVM->tm.s.StatDoQueues, STAMTYPE_PROFILE, "/TM/DoQueues", STAMUNIT_TICKS_PER_CALL, "Profiling timer TMR3TimerQueuesDo.");
708 STAM_REG(pVM, &pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Virtual", STAMUNIT_TICKS_PER_CALL, "Time spent on the virtual clock queue.");
709 STAM_REG(pVM, &pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], STAMTYPE_PROFILE_ADV, "/TM/DoQueues/VirtualSync", STAMUNIT_TICKS_PER_CALL, "Time spent on the virtual sync clock queue.");
710 STAM_REG(pVM, &pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Real", STAMUNIT_TICKS_PER_CALL, "Time spent on the real clock queue.");
711
712 STAM_REG(pVM, &pVM->tm.s.StatPoll, STAMTYPE_COUNTER, "/TM/Poll", STAMUNIT_OCCURENCES, "TMTimerPoll calls.");
713 STAM_REG(pVM, &pVM->tm.s.StatPollAlreadySet, STAMTYPE_COUNTER, "/TM/Poll/AlreadySet", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the FF was already set.");
714 STAM_REG(pVM, &pVM->tm.s.StatPollELoop, STAMTYPE_COUNTER, "/TM/Poll/ELoop", STAMUNIT_OCCURENCES, "Times TMTimerPoll has given up getting a consistent virtual sync data set.");
715 STAM_REG(pVM, &pVM->tm.s.StatPollMiss, STAMTYPE_COUNTER, "/TM/Poll/Miss", STAMUNIT_OCCURENCES, "TMTimerPoll calls where nothing had expired.");
716 STAM_REG(pVM, &pVM->tm.s.StatPollRunning, STAMTYPE_COUNTER, "/TM/Poll/Running", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the queues were being run.");
717 STAM_REG(pVM, &pVM->tm.s.StatPollSimple, STAMTYPE_COUNTER, "/TM/Poll/Simple", STAMUNIT_OCCURENCES, "TMTimerPoll calls where we could take the simple path.");
718 STAM_REG(pVM, &pVM->tm.s.StatPollVirtual, STAMTYPE_COUNTER, "/TM/Poll/HitsVirtual", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL queue.");
719 STAM_REG(pVM, &pVM->tm.s.StatPollVirtualSync, STAMTYPE_COUNTER, "/TM/Poll/HitsVirtualSync", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL_SYNC queue.");
720
721 STAM_REG(pVM, &pVM->tm.s.StatPostponedR3, STAMTYPE_COUNTER, "/TM/PostponedR3", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-3.");
722 STAM_REG(pVM, &pVM->tm.s.StatPostponedRZ, STAMTYPE_COUNTER, "/TM/PostponedRZ", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-0 / RC.");
723
724 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.");
725 STAM_REG(pVM, &pVM->tm.s.StatScheduleOneRZ, STAMTYPE_PROFILE, "/TM/ScheduleOneRZ", STAMUNIT_TICKS_PER_CALL, "Profiling the scheduling of one queue during a TMTimer* call in EMT.");
726 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.");
727
728 STAM_REG(pVM, &pVM->tm.s.StatTimerSet, STAMTYPE_COUNTER, "/TM/TimerSet", STAMUNIT_OCCURENCES, "Calls, except virtual sync timers");
729 STAM_REG(pVM, &pVM->tm.s.StatTimerSetOpt, STAMTYPE_COUNTER, "/TM/TimerSet/Opt", STAMUNIT_OCCURENCES, "Optimized path taken.");
730 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR3, STAMTYPE_PROFILE, "/TM/TimerSet/R3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3.");
731 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRZ, STAMTYPE_PROFILE, "/TM/TimerSet/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0 / RC.");
732 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStActive, STAMTYPE_COUNTER, "/TM/TimerSet/StActive", STAMUNIT_OCCURENCES, "ACTIVE");
733 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStExpDeliver, STAMTYPE_COUNTER, "/TM/TimerSet/StExpDeliver", STAMUNIT_OCCURENCES, "EXPIRED_DELIVER");
734 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStOther, STAMTYPE_COUNTER, "/TM/TimerSet/StOther", STAMUNIT_OCCURENCES, "Other states");
735 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendStop, STAMTYPE_COUNTER, "/TM/TimerSet/StPendStop", STAMUNIT_OCCURENCES, "PENDING_STOP");
736 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendStopSched, STAMTYPE_COUNTER, "/TM/TimerSet/StPendStopSched", STAMUNIT_OCCURENCES, "PENDING_STOP_SCHEDULE");
737 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendSched, STAMTYPE_COUNTER, "/TM/TimerSet/StPendSched", STAMUNIT_OCCURENCES, "PENDING_SCHEDULE");
738 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendResched, STAMTYPE_COUNTER, "/TM/TimerSet/StPendResched", STAMUNIT_OCCURENCES, "PENDING_RESCHEDULE");
739 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStStopped, STAMTYPE_COUNTER, "/TM/TimerSet/StStopped", STAMUNIT_OCCURENCES, "STOPPED");
740
741 STAM_REG(pVM, &pVM->tm.s.StatTimerSetVs, STAMTYPE_COUNTER, "/TM/TimerSetVs", STAMUNIT_OCCURENCES, "TMTimerSet calls on virtual sync timers");
742 STAM_REG(pVM, &pVM->tm.s.StatTimerSetVsR3, STAMTYPE_PROFILE, "/TM/TimerSetVs/R3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3 on virtual sync timers.");
743 STAM_REG(pVM, &pVM->tm.s.StatTimerSetVsRZ, STAMTYPE_PROFILE, "/TM/TimerSetVs/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0 / RC on virtual sync timers.");
744 STAM_REG(pVM, &pVM->tm.s.StatTimerSetVsStActive, STAMTYPE_COUNTER, "/TM/TimerSetVs/StActive", STAMUNIT_OCCURENCES, "ACTIVE");
745 STAM_REG(pVM, &pVM->tm.s.StatTimerSetVsStExpDeliver, STAMTYPE_COUNTER, "/TM/TimerSetVs/StExpDeliver", STAMUNIT_OCCURENCES, "EXPIRED_DELIVER");
746 STAM_REG(pVM, &pVM->tm.s.StatTimerSetVsStStopped, STAMTYPE_COUNTER, "/TM/TimerSetVs/StStopped", STAMUNIT_OCCURENCES, "STOPPED");
747
748 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelative, STAMTYPE_COUNTER, "/TM/TimerSetRelative", STAMUNIT_OCCURENCES, "Calls, except virtual sync timers");
749 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeOpt, STAMTYPE_COUNTER, "/TM/TimerSetRelative/Opt", STAMUNIT_OCCURENCES, "Optimized path taken.");
750 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeR3, STAMTYPE_PROFILE, "/TM/TimerSetRelative/R3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSetRelative calls made in ring-3 (sans virtual sync).");
751 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeRZ, STAMTYPE_PROFILE, "/TM/TimerSetRelative/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSetReltaive calls made in ring-0 / RC (sans virtual sync).");
752 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStActive, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StActive", STAMUNIT_OCCURENCES, "ACTIVE");
753 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStExpDeliver, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StExpDeliver", STAMUNIT_OCCURENCES, "EXPIRED_DELIVER");
754 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStOther, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StOther", STAMUNIT_OCCURENCES, "Other states");
755 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendStop, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendStop", STAMUNIT_OCCURENCES, "PENDING_STOP");
756 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendStopSched, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendStopSched",STAMUNIT_OCCURENCES, "PENDING_STOP_SCHEDULE");
757 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendSched, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendSched", STAMUNIT_OCCURENCES, "PENDING_SCHEDULE");
758 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendResched, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendResched", STAMUNIT_OCCURENCES, "PENDING_RESCHEDULE");
759 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStStopped, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StStopped", STAMUNIT_OCCURENCES, "STOPPED");
760
761 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeVs, STAMTYPE_COUNTER, "/TM/TimerSetRelativeVs", STAMUNIT_OCCURENCES, "TMTimerSetRelative calls on virtual sync timers");
762 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeVsR3, STAMTYPE_PROFILE, "/TM/TimerSetRelativeVs/R3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSetRelative calls made in ring-3 on virtual sync timers.");
763 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeVsRZ, STAMTYPE_PROFILE, "/TM/TimerSetRelativeVs/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSetReltaive calls made in ring-0 / RC on virtual sync timers.");
764 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeVsStActive, STAMTYPE_COUNTER, "/TM/TimerSetRelativeVs/StActive", STAMUNIT_OCCURENCES, "ACTIVE");
765 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeVsStExpDeliver, STAMTYPE_COUNTER, "/TM/TimerSetRelativeVs/StExpDeliver", STAMUNIT_OCCURENCES, "EXPIRED_DELIVER");
766 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeVsStStopped, STAMTYPE_COUNTER, "/TM/TimerSetRelativeVs/StStopped", STAMUNIT_OCCURENCES, "STOPPED");
767
768 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR3, STAMTYPE_PROFILE, "/TM/TimerStopR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-3.");
769 STAM_REG(pVM, &pVM->tm.s.StatTimerStopRZ, STAMTYPE_PROFILE, "/TM/TimerStopRZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-0 / RC.");
770
771 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.");
772 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualGetSetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGet.");
773 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGet, STAMTYPE_COUNTER, "/TM/VirtualSyncGet", STAMUNIT_OCCURENCES, "The number of times tmVirtualSyncGetEx was called.");
774 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetAdjLast, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/AdjLast", STAMUNIT_OCCURENCES, "Times we've adjusted against the last returned time stamp .");
775 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetELoop, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/ELoop", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx has given up getting a consistent virtual sync data set.");
776 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetExpired, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Expired", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx encountered an expired timer stopping the clock.");
777 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetLocked, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Locked", STAMUNIT_OCCURENCES, "Times we successfully acquired the lock in tmVirtualSyncGetEx.");
778 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetLockless, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Lockless", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx returned without needing to take the lock.");
779 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/SetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling tmVirtualSyncGetEx.");
780 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/VirtualPause", STAMUNIT_OCCURENCES, "The number of times TMR3TimerPause was called.");
781 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/VirtualResume", STAMUNIT_OCCURENCES, "The number of times TMR3TimerResume was called.");
782
783 STAM_REG(pVM, &pVM->tm.s.StatTimerCallbackSetFF, STAMTYPE_COUNTER, "/TM/CallbackSetFF", STAMUNIT_OCCURENCES, "The number of times the timer callback set FF.");
784 STAM_REG(pVM, &pVM->tm.s.StatTimerCallback, STAMTYPE_COUNTER, "/TM/Callback", STAMUNIT_OCCURENCES, "The number of times the timer callback is invoked.");
785
786 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE010, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE010", STAMUNIT_OCCURENCES, "In catch-up mode, 10% or lower.");
787 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE025, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE025", STAMUNIT_OCCURENCES, "In catch-up mode, 25%-11%.");
788 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE100, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE100", STAMUNIT_OCCURENCES, "In catch-up mode, 100%-26%.");
789 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupOther, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupOther", STAMUNIT_OCCURENCES, "In catch-up mode, > 100%.");
790 STAM_REG(pVM, &pVM->tm.s.StatTSCNotFixed, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotFixed", STAMUNIT_OCCURENCES, "TSC is not fixed, it may run at variable speed.");
791 STAM_REG(pVM, &pVM->tm.s.StatTSCNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotTicking", STAMUNIT_OCCURENCES, "TSC is not ticking.");
792 STAM_REG(pVM, &pVM->tm.s.StatTSCSyncNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/SyncNotTicking", STAMUNIT_OCCURENCES, "VirtualSync isn't ticking.");
793 STAM_REG(pVM, &pVM->tm.s.StatTSCWarp, STAMTYPE_COUNTER, "/TM/TSC/Intercept/Warp", STAMUNIT_OCCURENCES, "Warpdrive is active.");
794 STAM_REG(pVM, &pVM->tm.s.StatTSCSet, STAMTYPE_COUNTER, "/TM/TSC/Sets", STAMUNIT_OCCURENCES, "Calls to TMCpuTickSet.");
795 STAM_REG(pVM, &pVM->tm.s.StatTSCUnderflow, STAMTYPE_COUNTER, "/TM/TSC/Underflow", STAMUNIT_OCCURENCES, "TSC underflow; corrected with last seen value .");
796 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/TSC/Pause", STAMUNIT_OCCURENCES, "The number of times the TSC was paused.");
797 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/TSC/Resume", STAMUNIT_OCCURENCES, "The number of times the TSC was resumed.");
798#endif /* VBOX_WITH_STATISTICS */
799
800 for (VMCPUID i = 0; i < pVM->cCpus; i++)
801 {
802 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.offTSCRawSrc, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS, "TSC offset relative the raw source", "/TM/TSC/offCPU%u", i);
803#ifndef VBOX_WITHOUT_NS_ACCOUNTING
804# if defined(VBOX_WITH_STATISTICS) || defined(VBOX_WITH_NS_ACCOUNTING_STATS)
805 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsTotal, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Resettable: Total CPU run time.", "/TM/CPU/%02u", i);
806 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsExecuting, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_NS_PER_OCCURENCE, "Resettable: Time spent executing guest code.", "/TM/CPU/%02u/PrfExecuting", i);
807 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsExecLong, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_NS_PER_OCCURENCE, "Resettable: Time spent executing guest code - long hauls.", "/TM/CPU/%02u/PrfExecLong", i);
808 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsExecShort, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_NS_PER_OCCURENCE, "Resettable: Time spent executing guest code - short stretches.", "/TM/CPU/%02u/PrfExecShort", i);
809 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsExecTiny, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_NS_PER_OCCURENCE, "Resettable: Time spent executing guest code - tiny bits.", "/TM/CPU/%02u/PrfExecTiny", i);
810 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsHalted, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_NS_PER_OCCURENCE, "Resettable: Time spent halted.", "/TM/CPU/%02u/PrfHalted", i);
811 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsOther, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_NS_PER_OCCURENCE, "Resettable: Time spent in the VMM or preempted.", "/TM/CPU/%02u/PrfOther", i);
812# endif
813 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsTotal, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Total CPU run time.", "/TM/CPU/%02u/cNsTotal", i);
814 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsExecuting, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent executing guest code.", "/TM/CPU/%02u/cNsExecuting", i);
815 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsHalted, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent halted.", "/TM/CPU/%02u/cNsHalted", i);
816 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsOther, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent in the VMM or preempted.", "/TM/CPU/%02u/cNsOther", i);
817 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cPeriodsExecuting, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT, "Times executed guest code.", "/TM/CPU/%02u/cPeriodsExecuting", i);
818 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cPeriodsHalted, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT, "Times halted.", "/TM/CPU/%02u/cPeriodsHalted", i);
819 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.CpuLoad.cPctExecuting, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent executing guest code recently.", "/TM/CPU/%02u/pctExecuting", i);
820 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.CpuLoad.cPctHalted, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent halted recently.", "/TM/CPU/%02u/pctHalted", i);
821 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.CpuLoad.cPctOther, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent in the VMM or preempted recently.", "/TM/CPU/%02u/pctOther", i);
822#endif
823 }
824#ifndef VBOX_WITHOUT_NS_ACCOUNTING
825 STAMR3RegisterF(pVM, &pVM->tm.s.CpuLoad.cPctExecuting, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent executing guest code recently.", "/TM/CPU/pctExecuting");
826 STAMR3RegisterF(pVM, &pVM->tm.s.CpuLoad.cPctHalted, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent halted recently.", "/TM/CPU/pctHalted");
827 STAMR3RegisterF(pVM, &pVM->tm.s.CpuLoad.cPctOther, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent in the VMM or preempted recently.", "/TM/CPU/pctOther");
828#endif
829
830#ifdef VBOX_WITH_STATISTICS
831 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.");
832 STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
833 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)");
834 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncFF, STAMTYPE_PROFILE, "/TM/VirtualSync/FF", STAMUNIT_TICKS_PER_OCCURENCE, "Time spent in TMR3VirtualSyncFF by all but the dedicate timer EMT.");
835 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
836 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++.)");
837 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
838 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
839 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.");
840 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
841 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.)");
842 for (unsigned i = 0; i < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods); i++)
843 {
844 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
845 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
846 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
847 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);
848 }
849#endif /* VBOX_WITH_STATISTICS */
850
851 /*
852 * Register info handlers.
853 */
854 DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
855 DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
856 DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
857
858 return VINF_SUCCESS;
859}
860
861
862/**
863 * Checks if the host CPU has a fixed TSC frequency.
864 *
865 * @returns true if it has, false if it hasn't.
866 *
867 * @remark This test doesn't bother with very old CPUs that don't do power
868 * management or any other stuff that might influence the TSC rate.
869 * This isn't currently relevant.
870 */
871static bool tmR3HasFixedTSC(PVM pVM)
872{
873 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
874 if (pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC)
875 return true;
876
877 if (ASMHasCpuId())
878 {
879 uint32_t uEAX, uEBX, uECX, uEDX;
880
881 if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_AMD)
882 {
883 /** @todo This is redundant as it would get satisified in the invariant case
884 * above. Remove later or keep around for sync mode override? */
885 /*
886 * AuthenticAMD - Check for APM support and that TscInvariant is set.
887 *
888 * This test isn't correct with respect to fixed/non-fixed TSC and
889 * older models, but this isn't relevant since the result is currently
890 * only used for making a decision on AMD-V models.
891 */
892 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
893 if (uEAX >= 0x80000007)
894 {
895 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
896 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
897 && ( pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* No fixed tsc if the gip timer is in async mode. */
898 || pGip->u32Mode == SUPGIPMODE_INVARIANT_TSC))
899 return true;
900 }
901 }
902 else if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_INTEL)
903 {
904 /*
905 * GenuineIntel - Check the model number.
906 *
907 * This test is lacking in the same way and for the same reasons
908 * as the AMD test above.
909 */
910 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
911 unsigned uModel = (uEAX >> 4) & 0x0f;
912 unsigned uFamily = (uEAX >> 8) & 0x0f;
913 if (uFamily == 0x0f)
914 uFamily += (uEAX >> 20) & 0xff;
915 if (uFamily >= 0x06)
916 uModel += ((uEAX >> 16) & 0x0f) << 4;
917 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
918 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
919 return true;
920 }
921 else if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_VIA)
922 {
923 /*
924 * CentaurHauls - Check the model, family and stepping.
925 *
926 * This only checks for VIA CPU models Nano X2, Nano X3,
927 * Eden X2 and QuadCore.
928 */
929 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
930 unsigned uStepping = (uEAX & 0x0f);
931 unsigned uModel = (uEAX >> 4) & 0x0f;
932 unsigned uFamily = (uEAX >> 8) & 0x0f;
933 if ( uFamily == 0x06
934 && uModel == 0x0f
935 && uStepping >= 0x0c
936 && uStepping <= 0x0f)
937 {
938 return true;
939 }
940 }
941 }
942 return false;
943}
944
945
946/**
947 * Checks if we really need to apply the delta values when calculating time.
948 *
949 * Getting the delta for a CPU is _very_ expensive, it more than doubles the
950 * execution time for RTTimeNanoTS.
951 *
952 * @returns true if deltas needs to be applied, false if not.
953 * @param pGip The GIP.
954 */
955static bool tmR3ReallyNeedDeltas(PSUPGLOBALINFOPAGE pGip)
956{
957 if (!pGip->fOsTscDeltasInSync)
958 {
959 uint32_t i = pGip->cCpus;
960 while (i-- > 0)
961 if ( pGip->aCPUs[i].enmState == SUPGIPCPUSTATE_ONLINE
962 && ( pGip->aCPUs[i].i64TSCDelta > 384
963 || pGip->aCPUs[i].i64TSCDelta < -384) )
964 return true;
965 }
966 return false;
967}
968
969
970/**
971 * Calibrate the CPU tick.
972 *
973 * @returns Number of ticks per second.
974 */
975static uint64_t tmR3CalibrateTSC(PVM pVM)
976{
977 /*
978 * Use GIP when available.
979 */
980 uint64_t u64Hz = SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage);
981 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_INVARIANT_TSC)
982 {
983 Assert(u64Hz != UINT64_MAX);
984 return u64Hz;
985 }
986
987 if (u64Hz != UINT64_MAX)
988 {
989 if (tmR3HasFixedTSC(pVM))
990 /* Sleep a bit to get a more reliable CpuHz value. */
991 RTThreadSleep(32);
992 else
993 {
994 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
995 const uint64_t u64 = RTTimeMilliTS();
996 while ((RTTimeMilliTS() - u64) < 40 /* ms */)
997 /* nothing */;
998 }
999
1000 u64Hz = SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage);
1001 if (u64Hz != UINT64_MAX)
1002 return u64Hz;
1003 }
1004
1005 /* Call this once first to make sure it's initialized. */
1006 RTTimeNanoTS();
1007
1008 /*
1009 * Yield the CPU to increase our chances of getting
1010 * a correct value.
1011 */
1012 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
1013 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
1014 uint64_t au64Samples[5];
1015 unsigned i;
1016 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
1017 {
1018 RTMSINTERVAL cMillies;
1019 int cTries = 5;
1020 uint64_t u64Start = ASMReadTSC();
1021 uint64_t u64End;
1022 uint64_t StartTS = RTTimeNanoTS();
1023 uint64_t EndTS;
1024 do
1025 {
1026 RTThreadSleep(s_auSleep[i]);
1027 u64End = ASMReadTSC();
1028 EndTS = RTTimeNanoTS();
1029 cMillies = (RTMSINTERVAL)((EndTS - StartTS + 500000) / 1000000);
1030 } while ( cMillies == 0 /* the sleep may be interrupted... */
1031 || (cMillies < 20 && --cTries > 0));
1032 uint64_t u64Diff = u64End - u64Start;
1033
1034 au64Samples[i] = (u64Diff * 1000) / cMillies;
1035 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
1036 }
1037
1038 /*
1039 * Discard the highest and lowest results and calculate the average.
1040 */
1041 unsigned iHigh = 0;
1042 unsigned iLow = 0;
1043 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
1044 {
1045 if (au64Samples[i] < au64Samples[iLow])
1046 iLow = i;
1047 if (au64Samples[i] > au64Samples[iHigh])
1048 iHigh = i;
1049 }
1050 au64Samples[iLow] = 0;
1051 au64Samples[iHigh] = 0;
1052
1053 u64Hz = au64Samples[0];
1054 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
1055 u64Hz += au64Samples[i];
1056 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
1057
1058 return u64Hz;
1059}
1060
1061
1062/**
1063 * Translation of pfnVirtualGetRawR3 to symbol names.
1064 *
1065 * @remarks This is a global variable because some gcc versions have their
1066 * attribute/visibility warnings messed up.
1067 */
1068static const struct
1069{
1070 PFNTIMENANOTSINTERNAL pfnR3Worker;
1071 const char *pszName;
1072} g_aNanoTsWorkers[] =
1073{
1074#define ENTRY(a) { a, #a }
1075 ENTRY(RTTimeNanoTSLegacyAsync),
1076 ENTRY(RTTimeNanoTSLegacyInvariantNoDelta),
1077 ENTRY(RTTimeNanoTSLegacyInvariantWithDelta),
1078 ENTRY(RTTimeNanoTSLegacySyncNoDelta),
1079 ENTRY(RTTimeNanoTSLegacySyncWithDelta),
1080 ENTRY(RTTimeNanoTSLFenceAsync),
1081 ENTRY(RTTimeNanoTSLFenceInvariantNoDelta),
1082 ENTRY(RTTimeNanoTSLFenceInvariantWithDelta),
1083 ENTRY(RTTimeNanoTSLFenceSyncNoDelta),
1084 ENTRY(RTTimeNanoTSLFenceSyncWithDelta),
1085#undef ENTRY
1086};
1087
1088
1089/**
1090 * Translates TM::pfnVirtualGetRawR3 to a symbol name that we can find in ring-0
1091 * and raw-mode context.
1092 *
1093 * @returns Symbol name.
1094 * @param pfnWorkerR3 The TM::pfnVirtualGetRawR3 value.
1095 */
1096static const char *tmR3GetRTTimeNanoName(PFNTIMENANOTSINTERNAL pfnR3Worker)
1097{
1098 for (uint32_t iNanoTs = 0; iNanoTs < RT_ELEMENTS(g_aNanoTsWorkers); iNanoTs++)
1099 if (pfnR3Worker == g_aNanoTsWorkers[iNanoTs].pfnR3Worker)
1100 return g_aNanoTsWorkers[iNanoTs].pszName;
1101 AssertFatalFailed();
1102 return NULL;
1103}
1104
1105
1106/**
1107 * Finalizes the TM initialization.
1108 *
1109 * @returns VBox status code.
1110 * @param pVM Pointer to the VM.
1111 */
1112VMM_INT_DECL(int) TMR3InitFinalize(PVM pVM)
1113{
1114 int rc;
1115
1116 /*
1117 * Resolve symbols.
1118 */
1119 const char *pszRTTimeNanoTS = tmR3GetRTTimeNanoName(pVM->tm.s.pfnVirtualGetRawR3);
1120 if (!HMIsEnabled(pVM))
1121 {
1122 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
1123 AssertRCReturn(rc, rc);
1124 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
1125 AssertRCReturn(rc, rc);
1126 rc = PDMR3LdrGetSymbolRC(pVM, NULL, pszRTTimeNanoTS, &pVM->tm.s.pfnVirtualGetRawRC);
1127 AssertRCReturn(rc, rc);
1128 }
1129
1130 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
1131 AssertRCReturn(rc, rc);
1132 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
1133 AssertRCReturn(rc, rc);
1134 rc = PDMR3LdrGetSymbolR0(pVM, NULL, pszRTTimeNanoTS, &pVM->tm.s.pfnVirtualGetRawR0);
1135 AssertRCReturn(rc, rc);
1136
1137#ifndef VBOX_WITHOUT_NS_ACCOUNTING
1138 /*
1139 * Create a timer for refreshing the CPU load stats.
1140 */
1141 PTMTIMER pTimer;
1142 rc = TMR3TimerCreateInternal(pVM, TMCLOCK_REAL, tmR3CpuLoadTimer, NULL, "CPU Load Timer", &pTimer);
1143 if (RT_SUCCESS(rc))
1144 rc = TMTimerSetMillies(pTimer, 1000);
1145#endif
1146
1147 /*
1148 * GIM is now initialized. Determine if TSC mode switching is allowed (respecting CFGM override).
1149 */
1150 pVM->tm.s.fTSCModeSwitchAllowed &= GIMIsEnabled(pVM) && HMIsEnabled(pVM);
1151 return rc;
1152}
1153
1154
1155/**
1156 * Applies relocations to data and code managed by this
1157 * component. This function will be called at init and
1158 * whenever the VMM need to relocate it self inside the GC.
1159 *
1160 * @param pVM The VM.
1161 * @param offDelta Relocation delta relative to old location.
1162 */
1163VMM_INT_DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
1164{
1165 int rc;
1166 LogFlow(("TMR3Relocate\n"));
1167 NOREF(offDelta);
1168
1169 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
1170
1171 if (!HMIsEnabled(pVM))
1172 {
1173 pVM->tm.s.pvGIPRC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
1174 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
1175 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
1176 AssertFatal(pVM->tm.s.VirtualGetRawDataRC.pu64Prev);
1177 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
1178 AssertFatalRC(rc);
1179 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
1180 AssertFatalRC(rc);
1181 const char *pszRTTimeNanoTS = tmR3GetRTTimeNanoName(pVM->tm.s.pfnVirtualGetRawR3);
1182 rc = PDMR3LdrGetSymbolRC(pVM, NULL, pszRTTimeNanoTS, &pVM->tm.s.pfnVirtualGetRawRC);
1183 AssertFatalRC(rc);
1184 }
1185
1186 /*
1187 * Iterate the timers updating the pVMRC pointers.
1188 */
1189 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1190 {
1191 pTimer->pVMRC = pVM->pVMRC;
1192 pTimer->pVMR0 = pVM->pVMR0;
1193 }
1194}
1195
1196
1197/**
1198 * Terminates the TM.
1199 *
1200 * Termination means cleaning up and freeing all resources,
1201 * the VM it self is at this point powered off or suspended.
1202 *
1203 * @returns VBox status code.
1204 * @param pVM Pointer to the VM.
1205 */
1206VMM_INT_DECL(int) TMR3Term(PVM pVM)
1207{
1208 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
1209 if (pVM->tm.s.pTimer)
1210 {
1211 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
1212 AssertRC(rc);
1213 pVM->tm.s.pTimer = NULL;
1214 }
1215
1216 return VINF_SUCCESS;
1217}
1218
1219
1220/**
1221 * The VM is being reset.
1222 *
1223 * For the TM component this means that a rescheduling is preformed,
1224 * the FF is cleared and but without running the queues. We'll have to
1225 * check if this makes sense or not, but it seems like a good idea now....
1226 *
1227 * @param pVM Pointer to the VM.
1228 */
1229VMM_INT_DECL(void) TMR3Reset(PVM pVM)
1230{
1231 LogFlow(("TMR3Reset:\n"));
1232 VM_ASSERT_EMT(pVM);
1233 TM_LOCK_TIMERS(pVM);
1234
1235 /*
1236 * Abort any pending catch up.
1237 * This isn't perfect...
1238 */
1239 if (pVM->tm.s.fVirtualSyncCatchUp)
1240 {
1241 const uint64_t offVirtualNow = TMVirtualGetNoCheck(pVM);
1242 const uint64_t offVirtualSyncNow = TMVirtualSyncGetNoCheck(pVM);
1243 if (pVM->tm.s.fVirtualSyncCatchUp)
1244 {
1245 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1246
1247 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
1248 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
1249 Assert(offOld <= offNew);
1250 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1251 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
1252 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1253 LogRel(("TM: Aborting catch-up attempt on reset with a %'RU64 ns lag on reset; new total: %'RU64 ns\n", offNew - offOld, offNew));
1254 }
1255 }
1256
1257 /*
1258 * Process the queues.
1259 */
1260 for (int i = 0; i < TMCLOCK_MAX; i++)
1261 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
1262#ifdef VBOX_STRICT
1263 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
1264#endif
1265
1266 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1267 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /** @todo FIXME: this isn't right. */
1268
1269 /*
1270 * Switch TM TSC mode back to the original mode after a reset for
1271 * paravirtualized guests that alter the TM TSC mode during operation.
1272 */
1273 if ( pVM->tm.s.fTSCModeSwitchAllowed
1274 && pVM->tm.s.enmTSCMode != pVM->tm.s.enmOriginalTSCMode)
1275 {
1276 bool fParavirtTSC = false;
1277 tmR3CpuTickParavirtToggle(pVM, NULL /* pVCpuEmt */, &fParavirtTSC);
1278 }
1279 Assert(!GIMIsParavirtTscEnabled(pVM));
1280 pVM->tm.s.fParavirtTscEnabled = false;
1281
1282 TM_UNLOCK_TIMERS(pVM);
1283}
1284
1285
1286/**
1287 * Resolve a builtin RC symbol.
1288 * Called by PDM when loading or relocating GC modules.
1289 *
1290 * @returns VBox status
1291 * @param pVM Pointer to the VM.
1292 * @param pszSymbol Symbol to resolve.
1293 * @param pRCPtrValue Where to store the symbol value.
1294 * @remark This has to work before TMR3Relocate() is called.
1295 */
1296VMM_INT_DECL(int) TMR3GetImportRC(PVM pVM, const char *pszSymbol, PRTRCPTR pRCPtrValue)
1297{
1298 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
1299 *pRCPtrValue = MMHyperR3ToRC(pVM, &pVM->tm.s.pvGIPRC);
1300 //else if (..)
1301 else
1302 return VERR_SYMBOL_NOT_FOUND;
1303 return VINF_SUCCESS;
1304}
1305
1306
1307/**
1308 * Execute state save operation.
1309 *
1310 * @returns VBox status code.
1311 * @param pVM Pointer to the VM.
1312 * @param pSSM SSM operation handle.
1313 */
1314static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
1315{
1316 LogFlow(("tmR3Save:\n"));
1317#ifdef VBOX_STRICT
1318 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1319 {
1320 PVMCPU pVCpu = &pVM->aCpus[i];
1321 Assert(!pVCpu->tm.s.fTSCTicking);
1322 }
1323 Assert(!pVM->tm.s.cVirtualTicking);
1324 Assert(!pVM->tm.s.fVirtualSyncTicking);
1325 Assert(!pVM->tm.s.cTSCsTicking);
1326#endif
1327
1328 /*
1329 * Save the virtual clocks.
1330 */
1331 /* the virtual clock. */
1332 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
1333 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
1334
1335 /* the virtual timer synchronous clock. */
1336 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
1337 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
1338 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
1339 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
1340 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
1341
1342 /* real time clock */
1343 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
1344
1345 /* the cpu tick clock. */
1346 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1347 {
1348 PVMCPU pVCpu = &pVM->aCpus[i];
1349 SSMR3PutU64(pSSM, TMCpuTickGet(pVCpu));
1350 }
1351 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
1352}
1353
1354
1355/**
1356 * Execute state load operation.
1357 *
1358 * @returns VBox status code.
1359 * @param pVM Pointer to the VM.
1360 * @param pSSM SSM operation handle.
1361 * @param uVersion Data layout version.
1362 * @param uPass The data pass.
1363 */
1364static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1365{
1366 LogFlow(("tmR3Load:\n"));
1367
1368 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
1369#ifdef VBOX_STRICT
1370 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1371 {
1372 PVMCPU pVCpu = &pVM->aCpus[i];
1373 Assert(!pVCpu->tm.s.fTSCTicking);
1374 }
1375 Assert(!pVM->tm.s.cVirtualTicking);
1376 Assert(!pVM->tm.s.fVirtualSyncTicking);
1377 Assert(!pVM->tm.s.cTSCsTicking);
1378#endif
1379
1380 /*
1381 * Validate version.
1382 */
1383 if (uVersion != TM_SAVED_STATE_VERSION)
1384 {
1385 AssertMsgFailed(("tmR3Load: Invalid version uVersion=%d!\n", uVersion));
1386 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1387 }
1388
1389 /*
1390 * Load the virtual clock.
1391 */
1392 pVM->tm.s.cVirtualTicking = 0;
1393 /* the virtual clock. */
1394 uint64_t u64Hz;
1395 int rc = SSMR3GetU64(pSSM, &u64Hz);
1396 if (RT_FAILURE(rc))
1397 return rc;
1398 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
1399 {
1400 AssertMsgFailed(("The virtual clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1401 u64Hz, TMCLOCK_FREQ_VIRTUAL));
1402 return VERR_SSM_VIRTUAL_CLOCK_HZ;
1403 }
1404 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
1405 pVM->tm.s.u64VirtualOffset = 0;
1406
1407 /* the virtual timer synchronous clock. */
1408 pVM->tm.s.fVirtualSyncTicking = false;
1409 uint64_t u64;
1410 SSMR3GetU64(pSSM, &u64);
1411 pVM->tm.s.u64VirtualSync = u64;
1412 SSMR3GetU64(pSSM, &u64);
1413 pVM->tm.s.offVirtualSync = u64;
1414 SSMR3GetU64(pSSM, &u64);
1415 pVM->tm.s.offVirtualSyncGivenUp = u64;
1416 SSMR3GetU64(pSSM, &u64);
1417 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1418 bool f;
1419 SSMR3GetBool(pSSM, &f);
1420 pVM->tm.s.fVirtualSyncCatchUp = f;
1421
1422 /* the real clock */
1423 rc = SSMR3GetU64(pSSM, &u64Hz);
1424 if (RT_FAILURE(rc))
1425 return rc;
1426 if (u64Hz != TMCLOCK_FREQ_REAL)
1427 {
1428 AssertMsgFailed(("The real clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1429 u64Hz, TMCLOCK_FREQ_REAL));
1430 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* misleading... */
1431 }
1432
1433 /* the cpu tick clock. */
1434 pVM->tm.s.cTSCsTicking = 0;
1435 pVM->tm.s.offTSCPause = 0;
1436 pVM->tm.s.u64LastPausedTSC = 0;
1437 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1438 {
1439 PVMCPU pVCpu = &pVM->aCpus[i];
1440
1441 pVCpu->tm.s.fTSCTicking = false;
1442 SSMR3GetU64(pSSM, &pVCpu->tm.s.u64TSC);
1443 if (pVM->tm.s.u64LastPausedTSC < pVCpu->tm.s.u64TSC)
1444 pVM->tm.s.u64LastPausedTSC = pVCpu->tm.s.u64TSC;
1445
1446 if (pVM->tm.s.enmTSCMode == TMTSCMODE_REAL_TSC_OFFSET)
1447 pVCpu->tm.s.offTSCRawSrc = 0; /** @todo TSC restore stuff and HWACC. */
1448 }
1449
1450 rc = SSMR3GetU64(pSSM, &u64Hz);
1451 if (RT_FAILURE(rc))
1452 return rc;
1453 if (pVM->tm.s.enmTSCMode != TMTSCMODE_REAL_TSC_OFFSET)
1454 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1455 /** @todo Compare with real TSC rate even when restoring with real-tsc-offset
1456 * mode. */
1457
1458 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%'RU64) enmTSCMode=%d (%s) (state load)\n",
1459 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.enmTSCMode, tmR3GetTSCModeName(pVM)));
1460
1461 /*
1462 * Make sure timers get rescheduled immediately.
1463 */
1464 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1465 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1466
1467 return VINF_SUCCESS;
1468}
1469
1470
1471/**
1472 * Internal TMR3TimerCreate worker.
1473 *
1474 * @returns VBox status code.
1475 * @param pVM Pointer to the VM.
1476 * @param enmClock The timer clock.
1477 * @param pszDesc The timer description.
1478 * @param ppTimer Where to store the timer pointer on success.
1479 */
1480static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1481{
1482 VM_ASSERT_EMT(pVM);
1483
1484 /*
1485 * Allocate the timer.
1486 */
1487 PTMTIMERR3 pTimer = NULL;
1488 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1489 {
1490 pTimer = pVM->tm.s.pFree;
1491 pVM->tm.s.pFree = pTimer->pBigNext;
1492 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1493 }
1494
1495 if (!pTimer)
1496 {
1497 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1498 if (RT_FAILURE(rc))
1499 return rc;
1500 Log3(("TM: Allocated new timer %p\n", pTimer));
1501 }
1502
1503 /*
1504 * Initialize it.
1505 */
1506 pTimer->u64Expire = 0;
1507 pTimer->enmClock = enmClock;
1508 pTimer->pVMR3 = pVM;
1509 pTimer->pVMR0 = pVM->pVMR0;
1510 pTimer->pVMRC = pVM->pVMRC;
1511 pTimer->enmState = TMTIMERSTATE_STOPPED;
1512 pTimer->offScheduleNext = 0;
1513 pTimer->offNext = 0;
1514 pTimer->offPrev = 0;
1515 pTimer->pvUser = NULL;
1516 pTimer->pCritSect = NULL;
1517 pTimer->pszDesc = pszDesc;
1518
1519 /* insert into the list of created timers. */
1520 TM_LOCK_TIMERS(pVM);
1521 pTimer->pBigPrev = NULL;
1522 pTimer->pBigNext = pVM->tm.s.pCreated;
1523 pVM->tm.s.pCreated = pTimer;
1524 if (pTimer->pBigNext)
1525 pTimer->pBigNext->pBigPrev = pTimer;
1526#ifdef VBOX_STRICT
1527 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1528#endif
1529 TM_UNLOCK_TIMERS(pVM);
1530
1531 *ppTimer = pTimer;
1532 return VINF_SUCCESS;
1533}
1534
1535
1536/**
1537 * Creates a device timer.
1538 *
1539 * @returns VBox status.
1540 * @param pVM The VM to create the timer in.
1541 * @param pDevIns Device instance.
1542 * @param enmClock The clock to use on this timer.
1543 * @param pfnCallback Callback function.
1544 * @param pvUser The user argument to the callback.
1545 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1546 * @param pszDesc Pointer to description string which must stay around
1547 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1548 * @param ppTimer Where to store the timer on success.
1549 */
1550VMM_INT_DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock,
1551 PFNTMTIMERDEV pfnCallback, void *pvUser,
1552 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1553{
1554 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1555
1556 /*
1557 * Allocate and init stuff.
1558 */
1559 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1560 if (RT_SUCCESS(rc))
1561 {
1562 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1563 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1564 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1565 (*ppTimer)->pvUser = pvUser;
1566 if (!(fFlags & TMTIMER_FLAGS_NO_CRIT_SECT))
1567 (*ppTimer)->pCritSect = PDMR3DevGetCritSect(pVM, pDevIns);
1568 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1569 }
1570
1571 return rc;
1572}
1573
1574
1575
1576
1577/**
1578 * Creates a USB device timer.
1579 *
1580 * @returns VBox status.
1581 * @param pVM The VM to create the timer in.
1582 * @param pUsbIns The USB device instance.
1583 * @param enmClock The clock to use on this timer.
1584 * @param pfnCallback Callback function.
1585 * @param pvUser The user argument to the callback.
1586 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1587 * @param pszDesc Pointer to description string which must stay around
1588 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1589 * @param ppTimer Where to store the timer on success.
1590 */
1591VMM_INT_DECL(int) TMR3TimerCreateUsb(PVM pVM, PPDMUSBINS pUsbIns, TMCLOCK enmClock,
1592 PFNTMTIMERUSB pfnCallback, void *pvUser,
1593 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1594{
1595 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1596
1597 /*
1598 * Allocate and init stuff.
1599 */
1600 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1601 if (RT_SUCCESS(rc))
1602 {
1603 (*ppTimer)->enmType = TMTIMERTYPE_USB;
1604 (*ppTimer)->u.Usb.pfnTimer = pfnCallback;
1605 (*ppTimer)->u.Usb.pUsbIns = pUsbIns;
1606 (*ppTimer)->pvUser = pvUser;
1607 //if (!(fFlags & TMTIMER_FLAGS_NO_CRIT_SECT))
1608 //{
1609 // if (pDevIns->pCritSectR3)
1610 // (*ppTimer)->pCritSect = pUsbIns->pCritSectR3;
1611 // else
1612 // (*ppTimer)->pCritSect = IOMR3GetCritSect(pVM);
1613 //}
1614 Log(("TM: Created USB device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1615 }
1616
1617 return rc;
1618}
1619
1620
1621/**
1622 * Creates a driver timer.
1623 *
1624 * @returns VBox status.
1625 * @param pVM The VM to create the timer in.
1626 * @param pDrvIns Driver instance.
1627 * @param enmClock The clock to use on this timer.
1628 * @param pfnCallback Callback function.
1629 * @param pvUser The user argument to the callback.
1630 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1631 * @param pszDesc Pointer to description string which must stay around
1632 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1633 * @param ppTimer Where to store the timer on success.
1634 */
1635VMM_INT_DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, void *pvUser,
1636 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1637{
1638 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1639
1640 /*
1641 * Allocate and init stuff.
1642 */
1643 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1644 if (RT_SUCCESS(rc))
1645 {
1646 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1647 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1648 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1649 (*ppTimer)->pvUser = pvUser;
1650 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1651 }
1652
1653 return rc;
1654}
1655
1656
1657/**
1658 * Creates an internal timer.
1659 *
1660 * @returns VBox status.
1661 * @param pVM The VM to create the timer in.
1662 * @param enmClock The clock to use on this timer.
1663 * @param pfnCallback Callback function.
1664 * @param pvUser User argument to be passed to the callback.
1665 * @param pszDesc Pointer to description string which must stay around
1666 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1667 * @param ppTimer Where to store the timer on success.
1668 */
1669VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1670{
1671 /*
1672 * Allocate and init stuff.
1673 */
1674 PTMTIMER pTimer;
1675 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1676 if (RT_SUCCESS(rc))
1677 {
1678 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1679 pTimer->u.Internal.pfnTimer = pfnCallback;
1680 pTimer->pvUser = pvUser;
1681 *ppTimer = pTimer;
1682 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1683 }
1684
1685 return rc;
1686}
1687
1688/**
1689 * Creates an external timer.
1690 *
1691 * @returns Timer handle on success.
1692 * @returns NULL on failure.
1693 * @param pVM The VM to create the timer in.
1694 * @param enmClock The clock to use on this timer.
1695 * @param pfnCallback Callback function.
1696 * @param pvUser User argument.
1697 * @param pszDesc Pointer to description string which must stay around
1698 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1699 */
1700VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1701{
1702 /*
1703 * Allocate and init stuff.
1704 */
1705 PTMTIMERR3 pTimer;
1706 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1707 if (RT_SUCCESS(rc))
1708 {
1709 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1710 pTimer->u.External.pfnTimer = pfnCallback;
1711 pTimer->pvUser = pvUser;
1712 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1713 return pTimer;
1714 }
1715
1716 return NULL;
1717}
1718
1719
1720/**
1721 * Destroy a timer
1722 *
1723 * @returns VBox status.
1724 * @param pTimer Timer handle as returned by one of the create functions.
1725 */
1726VMMR3DECL(int) TMR3TimerDestroy(PTMTIMER pTimer)
1727{
1728 /*
1729 * Be extra careful here.
1730 */
1731 if (!pTimer)
1732 return VINF_SUCCESS;
1733 AssertPtr(pTimer);
1734 Assert((unsigned)pTimer->enmClock < (unsigned)TMCLOCK_MAX);
1735
1736 PVM pVM = pTimer->CTX_SUFF(pVM);
1737 PTMTIMERQUEUE pQueue = &pVM->tm.s.CTX_SUFF(paTimerQueues)[pTimer->enmClock];
1738 bool fActive = false;
1739 bool fPending = false;
1740
1741 AssertMsg( !pTimer->pCritSect
1742 || VMR3GetState(pVM) != VMSTATE_RUNNING
1743 || PDMCritSectIsOwner(pTimer->pCritSect), ("%s\n", pTimer->pszDesc));
1744
1745 /*
1746 * The rest of the game happens behind the lock, just
1747 * like create does. All the work is done here.
1748 */
1749 TM_LOCK_TIMERS(pVM);
1750 for (int cRetries = 1000;; cRetries--)
1751 {
1752 /*
1753 * Change to the DESTROY state.
1754 */
1755 TMTIMERSTATE const enmState = pTimer->enmState;
1756 Log2(("TMTimerDestroy: %p:{.enmState=%s, .pszDesc='%s'} cRetries=%d\n",
1757 pTimer, tmTimerState(enmState), R3STRING(pTimer->pszDesc), cRetries));
1758 switch (enmState)
1759 {
1760 case TMTIMERSTATE_STOPPED:
1761 case TMTIMERSTATE_EXPIRED_DELIVER:
1762 break;
1763
1764 case TMTIMERSTATE_ACTIVE:
1765 fActive = true;
1766 break;
1767
1768 case TMTIMERSTATE_PENDING_STOP:
1769 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1770 case TMTIMERSTATE_PENDING_RESCHEDULE:
1771 fActive = true;
1772 fPending = true;
1773 break;
1774
1775 case TMTIMERSTATE_PENDING_SCHEDULE:
1776 fPending = true;
1777 break;
1778
1779 /*
1780 * This shouldn't happen as the caller should make sure there are no races.
1781 */
1782 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
1783 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1784 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1785 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1786 TM_UNLOCK_TIMERS(pVM);
1787 if (!RTThreadYield())
1788 RTThreadSleep(1);
1789 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1790 VERR_TM_UNSTABLE_STATE);
1791 TM_LOCK_TIMERS(pVM);
1792 continue;
1793
1794 /*
1795 * Invalid states.
1796 */
1797 case TMTIMERSTATE_FREE:
1798 case TMTIMERSTATE_DESTROY:
1799 TM_UNLOCK_TIMERS(pVM);
1800 AssertLogRelMsgFailedReturn(("pTimer=%p %s\n", pTimer, tmTimerState(enmState)), VERR_TM_INVALID_STATE);
1801
1802 default:
1803 AssertMsgFailed(("Unknown timer state %d (%s)\n", enmState, R3STRING(pTimer->pszDesc)));
1804 TM_UNLOCK_TIMERS(pVM);
1805 return VERR_TM_UNKNOWN_STATE;
1806 }
1807
1808 /*
1809 * Try switch to the destroy state.
1810 * This should always succeed as the caller should make sure there are no race.
1811 */
1812 bool fRc;
1813 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_DESTROY, enmState, fRc);
1814 if (fRc)
1815 break;
1816 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1817 TM_UNLOCK_TIMERS(pVM);
1818 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1819 VERR_TM_UNSTABLE_STATE);
1820 TM_LOCK_TIMERS(pVM);
1821 }
1822
1823 /*
1824 * Unlink from the active list.
1825 */
1826 if (fActive)
1827 {
1828 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1829 const PTMTIMER pNext = TMTIMER_GET_NEXT(pTimer);
1830 if (pPrev)
1831 TMTIMER_SET_NEXT(pPrev, pNext);
1832 else
1833 {
1834 TMTIMER_SET_HEAD(pQueue, pNext);
1835 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1836 }
1837 if (pNext)
1838 TMTIMER_SET_PREV(pNext, pPrev);
1839 pTimer->offNext = 0;
1840 pTimer->offPrev = 0;
1841 }
1842
1843 /*
1844 * Unlink from the schedule list by running it.
1845 */
1846 if (fPending)
1847 {
1848 Log3(("TMR3TimerDestroy: tmTimerQueueSchedule\n"));
1849 STAM_PROFILE_START(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1850 Assert(pQueue->offSchedule);
1851 tmTimerQueueSchedule(pVM, pQueue);
1852 STAM_PROFILE_STOP(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1853 }
1854
1855 /*
1856 * Read to move the timer from the created list and onto the free list.
1857 */
1858 Assert(!pTimer->offNext); Assert(!pTimer->offPrev); Assert(!pTimer->offScheduleNext);
1859
1860 /* unlink from created list */
1861 if (pTimer->pBigPrev)
1862 pTimer->pBigPrev->pBigNext = pTimer->pBigNext;
1863 else
1864 pVM->tm.s.pCreated = pTimer->pBigNext;
1865 if (pTimer->pBigNext)
1866 pTimer->pBigNext->pBigPrev = pTimer->pBigPrev;
1867 pTimer->pBigNext = 0;
1868 pTimer->pBigPrev = 0;
1869
1870 /* free */
1871 Log2(("TM: Inserting %p into the free list ahead of %p!\n", pTimer, pVM->tm.s.pFree));
1872 TM_SET_STATE(pTimer, TMTIMERSTATE_FREE);
1873 pTimer->pBigNext = pVM->tm.s.pFree;
1874 pVM->tm.s.pFree = pTimer;
1875
1876#ifdef VBOX_STRICT
1877 tmTimerQueuesSanityChecks(pVM, "TMR3TimerDestroy");
1878#endif
1879 TM_UNLOCK_TIMERS(pVM);
1880 return VINF_SUCCESS;
1881}
1882
1883
1884/**
1885 * Destroy all timers owned by a device.
1886 *
1887 * @returns VBox status.
1888 * @param pVM Pointer to the VM.
1889 * @param pDevIns Device which timers should be destroyed.
1890 */
1891VMM_INT_DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1892{
1893 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1894 if (!pDevIns)
1895 return VERR_INVALID_PARAMETER;
1896
1897 TM_LOCK_TIMERS(pVM);
1898 PTMTIMER pCur = pVM->tm.s.pCreated;
1899 while (pCur)
1900 {
1901 PTMTIMER pDestroy = pCur;
1902 pCur = pDestroy->pBigNext;
1903 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1904 && pDestroy->u.Dev.pDevIns == pDevIns)
1905 {
1906 int rc = TMR3TimerDestroy(pDestroy);
1907 AssertRC(rc);
1908 }
1909 }
1910 TM_UNLOCK_TIMERS(pVM);
1911
1912 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1913 return VINF_SUCCESS;
1914}
1915
1916
1917/**
1918 * Destroy all timers owned by a USB device.
1919 *
1920 * @returns VBox status.
1921 * @param pVM Pointer to the VM.
1922 * @param pUsbIns USB device which timers should be destroyed.
1923 */
1924VMM_INT_DECL(int) TMR3TimerDestroyUsb(PVM pVM, PPDMUSBINS pUsbIns)
1925{
1926 LogFlow(("TMR3TimerDestroyUsb: pUsbIns=%p\n", pUsbIns));
1927 if (!pUsbIns)
1928 return VERR_INVALID_PARAMETER;
1929
1930 TM_LOCK_TIMERS(pVM);
1931 PTMTIMER pCur = pVM->tm.s.pCreated;
1932 while (pCur)
1933 {
1934 PTMTIMER pDestroy = pCur;
1935 pCur = pDestroy->pBigNext;
1936 if ( pDestroy->enmType == TMTIMERTYPE_USB
1937 && pDestroy->u.Usb.pUsbIns == pUsbIns)
1938 {
1939 int rc = TMR3TimerDestroy(pDestroy);
1940 AssertRC(rc);
1941 }
1942 }
1943 TM_UNLOCK_TIMERS(pVM);
1944
1945 LogFlow(("TMR3TimerDestroyUsb: returns VINF_SUCCESS\n"));
1946 return VINF_SUCCESS;
1947}
1948
1949
1950/**
1951 * Destroy all timers owned by a driver.
1952 *
1953 * @returns VBox status.
1954 * @param pVM Pointer to the VM.
1955 * @param pDrvIns Driver which timers should be destroyed.
1956 */
1957VMM_INT_DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1958{
1959 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1960 if (!pDrvIns)
1961 return VERR_INVALID_PARAMETER;
1962
1963 TM_LOCK_TIMERS(pVM);
1964 PTMTIMER pCur = pVM->tm.s.pCreated;
1965 while (pCur)
1966 {
1967 PTMTIMER pDestroy = pCur;
1968 pCur = pDestroy->pBigNext;
1969 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1970 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1971 {
1972 int rc = TMR3TimerDestroy(pDestroy);
1973 AssertRC(rc);
1974 }
1975 }
1976 TM_UNLOCK_TIMERS(pVM);
1977
1978 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1979 return VINF_SUCCESS;
1980}
1981
1982
1983/**
1984 * Internal function for getting the clock time.
1985 *
1986 * @returns clock time.
1987 * @param pVM Pointer to the VM.
1988 * @param enmClock The clock.
1989 */
1990DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
1991{
1992 switch (enmClock)
1993 {
1994 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
1995 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
1996 case TMCLOCK_REAL: return TMRealGet(pVM);
1997 case TMCLOCK_TSC: return TMCpuTickGet(&pVM->aCpus[0] /* just take VCPU 0 */);
1998 default:
1999 AssertMsgFailed(("enmClock=%d\n", enmClock));
2000 return ~(uint64_t)0;
2001 }
2002}
2003
2004
2005/**
2006 * Checks if the sync queue has one or more expired timers.
2007 *
2008 * @returns true / false.
2009 *
2010 * @param pVM Pointer to the VM.
2011 * @param enmClock The queue.
2012 */
2013DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
2014{
2015 const uint64_t u64Expire = pVM->tm.s.CTX_SUFF(paTimerQueues)[enmClock].u64Expire;
2016 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
2017}
2018
2019
2020/**
2021 * Checks for expired timers in all the queues.
2022 *
2023 * @returns true / false.
2024 * @param pVM Pointer to the VM.
2025 */
2026DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
2027{
2028 /*
2029 * Combine the time calculation for the first two since we're not on EMT
2030 * TMVirtualSyncGet only permits EMT.
2031 */
2032 uint64_t u64Now = TMVirtualGetNoCheck(pVM);
2033 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
2034 return true;
2035 u64Now = pVM->tm.s.fVirtualSyncTicking
2036 ? u64Now - pVM->tm.s.offVirtualSync
2037 : pVM->tm.s.u64VirtualSync;
2038 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
2039 return true;
2040
2041 /*
2042 * The remaining timers.
2043 */
2044 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
2045 return true;
2046 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
2047 return true;
2048 return false;
2049}
2050
2051
2052/**
2053 * Schedule timer callback.
2054 *
2055 * @param pTimer Timer handle.
2056 * @param pvUser Pointer to the VM.
2057 * @thread Timer thread.
2058 *
2059 * @remark We cannot do the scheduling and queues running from a timer handler
2060 * since it's not executing in EMT, and even if it was it would be async
2061 * and we wouldn't know the state of the affairs.
2062 * So, we'll just raise the timer FF and force any REM execution to exit.
2063 */
2064static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
2065{
2066 PVM pVM = (PVM)pvUser;
2067 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
2068 NOREF(pTimer);
2069
2070 AssertCompile(TMCLOCK_MAX == 4);
2071 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallback);
2072
2073#ifdef DEBUG_Sander /* very annoying, keep it private. */
2074 if (VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER))
2075 Log(("tmR3TimerCallback: timer event still pending!!\n"));
2076#endif
2077 if ( !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
2078 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule /** @todo FIXME - reconsider offSchedule as a reason for running the timer queues. */
2079 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
2080 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
2081 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
2082 || tmR3AnyExpiredTimers(pVM)
2083 )
2084 && !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
2085 && !pVM->tm.s.fRunningQueues
2086 )
2087 {
2088 Log5(("TM(%u): FF: 0 -> 1\n", __LINE__));
2089 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
2090#ifdef VBOX_WITH_REM
2091 REMR3NotifyTimerPending(pVM, pVCpuDst);
2092#endif
2093 VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM | VMNOTIFYFF_FLAGS_POKE);
2094 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
2095 }
2096}
2097
2098
2099/**
2100 * Schedules and runs any pending timers.
2101 *
2102 * This is normally called from a forced action handler in EMT.
2103 *
2104 * @param pVM The VM to run the timers for.
2105 *
2106 * @thread EMT (actually EMT0, but we fend off the others)
2107 */
2108VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
2109{
2110 /*
2111 * Only the dedicated timer EMT should do stuff here.
2112 * (fRunningQueues is only used as an indicator.)
2113 */
2114 Assert(pVM->tm.s.idTimerCpu < pVM->cCpus);
2115 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
2116 if (VMMGetCpu(pVM) != pVCpuDst)
2117 {
2118 Assert(pVM->cCpus > 1);
2119 return;
2120 }
2121 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
2122 Log2(("TMR3TimerQueuesDo:\n"));
2123 Assert(!pVM->tm.s.fRunningQueues);
2124 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, true);
2125 TM_LOCK_TIMERS(pVM);
2126
2127 /*
2128 * Process the queues.
2129 */
2130 AssertCompile(TMCLOCK_MAX == 4);
2131
2132 /* TMCLOCK_VIRTUAL_SYNC (see also TMR3VirtualSyncFF) */
2133 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
2134 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2135 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
2136 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /* Clear the FF once we started working for real. */
2137
2138 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule);
2139 tmR3TimerQueueRunVirtualSync(pVM);
2140 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
2141 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
2142
2143 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
2144 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2145 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
2146
2147 /* TMCLOCK_VIRTUAL */
2148 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
2149 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule)
2150 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
2151 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
2152 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
2153
2154 /* TMCLOCK_TSC */
2155 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offActive); /* not used */
2156
2157 /* TMCLOCK_REAL */
2158 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
2159 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule)
2160 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
2161 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
2162 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
2163
2164#ifdef VBOX_STRICT
2165 /* check that we didn't screw up. */
2166 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
2167#endif
2168
2169 /* done */
2170 Log2(("TMR3TimerQueuesDo: returns void\n"));
2171 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, false);
2172 TM_UNLOCK_TIMERS(pVM);
2173 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
2174}
2175
2176//RT_C_DECLS_BEGIN
2177//int iomLock(PVM pVM);
2178//void iomUnlock(PVM pVM);
2179//RT_C_DECLS_END
2180
2181
2182/**
2183 * Schedules and runs any pending times in the specified queue.
2184 *
2185 * This is normally called from a forced action handler in EMT.
2186 *
2187 * @param pVM The VM to run the timers for.
2188 * @param pQueue The queue to run.
2189 */
2190static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
2191{
2192 VM_ASSERT_EMT(pVM);
2193
2194 /*
2195 * Run timers.
2196 *
2197 * We check the clock once and run all timers which are ACTIVE
2198 * and have an expire time less or equal to the time we read.
2199 *
2200 * N.B. A generic unlink must be applied since other threads
2201 * are allowed to mess with any active timer at any time.
2202 * However, we only allow EMT to handle EXPIRED_PENDING
2203 * timers, thus enabling the timer handler function to
2204 * arm the timer again.
2205 */
2206 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
2207 if (!pNext)
2208 return;
2209 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
2210 while (pNext && pNext->u64Expire <= u64Now)
2211 {
2212 PTMTIMER pTimer = pNext;
2213 pNext = TMTIMER_GET_NEXT(pTimer);
2214 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2215 if (pCritSect)
2216 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2217 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2218 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2219 bool fRc;
2220 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_GET_UNLINK, TMTIMERSTATE_ACTIVE, fRc);
2221 if (fRc)
2222 {
2223 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
2224
2225 /* unlink */
2226 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
2227 if (pPrev)
2228 TMTIMER_SET_NEXT(pPrev, pNext);
2229 else
2230 {
2231 TMTIMER_SET_HEAD(pQueue, pNext);
2232 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
2233 }
2234 if (pNext)
2235 TMTIMER_SET_PREV(pNext, pPrev);
2236 pTimer->offNext = 0;
2237 pTimer->offPrev = 0;
2238
2239 /* fire */
2240 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2241 switch (pTimer->enmType)
2242 {
2243 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2244 case TMTIMERTYPE_USB: pTimer->u.Usb.pfnTimer(pTimer->u.Usb.pUsbIns, pTimer, pTimer->pvUser); break;
2245 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2246 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2247 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2248 default:
2249 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2250 break;
2251 }
2252
2253 /* change the state if it wasn't changed already in the handler. */
2254 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2255 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2256 }
2257 if (pCritSect)
2258 PDMCritSectLeave(pCritSect);
2259 } /* run loop */
2260}
2261
2262
2263/**
2264 * Schedules and runs any pending times in the timer queue for the
2265 * synchronous virtual clock.
2266 *
2267 * This scheduling is a bit different from the other queues as it need
2268 * to implement the special requirements of the timer synchronous virtual
2269 * clock, thus this 2nd queue run function.
2270 *
2271 * @param pVM The VM to run the timers for.
2272 *
2273 * @remarks The caller must the Virtual Sync lock. Owning the TM lock is no
2274 * longer important.
2275 */
2276static void tmR3TimerQueueRunVirtualSync(PVM pVM)
2277{
2278 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
2279 VM_ASSERT_EMT(pVM);
2280 Assert(PDMCritSectIsOwner(&pVM->tm.s.VirtualSyncLock));
2281
2282 /*
2283 * Any timers?
2284 */
2285 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
2286 if (RT_UNLIKELY(!pNext))
2287 {
2288 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.cVirtualTicking);
2289 return;
2290 }
2291 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
2292
2293 /*
2294 * Calculate the time frame for which we will dispatch timers.
2295 *
2296 * We use a time frame ranging from the current sync time (which is most likely the
2297 * same as the head timer) and some configurable period (100000ns) up towards the
2298 * current virtual time. This period might also need to be restricted by the catch-up
2299 * rate so frequent calls to this function won't accelerate the time too much, however
2300 * this will be implemented at a later point if necessary.
2301 *
2302 * Without this frame we would 1) having to run timers much more frequently
2303 * and 2) lag behind at a steady rate.
2304 */
2305 const uint64_t u64VirtualNow = TMVirtualGetNoCheck(pVM);
2306 uint64_t const offSyncGivenUp = pVM->tm.s.offVirtualSyncGivenUp;
2307 uint64_t u64Now;
2308 if (!pVM->tm.s.fVirtualSyncTicking)
2309 {
2310 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
2311 u64Now = pVM->tm.s.u64VirtualSync;
2312 Assert(u64Now <= pNext->u64Expire);
2313 }
2314 else
2315 {
2316 /* Calc 'now'. */
2317 bool fStopCatchup = false;
2318 bool fUpdateStuff = false;
2319 uint64_t off = pVM->tm.s.offVirtualSync;
2320 if (pVM->tm.s.fVirtualSyncCatchUp)
2321 {
2322 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
2323 if (RT_LIKELY(!(u64Delta >> 32)))
2324 {
2325 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
2326 if (off > u64Sub + offSyncGivenUp)
2327 {
2328 off -= u64Sub;
2329 Log4(("TM: %'RU64/-%'8RU64: sub %'RU64 [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow - off, off - offSyncGivenUp, u64Sub));
2330 }
2331 else
2332 {
2333 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2334 fStopCatchup = true;
2335 off = offSyncGivenUp;
2336 }
2337 fUpdateStuff = true;
2338 }
2339 }
2340 u64Now = u64VirtualNow - off;
2341
2342 /* Adjust against last returned time. */
2343 uint64_t u64Last = ASMAtomicUoReadU64(&pVM->tm.s.u64VirtualSync);
2344 if (u64Last > u64Now)
2345 {
2346 u64Now = u64Last + 1;
2347 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetAdjLast);
2348 }
2349
2350 /* Check if stopped by expired timer. */
2351 uint64_t const u64Expire = pNext->u64Expire;
2352 if (u64Now >= u64Expire)
2353 {
2354 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
2355 u64Now = u64Expire;
2356 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2357 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2358 Log4(("TM: %'RU64/-%'8RU64: exp tmr [tmR3TimerQueueRunVirtualSync]\n", u64Now, u64VirtualNow - u64Now - offSyncGivenUp));
2359 }
2360 else
2361 {
2362 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2363 if (fUpdateStuff)
2364 {
2365 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, off);
2366 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev, u64VirtualNow);
2367 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2368 if (fStopCatchup)
2369 {
2370 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2371 Log4(("TM: %'RU64/0: caught up [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow));
2372 }
2373 }
2374 }
2375 }
2376
2377 /* calc end of frame. */
2378 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
2379 if (u64Max > u64VirtualNow - offSyncGivenUp)
2380 u64Max = u64VirtualNow - offSyncGivenUp;
2381
2382 /* assert sanity */
2383 Assert(u64Now <= u64VirtualNow - offSyncGivenUp);
2384 Assert(u64Max <= u64VirtualNow - offSyncGivenUp);
2385 Assert(u64Now <= u64Max);
2386 Assert(offSyncGivenUp == pVM->tm.s.offVirtualSyncGivenUp);
2387
2388 /*
2389 * Process the expired timers moving the clock along as we progress.
2390 */
2391#ifdef VBOX_STRICT
2392 uint64_t u64Prev = u64Now; NOREF(u64Prev);
2393#endif
2394 while (pNext && pNext->u64Expire <= u64Max)
2395 {
2396 /* Advance */
2397 PTMTIMER pTimer = pNext;
2398 pNext = TMTIMER_GET_NEXT(pTimer);
2399
2400 /* Take the associated lock. */
2401 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2402 if (pCritSect)
2403 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2404
2405 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2406 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2407
2408 /* Advance the clock - don't permit timers to be out of order or armed
2409 in the 'past'. */
2410#ifdef VBOX_STRICT
2411 AssertMsg(pTimer->u64Expire >= u64Prev, ("%'RU64 < %'RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
2412 u64Prev = pTimer->u64Expire;
2413#endif
2414 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
2415 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2416
2417 /* Unlink it, change the state and do the callout. */
2418 tmTimerQueueUnlinkActive(pQueue, pTimer);
2419 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2420 switch (pTimer->enmType)
2421 {
2422 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2423 case TMTIMERTYPE_USB: pTimer->u.Usb.pfnTimer(pTimer->u.Usb.pUsbIns, pTimer, pTimer->pvUser); break;
2424 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2425 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2426 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2427 default:
2428 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2429 break;
2430 }
2431
2432 /* Change the state if it wasn't changed already in the handler.
2433 Reset the Hz hint too since this is the same as TMTimerStop. */
2434 bool fRc;
2435 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2436 if (fRc && pTimer->uHzHint)
2437 {
2438 if (pTimer->uHzHint >= pVM->tm.s.uMaxHzHint)
2439 ASMAtomicWriteBool(&pVM->tm.s.fHzHintNeedsUpdating, true);
2440 pTimer->uHzHint = 0;
2441 }
2442 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2443
2444 /* Leave the associated lock. */
2445 if (pCritSect)
2446 PDMCritSectLeave(pCritSect);
2447 } /* run loop */
2448
2449
2450 /*
2451 * Restart the clock if it was stopped to serve any timers,
2452 * and start/adjust catch-up if necessary.
2453 */
2454 if ( !pVM->tm.s.fVirtualSyncTicking
2455 && pVM->tm.s.cVirtualTicking)
2456 {
2457 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
2458
2459 /* calc the slack we've handed out. */
2460 const uint64_t u64VirtualNow2 = TMVirtualGetNoCheck(pVM);
2461 Assert(u64VirtualNow2 >= u64VirtualNow);
2462 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%'RU64 < %'RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
2463 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
2464 STAM_STATS({
2465 if (offSlack)
2466 {
2467 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
2468 p->cPeriods++;
2469 p->cTicks += offSlack;
2470 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
2471 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
2472 }
2473 });
2474
2475 /* Let the time run a little bit while we were busy running timers(?). */
2476 uint64_t u64Elapsed;
2477#define MAX_ELAPSED 30000U /* ns */
2478 if (offSlack > MAX_ELAPSED)
2479 u64Elapsed = 0;
2480 else
2481 {
2482 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
2483 if (u64Elapsed > MAX_ELAPSED)
2484 u64Elapsed = MAX_ELAPSED;
2485 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
2486 }
2487#undef MAX_ELAPSED
2488
2489 /* Calc the current offset. */
2490 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
2491 Assert(!(offNew & RT_BIT_64(63)));
2492 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
2493 Assert(!(offLag & RT_BIT_64(63)));
2494
2495 /*
2496 * Deal with starting, adjusting and stopping catchup.
2497 */
2498 if (pVM->tm.s.fVirtualSyncCatchUp)
2499 {
2500 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
2501 {
2502 /* stop */
2503 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2504 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2505 Log4(("TM: %'RU64/-%'8RU64: caught up [pt]\n", u64VirtualNow2 - offNew, offLag));
2506 }
2507 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2508 {
2509 /* adjust */
2510 unsigned i = 0;
2511 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2512 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2513 i++;
2514 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
2515 {
2516 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
2517 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2518 Log4(("TM: %'RU64/%'8RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2519 }
2520 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
2521 }
2522 else
2523 {
2524 /* give up */
2525 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
2526 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2527 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2528 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2529 Log4(("TM: %'RU64/%'8RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2530 LogRel(("TM: Giving up catch-up attempt at a %'RU64 ns lag; new total: %'RU64 ns\n", offLag, offNew));
2531 }
2532 }
2533 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
2534 {
2535 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2536 {
2537 /* start */
2538 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
2539 unsigned i = 0;
2540 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2541 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2542 i++;
2543 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
2544 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2545 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
2546 Log4(("TM: %'RU64/%'8RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2547 }
2548 else
2549 {
2550 /* don't bother */
2551 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
2552 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2553 Log4(("TM: %'RU64/%'8RU64: give up\n", u64VirtualNow2 - offNew, offLag));
2554 LogRel(("TM: Not bothering to attempt catching up a %'RU64 ns lag; new total: %'RU64\n", offLag, offNew));
2555 }
2556 }
2557
2558 /*
2559 * Update the offset and restart the clock.
2560 */
2561 Assert(!(offNew & RT_BIT_64(63)));
2562 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, offNew);
2563 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, true);
2564 }
2565}
2566
2567
2568/**
2569 * Deals with stopped Virtual Sync clock.
2570 *
2571 * This is called by the forced action flag handling code in EM when it
2572 * encounters the VM_FF_TM_VIRTUAL_SYNC flag. It is called by all VCPUs and they
2573 * will block on the VirtualSyncLock until the pending timers has been executed
2574 * and the clock restarted.
2575 *
2576 * @param pVM The VM to run the timers for.
2577 * @param pVCpu The virtual CPU we're running at.
2578 *
2579 * @thread EMTs
2580 */
2581VMMR3_INT_DECL(void) TMR3VirtualSyncFF(PVM pVM, PVMCPU pVCpu)
2582{
2583 Log2(("TMR3VirtualSyncFF:\n"));
2584
2585 /*
2586 * The EMT doing the timers is diverted to them.
2587 */
2588 if (pVCpu->idCpu == pVM->tm.s.idTimerCpu)
2589 TMR3TimerQueuesDo(pVM);
2590 /*
2591 * The other EMTs will block on the virtual sync lock and the first owner
2592 * will run the queue and thus restarting the clock.
2593 *
2594 * Note! This is very suboptimal code wrt to resuming execution when there
2595 * are more than two Virtual CPUs, since they will all have to enter
2596 * the critical section one by one. But it's a very simple solution
2597 * which will have to do the job for now.
2598 */
2599 else
2600 {
2601 STAM_PROFILE_START(&pVM->tm.s.StatVirtualSyncFF, a);
2602 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2603 if (pVM->tm.s.fVirtualSyncTicking)
2604 {
2605 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2606 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2607 Log2(("TMR3VirtualSyncFF: ticking\n"));
2608 }
2609 else
2610 {
2611 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2612
2613 /* try run it. */
2614 TM_LOCK_TIMERS(pVM);
2615 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2616 if (pVM->tm.s.fVirtualSyncTicking)
2617 Log2(("TMR3VirtualSyncFF: ticking (2)\n"));
2618 else
2619 {
2620 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
2621 Log2(("TMR3VirtualSyncFF: running queue\n"));
2622
2623 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule);
2624 tmR3TimerQueueRunVirtualSync(pVM);
2625 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
2626 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
2627
2628 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
2629 }
2630 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2631 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2632 TM_UNLOCK_TIMERS(pVM);
2633 }
2634 }
2635}
2636
2637
2638/** @name Saved state values
2639 * @{ */
2640#define TMTIMERSTATE_SAVED_PENDING_STOP 4
2641#define TMTIMERSTATE_SAVED_PENDING_SCHEDULE 7
2642/** @} */
2643
2644
2645/**
2646 * Saves the state of a timer to a saved state.
2647 *
2648 * @returns VBox status.
2649 * @param pTimer Timer to save.
2650 * @param pSSM Save State Manager handle.
2651 */
2652VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2653{
2654 LogFlow(("TMR3TimerSave: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2655 switch (pTimer->enmState)
2656 {
2657 case TMTIMERSTATE_STOPPED:
2658 case TMTIMERSTATE_PENDING_STOP:
2659 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
2660 return SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_STOP);
2661
2662 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
2663 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
2664 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
2665 if (!RTThreadYield())
2666 RTThreadSleep(1);
2667 /* fall thru */
2668 case TMTIMERSTATE_ACTIVE:
2669 case TMTIMERSTATE_PENDING_SCHEDULE:
2670 case TMTIMERSTATE_PENDING_RESCHEDULE:
2671 SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_SCHEDULE);
2672 return SSMR3PutU64(pSSM, pTimer->u64Expire);
2673
2674 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
2675 case TMTIMERSTATE_EXPIRED_DELIVER:
2676 case TMTIMERSTATE_DESTROY:
2677 case TMTIMERSTATE_FREE:
2678 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
2679 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
2680 }
2681
2682 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
2683 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
2684}
2685
2686
2687/**
2688 * Loads the state of a timer from a saved state.
2689 *
2690 * @returns VBox status.
2691 * @param pTimer Timer to restore.
2692 * @param pSSM Save State Manager handle.
2693 */
2694VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2695{
2696 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
2697 LogFlow(("TMR3TimerLoad: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2698
2699 /*
2700 * Load the state and validate it.
2701 */
2702 uint8_t u8State;
2703 int rc = SSMR3GetU8(pSSM, &u8State);
2704 if (RT_FAILURE(rc))
2705 return rc;
2706#if 1 /* Workaround for accidental state shift in r47786 (2009-05-26 19:12:12). */ /** @todo remove this in a few weeks! */
2707 if ( u8State == TMTIMERSTATE_SAVED_PENDING_STOP + 1
2708 || u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE + 1)
2709 u8State--;
2710#endif
2711 if ( u8State != TMTIMERSTATE_SAVED_PENDING_STOP
2712 && u8State != TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2713 {
2714 AssertLogRelMsgFailed(("u8State=%d\n", u8State));
2715 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
2716 }
2717
2718 /* Enter the critical sections to make TMTimerSet/Stop happy. */
2719 if (pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC)
2720 PDMCritSectEnter(&pTimer->pVMR3->tm.s.VirtualSyncLock, VERR_IGNORED);
2721 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2722 if (pCritSect)
2723 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2724
2725 if (u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2726 {
2727 /*
2728 * Load the expire time.
2729 */
2730 uint64_t u64Expire;
2731 rc = SSMR3GetU64(pSSM, &u64Expire);
2732 if (RT_FAILURE(rc))
2733 return rc;
2734
2735 /*
2736 * Set it.
2737 */
2738 Log(("u8State=%d u64Expire=%llu\n", u8State, u64Expire));
2739 rc = TMTimerSet(pTimer, u64Expire);
2740 }
2741 else
2742 {
2743 /*
2744 * Stop it.
2745 */
2746 Log(("u8State=%d\n", u8State));
2747 rc = TMTimerStop(pTimer);
2748 }
2749
2750 if (pCritSect)
2751 PDMCritSectLeave(pCritSect);
2752 if (pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC)
2753 PDMCritSectLeave(&pTimer->pVMR3->tm.s.VirtualSyncLock);
2754
2755 /*
2756 * On failure set SSM status.
2757 */
2758 if (RT_FAILURE(rc))
2759 rc = SSMR3HandleSetStatus(pSSM, rc);
2760 return rc;
2761}
2762
2763
2764/**
2765 * Associates a critical section with a timer.
2766 *
2767 * The critical section will be entered prior to doing the timer call back, thus
2768 * avoiding potential races between the timer thread and other threads trying to
2769 * stop or adjust the timer expiration while it's being delivered. The timer
2770 * thread will leave the critical section when the timer callback returns.
2771 *
2772 * In strict builds, ownership of the critical section will be asserted by
2773 * TMTimerSet, TMTimerStop, TMTimerGetExpire and TMTimerDestroy (when called at
2774 * runtime).
2775 *
2776 * @retval VINF_SUCCESS on success.
2777 * @retval VERR_INVALID_HANDLE if the timer handle is NULL or invalid
2778 * (asserted).
2779 * @retval VERR_INVALID_PARAMETER if pCritSect is NULL or has an invalid magic
2780 * (asserted).
2781 * @retval VERR_ALREADY_EXISTS if a critical section was already associated
2782 * with the timer (asserted).
2783 * @retval VERR_INVALID_STATE if the timer isn't stopped.
2784 *
2785 * @param pTimer The timer handle.
2786 * @param pCritSect The critical section. The caller must make sure this
2787 * is around for the life time of the timer.
2788 *
2789 * @thread Any, but the caller is responsible for making sure the timer is not
2790 * active.
2791 */
2792VMMR3DECL(int) TMR3TimerSetCritSect(PTMTIMERR3 pTimer, PPDMCRITSECT pCritSect)
2793{
2794 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
2795 AssertPtrReturn(pCritSect, VERR_INVALID_PARAMETER);
2796 const char *pszName = PDMR3CritSectName(pCritSect); /* exploited for validation */
2797 AssertReturn(pszName, VERR_INVALID_PARAMETER);
2798 AssertReturn(!pTimer->pCritSect, VERR_ALREADY_EXISTS);
2799 AssertReturn(pTimer->enmState == TMTIMERSTATE_STOPPED, VERR_INVALID_STATE);
2800 LogFlow(("pTimer=%p (%s) pCritSect=%p (%s)\n", pTimer, pTimer->pszDesc, pCritSect, pszName));
2801
2802 pTimer->pCritSect = pCritSect;
2803 return VINF_SUCCESS;
2804}
2805
2806
2807/**
2808 * Get the real world UTC time adjusted for VM lag.
2809 *
2810 * @returns pTime.
2811 * @param pVM The VM instance.
2812 * @param pTime Where to store the time.
2813 */
2814VMMR3_INT_DECL(PRTTIMESPEC) TMR3UtcNow(PVM pVM, PRTTIMESPEC pTime)
2815{
2816 /* Get a stable set of VirtualSync parameters before querying UTC. */
2817 uint64_t offVirtualSync;
2818 uint64_t offVirtualSyncGivenUp;
2819 do
2820 {
2821 offVirtualSync = ASMAtomicReadU64(&pVM->tm.s.offVirtualSync);
2822 offVirtualSyncGivenUp = ASMAtomicReadU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp);
2823 } while (ASMAtomicReadU64(&pVM->tm.s.offVirtualSync) != offVirtualSync);
2824
2825 Assert(offVirtualSync >= offVirtualSyncGivenUp);
2826 uint64_t const offLag = offVirtualSync - offVirtualSyncGivenUp;
2827
2828 RTTimeNow(pTime);
2829 RTTimeSpecSubNano(pTime, offLag);
2830 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
2831 return pTime;
2832}
2833
2834
2835/**
2836 * Pauses all clocks except TMCLOCK_REAL.
2837 *
2838 * @returns VBox status code, all errors are asserted.
2839 * @param pVM Pointer to the VM.
2840 * @param pVCpu Pointer to the VMCPU.
2841 * @thread EMT corresponding to Pointer to the VMCPU.
2842 */
2843VMMR3DECL(int) TMR3NotifySuspend(PVM pVM, PVMCPU pVCpu)
2844{
2845 VMCPU_ASSERT_EMT(pVCpu);
2846
2847 /*
2848 * The shared virtual clock (includes virtual sync which is tied to it).
2849 */
2850 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2851 int rc = tmVirtualPauseLocked(pVM);
2852 TM_UNLOCK_TIMERS(pVM);
2853 if (RT_FAILURE(rc))
2854 return rc;
2855
2856 /*
2857 * Pause the TSC last since it is normally linked to the virtual
2858 * sync clock, so the above code may actually stop both clocks.
2859 */
2860 if (!pVM->tm.s.fTSCTiedToExecution)
2861 {
2862 TM_LOCK_TIMERS(pVM); /* Exploit the timer lock for synchronization. */
2863 rc = tmCpuTickPauseLocked(pVM, pVCpu);
2864 TM_UNLOCK_TIMERS(pVM);
2865 if (RT_FAILURE(rc))
2866 return rc;
2867 }
2868
2869#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2870 /*
2871 * Update cNsTotal.
2872 */
2873 uint32_t uGen = ASMAtomicIncU32(&pVCpu->tm.s.uTimesGen); Assert(uGen & 1);
2874 pVCpu->tm.s.cNsTotal = RTTimeNanoTS() - pVCpu->tm.s.u64NsTsStartTotal;
2875 pVCpu->tm.s.cNsOther = pVCpu->tm.s.cNsTotal - pVCpu->tm.s.cNsExecuting - pVCpu->tm.s.cNsHalted;
2876 ASMAtomicWriteU32(&pVCpu->tm.s.uTimesGen, (uGen | 1) + 1);
2877#endif
2878
2879 return VINF_SUCCESS;
2880}
2881
2882
2883/**
2884 * Resumes all clocks except TMCLOCK_REAL.
2885 *
2886 * @returns VBox status code, all errors are asserted.
2887 * @param pVM Pointer to the VM.
2888 * @param pVCpu Pointer to the VMCPU.
2889 * @thread EMT corresponding to Pointer to the VMCPU.
2890 */
2891VMMR3DECL(int) TMR3NotifyResume(PVM pVM, PVMCPU pVCpu)
2892{
2893 VMCPU_ASSERT_EMT(pVCpu);
2894 int rc;
2895
2896#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2897 /*
2898 * Set u64NsTsStartTotal. There is no need to back this out if either of
2899 * the two calls below fail.
2900 */
2901 pVCpu->tm.s.u64NsTsStartTotal = RTTimeNanoTS() - pVCpu->tm.s.cNsTotal;
2902#endif
2903
2904 /*
2905 * Resume the TSC first since it is normally linked to the virtual sync
2906 * clock, so it may actually not be resumed until we've executed the code
2907 * below.
2908 */
2909 if (!pVM->tm.s.fTSCTiedToExecution)
2910 {
2911 TM_LOCK_TIMERS(pVM); /* Exploit the timer lock for synchronization. */
2912 rc = tmCpuTickResumeLocked(pVM, pVCpu);
2913 TM_UNLOCK_TIMERS(pVM);
2914 if (RT_FAILURE(rc))
2915 return rc;
2916 }
2917
2918 /*
2919 * The shared virtual clock (includes virtual sync which is tied to it).
2920 */
2921 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2922 rc = tmVirtualResumeLocked(pVM);
2923 TM_UNLOCK_TIMERS(pVM);
2924
2925 return rc;
2926}
2927
2928
2929/**
2930 * Sets the warp drive percent of the virtual time.
2931 *
2932 * @returns VBox status code.
2933 * @param pVM Pointer to the VM.
2934 * @param u32Percent The new percentage. 100 means normal operation.
2935 */
2936VMMDECL(int) TMR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent)
2937{
2938 return VMR3ReqPriorityCallWaitU(pUVM, VMCPUID_ANY, (PFNRT)tmR3SetWarpDrive, 2, pUVM, u32Percent);
2939}
2940
2941
2942/**
2943 * EMT worker for TMR3SetWarpDrive.
2944 *
2945 * @returns VBox status code.
2946 * @param pUVM The user mode VM handle.
2947 * @param u32Percent See TMR3SetWarpDrive().
2948 * @internal
2949 */
2950static DECLCALLBACK(int) tmR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent)
2951{
2952 PVM pVM = pUVM->pVM;
2953 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2954 PVMCPU pVCpu = VMMGetCpu(pVM);
2955
2956 /*
2957 * Validate it.
2958 */
2959 AssertMsgReturn(u32Percent >= 2 && u32Percent <= 20000,
2960 ("%RX32 is not between 2 and 20000 (inclusive).\n", u32Percent),
2961 VERR_INVALID_PARAMETER);
2962
2963/** @todo This isn't a feature specific to virtual time, move the variables to
2964 * TM level and make it affect TMR3UTCNow as well! */
2965
2966 /*
2967 * If the time is running we'll have to pause it before we can change
2968 * the warp drive settings.
2969 */
2970 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2971 bool fPaused = !!pVM->tm.s.cVirtualTicking;
2972 if (fPaused) /** @todo this isn't really working, but wtf. */
2973 TMR3NotifySuspend(pVM, pVCpu);
2974
2975 /** @todo Should switch TM mode to virt-tsc-emulated if it isn't already! */
2976 pVM->tm.s.u32VirtualWarpDrivePercentage = u32Percent;
2977 pVM->tm.s.fVirtualWarpDrive = u32Percent != 100;
2978 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32 fVirtualWarpDrive=%RTbool\n",
2979 pVM->tm.s.u32VirtualWarpDrivePercentage, pVM->tm.s.fVirtualWarpDrive));
2980
2981 if (fPaused)
2982 TMR3NotifyResume(pVM, pVCpu);
2983 TM_UNLOCK_TIMERS(pVM);
2984 return VINF_SUCCESS;
2985}
2986
2987
2988/**
2989 * Gets the current warp drive percent.
2990 *
2991 * @returns The warp drive percent.
2992 * @param pVM Pointer to the VM.
2993 */
2994VMMR3DECL(uint32_t) TMR3GetWarpDrive(PUVM pUVM)
2995{
2996 UVM_ASSERT_VALID_EXT_RETURN(pUVM, UINT32_MAX);
2997 PVM pVM = pUVM->pVM;
2998 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
2999 return pVM->tm.s.u32VirtualWarpDrivePercentage;
3000}
3001
3002
3003/**
3004 * Gets the performance information for one virtual CPU as seen by the VMM.
3005 *
3006 * The returned times covers the period where the VM is running and will be
3007 * reset when restoring a previous VM state (at least for the time being).
3008 *
3009 * @retval VINF_SUCCESS on success.
3010 * @retval VERR_NOT_IMPLEMENTED if not compiled in.
3011 * @retval VERR_INVALID_STATE if the VM handle is bad.
3012 * @retval VERR_INVALID_PARAMETER if idCpu is out of range.
3013 *
3014 * @param pVM Pointer to the VM.
3015 * @param idCpu The ID of the virtual CPU which times to get.
3016 * @param pcNsTotal Where to store the total run time (nano seconds) of
3017 * the CPU, i.e. the sum of the three other returns.
3018 * Optional.
3019 * @param pcNsExecuting Where to store the time (nano seconds) spent
3020 * executing guest code. Optional.
3021 * @param pcNsHalted Where to store the time (nano seconds) spent
3022 * halted. Optional
3023 * @param pcNsOther Where to store the time (nano seconds) spent
3024 * preempted by the host scheduler, on virtualization
3025 * overhead and on other tasks.
3026 */
3027VMMR3DECL(int) TMR3GetCpuLoadTimes(PVM pVM, VMCPUID idCpu, uint64_t *pcNsTotal, uint64_t *pcNsExecuting,
3028 uint64_t *pcNsHalted, uint64_t *pcNsOther)
3029{
3030 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_STATE);
3031 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_PARAMETER);
3032
3033#ifndef VBOX_WITHOUT_NS_ACCOUNTING
3034 /*
3035 * Get a stable result set.
3036 * This should be way quicker than an EMT request.
3037 */
3038 PVMCPU pVCpu = &pVM->aCpus[idCpu];
3039 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
3040 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
3041 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
3042 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
3043 uint64_t cNsOther = pVCpu->tm.s.cNsOther;
3044 while ( (uTimesGen & 1) /* update in progress */
3045 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen))
3046 {
3047 RTThreadYield();
3048 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
3049 cNsTotal = pVCpu->tm.s.cNsTotal;
3050 cNsExecuting = pVCpu->tm.s.cNsExecuting;
3051 cNsHalted = pVCpu->tm.s.cNsHalted;
3052 cNsOther = pVCpu->tm.s.cNsOther;
3053 }
3054
3055 /*
3056 * Fill in the return values.
3057 */
3058 if (pcNsTotal)
3059 *pcNsTotal = cNsTotal;
3060 if (pcNsExecuting)
3061 *pcNsExecuting = cNsExecuting;
3062 if (pcNsHalted)
3063 *pcNsHalted = cNsHalted;
3064 if (pcNsOther)
3065 *pcNsOther = cNsOther;
3066
3067 return VINF_SUCCESS;
3068
3069#else
3070 return VERR_NOT_IMPLEMENTED;
3071#endif
3072}
3073
3074#ifndef VBOX_WITHOUT_NS_ACCOUNTING
3075
3076/**
3077 * Helper for tmR3CpuLoadTimer.
3078 * @returns
3079 * @param pState The state to update.
3080 * @param cNsTotalDelta Total time.
3081 * @param cNsExecutingDelta Time executing.
3082 * @param cNsHaltedDelta Time halted.
3083 */
3084DECLINLINE(void) tmR3CpuLoadTimerMakeUpdate(PTMCPULOADSTATE pState,
3085 uint64_t cNsTotal,
3086 uint64_t cNsExecuting,
3087 uint64_t cNsHalted)
3088{
3089 /* Calc deltas */
3090 uint64_t cNsTotalDelta = cNsTotal - pState->cNsPrevTotal;
3091 pState->cNsPrevTotal = cNsTotal;
3092
3093 uint64_t cNsExecutingDelta = cNsExecuting - pState->cNsPrevExecuting;
3094 pState->cNsPrevExecuting = cNsExecuting;
3095
3096 uint64_t cNsHaltedDelta = cNsHalted - pState->cNsPrevHalted;
3097 pState->cNsPrevHalted = cNsHalted;
3098
3099 /* Calc pcts. */
3100 if (!cNsTotalDelta)
3101 {
3102 pState->cPctExecuting = 0;
3103 pState->cPctHalted = 100;
3104 pState->cPctOther = 0;
3105 }
3106 else if (cNsTotalDelta < UINT64_MAX / 4)
3107 {
3108 pState->cPctExecuting = (uint8_t)(cNsExecutingDelta * 100 / cNsTotalDelta);
3109 pState->cPctHalted = (uint8_t)(cNsHaltedDelta * 100 / cNsTotalDelta);
3110 pState->cPctOther = (uint8_t)((cNsTotalDelta - cNsExecutingDelta - cNsHaltedDelta) * 100 / cNsTotalDelta);
3111 }
3112 else
3113 {
3114 pState->cPctExecuting = 0;
3115 pState->cPctHalted = 100;
3116 pState->cPctOther = 0;
3117 }
3118}
3119
3120
3121/**
3122 * Timer callback that calculates the CPU load since the last time it was
3123 * called.
3124 *
3125 * @param pVM Pointer to the VM.
3126 * @param pTimer The timer.
3127 * @param pvUser NULL, unused.
3128 */
3129static DECLCALLBACK(void) tmR3CpuLoadTimer(PVM pVM, PTMTIMER pTimer, void *pvUser)
3130{
3131 /*
3132 * Re-arm the timer first.
3133 */
3134 int rc = TMTimerSetMillies(pTimer, 1000);
3135 AssertLogRelRC(rc);
3136 NOREF(pvUser);
3137
3138 /*
3139 * Update the values for each CPU.
3140 */
3141 uint64_t cNsTotalAll = 0;
3142 uint64_t cNsExecutingAll = 0;
3143 uint64_t cNsHaltedAll = 0;
3144 for (VMCPUID iCpu = 0; iCpu < pVM->cCpus; iCpu++)
3145 {
3146 PVMCPU pVCpu = &pVM->aCpus[iCpu];
3147
3148 /* Try get a stable data set. */
3149 uint32_t cTries = 3;
3150 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
3151 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
3152 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
3153 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
3154 while (RT_UNLIKELY( (uTimesGen & 1) /* update in progress */
3155 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen)))
3156 {
3157 if (!--cTries)
3158 break;
3159 ASMNopPause();
3160 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
3161 cNsTotal = pVCpu->tm.s.cNsTotal;
3162 cNsExecuting = pVCpu->tm.s.cNsExecuting;
3163 cNsHalted = pVCpu->tm.s.cNsHalted;
3164 }
3165
3166 /* Totals */
3167 cNsTotalAll += cNsTotal;
3168 cNsExecutingAll += cNsExecuting;
3169 cNsHaltedAll += cNsHalted;
3170
3171 /* Calc the PCTs and update the state. */
3172 tmR3CpuLoadTimerMakeUpdate(&pVCpu->tm.s.CpuLoad, cNsTotal, cNsExecuting, cNsHalted);
3173 }
3174
3175 /*
3176 * Update the value for all the CPUs.
3177 */
3178 tmR3CpuLoadTimerMakeUpdate(&pVM->tm.s.CpuLoad, cNsTotalAll, cNsExecutingAll, cNsHaltedAll);
3179
3180 /** @todo Try add 1, 5 and 15 min load stats. */
3181
3182}
3183
3184#endif /* !VBOX_WITHOUT_NS_ACCOUNTING */
3185
3186
3187/**
3188 * Switch TM TSC mode to the most appropriate/efficient one.
3189 *
3190 * @returns strict VBox status code.
3191 * @param pVM Pointer to the VM.
3192 * @param pVCpuEmt Pointer to the VMCPU it's called on, can be NULL.
3193 * @param pvData Opaque pointer to whether usage of paravirt. TSC is
3194 * enabled or disabled by the guest OS.
3195 *
3196 * @thread EMT.
3197 * @remarks Must only be called during an EMTs rendezvous.
3198 */
3199static DECLCALLBACK(VBOXSTRICTRC) tmR3CpuTickParavirtToggle(PVM pVM, PVMCPU pVCpuEmt, void *pvData)
3200{
3201 Assert(pVM);
3202 Assert(pvData);
3203 Assert(pVM->tm.s.fTSCModeSwitchAllowed);
3204 NOREF(pVCpuEmt);
3205
3206 bool *pfEnable = (bool *)pvData;
3207 if (*pfEnable)
3208 {
3209 if (pVM->tm.s.enmTSCMode != TMTSCMODE_REAL_TSC_OFFSET)
3210 {
3211 if (tmR3HasFixedTSC(pVM))
3212 {
3213 uint64_t u64NowVirtSync = TMVirtualSyncGetNoCheck(pVM);
3214 uint64_t u64Now = ASMMultU64ByU32DivByU32(u64NowVirtSync, pVM->tm.s.cTSCTicksPerSecond, TMCLOCK_FREQ_VIRTUAL);
3215 uint32_t cCpus = pVM->cCpus;
3216 uint64_t u64RealTSC = ASMReadTSC();
3217 for (uint32_t i = 0; i < cCpus; i++)
3218 {
3219 PVMCPU pVCpu = &pVM->aCpus[i];
3220 uint64_t u64TickOld = u64Now - pVCpu->tm.s.offTSCRawSrc;
3221
3222 /*
3223 * The return value of TMCpuTickGet() and the guest's TSC value (u64Tick) must
3224 * remain constant across the TM TSC mode-switch.
3225 * OldTick = VrSync - CurOff
3226 * NewTick = RealTsc - NewOff
3227 * NewTick = OldTick
3228 * => RealTsc - NewOff = VrSync - CurOff
3229 * => NewOff = CurOff + RealTsc - VrSync
3230 */
3231 pVCpu->tm.s.offTSCRawSrc = pVCpu->tm.s.offTSCRawSrc + u64RealTSC - u64Now;
3232
3233 /* If the new offset results in the TSC going backwards, re-adjust the offset. */
3234 if (u64RealTSC - pVCpu->tm.s.offTSCRawSrc < u64TickOld)
3235 pVCpu->tm.s.offTSCRawSrc += u64TickOld - u64RealTSC;
3236 Assert(u64RealTSC - pVCpu->tm.s.offTSCRawSrc >= u64TickOld);
3237 }
3238 pVM->tm.s.enmTSCMode = TMTSCMODE_REAL_TSC_OFFSET;
3239 LogRel(("TM: Switched TSC mode. New enmTSCMode=%d (%s)\n", pVM->tm.s.enmTSCMode, tmR3GetTSCModeName(pVM)));
3240 }
3241 else
3242 LogRel(("TM: Host is not suitable for using TSC mode (%d - %s). Request to change TSC mode ignored.\n",
3243 TMTSCMODE_REAL_TSC_OFFSET, tmR3GetTSCModeNameEx(TMTSCMODE_REAL_TSC_OFFSET)));
3244 }
3245 }
3246 else
3247 {
3248 if ( pVM->tm.s.enmTSCMode == TMTSCMODE_REAL_TSC_OFFSET
3249 && pVM->tm.s.enmTSCMode != pVM->tm.s.enmOriginalTSCMode)
3250 {
3251 uint64_t u64NowVirtSync = TMVirtualSyncGetNoCheck(pVM);
3252 uint64_t u64Now = ASMMultU64ByU32DivByU32(u64NowVirtSync, pVM->tm.s.cTSCTicksPerSecond, TMCLOCK_FREQ_VIRTUAL);
3253 uint64_t u64RealTSC = ASMReadTSC(); /** @todo replace with SUPReadTSC() eventually. */
3254 uint32_t cCpus = pVM->cCpus;
3255 for (uint32_t i = 0; i < cCpus; i++)
3256 {
3257 PVMCPU pVCpu = &pVM->aCpus[i];
3258 uint64_t u64TickOld = u64RealTSC - pVCpu->tm.s.offTSCRawSrc;
3259
3260 /* Update the last-seen tick here as we havent't been updating it (as we don't
3261 need it) while in pure TSC-offsetting mode. */
3262 pVCpu->tm.s.u64TSCLastSeen = pVCpu->tm.s.u64TSC;
3263
3264 /*
3265 * The return value of TMCpuTickGet() and the guest's TSC value (u64Tick) must
3266 * remain constant across the TM TSC mode-switch.
3267 * OldTick = RealTsc - CurOff
3268 * NewTick = VrSync - NewOff
3269 * NewTick = OldTick
3270 * => VrSync - NewOff = RealTsc - CurOff
3271 * => NewOff = CurOff + VrSync - RealTsc
3272 */
3273 pVCpu->tm.s.offTSCRawSrc = pVCpu->tm.s.offTSCRawSrc + u64Now - u64RealTSC;
3274
3275 /* If the new offset results in the TSC going backwards, re-adjust the offset. */
3276 if (u64Now - pVCpu->tm.s.offTSCRawSrc < u64TickOld)
3277 pVCpu->tm.s.offTSCRawSrc += u64TickOld - u64Now;
3278 Assert(u64Now - pVCpu->tm.s.offTSCRawSrc >= u64TickOld);
3279 }
3280 pVM->tm.s.enmTSCMode = pVM->tm.s.enmOriginalTSCMode;
3281 LogRel(("TM: Switched TSC mode. New enmTSCMode=%d (%s)\n", pVM->tm.s.enmTSCMode, tmR3GetTSCModeName(pVM)));
3282 }
3283 }
3284 return VINF_SUCCESS;
3285}
3286
3287
3288/**
3289 * Notify TM that the guest has enabled usage of a paravirtualized TSC.
3290 *
3291 * @returns VBox status code.
3292 * @param pVM Pointer to the VM.
3293 */
3294VMMR3_INT_DECL(int) TMR3CpuTickParavirtEnable(PVM pVM)
3295{
3296 int rc = VINF_SUCCESS;
3297 if (pVM->tm.s.fTSCModeSwitchAllowed)
3298 {
3299 bool fEnable = true;
3300 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, tmR3CpuTickParavirtToggle, (void *)&fEnable);
3301 }
3302 pVM->tm.s.fParavirtTscEnabled = true;
3303 return rc;
3304}
3305
3306
3307/**
3308 * Notify TM that the guest has disabled usage of a paravirtualized TSC.
3309 *
3310 * @returns VBox status code.
3311 * @param pVM Pointer to the VM.
3312 */
3313VMMR3_INT_DECL(int) TMR3CpuTickParavirtDisable(PVM pVM)
3314{
3315 int rc = VINF_SUCCESS;
3316 if (pVM->tm.s.fTSCModeSwitchAllowed)
3317 {
3318 bool fEnable = false;
3319 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, tmR3CpuTickParavirtToggle, (void *)&fEnable);
3320 }
3321 pVM->tm.s.fParavirtTscEnabled = false;
3322 return rc;
3323}
3324
3325
3326/**
3327 * Gets the 5 char clock name for the info tables.
3328 *
3329 * @returns The name.
3330 * @param enmClock The clock.
3331 */
3332DECLINLINE(const char *) tmR3Get5CharClockName(TMCLOCK enmClock)
3333{
3334 switch (enmClock)
3335 {
3336 case TMCLOCK_REAL: return "Real ";
3337 case TMCLOCK_VIRTUAL: return "Virt ";
3338 case TMCLOCK_VIRTUAL_SYNC: return "VrSy ";
3339 case TMCLOCK_TSC: return "TSC ";
3340 default: return "Bad ";
3341 }
3342}
3343
3344
3345/**
3346 * Display all timers.
3347 *
3348 * @param pVM Pointer to the VM.
3349 * @param pHlp The info helpers.
3350 * @param pszArgs Arguments, ignored.
3351 */
3352static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3353{
3354 NOREF(pszArgs);
3355 pHlp->pfnPrintf(pHlp,
3356 "Timers (pVM=%p)\n"
3357 "%.*s %.*s %.*s %.*s Clock %18s %18s %6s %-25s Description\n",
3358 pVM,
3359 sizeof(RTR3PTR) * 2, "pTimerR3 ",
3360 sizeof(int32_t) * 2, "offNext ",
3361 sizeof(int32_t) * 2, "offPrev ",
3362 sizeof(int32_t) * 2, "offSched ",
3363 "Time",
3364 "Expire",
3365 "HzHint",
3366 "State");
3367 TM_LOCK_TIMERS(pVM);
3368 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
3369 {
3370 pHlp->pfnPrintf(pHlp,
3371 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %6RU32 %-25s %s\n",
3372 pTimer,
3373 pTimer->offNext,
3374 pTimer->offPrev,
3375 pTimer->offScheduleNext,
3376 tmR3Get5CharClockName(pTimer->enmClock),
3377 TMTimerGet(pTimer),
3378 pTimer->u64Expire,
3379 pTimer->uHzHint,
3380 tmTimerState(pTimer->enmState),
3381 pTimer->pszDesc);
3382 }
3383 TM_UNLOCK_TIMERS(pVM);
3384}
3385
3386
3387/**
3388 * Display all active timers.
3389 *
3390 * @param pVM Pointer to the VM.
3391 * @param pHlp The info helpers.
3392 * @param pszArgs Arguments, ignored.
3393 */
3394static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3395{
3396 NOREF(pszArgs);
3397 pHlp->pfnPrintf(pHlp,
3398 "Active Timers (pVM=%p)\n"
3399 "%.*s %.*s %.*s %.*s Clock %18s %18s %6s %-25s Description\n",
3400 pVM,
3401 sizeof(RTR3PTR) * 2, "pTimerR3 ",
3402 sizeof(int32_t) * 2, "offNext ",
3403 sizeof(int32_t) * 2, "offPrev ",
3404 sizeof(int32_t) * 2, "offSched ",
3405 "Time",
3406 "Expire",
3407 "HzHint",
3408 "State");
3409 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
3410 {
3411 TM_LOCK_TIMERS(pVM);
3412 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
3413 pTimer;
3414 pTimer = TMTIMER_GET_NEXT(pTimer))
3415 {
3416 pHlp->pfnPrintf(pHlp,
3417 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %6RU32 %-25s %s\n",
3418 pTimer,
3419 pTimer->offNext,
3420 pTimer->offPrev,
3421 pTimer->offScheduleNext,
3422 tmR3Get5CharClockName(pTimer->enmClock),
3423 TMTimerGet(pTimer),
3424 pTimer->u64Expire,
3425 pTimer->uHzHint,
3426 tmTimerState(pTimer->enmState),
3427 pTimer->pszDesc);
3428 }
3429 TM_UNLOCK_TIMERS(pVM);
3430 }
3431}
3432
3433
3434/**
3435 * Display all clocks.
3436 *
3437 * @param pVM Pointer to the VM.
3438 * @param pHlp The info helpers.
3439 * @param pszArgs Arguments, ignored.
3440 */
3441static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3442{
3443 NOREF(pszArgs);
3444
3445 /*
3446 * Read the times first to avoid more than necessary time variation.
3447 */
3448 const uint64_t u64Virtual = TMVirtualGet(pVM);
3449 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
3450 const uint64_t u64Real = TMRealGet(pVM);
3451
3452 for (VMCPUID i = 0; i < pVM->cCpus; i++)
3453 {
3454 PVMCPU pVCpu = &pVM->aCpus[i];
3455 uint64_t u64TSC = TMCpuTickGet(pVCpu);
3456
3457 /*
3458 * TSC
3459 */
3460 pHlp->pfnPrintf(pHlp,
3461 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s - virtualized",
3462 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
3463 pVCpu->tm.s.fTSCTicking ? "ticking" : "paused");
3464 if (pVM->tm.s.enmTSCMode == TMTSCMODE_REAL_TSC_OFFSET)
3465 {
3466 pHlp->pfnPrintf(pHlp, " - real tsc offset");
3467 if (pVCpu->tm.s.offTSCRawSrc)
3468 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVCpu->tm.s.offTSCRawSrc);
3469 }
3470 else
3471 pHlp->pfnPrintf(pHlp, " - virtual clock");
3472 pHlp->pfnPrintf(pHlp, "\n");
3473 }
3474
3475 /*
3476 * virtual
3477 */
3478 pHlp->pfnPrintf(pHlp,
3479 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
3480 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
3481 pVM->tm.s.cVirtualTicking ? "ticking" : "paused");
3482 if (pVM->tm.s.fVirtualWarpDrive)
3483 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
3484 pHlp->pfnPrintf(pHlp, "\n");
3485
3486 /*
3487 * virtual sync
3488 */
3489 pHlp->pfnPrintf(pHlp,
3490 "VirtSync: %18RU64 (%#016RX64) %s%s",
3491 u64VirtualSync, u64VirtualSync,
3492 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
3493 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
3494 if (pVM->tm.s.offVirtualSync)
3495 {
3496 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
3497 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
3498 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
3499 }
3500 pHlp->pfnPrintf(pHlp, "\n");
3501
3502 /*
3503 * real
3504 */
3505 pHlp->pfnPrintf(pHlp,
3506 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
3507 u64Real, u64Real, TMRealGetFreq(pVM));
3508}
3509
3510
3511/**
3512 * Gets the descriptive TM TSC mode name given the enum value.
3513 *
3514 * @returns The name.
3515 * @param pVM Pointer to the VM.
3516 */
3517static const char *tmR3GetTSCModeNameEx(TMTSCMODE enmMode)
3518{
3519 switch (enmMode)
3520 {
3521 case TMTSCMODE_REAL_TSC_OFFSET: return "RealTscOffset";
3522 case TMTSCMODE_VIRT_TSC_EMULATED: return "VirtTscEmulated";
3523 case TMTSCMODE_DYNAMIC: return "Dynamic";
3524 default: return "???";
3525 }
3526}
3527
3528
3529/**
3530 * Gets the descriptive TM TSC mode name.
3531 *
3532 * @returns The name.
3533 * @param pVM Pointer to the VM.
3534 */
3535static const char *tmR3GetTSCModeName(PVM pVM)
3536{
3537 Assert(pVM);
3538 return tmR3GetTSCModeNameEx(pVM->tm.s.enmTSCMode);
3539}
3540
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