VirtualBox

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

Last change on this file since 19527 was 19507, checked in by vboxsync, 16 years ago

TM: TMTimerDestroy -> TMR3TimerDestroy. (trying to simplify)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 94.6 KB
Line 
1/* $Id: TM.cpp 19507 2009-05-07 20:58:49Z vboxsync $ */
2/** @file
3 * TM - Time Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/** @page pg_tm TM - The Time Manager
23 *
24 * The Time Manager abstracts the CPU clocks and manages timers used by the VMM,
25 * device and drivers.
26 *
27 * @see grp_tm
28 *
29 *
30 * @section sec_tm_clocks Clocks
31 *
32 * There are currently 4 clocks:
33 * - Virtual (guest).
34 * - Synchronous virtual (guest).
35 * - CPU Tick (TSC) (guest). Only current use is rdtsc emulation. Usually a
36 * function of the virtual clock.
37 * - Real (host). This is only used for display updates atm.
38 *
39 * The most important clocks are the three first ones and of these the second is
40 * the most interesting.
41 *
42 *
43 * The synchronous virtual clock is tied to the virtual clock except that it
44 * will take into account timer delivery lag caused by host scheduling. It will
45 * normally never advance beyond the head timer, and when lagging too far behind
46 * it will gradually speed up to catch up with the virtual clock. All devices
47 * implementing time sources accessible to and used by the guest is using this
48 * clock (for timers and other things). This ensures consistency between the
49 * time sources.
50 *
51 * The virtual clock is implemented as an offset to a monotonic, high
52 * resolution, wall clock. The current time source is using the RTTimeNanoTS()
53 * machinery based upon the Global Info Pages (GIP), that is, we're using TSC
54 * deltas (usually 10 ms) to fill the gaps between GIP updates. The result is
55 * a fairly high res clock that works in all contexts and on all hosts. The
56 * virtual clock is paused when the VM isn't in the running state.
57 *
58 * The CPU tick (TSC) is normally virtualized as a function of the synchronous
59 * virtual clock, where the frequency defaults to the host cpu frequency (as we
60 * measure it). In this mode it is possible to configure the frequency. Another
61 * (non-default) option is to use the raw unmodified host TSC values. And yet
62 * another, to tie it to time spent executing guest code. All these things are
63 * configurable should non-default behavior be desirable.
64 *
65 * The real clock is a monotonic clock (when available) with relatively low
66 * resolution, though this a bit host specific. Note that we're currently not
67 * servicing timers using the real clock when the VM is not running, this is
68 * simply because it has not been needed yet therefore not implemented.
69 *
70 *
71 * @subsection subsec_tm_timesync Guest Time Sync / UTC time
72 *
73 * Guest time syncing is primarily taken care of by the VMM device. The
74 * principle is very simple, the guest additions periodically asks the VMM
75 * device what the current UTC time is and makes adjustments accordingly.
76 *
77 * A complicating factor is that the synchronous virtual clock might be doing
78 * catchups and the guest perception is currently a little bit behind the world
79 * but it will (hopefully) be catching up soon as we're feeding timer interrupts
80 * at a slightly higher rate. Adjusting the guest clock to the current wall
81 * time in the real world would be a bad idea then because the guest will be
82 * advancing too fast and run ahead of world time (if the catchup works out).
83 * To solve this problem TM provides the VMM device with an UTC time source that
84 * gets adjusted with the current lag, so that when the guest eventually catches
85 * up the lag it will be showing correct real world time.
86 *
87 *
88 * @section sec_tm_timers Timers
89 *
90 * The timers can use any of the TM clocks described in the previous section.
91 * Each clock has its own scheduling facility, or timer queue if you like.
92 * There are a few factors which makes it a bit complex. First, there is the
93 * usual R0 vs R3 vs. RC thing. Then there are multiple threads, and then there
94 * is the timer thread that periodically checks whether any timers has expired
95 * without EMT noticing. On the API level, all but the create and save APIs
96 * must be mulithreaded. EMT will always run the timers.
97 *
98 * The design is using a doubly linked list of active timers which is ordered
99 * by expire date. This list is only modified by the EMT thread. Updates to
100 * the list are batched in a singly linked list, which is then processed by the
101 * EMT thread at the first opportunity (immediately, next time EMT modifies a
102 * timer on that clock, or next timer timeout). Both lists are offset based and
103 * all the elements are therefore allocated from the hyper heap.
104 *
105 * For figuring out when there is need to schedule and run timers TM will:
106 * - Poll whenever somebody queries the virtual clock.
107 * - Poll the virtual clocks from the EM and REM loops.
108 * - Poll the virtual clocks from trap exit path.
109 * - Poll the virtual clocks and calculate first timeout from the halt loop.
110 * - Employ a thread which periodically (100Hz) polls all the timer queues.
111 *
112 *
113 * @image html TMTIMER-Statechart-Diagram.gif
114 *
115 * @section sec_tm_timer Logging
116 *
117 * Level 2: Logs a most of the timer state transitions and queue servicing.
118 * Level 3: Logs a few oddments.
119 * Level 4: Logs TMCLOCK_VIRTUAL_SYNC catch-up events.
120 *
121 */
122
123/*******************************************************************************
124* Header Files *
125*******************************************************************************/
126#define LOG_GROUP LOG_GROUP_TM
127#include <VBox/tm.h>
128#include <VBox/vmm.h>
129#include <VBox/mm.h>
130#include <VBox/ssm.h>
131#include <VBox/dbgf.h>
132#include <VBox/rem.h>
133#include <VBox/pdm.h>
134#include "TMInternal.h"
135#include <VBox/vm.h>
136
137#include <VBox/param.h>
138#include <VBox/err.h>
139
140#include <VBox/log.h>
141#include <iprt/asm.h>
142#include <iprt/assert.h>
143#include <iprt/thread.h>
144#include <iprt/time.h>
145#include <iprt/timer.h>
146#include <iprt/semaphore.h>
147#include <iprt/string.h>
148#include <iprt/env.h>
149
150
151/*******************************************************************************
152* Defined Constants And Macros *
153*******************************************************************************/
154/** The current saved state version.*/
155#define TM_SAVED_STATE_VERSION 3
156
157
158/*******************************************************************************
159* Internal Functions *
160*******************************************************************************/
161static bool tmR3HasFixedTSC(PVM pVM);
162static uint64_t tmR3CalibrateTSC(PVM pVM);
163static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM);
164static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
165static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
166static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue);
167static void tmR3TimerQueueRunVirtualSync(PVM pVM);
168static DECLCALLBACK(int) tmR3SetWarpDrive(PVM pVM, uint32_t u32Percent);
169static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
170static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
171static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
172
173
174/**
175 * Initializes the TM.
176 *
177 * @returns VBox status code.
178 * @param pVM The VM to operate on.
179 */
180VMMR3DECL(int) TMR3Init(PVM pVM)
181{
182 LogFlow(("TMR3Init:\n"));
183
184 /*
185 * Assert alignment and sizes.
186 */
187 AssertRelease(!(RT_OFFSETOF(VM, tm.s) & 31));
188 AssertRelease(sizeof(pVM->tm.s) <= sizeof(pVM->tm.padding));
189
190 /*
191 * Init the structure.
192 */
193 void *pv;
194 int rc = MMHyperAlloc(pVM, sizeof(pVM->tm.s.paTimerQueuesR3[0]) * TMCLOCK_MAX, 0, MM_TAG_TM, &pv);
195 AssertRCReturn(rc, rc);
196 pVM->tm.s.paTimerQueuesR3 = (PTMTIMERQUEUE)pv;
197 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pv);
198 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pv);
199
200 pVM->tm.s.offVM = RT_OFFSETOF(VM, tm.s);
201 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].enmClock = TMCLOCK_VIRTUAL;
202 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].u64Expire = INT64_MAX;
203 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].enmClock = TMCLOCK_VIRTUAL_SYNC;
204 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].u64Expire = INT64_MAX;
205 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].enmClock = TMCLOCK_REAL;
206 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].u64Expire = INT64_MAX;
207 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].enmClock = TMCLOCK_TSC;
208 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].u64Expire = INT64_MAX;
209
210 /*
211 * We directly use the GIP to calculate the virtual time. We map the
212 * the GIP into the guest context so we can do this calculation there
213 * as well and save costly world switches.
214 */
215 pVM->tm.s.pvGIPR3 = (void *)g_pSUPGlobalInfoPage;
216 AssertMsgReturn(pVM->tm.s.pvGIPR3, ("GIP support is now required!\n"), VERR_INTERNAL_ERROR);
217 RTHCPHYS HCPhysGIP;
218 rc = SUPGipGetPhys(&HCPhysGIP);
219 AssertMsgRCReturn(rc, ("Failed to get GIP physical address!\n"), rc);
220
221 RTGCPTR GCPtr;
222 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, NIL_RTR0PTR, HCPhysGIP, PAGE_SIZE, "GIP", &GCPtr);
223 if (RT_FAILURE(rc))
224 {
225 AssertMsgFailed(("Failed to map GIP into GC, rc=%Rrc!\n", rc));
226 return rc;
227 }
228 pVM->tm.s.pvGIPRC = GCPtr;
229 LogFlow(("TMR3Init: HCPhysGIP=%RHp at %RRv\n", HCPhysGIP, pVM->tm.s.pvGIPRC));
230 MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);
231
232 /* Check assumptions made in TMAllVirtual.cpp about the GIP update interval. */
233 if ( g_pSUPGlobalInfoPage->u32Magic == SUPGLOBALINFOPAGE_MAGIC
234 && g_pSUPGlobalInfoPage->u32UpdateIntervalNS >= 250000000 /* 0.25s */)
235 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
236 N_("The GIP update interval is too big. u32UpdateIntervalNS=%RU32 (u32UpdateHz=%RU32)"),
237 g_pSUPGlobalInfoPage->u32UpdateIntervalNS, g_pSUPGlobalInfoPage->u32UpdateHz);
238 LogRel(("TM: GIP - u32Mode=%d (%s) u32UpdateHz=%u\n", g_pSUPGlobalInfoPage->u32Mode,
239 g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC ? "SyncTSC"
240 : g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_ASYNC_TSC ? "AsyncTSC" : "Unknown",
241 g_pSUPGlobalInfoPage->u32UpdateHz));
242
243 /*
244 * Setup the VirtualGetRaw backend.
245 */
246 pVM->tm.s.VirtualGetRawDataR3.pu64Prev = &pVM->tm.s.u64VirtualRawPrev;
247 pVM->tm.s.VirtualGetRawDataR3.pfnBad = tmVirtualNanoTSBad;
248 pVM->tm.s.VirtualGetRawDataR3.pfnRediscover = tmVirtualNanoTSRediscover;
249 if (ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2)
250 {
251 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
252 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceSync;
253 else
254 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceAsync;
255 }
256 else
257 {
258 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
259 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacySync;
260 else
261 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacyAsync;
262 }
263
264 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
265 pVM->tm.s.VirtualGetRawDataR0.pu64Prev = MMHyperR3ToR0(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
266 AssertReturn(pVM->tm.s.VirtualGetRawDataR0.pu64Prev, VERR_INTERNAL_ERROR);
267 /* The rest is done in TMR3InitFinalize since it's too early to call PDM. */
268
269 /*
270 * Init the lock.
271 */
272 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.EmtLock, "TM EMT Lock");
273 if (RT_FAILURE(rc))
274 return rc;
275
276 /*
277 * Get our CFGM node, create it if necessary.
278 */
279 PCFGMNODE pCfgHandle = CFGMR3GetChild(CFGMR3GetRoot(pVM), "TM");
280 if (!pCfgHandle)
281 {
282 rc = CFGMR3InsertNode(CFGMR3GetRoot(pVM), "TM", &pCfgHandle);
283 AssertRCReturn(rc, rc);
284 }
285
286 /*
287 * Determin the TSC configuration and frequency.
288 */
289 /* mode */
290 /** @cfgm{/TM/TSCVirtualized,bool,true}
291 * Use a virtualize TSC, i.e. trap all TSC access. */
292 rc = CFGMR3QueryBool(pCfgHandle, "TSCVirtualized", &pVM->tm.s.fTSCVirtualized);
293 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
294 pVM->tm.s.fTSCVirtualized = true; /* trap rdtsc */
295 else if (RT_FAILURE(rc))
296 return VMSetError(pVM, rc, RT_SRC_POS,
297 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
298
299 /* source */
300 /** @cfgm{/TM/UseRealTSC,bool,false}
301 * Use the real TSC as time source for the TSC instead of the synchronous
302 * virtual clock (false, default). */
303 rc = CFGMR3QueryBool(pCfgHandle, "UseRealTSC", &pVM->tm.s.fTSCUseRealTSC);
304 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
305 pVM->tm.s.fTSCUseRealTSC = false; /* use virtual time */
306 else if (RT_FAILURE(rc))
307 return VMSetError(pVM, rc, RT_SRC_POS,
308 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
309 if (!pVM->tm.s.fTSCUseRealTSC)
310 pVM->tm.s.fTSCVirtualized = true;
311
312 /* TSC reliability */
313 /** @cfgm{/TM/MaybeUseOffsettedHostTSC,bool,detect}
314 * Whether the CPU has a fixed TSC rate and may be used in offsetted mode with
315 * VT-x/AMD-V execution. This is autodetected in a very restrictive way by
316 * default. */
317 rc = CFGMR3QueryBool(pCfgHandle, "MaybeUseOffsettedHostTSC", &pVM->tm.s.fMaybeUseOffsettedHostTSC);
318 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
319 {
320 if (!pVM->tm.s.fTSCUseRealTSC)
321 {
322 /* @todo simple case for guest SMP; always emulate RDTSC */
323 if (pVM->cCPUs == 1)
324 pVM->tm.s.fMaybeUseOffsettedHostTSC = tmR3HasFixedTSC(pVM);
325 }
326 else
327 pVM->tm.s.fMaybeUseOffsettedHostTSC = true;
328 }
329
330 /** @cfgm{TM/TSCTicksPerSecond, uint32_t, Current TSC frequency from GIP}
331 * The number of TSC ticks per second (i.e. the TSC frequency). This will
332 * override TSCUseRealTSC, TSCVirtualized and MaybeUseOffsettedHostTSC.
333 */
334 rc = CFGMR3QueryU64(pCfgHandle, "TSCTicksPerSecond", &pVM->tm.s.cTSCTicksPerSecond);
335 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
336 {
337 pVM->tm.s.cTSCTicksPerSecond = tmR3CalibrateTSC(pVM);
338 if ( !pVM->tm.s.fTSCUseRealTSC
339 && pVM->tm.s.cTSCTicksPerSecond >= _4G)
340 {
341 pVM->tm.s.cTSCTicksPerSecond = _4G - 1; /* (A limitation of our math code) */
342 pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
343 }
344 }
345 else if (RT_FAILURE(rc))
346 return VMSetError(pVM, rc, RT_SRC_POS,
347 N_("Configuration error: Failed to querying uint64_t value \"TSCTicksPerSecond\""));
348 else if ( pVM->tm.s.cTSCTicksPerSecond < _1M
349 || pVM->tm.s.cTSCTicksPerSecond >= _4G)
350 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
351 N_("Configuration error: \"TSCTicksPerSecond\" = %RI64 is not in the range 1MHz..4GHz-1"),
352 pVM->tm.s.cTSCTicksPerSecond);
353 else
354 {
355 pVM->tm.s.fTSCUseRealTSC = pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
356 pVM->tm.s.fTSCVirtualized = true;
357 }
358
359 /** @cfgm{TM/TSCTiedToExecution, bool, false}
360 * Whether the TSC should be tied to execution. This will exclude most of the
361 * virtualization overhead, but will by default include the time spent in the
362 * halt state (see TM/TSCNotTiedToHalt). This setting will override all other
363 * TSC settings except for TSCTicksPerSecond and TSCNotTiedToHalt, which should
364 * be used avoided or used with great care. Note that this will only work right
365 * together with VT-x or AMD-V, and with a single virtual CPU. */
366 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCTiedToExecution", &pVM->tm.s.fTSCTiedToExecution, false);
367 if (RT_FAILURE(rc))
368 return VMSetError(pVM, rc, RT_SRC_POS,
369 N_("Configuration error: Failed to querying bool value \"TSCTiedToExecution\""));
370 if (pVM->tm.s.fTSCTiedToExecution)
371 {
372 /* tied to execution, override all other settings. */
373 pVM->tm.s.fTSCVirtualized = true;
374 pVM->tm.s.fTSCUseRealTSC = true;
375 pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
376 }
377
378 /** @cfgm{TM/TSCNotTiedToHalt, bool, true}
379 * For overriding the default of TM/TSCTiedToExecution, i.e. set this to false
380 * to make the TSC freeze during HLT. */
381 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCNotTiedToHalt", &pVM->tm.s.fTSCNotTiedToHalt, false);
382 if (RT_FAILURE(rc))
383 return VMSetError(pVM, rc, RT_SRC_POS,
384 N_("Configuration error: Failed to querying bool value \"TSCNotTiedToHalt\""));
385
386 /* setup and report */
387 if (pVM->tm.s.fTSCVirtualized)
388 CPUMR3SetCR4Feature(pVM, X86_CR4_TSD, ~X86_CR4_TSD);
389 else
390 CPUMR3SetCR4Feature(pVM, 0, ~X86_CR4_TSD);
391 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool\n"
392 "TM: fMaybeUseOffsettedHostTSC=%RTbool TSCTiedToExecution=%RTbool TSCNotTiedToHalt=%RTbool\n",
393 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC,
394 pVM->tm.s.fMaybeUseOffsettedHostTSC, pVM->tm.s.fTSCTiedToExecution, pVM->tm.s.fTSCNotTiedToHalt));
395
396 /*
397 * Configure the timer synchronous virtual time.
398 */
399 /** @cfgm{TM/ScheduleSlack, uint32_t, ns, 0, UINT32_MAX, 100000}
400 * Scheduling slack when processing timers. */
401 rc = CFGMR3QueryU32(pCfgHandle, "ScheduleSlack", &pVM->tm.s.u32VirtualSyncScheduleSlack);
402 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
403 pVM->tm.s.u32VirtualSyncScheduleSlack = 100000; /* 0.100ms (ASSUMES virtual time is nanoseconds) */
404 else if (RT_FAILURE(rc))
405 return VMSetError(pVM, rc, RT_SRC_POS,
406 N_("Configuration error: Failed to querying 32-bit integer value \"ScheduleSlack\""));
407
408 /** @cfgm{TM/CatchUpStopThreshold, uint64_t, ns, 0, UINT64_MAX, 500000}
409 * When to stop a catch-up, considering it successful. */
410 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStopThreshold", &pVM->tm.s.u64VirtualSyncCatchUpStopThreshold);
411 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
412 pVM->tm.s.u64VirtualSyncCatchUpStopThreshold = 500000; /* 0.5ms */
413 else if (RT_FAILURE(rc))
414 return VMSetError(pVM, rc, RT_SRC_POS,
415 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpStopThreshold\""));
416
417 /** @cfgm{TM/CatchUpGiveUpThreshold, uint64_t, ns, 0, UINT64_MAX, 60000000000}
418 * When to give up a catch-up attempt. */
419 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpGiveUpThreshold", &pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold);
420 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
421 pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold = UINT64_C(60000000000); /* 60 sec */
422 else if (RT_FAILURE(rc))
423 return VMSetError(pVM, rc, RT_SRC_POS,
424 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpGiveUpThreshold\""));
425
426
427 /** @cfgm{TM/CatchUpPrecentage[0..9], uint32_t, %, 1, 2000, various}
428 * The catch-up percent for a given period. */
429 /** @cfgm{TM/CatchUpStartThreshold[0..9], uint64_t, ns, 0, UINT64_MAX,
430 * The catch-up period threshold, or if you like, when a period starts. */
431#define TM_CFG_PERIOD(iPeriod, DefStart, DefPct) \
432 do \
433 { \
434 uint64_t u64; \
435 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStartThreshold" #iPeriod, &u64); \
436 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
437 u64 = UINT64_C(DefStart); \
438 else if (RT_FAILURE(rc)) \
439 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpThreshold" #iPeriod "\"")); \
440 if ( (iPeriod > 0 && u64 <= pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod - 1].u64Start) \
441 || u64 >= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold) \
442 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Configuration error: Invalid start of period #" #iPeriod ": %RU64"), u64); \
443 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u64Start = u64; \
444 rc = CFGMR3QueryU32(pCfgHandle, "CatchUpPrecentage" #iPeriod, &pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage); \
445 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
446 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage = (DefPct); \
447 else if (RT_FAILURE(rc)) \
448 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 32-bit integer value \"CatchUpPrecentage" #iPeriod "\"")); \
449 } while (0)
450 /* This needs more tuning. Not sure if we really need so many period and be so gentle. */
451 TM_CFG_PERIOD(0, 750000, 5); /* 0.75ms at 1.05x */
452 TM_CFG_PERIOD(1, 1500000, 10); /* 1.50ms at 1.10x */
453 TM_CFG_PERIOD(2, 8000000, 25); /* 8ms at 1.25x */
454 TM_CFG_PERIOD(3, 30000000, 50); /* 30ms at 1.50x */
455 TM_CFG_PERIOD(4, 75000000, 75); /* 75ms at 1.75x */
456 TM_CFG_PERIOD(5, 175000000, 100); /* 175ms at 2x */
457 TM_CFG_PERIOD(6, 500000000, 200); /* 500ms at 3x */
458 TM_CFG_PERIOD(7, 3000000000, 300); /* 3s at 4x */
459 TM_CFG_PERIOD(8,30000000000, 400); /* 30s at 5x */
460 TM_CFG_PERIOD(9,55000000000, 500); /* 55s at 6x */
461 AssertCompile(RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods) == 10);
462#undef TM_CFG_PERIOD
463
464 /*
465 * Configure real world time (UTC).
466 */
467 /** @cfgm{TM/UTCOffset, int64_t, ns, INT64_MIN, INT64_MAX, 0}
468 * The UTC offset. This is used to put the guest back or forwards in time. */
469 rc = CFGMR3QueryS64(pCfgHandle, "UTCOffset", &pVM->tm.s.offUTC);
470 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
471 pVM->tm.s.offUTC = 0; /* ns */
472 else if (RT_FAILURE(rc))
473 return VMSetError(pVM, rc, RT_SRC_POS,
474 N_("Configuration error: Failed to querying 64-bit integer value \"UTCOffset\""));
475
476 /*
477 * Setup the warp drive.
478 */
479 /** @cfgm{TM/WarpDrivePercentage, uint32_t, %, 0, 20000, 100}
480 * The warp drive percentage, 100% is normal speed. This is used to speed up
481 * or slow down the virtual clock, which can be useful for fast forwarding
482 * borring periods during tests. */
483 rc = CFGMR3QueryU32(pCfgHandle, "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage);
484 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
485 rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage); /* legacy */
486 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
487 pVM->tm.s.u32VirtualWarpDrivePercentage = 100;
488 else if (RT_FAILURE(rc))
489 return VMSetError(pVM, rc, RT_SRC_POS,
490 N_("Configuration error: Failed to querying uint32_t value \"WarpDrivePercent\""));
491 else if ( pVM->tm.s.u32VirtualWarpDrivePercentage < 2
492 || pVM->tm.s.u32VirtualWarpDrivePercentage > 20000)
493 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
494 N_("Configuration error: \"WarpDrivePercent\" = %RI32 is not in the range 2..20000"),
495 pVM->tm.s.u32VirtualWarpDrivePercentage);
496 pVM->tm.s.fVirtualWarpDrive = pVM->tm.s.u32VirtualWarpDrivePercentage != 100;
497 if (pVM->tm.s.fVirtualWarpDrive)
498 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32\n", pVM->tm.s.u32VirtualWarpDrivePercentage));
499
500 /*
501 * Start the timer (guard against REM not yielding).
502 */
503 /** @cfgm{TM/TimerMillies, uint32_t, ms, 1, 1000, 10}
504 * The watchdog timer interval. */
505 uint32_t u32Millies;
506 rc = CFGMR3QueryU32(pCfgHandle, "TimerMillies", &u32Millies);
507 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
508 u32Millies = 10;
509 else if (RT_FAILURE(rc))
510 return VMSetError(pVM, rc, RT_SRC_POS,
511 N_("Configuration error: Failed to query uint32_t value \"TimerMillies\""));
512 rc = RTTimerCreate(&pVM->tm.s.pTimer, u32Millies, tmR3TimerCallback, pVM);
513 if (RT_FAILURE(rc))
514 {
515 AssertMsgFailed(("Failed to create timer, u32Millies=%d rc=%Rrc.\n", u32Millies, rc));
516 return rc;
517 }
518 Log(("TM: Created timer %p firing every %d millieseconds\n", pVM->tm.s.pTimer, u32Millies));
519 pVM->tm.s.u32TimerMillies = u32Millies;
520
521 /*
522 * Register saved state.
523 */
524 rc = SSMR3RegisterInternal(pVM, "tm", 1, TM_SAVED_STATE_VERSION, sizeof(uint64_t) * 8,
525 NULL, tmR3Save, NULL,
526 NULL, tmR3Load, NULL);
527 if (RT_FAILURE(rc))
528 return rc;
529
530 /*
531 * Register statistics.
532 */
533 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).");
534 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).");
535 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).");
536 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).");
537 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.c1nsSteps,STAMTYPE_U32, "/TM/GC/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
538 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.cBadPrev, STAMTYPE_U32, "/TM/GC/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
539 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)");
540 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 attemted caught up with.");
541
542#ifdef VBOX_WITH_STATISTICS
543 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).");
544 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR3.cUpdateRaces,STAMTYPE_U32, "/TM/R3/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
545 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).");
546 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR0.cUpdateRaces,STAMTYPE_U32, "/TM/R0/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
547 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cExpired, STAMTYPE_U32, "/TM/GC/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
548 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cUpdateRaces,STAMTYPE_U32, "/TM/GC/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
549 STAM_REG(pVM, &pVM->tm.s.StatDoQueues, STAMTYPE_PROFILE, "/TM/DoQueues", STAMUNIT_TICKS_PER_CALL, "Profiling timer TMR3TimerQueuesDo.");
550 STAM_REG(pVM, &pVM->tm.s.StatDoQueuesSchedule, STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Schedule", STAMUNIT_TICKS_PER_CALL, "The scheduling part.");
551 STAM_REG(pVM, &pVM->tm.s.StatDoQueuesRun, STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Run", STAMUNIT_TICKS_PER_CALL, "The run part.");
552
553 STAM_REG(pVM, &pVM->tm.s.StatPollAlreadySet, STAMTYPE_COUNTER, "/TM/PollAlreadySet", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the FF was already set.");
554 STAM_REG(pVM, &pVM->tm.s.StatPollVirtual, STAMTYPE_COUNTER, "/TM/PollHitsVirtual", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL queue.");
555 STAM_REG(pVM, &pVM->tm.s.StatPollVirtualSync, STAMTYPE_COUNTER, "/TM/PollHitsVirtualSync", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL_SYNC queue.");
556 STAM_REG(pVM, &pVM->tm.s.StatPollMiss, STAMTYPE_COUNTER, "/TM/PollMiss", STAMUNIT_OCCURENCES, "TMTimerPoll calls where nothing had expired.");
557
558 STAM_REG(pVM, &pVM->tm.s.StatPostponedR3, STAMTYPE_COUNTER, "/TM/PostponedR3", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-3.");
559 STAM_REG(pVM, &pVM->tm.s.StatPostponedRZ, STAMTYPE_COUNTER, "/TM/PostponedRZ", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-0 / RC.");
560
561 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.");
562 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.");
563 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.");
564
565 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR3, STAMTYPE_PROFILE, "/TM/TimerSetR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3.");
566 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRZ, STAMTYPE_PROFILE, "/TM/TimerSetRZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0 / RC.");
567
568 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR3, STAMTYPE_PROFILE, "/TM/TimerStopR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-3.");
569 STAM_REG(pVM, &pVM->tm.s.StatTimerStopRZ, STAMTYPE_PROFILE, "/TM/TimerStopRZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-0 / RC.");
570
571 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.");
572 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualGetSetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGet.");
573 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSync, STAMTYPE_COUNTER, "/TM/VirtualGetSync", STAMUNIT_OCCURENCES, "The number of times TMTimerGetSync was called when the clock was running.");
574 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSyncSetFF, STAMTYPE_COUNTER, "/TM/VirtualGetSyncSetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGetSync.");
575 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/VirtualPause", STAMUNIT_OCCURENCES, "The number of times TMR3TimerPause was called.");
576 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/VirtualResume", STAMUNIT_OCCURENCES, "The number of times TMR3TimerResume was called.");
577
578 STAM_REG(pVM, &pVM->tm.s.StatTimerCallbackSetFF, STAMTYPE_COUNTER, "/TM/CallbackSetFF", STAMUNIT_OCCURENCES, "The number of times the timer callback set FF.");
579
580 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE010, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE010", STAMUNIT_OCCURENCES, "In catch-up mode, 10% or lower.");
581 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE025, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE025", STAMUNIT_OCCURENCES, "In catch-up mode, 25%-11%.");
582 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE100, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE100", STAMUNIT_OCCURENCES, "In catch-up mode, 100%-26%.");
583 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupOther, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupOther", STAMUNIT_OCCURENCES, "In catch-up mode, > 100%.");
584 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.");
585 STAM_REG(pVM, &pVM->tm.s.StatTSCNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotTicking", STAMUNIT_OCCURENCES, "TSC is not ticking.");
586 STAM_REG(pVM, &pVM->tm.s.StatTSCSyncNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/SyncNotTicking", STAMUNIT_OCCURENCES, "VirtualSync isn't ticking.");
587 STAM_REG(pVM, &pVM->tm.s.StatTSCWarp, STAMTYPE_COUNTER, "/TM/TSC/Intercept/Warp", STAMUNIT_OCCURENCES, "Warpdrive is active.");
588
589
590 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.");
591 STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
592 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)");
593 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
594 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++.)");
595 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
596 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
597 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.");
598 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
599 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.)");
600 for (unsigned i = 0; i < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods); i++)
601 {
602 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
603 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
604 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
605 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);
606 }
607
608#endif /* VBOX_WITH_STATISTICS */
609
610 /*
611 * Register info handlers.
612 */
613 DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
614 DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
615 DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
616
617 return VINF_SUCCESS;
618}
619
620
621/**
622 * Initializes the per-VCPU TM.
623 *
624 * @returns VBox status code.
625 * @param pVM The VM to operate on.
626 */
627VMMR3DECL(int) TMR3InitCPU(PVM pVM)
628{
629 LogFlow(("TMR3InitCPU\n"));
630 return VINF_SUCCESS;
631}
632
633
634/**
635 * Checks if the host CPU has a fixed TSC frequency.
636 *
637 * @returns true if it has, false if it hasn't.
638 *
639 * @remark This test doesn't bother with very old CPUs that don't do power
640 * management or any other stuff that might influence the TSC rate.
641 * This isn't currently relevant.
642 */
643static bool tmR3HasFixedTSC(PVM pVM)
644{
645 if (ASMHasCpuId())
646 {
647 uint32_t uEAX, uEBX, uECX, uEDX;
648
649 if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_AMD)
650 {
651 /*
652 * AuthenticAMD - Check for APM support and that TscInvariant is set.
653 *
654 * This test isn't correct with respect to fixed/non-fixed TSC and
655 * older models, but this isn't relevant since the result is currently
656 * only used for making a descision on AMD-V models.
657 */
658 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
659 if (uEAX >= 0x80000007)
660 {
661 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
662
663 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
664 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
665 && pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* no fixed tsc if the gip timer is in async mode */)
666 return true;
667 }
668 }
669 else if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_INTEL)
670 {
671 /*
672 * GenuineIntel - Check the model number.
673 *
674 * This test is lacking in the same way and for the same reasons
675 * as the AMD test above.
676 */
677 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
678 unsigned uModel = (uEAX >> 4) & 0x0f;
679 unsigned uFamily = (uEAX >> 8) & 0x0f;
680 if (uFamily == 0x0f)
681 uFamily += (uEAX >> 20) & 0xff;
682 if (uFamily >= 0x06)
683 uModel += ((uEAX >> 16) & 0x0f) << 4;
684 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
685 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
686 return true;
687 }
688 }
689 return false;
690}
691
692
693/**
694 * Calibrate the CPU tick.
695 *
696 * @returns Number of ticks per second.
697 */
698static uint64_t tmR3CalibrateTSC(PVM pVM)
699{
700 /*
701 * Use GIP when available present.
702 */
703 uint64_t u64Hz;
704 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
705 if ( pGip
706 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC)
707 {
708 unsigned iCpu = pGip->u32Mode != SUPGIPMODE_ASYNC_TSC ? 0 : ASMGetApicId();
709 if (iCpu >= RT_ELEMENTS(pGip->aCPUs))
710 AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
711 else
712 {
713 if (tmR3HasFixedTSC(pVM))
714 /* Sleep a bit to get a more reliable CpuHz value. */
715 RTThreadSleep(32);
716 else
717 {
718 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
719 const uint64_t u64 = RTTimeMilliTS();
720 while ((RTTimeMilliTS() - u64) < 40 /*ms*/)
721 /* nothing */;
722 }
723
724 pGip = g_pSUPGlobalInfoPage;
725 if ( pGip
726 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC
727 && (u64Hz = pGip->aCPUs[iCpu].u64CpuHz)
728 && u64Hz != ~(uint64_t)0)
729 return u64Hz;
730 }
731 }
732
733 /* call this once first to make sure it's initialized. */
734 RTTimeNanoTS();
735
736 /*
737 * Yield the CPU to increase our chances of getting
738 * a correct value.
739 */
740 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
741 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
742 uint64_t au64Samples[5];
743 unsigned i;
744 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
745 {
746 unsigned cMillies;
747 int cTries = 5;
748 uint64_t u64Start = ASMReadTSC();
749 uint64_t u64End;
750 uint64_t StartTS = RTTimeNanoTS();
751 uint64_t EndTS;
752 do
753 {
754 RTThreadSleep(s_auSleep[i]);
755 u64End = ASMReadTSC();
756 EndTS = RTTimeNanoTS();
757 cMillies = (unsigned)((EndTS - StartTS + 500000) / 1000000);
758 } while ( cMillies == 0 /* the sleep may be interrupted... */
759 || (cMillies < 20 && --cTries > 0));
760 uint64_t u64Diff = u64End - u64Start;
761
762 au64Samples[i] = (u64Diff * 1000) / cMillies;
763 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
764 }
765
766 /*
767 * Discard the highest and lowest results and calculate the average.
768 */
769 unsigned iHigh = 0;
770 unsigned iLow = 0;
771 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
772 {
773 if (au64Samples[i] < au64Samples[iLow])
774 iLow = i;
775 if (au64Samples[i] > au64Samples[iHigh])
776 iHigh = i;
777 }
778 au64Samples[iLow] = 0;
779 au64Samples[iHigh] = 0;
780
781 u64Hz = au64Samples[0];
782 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
783 u64Hz += au64Samples[i];
784 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
785
786 return u64Hz;
787}
788
789
790/**
791 * Finalizes the TM initialization.
792 *
793 * @returns VBox status code.
794 * @param pVM The VM to operate on.
795 */
796VMMR3DECL(int) TMR3InitFinalize(PVM pVM)
797{
798 int rc;
799
800 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
801 AssertRCReturn(rc, rc);
802 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
803 AssertRCReturn(rc, rc);
804 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
805 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
806 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
807 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
808 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
809 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
810 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
811 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
812 else
813 AssertFatalFailed();
814 AssertRCReturn(rc, rc);
815
816 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
817 AssertRCReturn(rc, rc);
818 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
819 AssertRCReturn(rc, rc);
820 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
821 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawR0);
822 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
823 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawR0);
824 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
825 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawR0);
826 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
827 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawR0);
828 else
829 AssertFatalFailed();
830 AssertRCReturn(rc, rc);
831
832 return VINF_SUCCESS;
833}
834
835
836/**
837 * Applies relocations to data and code managed by this
838 * component. This function will be called at init and
839 * whenever the VMM need to relocate it self inside the GC.
840 *
841 * @param pVM The VM.
842 * @param offDelta Relocation delta relative to old location.
843 */
844VMMR3DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
845{
846 int rc;
847 LogFlow(("TMR3Relocate\n"));
848
849 pVM->tm.s.pvGIPRC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
850 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
851 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
852
853 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
854 AssertFatal(pVM->tm.s.VirtualGetRawDataRC.pu64Prev);
855 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
856 AssertFatalRC(rc);
857 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
858 AssertFatalRC(rc);
859
860 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
861 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
862 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
863 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
864 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
865 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
866 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
867 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
868 else
869 AssertFatalFailed();
870 AssertFatalRC(rc);
871
872 /*
873 * Iterate the timers updating the pVMRC pointers.
874 */
875 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
876 {
877 pTimer->pVMRC = pVM->pVMRC;
878 pTimer->pVMR0 = pVM->pVMR0;
879 }
880}
881
882
883/**
884 * Terminates the TM.
885 *
886 * Termination means cleaning up and freeing all resources,
887 * the VM it self is at this point powered off or suspended.
888 *
889 * @returns VBox status code.
890 * @param pVM The VM to operate on.
891 */
892VMMR3DECL(int) TMR3Term(PVM pVM)
893{
894 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
895 if (pVM->tm.s.pTimer)
896 {
897 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
898 AssertRC(rc);
899 pVM->tm.s.pTimer = NULL;
900 }
901
902 return VINF_SUCCESS;
903}
904
905
906/**
907 * Terminates the per-VCPU TM.
908 *
909 * Termination means cleaning up and freeing all resources,
910 * the VM it self is at this point powered off or suspended.
911 *
912 * @returns VBox status code.
913 * @param pVM The VM to operate on.
914 */
915VMMR3DECL(int) TMR3TermCPU(PVM pVM)
916{
917 return 0;
918}
919
920
921/**
922 * The VM is being reset.
923 *
924 * For the TM component this means that a rescheduling is preformed,
925 * the FF is cleared and but without running the queues. We'll have to
926 * check if this makes sense or not, but it seems like a good idea now....
927 *
928 * @param pVM VM handle.
929 */
930VMMR3DECL(void) TMR3Reset(PVM pVM)
931{
932 LogFlow(("TMR3Reset:\n"));
933 VM_ASSERT_EMT(pVM);
934 tmLock(pVM);
935
936 /*
937 * Abort any pending catch up.
938 * This isn't perfect,
939 */
940 if (pVM->tm.s.fVirtualSyncCatchUp)
941 {
942 const uint64_t offVirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
943 const uint64_t offVirtualSyncNow = TMVirtualSyncGetEx(pVM, false /* don't check timers */);
944 if (pVM->tm.s.fVirtualSyncCatchUp)
945 {
946 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
947
948 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
949 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
950 Assert(offOld <= offNew);
951 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
952 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
953 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
954 LogRel(("TM: Aborting catch-up attempt on reset with a %RU64 ns lag on reset; new total: %RU64 ns\n", offNew - offOld, offNew));
955 }
956 }
957
958 /*
959 * Process the queues.
960 */
961 for (int i = 0; i < TMCLOCK_MAX; i++)
962 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
963#ifdef VBOX_STRICT
964 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
965#endif
966
967 VM_FF_CLEAR(pVM, VM_FF_TIMER);
968 tmUnlock(pVM);
969}
970
971
972/**
973 * Resolve a builtin RC symbol.
974 * Called by PDM when loading or relocating GC modules.
975 *
976 * @returns VBox status
977 * @param pVM VM Handle.
978 * @param pszSymbol Symbol to resolve.
979 * @param pRCPtrValue Where to store the symbol value.
980 * @remark This has to work before TMR3Relocate() is called.
981 */
982VMMR3DECL(int) TMR3GetImportRC(PVM pVM, const char *pszSymbol, PRTRCPTR pRCPtrValue)
983{
984 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
985 *pRCPtrValue = MMHyperR3ToRC(pVM, &pVM->tm.s.pvGIPRC);
986 //else if (..)
987 else
988 return VERR_SYMBOL_NOT_FOUND;
989 return VINF_SUCCESS;
990}
991
992
993/**
994 * Execute state save operation.
995 *
996 * @returns VBox status code.
997 * @param pVM VM Handle.
998 * @param pSSM SSM operation handle.
999 */
1000static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
1001{
1002 LogFlow(("tmR3Save:\n"));
1003#ifdef VBOX_STRICT
1004 for (VMCPUID i = 0; i < pVM->cCPUs; i++)
1005 {
1006 PVMCPU pVCpu = &pVM->aCpus[i];
1007 Assert(!pVCpu->tm.s.fTSCTicking);
1008 }
1009 Assert(!pVM->tm.s.cVirtualTicking);
1010 Assert(!pVM->tm.s.fVirtualSyncTicking);
1011#endif
1012
1013 /*
1014 * Save the virtual clocks.
1015 */
1016 /* the virtual clock. */
1017 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
1018 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
1019
1020 /* the virtual timer synchronous clock. */
1021 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
1022 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
1023 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
1024 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
1025 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
1026
1027 /* real time clock */
1028 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
1029
1030 for (VMCPUID i = 0; i < pVM->cCPUs; i++)
1031 {
1032 PVMCPU pVCpu = &pVM->aCpus[i];
1033
1034 /* the cpu tick clock. */
1035 SSMR3PutU64(pSSM, TMCpuTickGet(pVCpu));
1036 }
1037 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
1038}
1039
1040
1041/**
1042 * Execute state load operation.
1043 *
1044 * @returns VBox status code.
1045 * @param pVM VM Handle.
1046 * @param pSSM SSM operation handle.
1047 * @param u32Version Data layout version.
1048 */
1049static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
1050{
1051 LogFlow(("tmR3Load:\n"));
1052
1053#ifdef VBOX_STRICT
1054 for (VMCPUID i = 0; i < pVM->cCPUs; i++)
1055 {
1056 PVMCPU pVCpu = &pVM->aCpus[i];
1057 Assert(!pVCpu->tm.s.fTSCTicking);
1058 }
1059 Assert(!pVM->tm.s.cVirtualTicking);
1060 Assert(!pVM->tm.s.fVirtualSyncTicking);
1061#endif
1062
1063 /*
1064 * Validate version.
1065 */
1066 if (u32Version != TM_SAVED_STATE_VERSION)
1067 {
1068 AssertMsgFailed(("tmR3Load: Invalid version u32Version=%d!\n", u32Version));
1069 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1070 }
1071
1072 /*
1073 * Load the virtual clock.
1074 */
1075 pVM->tm.s.cVirtualTicking = 0;
1076 /* the virtual clock. */
1077 uint64_t u64Hz;
1078 int rc = SSMR3GetU64(pSSM, &u64Hz);
1079 if (RT_FAILURE(rc))
1080 return rc;
1081 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
1082 {
1083 AssertMsgFailed(("The virtual clock frequency differs! Saved: %RU64 Binary: %RU64\n",
1084 u64Hz, TMCLOCK_FREQ_VIRTUAL));
1085 return VERR_SSM_VIRTUAL_CLOCK_HZ;
1086 }
1087 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
1088 pVM->tm.s.u64VirtualOffset = 0;
1089
1090 /* the virtual timer synchronous clock. */
1091 pVM->tm.s.fVirtualSyncTicking = false;
1092 uint64_t u64;
1093 SSMR3GetU64(pSSM, &u64);
1094 pVM->tm.s.u64VirtualSync = u64;
1095 SSMR3GetU64(pSSM, &u64);
1096 pVM->tm.s.offVirtualSync = u64;
1097 SSMR3GetU64(pSSM, &u64);
1098 pVM->tm.s.offVirtualSyncGivenUp = u64;
1099 SSMR3GetU64(pSSM, &u64);
1100 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1101 bool f;
1102 SSMR3GetBool(pSSM, &f);
1103 pVM->tm.s.fVirtualSyncCatchUp = f;
1104
1105 /* the real clock */
1106 rc = SSMR3GetU64(pSSM, &u64Hz);
1107 if (RT_FAILURE(rc))
1108 return rc;
1109 if (u64Hz != TMCLOCK_FREQ_REAL)
1110 {
1111 AssertMsgFailed(("The real clock frequency differs! Saved: %RU64 Binary: %RU64\n",
1112 u64Hz, TMCLOCK_FREQ_REAL));
1113 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
1114 }
1115
1116 /* the cpu tick clock. */
1117 for (VMCPUID i = 0; i < pVM->cCPUs; i++)
1118 {
1119 PVMCPU pVCpu = &pVM->aCpus[i];
1120
1121 pVCpu->tm.s.fTSCTicking = false;
1122 SSMR3GetU64(pSSM, &pVCpu->tm.s.u64TSC);
1123
1124 if (pVM->tm.s.fTSCUseRealTSC)
1125 pVCpu->tm.s.u64TSCOffset = 0; /** @todo TSC restore stuff and HWACC. */
1126 }
1127
1128 rc = SSMR3GetU64(pSSM, &u64Hz);
1129 if (RT_FAILURE(rc))
1130 return rc;
1131 if (!pVM->tm.s.fTSCUseRealTSC)
1132 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1133
1134 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1135 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1136
1137 /*
1138 * Make sure timers get rescheduled immediately.
1139 */
1140 VM_FF_SET(pVM, VM_FF_TIMER);
1141
1142 return VINF_SUCCESS;
1143}
1144
1145
1146/**
1147 * Internal TMR3TimerCreate worker.
1148 *
1149 * @returns VBox status code.
1150 * @param pVM The VM handle.
1151 * @param enmClock The timer clock.
1152 * @param pszDesc The timer description.
1153 * @param ppTimer Where to store the timer pointer on success.
1154 */
1155static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1156{
1157 VM_ASSERT_EMT(pVM);
1158
1159 /*
1160 * Allocate the timer.
1161 */
1162 PTMTIMERR3 pTimer = NULL;
1163 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1164 {
1165 pTimer = pVM->tm.s.pFree;
1166 pVM->tm.s.pFree = pTimer->pBigNext;
1167 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1168 }
1169
1170 if (!pTimer)
1171 {
1172 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1173 if (RT_FAILURE(rc))
1174 return rc;
1175 Log3(("TM: Allocated new timer %p\n", pTimer));
1176 }
1177
1178 /*
1179 * Initialize it.
1180 */
1181 pTimer->u64Expire = 0;
1182 pTimer->enmClock = enmClock;
1183 pTimer->pVMR3 = pVM;
1184 pTimer->pVMR0 = pVM->pVMR0;
1185 pTimer->pVMRC = pVM->pVMRC;
1186 pTimer->enmState = TMTIMERSTATE_STOPPED;
1187 pTimer->offScheduleNext = 0;
1188 pTimer->offNext = 0;
1189 pTimer->offPrev = 0;
1190 pTimer->pszDesc = pszDesc;
1191
1192 /* insert into the list of created timers. */
1193 tmLock(pVM);
1194 pTimer->pBigPrev = NULL;
1195 pTimer->pBigNext = pVM->tm.s.pCreated;
1196 pVM->tm.s.pCreated = pTimer;
1197 if (pTimer->pBigNext)
1198 pTimer->pBigNext->pBigPrev = pTimer;
1199#ifdef VBOX_STRICT
1200 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1201#endif
1202 tmUnlock(pVM);
1203
1204 *ppTimer = pTimer;
1205 return VINF_SUCCESS;
1206}
1207
1208
1209/**
1210 * Creates a device timer.
1211 *
1212 * @returns VBox status.
1213 * @param pVM The VM to create the timer in.
1214 * @param pDevIns Device instance.
1215 * @param enmClock The clock to use on this timer.
1216 * @param pfnCallback Callback function.
1217 * @param pszDesc Pointer to description string which must stay around
1218 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1219 * @param ppTimer Where to store the timer on success.
1220 */
1221VMMR3DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1222{
1223 /*
1224 * Allocate and init stuff.
1225 */
1226 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1227 if (RT_SUCCESS(rc))
1228 {
1229 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1230 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1231 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1232 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1233 }
1234
1235 return rc;
1236}
1237
1238
1239/**
1240 * Creates a driver timer.
1241 *
1242 * @returns VBox status.
1243 * @param pVM The VM to create the timer in.
1244 * @param pDrvIns Driver instance.
1245 * @param enmClock The clock to use on this timer.
1246 * @param pfnCallback Callback function.
1247 * @param pszDesc Pointer to description string which must stay around
1248 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1249 * @param ppTimer Where to store the timer on success.
1250 */
1251VMMR3DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1252{
1253 /*
1254 * Allocate and init stuff.
1255 */
1256 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1257 if (RT_SUCCESS(rc))
1258 {
1259 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1260 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1261 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1262 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1263 }
1264
1265 return rc;
1266}
1267
1268
1269/**
1270 * Creates an internal timer.
1271 *
1272 * @returns VBox status.
1273 * @param pVM The VM to create the timer in.
1274 * @param enmClock The clock to use on this timer.
1275 * @param pfnCallback Callback function.
1276 * @param pvUser User argument to be passed to the callback.
1277 * @param pszDesc Pointer to description string which must stay around
1278 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1279 * @param ppTimer Where to store the timer on success.
1280 */
1281VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1282{
1283 /*
1284 * Allocate and init stuff.
1285 */
1286 PTMTIMER pTimer;
1287 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1288 if (RT_SUCCESS(rc))
1289 {
1290 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1291 pTimer->u.Internal.pfnTimer = pfnCallback;
1292 pTimer->u.Internal.pvUser = pvUser;
1293 *ppTimer = pTimer;
1294 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1295 }
1296
1297 return rc;
1298}
1299
1300/**
1301 * Creates an external timer.
1302 *
1303 * @returns Timer handle on success.
1304 * @returns NULL on failure.
1305 * @param pVM The VM to create the timer in.
1306 * @param enmClock The clock to use on this timer.
1307 * @param pfnCallback Callback function.
1308 * @param pvUser User argument.
1309 * @param pszDesc Pointer to description string which must stay around
1310 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1311 */
1312VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1313{
1314 /*
1315 * Allocate and init stuff.
1316 */
1317 PTMTIMERR3 pTimer;
1318 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1319 if (RT_SUCCESS(rc))
1320 {
1321 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1322 pTimer->u.External.pfnTimer = pfnCallback;
1323 pTimer->u.External.pvUser = pvUser;
1324 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1325 return pTimer;
1326 }
1327
1328 return NULL;
1329}
1330
1331
1332/**
1333 * Destroy all timers owned by a device.
1334 *
1335 * @returns VBox status.
1336 * @param pVM VM handle.
1337 * @param pDevIns Device which timers should be destroyed.
1338 */
1339VMMR3DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1340{
1341 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1342 if (!pDevIns)
1343 return VERR_INVALID_PARAMETER;
1344
1345 tmLock(pVM);
1346 PTMTIMER pCur = pVM->tm.s.pCreated;
1347 while (pCur)
1348 {
1349 PTMTIMER pDestroy = pCur;
1350 pCur = pDestroy->pBigNext;
1351 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1352 && pDestroy->u.Dev.pDevIns == pDevIns)
1353 {
1354 int rc = TMR3TimerDestroy(pDestroy);
1355 AssertRC(rc);
1356 }
1357 }
1358 tmUnlock(pVM);
1359
1360 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1361 return VINF_SUCCESS;
1362}
1363
1364
1365/**
1366 * Destroy all timers owned by a driver.
1367 *
1368 * @returns VBox status.
1369 * @param pVM VM handle.
1370 * @param pDrvIns Driver which timers should be destroyed.
1371 */
1372VMMR3DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1373{
1374 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1375 if (!pDrvIns)
1376 return VERR_INVALID_PARAMETER;
1377
1378 tmLock(pVM);
1379 PTMTIMER pCur = pVM->tm.s.pCreated;
1380 while (pCur)
1381 {
1382 PTMTIMER pDestroy = pCur;
1383 pCur = pDestroy->pBigNext;
1384 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1385 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1386 {
1387 int rc = TMR3TimerDestroy(pDestroy);
1388 AssertRC(rc);
1389 }
1390 }
1391 tmUnlock(pVM);
1392
1393 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1394 return VINF_SUCCESS;
1395}
1396
1397
1398/**
1399 * Internal function for getting the clock time.
1400 *
1401 * @returns clock time.
1402 * @param pVM The VM handle.
1403 * @param enmClock The clock.
1404 */
1405DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
1406{
1407 switch (enmClock)
1408 {
1409 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
1410 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
1411 case TMCLOCK_REAL: return TMRealGet(pVM);
1412 case TMCLOCK_TSC: return TMCpuTickGet(&pVM->aCpus[0] /* just take VCPU 0 */);
1413 default:
1414 AssertMsgFailed(("enmClock=%d\n", enmClock));
1415 return ~(uint64_t)0;
1416 }
1417}
1418
1419
1420/**
1421 * Checks if the sync queue has one or more expired timers.
1422 *
1423 * @returns true / false.
1424 *
1425 * @param pVM The VM handle.
1426 * @param enmClock The queue.
1427 */
1428DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1429{
1430 const uint64_t u64Expire = pVM->tm.s.CTX_SUFF(paTimerQueues)[enmClock].u64Expire;
1431 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1432}
1433
1434
1435/**
1436 * Checks for expired timers in all the queues.
1437 *
1438 * @returns true / false.
1439 * @param pVM The VM handle.
1440 */
1441DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1442{
1443 /*
1444 * Combine the time calculation for the first two since we're not on EMT
1445 * TMVirtualSyncGet only permits EMT.
1446 */
1447 uint64_t u64Now = TMVirtualGet(pVM);
1448 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1449 return true;
1450 u64Now = pVM->tm.s.fVirtualSyncTicking
1451 ? u64Now - pVM->tm.s.offVirtualSync
1452 : pVM->tm.s.u64VirtualSync;
1453 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1454 return true;
1455
1456 /*
1457 * The remaining timers.
1458 */
1459 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1460 return true;
1461 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1462 return true;
1463 return false;
1464}
1465
1466
1467/**
1468 * Schedulation timer callback.
1469 *
1470 * @param pTimer Timer handle.
1471 * @param pvUser VM handle.
1472 * @thread Timer thread.
1473 *
1474 * @remark We cannot do the scheduling and queues running from a timer handler
1475 * since it's not executing in EMT, and even if it was it would be async
1476 * and we wouldn't know the state of the affairs.
1477 * So, we'll just raise the timer FF and force any REM execution to exit.
1478 */
1479static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1480{
1481 PVM pVM = (PVM)pvUser;
1482 AssertCompile(TMCLOCK_MAX == 4);
1483#ifdef DEBUG_Sander /* very annoying, keep it private. */
1484 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
1485 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1486#endif
1487 if ( !VM_FF_ISSET(pVM, VM_FF_TIMER)
1488 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule
1489 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1490 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1491 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1492 || tmR3AnyExpiredTimers(pVM)
1493 )
1494 && !VM_FF_ISSET(pVM, VM_FF_TIMER)
1495 && !pVM->tm.s.fRunningQueues
1496 )
1497 {
1498 VM_FF_SET(pVM, VM_FF_TIMER);
1499 REMR3NotifyTimerPending(pVM);
1500 VMR3NotifyGlobalFFU(pVM->pUVM, VMNOTIFYFF_FLAGS_DONE_REM);
1501 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1502 }
1503}
1504
1505
1506/**
1507 * Schedules and runs any pending timers.
1508 *
1509 * This is normally called from a forced action handler in EMT.
1510 *
1511 * @param pVM The VM to run the timers for.
1512 *
1513 * @thread EMT (actually EMT0, but we fend off the others)
1514 */
1515VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1516{
1517 /*
1518 * Only one EMT should be doing this at a time.
1519 */
1520 VM_FF_CLEAR(pVM, VM_FF_TIMER);
1521 if (ASMBitTestAndSet(&pVM->tm.s.fRunningQueues, 0))
1522 {
1523 Assert(pVM->cCPUs > 1);
1524 return;
1525 }
1526
1527 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1528 Log2(("TMR3TimerQueuesDo:\n"));
1529 tmLock(pVM);
1530
1531 /*
1532 * Process the queues.
1533 */
1534 AssertCompile(TMCLOCK_MAX == 4);
1535
1536 /* TMCLOCK_VIRTUAL_SYNC */
1537 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesSchedule, s1);
1538 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
1539 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s1);
1540 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesRun, r1);
1541 tmR3TimerQueueRunVirtualSync(pVM);
1542 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r1);
1543
1544 /* TMCLOCK_VIRTUAL */
1545 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s1);
1546 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1547 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s2);
1548 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r1);
1549 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1550 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r2);
1551
1552#if 0 /** @todo if ever used, remove this and fix the stam prefixes on TMCLOCK_REAL below. */
1553 /* TMCLOCK_TSC */
1554 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1555 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1556 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s3);
1557 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1558 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1559 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r3);
1560#endif
1561
1562 /* TMCLOCK_REAL */
1563 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1564 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1565 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesSchedule, s3);
1566 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1567 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1568 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesRun, r3);
1569
1570#ifdef VBOX_STRICT
1571 /* check that we didn't screwup. */
1572 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1573#endif
1574
1575 Log2(("TMR3TimerQueuesDo: returns void\n"));
1576 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1577
1578 /* done */
1579 ASMAtomicBitClear(&pVM->tm.s.fRunningQueues, 0);
1580 tmUnlock(pVM);
1581}
1582
1583
1584/**
1585 * Schedules and runs any pending times in the specified queue.
1586 *
1587 * This is normally called from a forced action handler in EMT.
1588 *
1589 * @param pVM The VM to run the timers for.
1590 * @param pQueue The queue to run.
1591 */
1592static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1593{
1594 VM_ASSERT_EMT(pVM);
1595
1596 /*
1597 * Run timers.
1598 *
1599 * We check the clock once and run all timers which are ACTIVE
1600 * and have an expire time less or equal to the time we read.
1601 *
1602 * N.B. A generic unlink must be applied since other threads
1603 * are allowed to mess with any active timer at any time.
1604 * However, we only allow EMT to handle EXPIRED_PENDING
1605 * timers, thus enabling the timer handler function to
1606 * arm the timer again.
1607 */
1608 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1609 if (!pNext)
1610 return;
1611 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1612 while (pNext && pNext->u64Expire <= u64Now)
1613 {
1614 PTMTIMER pTimer = pNext;
1615 pNext = TMTIMER_GET_NEXT(pTimer);
1616 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1617 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1618 bool fRc;
1619 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1620 if (fRc)
1621 {
1622 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1623
1624 /* unlink */
1625 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1626 if (pPrev)
1627 TMTIMER_SET_NEXT(pPrev, pNext);
1628 else
1629 {
1630 TMTIMER_SET_HEAD(pQueue, pNext);
1631 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1632 }
1633 if (pNext)
1634 TMTIMER_SET_PREV(pNext, pPrev);
1635 pTimer->offNext = 0;
1636 pTimer->offPrev = 0;
1637
1638
1639 /* fire */
1640 switch (pTimer->enmType)
1641 {
1642 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1643 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1644 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1645 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1646 default:
1647 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1648 break;
1649 }
1650
1651 /* change the state if it wasn't changed already in the handler. */
1652 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1653 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1654 }
1655 } /* run loop */
1656}
1657
1658
1659/**
1660 * Schedules and runs any pending times in the timer queue for the
1661 * synchronous virtual clock.
1662 *
1663 * This scheduling is a bit different from the other queues as it need
1664 * to implement the special requirements of the timer synchronous virtual
1665 * clock, thus this 2nd queue run funcion.
1666 *
1667 * @param pVM The VM to run the timers for.
1668 */
1669static void tmR3TimerQueueRunVirtualSync(PVM pVM)
1670{
1671 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
1672 VM_ASSERT_EMT(pVM);
1673
1674 /*
1675 * Any timers?
1676 */
1677 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1678 if (RT_UNLIKELY(!pNext))
1679 {
1680 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.cVirtualTicking);
1681 return;
1682 }
1683 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
1684
1685 /*
1686 * Calculate the time frame for which we will dispatch timers.
1687 *
1688 * We use a time frame ranging from the current sync time (which is most likely the
1689 * same as the head timer) and some configurable period (100000ns) up towards the
1690 * current virtual time. This period might also need to be restricted by the catch-up
1691 * rate so frequent calls to this function won't accelerate the time too much, however
1692 * this will be implemented at a later point if neccessary.
1693 *
1694 * Without this frame we would 1) having to run timers much more frequently
1695 * and 2) lag behind at a steady rate.
1696 */
1697 const uint64_t u64VirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
1698 uint64_t u64Now;
1699 if (!pVM->tm.s.fVirtualSyncTicking)
1700 {
1701 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
1702 u64Now = pVM->tm.s.u64VirtualSync;
1703 Assert(u64Now <= pNext->u64Expire);
1704 }
1705 else
1706 {
1707 /* Calc 'now'. (update order doesn't really matter here) */
1708 uint64_t off = pVM->tm.s.offVirtualSync;
1709 if (pVM->tm.s.fVirtualSyncCatchUp)
1710 {
1711 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
1712 if (RT_LIKELY(!(u64Delta >> 32)))
1713 {
1714 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
1715 if (off > u64Sub + pVM->tm.s.offVirtualSyncGivenUp)
1716 {
1717 off -= u64Sub;
1718 Log4(("TM: %RU64/%RU64: sub %RU64 (run)\n", u64VirtualNow - off, off - pVM->tm.s.offVirtualSyncGivenUp, u64Sub));
1719 }
1720 else
1721 {
1722 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1723 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1724 off = pVM->tm.s.offVirtualSyncGivenUp;
1725 Log4(("TM: %RU64/0: caught up (run)\n", u64VirtualNow));
1726 }
1727 }
1728 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, off);
1729 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow;
1730 }
1731 u64Now = u64VirtualNow - off;
1732
1733 /* Check if stopped by expired timer. */
1734 if (u64Now >= pNext->u64Expire)
1735 {
1736 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
1737 u64Now = pNext->u64Expire;
1738 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, u64Now);
1739 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, false);
1740 Log4(("TM: %RU64/%RU64: exp tmr (run)\n", u64Now, u64VirtualNow - u64Now - pVM->tm.s.offVirtualSyncGivenUp));
1741
1742 }
1743 }
1744
1745 /* calc end of frame. */
1746 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
1747 if (u64Max > u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp)
1748 u64Max = u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp;
1749
1750 /* assert sanity */
1751 Assert(u64Now <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1752 Assert(u64Max <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1753 Assert(u64Now <= u64Max);
1754
1755 /*
1756 * Process the expired timers moving the clock along as we progress.
1757 */
1758#ifdef VBOX_STRICT
1759 uint64_t u64Prev = u64Now; NOREF(u64Prev);
1760#endif
1761 while (pNext && pNext->u64Expire <= u64Max)
1762 {
1763 PTMTIMER pTimer = pNext;
1764 pNext = TMTIMER_GET_NEXT(pTimer);
1765 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1766 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1767 bool fRc;
1768 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1769 if (fRc)
1770 {
1771 /* unlink */
1772 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1773 if (pPrev)
1774 TMTIMER_SET_NEXT(pPrev, pNext);
1775 else
1776 {
1777 TMTIMER_SET_HEAD(pQueue, pNext);
1778 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1779 }
1780 if (pNext)
1781 TMTIMER_SET_PREV(pNext, pPrev);
1782 pTimer->offNext = 0;
1783 pTimer->offPrev = 0;
1784
1785 /* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
1786#ifdef VBOX_STRICT
1787 AssertMsg(pTimer->u64Expire >= u64Prev, ("%RU64 < %RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
1788 u64Prev = pTimer->u64Expire;
1789#endif
1790 ASMAtomicXchgSize(&pVM->tm.s.fVirtualSyncTicking, false);
1791 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
1792
1793 /* fire */
1794 switch (pTimer->enmType)
1795 {
1796 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1797 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1798 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1799 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1800 default:
1801 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1802 break;
1803 }
1804
1805 /* change the state if it wasn't changed already in the handler. */
1806 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1807 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1808 }
1809 } /* run loop */
1810
1811 /*
1812 * Restart the clock if it was stopped to serve any timers,
1813 * and start/adjust catch-up if necessary.
1814 */
1815 if ( !pVM->tm.s.fVirtualSyncTicking
1816 && pVM->tm.s.cVirtualTicking)
1817 {
1818 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
1819
1820 /* calc the slack we've handed out. */
1821 const uint64_t u64VirtualNow2 = TMVirtualGetEx(pVM, false /* don't check timers */);
1822 Assert(u64VirtualNow2 >= u64VirtualNow);
1823 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%RU64 < %RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
1824 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
1825 STAM_STATS({
1826 if (offSlack)
1827 {
1828 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
1829 p->cPeriods++;
1830 p->cTicks += offSlack;
1831 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
1832 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
1833 }
1834 });
1835
1836 /* Let the time run a little bit while we were busy running timers(?). */
1837 uint64_t u64Elapsed;
1838#define MAX_ELAPSED 30000 /* ns */
1839 if (offSlack > MAX_ELAPSED)
1840 u64Elapsed = 0;
1841 else
1842 {
1843 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
1844 if (u64Elapsed > MAX_ELAPSED)
1845 u64Elapsed = MAX_ELAPSED;
1846 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
1847 }
1848#undef MAX_ELAPSED
1849
1850 /* Calc the current offset. */
1851 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
1852 Assert(!(offNew & RT_BIT_64(63)));
1853 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
1854 Assert(!(offLag & RT_BIT_64(63)));
1855
1856 /*
1857 * Deal with starting, adjusting and stopping catchup.
1858 */
1859 if (pVM->tm.s.fVirtualSyncCatchUp)
1860 {
1861 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
1862 {
1863 /* stop */
1864 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1865 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1866 Log4(("TM: %RU64/%RU64: caught up\n", u64VirtualNow2 - offNew, offLag));
1867 }
1868 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1869 {
1870 /* adjust */
1871 unsigned i = 0;
1872 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1873 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1874 i++;
1875 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
1876 {
1877 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
1878 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1879 Log4(("TM: %RU64/%RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1880 }
1881 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
1882 }
1883 else
1884 {
1885 /* give up */
1886 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
1887 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1888 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1889 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1890 Log4(("TM: %RU64/%RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1891 LogRel(("TM: Giving up catch-up attempt at a %RU64 ns lag; new total: %RU64 ns\n", offLag, offNew));
1892 }
1893 }
1894 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
1895 {
1896 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1897 {
1898 /* start */
1899 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
1900 unsigned i = 0;
1901 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1902 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1903 i++;
1904 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
1905 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1906 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
1907 Log4(("TM: %RU64/%RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1908 }
1909 else
1910 {
1911 /* don't bother */
1912 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
1913 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1914 Log4(("TM: %RU64/%RU64: give up\n", u64VirtualNow2 - offNew, offLag));
1915 LogRel(("TM: Not bothering to attempt catching up a %RU64 ns lag; new total: %RU64\n", offLag, offNew));
1916 }
1917 }
1918
1919 /*
1920 * Update the offset and restart the clock.
1921 */
1922 Assert(!(offNew & RT_BIT_64(63)));
1923 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, offNew);
1924 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, true);
1925 }
1926}
1927
1928
1929/**
1930 * Saves the state of a timer to a saved state.
1931 *
1932 * @returns VBox status.
1933 * @param pTimer Timer to save.
1934 * @param pSSM Save State Manager handle.
1935 */
1936VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1937{
1938 LogFlow(("TMR3TimerSave: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1939 switch (pTimer->enmState)
1940 {
1941 case TMTIMERSTATE_STOPPED:
1942 case TMTIMERSTATE_PENDING_STOP:
1943 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1944 return SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_STOP);
1945
1946 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1947 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1948 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
1949 if (!RTThreadYield())
1950 RTThreadSleep(1);
1951 /* fall thru */
1952 case TMTIMERSTATE_ACTIVE:
1953 case TMTIMERSTATE_PENDING_SCHEDULE:
1954 case TMTIMERSTATE_PENDING_RESCHEDULE:
1955 SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_SCHEDULE);
1956 return SSMR3PutU64(pSSM, pTimer->u64Expire);
1957
1958 case TMTIMERSTATE_EXPIRED:
1959 case TMTIMERSTATE_PENDING_DESTROY:
1960 case TMTIMERSTATE_PENDING_STOP_DESTROY:
1961 case TMTIMERSTATE_FREE:
1962 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
1963 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
1964 }
1965
1966 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
1967 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
1968}
1969
1970
1971/**
1972 * Loads the state of a timer from a saved state.
1973 *
1974 * @returns VBox status.
1975 * @param pTimer Timer to restore.
1976 * @param pSSM Save State Manager handle.
1977 */
1978VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1979{
1980 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
1981 LogFlow(("TMR3TimerLoad: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1982
1983 /*
1984 * Load the state and validate it.
1985 */
1986 uint8_t u8State;
1987 int rc = SSMR3GetU8(pSSM, &u8State);
1988 if (RT_FAILURE(rc))
1989 return rc;
1990 TMTIMERSTATE enmState = (TMTIMERSTATE)u8State;
1991 if ( enmState != TMTIMERSTATE_PENDING_STOP
1992 && enmState != TMTIMERSTATE_PENDING_SCHEDULE
1993 && enmState != TMTIMERSTATE_PENDING_STOP_SCHEDULE)
1994 {
1995 AssertMsgFailed(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1996 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
1997 }
1998
1999 if (enmState == TMTIMERSTATE_PENDING_SCHEDULE)
2000 {
2001 /*
2002 * Load the expire time.
2003 */
2004 uint64_t u64Expire;
2005 rc = SSMR3GetU64(pSSM, &u64Expire);
2006 if (RT_FAILURE(rc))
2007 return rc;
2008
2009 /*
2010 * Set it.
2011 */
2012 Log(("enmState=%d %s u64Expire=%llu\n", enmState, tmTimerState(enmState), u64Expire));
2013 rc = TMTimerSet(pTimer, u64Expire);
2014 }
2015 else
2016 {
2017 /*
2018 * Stop it.
2019 */
2020 Log(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
2021 rc = TMTimerStop(pTimer);
2022 }
2023
2024 /*
2025 * On failure set SSM status.
2026 */
2027 if (RT_FAILURE(rc))
2028 rc = SSMR3HandleSetStatus(pSSM, rc);
2029 return rc;
2030}
2031
2032
2033/**
2034 * Get the real world UTC time adjusted for VM lag.
2035 *
2036 * @returns pTime.
2037 * @param pVM The VM instance.
2038 * @param pTime Where to store the time.
2039 */
2040VMMR3DECL(PRTTIMESPEC) TMR3UTCNow(PVM pVM, PRTTIMESPEC pTime)
2041{
2042 RTTimeNow(pTime);
2043 RTTimeSpecSubNano(pTime, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp);
2044 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
2045 return pTime;
2046}
2047
2048
2049/**
2050 * Sets the warp drive percent of the virtual time.
2051 *
2052 * @returns VBox status code.
2053 * @param pVM The VM handle.
2054 * @param u32Percent The new percentage. 100 means normal operation.
2055 *
2056 * @todo Move to Ring-3!
2057 */
2058VMMDECL(int) TMR3SetWarpDrive(PVM pVM, uint32_t u32Percent)
2059{
2060 PVMREQ pReq;
2061 int rc = VMR3ReqCall(pVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT,
2062 (PFNRT)tmR3SetWarpDrive, 2, pVM, u32Percent);
2063 if (RT_SUCCESS(rc))
2064 rc = pReq->iStatus;
2065 VMR3ReqFree(pReq);
2066 return rc;
2067}
2068
2069
2070/**
2071 * EMT worker for TMR3SetWarpDrive.
2072 *
2073 * @returns VBox status code.
2074 * @param pVM The VM handle.
2075 * @param u32Percent See TMR3SetWarpDrive().
2076 * @internal
2077 */
2078static DECLCALLBACK(int) tmR3SetWarpDrive(PVM pVM, uint32_t u32Percent)
2079{
2080 PVMCPU pVCpu = VMMGetCpu(pVM);
2081
2082 /*
2083 * Validate it.
2084 */
2085 AssertMsgReturn(u32Percent >= 2 && u32Percent <= 20000,
2086 ("%RX32 is not between 2 and 20000 (inclusive).\n", u32Percent),
2087 VERR_INVALID_PARAMETER);
2088 tmLock(pVM); /* paranoia */
2089
2090/** @todo This isn't a feature specific to virtual time, move the variables to
2091 * TM level and make it affect TMR3UCTNow as well! */
2092
2093 /*
2094 * If the time is running we'll have to pause it before we can change
2095 * the warp drive settings.
2096 */
2097 bool fPaused = !!pVM->tm.s.cVirtualTicking;
2098 if (fPaused)
2099 {
2100 int rc = TMVirtualPause(pVM);
2101 AssertRC(rc);
2102 rc = TMCpuTickPause(pVCpu);
2103 AssertRC(rc);
2104 }
2105
2106 pVM->tm.s.u32VirtualWarpDrivePercentage = u32Percent;
2107 pVM->tm.s.fVirtualWarpDrive = u32Percent != 100;
2108 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32 fVirtualWarpDrive=%RTbool\n",
2109 pVM->tm.s.u32VirtualWarpDrivePercentage, pVM->tm.s.fVirtualWarpDrive));
2110
2111 if (fPaused)
2112 {
2113 int rc = TMVirtualResume(pVM);
2114 AssertRC(rc);
2115 rc = TMCpuTickResume(pVCpu);
2116 AssertRC(rc);
2117 }
2118
2119 tmUnlock(pVM);
2120 return VINF_SUCCESS;
2121}
2122
2123
2124
2125
2126/**
2127 * Display all timers.
2128 *
2129 * @param pVM VM Handle.
2130 * @param pHlp The info helpers.
2131 * @param pszArgs Arguments, ignored.
2132 */
2133static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2134{
2135 NOREF(pszArgs);
2136 pHlp->pfnPrintf(pHlp,
2137 "Timers (pVM=%p)\n"
2138 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
2139 pVM,
2140 sizeof(RTR3PTR) * 2, "pTimerR3 ",
2141 sizeof(int32_t) * 2, "offNext ",
2142 sizeof(int32_t) * 2, "offPrev ",
2143 sizeof(int32_t) * 2, "offSched ",
2144 "Time",
2145 "Expire",
2146 "State");
2147 tmLock(pVM);
2148 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
2149 {
2150 pHlp->pfnPrintf(pHlp,
2151 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
2152 pTimer,
2153 pTimer->offNext,
2154 pTimer->offPrev,
2155 pTimer->offScheduleNext,
2156 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
2157 TMTimerGet(pTimer),
2158 pTimer->u64Expire,
2159 tmTimerState(pTimer->enmState),
2160 pTimer->pszDesc);
2161 }
2162 tmUnlock(pVM);
2163}
2164
2165
2166/**
2167 * Display all active timers.
2168 *
2169 * @param pVM VM Handle.
2170 * @param pHlp The info helpers.
2171 * @param pszArgs Arguments, ignored.
2172 */
2173static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2174{
2175 NOREF(pszArgs);
2176 pHlp->pfnPrintf(pHlp,
2177 "Active Timers (pVM=%p)\n"
2178 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
2179 pVM,
2180 sizeof(RTR3PTR) * 2, "pTimerR3 ",
2181 sizeof(int32_t) * 2, "offNext ",
2182 sizeof(int32_t) * 2, "offPrev ",
2183 sizeof(int32_t) * 2, "offSched ",
2184 "Time",
2185 "Expire",
2186 "State");
2187 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
2188 {
2189 tmLock(pVM);
2190 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
2191 pTimer;
2192 pTimer = TMTIMER_GET_NEXT(pTimer))
2193 {
2194 pHlp->pfnPrintf(pHlp,
2195 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
2196 pTimer,
2197 pTimer->offNext,
2198 pTimer->offPrev,
2199 pTimer->offScheduleNext,
2200 pTimer->enmClock == TMCLOCK_REAL
2201 ? "Real "
2202 : pTimer->enmClock == TMCLOCK_VIRTUAL
2203 ? "Virt "
2204 : pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC
2205 ? "VrSy "
2206 : "TSC ",
2207 TMTimerGet(pTimer),
2208 pTimer->u64Expire,
2209 tmTimerState(pTimer->enmState),
2210 pTimer->pszDesc);
2211 }
2212 tmUnlock(pVM);
2213 }
2214}
2215
2216
2217/**
2218 * Display all clocks.
2219 *
2220 * @param pVM VM Handle.
2221 * @param pHlp The info helpers.
2222 * @param pszArgs Arguments, ignored.
2223 */
2224static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2225{
2226 NOREF(pszArgs);
2227
2228 /*
2229 * Read the times first to avoid more than necessary time variation.
2230 */
2231 const uint64_t u64Virtual = TMVirtualGet(pVM);
2232 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
2233 const uint64_t u64Real = TMRealGet(pVM);
2234
2235 for (unsigned i = 0; i < pVM->cCPUs; i++)
2236 {
2237 PVMCPU pVCpu = &pVM->aCpus[i];
2238 uint64_t u64TSC = TMCpuTickGet(pVCpu);
2239
2240 /*
2241 * TSC
2242 */
2243 pHlp->pfnPrintf(pHlp,
2244 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
2245 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
2246 pVCpu->tm.s.fTSCTicking ? "ticking" : "paused",
2247 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
2248 if (pVM->tm.s.fTSCUseRealTSC)
2249 {
2250 pHlp->pfnPrintf(pHlp, " - real tsc");
2251 if (pVCpu->tm.s.u64TSCOffset)
2252 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVCpu->tm.s.u64TSCOffset);
2253 }
2254 else
2255 pHlp->pfnPrintf(pHlp, " - virtual clock");
2256 pHlp->pfnPrintf(pHlp, "\n");
2257 }
2258
2259 /*
2260 * virtual
2261 */
2262 pHlp->pfnPrintf(pHlp,
2263 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
2264 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
2265 pVM->tm.s.cVirtualTicking ? "ticking" : "paused");
2266 if (pVM->tm.s.fVirtualWarpDrive)
2267 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
2268 pHlp->pfnPrintf(pHlp, "\n");
2269
2270 /*
2271 * virtual sync
2272 */
2273 pHlp->pfnPrintf(pHlp,
2274 "VirtSync: %18RU64 (%#016RX64) %s%s",
2275 u64VirtualSync, u64VirtualSync,
2276 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
2277 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
2278 if (pVM->tm.s.offVirtualSync)
2279 {
2280 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
2281 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
2282 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
2283 }
2284 pHlp->pfnPrintf(pHlp, "\n");
2285
2286 /*
2287 * real
2288 */
2289 pHlp->pfnPrintf(pHlp,
2290 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
2291 u64Real, u64Real, TMRealGetFreq(pVM));
2292}
2293
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