VirtualBox

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

Last change on this file since 20680 was 20678, checked in by vboxsync, 16 years ago

TM: Count calls to TMCpuTickSet and take the VM handle as an argument.

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

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