VirtualBox

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

Last change on this file since 2676 was 2623, checked in by vboxsync, 17 years ago

Fixed UTC typo.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use