VirtualBox

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

Last change on this file since 78402 was 77284, checked in by vboxsync, 6 years ago

VMM/TM: Changed the watchdog timer frequency to 1Hz for HM mode. Will remove it after raw-mode has been kicked to the curb.

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