VirtualBox

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

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

Virtualize the TSC.

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