VirtualBox

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

Last change on this file since 28800 was 28800, checked in by vboxsync, 14 years ago

Automated rebranding to Oracle copyright/license strings via filemuncher

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

© 2023 Oracle
ContactPrivacy policyTerms of Use