VirtualBox

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

Last change on this file since 9176 was 9148, checked in by vboxsync, 17 years ago

More 64 bits guest preps

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