VirtualBox

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

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

VMM: Eliminating the VBOX_BUGREF_9217 preprocessor macro. bugref:9217

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