VirtualBox

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

Last change on this file since 21567 was 21527, checked in by vboxsync, 15 years ago

Got rid of obsolete rdtsc restriction with SMP guests.

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