VirtualBox

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

最後變更 在這個檔案從80333是 80333,由 vboxsync 提交於 6 年 前

VMM: Eliminating the VBOX_BUGREF_9217_PART_I preprocessor macro. bugref:9217

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

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