VirtualBox

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

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

More logging.

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