VirtualBox

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

Last change on this file since 86649 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

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

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