VirtualBox

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

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

Per VCPU init/term.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 90.6 KB
Line 
1/* $Id: TM.cpp 13778 2008-11-04 09:45:27Z 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 * Initializes the per-VCPU TM.
605 *
606 * @returns VBox status code.
607 * @param pVM The VM to operate on.
608 */
609VMMR3DECL(int) TMR3InitCPU(PVM pVM)
610{
611 LogFlow(("TMR3InitCPU\n"));
612 return VINF_SUCCESS;
613}
614
615/**
616 * Checks if the host CPU has a fixed TSC frequency.
617 *
618 * @returns true if it has, false if it hasn't.
619 *
620 * @remark This test doesn't bother with very old CPUs that don't do power
621 * management or any other stuff that might influence the TSC rate.
622 * This isn't currently relevant.
623 */
624static bool tmR3HasFixedTSC(PVM pVM)
625{
626 if (ASMHasCpuId())
627 {
628 uint32_t uEAX, uEBX, uECX, uEDX;
629
630 if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_AMD)
631 {
632 /*
633 * AuthenticAMD - Check for APM support and that TscInvariant is set.
634 *
635 * This test isn't correct with respect to fixed/non-fixed TSC and
636 * older models, but this isn't relevant since the result is currently
637 * only used for making a descision on AMD-V models.
638 */
639 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
640 if (uEAX >= 0x80000007)
641 {
642 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
643
644 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
645 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
646 && pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* no fixed tsc if the gip timer is in async mode */)
647 return true;
648 }
649 }
650 else if (CPUMGetCPUVendor(pVM) == CPUMCPUVENDOR_INTEL)
651 {
652 /*
653 * GenuineIntel - Check the model number.
654 *
655 * This test is lacking in the same way and for the same reasons
656 * as the AMD test above.
657 */
658 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
659 unsigned uModel = (uEAX >> 4) & 0x0f;
660 unsigned uFamily = (uEAX >> 8) & 0x0f;
661 if (uFamily == 0x0f)
662 uFamily += (uEAX >> 20) & 0xff;
663 if (uFamily >= 0x06)
664 uModel += ((uEAX >> 16) & 0x0f) << 4;
665 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
666 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
667 return true;
668 }
669 }
670 return false;
671}
672
673
674/**
675 * Calibrate the CPU tick.
676 *
677 * @returns Number of ticks per second.
678 */
679static uint64_t tmR3CalibrateTSC(PVM pVM)
680{
681 /*
682 * Use GIP when available present.
683 */
684 uint64_t u64Hz;
685 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
686 if ( pGip
687 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC)
688 {
689 unsigned iCpu = pGip->u32Mode != SUPGIPMODE_ASYNC_TSC ? 0 : ASMGetApicId();
690 if (iCpu >= RT_ELEMENTS(pGip->aCPUs))
691 AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
692 else
693 {
694 if (tmR3HasFixedTSC(pVM))
695 /* Sleep a bit to get a more reliable CpuHz value. */
696 RTThreadSleep(32);
697 else
698 {
699 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
700 const uint64_t u64 = RTTimeMilliTS();
701 while ((RTTimeMilliTS() - u64) < 40 /*ms*/)
702 /* nothing */;
703 }
704
705 pGip = g_pSUPGlobalInfoPage;
706 if ( pGip
707 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC
708 && (u64Hz = pGip->aCPUs[iCpu].u64CpuHz)
709 && u64Hz != ~(uint64_t)0)
710 return u64Hz;
711 }
712 }
713
714 /* call this once first to make sure it's initialized. */
715 RTTimeNanoTS();
716
717 /*
718 * Yield the CPU to increase our chances of getting
719 * a correct value.
720 */
721 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
722 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
723 uint64_t au64Samples[5];
724 unsigned i;
725 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
726 {
727 unsigned cMillies;
728 int cTries = 5;
729 uint64_t u64Start = ASMReadTSC();
730 uint64_t u64End;
731 uint64_t StartTS = RTTimeNanoTS();
732 uint64_t EndTS;
733 do
734 {
735 RTThreadSleep(s_auSleep[i]);
736 u64End = ASMReadTSC();
737 EndTS = RTTimeNanoTS();
738 cMillies = (unsigned)((EndTS - StartTS + 500000) / 1000000);
739 } while ( cMillies == 0 /* the sleep may be interrupted... */
740 || (cMillies < 20 && --cTries > 0));
741 uint64_t u64Diff = u64End - u64Start;
742
743 au64Samples[i] = (u64Diff * 1000) / cMillies;
744 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
745 }
746
747 /*
748 * Discard the highest and lowest results and calculate the average.
749 */
750 unsigned iHigh = 0;
751 unsigned iLow = 0;
752 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
753 {
754 if (au64Samples[i] < au64Samples[iLow])
755 iLow = i;
756 if (au64Samples[i] > au64Samples[iHigh])
757 iHigh = i;
758 }
759 au64Samples[iLow] = 0;
760 au64Samples[iHigh] = 0;
761
762 u64Hz = au64Samples[0];
763 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
764 u64Hz += au64Samples[i];
765 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
766
767 return u64Hz;
768}
769
770
771/**
772 * Finalizes the TM initialization.
773 *
774 * @returns VBox status code.
775 * @param pVM The VM to operate on.
776 */
777VMMR3DECL(int) TMR3InitFinalize(PVM pVM)
778{
779 int rc;
780
781 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
782 AssertRCReturn(rc, rc);
783 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
784 AssertRCReturn(rc, rc);
785 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
786 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
787 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
788 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
789 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
790 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
791 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
792 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
793 else
794 AssertFatalFailed();
795 AssertRCReturn(rc, rc);
796
797 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
798 AssertRCReturn(rc, rc);
799 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
800 AssertRCReturn(rc, rc);
801 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
802 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawR0);
803 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
804 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawR0);
805 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
806 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawR0);
807 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
808 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawR0);
809 else
810 AssertFatalFailed();
811 AssertRCReturn(rc, rc);
812
813 return VINF_SUCCESS;
814}
815
816
817/**
818 * Applies relocations to data and code managed by this
819 * component. This function will be called at init and
820 * whenever the VMM need to relocate it self inside the GC.
821 *
822 * @param pVM The VM.
823 * @param offDelta Relocation delta relative to old location.
824 */
825VMMR3DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
826{
827 int rc;
828 LogFlow(("TMR3Relocate\n"));
829
830 pVM->tm.s.pvGIPRC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
831 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
832 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
833
834 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
835 AssertFatal(pVM->tm.s.VirtualGetRawDataRC.pu64Prev);
836 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
837 AssertFatalRC(rc);
838 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
839 AssertFatalRC(rc);
840
841 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
842 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
843 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
844 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
845 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
846 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
847 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
848 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
849 else
850 AssertFatalFailed();
851 AssertFatalRC(rc);
852
853 /*
854 * Iterate the timers updating the pVMGC pointers.
855 */
856 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
857 {
858 pTimer->pVMRC = pVM->pVMRC;
859 pTimer->pVMR0 = pVM->pVMR0;
860 }
861}
862
863
864/**
865 * Terminates the TM.
866 *
867 * Termination means cleaning up and freeing all resources,
868 * the VM it self is at this point powered off or suspended.
869 *
870 * @returns VBox status code.
871 * @param pVM The VM to operate on.
872 */
873VMMR3DECL(int) TMR3Term(PVM pVM)
874{
875 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
876 if (pVM->tm.s.pTimer)
877 {
878 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
879 AssertRC(rc);
880 pVM->tm.s.pTimer = NULL;
881 }
882
883 return VINF_SUCCESS;
884}
885
886/**
887 * Terminates the per-VCPU TM.
888 *
889 * Termination means cleaning up and freeing all resources,
890 * the VM it self is at this point powered off or suspended.
891 *
892 * @returns VBox status code.
893 * @param pVM The VM to operate on.
894 */
895VMMR3DECL(int) TMR3TermCPU(PVM pVM)
896{
897 return 0;
898}
899
900/**
901 * The VM is being reset.
902 *
903 * For the TM component this means that a rescheduling is preformed,
904 * the FF is cleared and but without running the queues. We'll have to
905 * check if this makes sense or not, but it seems like a good idea now....
906 *
907 * @param pVM VM handle.
908 */
909VMMR3DECL(void) TMR3Reset(PVM pVM)
910{
911 LogFlow(("TMR3Reset:\n"));
912 VM_ASSERT_EMT(pVM);
913
914 /*
915 * Abort any pending catch up.
916 * This isn't perfect,
917 */
918 if (pVM->tm.s.fVirtualSyncCatchUp)
919 {
920 const uint64_t offVirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
921 const uint64_t offVirtualSyncNow = TMVirtualSyncGetEx(pVM, false /* don't check timers */);
922 if (pVM->tm.s.fVirtualSyncCatchUp)
923 {
924 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
925
926 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
927 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
928 Assert(offOld <= offNew);
929 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
930 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
931 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
932 LogRel(("TM: Aborting catch-up attempt on reset with a %RU64 ns lag on reset; new total: %RU64 ns\n", offNew - offOld, offNew));
933 }
934 }
935
936 /*
937 * Process the queues.
938 */
939 for (int i = 0; i < TMCLOCK_MAX; i++)
940 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
941#ifdef VBOX_STRICT
942 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
943#endif
944 VM_FF_CLEAR(pVM, VM_FF_TIMER);
945}
946
947
948/**
949 * Resolve a builtin RC symbol.
950 * Called by PDM when loading or relocating GC modules.
951 *
952 * @returns VBox status
953 * @param pVM VM Handle.
954 * @param pszSymbol Symbol to resolve.
955 * @param pRCPtrValue Where to store the symbol value.
956 * @remark This has to work before TMR3Relocate() is called.
957 */
958VMMR3DECL(int) TMR3GetImportRC(PVM pVM, const char *pszSymbol, PRTRCPTR pRCPtrValue)
959{
960 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
961 *pRCPtrValue = MMHyperR3ToRC(pVM, &pVM->tm.s.pvGIPRC);
962 //else if (..)
963 else
964 return VERR_SYMBOL_NOT_FOUND;
965 return VINF_SUCCESS;
966}
967
968
969/**
970 * Execute state save operation.
971 *
972 * @returns VBox status code.
973 * @param pVM VM Handle.
974 * @param pSSM SSM operation handle.
975 */
976static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
977{
978 LogFlow(("tmR3Save:\n"));
979 Assert(!pVM->tm.s.fTSCTicking);
980 Assert(!pVM->tm.s.fVirtualTicking);
981 Assert(!pVM->tm.s.fVirtualSyncTicking);
982
983 /*
984 * Save the virtual clocks.
985 */
986 /* the virtual clock. */
987 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
988 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
989
990 /* the virtual timer synchronous clock. */
991 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
992 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
993 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
994 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
995 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
996
997 /* real time clock */
998 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
999
1000 /* the cpu tick clock. */
1001 SSMR3PutU64(pSSM, TMCpuTickGet(pVM));
1002 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
1003}
1004
1005
1006/**
1007 * Execute state load operation.
1008 *
1009 * @returns VBox status code.
1010 * @param pVM VM Handle.
1011 * @param pSSM SSM operation handle.
1012 * @param u32Version Data layout version.
1013 */
1014static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
1015{
1016 LogFlow(("tmR3Load:\n"));
1017 Assert(!pVM->tm.s.fTSCTicking);
1018 Assert(!pVM->tm.s.fVirtualTicking);
1019 Assert(!pVM->tm.s.fVirtualSyncTicking);
1020
1021 /*
1022 * Validate version.
1023 */
1024 if (u32Version != TM_SAVED_STATE_VERSION)
1025 {
1026 AssertMsgFailed(("tmR3Load: Invalid version u32Version=%d!\n", u32Version));
1027 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1028 }
1029
1030 /*
1031 * Load the virtual clock.
1032 */
1033 pVM->tm.s.fVirtualTicking = false;
1034 /* the virtual clock. */
1035 uint64_t u64Hz;
1036 int rc = SSMR3GetU64(pSSM, &u64Hz);
1037 if (VBOX_FAILURE(rc))
1038 return rc;
1039 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
1040 {
1041 AssertMsgFailed(("The virtual clock frequency differs! Saved: %RU64 Binary: %RU64\n",
1042 u64Hz, TMCLOCK_FREQ_VIRTUAL));
1043 return VERR_SSM_VIRTUAL_CLOCK_HZ;
1044 }
1045 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
1046 pVM->tm.s.u64VirtualOffset = 0;
1047
1048 /* the virtual timer synchronous clock. */
1049 pVM->tm.s.fVirtualSyncTicking = false;
1050 uint64_t u64;
1051 SSMR3GetU64(pSSM, &u64);
1052 pVM->tm.s.u64VirtualSync = u64;
1053 SSMR3GetU64(pSSM, &u64);
1054 pVM->tm.s.offVirtualSync = u64;
1055 SSMR3GetU64(pSSM, &u64);
1056 pVM->tm.s.offVirtualSyncGivenUp = u64;
1057 SSMR3GetU64(pSSM, &u64);
1058 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1059 bool f;
1060 SSMR3GetBool(pSSM, &f);
1061 pVM->tm.s.fVirtualSyncCatchUp = f;
1062
1063 /* the real clock */
1064 rc = SSMR3GetU64(pSSM, &u64Hz);
1065 if (VBOX_FAILURE(rc))
1066 return rc;
1067 if (u64Hz != TMCLOCK_FREQ_REAL)
1068 {
1069 AssertMsgFailed(("The real clock frequency differs! Saved: %RU64 Binary: %RU64\n",
1070 u64Hz, TMCLOCK_FREQ_REAL));
1071 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
1072 }
1073
1074 /* the cpu tick clock. */
1075 pVM->tm.s.fTSCTicking = false;
1076 SSMR3GetU64(pSSM, &pVM->tm.s.u64TSC);
1077 rc = SSMR3GetU64(pSSM, &u64Hz);
1078 if (VBOX_FAILURE(rc))
1079 return rc;
1080 if (pVM->tm.s.fTSCUseRealTSC)
1081 pVM->tm.s.u64TSCOffset = 0; /** @todo TSC restore stuff and HWACC. */
1082 else
1083 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1084 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1085 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1086
1087 /*
1088 * Make sure timers get rescheduled immediately.
1089 */
1090 VM_FF_SET(pVM, VM_FF_TIMER);
1091
1092 return VINF_SUCCESS;
1093}
1094
1095
1096/**
1097 * Internal TMR3TimerCreate worker.
1098 *
1099 * @returns VBox status code.
1100 * @param pVM The VM handle.
1101 * @param enmClock The timer clock.
1102 * @param pszDesc The timer description.
1103 * @param ppTimer Where to store the timer pointer on success.
1104 */
1105static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1106{
1107 VM_ASSERT_EMT(pVM);
1108
1109 /*
1110 * Allocate the timer.
1111 */
1112 PTMTIMERR3 pTimer = NULL;
1113 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1114 {
1115 pTimer = pVM->tm.s.pFree;
1116 pVM->tm.s.pFree = pTimer->pBigNext;
1117 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1118 }
1119
1120 if (!pTimer)
1121 {
1122 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1123 if (VBOX_FAILURE(rc))
1124 return rc;
1125 Log3(("TM: Allocated new timer %p\n", pTimer));
1126 }
1127
1128 /*
1129 * Initialize it.
1130 */
1131 pTimer->u64Expire = 0;
1132 pTimer->enmClock = enmClock;
1133 pTimer->pVMR3 = pVM;
1134 pTimer->pVMR0 = pVM->pVMR0;
1135 pTimer->pVMRC = pVM->pVMRC;
1136 pTimer->enmState = TMTIMERSTATE_STOPPED;
1137 pTimer->offScheduleNext = 0;
1138 pTimer->offNext = 0;
1139 pTimer->offPrev = 0;
1140 pTimer->pszDesc = pszDesc;
1141
1142 /* insert into the list of created timers. */
1143 pTimer->pBigPrev = NULL;
1144 pTimer->pBigNext = pVM->tm.s.pCreated;
1145 pVM->tm.s.pCreated = pTimer;
1146 if (pTimer->pBigNext)
1147 pTimer->pBigNext->pBigPrev = pTimer;
1148#ifdef VBOX_STRICT
1149 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1150#endif
1151
1152 *ppTimer = pTimer;
1153 return VINF_SUCCESS;
1154}
1155
1156
1157/**
1158 * Creates a device timer.
1159 *
1160 * @returns VBox status.
1161 * @param pVM The VM to create the timer in.
1162 * @param pDevIns Device instance.
1163 * @param enmClock The clock to use on this timer.
1164 * @param pfnCallback Callback function.
1165 * @param pszDesc Pointer to description string which must stay around
1166 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1167 * @param ppTimer Where to store the timer on success.
1168 */
1169VMMR3DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1170{
1171 /*
1172 * Allocate and init stuff.
1173 */
1174 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1175 if (VBOX_SUCCESS(rc))
1176 {
1177 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1178 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1179 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1180 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1181 }
1182
1183 return rc;
1184}
1185
1186
1187/**
1188 * Creates a driver timer.
1189 *
1190 * @returns VBox status.
1191 * @param pVM The VM to create the timer in.
1192 * @param pDrvIns Driver instance.
1193 * @param enmClock The clock to use on this timer.
1194 * @param pfnCallback Callback function.
1195 * @param pszDesc Pointer to description string which must stay around
1196 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1197 * @param ppTimer Where to store the timer on success.
1198 */
1199VMMR3DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
1200{
1201 /*
1202 * Allocate and init stuff.
1203 */
1204 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1205 if (VBOX_SUCCESS(rc))
1206 {
1207 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1208 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1209 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1210 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1211 }
1212
1213 return rc;
1214}
1215
1216
1217/**
1218 * Creates an internal timer.
1219 *
1220 * @returns VBox status.
1221 * @param pVM The VM to create the timer in.
1222 * @param enmClock The clock to use on this timer.
1223 * @param pfnCallback Callback function.
1224 * @param pvUser User argument to be passed to the callback.
1225 * @param pszDesc Pointer to description string which must stay around
1226 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1227 * @param ppTimer Where to store the timer on success.
1228 */
1229VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1230{
1231 /*
1232 * Allocate and init stuff.
1233 */
1234 PTMTIMER pTimer;
1235 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1236 if (VBOX_SUCCESS(rc))
1237 {
1238 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1239 pTimer->u.Internal.pfnTimer = pfnCallback;
1240 pTimer->u.Internal.pvUser = pvUser;
1241 *ppTimer = pTimer;
1242 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1243 }
1244
1245 return rc;
1246}
1247
1248/**
1249 * Creates an external timer.
1250 *
1251 * @returns Timer handle on success.
1252 * @returns NULL on failure.
1253 * @param pVM The VM to create the timer in.
1254 * @param enmClock The clock to use on this timer.
1255 * @param pfnCallback Callback function.
1256 * @param pvUser User argument.
1257 * @param pszDesc Pointer to description string which must stay around
1258 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1259 */
1260VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1261{
1262 /*
1263 * Allocate and init stuff.
1264 */
1265 PTMTIMERR3 pTimer;
1266 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1267 if (VBOX_SUCCESS(rc))
1268 {
1269 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1270 pTimer->u.External.pfnTimer = pfnCallback;
1271 pTimer->u.External.pvUser = pvUser;
1272 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1273 return pTimer;
1274 }
1275
1276 return NULL;
1277}
1278
1279
1280/**
1281 * Destroy all timers owned by a device.
1282 *
1283 * @returns VBox status.
1284 * @param pVM VM handle.
1285 * @param pDevIns Device which timers should be destroyed.
1286 */
1287VMMR3DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1288{
1289 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1290 if (!pDevIns)
1291 return VERR_INVALID_PARAMETER;
1292
1293 PTMTIMER pCur = pVM->tm.s.pCreated;
1294 while (pCur)
1295 {
1296 PTMTIMER pDestroy = pCur;
1297 pCur = pDestroy->pBigNext;
1298 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1299 && pDestroy->u.Dev.pDevIns == pDevIns)
1300 {
1301 int rc = TMTimerDestroy(pDestroy);
1302 AssertRC(rc);
1303 }
1304 }
1305 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1306 return VINF_SUCCESS;
1307}
1308
1309
1310/**
1311 * Destroy all timers owned by a driver.
1312 *
1313 * @returns VBox status.
1314 * @param pVM VM handle.
1315 * @param pDrvIns Driver which timers should be destroyed.
1316 */
1317VMMR3DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1318{
1319 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1320 if (!pDrvIns)
1321 return VERR_INVALID_PARAMETER;
1322
1323 PTMTIMER pCur = pVM->tm.s.pCreated;
1324 while (pCur)
1325 {
1326 PTMTIMER pDestroy = pCur;
1327 pCur = pDestroy->pBigNext;
1328 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1329 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1330 {
1331 int rc = TMTimerDestroy(pDestroy);
1332 AssertRC(rc);
1333 }
1334 }
1335 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1336 return VINF_SUCCESS;
1337}
1338
1339
1340/**
1341 * Internal function for getting the clock time.
1342 *
1343 * @returns clock time.
1344 * @param pVM The VM handle.
1345 * @param enmClock The clock.
1346 */
1347DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
1348{
1349 switch (enmClock)
1350 {
1351 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
1352 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
1353 case TMCLOCK_REAL: return TMRealGet(pVM);
1354 case TMCLOCK_TSC: return TMCpuTickGet(pVM);
1355 default:
1356 AssertMsgFailed(("enmClock=%d\n", enmClock));
1357 return ~(uint64_t)0;
1358 }
1359}
1360
1361
1362/**
1363 * Checks if the sync queue has one or more expired timers.
1364 *
1365 * @returns true / false.
1366 *
1367 * @param pVM The VM handle.
1368 * @param enmClock The queue.
1369 */
1370DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1371{
1372 const uint64_t u64Expire = pVM->tm.s.CTX_SUFF(paTimerQueues)[enmClock].u64Expire;
1373 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1374}
1375
1376
1377/**
1378 * Checks for expired timers in all the queues.
1379 *
1380 * @returns true / false.
1381 * @param pVM The VM handle.
1382 */
1383DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1384{
1385 /*
1386 * Combine the time calculation for the first two since we're not on EMT
1387 * TMVirtualSyncGet only permits EMT.
1388 */
1389 uint64_t u64Now = TMVirtualGet(pVM);
1390 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1391 return true;
1392 u64Now = pVM->tm.s.fVirtualSyncTicking
1393 ? u64Now - pVM->tm.s.offVirtualSync
1394 : pVM->tm.s.u64VirtualSync;
1395 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1396 return true;
1397
1398 /*
1399 * The remaining timers.
1400 */
1401 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1402 return true;
1403 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1404 return true;
1405 return false;
1406}
1407
1408
1409/**
1410 * Schedulation timer callback.
1411 *
1412 * @param pTimer Timer handle.
1413 * @param pvUser VM handle.
1414 * @thread Timer thread.
1415 *
1416 * @remark We cannot do the scheduling and queues running from a timer handler
1417 * since it's not executing in EMT, and even if it was it would be async
1418 * and we wouldn't know the state of the affairs.
1419 * So, we'll just raise the timer FF and force any REM execution to exit.
1420 */
1421static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1422{
1423 PVM pVM = (PVM)pvUser;
1424 AssertCompile(TMCLOCK_MAX == 4);
1425#ifdef DEBUG_Sander /* very annoying, keep it private. */
1426 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
1427 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1428#endif
1429 if ( !VM_FF_ISSET(pVM, VM_FF_TIMER)
1430 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule
1431 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1432 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1433 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1434 || tmR3AnyExpiredTimers(pVM)
1435 )
1436 && !VM_FF_ISSET(pVM, VM_FF_TIMER)
1437 )
1438 {
1439 VM_FF_SET(pVM, VM_FF_TIMER);
1440 REMR3NotifyTimerPending(pVM);
1441 VMR3NotifyFF(pVM, true);
1442 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1443 }
1444}
1445
1446
1447/**
1448 * Schedules and runs any pending timers.
1449 *
1450 * This is normally called from a forced action handler in EMT.
1451 *
1452 * @param pVM The VM to run the timers for.
1453 */
1454VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1455{
1456 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1457 Log2(("TMR3TimerQueuesDo:\n"));
1458
1459 /*
1460 * Process the queues.
1461 */
1462 AssertCompile(TMCLOCK_MAX == 4);
1463
1464 /* TMCLOCK_VIRTUAL_SYNC */
1465 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesSchedule, s1);
1466 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
1467 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s1);
1468 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesRun, r1);
1469 tmR3TimerQueueRunVirtualSync(pVM);
1470 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r1);
1471
1472 /* TMCLOCK_VIRTUAL */
1473 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s1);
1474 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1475 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s2);
1476 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r1);
1477 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1478 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r2);
1479
1480#if 0 /** @todo if ever used, remove this and fix the stam prefixes on TMCLOCK_REAL below. */
1481 /* TMCLOCK_TSC */
1482 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1483 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1484 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s3);
1485 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1486 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1487 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r3);
1488#endif
1489
1490 /* TMCLOCK_REAL */
1491 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
1492 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1493 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesSchedule, s3);
1494 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
1495 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1496 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesRun, r3);
1497
1498 /* done. */
1499 VM_FF_CLEAR(pVM, VM_FF_TIMER);
1500
1501#ifdef VBOX_STRICT
1502 /* check that we didn't screwup. */
1503 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1504#endif
1505
1506 Log2(("TMR3TimerQueuesDo: returns void\n"));
1507 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1508}
1509
1510
1511/**
1512 * Schedules and runs any pending times in the specified queue.
1513 *
1514 * This is normally called from a forced action handler in EMT.
1515 *
1516 * @param pVM The VM to run the timers for.
1517 * @param pQueue The queue to run.
1518 */
1519static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1520{
1521 VM_ASSERT_EMT(pVM);
1522
1523 /*
1524 * Run timers.
1525 *
1526 * We check the clock once and run all timers which are ACTIVE
1527 * and have an expire time less or equal to the time we read.
1528 *
1529 * N.B. A generic unlink must be applied since other threads
1530 * are allowed to mess with any active timer at any time.
1531 * However, we only allow EMT to handle EXPIRED_PENDING
1532 * timers, thus enabling the timer handler function to
1533 * arm the timer again.
1534 */
1535 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1536 if (!pNext)
1537 return;
1538 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1539 while (pNext && pNext->u64Expire <= u64Now)
1540 {
1541 PTMTIMER pTimer = pNext;
1542 pNext = TMTIMER_GET_NEXT(pTimer);
1543 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1544 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1545 bool fRc;
1546 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1547 if (fRc)
1548 {
1549 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1550
1551 /* unlink */
1552 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1553 if (pPrev)
1554 TMTIMER_SET_NEXT(pPrev, pNext);
1555 else
1556 {
1557 TMTIMER_SET_HEAD(pQueue, pNext);
1558 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1559 }
1560 if (pNext)
1561 TMTIMER_SET_PREV(pNext, pPrev);
1562 pTimer->offNext = 0;
1563 pTimer->offPrev = 0;
1564
1565
1566 /* fire */
1567 switch (pTimer->enmType)
1568 {
1569 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1570 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1571 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1572 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1573 default:
1574 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1575 break;
1576 }
1577
1578 /* change the state if it wasn't changed already in the handler. */
1579 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1580 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1581 }
1582 } /* run loop */
1583}
1584
1585
1586/**
1587 * Schedules and runs any pending times in the timer queue for the
1588 * synchronous virtual clock.
1589 *
1590 * This scheduling is a bit different from the other queues as it need
1591 * to implement the special requirements of the timer synchronous virtual
1592 * clock, thus this 2nd queue run funcion.
1593 *
1594 * @param pVM The VM to run the timers for.
1595 */
1596static void tmR3TimerQueueRunVirtualSync(PVM pVM)
1597{
1598 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
1599 VM_ASSERT_EMT(pVM);
1600
1601 /*
1602 * Any timers?
1603 */
1604 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1605 if (RT_UNLIKELY(!pNext))
1606 {
1607 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.fVirtualTicking);
1608 return;
1609 }
1610 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
1611
1612 /*
1613 * Calculate the time frame for which we will dispatch timers.
1614 *
1615 * We use a time frame ranging from the current sync time (which is most likely the
1616 * same as the head timer) and some configurable period (100000ns) up towards the
1617 * current virtual time. This period might also need to be restricted by the catch-up
1618 * rate so frequent calls to this function won't accelerate the time too much, however
1619 * this will be implemented at a later point if neccessary.
1620 *
1621 * Without this frame we would 1) having to run timers much more frequently
1622 * and 2) lag behind at a steady rate.
1623 */
1624 const uint64_t u64VirtualNow = TMVirtualGetEx(pVM, false /* don't check timers */);
1625 uint64_t u64Now;
1626 if (!pVM->tm.s.fVirtualSyncTicking)
1627 {
1628 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
1629 u64Now = pVM->tm.s.u64VirtualSync;
1630 Assert(u64Now <= pNext->u64Expire);
1631 }
1632 else
1633 {
1634 /* Calc 'now'. (update order doesn't really matter here) */
1635 uint64_t off = pVM->tm.s.offVirtualSync;
1636 if (pVM->tm.s.fVirtualSyncCatchUp)
1637 {
1638 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
1639 if (RT_LIKELY(!(u64Delta >> 32)))
1640 {
1641 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
1642 if (off > u64Sub + pVM->tm.s.offVirtualSyncGivenUp)
1643 {
1644 off -= u64Sub;
1645 Log4(("TM: %RU64/%RU64: sub %RU64 (run)\n", u64VirtualNow - off, off - pVM->tm.s.offVirtualSyncGivenUp, u64Sub));
1646 }
1647 else
1648 {
1649 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1650 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1651 off = pVM->tm.s.offVirtualSyncGivenUp;
1652 Log4(("TM: %RU64/0: caught up (run)\n", u64VirtualNow));
1653 }
1654 }
1655 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, off);
1656 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow;
1657 }
1658 u64Now = u64VirtualNow - off;
1659
1660 /* Check if stopped by expired timer. */
1661 if (u64Now >= pNext->u64Expire)
1662 {
1663 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
1664 u64Now = pNext->u64Expire;
1665 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, u64Now);
1666 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, false);
1667 Log4(("TM: %RU64/%RU64: exp tmr (run)\n", u64Now, u64VirtualNow - u64Now - pVM->tm.s.offVirtualSyncGivenUp));
1668
1669 }
1670 }
1671
1672 /* calc end of frame. */
1673 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
1674 if (u64Max > u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp)
1675 u64Max = u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp;
1676
1677 /* assert sanity */
1678 Assert(u64Now <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1679 Assert(u64Max <= u64VirtualNow - pVM->tm.s.offVirtualSyncGivenUp);
1680 Assert(u64Now <= u64Max);
1681
1682 /*
1683 * Process the expired timers moving the clock along as we progress.
1684 */
1685#ifdef VBOX_STRICT
1686 uint64_t u64Prev = u64Now; NOREF(u64Prev);
1687#endif
1688 while (pNext && pNext->u64Expire <= u64Max)
1689 {
1690 PTMTIMER pTimer = pNext;
1691 pNext = TMTIMER_GET_NEXT(pTimer);
1692 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1693 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1694 bool fRc;
1695 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1696 if (fRc)
1697 {
1698 /* unlink */
1699 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1700 if (pPrev)
1701 TMTIMER_SET_NEXT(pPrev, pNext);
1702 else
1703 {
1704 TMTIMER_SET_HEAD(pQueue, pNext);
1705 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1706 }
1707 if (pNext)
1708 TMTIMER_SET_PREV(pNext, pPrev);
1709 pTimer->offNext = 0;
1710 pTimer->offPrev = 0;
1711
1712 /* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
1713#ifdef VBOX_STRICT
1714 AssertMsg(pTimer->u64Expire >= u64Prev, ("%RU64 < %RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
1715 u64Prev = pTimer->u64Expire;
1716#endif
1717 ASMAtomicXchgSize(&pVM->tm.s.fVirtualSyncTicking, false);
1718 ASMAtomicXchgU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
1719
1720 /* fire */
1721 switch (pTimer->enmType)
1722 {
1723 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1724 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1725 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1726 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1727 default:
1728 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1729 break;
1730 }
1731
1732 /* change the state if it wasn't changed already in the handler. */
1733 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1734 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1735 }
1736 } /* run loop */
1737
1738 /*
1739 * Restart the clock if it was stopped to serve any timers,
1740 * and start/adjust catch-up if necessary.
1741 */
1742 if ( !pVM->tm.s.fVirtualSyncTicking
1743 && pVM->tm.s.fVirtualTicking)
1744 {
1745 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
1746
1747 /* calc the slack we've handed out. */
1748 const uint64_t u64VirtualNow2 = TMVirtualGetEx(pVM, false /* don't check timers */);
1749 Assert(u64VirtualNow2 >= u64VirtualNow);
1750 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%RU64 < %RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
1751 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
1752 STAM_STATS({
1753 if (offSlack)
1754 {
1755 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
1756 p->cPeriods++;
1757 p->cTicks += offSlack;
1758 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
1759 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
1760 }
1761 });
1762
1763 /* Let the time run a little bit while we were busy running timers(?). */
1764 uint64_t u64Elapsed;
1765#define MAX_ELAPSED 30000 /* ns */
1766 if (offSlack > MAX_ELAPSED)
1767 u64Elapsed = 0;
1768 else
1769 {
1770 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
1771 if (u64Elapsed > MAX_ELAPSED)
1772 u64Elapsed = MAX_ELAPSED;
1773 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
1774 }
1775#undef MAX_ELAPSED
1776
1777 /* Calc the current offset. */
1778 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
1779 Assert(!(offNew & RT_BIT_64(63)));
1780 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
1781 Assert(!(offLag & RT_BIT_64(63)));
1782
1783 /*
1784 * Deal with starting, adjusting and stopping catchup.
1785 */
1786 if (pVM->tm.s.fVirtualSyncCatchUp)
1787 {
1788 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
1789 {
1790 /* stop */
1791 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1792 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1793 Log4(("TM: %RU64/%RU64: caught up\n", u64VirtualNow2 - offNew, offLag));
1794 }
1795 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1796 {
1797 /* adjust */
1798 unsigned i = 0;
1799 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1800 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1801 i++;
1802 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
1803 {
1804 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
1805 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1806 Log4(("TM: %RU64/%RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1807 }
1808 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
1809 }
1810 else
1811 {
1812 /* give up */
1813 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
1814 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1815 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1816 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1817 Log4(("TM: %RU64/%RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1818 LogRel(("TM: Giving up catch-up attempt at a %RU64 ns lag; new total: %RU64 ns\n", offLag, offNew));
1819 }
1820 }
1821 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
1822 {
1823 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
1824 {
1825 /* start */
1826 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
1827 unsigned i = 0;
1828 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
1829 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
1830 i++;
1831 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
1832 ASMAtomicXchgU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
1833 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
1834 Log4(("TM: %RU64/%RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
1835 }
1836 else
1837 {
1838 /* don't bother */
1839 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
1840 ASMAtomicXchgU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1841 Log4(("TM: %RU64/%RU64: give up\n", u64VirtualNow2 - offNew, offLag));
1842 LogRel(("TM: Not bothering to attempt catching up a %RU64 ns lag; new total: %RU64\n", offLag, offNew));
1843 }
1844 }
1845
1846 /*
1847 * Update the offset and restart the clock.
1848 */
1849 Assert(!(offNew & RT_BIT_64(63)));
1850 ASMAtomicXchgU64(&pVM->tm.s.offVirtualSync, offNew);
1851 ASMAtomicXchgBool(&pVM->tm.s.fVirtualSyncTicking, true);
1852 }
1853}
1854
1855
1856/**
1857 * Saves the state of a timer to a saved state.
1858 *
1859 * @returns VBox status.
1860 * @param pTimer Timer to save.
1861 * @param pSSM Save State Manager handle.
1862 */
1863VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1864{
1865 LogFlow(("TMR3TimerSave: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1866 switch (pTimer->enmState)
1867 {
1868 case TMTIMERSTATE_STOPPED:
1869 case TMTIMERSTATE_PENDING_STOP:
1870 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1871 return SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_STOP);
1872
1873 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1874 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1875 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
1876 if (!RTThreadYield())
1877 RTThreadSleep(1);
1878 /* fall thru */
1879 case TMTIMERSTATE_ACTIVE:
1880 case TMTIMERSTATE_PENDING_SCHEDULE:
1881 case TMTIMERSTATE_PENDING_RESCHEDULE:
1882 SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_SCHEDULE);
1883 return SSMR3PutU64(pSSM, pTimer->u64Expire);
1884
1885 case TMTIMERSTATE_EXPIRED:
1886 case TMTIMERSTATE_PENDING_DESTROY:
1887 case TMTIMERSTATE_PENDING_STOP_DESTROY:
1888 case TMTIMERSTATE_FREE:
1889 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
1890 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
1891 }
1892
1893 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
1894 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
1895}
1896
1897
1898/**
1899 * Loads the state of a timer from a saved state.
1900 *
1901 * @returns VBox status.
1902 * @param pTimer Timer to restore.
1903 * @param pSSM Save State Manager handle.
1904 */
1905VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
1906{
1907 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
1908 LogFlow(("TMR3TimerLoad: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1909
1910 /*
1911 * Load the state and validate it.
1912 */
1913 uint8_t u8State;
1914 int rc = SSMR3GetU8(pSSM, &u8State);
1915 if (VBOX_FAILURE(rc))
1916 return rc;
1917 TMTIMERSTATE enmState = (TMTIMERSTATE)u8State;
1918 if ( enmState != TMTIMERSTATE_PENDING_STOP
1919 && enmState != TMTIMERSTATE_PENDING_SCHEDULE
1920 && enmState != TMTIMERSTATE_PENDING_STOP_SCHEDULE)
1921 {
1922 AssertMsgFailed(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1923 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
1924 }
1925
1926 if (enmState == TMTIMERSTATE_PENDING_SCHEDULE)
1927 {
1928 /*
1929 * Load the expire time.
1930 */
1931 uint64_t u64Expire;
1932 rc = SSMR3GetU64(pSSM, &u64Expire);
1933 if (VBOX_FAILURE(rc))
1934 return rc;
1935
1936 /*
1937 * Set it.
1938 */
1939 Log(("enmState=%d %s u64Expire=%llu\n", enmState, tmTimerState(enmState), u64Expire));
1940 rc = TMTimerSet(pTimer, u64Expire);
1941 }
1942 else
1943 {
1944 /*
1945 * Stop it.
1946 */
1947 Log(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1948 rc = TMTimerStop(pTimer);
1949 }
1950
1951 /*
1952 * On failure set SSM status.
1953 */
1954 if (VBOX_FAILURE(rc))
1955 rc = SSMR3HandleSetStatus(pSSM, rc);
1956 return rc;
1957}
1958
1959
1960/**
1961 * Get the real world UTC time adjusted for VM lag.
1962 *
1963 * @returns pTime.
1964 * @param pVM The VM instance.
1965 * @param pTime Where to store the time.
1966 */
1967VMMR3DECL(PRTTIMESPEC) TMR3UTCNow(PVM pVM, PRTTIMESPEC pTime)
1968{
1969 RTTimeNow(pTime);
1970 RTTimeSpecSubNano(pTime, pVM->tm.s.offVirtualSync - pVM->tm.s.offVirtualSyncGivenUp);
1971 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
1972 return pTime;
1973}
1974
1975
1976/**
1977 * Display all timers.
1978 *
1979 * @param pVM VM Handle.
1980 * @param pHlp The info helpers.
1981 * @param pszArgs Arguments, ignored.
1982 */
1983static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1984{
1985 NOREF(pszArgs);
1986 pHlp->pfnPrintf(pHlp,
1987 "Timers (pVM=%p)\n"
1988 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1989 pVM,
1990 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1991 sizeof(int32_t) * 2, "offNext ",
1992 sizeof(int32_t) * 2, "offPrev ",
1993 sizeof(int32_t) * 2, "offSched ",
1994 "Time",
1995 "Expire",
1996 "State");
1997 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1998 {
1999 pHlp->pfnPrintf(pHlp,
2000 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
2001 pTimer,
2002 pTimer->offNext,
2003 pTimer->offPrev,
2004 pTimer->offScheduleNext,
2005 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
2006 TMTimerGet(pTimer),
2007 pTimer->u64Expire,
2008 tmTimerState(pTimer->enmState),
2009 pTimer->pszDesc);
2010 }
2011}
2012
2013
2014/**
2015 * Display all active timers.
2016 *
2017 * @param pVM VM Handle.
2018 * @param pHlp The info helpers.
2019 * @param pszArgs Arguments, ignored.
2020 */
2021static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2022{
2023 NOREF(pszArgs);
2024 pHlp->pfnPrintf(pHlp,
2025 "Active Timers (pVM=%p)\n"
2026 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
2027 pVM,
2028 sizeof(RTR3PTR) * 2, "pTimerR3 ",
2029 sizeof(int32_t) * 2, "offNext ",
2030 sizeof(int32_t) * 2, "offPrev ",
2031 sizeof(int32_t) * 2, "offSched ",
2032 "Time",
2033 "Expire",
2034 "State");
2035 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
2036 {
2037 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
2038 pTimer;
2039 pTimer = TMTIMER_GET_NEXT(pTimer))
2040 {
2041 pHlp->pfnPrintf(pHlp,
2042 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
2043 pTimer,
2044 pTimer->offNext,
2045 pTimer->offPrev,
2046 pTimer->offScheduleNext,
2047 pTimer->enmClock == TMCLOCK_REAL
2048 ? "Real "
2049 : pTimer->enmClock == TMCLOCK_VIRTUAL
2050 ? "Virt "
2051 : pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC
2052 ? "VrSy "
2053 : "TSC ",
2054 TMTimerGet(pTimer),
2055 pTimer->u64Expire,
2056 tmTimerState(pTimer->enmState),
2057 pTimer->pszDesc);
2058 }
2059 }
2060}
2061
2062
2063/**
2064 * Display all clocks.
2065 *
2066 * @param pVM VM Handle.
2067 * @param pHlp The info helpers.
2068 * @param pszArgs Arguments, ignored.
2069 */
2070static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2071{
2072 NOREF(pszArgs);
2073
2074 /*
2075 * Read the times first to avoid more than necessary time variation.
2076 */
2077 const uint64_t u64TSC = TMCpuTickGet(pVM);
2078 const uint64_t u64Virtual = TMVirtualGet(pVM);
2079 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
2080 const uint64_t u64Real = TMRealGet(pVM);
2081
2082 /*
2083 * TSC
2084 */
2085 pHlp->pfnPrintf(pHlp,
2086 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
2087 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
2088 pVM->tm.s.fTSCTicking ? "ticking" : "paused",
2089 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
2090 if (pVM->tm.s.fTSCUseRealTSC)
2091 {
2092 pHlp->pfnPrintf(pHlp, " - real tsc");
2093 if (pVM->tm.s.u64TSCOffset)
2094 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.u64TSCOffset);
2095 }
2096 else
2097 pHlp->pfnPrintf(pHlp, " - virtual clock");
2098 pHlp->pfnPrintf(pHlp, "\n");
2099
2100 /*
2101 * virtual
2102 */
2103 pHlp->pfnPrintf(pHlp,
2104 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
2105 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
2106 pVM->tm.s.fVirtualTicking ? "ticking" : "paused");
2107 if (pVM->tm.s.fVirtualWarpDrive)
2108 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
2109 pHlp->pfnPrintf(pHlp, "\n");
2110
2111 /*
2112 * virtual sync
2113 */
2114 pHlp->pfnPrintf(pHlp,
2115 "VirtSync: %18RU64 (%#016RX64) %s%s",
2116 u64VirtualSync, u64VirtualSync,
2117 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
2118 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
2119 if (pVM->tm.s.offVirtualSync)
2120 {
2121 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
2122 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
2123 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
2124 }
2125 pHlp->pfnPrintf(pHlp, "\n");
2126
2127 /*
2128 * real
2129 */
2130 pHlp->pfnPrintf(pHlp,
2131 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
2132 u64Real, u64Real, TMRealGetFreq(pVM));
2133}
2134
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