VirtualBox

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

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

Implementing timer syncrhonous virtual clock.

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