VirtualBox

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

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

VMM/TM: 'info cpuload' improvements.

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

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