VirtualBox

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

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

PDM,IOM,TM: Added an optional per-device critsect for avoiding the global IOM lock. Only port I/O and timer callbacks use it, cannot yet be used with MMIO callbacks (will assert and fail).

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

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