VirtualBox

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

Last change on this file since 2871 was 2869, checked in by vboxsync, 18 years ago

Create a speciallized version of the RTTimeNanoTS code in timesup.cpp for calculating the virtual time. I hope this will eliminate the w32_2 trouble and related issues seen on the black box and my laptop.

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