VirtualBox

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

Last change on this file since 104557 was 104131, checked in by vboxsync, 7 months ago

VMM/TM: Allow linear scaling of the guest TSC; primarily required for scaling up a 24MHz tickrate on ARM64 hosts.

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

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