VirtualBox

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

Last change on this file since 57166 was 57107, checked in by vboxsync, 9 years ago

VMM/TM: Fixes to TSC mode handling with TSC freq is incompatible, still disabled code.

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

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