VirtualBox

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

Last change on this file since 72552 was 72526, checked in by vboxsync, 7 years ago

NEM,TM: More TSC adjustments for NEM/win. bugref:9044

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

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