VirtualBox

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

Last change on this file since 107227 was 107227, checked in by vboxsync, 6 weeks ago

VMM: Cleaning up ARMv8 / x86 split. jiraref:VBP-1470

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