VirtualBox

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

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

Temporarily restrict servicing timer queues to VCPU 0

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