VirtualBox

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

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

VMM/TM: typo.

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