VirtualBox

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

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

sync virt time docs and some general docs updates.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 50.2 KB
Line 
1/* $Id: TM.cpp 2105 2007-04-16 15:08:48Z 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
88
89
90
91/*******************************************************************************
92* Header Files *
93*******************************************************************************/
94#define LOG_GROUP LOG_GROUP_TM
95#include <VBox/tm.h>
96#include <VBox/vmm.h>
97#include <VBox/mm.h>
98#include <VBox/ssm.h>
99#include <VBox/dbgf.h>
100#include <VBox/rem.h>
101#include "TMInternal.h"
102#include <VBox/vm.h>
103
104#include <VBox/param.h>
105#include <VBox/err.h>
106
107#include <VBox/log.h>
108#include <iprt/asm.h>
109#include <iprt/assert.h>
110#include <iprt/thread.h>
111#include <iprt/time.h>
112#include <iprt/timer.h>
113#include <iprt/semaphore.h>
114#include <iprt/string.h>
115#include <iprt/env.h>
116
117
118/*******************************************************************************
119* Defined Constants And Macros *
120*******************************************************************************/
121/** The current saved state version.*/
122#define TM_SAVED_STATE_VERSION 2
123
124
125/*******************************************************************************
126* Internal Functions *
127*******************************************************************************/
128static uint64_t tmR3Calibrate(void);
129static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM);
130static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
131static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser);
132static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue);
133static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
134static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
135static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
136
137
138/**
139 * Internal function for getting the clock time.
140 *
141 * @returns clock time.
142 * @param pVM The VM handle.
143 * @param enmClock The clock.
144 */
145DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
146{
147 switch (enmClock)
148 {
149 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
150 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualGetSync(pVM);
151 case TMCLOCK_REAL: return TMRealGet(pVM);
152 case TMCLOCK_TSC: return TMCpuTickGet(pVM);
153 default:
154 AssertMsgFailed(("enmClock=%d\n", enmClock));
155 return ~(uint64_t)0;
156 }
157}
158
159
160/**
161 * Initializes the TM.
162 *
163 * @returns VBox status code.
164 * @param pVM The VM to operate on.
165 */
166TMR3DECL(int) TMR3Init(PVM pVM)
167{
168 LogFlow(("TMR3Init:\n"));
169
170 /*
171 * Assert alignment and sizes.
172 */
173 AssertRelease(!(RT_OFFSETOF(VM, tm.s) & 31));
174 AssertRelease(sizeof(pVM->tm.s) <= sizeof(pVM->tm.padding));
175
176 /*
177 * Init the structure.
178 */
179 void *pv;
180 int rc = MMHyperAlloc(pVM, sizeof(pVM->tm.s.paTimerQueuesR3[0]) * TMCLOCK_MAX, 0, MM_TAG_TM, &pv);
181 AssertRCReturn(rc, rc);
182 pVM->tm.s.paTimerQueuesR3 = (PTMTIMERQUEUE)pv;
183
184 pVM->tm.s.offVM = RT_OFFSETOF(VM, tm.s);
185 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].enmClock = TMCLOCK_VIRTUAL;
186 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].u64Expire = INT64_MAX;
187 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].enmClock = TMCLOCK_VIRTUAL_SYNC;
188 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].u64Expire = INT64_MAX;
189 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].enmClock = TMCLOCK_REAL;
190 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].u64Expire = INT64_MAX;
191 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].enmClock = TMCLOCK_TSC;
192 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].u64Expire = INT64_MAX;
193
194 /*
195 * We indirectly - thru RTTimeNanoTS and RTTimeMilliTS - use the global
196 * info page (GIP) for both the virtual and the real clock. By mapping
197 * the GIP into guest context we can get just as accurate time even there.
198 * All that's required is that the g_pSUPGlobalInfoPage symbol is available
199 * to the GC Runtime.
200 */
201 pVM->tm.s.pvGIPR3 = (void *)g_pSUPGlobalInfoPage;
202 AssertMsgReturn(pVM->tm.s.pvGIPR3, ("GIP support is now required!\n"), VERR_INTERNAL_ERROR);
203 RTHCPHYS HCPhysGIP;
204 rc = SUPGipGetPhys(&HCPhysGIP);
205 AssertMsgRCReturn(rc, ("Failed to get GIP physical address!\n"), rc);
206
207 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, HCPhysGIP, PAGE_SIZE, "GIP", &pVM->tm.s.pvGIPGC);
208 if (VBOX_FAILURE(rc))
209 {
210 AssertMsgFailed(("Failed to map GIP into GC, rc=%Vrc!\n", rc));
211 return rc;
212 }
213 LogFlow(("TMR3Init: HCPhysGIP=%RHp at %VGv\n", HCPhysGIP, pVM->tm.s.pvGIPGC));
214 MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);
215
216 /*
217 * Determin the TSC configuration and frequency.
218 */
219 /* mode */
220 rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "TSCVirtualized", &pVM->tm.s.fTSCVirtualized);
221 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
222 pVM->tm.s.fTSCVirtualized = true; /* trap rdtsc */
223 else if (VBOX_FAILURE(rc))
224 return VMSetError(pVM, rc, RT_SRC_POS,
225 N_("Configuration error: Failed to querying bool value \"UseRealTSC\". (%Vrc)"), rc);
226
227 /* source */
228 rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "UseRealTSC", &pVM->tm.s.fTSCTicking);
229 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
230 pVM->tm.s.fTSCUseRealTSC = false; /* use virtual time */
231 else if (VBOX_FAILURE(rc))
232 return VMSetError(pVM, rc, RT_SRC_POS,
233 N_("Configuration error: Failed to querying bool value \"UseRealTSC\". (%Vrc)"), rc);
234 if (!pVM->tm.s.fTSCUseRealTSC)
235 pVM->tm.s.fTSCVirtualized = true;
236
237 /* frequency */
238 rc = CFGMR3QueryU64(CFGMR3GetRoot(pVM), "TSCTicksPerSecond", &pVM->tm.s.cTSCTicksPerSecond);
239 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
240 {
241 pVM->tm.s.cTSCTicksPerSecond = tmR3Calibrate();
242 if ( !pVM->tm.s.fTSCUseRealTSC
243 && pVM->tm.s.cTSCTicksPerSecond >= _4G)
244 pVM->tm.s.cTSCTicksPerSecond = _4G - 1; /* (A limitation of our math code) */
245 }
246 else if (VBOX_FAILURE(rc))
247 return VMSetError(pVM, rc, RT_SRC_POS,
248 N_("Configuration error: Failed to querying uint64_t value \"TSCTicksPerSecond\". (%Vrc)"), rc);
249 else if ( pVM->tm.s.cTSCTicksPerSecond < _1M
250 || pVM->tm.s.cTSCTicksPerSecond >= _4G)
251 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
252 N_("Configuration error: \"TSCTicksPerSecond\" = %RI64 is not in the range 1MHz..4GHz-1!"),
253 pVM->tm.s.cTSCTicksPerSecond);
254 else
255 {
256 pVM->tm.s.fTSCUseRealTSC = false;
257 pVM->tm.s.fTSCVirtualized = true;
258 }
259
260 /* setup and report */
261 if (pVM->tm.s.fTSCUseRealTSC)
262 CPUMR3SetCR4Feature(pVM, 0, ~X86_CR4_TSD);
263 else
264 CPUMR3SetCR4Feature(pVM, X86_CR4_TSD, ~X86_CR4_TSD);
265 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool\n",
266 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
267
268 /*
269 * Register saved state.
270 */
271 rc = SSMR3RegisterInternal(pVM, "tm", 1, TM_SAVED_STATE_VERSION, sizeof(uint64_t) * 8,
272 NULL, tmR3Save, NULL,
273 NULL, tmR3Load, NULL);
274 if (VBOX_FAILURE(rc))
275 return rc;
276
277 /*
278 * Setup the warp drive.
279 */
280 rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage);
281 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
282 pVM->tm.s.u32VirtualWarpDrivePercentage = 100;
283 else if (VBOX_FAILURE(rc))
284 return VMSetError(pVM, rc, RT_SRC_POS,
285 N_("Configuration error: Failed to querying uint32_t value \"WarpDrivePercent\". (%Vrc)"), rc);
286 else if ( pVM->tm.s.u32VirtualWarpDrivePercentage < 2
287 || pVM->tm.s.u32VirtualWarpDrivePercentage > 20000)
288 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
289 N_("Configuration error: \"WarpDrivePercent\" = %RI32 is not in the range 2..20000!"),
290 pVM->tm.s.u32VirtualWarpDrivePercentage);
291 pVM->tm.s.fVirtualWarpDrive = pVM->tm.s.u32VirtualWarpDrivePercentage != 100;
292 if (pVM->tm.s.fVirtualWarpDrive)
293 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32\n", pVM->tm.s.u32VirtualWarpDrivePercentage));
294
295 /*
296 * Start the timer (guard against REM not yielding).
297 */
298 uint32_t u32Millies;
299 rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "TimerMillies", &u32Millies);
300 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
301 u32Millies = 10;
302 else if (VBOX_FAILURE(rc))
303 return VMSetError(pVM, rc, RT_SRC_POS,
304 N_("Configuration error: Failed to query uint32_t value \"TimerMillies\", rc=%Vrc.\n"), rc);
305 rc = RTTimerCreate(&pVM->tm.s.pTimer, u32Millies, tmR3TimerCallback, pVM);
306 if (VBOX_FAILURE(rc))
307 {
308 AssertMsgFailed(("Failed to create timer, u32Millies=%d rc=%Vrc.\n", u32Millies, rc));
309 return rc;
310 }
311 Log(("TM: Created timer %p firing every %d millieseconds\n", pVM->tm.s.pTimer, u32Millies));
312 pVM->tm.s.u32TimerMillies = u32Millies;
313
314#ifdef VBOX_WITH_STATISTICS
315 /*
316 * Register statistics.
317 */
318 STAM_REG(pVM, &pVM->tm.s.StatDoQueues, STAMTYPE_PROFILE, "/TM/DoQueues", STAMUNIT_TICKS_PER_CALL, "Profiling timer TMR3TimerQueuesDo.");
319 STAM_REG(pVM, &pVM->tm.s.StatDoQueuesSchedule, STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Schedule",STAMUNIT_TICKS_PER_CALL, "The scheduling part.");
320 STAM_REG(pVM, &pVM->tm.s.StatDoQueuesRun, STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Run", STAMUNIT_TICKS_PER_CALL, "The run part.");
321
322 STAM_REG(pVM, &pVM->tm.s.StatPollAlreadySet, STAMTYPE_COUNTER, "/TM/PollAlreadySet", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the FF was already set.");
323 STAM_REG(pVM, &pVM->tm.s.StatPollVirtual, STAMTYPE_COUNTER, "/TM/PollHitsVirtual", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL queue.");
324 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.");
325 STAM_REG(pVM, &pVM->tm.s.StatPollMiss, STAMTYPE_COUNTER, "/TM/PollMiss", STAMUNIT_OCCURENCES, "TMTimerPoll calls where nothing had expired.");
326
327 STAM_REG(pVM, &pVM->tm.s.StatPostponedR3, STAMTYPE_COUNTER, "/TM/PostponedR3", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-3.");
328 STAM_REG(pVM, &pVM->tm.s.StatPostponedR0, STAMTYPE_COUNTER, "/TM/PostponedR0", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-0.");
329 STAM_REG(pVM, &pVM->tm.s.StatPostponedGC, STAMTYPE_COUNTER, "/TM/PostponedGC", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in GC.");
330
331 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");
332 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");
333 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");
334 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.");
335
336 STAM_REG(pVM, &pVM->tm.s.StatTimerSetGC, STAMTYPE_PROFILE, "/TM/TimerSetGC", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in GC.");
337 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR0, STAMTYPE_PROFILE, "/TM/TimerSetR0", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0.");
338 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR3, STAMTYPE_PROFILE, "/TM/TimerSetR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3.");
339
340 STAM_REG(pVM, &pVM->tm.s.StatTimerStopGC, STAMTYPE_PROFILE, "/TM/TimerStopGC", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in GC.");
341 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR0, STAMTYPE_PROFILE, "/TM/TimerStopR0", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-0.");
342 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR3, STAMTYPE_PROFILE, "/TM/TimerStopR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-3.");
343
344 STAM_REG(pVM, &pVM->tm.s.StatVirtualGet, STAMTYPE_COUNTER, "/TM/VirtualGet", STAMUNIT_OCCURENCES, "The number of times TMR3TimerGet was called when the clock was running.");
345 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSync, STAMTYPE_COUNTER, "/TM/VirtualGetSync", STAMUNIT_OCCURENCES, "The number of times TMR3TimerGetSync was called when the clock was running.");
346 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/VirtualPause", STAMUNIT_OCCURENCES, "The number of times TMR3TimerPause was called.");
347 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/VirtualResume", STAMUNIT_OCCURENCES, "The number of times TMR3TimerResume was called.");
348
349 STAM_REG(pVM, &pVM->tm.s.StatTimerCallbackSetFF,STAMTYPE_COUNTER, "/TM/CallbackSetFF", STAMUNIT_OCCURENCES, "The number of times the timer callback set FF.");
350#endif /* VBOX_WITH_STATISTICS */
351
352 /*
353 * Register info handlers.
354 */
355 DBGFR3InfoRegisterInternal(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo);
356 DBGFR3InfoRegisterInternal(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive);
357 DBGFR3InfoRegisterInternal(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks);
358
359 return VINF_SUCCESS;
360}
361
362
363/**
364 * Calibrate the CPU tick.
365 *
366 * @returns Number of ticks per second.
367 */
368static uint64_t tmR3Calibrate(void)
369{
370 /*
371 * Use GIP when available present.
372 */
373 uint64_t u64Hz;
374 PCSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
375 if ( pGip
376 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC)
377 {
378 unsigned iCpu = pGip->u32Mode != SUPGIPMODE_ASYNC_TSC ? 0 : ASMGetApicId();
379 if (iCpu >= RT_ELEMENTS(pGip->aCPUs))
380 AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
381 else
382 {
383 RTThreadSleep(32); /* To preserve old behaviour and to get a good CpuHz at startup. */
384 pGip = g_pSUPGlobalInfoPage;
385 if ( pGip
386 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC
387 && (u64Hz = pGip->aCPUs[iCpu].u64CpuHz)
388 && u64Hz != ~(uint64_t)0)
389 return u64Hz;
390 }
391 }
392
393 /* call this once first to make sure it's initialized. */
394 RTTimeNanoTS();
395
396 /*
397 * Yield the CPU to increase our chances of getting
398 * a correct value.
399 */
400 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
401 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
402 uint64_t au64Samples[5];
403 unsigned i;
404 for (i = 0; i < ELEMENTS(au64Samples); i++)
405 {
406 unsigned cMillies;
407 int cTries = 5;
408 uint64_t u64Start = ASMReadTSC();
409 uint64_t u64End;
410 uint64_t StartTS = RTTimeNanoTS();
411 uint64_t EndTS;
412 do
413 {
414 RTThreadSleep(s_auSleep[i]);
415 u64End = ASMReadTSC();
416 EndTS = RTTimeNanoTS();
417 cMillies = (unsigned)((EndTS - StartTS + 500000) / 1000000);
418 } while ( cMillies == 0 /* the sleep may be interrupted... */
419 || (cMillies < 20 && --cTries > 0));
420 uint64_t u64Diff = u64End - u64Start;
421
422 au64Samples[i] = (u64Diff * 1000) / cMillies;
423 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
424 }
425
426 /*
427 * Discard the highest and lowest results and calculate the average.
428 */
429 unsigned iHigh = 0;
430 unsigned iLow = 0;
431 for (i = 1; i < ELEMENTS(au64Samples); i++)
432 {
433 if (au64Samples[i] < au64Samples[iLow])
434 iLow = i;
435 if (au64Samples[i] > au64Samples[iHigh])
436 iHigh = i;
437 }
438 au64Samples[iLow] = 0;
439 au64Samples[iHigh] = 0;
440
441 u64Hz = au64Samples[0];
442 for (i = 1; i < ELEMENTS(au64Samples); i++)
443 u64Hz += au64Samples[i];
444 u64Hz /= ELEMENTS(au64Samples) - 2;
445
446 return u64Hz;
447}
448
449
450/**
451 * Applies relocations to data and code managed by this
452 * component. This function will be called at init and
453 * whenever the VMM need to relocate it self inside the GC.
454 *
455 * @param pVM The VM.
456 * @param offDelta Relocation delta relative to old location.
457 */
458TMR3DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
459{
460 LogFlow(("TMR3Relocate\n"));
461 pVM->tm.s.pvGIPGC = MMHyperR3ToGC(pVM, pVM->tm.s.pvGIPR3);
462 pVM->tm.s.paTimerQueuesGC = MMHyperR3ToGC(pVM, pVM->tm.s.paTimerQueuesR3);
463 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
464
465 /*
466 * Iterate the timers updating the pVMGC pointers.
467 */
468 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
469 {
470 pTimer->pVMGC = pVM->pVMGC;
471 pTimer->pVMR0 = (PVMR0)pVM->pVMHC; /// @todo pTimer->pVMR0 = pVM->pVMR0;
472 }
473}
474
475
476/**
477 * Terminates the TM.
478 *
479 * Termination means cleaning up and freeing all resources,
480 * the VM it self is at this point powered off or suspended.
481 *
482 * @returns VBox status code.
483 * @param pVM The VM to operate on.
484 */
485TMR3DECL(int) TMR3Term(PVM pVM)
486{
487 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
488 if (pVM->tm.s.pTimer)
489 {
490 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
491 AssertRC(rc);
492 pVM->tm.s.pTimer = NULL;
493 }
494
495 return VINF_SUCCESS;
496}
497
498
499/**
500 * The VM is being reset.
501 *
502 * For the TM component this means that a rescheduling is preformed,
503 * the FF is cleared and but without running the queues. We'll have to
504 * check if this makes sense or not, but it seems like a good idea now....
505 *
506 * @param pVM VM handle.
507 */
508TMR3DECL(void) TMR3Reset(PVM pVM)
509{
510 LogFlow(("TMR3Reset:\n"));
511 VM_ASSERT_EMT(pVM);
512
513 /*
514 * Process the queues.
515 */
516 for (int i = 0; i < TMCLOCK_MAX; i++)
517 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
518#ifdef VBOX_STRICT
519 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
520#endif
521 VM_FF_CLEAR(pVM, VM_FF_TIMER);
522}
523
524
525/**
526 * Resolve a builtin GC symbol.
527 * Called by PDM when loading or relocating GC modules.
528 *
529 * @returns VBox status
530 * @param pVM VM Handle.
531 * @param pszSymbol Symbol to resolv
532 * @param pGCPtrValue Where to store the symbol value.
533 * @remark This has to work before TMR3Relocate() is called.
534 */
535TMR3DECL(int) TMR3GetImportGC(PVM pVM, const char *pszSymbol, PRTGCPTR pGCPtrValue)
536{
537 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
538 *pGCPtrValue = MMHyperHC2GC(pVM, &pVM->tm.s.pvGIPGC);
539 //else if (..)
540 else
541 return VERR_SYMBOL_NOT_FOUND;
542 return VINF_SUCCESS;
543}
544
545
546/**
547 * Execute state save operation.
548 *
549 * @returns VBox status code.
550 * @param pVM VM Handle.
551 * @param pSSM SSM operation handle.
552 */
553static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
554{
555 LogFlow(("tmR3Save:\n"));
556 Assert(!pVM->tm.s.fTSCTicking);
557 Assert(!pVM->tm.s.fVirtualTicking);
558 Assert(!pVM->tm.s.fVirtualSyncTicking);
559
560 /*
561 * Save the virtual clocks.
562 */
563 /* the virtual clock. */
564 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
565 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
566
567 /* the virtual timer synchronous clock. */
568 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
569 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncOffset);
570 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
571 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
572
573 /* real time clock */
574 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
575
576 /* the cpu tick clock. */
577 SSMR3PutU64(pSSM, TMCpuTickGet(pVM));
578 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
579}
580
581
582/**
583 * Execute state load operation.
584 *
585 * @returns VBox status code.
586 * @param pVM VM Handle.
587 * @param pSSM SSM operation handle.
588 * @param u32Version Data layout version.
589 */
590static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
591{
592 LogFlow(("tmR3Load:\n"));
593 Assert(!pVM->tm.s.fTSCTicking);
594 Assert(!pVM->tm.s.fVirtualTicking);
595 Assert(!pVM->tm.s.fVirtualSyncTicking);
596
597 /*
598 * Validate version.
599 */
600 if (u32Version != TM_SAVED_STATE_VERSION)
601 {
602 Log(("tmR3Load: Invalid version u32Version=%d!\n", u32Version));
603 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
604 }
605
606 /*
607 * Load the virtual clock.
608 */
609 pVM->tm.s.fVirtualTicking = false;
610 /* the virtual clock. */
611 uint64_t u64Hz;
612 int rc = SSMR3GetU64(pSSM, &u64Hz);
613 if (VBOX_FAILURE(rc))
614 return rc;
615 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
616 {
617 AssertMsgFailed(("The virtual clock frequency differs! Saved: %RU64 Binary: %RU64\n",
618 u64Hz, TMCLOCK_FREQ_VIRTUAL));
619 return VERR_SSM_VIRTUAL_CLOCK_HZ;
620 }
621 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
622 pVM->tm.s.u64VirtualOffset = 0;
623
624 /* the virtual timer synchronous clock. */
625 pVM->tm.s.fVirtualSyncTicking = false;
626 SSMR3GetU64(pSSM, &pVM->tm.s.u64VirtualSync);
627 uint64_t u64;
628 SSMR3GetU64(pSSM, &u64);
629 pVM->tm.s.u64VirtualSyncOffset = u64;
630 SSMR3GetU64(pSSM, &u64);
631 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
632 bool f;
633 SSMR3GetBool(pSSM, &f);
634 pVM->tm.s.fVirtualSyncCatchUp = f;
635
636 /* the real clock */
637 rc = SSMR3GetU64(pSSM, &u64Hz);
638 if (VBOX_FAILURE(rc))
639 return rc;
640 if (u64Hz != TMCLOCK_FREQ_REAL)
641 {
642 AssertMsgFailed(("The real clock frequency differs! Saved: %RU64 Binary: %RU64\n",
643 u64Hz, TMCLOCK_FREQ_REAL));
644 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
645 }
646
647 /* the cpu tick clock. */
648 pVM->tm.s.fTSCTicking = false;
649 SSMR3GetU64(pSSM, &pVM->tm.s.u64TSC);
650 rc = SSMR3GetU64(pSSM, &u64Hz);
651 if (VBOX_FAILURE(rc))
652 return rc;
653 if (pVM->tm.s.fTSCUseRealTSC)
654 pVM->tm.s.u64TSCOffset = 0; /** @todo TSC restore stuff and HWACC. */
655 else
656 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
657 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
658 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
659
660 /*
661 * Make sure timers get rescheduled immediately.
662 */
663 VM_FF_SET(pVM, VM_FF_TIMER);
664
665 return VINF_SUCCESS;
666}
667
668
669/** @todo doc */
670static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERHC ppTimer)
671{
672 VM_ASSERT_EMT(pVM);
673
674 /*
675 * Allocate the timer.
676 */
677 PTMTIMERHC pTimer = NULL;
678 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
679 {
680 pTimer = pVM->tm.s.pFree;
681 pVM->tm.s.pFree = pTimer->pBigNext;
682 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
683 }
684
685 if (!pTimer)
686 {
687 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
688 if (VBOX_FAILURE(rc))
689 return rc;
690 Log3(("TM: Allocated new timer %p\n", pTimer));
691 }
692
693 /*
694 * Initialize it.
695 */
696 pTimer->u64Expire = 0;
697 pTimer->enmClock = enmClock;
698 pTimer->pVMR3 = pVM;
699 pTimer->pVMR0 = (PVMR0)pVM->pVMHC; /// @todo pTimer->pVMR0 = pVM->pVMR0;
700 pTimer->pVMGC = pVM->pVMGC;
701 pTimer->enmState = TMTIMERSTATE_STOPPED;
702 pTimer->offScheduleNext = 0;
703 pTimer->offNext = 0;
704 pTimer->offPrev = 0;
705 pTimer->pszDesc = pszDesc;
706
707 /* insert into the list of created timers. */
708 pTimer->pBigPrev = NULL;
709 pTimer->pBigNext = pVM->tm.s.pCreated;
710 pVM->tm.s.pCreated = pTimer;
711 if (pTimer->pBigNext)
712 pTimer->pBigNext->pBigPrev = pTimer;
713#ifdef VBOX_STRICT
714 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
715#endif
716
717 *ppTimer = pTimer;
718 return VINF_SUCCESS;
719}
720
721
722/**
723 * Creates a device timer.
724 *
725 * @returns VBox status.
726 * @param pVM The VM to create the timer in.
727 * @param pDevIns Device instance.
728 * @param enmClock The clock to use on this timer.
729 * @param pfnCallback Callback function.
730 * @param pszDesc Pointer to description string which must stay around
731 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
732 * @param ppTimer Where to store the timer on success.
733 */
734TMR3DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, const char *pszDesc, PPTMTIMERHC ppTimer)
735{
736 /*
737 * Allocate and init stuff.
738 */
739 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
740 if (VBOX_SUCCESS(rc))
741 {
742 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
743 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
744 (*ppTimer)->u.Dev.pDevIns = pDevIns;
745 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
746 }
747
748 return rc;
749}
750
751
752/**
753 * Creates a driver timer.
754 *
755 * @returns VBox status.
756 * @param pVM The VM to create the timer in.
757 * @param pDrvIns Driver instance.
758 * @param enmClock The clock to use on this timer.
759 * @param pfnCallback Callback function.
760 * @param pszDesc Pointer to description string which must stay around
761 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
762 * @param ppTimer Where to store the timer on success.
763 */
764TMR3DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, const char *pszDesc, PPTMTIMERHC ppTimer)
765{
766 /*
767 * Allocate and init stuff.
768 */
769 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
770 if (VBOX_SUCCESS(rc))
771 {
772 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
773 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
774 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
775 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
776 }
777
778 return rc;
779}
780
781
782/**
783 * Creates an internal timer.
784 *
785 * @returns VBox status.
786 * @param pVM The VM to create the timer in.
787 * @param enmClock The clock to use on this timer.
788 * @param pfnCallback Callback function.
789 * @param pvUser User argument to be passed to the callback.
790 * @param pszDesc Pointer to description string which must stay around
791 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
792 * @param ppTimer Where to store the timer on success.
793 */
794TMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERHC ppTimer)
795{
796 /*
797 * Allocate and init stuff.
798 */
799 PTMTIMER pTimer;
800 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
801 if (VBOX_SUCCESS(rc))
802 {
803 pTimer->enmType = TMTIMERTYPE_INTERNAL;
804 pTimer->u.Internal.pfnTimer = pfnCallback;
805 pTimer->u.Internal.pvUser = pvUser;
806 *ppTimer = pTimer;
807 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
808 }
809
810 return rc;
811}
812
813/**
814 * Creates an external timer.
815 *
816 * @returns Timer handle on success.
817 * @returns NULL on failure.
818 * @param pVM The VM to create the timer in.
819 * @param enmClock The clock to use on this timer.
820 * @param pfnCallback Callback function.
821 * @param pvUser User argument.
822 * @param pszDesc Pointer to description string which must stay around
823 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
824 */
825TMR3DECL(PTMTIMERHC) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
826{
827 /*
828 * Allocate and init stuff.
829 */
830 PTMTIMERHC pTimer;
831 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
832 if (VBOX_SUCCESS(rc))
833 {
834 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
835 pTimer->u.External.pfnTimer = pfnCallback;
836 pTimer->u.External.pvUser = pvUser;
837 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
838 return pTimer;
839 }
840
841 return NULL;
842}
843
844
845/**
846 * Destroy all timers owned by a device.
847 *
848 * @returns VBox status.
849 * @param pVM VM handle.
850 * @param pDevIns Device which timers should be destroyed.
851 */
852TMR3DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
853{
854 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
855 if (!pDevIns)
856 return VERR_INVALID_PARAMETER;
857
858 PTMTIMER pCur = pVM->tm.s.pCreated;
859 while (pCur)
860 {
861 PTMTIMER pDestroy = pCur;
862 pCur = pDestroy->pBigNext;
863 if ( pDestroy->enmType == TMTIMERTYPE_DEV
864 && pDestroy->u.Dev.pDevIns == pDevIns)
865 {
866 int rc = TMTimerDestroy(pDestroy);
867 AssertRC(rc);
868 }
869 }
870 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
871 return VINF_SUCCESS;
872}
873
874
875/**
876 * Destroy all timers owned by a driver.
877 *
878 * @returns VBox status.
879 * @param pVM VM handle.
880 * @param pDrvIns Driver which timers should be destroyed.
881 */
882TMR3DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
883{
884 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
885 if (!pDrvIns)
886 return VERR_INVALID_PARAMETER;
887
888 PTMTIMER pCur = pVM->tm.s.pCreated;
889 while (pCur)
890 {
891 PTMTIMER pDestroy = pCur;
892 pCur = pDestroy->pBigNext;
893 if ( pDestroy->enmType == TMTIMERTYPE_DRV
894 && pDestroy->u.Drv.pDrvIns == pDrvIns)
895 {
896 int rc = TMTimerDestroy(pDestroy);
897 AssertRC(rc);
898 }
899 }
900 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
901 return VINF_SUCCESS;
902}
903
904
905/**
906 * Checks if a queue has a pending timer.
907 *
908 * @returns true if it has a pending timer.
909 * @returns false is no pending timer.
910 *
911 * @param pVM The VM handle.
912 * @param enmClock The queue.
913 */
914DECLINLINE(bool) tmR3HasPending(PVM pVM, TMCLOCK enmClock)
915{
916 const uint64_t u64Expire = pVM->tm.s.CTXALLSUFF(paTimerQueues)[enmClock].u64Expire;
917 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
918}
919
920
921/**
922 * Schedulation timer callback.
923 *
924 * @param pTimer Timer handle.
925 * @param pvUser VM handle.
926 * @remark We cannot do the scheduling and queues running from a timer handler
927 * since it's not executing in EMT, and even if it was it would be async
928 * and we wouldn't know the state of the affairs.
929 * So, we'll just raise the timer FF and force any REM execution to exit.
930 */
931static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser)
932{
933 PVM pVM = (PVM)pvUser;
934 AssertCompile(TMCLOCK_MAX == 4);
935#ifdef DEBUG_Sander /* very annoying, keep it private. */
936 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
937 Log(("tmR3TimerCallback: timer event still pending!!\n"));
938#endif
939 if ( !VM_FF_ISSET(pVM, VM_FF_TIMER)
940 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule
941 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
942 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
943 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
944 || tmR3HasPending(pVM, TMCLOCK_VIRTUAL_SYNC)
945 || tmR3HasPending(pVM, TMCLOCK_VIRTUAL)
946 || tmR3HasPending(pVM, TMCLOCK_REAL)
947 || tmR3HasPending(pVM, TMCLOCK_TSC)
948 )
949 && !VM_FF_ISSET(pVM, VM_FF_TIMER)
950 )
951 {
952 VM_FF_SET(pVM, VM_FF_TIMER);
953 REMR3NotifyTimerPending(pVM);
954 VMR3NotifyFF(pVM, true);
955 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
956 }
957}
958
959
960/**
961 * Schedules and runs any pending timers.
962 *
963 * This is normally called from a forced action handler in EMT.
964 *
965 * @param pVM The VM to run the timers for.
966 */
967TMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
968{
969 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
970 Log2(("TMR3TimerQueuesDo:\n"));
971
972 /*
973 * Process the queues.
974 */
975 AssertCompile(TMCLOCK_MAX == 4);
976
977 /* TMCLOCK_VIRTUAL */
978 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesSchedule, s1);
979 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
980 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s1);
981 STAM_PROFILE_ADV_START(&pVM->tm.s.StatDoQueuesRun, r1);
982 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
983 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r1);
984
985 /* TMCLOCK_VIRTUAL_SYNC */
986 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s1);
987 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
988 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s2);
989 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r1);
990 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
991 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r2);
992
993 /* TMCLOCK_REAL */
994 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s2);
995 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
996 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesSchedule, s3);
997 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r2);
998 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
999 STAM_PROFILE_ADV_SUSPEND(&pVM->tm.s.StatDoQueuesRun, r3);
1000
1001 /* TMCLOCK_TSC */
1002 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesSchedule, s3);
1003 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1004 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesSchedule, s3);
1005 STAM_PROFILE_ADV_RESUME(&pVM->tm.s.StatDoQueuesRun, r3);
1006 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC]);
1007 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatDoQueuesRun, r3);
1008
1009 /* done. */
1010 VM_FF_CLEAR(pVM, VM_FF_TIMER);
1011
1012#ifdef VBOX_STRICT
1013 /* check that we didn't screwup. */
1014 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1015#endif
1016
1017 Log2(("TMR3TimerQueuesDo: returns void\n"));
1018 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1019}
1020
1021
1022/**
1023 * Schedules and runs any pending times in the specified queue.
1024 *
1025 * This is normally called from a forced action handler in EMT.
1026 *
1027 * @param pVM The VM to run the timers for.
1028 * @param pQueue The queue to run.
1029 */
1030static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1031{
1032 VM_ASSERT_EMT(pVM);
1033
1034 /*
1035 * Run timers.
1036 *
1037 * We check the clock once and run all timers which are ACTIVE
1038 * and have an expire time less or equal to the time we read.
1039 *
1040 * N.B. A generic unlink must be applied since other threads
1041 * are allowed to mess with any active timer at any time.
1042 * However, we only allow EMT to handle EXPIRED_PENDING
1043 * timers, thus enabling the timer handler function to
1044 * arm the timer again.
1045 */
1046 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1047 if (!pNext)
1048 return;
1049 /** @todo deal with the VIRTUAL_SYNC pausing and catch calcs ++ */
1050 uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1051 while (pNext && pNext->u64Expire <= u64Now)
1052 {
1053 PTMTIMER pTimer = pNext;
1054 pNext = TMTIMER_GET_NEXT(pTimer);
1055 Log2(("tmR3TimerQueueRun: pTimer=%p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1056 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1057 bool fRc;
1058 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED, TMTIMERSTATE_ACTIVE, fRc);
1059 if (fRc)
1060 {
1061 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1062
1063 /* unlink */
1064 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1065 if (pPrev)
1066 TMTIMER_SET_NEXT(pPrev, pNext);
1067 else
1068 {
1069 TMTIMER_SET_HEAD(pQueue, pNext);
1070 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1071 }
1072 if (pNext)
1073 TMTIMER_SET_PREV(pNext, pPrev);
1074 pTimer->offNext = 0;
1075 pTimer->offPrev = 0;
1076
1077
1078 /* fire */
1079 switch (pTimer->enmType)
1080 {
1081 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer); break;
1082 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer); break;
1083 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
1084 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->u.External.pvUser); break;
1085 default:
1086 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1087 break;
1088 }
1089
1090 /* change the state if it wasn't changed already in the handler. */
1091 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED, fRc);
1092 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1093 }
1094 } /* run loop */
1095}
1096
1097
1098/**
1099 * Saves the state of a timer to a saved state.
1100 *
1101 * @returns VBox status.
1102 * @param pTimer Timer to save.
1103 * @param pSSM Save State Manager handle.
1104 */
1105TMR3DECL(int) TMR3TimerSave(PTMTIMERHC pTimer, PSSMHANDLE pSSM)
1106{
1107 LogFlow(("TMR3TimerSave: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1108 switch (pTimer->enmState)
1109 {
1110 case TMTIMERSTATE_STOPPED:
1111 case TMTIMERSTATE_PENDING_STOP:
1112 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1113 return SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_STOP);
1114
1115 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1116 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1117 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
1118 if (!RTThreadYield())
1119 RTThreadSleep(1);
1120 /* fall thru */
1121 case TMTIMERSTATE_ACTIVE:
1122 case TMTIMERSTATE_PENDING_SCHEDULE:
1123 case TMTIMERSTATE_PENDING_RESCHEDULE:
1124 SSMR3PutU8(pSSM, (uint8_t)TMTIMERSTATE_PENDING_SCHEDULE);
1125 return SSMR3PutU64(pSSM, pTimer->u64Expire);
1126
1127 case TMTIMERSTATE_EXPIRED:
1128 case TMTIMERSTATE_PENDING_DESTROY:
1129 case TMTIMERSTATE_PENDING_STOP_DESTROY:
1130 case TMTIMERSTATE_FREE:
1131 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
1132 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
1133 }
1134
1135 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
1136 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
1137}
1138
1139
1140/**
1141 * Loads the state of a timer from a saved state.
1142 *
1143 * @returns VBox status.
1144 * @param pTimer Timer to restore.
1145 * @param pSSM Save State Manager handle.
1146 */
1147TMR3DECL(int) TMR3TimerLoad(PTMTIMERHC pTimer, PSSMHANDLE pSSM)
1148{
1149 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
1150 LogFlow(("TMR3TimerLoad: pTimer=%p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
1151
1152 /*
1153 * Load the state and validate it.
1154 */
1155 uint8_t u8State;
1156 int rc = SSMR3GetU8(pSSM, &u8State);
1157 if (VBOX_FAILURE(rc))
1158 return rc;
1159 TMTIMERSTATE enmState = (TMTIMERSTATE)u8State;
1160 if ( enmState != TMTIMERSTATE_PENDING_STOP
1161 && enmState != TMTIMERSTATE_PENDING_SCHEDULE
1162 && enmState != TMTIMERSTATE_PENDING_STOP_SCHEDULE)
1163 {
1164 AssertMsgFailed(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1165 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
1166 }
1167
1168 if (enmState == TMTIMERSTATE_PENDING_SCHEDULE)
1169 {
1170 /*
1171 * Load the expire time.
1172 */
1173 uint64_t u64Expire;
1174 rc = SSMR3GetU64(pSSM, &u64Expire);
1175 if (VBOX_FAILURE(rc))
1176 return rc;
1177
1178 /*
1179 * Set it.
1180 */
1181 Log(("enmState=%d %s u64Expire=%llu\n", enmState, tmTimerState(enmState), u64Expire));
1182 rc = TMTimerSet(pTimer, u64Expire);
1183 }
1184 else
1185 {
1186 /*
1187 * Stop it.
1188 */
1189 Log(("enmState=%d %s\n", enmState, tmTimerState(enmState)));
1190 rc = TMTimerStop(pTimer);
1191 }
1192
1193 /*
1194 * On failure set SSM status.
1195 */
1196 if (VBOX_FAILURE(rc))
1197 rc = SSMR3HandleSetStatus(pSSM, rc);
1198 return rc;
1199}
1200
1201
1202/**
1203 * Display all timers.
1204 *
1205 * @param pVM VM Handle.
1206 * @param pHlp The info helpers.
1207 * @param pszArgs Arguments, ignored.
1208 */
1209static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1210{
1211 NOREF(pszArgs);
1212 pHlp->pfnPrintf(pHlp,
1213 "Timers (pVM=%p)\n"
1214 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1215 pVM,
1216 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1217 sizeof(int32_t) * 2, "offNext ",
1218 sizeof(int32_t) * 2, "offPrev ",
1219 sizeof(int32_t) * 2, "offSched ",
1220 "Time",
1221 "Expire",
1222 "State");
1223 for (PTMTIMERHC pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1224 {
1225 pHlp->pfnPrintf(pHlp,
1226 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1227 pTimer,
1228 pTimer->offNext,
1229 pTimer->offPrev,
1230 pTimer->offScheduleNext,
1231 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
1232 TMTimerGet(pTimer),
1233 pTimer->u64Expire,
1234 tmTimerState(pTimer->enmState),
1235 pTimer->pszDesc);
1236 }
1237}
1238
1239
1240/**
1241 * Display all active timers.
1242 *
1243 * @param pVM VM Handle.
1244 * @param pHlp The info helpers.
1245 * @param pszArgs Arguments, ignored.
1246 */
1247static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1248{
1249 NOREF(pszArgs);
1250 pHlp->pfnPrintf(pHlp,
1251 "Active Timers (pVM=%p)\n"
1252 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
1253 pVM,
1254 sizeof(RTR3PTR) * 2, "pTimerR3 ",
1255 sizeof(int32_t) * 2, "offNext ",
1256 sizeof(int32_t) * 2, "offPrev ",
1257 sizeof(int32_t) * 2, "offSched ",
1258 "Time",
1259 "Expire",
1260 "State");
1261 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
1262 {
1263 for (PTMTIMERHC pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
1264 pTimer;
1265 pTimer = TMTIMER_GET_NEXT(pTimer))
1266 {
1267 pHlp->pfnPrintf(pHlp,
1268 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
1269 pTimer,
1270 pTimer->offNext,
1271 pTimer->offPrev,
1272 pTimer->offScheduleNext,
1273 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
1274 TMTimerGet(pTimer),
1275 pTimer->u64Expire,
1276 tmTimerState(pTimer->enmState),
1277 pTimer->pszDesc);
1278 }
1279 }
1280}
1281
1282
1283/**
1284 * Display all clocks.
1285 *
1286 * @param pVM VM Handle.
1287 * @param pHlp The info helpers.
1288 * @param pszArgs Arguments, ignored.
1289 */
1290static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
1291{
1292 NOREF(pszArgs);
1293
1294 /* TSC */
1295 uint64_t u64 = TMCpuTickGet(pVM);
1296 pHlp->pfnPrintf(pHlp,
1297 "Cpu Tick: %#RX64 (%RU64) %RU64Hz %s%s",
1298 u64, u64, TMCpuTicksPerSecond(pVM),
1299 pVM->tm.s.fTSCTicking ? "ticking" : "paused",
1300 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
1301 if (pVM->tm.s.fTSCUseRealTSC)
1302 {
1303 pHlp->pfnPrintf(pHlp, " - real tsc");
1304 if (pVM->tm.s.u64TSCOffset)
1305 pHlp->pfnPrintf(pHlp, "\n offset %#RX64", pVM->tm.s.u64TSCOffset);
1306 }
1307 else
1308 pHlp->pfnPrintf(pHlp, " - virtual clock");
1309 pHlp->pfnPrintf(pHlp, "\n");
1310
1311 /* virtual */
1312 u64 = TMVirtualGet(pVM);
1313 pHlp->pfnPrintf(pHlp,
1314 " Virtual: %#RX64 (%RU64) %RU64Hz %s",
1315 u64, u64, TMVirtualGetFreq(pVM),
1316 pVM->tm.s.fVirtualTicking ? "ticking" : "paused");
1317 if (pVM->tm.s.fVirtualWarpDrive)
1318 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
1319 pHlp->pfnPrintf(pHlp, "\n");
1320
1321 /* virtual sync */
1322 u64 = TMVirtualGetSync(pVM);
1323 pHlp->pfnPrintf(pHlp,
1324 "VirtSync: %#RX64 (%RU64) %s%s",
1325 u64, u64,
1326 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
1327 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
1328 if (pVM->tm.s.u64VirtualSyncOffset)
1329 pHlp->pfnPrintf(pHlp, "\n offset %#RX64", pVM->tm.s.u64VirtualSyncOffset);
1330 pHlp->pfnPrintf(pHlp, "\n");
1331
1332 /* real */
1333 u64 = TMRealGet(pVM);
1334 pHlp->pfnPrintf(pHlp,
1335 " Real: %#RX64 (%RU64) %RU64Hz\n",
1336 u64, u64, TMRealGetFreq(pVM));
1337}
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