VirtualBox

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

Last change on this file since 99740 was 99740, checked in by vboxsync, 12 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void). [scm fixes]

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

© 2023 Oracle
ContactPrivacy policyTerms of Use