VirtualBox

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

Last change on this file since 107200 was 107194, checked in by vboxsync, 2 months ago

VMM: More adjustments for VBOX_WITH_ONLY_PGM_NEM_MODE, VBOX_WITH_MINIMAL_R0, VBOX_WITH_HWVIRT and such. jiraref:VBP-1466

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