VirtualBox

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

Last change on this file since 13762 was 13633, checked in by vboxsync, 16 years ago

#1865: TM.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use