VirtualBox

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

Last change on this file since 87765 was 87765, checked in by vboxsync, 3 years ago

VMM/TM,*: Added flag parameter to TMR3TimerCreateInternal and renamed it to TMR3TimerCreate. bugref:9943

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

© 2023 Oracle
ContactPrivacy policyTerms of Use