VirtualBox

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

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

oops.

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