VirtualBox

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

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

VMM/r3: Refactored VMCPU enumeration in preparation that aCpus will be replaced with a pointer array. Removed two raw-mode offset members from the CPUM and CPUMCPU sub-structures. bugref:9217 bugref:9517

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