VirtualBox

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

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

TM: Set pVM->tm.s.u64LastPausedTSC to the highest pVCpu->tm.s.u64TSC value on saved state restore. Cleanups.

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