VirtualBox

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

Last change on this file since 93666 was 93655, checked in by vboxsync, 3 years ago

VMM/TM,VMM/*: Moved RTTIMENANOTSDATAR0 into the ring-0 only part of the VM structure. Added a VMCC_CTX macro for selecting between tm and tmr0 VM components depending on the compilation context. Added a bunch of missing padding checks for GVM. bugref:10094

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

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