VirtualBox

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

Last change on this file since 53438 was 53438, checked in by vboxsync, 10 years ago

TM: Use CFGMR3Exists. Moved the do-not-use-dynamic-mode-with-SMP-VMs to the case where 'TSCMode' isn't specified. If someone want to experiment with SMP and the 'Dynamic' mode, I don't see why we should prevent them. (I don't expect anyone to do it unless we tell them to.)

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