VirtualBox

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

Last change on this file since 108959 was 108708, checked in by vboxsync, 4 weeks ago

VMM: Introduce VMM_HOST_PAGE_SIZE_DYNAMIC, HOST_PAGE_SIZE_DYNAMIC, and HOST_PAGE_SHIFT_DYNAMIC, bugref:10391

HOST_PAGE_SIZE_DYNAMIC either resolves to HOST_PAGE_SIZE or calls RTSystemGetPageSize() on hosts where
the system page size is not known during build time (linux.arm64 for now).
HOST_PAGE_SHIFT_DYNAMIC is the same for the page shift.

This allows building VMM libraries which are agnostic to the host page size (at the cost of a slightly
larger overhead).

Currently enabled only on linux.arm64

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

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