VirtualBox

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

Last change on this file since 94249 was 93901, checked in by vboxsync, 3 years ago

VMM,Main,++: Removed VM_IS_RAW_MODE_ENABLED/VM_EXEC_ENGINE_RAW_MODE and added VM_IS_EXEC_ENGINE_IEM/VM_EXEC_ENGINE_IEM instead. In IMachineDebugger::getExecutionEngine VMExecutionEngine_RawMode was removed and VMExecutionEngine_Emulated added. Removed dead code and updated frontends accordingly. On darwin.arm64 HM now falls back on IEM execution since neither HM or NEM is availble there. bugref:9898

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette