VirtualBox

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

Last change on this file since 71289 was 70948, checked in by vboxsync, 7 years ago

VMM: Added a bMainExecutionEngine member to the VM structure for use instead of fHMEnabled and fNEMEnabled. Changed a lot of HMIsEnabled invocations to use the new macros VM_IS_RAW_MODE_ENABLED and VM_IS_HM_OR_NEM_ENABLED. Eliminated fHMEnabledFixed. Fixed inverted test for raw-mode debug register sanity checking. Some other minor cleanups.

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