VirtualBox

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

Last change on this file since 84044 was 82968, checked in by vboxsync, 4 years ago

Copyright year updates by scm.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use