VirtualBox

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

Last change on this file since 106842 was 106061, checked in by vboxsync, 3 months ago

Copyright year updates by scm.

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