VirtualBox

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

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

TMCPU::u64TSCOffset -> offTSCRawSrc

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

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