VirtualBox

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

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

TM: fixed incorrect use of ASMBitTestAndSet in TMR3TimerQueuesDo that could result in the queues only being run on every 2nd call.

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

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