VirtualBox

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

Last change on this file since 30581 was 30581, checked in by vboxsync, 14 years ago

TM: Added simple CPU time accounting. Accessible thru the statistics and TMR3GetCpuLoadTimes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 120.4 KB
Line 
1/* $Id: TM.cpp 30581 2010-07-02 16:02:57Z vboxsync $ */
2/** @file
3 * TM - Time Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Oracle Corporation
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 (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @page pg_tm TM - The Time Manager
19 *
20 * The Time Manager abstracts the CPU clocks and manages timers used by the VMM,
21 * device and drivers.
22 *
23 * @see grp_tm
24 *
25 *
26 * @section sec_tm_clocks Clocks
27 *
28 * There are currently 4 clocks:
29 * - Virtual (guest).
30 * - Synchronous virtual (guest).
31 * - CPU Tick (TSC) (guest). Only current use is rdtsc emulation. Usually a
32 * function of the virtual clock.
33 * - Real (host). This is only used for display updates atm.
34 *
35 * The most important clocks are the three first ones and of these the second is
36 * the most interesting.
37 *
38 *
39 * The synchronous virtual clock is tied to the virtual clock except that it
40 * will take into account timer delivery lag caused by host scheduling. It will
41 * normally never advance beyond the head timer, and when lagging too far behind
42 * it will gradually speed up to catch up with the virtual clock. All devices
43 * implementing time sources accessible to and used by the guest is using this
44 * clock (for timers and other things). This ensures consistency between the
45 * time sources.
46 *
47 * The virtual clock is implemented as an offset to a monotonic, high
48 * resolution, wall clock. The current time source is using the RTTimeNanoTS()
49 * machinery based upon the Global Info Pages (GIP), that is, we're using TSC
50 * deltas (usually 10 ms) to fill the gaps between GIP updates. The result is
51 * a fairly high res clock that works in all contexts and on all hosts. The
52 * virtual clock is paused when the VM isn't in the running state.
53 *
54 * The CPU tick (TSC) is normally virtualized as a function of the synchronous
55 * virtual clock, where the frequency defaults to the host cpu frequency (as we
56 * measure it). In this mode it is possible to configure the frequency. Another
57 * (non-default) option is to use the raw unmodified host TSC values. And yet
58 * another, to tie it to time spent executing guest code. All these things are
59 * configurable should non-default behavior be desirable.
60 *
61 * The real clock is a monotonic clock (when available) with relatively low
62 * resolution, though this a bit host specific. Note that we're currently not
63 * servicing timers using the real clock when the VM is not running, this is
64 * simply because it has not been needed yet therefore not implemented.
65 *
66 *
67 * @subsection subsec_tm_timesync Guest Time Sync / UTC time
68 *
69 * Guest time syncing is primarily taken care of by the VMM device. The
70 * principle is very simple, the guest additions periodically asks the VMM
71 * device what the current UTC time is and makes adjustments accordingly.
72 *
73 * A complicating factor is that the synchronous virtual clock might be doing
74 * catchups and the guest perception is currently a little bit behind the world
75 * but it will (hopefully) be catching up soon as we're feeding timer interrupts
76 * at a slightly higher rate. Adjusting the guest clock to the current wall
77 * time in the real world would be a bad idea then because the guest will be
78 * advancing too fast and run ahead of world time (if the catchup works out).
79 * To solve this problem TM provides the VMM device with an UTC time source that
80 * gets adjusted with the current lag, so that when the guest eventually catches
81 * up the lag it will be showing correct real world time.
82 *
83 *
84 * @section sec_tm_timers Timers
85 *
86 * The timers can use any of the TM clocks described in the previous section.
87 * Each clock has its own scheduling facility, or timer queue if you like.
88 * There are a few factors which makes it a bit complex. First, there is the
89 * usual R0 vs R3 vs. RC thing. Then there are multiple threads, and then there
90 * is the timer thread that periodically checks whether any timers has expired
91 * without EMT noticing. On the API level, all but the create and save APIs
92 * must be mulithreaded. EMT will always run the timers.
93 *
94 * The design is using a doubly linked list of active timers which is ordered
95 * by expire date. This list is only modified by the EMT thread. Updates to
96 * the list are batched in a singly linked list, which is then processed by the
97 * EMT thread at the first opportunity (immediately, next time EMT modifies a
98 * timer on that clock, or next timer timeout). Both lists are offset based and
99 * all the elements are therefore allocated from the hyper heap.
100 *
101 * For figuring out when there is need to schedule and run timers TM will:
102 * - Poll whenever somebody queries the virtual clock.
103 * - Poll the virtual clocks from the EM and REM loops.
104 * - Poll the virtual clocks from trap exit path.
105 * - Poll the virtual clocks and calculate first timeout from the halt loop.
106 * - Employ a thread which periodically (100Hz) polls all the timer queues.
107 *
108 *
109 * @image html TMTIMER-Statechart-Diagram.gif
110 *
111 * @section sec_tm_timer Logging
112 *
113 * Level 2: Logs a most of the timer state transitions and queue servicing.
114 * Level 3: Logs a few oddments.
115 * Level 4: Logs TMCLOCK_VIRTUAL_SYNC catch-up events.
116 *
117 */
118
119/*******************************************************************************
120* Header Files *
121*******************************************************************************/
122#define LOG_GROUP LOG_GROUP_TM
123#include <VBox/tm.h>
124#include <VBox/vmm.h>
125#include <VBox/mm.h>
126#include <VBox/ssm.h>
127#include <VBox/dbgf.h>
128#include <VBox/rem.h>
129#include <VBox/pdmapi.h>
130#include <VBox/iom.h>
131#include "TMInternal.h"
132#include <VBox/vm.h>
133
134#include <VBox/pdmdev.h>
135#include <VBox/param.h>
136#include <VBox/err.h>
137
138#include <VBox/log.h>
139#include <iprt/asm.h>
140#include <iprt/asm-math.h>
141#include <iprt/asm-amd64-x86.h>
142#include <iprt/assert.h>
143#include <iprt/thread.h>
144#include <iprt/time.h>
145#include <iprt/timer.h>
146#include <iprt/semaphore.h>
147#include <iprt/string.h>
148#include <iprt/env.h>
149
150
151/*******************************************************************************
152* Defined Constants And Macros *
153*******************************************************************************/
154/** The current saved state version.*/
155#define TM_SAVED_STATE_VERSION 3
156
157
158/*******************************************************************************
159* Internal Functions *
160*******************************************************************************/
161static bool tmR3HasFixedTSC(PVM pVM);
162static uint64_t tmR3CalibrateTSC(PVM pVM);
163static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM);
164static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
165static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
166static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue);
167static void tmR3TimerQueueRunVirtualSync(PVM pVM);
168static DECLCALLBACK(int) tmR3SetWarpDrive(PVM pVM, uint32_t u32Percent);
169static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
170static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
171static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
172
173
174/**
175 * Initializes the TM.
176 *
177 * @returns VBox status code.
178 * @param pVM The VM to operate on.
179 */
180VMM_INT_DECL(int) TMR3Init(PVM pVM)
181{
182 LogFlow(("TMR3Init:\n"));
183
184 /*
185 * Assert alignment and sizes.
186 */
187 AssertCompileMemberAlignment(VM, tm.s, 32);
188 AssertCompile(sizeof(pVM->tm.s) <= sizeof(pVM->tm.padding));
189 AssertCompileMemberAlignment(TM, TimerCritSect, 8);
190 AssertCompileMemberAlignment(TM, VirtualSyncLock, 8);
191
192 /*
193 * Init the structure.
194 */
195 void *pv;
196 int rc = MMHyperAlloc(pVM, sizeof(pVM->tm.s.paTimerQueuesR3[0]) * TMCLOCK_MAX, 0, MM_TAG_TM, &pv);
197 AssertRCReturn(rc, rc);
198 pVM->tm.s.paTimerQueuesR3 = (PTMTIMERQUEUE)pv;
199 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pv);
200 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pv);
201
202 pVM->tm.s.offVM = RT_OFFSETOF(VM, tm.s);
203 pVM->tm.s.idTimerCpu = pVM->cCpus - 1; /* The last CPU. */
204 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].enmClock = TMCLOCK_VIRTUAL;
205 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].u64Expire = INT64_MAX;
206 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].enmClock = TMCLOCK_VIRTUAL_SYNC;
207 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].u64Expire = INT64_MAX;
208 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].enmClock = TMCLOCK_REAL;
209 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].u64Expire = INT64_MAX;
210 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].enmClock = TMCLOCK_TSC;
211 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].u64Expire = INT64_MAX;
212
213
214 /*
215 * We directly use the GIP to calculate the virtual time. We map the
216 * the GIP into the guest context so we can do this calculation there
217 * as well and save costly world switches.
218 */
219 pVM->tm.s.pvGIPR3 = (void *)g_pSUPGlobalInfoPage;
220 AssertMsgReturn(pVM->tm.s.pvGIPR3, ("GIP support is now required!\n"), VERR_INTERNAL_ERROR);
221 RTHCPHYS HCPhysGIP;
222 rc = SUPR3GipGetPhys(&HCPhysGIP);
223 AssertMsgRCReturn(rc, ("Failed to get GIP physical address!\n"), rc);
224
225 RTGCPTR GCPtr;
226 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, NIL_RTR0PTR, HCPhysGIP, PAGE_SIZE, "GIP", &GCPtr);
227 if (RT_FAILURE(rc))
228 {
229 AssertMsgFailed(("Failed to map GIP into GC, rc=%Rrc!\n", rc));
230 return rc;
231 }
232 pVM->tm.s.pvGIPRC = GCPtr;
233 LogFlow(("TMR3Init: HCPhysGIP=%RHp at %RRv\n", HCPhysGIP, pVM->tm.s.pvGIPRC));
234 MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);
235
236 /* Check assumptions made in TMAllVirtual.cpp about the GIP update interval. */
237 if ( g_pSUPGlobalInfoPage->u32Magic == SUPGLOBALINFOPAGE_MAGIC
238 && g_pSUPGlobalInfoPage->u32UpdateIntervalNS >= 250000000 /* 0.25s */)
239 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
240 N_("The GIP update interval is too big. u32UpdateIntervalNS=%RU32 (u32UpdateHz=%RU32)"),
241 g_pSUPGlobalInfoPage->u32UpdateIntervalNS, g_pSUPGlobalInfoPage->u32UpdateHz);
242 LogRel(("TM: GIP - u32Mode=%d (%s) u32UpdateHz=%u\n", g_pSUPGlobalInfoPage->u32Mode,
243 g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC ? "SyncTSC"
244 : g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_ASYNC_TSC ? "AsyncTSC" : "Unknown",
245 g_pSUPGlobalInfoPage->u32UpdateHz));
246
247 /*
248 * Setup the VirtualGetRaw backend.
249 */
250 pVM->tm.s.VirtualGetRawDataR3.pu64Prev = &pVM->tm.s.u64VirtualRawPrev;
251 pVM->tm.s.VirtualGetRawDataR3.pfnBad = tmVirtualNanoTSBad;
252 pVM->tm.s.VirtualGetRawDataR3.pfnRediscover = tmVirtualNanoTSRediscover;
253 if (ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2)
254 {
255 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
256 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceSync;
257 else
258 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceAsync;
259 }
260 else
261 {
262 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
263 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacySync;
264 else
265 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacyAsync;
266 }
267
268 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
269 pVM->tm.s.VirtualGetRawDataR0.pu64Prev = MMHyperR3ToR0(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
270 AssertReturn(pVM->tm.s.VirtualGetRawDataR0.pu64Prev, VERR_INTERNAL_ERROR);
271 /* The rest is done in TMR3InitFinalize since it's too early to call PDM. */
272
273 /*
274 * Init the locks.
275 */
276 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.TimerCritSect, RT_SRC_POS, "TM Timer Lock");
277 if (RT_FAILURE(rc))
278 return rc;
279 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.VirtualSyncLock, RT_SRC_POS, "TM VirtualSync Lock");
280 if (RT_FAILURE(rc))
281 return rc;
282
283 /*
284 * Get our CFGM node, create it if necessary.
285 */
286 PCFGMNODE pCfgHandle = CFGMR3GetChild(CFGMR3GetRoot(pVM), "TM");
287 if (!pCfgHandle)
288 {
289 rc = CFGMR3InsertNode(CFGMR3GetRoot(pVM), "TM", &pCfgHandle);
290 AssertRCReturn(rc, rc);
291 }
292
293 /*
294 * Determin the TSC configuration and frequency.
295 */
296 /* mode */
297 /** @cfgm{/TM/TSCVirtualized,bool,true}
298 * Use a virtualize TSC, i.e. trap all TSC access. */
299 rc = CFGMR3QueryBool(pCfgHandle, "TSCVirtualized", &pVM->tm.s.fTSCVirtualized);
300 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
301 pVM->tm.s.fTSCVirtualized = true; /* trap rdtsc */
302 else if (RT_FAILURE(rc))
303 return VMSetError(pVM, rc, RT_SRC_POS,
304 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
305
306 /* source */
307 /** @cfgm{/TM/UseRealTSC,bool,false}
308 * Use the real TSC as time source for the TSC instead of the synchronous
309 * virtual clock (false, default). */
310 rc = CFGMR3QueryBool(pCfgHandle, "UseRealTSC", &pVM->tm.s.fTSCUseRealTSC);
311 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
312 pVM->tm.s.fTSCUseRealTSC = false; /* use virtual time */
313 else if (RT_FAILURE(rc))
314 return VMSetError(pVM, rc, RT_SRC_POS,
315 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
316 if (!pVM->tm.s.fTSCUseRealTSC)
317 pVM->tm.s.fTSCVirtualized = true;
318
319 /* TSC reliability */
320 /** @cfgm{/TM/MaybeUseOffsettedHostTSC,bool,detect}
321 * Whether the CPU has a fixed TSC rate and may be used in offsetted mode with
322 * VT-x/AMD-V execution. This is autodetected in a very restrictive way by
323 * default. */
324 rc = CFGMR3QueryBool(pCfgHandle, "MaybeUseOffsettedHostTSC", &pVM->tm.s.fMaybeUseOffsettedHostTSC);
325 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
326 {
327 if (!pVM->tm.s.fTSCUseRealTSC)
328 pVM->tm.s.fMaybeUseOffsettedHostTSC = tmR3HasFixedTSC(pVM);
329 else
330 pVM->tm.s.fMaybeUseOffsettedHostTSC = true;
331 }
332
333 /** @cfgm{TM/TSCTicksPerSecond, uint32_t, Current TSC frequency from GIP}
334 * The number of TSC ticks per second (i.e. the TSC frequency). This will
335 * override TSCUseRealTSC, TSCVirtualized and MaybeUseOffsettedHostTSC.
336 */
337 rc = CFGMR3QueryU64(pCfgHandle, "TSCTicksPerSecond", &pVM->tm.s.cTSCTicksPerSecond);
338 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
339 {
340 pVM->tm.s.cTSCTicksPerSecond = tmR3CalibrateTSC(pVM);
341 if ( !pVM->tm.s.fTSCUseRealTSC
342 && pVM->tm.s.cTSCTicksPerSecond >= _4G)
343 {
344 pVM->tm.s.cTSCTicksPerSecond = _4G - 1; /* (A limitation of our math code) */
345 pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
346 }
347 }
348 else if (RT_FAILURE(rc))
349 return VMSetError(pVM, rc, RT_SRC_POS,
350 N_("Configuration error: Failed to querying uint64_t value \"TSCTicksPerSecond\""));
351 else if ( pVM->tm.s.cTSCTicksPerSecond < _1M
352 || pVM->tm.s.cTSCTicksPerSecond >= _4G)
353 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
354 N_("Configuration error: \"TSCTicksPerSecond\" = %RI64 is not in the range 1MHz..4GHz-1"),
355 pVM->tm.s.cTSCTicksPerSecond);
356 else
357 {
358 pVM->tm.s.fTSCUseRealTSC = pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
359 pVM->tm.s.fTSCVirtualized = true;
360 }
361
362 /** @cfgm{TM/TSCTiedToExecution, bool, false}
363 * Whether the TSC should be tied to execution. This will exclude most of the
364 * virtualization overhead, but will by default include the time spent in the
365 * halt state (see TM/TSCNotTiedToHalt). This setting will override all other
366 * TSC settings except for TSCTicksPerSecond and TSCNotTiedToHalt, which should
367 * be used avoided or used with great care. Note that this will only work right
368 * together with VT-x or AMD-V, and with a single virtual CPU. */
369 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCTiedToExecution", &pVM->tm.s.fTSCTiedToExecution, false);
370 if (RT_FAILURE(rc))
371 return VMSetError(pVM, rc, RT_SRC_POS,
372 N_("Configuration error: Failed to querying bool value \"TSCTiedToExecution\""));
373 if (pVM->tm.s.fTSCTiedToExecution)
374 {
375 /* tied to execution, override all other settings. */
376 pVM->tm.s.fTSCVirtualized = true;
377 pVM->tm.s.fTSCUseRealTSC = true;
378 pVM->tm.s.fMaybeUseOffsettedHostTSC = false;
379 }
380
381 /** @cfgm{TM/TSCNotTiedToHalt, bool, true}
382 * For overriding the default of TM/TSCTiedToExecution, i.e. set this to false
383 * to make the TSC freeze during HLT. */
384 rc = CFGMR3QueryBoolDef(pCfgHandle, "TSCNotTiedToHalt", &pVM->tm.s.fTSCNotTiedToHalt, false);
385 if (RT_FAILURE(rc))
386 return VMSetError(pVM, rc, RT_SRC_POS,
387 N_("Configuration error: Failed to querying bool value \"TSCNotTiedToHalt\""));
388
389 /* setup and report */
390 if (pVM->tm.s.fTSCVirtualized)
391 CPUMR3SetCR4Feature(pVM, X86_CR4_TSD, ~X86_CR4_TSD);
392 else
393 CPUMR3SetCR4Feature(pVM, 0, ~X86_CR4_TSD);
394 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%'RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool\n"
395 "TM: fMaybeUseOffsettedHostTSC=%RTbool TSCTiedToExecution=%RTbool TSCNotTiedToHalt=%RTbool\n",
396 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC,
397 pVM->tm.s.fMaybeUseOffsettedHostTSC, pVM->tm.s.fTSCTiedToExecution, pVM->tm.s.fTSCNotTiedToHalt));
398
399 /*
400 * Configure the timer synchronous virtual time.
401 */
402 /** @cfgm{TM/ScheduleSlack, uint32_t, ns, 0, UINT32_MAX, 100000}
403 * Scheduling slack when processing timers. */
404 rc = CFGMR3QueryU32(pCfgHandle, "ScheduleSlack", &pVM->tm.s.u32VirtualSyncScheduleSlack);
405 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
406 pVM->tm.s.u32VirtualSyncScheduleSlack = 100000; /* 0.100ms (ASSUMES virtual time is nanoseconds) */
407 else if (RT_FAILURE(rc))
408 return VMSetError(pVM, rc, RT_SRC_POS,
409 N_("Configuration error: Failed to querying 32-bit integer value \"ScheduleSlack\""));
410
411 /** @cfgm{TM/CatchUpStopThreshold, uint64_t, ns, 0, UINT64_MAX, 500000}
412 * When to stop a catch-up, considering it successful. */
413 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStopThreshold", &pVM->tm.s.u64VirtualSyncCatchUpStopThreshold);
414 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
415 pVM->tm.s.u64VirtualSyncCatchUpStopThreshold = 500000; /* 0.5ms */
416 else if (RT_FAILURE(rc))
417 return VMSetError(pVM, rc, RT_SRC_POS,
418 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpStopThreshold\""));
419
420 /** @cfgm{TM/CatchUpGiveUpThreshold, uint64_t, ns, 0, UINT64_MAX, 60000000000}
421 * When to give up a catch-up attempt. */
422 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpGiveUpThreshold", &pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold);
423 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
424 pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold = UINT64_C(60000000000); /* 60 sec */
425 else if (RT_FAILURE(rc))
426 return VMSetError(pVM, rc, RT_SRC_POS,
427 N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpGiveUpThreshold\""));
428
429
430 /** @cfgm{TM/CatchUpPrecentage[0..9], uint32_t, %, 1, 2000, various}
431 * The catch-up percent for a given period. */
432 /** @cfgm{TM/CatchUpStartThreshold[0..9], uint64_t, ns, 0, UINT64_MAX,
433 * The catch-up period threshold, or if you like, when a period starts. */
434#define TM_CFG_PERIOD(iPeriod, DefStart, DefPct) \
435 do \
436 { \
437 uint64_t u64; \
438 rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStartThreshold" #iPeriod, &u64); \
439 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
440 u64 = UINT64_C(DefStart); \
441 else if (RT_FAILURE(rc)) \
442 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpThreshold" #iPeriod "\"")); \
443 if ( (iPeriod > 0 && u64 <= pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod - 1].u64Start) \
444 || u64 >= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold) \
445 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Configuration error: Invalid start of period #" #iPeriod ": %'RU64"), u64); \
446 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u64Start = u64; \
447 rc = CFGMR3QueryU32(pCfgHandle, "CatchUpPrecentage" #iPeriod, &pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage); \
448 if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
449 pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage = (DefPct); \
450 else if (RT_FAILURE(rc)) \
451 return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 32-bit integer value \"CatchUpPrecentage" #iPeriod "\"")); \
452 } while (0)
453 /* This needs more tuning. Not sure if we really need so many period and be so gentle. */
454 TM_CFG_PERIOD(0, 750000, 5); /* 0.75ms at 1.05x */
455 TM_CFG_PERIOD(1, 1500000, 10); /* 1.50ms at 1.10x */
456 TM_CFG_PERIOD(2, 8000000, 25); /* 8ms at 1.25x */
457 TM_CFG_PERIOD(3, 30000000, 50); /* 30ms at 1.50x */
458 TM_CFG_PERIOD(4, 75000000, 75); /* 75ms at 1.75x */
459 TM_CFG_PERIOD(5, 175000000, 100); /* 175ms at 2x */
460 TM_CFG_PERIOD(6, 500000000, 200); /* 500ms at 3x */
461 TM_CFG_PERIOD(7, 3000000000, 300); /* 3s at 4x */
462 TM_CFG_PERIOD(8,30000000000, 400); /* 30s at 5x */
463 TM_CFG_PERIOD(9,55000000000, 500); /* 55s at 6x */
464 AssertCompile(RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods) == 10);
465#undef TM_CFG_PERIOD
466
467 /*
468 * Configure real world time (UTC).
469 */
470 /** @cfgm{TM/UTCOffset, int64_t, ns, INT64_MIN, INT64_MAX, 0}
471 * The UTC offset. This is used to put the guest back or forwards in time. */
472 rc = CFGMR3QueryS64(pCfgHandle, "UTCOffset", &pVM->tm.s.offUTC);
473 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
474 pVM->tm.s.offUTC = 0; /* ns */
475 else if (RT_FAILURE(rc))
476 return VMSetError(pVM, rc, RT_SRC_POS,
477 N_("Configuration error: Failed to querying 64-bit integer value \"UTCOffset\""));
478
479 /*
480 * Setup the warp drive.
481 */
482 /** @cfgm{TM/WarpDrivePercentage, uint32_t, %, 0, 20000, 100}
483 * The warp drive percentage, 100% is normal speed. This is used to speed up
484 * or slow down the virtual clock, which can be useful for fast forwarding
485 * borring periods during tests. */
486 rc = CFGMR3QueryU32(pCfgHandle, "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage);
487 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
488 rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage); /* legacy */
489 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
490 pVM->tm.s.u32VirtualWarpDrivePercentage = 100;
491 else if (RT_FAILURE(rc))
492 return VMSetError(pVM, rc, RT_SRC_POS,
493 N_("Configuration error: Failed to querying uint32_t value \"WarpDrivePercent\""));
494 else if ( pVM->tm.s.u32VirtualWarpDrivePercentage < 2
495 || pVM->tm.s.u32VirtualWarpDrivePercentage > 20000)
496 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
497 N_("Configuration error: \"WarpDrivePercent\" = %RI32 is not in the range 2..20000"),
498 pVM->tm.s.u32VirtualWarpDrivePercentage);
499 pVM->tm.s.fVirtualWarpDrive = pVM->tm.s.u32VirtualWarpDrivePercentage != 100;
500 if (pVM->tm.s.fVirtualWarpDrive)
501 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32\n", pVM->tm.s.u32VirtualWarpDrivePercentage));
502
503 /*
504 * Start the timer (guard against REM not yielding).
505 */
506 /** @cfgm{TM/TimerMillies, uint32_t, ms, 1, 1000, 10}
507 * The watchdog timer interval. */
508 uint32_t u32Millies;
509 rc = CFGMR3QueryU32(pCfgHandle, "TimerMillies", &u32Millies);
510 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
511 u32Millies = 10;
512 else if (RT_FAILURE(rc))
513 return VMSetError(pVM, rc, RT_SRC_POS,
514 N_("Configuration error: Failed to query uint32_t value \"TimerMillies\""));
515 rc = RTTimerCreate(&pVM->tm.s.pTimer, u32Millies, tmR3TimerCallback, pVM);
516 if (RT_FAILURE(rc))
517 {
518 AssertMsgFailed(("Failed to create timer, u32Millies=%d rc=%Rrc.\n", u32Millies, rc));
519 return rc;
520 }
521 Log(("TM: Created timer %p firing every %d millieseconds\n", pVM->tm.s.pTimer, u32Millies));
522 pVM->tm.s.u32TimerMillies = u32Millies;
523
524 /*
525 * Register saved state.
526 */
527 rc = SSMR3RegisterInternal(pVM, "tm", 1, TM_SAVED_STATE_VERSION, sizeof(uint64_t) * 8,
528 NULL, NULL, NULL,
529 NULL, tmR3Save, NULL,
530 NULL, tmR3Load, NULL);
531 if (RT_FAILURE(rc))
532 return rc;
533
534 /*
535 * Register statistics.
536 */
537 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataR3.c1nsSteps,STAMTYPE_U32, "/TM/R3/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
538 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataR3.cBadPrev, STAMTYPE_U32, "/TM/R3/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
539 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataR0.c1nsSteps,STAMTYPE_U32, "/TM/R0/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
540 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataR0.cBadPrev, STAMTYPE_U32, "/TM/R0/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
541 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.c1nsSteps,STAMTYPE_U32, "/TM/RC/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
542 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.cBadPrev, STAMTYPE_U32, "/TM/RC/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
543 STAM_REL_REG( pVM,(void*)&pVM->tm.s.offVirtualSync, STAMTYPE_U64, "/TM/VirtualSync/CurrentOffset", STAMUNIT_NS, "The current offset. (subtract GivenUp to get the lag)");
544 STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.offVirtualSyncGivenUp, STAMTYPE_U64, "/TM/VirtualSync/GivenUp", STAMUNIT_NS, "Nanoseconds of the 'CurrentOffset' that's been given up and won't ever be attemted caught up with.");
545
546#ifdef VBOX_WITH_STATISTICS
547 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR3.cExpired, STAMTYPE_U32, "/TM/R3/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
548 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR3.cUpdateRaces,STAMTYPE_U32, "/TM/R3/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
549 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR0.cExpired, STAMTYPE_U32, "/TM/R0/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
550 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR0.cUpdateRaces,STAMTYPE_U32, "/TM/R0/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
551 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cExpired, STAMTYPE_U32, "/TM/RC/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
552 STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cUpdateRaces,STAMTYPE_U32, "/TM/RC/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
553 STAM_REG(pVM, &pVM->tm.s.StatDoQueues, STAMTYPE_PROFILE, "/TM/DoQueues", STAMUNIT_TICKS_PER_CALL, "Profiling timer TMR3TimerQueuesDo.");
554 STAM_REG(pVM, &pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Virtual", STAMUNIT_TICKS_PER_CALL, "Time spent on the virtual clock queue.");
555 STAM_REG(pVM, &pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], STAMTYPE_PROFILE_ADV, "/TM/DoQueues/VirtualSync", STAMUNIT_TICKS_PER_CALL, "Time spent on the virtual sync clock queue.");
556 STAM_REG(pVM, &pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], STAMTYPE_PROFILE_ADV, "/TM/DoQueues/Real", STAMUNIT_TICKS_PER_CALL, "Time spent on the real clock queue.");
557
558 STAM_REG(pVM, &pVM->tm.s.StatPoll, STAMTYPE_COUNTER, "/TM/Poll", STAMUNIT_OCCURENCES, "TMTimerPoll calls.");
559 STAM_REG(pVM, &pVM->tm.s.StatPollAlreadySet, STAMTYPE_COUNTER, "/TM/Poll/AlreadySet", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the FF was already set.");
560 STAM_REG(pVM, &pVM->tm.s.StatPollELoop, STAMTYPE_COUNTER, "/TM/Poll/ELoop", STAMUNIT_OCCURENCES, "Times TMTimerPoll has given up getting a consistent virtual sync data set.");
561 STAM_REG(pVM, &pVM->tm.s.StatPollMiss, STAMTYPE_COUNTER, "/TM/Poll/Miss", STAMUNIT_OCCURENCES, "TMTimerPoll calls where nothing had expired.");
562 STAM_REG(pVM, &pVM->tm.s.StatPollRunning, STAMTYPE_COUNTER, "/TM/Poll/Running", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the queues were being run.");
563 STAM_REG(pVM, &pVM->tm.s.StatPollSimple, STAMTYPE_COUNTER, "/TM/Poll/Simple", STAMUNIT_OCCURENCES, "TMTimerPoll calls where we could take the simple path.");
564 STAM_REG(pVM, &pVM->tm.s.StatPollVirtual, STAMTYPE_COUNTER, "/TM/Poll/HitsVirtual", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL queue.");
565 STAM_REG(pVM, &pVM->tm.s.StatPollVirtualSync, STAMTYPE_COUNTER, "/TM/Poll/HitsVirtualSync", STAMUNIT_OCCURENCES, "The number of times TMTimerPoll found an expired TMCLOCK_VIRTUAL_SYNC queue.");
566
567 STAM_REG(pVM, &pVM->tm.s.StatPostponedR3, STAMTYPE_COUNTER, "/TM/PostponedR3", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-3.");
568 STAM_REG(pVM, &pVM->tm.s.StatPostponedRZ, STAMTYPE_COUNTER, "/TM/PostponedRZ", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-0 / RC.");
569
570 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.");
571 STAM_REG(pVM, &pVM->tm.s.StatScheduleOneRZ, STAMTYPE_PROFILE, "/TM/ScheduleOneRZ", STAMUNIT_TICKS_PER_CALL, "Profiling the scheduling of one queue during a TMTimer* call in EMT.");
572 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.");
573
574 STAM_REG(pVM, &pVM->tm.s.StatTimerSet, STAMTYPE_COUNTER, "/TM/TimerSet", STAMUNIT_OCCURENCES, "Calls");
575 STAM_REG(pVM, &pVM->tm.s.StatTimerSetOpt, STAMTYPE_COUNTER, "/TM/TimerSet/Opt", STAMUNIT_OCCURENCES, "Optimized path taken.");
576 STAM_REG(pVM, &pVM->tm.s.StatTimerSetR3, STAMTYPE_PROFILE, "/TM/TimerSet/R3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3.");
577 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRZ, STAMTYPE_PROFILE, "/TM/TimerSet/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0 / RC.");
578 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStActive, STAMTYPE_COUNTER, "/TM/TimerSet/StActive", STAMUNIT_OCCURENCES, "ACTIVE");
579 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStExpDeliver, STAMTYPE_COUNTER, "/TM/TimerSet/StExpDeliver", STAMUNIT_OCCURENCES, "EXPIRED_DELIVER");
580 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStOther, STAMTYPE_COUNTER, "/TM/TimerSet/StOther", STAMUNIT_OCCURENCES, "Other states");
581 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendStop, STAMTYPE_COUNTER, "/TM/TimerSet/StPendStop", STAMUNIT_OCCURENCES, "PENDING_STOP");
582 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendStopSched, STAMTYPE_COUNTER, "/TM/TimerSet/StPendStopSched", STAMUNIT_OCCURENCES, "PENDING_STOP_SCHEDULE");
583 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendSched, STAMTYPE_COUNTER, "/TM/TimerSet/StPendSched", STAMUNIT_OCCURENCES, "PENDING_SCHEDULE");
584 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStPendResched, STAMTYPE_COUNTER, "/TM/TimerSet/StPendResched", STAMUNIT_OCCURENCES, "PENDING_RESCHEDULE");
585 STAM_REG(pVM, &pVM->tm.s.StatTimerSetStStopped, STAMTYPE_COUNTER, "/TM/TimerSet/StStopped", STAMUNIT_OCCURENCES, "STOPPED");
586
587 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelative, STAMTYPE_COUNTER, "/TM/TimerSetRelative", STAMUNIT_OCCURENCES, "Calls");
588 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeOpt, STAMTYPE_COUNTER, "/TM/TimerSetRelative/Opt", STAMUNIT_OCCURENCES, "Optimized path taken.");
589 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeR3, STAMTYPE_PROFILE, "/TM/TimerSetRelative/R3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSetRelative calls made in ring-3.");
590 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeRZ, STAMTYPE_PROFILE, "/TM/TimerSetRelative/RZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSetReltaive calls made in ring-0 / RC.");
591 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeRacyVirtSync, STAMTYPE_COUNTER, "/TM/TimerSetRelative/RacyVirtSync", STAMUNIT_OCCURENCES, "Potentially racy virtual sync timer update.");
592 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStActive, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StActive", STAMUNIT_OCCURENCES, "ACTIVE");
593 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStExpDeliver, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StExpDeliver", STAMUNIT_OCCURENCES, "EXPIRED_DELIVER");
594 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStOther, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StOther", STAMUNIT_OCCURENCES, "Other states");
595 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendStop, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendStop", STAMUNIT_OCCURENCES, "PENDING_STOP");
596 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendStopSched, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendStopSched",STAMUNIT_OCCURENCES, "PENDING_STOP_SCHEDULE");
597 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendSched, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendSched", STAMUNIT_OCCURENCES, "PENDING_SCHEDULE");
598 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStPendResched, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StPendResched", STAMUNIT_OCCURENCES, "PENDING_RESCHEDULE");
599 STAM_REG(pVM, &pVM->tm.s.StatTimerSetRelativeStStopped, STAMTYPE_COUNTER, "/TM/TimerSetRelative/StStopped", STAMUNIT_OCCURENCES, "STOPPED");
600
601 STAM_REG(pVM, &pVM->tm.s.StatTimerStopR3, STAMTYPE_PROFILE, "/TM/TimerStopR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-3.");
602 STAM_REG(pVM, &pVM->tm.s.StatTimerStopRZ, STAMTYPE_PROFILE, "/TM/TimerStopRZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-0 / RC.");
603
604 STAM_REG(pVM, &pVM->tm.s.StatVirtualGet, STAMTYPE_COUNTER, "/TM/VirtualGet", STAMUNIT_OCCURENCES, "The number of times TMTimerGet was called when the clock was running.");
605 STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualGetSetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGet.");
606 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGet, STAMTYPE_COUNTER, "/TM/VirtualSyncGet", STAMUNIT_OCCURENCES, "The number of times tmVirtualSyncGetEx was called.");
607 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetELoop, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/ELoop", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx has given up getting a consistent virtual sync data set.");
608 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetExpired, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Expired", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx encountered an expired timer stopping the clock.");
609 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetLocked, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Locked", STAMUNIT_OCCURENCES, "Times we successfully acquired the lock in tmVirtualSyncGetEx.");
610 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetLockless, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Lockless", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx returned without needing to take the lock.");
611 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/SetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling tmVirtualSyncGetEx.");
612 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/VirtualPause", STAMUNIT_OCCURENCES, "The number of times TMR3TimerPause was called.");
613 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/VirtualResume", STAMUNIT_OCCURENCES, "The number of times TMR3TimerResume was called.");
614
615 STAM_REG(pVM, &pVM->tm.s.StatTimerCallbackSetFF, STAMTYPE_COUNTER, "/TM/CallbackSetFF", STAMUNIT_OCCURENCES, "The number of times the timer callback set FF.");
616
617 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE010, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE010", STAMUNIT_OCCURENCES, "In catch-up mode, 10% or lower.");
618 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE025, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE025", STAMUNIT_OCCURENCES, "In catch-up mode, 25%-11%.");
619 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE100, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE100", STAMUNIT_OCCURENCES, "In catch-up mode, 100%-26%.");
620 STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupOther, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupOther", STAMUNIT_OCCURENCES, "In catch-up mode, > 100%.");
621 STAM_REG(pVM, &pVM->tm.s.StatTSCNotFixed, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotFixed", STAMUNIT_OCCURENCES, "TSC is not fixed, it may run at variable speed.");
622 STAM_REG(pVM, &pVM->tm.s.StatTSCNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotTicking", STAMUNIT_OCCURENCES, "TSC is not ticking.");
623 STAM_REG(pVM, &pVM->tm.s.StatTSCSyncNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/SyncNotTicking", STAMUNIT_OCCURENCES, "VirtualSync isn't ticking.");
624 STAM_REG(pVM, &pVM->tm.s.StatTSCWarp, STAMTYPE_COUNTER, "/TM/TSC/Intercept/Warp", STAMUNIT_OCCURENCES, "Warpdrive is active.");
625 STAM_REG(pVM, &pVM->tm.s.StatTSCSet, STAMTYPE_COUNTER, "/TM/TSC/Sets", STAMUNIT_OCCURENCES, "Calls to TMCpuTickSet.");
626 STAM_REG(pVM, &pVM->tm.s.StatTSCUnderflow, STAMTYPE_COUNTER, "/TM/TSC/Underflow", STAMUNIT_OCCURENCES, "TSC underflow; corrected with last seen value .");
627#endif /* VBOX_WITH_STATISTICS */
628
629 for (VMCPUID i = 0; i < pVM->cCpus; i++)
630 {
631 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.offTSCRawSrc, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS, "TSC offset relative the raw source", "/TM/TSC/offCPU%u", i);
632#ifndef VBOX_WITHOUT_NS_ACCOUNTING
633 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsTotal, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Total CPU run time.", "/TM/CPU/%02u", i);
634 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsExecuting, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent executing guest code.", "/TM/CPU/%02u/Executing", i);
635 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsHalted, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent halted.", "/TM/CPU/%02u/Halted", i);
636 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsOther, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent in the VMM or preempted.", "/TM/CPU/%02u/Other", i);
637 /** @todo Try add 1, 5 and 15 min load stats. */
638#endif
639 }
640
641#ifdef VBOX_WITH_STATISTICS
642 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.");
643 STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
644 STAM_REG(pVM, (void *)&pVM->tm.s.u32VirtualSyncCatchUpPercentage, STAMTYPE_U32, "/TM/VirtualSync/CatchUpPercentage", STAMUNIT_PCT, "The catch-up percentage. (+100/100 to get clock multiplier)");
645 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncFF, STAMTYPE_PROFILE, "/TM/VirtualSync/FF", STAMUNIT_TICKS_PER_OCCURENCE, "Time spent in TMR3VirtualSyncFF by all but the dedicate timer EMT.");
646 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
647 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++.)");
648 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
649 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
650 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.");
651 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
652 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.)");
653 for (unsigned i = 0; i < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods); i++)
654 {
655 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
656 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
657 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
658 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u64Start, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Start of this period (lag).", "/TM/VirtualSync/Periods/%u/Start", i);
659 }
660#endif /* VBOX_WITH_STATISTICS */
661
662 /*
663 * Register info handlers.
664 */
665 DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
666 DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
667 DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
668
669 return VINF_SUCCESS;
670}
671
672
673/**
674 * Initializes the per-VCPU TM.
675 *
676 * @returns VBox status code.
677 * @param pVM The VM to operate on.
678 */
679VMM_INT_DECL(int) TMR3InitCPU(PVM pVM)
680{
681 LogFlow(("TMR3InitCPU\n"));
682 return VINF_SUCCESS;
683}
684
685
686/**
687 * Checks if the host CPU has a fixed TSC frequency.
688 *
689 * @returns true if it has, false if it hasn't.
690 *
691 * @remark This test doesn't bother with very old CPUs that don't do power
692 * management or any other stuff that might influence the TSC rate.
693 * This isn't currently relevant.
694 */
695static bool tmR3HasFixedTSC(PVM pVM)
696{
697 if (ASMHasCpuId())
698 {
699 uint32_t uEAX, uEBX, uECX, uEDX;
700
701 if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_AMD)
702 {
703 /*
704 * AuthenticAMD - Check for APM support and that TscInvariant is set.
705 *
706 * This test isn't correct with respect to fixed/non-fixed TSC and
707 * older models, but this isn't relevant since the result is currently
708 * only used for making a descision on AMD-V models.
709 */
710 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
711 if (uEAX >= 0x80000007)
712 {
713 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
714
715 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
716 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
717 && pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* no fixed tsc if the gip timer is in async mode */)
718 return true;
719 }
720 }
721 else if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_INTEL)
722 {
723 /*
724 * GenuineIntel - Check the model number.
725 *
726 * This test is lacking in the same way and for the same reasons
727 * as the AMD test above.
728 */
729 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
730 unsigned uModel = (uEAX >> 4) & 0x0f;
731 unsigned uFamily = (uEAX >> 8) & 0x0f;
732 if (uFamily == 0x0f)
733 uFamily += (uEAX >> 20) & 0xff;
734 if (uFamily >= 0x06)
735 uModel += ((uEAX >> 16) & 0x0f) << 4;
736 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
737 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
738 return true;
739 }
740 }
741 return false;
742}
743
744
745/**
746 * Calibrate the CPU tick.
747 *
748 * @returns Number of ticks per second.
749 */
750static uint64_t tmR3CalibrateTSC(PVM pVM)
751{
752 /*
753 * Use GIP when available present.
754 */
755 uint64_t u64Hz;
756 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
757 if ( pGip
758 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC)
759 {
760 unsigned iCpu = pGip->u32Mode != SUPGIPMODE_ASYNC_TSC ? 0 : ASMGetApicId();
761 if (iCpu >= RT_ELEMENTS(pGip->aCPUs))
762 AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
763 else
764 {
765 if (tmR3HasFixedTSC(pVM))
766 /* Sleep a bit to get a more reliable CpuHz value. */
767 RTThreadSleep(32);
768 else
769 {
770 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
771 const uint64_t u64 = RTTimeMilliTS();
772 while ((RTTimeMilliTS() - u64) < 40 /*ms*/)
773 /* nothing */;
774 }
775
776 pGip = g_pSUPGlobalInfoPage;
777 if ( pGip
778 && pGip->u32Magic == SUPGLOBALINFOPAGE_MAGIC
779 && (u64Hz = pGip->aCPUs[iCpu].u64CpuHz)
780 && u64Hz != ~(uint64_t)0)
781 return u64Hz;
782 }
783 }
784
785 /* call this once first to make sure it's initialized. */
786 RTTimeNanoTS();
787
788 /*
789 * Yield the CPU to increase our chances of getting
790 * a correct value.
791 */
792 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
793 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
794 uint64_t au64Samples[5];
795 unsigned i;
796 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
797 {
798 RTMSINTERVAL cMillies;
799 int cTries = 5;
800 uint64_t u64Start = ASMReadTSC();
801 uint64_t u64End;
802 uint64_t StartTS = RTTimeNanoTS();
803 uint64_t EndTS;
804 do
805 {
806 RTThreadSleep(s_auSleep[i]);
807 u64End = ASMReadTSC();
808 EndTS = RTTimeNanoTS();
809 cMillies = (RTMSINTERVAL)((EndTS - StartTS + 500000) / 1000000);
810 } while ( cMillies == 0 /* the sleep may be interrupted... */
811 || (cMillies < 20 && --cTries > 0));
812 uint64_t u64Diff = u64End - u64Start;
813
814 au64Samples[i] = (u64Diff * 1000) / cMillies;
815 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
816 }
817
818 /*
819 * Discard the highest and lowest results and calculate the average.
820 */
821 unsigned iHigh = 0;
822 unsigned iLow = 0;
823 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
824 {
825 if (au64Samples[i] < au64Samples[iLow])
826 iLow = i;
827 if (au64Samples[i] > au64Samples[iHigh])
828 iHigh = i;
829 }
830 au64Samples[iLow] = 0;
831 au64Samples[iHigh] = 0;
832
833 u64Hz = au64Samples[0];
834 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
835 u64Hz += au64Samples[i];
836 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
837
838 return u64Hz;
839}
840
841
842/**
843 * Finalizes the TM initialization.
844 *
845 * @returns VBox status code.
846 * @param pVM The VM to operate on.
847 */
848VMM_INT_DECL(int) TMR3InitFinalize(PVM pVM)
849{
850 int rc;
851
852 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
853 AssertRCReturn(rc, rc);
854 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
855 AssertRCReturn(rc, rc);
856 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
857 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
858 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
859 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
860 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
861 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
862 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
863 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
864 else
865 AssertFatalFailed();
866 AssertRCReturn(rc, rc);
867
868 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
869 AssertRCReturn(rc, rc);
870 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
871 AssertRCReturn(rc, rc);
872 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
873 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawR0);
874 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
875 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawR0);
876 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
877 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawR0);
878 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
879 rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawR0);
880 else
881 AssertFatalFailed();
882 AssertRCReturn(rc, rc);
883
884 return VINF_SUCCESS;
885}
886
887
888/**
889 * Applies relocations to data and code managed by this
890 * component. This function will be called at init and
891 * whenever the VMM need to relocate it self inside the GC.
892 *
893 * @param pVM The VM.
894 * @param offDelta Relocation delta relative to old location.
895 */
896VMM_INT_DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
897{
898 int rc;
899 LogFlow(("TMR3Relocate\n"));
900
901 pVM->tm.s.pvGIPRC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
902 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
903 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
904
905 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
906 AssertFatal(pVM->tm.s.VirtualGetRawDataRC.pu64Prev);
907 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
908 AssertFatalRC(rc);
909 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
910 AssertFatalRC(rc);
911
912 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
913 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
914 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
915 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
916 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
917 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
918 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
919 rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
920 else
921 AssertFatalFailed();
922 AssertFatalRC(rc);
923
924 /*
925 * Iterate the timers updating the pVMRC pointers.
926 */
927 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
928 {
929 pTimer->pVMRC = pVM->pVMRC;
930 pTimer->pVMR0 = pVM->pVMR0;
931 }
932}
933
934
935/**
936 * Terminates the TM.
937 *
938 * Termination means cleaning up and freeing all resources,
939 * the VM it self is at this point powered off or suspended.
940 *
941 * @returns VBox status code.
942 * @param pVM The VM to operate on.
943 */
944VMM_INT_DECL(int) TMR3Term(PVM pVM)
945{
946 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
947 if (pVM->tm.s.pTimer)
948 {
949 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
950 AssertRC(rc);
951 pVM->tm.s.pTimer = NULL;
952 }
953
954 return VINF_SUCCESS;
955}
956
957
958/**
959 * Terminates the per-VCPU TM.
960 *
961 * Termination means cleaning up and freeing all resources,
962 * the VM it self is at this point powered off or suspended.
963 *
964 * @returns VBox status code.
965 * @param pVM The VM to operate on.
966 */
967VMM_INT_DECL(int) TMR3TermCPU(PVM pVM)
968{
969 return VINF_SUCCESS;
970}
971
972
973/**
974 * The VM is being reset.
975 *
976 * For the TM component this means that a rescheduling is preformed,
977 * the FF is cleared and but without running the queues. We'll have to
978 * check if this makes sense or not, but it seems like a good idea now....
979 *
980 * @param pVM VM handle.
981 */
982VMM_INT_DECL(void) TMR3Reset(PVM pVM)
983{
984 LogFlow(("TMR3Reset:\n"));
985 VM_ASSERT_EMT(pVM);
986 tmTimerLock(pVM);
987
988 /*
989 * Abort any pending catch up.
990 * This isn't perfect...
991 */
992 if (pVM->tm.s.fVirtualSyncCatchUp)
993 {
994 const uint64_t offVirtualNow = TMVirtualGetNoCheck(pVM);
995 const uint64_t offVirtualSyncNow = TMVirtualSyncGetNoCheck(pVM);
996 if (pVM->tm.s.fVirtualSyncCatchUp)
997 {
998 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
999
1000 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
1001 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
1002 Assert(offOld <= offNew);
1003 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1004 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
1005 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1006 LogRel(("TM: Aborting catch-up attempt on reset with a %'RU64 ns lag on reset; new total: %'RU64 ns\n", offNew - offOld, offNew));
1007 }
1008 }
1009
1010 /*
1011 * Process the queues.
1012 */
1013 for (int i = 0; i < TMCLOCK_MAX; i++)
1014 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
1015#ifdef VBOX_STRICT
1016 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
1017#endif
1018
1019 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1020 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /** @todo FIXME: this isn't right. */
1021 tmTimerUnlock(pVM);
1022}
1023
1024
1025/**
1026 * Resolve a builtin RC symbol.
1027 * Called by PDM when loading or relocating GC modules.
1028 *
1029 * @returns VBox status
1030 * @param pVM VM Handle.
1031 * @param pszSymbol Symbol to resolve.
1032 * @param pRCPtrValue Where to store the symbol value.
1033 * @remark This has to work before TMR3Relocate() is called.
1034 */
1035VMM_INT_DECL(int) TMR3GetImportRC(PVM pVM, const char *pszSymbol, PRTRCPTR pRCPtrValue)
1036{
1037 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
1038 *pRCPtrValue = MMHyperR3ToRC(pVM, &pVM->tm.s.pvGIPRC);
1039 //else if (..)
1040 else
1041 return VERR_SYMBOL_NOT_FOUND;
1042 return VINF_SUCCESS;
1043}
1044
1045
1046/**
1047 * Execute state save operation.
1048 *
1049 * @returns VBox status code.
1050 * @param pVM VM Handle.
1051 * @param pSSM SSM operation handle.
1052 */
1053static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
1054{
1055 LogFlow(("tmR3Save:\n"));
1056#ifdef VBOX_STRICT
1057 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1058 {
1059 PVMCPU pVCpu = &pVM->aCpus[i];
1060 Assert(!pVCpu->tm.s.fTSCTicking);
1061 }
1062 Assert(!pVM->tm.s.cVirtualTicking);
1063 Assert(!pVM->tm.s.fVirtualSyncTicking);
1064#endif
1065
1066 /*
1067 * Save the virtual clocks.
1068 */
1069 /* the virtual clock. */
1070 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
1071 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
1072
1073 /* the virtual timer synchronous clock. */
1074 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
1075 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
1076 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
1077 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
1078 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
1079
1080 /* real time clock */
1081 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
1082
1083 /* the cpu tick clock. */
1084 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1085 {
1086 PVMCPU pVCpu = &pVM->aCpus[i];
1087 SSMR3PutU64(pSSM, TMCpuTickGet(pVCpu));
1088 }
1089 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
1090}
1091
1092
1093/**
1094 * Execute state load operation.
1095 *
1096 * @returns VBox status code.
1097 * @param pVM VM Handle.
1098 * @param pSSM SSM operation handle.
1099 * @param uVersion Data layout version.
1100 * @param uPass The data pass.
1101 */
1102static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1103{
1104 LogFlow(("tmR3Load:\n"));
1105
1106 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
1107#ifdef VBOX_STRICT
1108 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1109 {
1110 PVMCPU pVCpu = &pVM->aCpus[i];
1111 Assert(!pVCpu->tm.s.fTSCTicking);
1112 }
1113 Assert(!pVM->tm.s.cVirtualTicking);
1114 Assert(!pVM->tm.s.fVirtualSyncTicking);
1115#endif
1116
1117 /*
1118 * Validate version.
1119 */
1120 if (uVersion != TM_SAVED_STATE_VERSION)
1121 {
1122 AssertMsgFailed(("tmR3Load: Invalid version uVersion=%d!\n", uVersion));
1123 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1124 }
1125
1126 /*
1127 * Load the virtual clock.
1128 */
1129 pVM->tm.s.cVirtualTicking = 0;
1130 /* the virtual clock. */
1131 uint64_t u64Hz;
1132 int rc = SSMR3GetU64(pSSM, &u64Hz);
1133 if (RT_FAILURE(rc))
1134 return rc;
1135 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
1136 {
1137 AssertMsgFailed(("The virtual clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1138 u64Hz, TMCLOCK_FREQ_VIRTUAL));
1139 return VERR_SSM_VIRTUAL_CLOCK_HZ;
1140 }
1141 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
1142 pVM->tm.s.u64VirtualOffset = 0;
1143
1144 /* the virtual timer synchronous clock. */
1145 pVM->tm.s.fVirtualSyncTicking = false;
1146 uint64_t u64;
1147 SSMR3GetU64(pSSM, &u64);
1148 pVM->tm.s.u64VirtualSync = u64;
1149 SSMR3GetU64(pSSM, &u64);
1150 pVM->tm.s.offVirtualSync = u64;
1151 SSMR3GetU64(pSSM, &u64);
1152 pVM->tm.s.offVirtualSyncGivenUp = u64;
1153 SSMR3GetU64(pSSM, &u64);
1154 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1155 bool f;
1156 SSMR3GetBool(pSSM, &f);
1157 pVM->tm.s.fVirtualSyncCatchUp = f;
1158
1159 /* the real clock */
1160 rc = SSMR3GetU64(pSSM, &u64Hz);
1161 if (RT_FAILURE(rc))
1162 return rc;
1163 if (u64Hz != TMCLOCK_FREQ_REAL)
1164 {
1165 AssertMsgFailed(("The real clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1166 u64Hz, TMCLOCK_FREQ_REAL));
1167 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
1168 }
1169
1170 /* the cpu tick clock. */
1171 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1172 {
1173 PVMCPU pVCpu = &pVM->aCpus[i];
1174
1175 pVCpu->tm.s.fTSCTicking = false;
1176 SSMR3GetU64(pSSM, &pVCpu->tm.s.u64TSC);
1177
1178 if (pVM->tm.s.fTSCUseRealTSC)
1179 pVCpu->tm.s.offTSCRawSrc = 0; /** @todo TSC restore stuff and HWACC. */
1180 }
1181
1182 rc = SSMR3GetU64(pSSM, &u64Hz);
1183 if (RT_FAILURE(rc))
1184 return rc;
1185 if (!pVM->tm.s.fTSCUseRealTSC)
1186 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1187
1188 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%'RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1189 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1190
1191 /*
1192 * Make sure timers get rescheduled immediately.
1193 */
1194 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1195 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1196
1197 return VINF_SUCCESS;
1198}
1199
1200
1201/**
1202 * Internal TMR3TimerCreate worker.
1203 *
1204 * @returns VBox status code.
1205 * @param pVM The VM handle.
1206 * @param enmClock The timer clock.
1207 * @param pszDesc The timer description.
1208 * @param ppTimer Where to store the timer pointer on success.
1209 */
1210static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1211{
1212 VM_ASSERT_EMT(pVM);
1213
1214 /*
1215 * Allocate the timer.
1216 */
1217 PTMTIMERR3 pTimer = NULL;
1218 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1219 {
1220 pTimer = pVM->tm.s.pFree;
1221 pVM->tm.s.pFree = pTimer->pBigNext;
1222 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1223 }
1224
1225 if (!pTimer)
1226 {
1227 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1228 if (RT_FAILURE(rc))
1229 return rc;
1230 Log3(("TM: Allocated new timer %p\n", pTimer));
1231 }
1232
1233 /*
1234 * Initialize it.
1235 */
1236 pTimer->u64Expire = 0;
1237 pTimer->enmClock = enmClock;
1238 pTimer->pVMR3 = pVM;
1239 pTimer->pVMR0 = pVM->pVMR0;
1240 pTimer->pVMRC = pVM->pVMRC;
1241 pTimer->enmState = TMTIMERSTATE_STOPPED;
1242 pTimer->offScheduleNext = 0;
1243 pTimer->offNext = 0;
1244 pTimer->offPrev = 0;
1245 pTimer->pvUser = NULL;
1246 pTimer->pCritSect = NULL;
1247 pTimer->pszDesc = pszDesc;
1248
1249 /* insert into the list of created timers. */
1250 tmTimerLock(pVM);
1251 pTimer->pBigPrev = NULL;
1252 pTimer->pBigNext = pVM->tm.s.pCreated;
1253 pVM->tm.s.pCreated = pTimer;
1254 if (pTimer->pBigNext)
1255 pTimer->pBigNext->pBigPrev = pTimer;
1256#ifdef VBOX_STRICT
1257 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1258#endif
1259 tmTimerUnlock(pVM);
1260
1261 *ppTimer = pTimer;
1262 return VINF_SUCCESS;
1263}
1264
1265
1266/**
1267 * Creates a device timer.
1268 *
1269 * @returns VBox status.
1270 * @param pVM The VM to create the timer in.
1271 * @param pDevIns Device instance.
1272 * @param enmClock The clock to use on this timer.
1273 * @param pfnCallback Callback function.
1274 * @param pvUser The user argument to the callback.
1275 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1276 * @param pszDesc Pointer to description string which must stay around
1277 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1278 * @param ppTimer Where to store the timer on success.
1279 */
1280VMM_INT_DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, void *pvUser, uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1281{
1282 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1283
1284 /*
1285 * Allocate and init stuff.
1286 */
1287 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1288 if (RT_SUCCESS(rc))
1289 {
1290 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1291 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1292 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1293 (*ppTimer)->pvUser = pvUser;
1294 if (fFlags & TMTIMER_FLAGS_DEFAULT_CRIT_SECT)
1295 {
1296 if (pDevIns->pCritSectR3)
1297 (*ppTimer)->pCritSect = pDevIns->pCritSectR3;
1298 else
1299 (*ppTimer)->pCritSect = IOMR3GetCritSect(pVM);
1300 }
1301 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1302 }
1303
1304 return rc;
1305}
1306
1307
1308/**
1309 * Creates a driver timer.
1310 *
1311 * @returns VBox status.
1312 * @param pVM The VM to create the timer in.
1313 * @param pDrvIns Driver instance.
1314 * @param enmClock The clock to use on this timer.
1315 * @param pfnCallback Callback function.
1316 * @param pvUser The user argument to the callback.
1317 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1318 * @param pszDesc Pointer to description string which must stay around
1319 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1320 * @param ppTimer Where to store the timer on success.
1321 */
1322VMM_INT_DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, void *pvUser,
1323 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1324{
1325 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1326
1327 /*
1328 * Allocate and init stuff.
1329 */
1330 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1331 if (RT_SUCCESS(rc))
1332 {
1333 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1334 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1335 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1336 (*ppTimer)->pvUser = pvUser;
1337 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1338 }
1339
1340 return rc;
1341}
1342
1343
1344/**
1345 * Creates an internal timer.
1346 *
1347 * @returns VBox status.
1348 * @param pVM The VM to create the timer in.
1349 * @param enmClock The clock to use on this timer.
1350 * @param pfnCallback Callback function.
1351 * @param pvUser User argument to be passed to the callback.
1352 * @param pszDesc Pointer to description string which must stay around
1353 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1354 * @param ppTimer Where to store the timer on success.
1355 */
1356VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1357{
1358 /*
1359 * Allocate and init stuff.
1360 */
1361 PTMTIMER pTimer;
1362 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1363 if (RT_SUCCESS(rc))
1364 {
1365 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1366 pTimer->u.Internal.pfnTimer = pfnCallback;
1367 pTimer->pvUser = pvUser;
1368 *ppTimer = pTimer;
1369 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1370 }
1371
1372 return rc;
1373}
1374
1375/**
1376 * Creates an external timer.
1377 *
1378 * @returns Timer handle on success.
1379 * @returns NULL on failure.
1380 * @param pVM The VM to create the timer in.
1381 * @param enmClock The clock to use on this timer.
1382 * @param pfnCallback Callback function.
1383 * @param pvUser User argument.
1384 * @param pszDesc Pointer to description string which must stay around
1385 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1386 */
1387VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1388{
1389 /*
1390 * Allocate and init stuff.
1391 */
1392 PTMTIMERR3 pTimer;
1393 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1394 if (RT_SUCCESS(rc))
1395 {
1396 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1397 pTimer->u.External.pfnTimer = pfnCallback;
1398 pTimer->pvUser = pvUser;
1399 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1400 return pTimer;
1401 }
1402
1403 return NULL;
1404}
1405
1406
1407/**
1408 * Destroy a timer
1409 *
1410 * @returns VBox status.
1411 * @param pTimer Timer handle as returned by one of the create functions.
1412 */
1413VMMR3DECL(int) TMR3TimerDestroy(PTMTIMER pTimer)
1414{
1415 /*
1416 * Be extra careful here.
1417 */
1418 if (!pTimer)
1419 return VINF_SUCCESS;
1420 AssertPtr(pTimer);
1421 Assert((unsigned)pTimer->enmClock < (unsigned)TMCLOCK_MAX);
1422
1423 PVM pVM = pTimer->CTX_SUFF(pVM);
1424 PTMTIMERQUEUE pQueue = &pVM->tm.s.CTX_SUFF(paTimerQueues)[pTimer->enmClock];
1425 bool fActive = false;
1426 bool fPending = false;
1427
1428 AssertMsg( !pTimer->pCritSect
1429 || VMR3GetState(pVM) != VMSTATE_RUNNING
1430 || PDMCritSectIsOwner(pTimer->pCritSect), ("%s\n", pTimer->pszDesc));
1431
1432 /*
1433 * The rest of the game happens behind the lock, just
1434 * like create does. All the work is done here.
1435 */
1436 tmTimerLock(pVM);
1437 for (int cRetries = 1000;; cRetries--)
1438 {
1439 /*
1440 * Change to the DESTROY state.
1441 */
1442 TMTIMERSTATE enmState = pTimer->enmState;
1443 TMTIMERSTATE enmNewState = enmState;
1444 Log2(("TMTimerDestroy: %p:{.enmState=%s, .pszDesc='%s'} cRetries=%d\n",
1445 pTimer, tmTimerState(enmState), R3STRING(pTimer->pszDesc), cRetries));
1446 switch (enmState)
1447 {
1448 case TMTIMERSTATE_STOPPED:
1449 case TMTIMERSTATE_EXPIRED_DELIVER:
1450 break;
1451
1452 case TMTIMERSTATE_ACTIVE:
1453 fActive = true;
1454 break;
1455
1456 case TMTIMERSTATE_PENDING_STOP:
1457 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1458 case TMTIMERSTATE_PENDING_RESCHEDULE:
1459 fActive = true;
1460 fPending = true;
1461 break;
1462
1463 case TMTIMERSTATE_PENDING_SCHEDULE:
1464 fPending = true;
1465 break;
1466
1467 /*
1468 * This shouldn't happen as the caller should make sure there are no races.
1469 */
1470 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
1471 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1472 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1473 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1474 tmTimerUnlock(pVM);
1475 if (!RTThreadYield())
1476 RTThreadSleep(1);
1477 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1478 VERR_TM_UNSTABLE_STATE);
1479 tmTimerLock(pVM);
1480 continue;
1481
1482 /*
1483 * Invalid states.
1484 */
1485 case TMTIMERSTATE_FREE:
1486 case TMTIMERSTATE_DESTROY:
1487 tmTimerUnlock(pVM);
1488 AssertLogRelMsgFailedReturn(("pTimer=%p %s\n", pTimer, tmTimerState(enmState)), VERR_TM_INVALID_STATE);
1489
1490 default:
1491 AssertMsgFailed(("Unknown timer state %d (%s)\n", enmState, R3STRING(pTimer->pszDesc)));
1492 tmTimerUnlock(pVM);
1493 return VERR_TM_UNKNOWN_STATE;
1494 }
1495
1496 /*
1497 * Try switch to the destroy state.
1498 * This should always succeed as the caller should make sure there are no race.
1499 */
1500 bool fRc;
1501 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_DESTROY, enmState, fRc);
1502 if (fRc)
1503 break;
1504 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1505 tmTimerUnlock(pVM);
1506 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1507 VERR_TM_UNSTABLE_STATE);
1508 tmTimerLock(pVM);
1509 }
1510
1511 /*
1512 * Unlink from the active list.
1513 */
1514 if (fActive)
1515 {
1516 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1517 const PTMTIMER pNext = TMTIMER_GET_NEXT(pTimer);
1518 if (pPrev)
1519 TMTIMER_SET_NEXT(pPrev, pNext);
1520 else
1521 {
1522 TMTIMER_SET_HEAD(pQueue, pNext);
1523 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1524 }
1525 if (pNext)
1526 TMTIMER_SET_PREV(pNext, pPrev);
1527 pTimer->offNext = 0;
1528 pTimer->offPrev = 0;
1529 }
1530
1531 /*
1532 * Unlink from the schedule list by running it.
1533 */
1534 if (fPending)
1535 {
1536 Log3(("TMR3TimerDestroy: tmTimerQueueSchedule\n"));
1537 STAM_PROFILE_START(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1538 Assert(pQueue->offSchedule);
1539 tmTimerQueueSchedule(pVM, pQueue);
1540 }
1541
1542 /*
1543 * Read to move the timer from the created list and onto the free list.
1544 */
1545 Assert(!pTimer->offNext); Assert(!pTimer->offPrev); Assert(!pTimer->offScheduleNext);
1546
1547 /* unlink from created list */
1548 if (pTimer->pBigPrev)
1549 pTimer->pBigPrev->pBigNext = pTimer->pBigNext;
1550 else
1551 pVM->tm.s.pCreated = pTimer->pBigNext;
1552 if (pTimer->pBigNext)
1553 pTimer->pBigNext->pBigPrev = pTimer->pBigPrev;
1554 pTimer->pBigNext = 0;
1555 pTimer->pBigPrev = 0;
1556
1557 /* free */
1558 Log2(("TM: Inserting %p into the free list ahead of %p!\n", pTimer, pVM->tm.s.pFree));
1559 TM_SET_STATE(pTimer, TMTIMERSTATE_FREE);
1560 pTimer->pBigNext = pVM->tm.s.pFree;
1561 pVM->tm.s.pFree = pTimer;
1562
1563#ifdef VBOX_STRICT
1564 tmTimerQueuesSanityChecks(pVM, "TMR3TimerDestroy");
1565#endif
1566 tmTimerUnlock(pVM);
1567 return VINF_SUCCESS;
1568}
1569
1570
1571/**
1572 * Destroy all timers owned by a device.
1573 *
1574 * @returns VBox status.
1575 * @param pVM VM handle.
1576 * @param pDevIns Device which timers should be destroyed.
1577 */
1578VMM_INT_DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1579{
1580 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1581 if (!pDevIns)
1582 return VERR_INVALID_PARAMETER;
1583
1584 tmTimerLock(pVM);
1585 PTMTIMER pCur = pVM->tm.s.pCreated;
1586 while (pCur)
1587 {
1588 PTMTIMER pDestroy = pCur;
1589 pCur = pDestroy->pBigNext;
1590 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1591 && pDestroy->u.Dev.pDevIns == pDevIns)
1592 {
1593 int rc = TMR3TimerDestroy(pDestroy);
1594 AssertRC(rc);
1595 }
1596 }
1597 tmTimerUnlock(pVM);
1598
1599 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1600 return VINF_SUCCESS;
1601}
1602
1603
1604/**
1605 * Destroy all timers owned by a driver.
1606 *
1607 * @returns VBox status.
1608 * @param pVM VM handle.
1609 * @param pDrvIns Driver which timers should be destroyed.
1610 */
1611VMM_INT_DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1612{
1613 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1614 if (!pDrvIns)
1615 return VERR_INVALID_PARAMETER;
1616
1617 tmTimerLock(pVM);
1618 PTMTIMER pCur = pVM->tm.s.pCreated;
1619 while (pCur)
1620 {
1621 PTMTIMER pDestroy = pCur;
1622 pCur = pDestroy->pBigNext;
1623 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1624 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1625 {
1626 int rc = TMR3TimerDestroy(pDestroy);
1627 AssertRC(rc);
1628 }
1629 }
1630 tmTimerUnlock(pVM);
1631
1632 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1633 return VINF_SUCCESS;
1634}
1635
1636
1637/**
1638 * Internal function for getting the clock time.
1639 *
1640 * @returns clock time.
1641 * @param pVM The VM handle.
1642 * @param enmClock The clock.
1643 */
1644DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
1645{
1646 switch (enmClock)
1647 {
1648 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
1649 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
1650 case TMCLOCK_REAL: return TMRealGet(pVM);
1651 case TMCLOCK_TSC: return TMCpuTickGet(&pVM->aCpus[0] /* just take VCPU 0 */);
1652 default:
1653 AssertMsgFailed(("enmClock=%d\n", enmClock));
1654 return ~(uint64_t)0;
1655 }
1656}
1657
1658
1659/**
1660 * Checks if the sync queue has one or more expired timers.
1661 *
1662 * @returns true / false.
1663 *
1664 * @param pVM The VM handle.
1665 * @param enmClock The queue.
1666 */
1667DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1668{
1669 const uint64_t u64Expire = pVM->tm.s.CTX_SUFF(paTimerQueues)[enmClock].u64Expire;
1670 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1671}
1672
1673
1674/**
1675 * Checks for expired timers in all the queues.
1676 *
1677 * @returns true / false.
1678 * @param pVM The VM handle.
1679 */
1680DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1681{
1682 /*
1683 * Combine the time calculation for the first two since we're not on EMT
1684 * TMVirtualSyncGet only permits EMT.
1685 */
1686 uint64_t u64Now = TMVirtualGetNoCheck(pVM);
1687 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1688 return true;
1689 u64Now = pVM->tm.s.fVirtualSyncTicking
1690 ? u64Now - pVM->tm.s.offVirtualSync
1691 : pVM->tm.s.u64VirtualSync;
1692 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1693 return true;
1694
1695 /*
1696 * The remaining timers.
1697 */
1698 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1699 return true;
1700 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1701 return true;
1702 return false;
1703}
1704
1705
1706/**
1707 * Schedulation timer callback.
1708 *
1709 * @param pTimer Timer handle.
1710 * @param pvUser VM handle.
1711 * @thread Timer thread.
1712 *
1713 * @remark We cannot do the scheduling and queues running from a timer handler
1714 * since it's not executing in EMT, and even if it was it would be async
1715 * and we wouldn't know the state of the affairs.
1716 * So, we'll just raise the timer FF and force any REM execution to exit.
1717 */
1718static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1719{
1720 PVM pVM = (PVM)pvUser;
1721 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1722
1723 AssertCompile(TMCLOCK_MAX == 4);
1724#ifdef DEBUG_Sander /* very annoying, keep it private. */
1725 if (VMCPU_FF_ISSET(pVCpuDst, VMCPU_FF_TIMER))
1726 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1727#endif
1728 if ( !VMCPU_FF_ISSET(pVCpuDst, VMCPU_FF_TIMER)
1729 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule /** @todo FIXME - reconsider offSchedule as a reason for running the timer queues. */
1730 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1731 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1732 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1733 || tmR3AnyExpiredTimers(pVM)
1734 )
1735 && !VMCPU_FF_ISSET(pVCpuDst, VMCPU_FF_TIMER)
1736 && !pVM->tm.s.fRunningQueues
1737 )
1738 {
1739 Log5(("TM(%u): FF: 0 -> 1\n", __LINE__));
1740 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1741 REMR3NotifyTimerPending(pVM, pVCpuDst);
1742 VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM /** @todo | VMNOTIFYFF_FLAGS_POKE ?*/);
1743 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1744 }
1745}
1746
1747
1748/**
1749 * Schedules and runs any pending timers.
1750 *
1751 * This is normally called from a forced action handler in EMT.
1752 *
1753 * @param pVM The VM to run the timers for.
1754 *
1755 * @thread EMT (actually EMT0, but we fend off the others)
1756 */
1757VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1758{
1759 /*
1760 * Only the dedicated timer EMT should do stuff here.
1761 * (fRunningQueues is only used as an indicator.)
1762 */
1763 Assert(pVM->tm.s.idTimerCpu < pVM->cCpus);
1764 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1765 if (VMMGetCpu(pVM) != pVCpuDst)
1766 {
1767 Assert(pVM->cCpus > 1);
1768 return;
1769 }
1770 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1771 Log2(("TMR3TimerQueuesDo:\n"));
1772 Assert(!pVM->tm.s.fRunningQueues);
1773 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, true);
1774 tmTimerLock(pVM);
1775
1776 /*
1777 * Process the queues.
1778 */
1779 AssertCompile(TMCLOCK_MAX == 4);
1780
1781 /* TMCLOCK_VIRTUAL_SYNC (see also TMR3VirtualSyncFF) */
1782 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
1783 tmVirtualSyncLock(pVM);
1784 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
1785 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /* Clear the FF once we started working for real. */
1786
1787 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule)
1788 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
1789 tmR3TimerQueueRunVirtualSync(pVM);
1790 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
1791 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
1792
1793 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
1794 tmVirtualSyncUnlock(pVM);
1795 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
1796
1797 /* TMCLOCK_VIRTUAL */
1798 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
1799 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule)
1800 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1801 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1802 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
1803
1804 /* TMCLOCK_TSC */
1805 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offActive); /* not used */
1806
1807 /* TMCLOCK_REAL */
1808 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
1809 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule)
1810 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1811 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1812 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
1813
1814#ifdef VBOX_STRICT
1815 /* check that we didn't screwup. */
1816 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1817#endif
1818
1819 /* done */
1820 Log2(("TMR3TimerQueuesDo: returns void\n"));
1821 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, false);
1822 tmTimerUnlock(pVM);
1823 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1824}
1825
1826//RT_C_DECLS_BEGIN
1827//int iomLock(PVM pVM);
1828//void iomUnlock(PVM pVM);
1829//RT_C_DECLS_END
1830
1831
1832/**
1833 * Schedules and runs any pending times in the specified queue.
1834 *
1835 * This is normally called from a forced action handler in EMT.
1836 *
1837 * @param pVM The VM to run the timers for.
1838 * @param pQueue The queue to run.
1839 */
1840static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
1841{
1842 VM_ASSERT_EMT(pVM);
1843
1844 /*
1845 * Run timers.
1846 *
1847 * We check the clock once and run all timers which are ACTIVE
1848 * and have an expire time less or equal to the time we read.
1849 *
1850 * N.B. A generic unlink must be applied since other threads
1851 * are allowed to mess with any active timer at any time.
1852 * However, we only allow EMT to handle EXPIRED_PENDING
1853 * timers, thus enabling the timer handler function to
1854 * arm the timer again.
1855 */
1856 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1857 if (!pNext)
1858 return;
1859 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
1860 while (pNext && pNext->u64Expire <= u64Now)
1861 {
1862 PTMTIMER pTimer = pNext;
1863 pNext = TMTIMER_GET_NEXT(pTimer);
1864 PPDMCRITSECT pCritSect = pTimer->pCritSect;
1865 if (pCritSect)
1866 PDMCritSectEnter(pCritSect, VERR_INTERNAL_ERROR);
1867 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
1868 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
1869 bool fRc;
1870 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_GET_UNLINK, TMTIMERSTATE_ACTIVE, fRc);
1871 if (fRc)
1872 {
1873 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
1874
1875 /* unlink */
1876 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1877 if (pPrev)
1878 TMTIMER_SET_NEXT(pPrev, pNext);
1879 else
1880 {
1881 TMTIMER_SET_HEAD(pQueue, pNext);
1882 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1883 }
1884 if (pNext)
1885 TMTIMER_SET_PREV(pNext, pPrev);
1886 pTimer->offNext = 0;
1887 pTimer->offPrev = 0;
1888
1889 /* fire */
1890 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
1891 switch (pTimer->enmType)
1892 {
1893 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
1894 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
1895 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
1896 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
1897 default:
1898 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
1899 break;
1900 }
1901
1902 /* change the state if it wasn't changed already in the handler. */
1903 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
1904 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
1905 }
1906 if (pCritSect)
1907 PDMCritSectLeave(pCritSect);
1908 } /* run loop */
1909}
1910
1911
1912/**
1913 * Schedules and runs any pending times in the timer queue for the
1914 * synchronous virtual clock.
1915 *
1916 * This scheduling is a bit different from the other queues as it need
1917 * to implement the special requirements of the timer synchronous virtual
1918 * clock, thus this 2nd queue run funcion.
1919 *
1920 * @param pVM The VM to run the timers for.
1921 *
1922 * @remarks The caller must own both the TM/EMT and the Virtual Sync locks.
1923 */
1924static void tmR3TimerQueueRunVirtualSync(PVM pVM)
1925{
1926 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
1927 VM_ASSERT_EMT(pVM);
1928
1929 /*
1930 * Any timers?
1931 */
1932 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
1933 if (RT_UNLIKELY(!pNext))
1934 {
1935 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.cVirtualTicking);
1936 return;
1937 }
1938 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
1939
1940 /*
1941 * Calculate the time frame for which we will dispatch timers.
1942 *
1943 * We use a time frame ranging from the current sync time (which is most likely the
1944 * same as the head timer) and some configurable period (100000ns) up towards the
1945 * current virtual time. This period might also need to be restricted by the catch-up
1946 * rate so frequent calls to this function won't accelerate the time too much, however
1947 * this will be implemented at a later point if neccessary.
1948 *
1949 * Without this frame we would 1) having to run timers much more frequently
1950 * and 2) lag behind at a steady rate.
1951 */
1952 const uint64_t u64VirtualNow = TMVirtualGetNoCheck(pVM);
1953 uint64_t const offSyncGivenUp = pVM->tm.s.offVirtualSyncGivenUp;
1954 uint64_t u64Now;
1955 if (!pVM->tm.s.fVirtualSyncTicking)
1956 {
1957 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
1958 u64Now = pVM->tm.s.u64VirtualSync;
1959#ifdef DEBUG_bird
1960 Assert(u64Now <= pNext->u64Expire);
1961#endif
1962 }
1963 else
1964 {
1965 /* Calc 'now'. */
1966 bool fStopCatchup = false;
1967 bool fUpdateStuff = false;
1968 uint64_t off = pVM->tm.s.offVirtualSync;
1969 if (pVM->tm.s.fVirtualSyncCatchUp)
1970 {
1971 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
1972 if (RT_LIKELY(!(u64Delta >> 32)))
1973 {
1974 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
1975 if (off > u64Sub + offSyncGivenUp)
1976 {
1977 off -= u64Sub;
1978 Log4(("TM: %'RU64/-%'8RU64: sub %'RU64 [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow - off, off - offSyncGivenUp, u64Sub));
1979 }
1980 else
1981 {
1982 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1983 fStopCatchup = true;
1984 off = offSyncGivenUp;
1985 }
1986 fUpdateStuff = true;
1987 }
1988 }
1989 u64Now = u64VirtualNow - off;
1990
1991 /* Check if stopped by expired timer. */
1992 uint64_t u64Expire = pNext->u64Expire;
1993 if (u64Now >= pNext->u64Expire)
1994 {
1995 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
1996 u64Now = pNext->u64Expire;
1997 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
1998 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
1999 Log4(("TM: %'RU64/-%'8RU64: exp tmr [tmR3TimerQueueRunVirtualSync]\n", u64Now, u64VirtualNow - u64Now - offSyncGivenUp));
2000 }
2001 else if (fUpdateStuff)
2002 {
2003 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, off);
2004 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev, u64VirtualNow);
2005 if (fStopCatchup)
2006 {
2007 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2008 Log4(("TM: %'RU64/0: caught up [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow));
2009 }
2010 }
2011 }
2012
2013 /* calc end of frame. */
2014 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
2015 if (u64Max > u64VirtualNow - offSyncGivenUp)
2016 u64Max = u64VirtualNow - offSyncGivenUp;
2017
2018 /* assert sanity */
2019#ifdef DEBUG_bird
2020 Assert(u64Now <= u64VirtualNow - offSyncGivenUp);
2021 Assert(u64Max <= u64VirtualNow - offSyncGivenUp);
2022 Assert(u64Now <= u64Max);
2023 Assert(offSyncGivenUp == pVM->tm.s.offVirtualSyncGivenUp);
2024#endif
2025
2026 /*
2027 * Process the expired timers moving the clock along as we progress.
2028 */
2029#ifdef DEBUG_bird
2030#ifdef VBOX_STRICT
2031 uint64_t u64Prev = u64Now; NOREF(u64Prev);
2032#endif
2033#endif
2034 while (pNext && pNext->u64Expire <= u64Max)
2035 {
2036 PTMTIMER pTimer = pNext;
2037 pNext = TMTIMER_GET_NEXT(pTimer);
2038 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2039 if (pCritSect)
2040 PDMCritSectEnter(pCritSect, VERR_INTERNAL_ERROR);
2041 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2042 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2043 bool fRc;
2044 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_GET_UNLINK, TMTIMERSTATE_ACTIVE, fRc);
2045 if (fRc)
2046 {
2047 /* unlink */
2048 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
2049 if (pPrev)
2050 TMTIMER_SET_NEXT(pPrev, pNext);
2051 else
2052 {
2053 TMTIMER_SET_HEAD(pQueue, pNext);
2054 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
2055 }
2056 if (pNext)
2057 TMTIMER_SET_PREV(pNext, pPrev);
2058 pTimer->offNext = 0;
2059 pTimer->offPrev = 0;
2060
2061 /* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
2062#ifdef DEBUG_bird
2063#ifdef VBOX_STRICT
2064 AssertMsg(pTimer->u64Expire >= u64Prev, ("%'RU64 < %'RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
2065 u64Prev = pTimer->u64Expire;
2066#endif
2067#endif
2068 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
2069 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2070
2071 /* fire */
2072 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2073 switch (pTimer->enmType)
2074 {
2075 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2076 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2077 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2078 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2079 default:
2080 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2081 break;
2082 }
2083
2084 /* change the state if it wasn't changed already in the handler. */
2085 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2086 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2087 }
2088 if (pCritSect)
2089 PDMCritSectLeave(pCritSect);
2090 } /* run loop */
2091
2092 /*
2093 * Restart the clock if it was stopped to serve any timers,
2094 * and start/adjust catch-up if necessary.
2095 */
2096 if ( !pVM->tm.s.fVirtualSyncTicking
2097 && pVM->tm.s.cVirtualTicking)
2098 {
2099 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
2100
2101 /* calc the slack we've handed out. */
2102 const uint64_t u64VirtualNow2 = TMVirtualGetNoCheck(pVM);
2103 Assert(u64VirtualNow2 >= u64VirtualNow);
2104#ifdef DEBUG_bird
2105 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%'RU64 < %'RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
2106#endif
2107 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
2108 STAM_STATS({
2109 if (offSlack)
2110 {
2111 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
2112 p->cPeriods++;
2113 p->cTicks += offSlack;
2114 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
2115 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
2116 }
2117 });
2118
2119 /* Let the time run a little bit while we were busy running timers(?). */
2120 uint64_t u64Elapsed;
2121#define MAX_ELAPSED 30000U /* ns */
2122 if (offSlack > MAX_ELAPSED)
2123 u64Elapsed = 0;
2124 else
2125 {
2126 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
2127 if (u64Elapsed > MAX_ELAPSED)
2128 u64Elapsed = MAX_ELAPSED;
2129 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
2130 }
2131#undef MAX_ELAPSED
2132
2133 /* Calc the current offset. */
2134 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
2135 Assert(!(offNew & RT_BIT_64(63)));
2136 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
2137 Assert(!(offLag & RT_BIT_64(63)));
2138
2139 /*
2140 * Deal with starting, adjusting and stopping catchup.
2141 */
2142 if (pVM->tm.s.fVirtualSyncCatchUp)
2143 {
2144 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
2145 {
2146 /* stop */
2147 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2148 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2149 Log4(("TM: %'RU64/-%'8RU64: caught up [pt]\n", u64VirtualNow2 - offNew, offLag));
2150 }
2151 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2152 {
2153 /* adjust */
2154 unsigned i = 0;
2155 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2156 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2157 i++;
2158 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
2159 {
2160 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
2161 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2162 Log4(("TM: %'RU64/%'8RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2163 }
2164 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
2165 }
2166 else
2167 {
2168 /* give up */
2169 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
2170 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2171 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2172 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2173 Log4(("TM: %'RU64/%'8RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2174 LogRel(("TM: Giving up catch-up attempt at a %'RU64 ns lag; new total: %'RU64 ns\n", offLag, offNew));
2175 }
2176 }
2177 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
2178 {
2179 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2180 {
2181 /* start */
2182 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
2183 unsigned i = 0;
2184 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2185 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2186 i++;
2187 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
2188 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2189 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
2190 Log4(("TM: %'RU64/%'8RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2191 }
2192 else
2193 {
2194 /* don't bother */
2195 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
2196 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2197 Log4(("TM: %'RU64/%'8RU64: give up\n", u64VirtualNow2 - offNew, offLag));
2198 LogRel(("TM: Not bothering to attempt catching up a %'RU64 ns lag; new total: %'RU64\n", offLag, offNew));
2199 }
2200 }
2201
2202 /*
2203 * Update the offset and restart the clock.
2204 */
2205 Assert(!(offNew & RT_BIT_64(63)));
2206 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, offNew);
2207 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, true);
2208 }
2209}
2210
2211
2212/**
2213 * Deals with stopped Virtual Sync clock.
2214 *
2215 * This is called by the forced action flag handling code in EM when it
2216 * encounters the VM_FF_TM_VIRTUAL_SYNC flag. It is called by all VCPUs and they
2217 * will block on the VirtualSyncLock until the pending timers has been executed
2218 * and the clock restarted.
2219 *
2220 * @param pVM The VM to run the timers for.
2221 * @param pVCpu The virtual CPU we're running at.
2222 *
2223 * @thread EMTs
2224 */
2225VMM_INT_DECL(void) TMR3VirtualSyncFF(PVM pVM, PVMCPU pVCpu)
2226{
2227 Log2(("TMR3VirtualSyncFF:\n"));
2228
2229 /*
2230 * The EMT doing the timers is diverted to them.
2231 */
2232 if (pVCpu->idCpu == pVM->tm.s.idTimerCpu)
2233 TMR3TimerQueuesDo(pVM);
2234 /*
2235 * The other EMTs will block on the virtual sync lock and the first owner
2236 * will run the queue and thus restarting the clock.
2237 *
2238 * Note! This is very suboptimal code wrt to resuming execution when there
2239 * are more than two Virtual CPUs, since they will all have to enter
2240 * the critical section one by one. But it's a very simple solution
2241 * which will have to do the job for now.
2242 */
2243 else
2244 {
2245 STAM_PROFILE_START(&pVM->tm.s.StatVirtualSyncFF, a);
2246 tmVirtualSyncLock(pVM);
2247 if (pVM->tm.s.fVirtualSyncTicking)
2248 {
2249 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2250 tmVirtualSyncUnlock(pVM);
2251 Log2(("TMR3VirtualSyncFF: ticking\n"));
2252 }
2253 else
2254 {
2255 tmVirtualSyncUnlock(pVM);
2256
2257 /* try run it. */
2258 tmTimerLock(pVM);
2259 tmVirtualSyncLock(pVM);
2260 if (pVM->tm.s.fVirtualSyncTicking)
2261 Log2(("TMR3VirtualSyncFF: ticking (2)\n"));
2262 else
2263 {
2264 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
2265 Log2(("TMR3VirtualSyncFF: running queue\n"));
2266
2267 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule)
2268 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC]);
2269 tmR3TimerQueueRunVirtualSync(pVM);
2270 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
2271 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
2272
2273 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
2274 }
2275 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2276 tmVirtualSyncUnlock(pVM);
2277 tmTimerUnlock(pVM);
2278 }
2279 }
2280}
2281
2282
2283/** @name Saved state values
2284 * @{ */
2285#define TMTIMERSTATE_SAVED_PENDING_STOP 4
2286#define TMTIMERSTATE_SAVED_PENDING_SCHEDULE 7
2287/** @} */
2288
2289
2290/**
2291 * Saves the state of a timer to a saved state.
2292 *
2293 * @returns VBox status.
2294 * @param pTimer Timer to save.
2295 * @param pSSM Save State Manager handle.
2296 */
2297VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2298{
2299 LogFlow(("TMR3TimerSave: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2300 switch (pTimer->enmState)
2301 {
2302 case TMTIMERSTATE_STOPPED:
2303 case TMTIMERSTATE_PENDING_STOP:
2304 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
2305 return SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_STOP);
2306
2307 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
2308 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
2309 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
2310 if (!RTThreadYield())
2311 RTThreadSleep(1);
2312 /* fall thru */
2313 case TMTIMERSTATE_ACTIVE:
2314 case TMTIMERSTATE_PENDING_SCHEDULE:
2315 case TMTIMERSTATE_PENDING_RESCHEDULE:
2316 SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_SCHEDULE);
2317 return SSMR3PutU64(pSSM, pTimer->u64Expire);
2318
2319 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
2320 case TMTIMERSTATE_EXPIRED_DELIVER:
2321 case TMTIMERSTATE_DESTROY:
2322 case TMTIMERSTATE_FREE:
2323 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
2324 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
2325 }
2326
2327 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
2328 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
2329}
2330
2331
2332/**
2333 * Loads the state of a timer from a saved state.
2334 *
2335 * @returns VBox status.
2336 * @param pTimer Timer to restore.
2337 * @param pSSM Save State Manager handle.
2338 */
2339VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2340{
2341 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
2342 LogFlow(("TMR3TimerLoad: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2343
2344 /*
2345 * Load the state and validate it.
2346 */
2347 uint8_t u8State;
2348 int rc = SSMR3GetU8(pSSM, &u8State);
2349 if (RT_FAILURE(rc))
2350 return rc;
2351#if 1 /* Workaround for accidental state shift in r47786 (2009-05-26 19:12:12). */ /** @todo remove this in a few weeks! */
2352 if ( u8State == TMTIMERSTATE_SAVED_PENDING_STOP + 1
2353 || u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE + 1)
2354 u8State--;
2355#endif
2356 if ( u8State != TMTIMERSTATE_SAVED_PENDING_STOP
2357 && u8State != TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2358 {
2359 AssertLogRelMsgFailed(("u8State=%d\n", u8State));
2360 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
2361 }
2362
2363 /* Enter the critical section to make TMTimerSet/Stop happy. */
2364 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2365 if (pCritSect)
2366 PDMCritSectEnter(pCritSect, VERR_INTERNAL_ERROR);
2367
2368 if (u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2369 {
2370 /*
2371 * Load the expire time.
2372 */
2373 uint64_t u64Expire;
2374 rc = SSMR3GetU64(pSSM, &u64Expire);
2375 if (RT_FAILURE(rc))
2376 return rc;
2377
2378 /*
2379 * Set it.
2380 */
2381 Log(("u8State=%d u64Expire=%llu\n", u8State, u64Expire));
2382 rc = TMTimerSet(pTimer, u64Expire);
2383 }
2384 else
2385 {
2386 /*
2387 * Stop it.
2388 */
2389 Log(("u8State=%d\n", u8State));
2390 rc = TMTimerStop(pTimer);
2391 }
2392
2393 if (pCritSect)
2394 PDMCritSectLeave(pCritSect);
2395
2396 /*
2397 * On failure set SSM status.
2398 */
2399 if (RT_FAILURE(rc))
2400 rc = SSMR3HandleSetStatus(pSSM, rc);
2401 return rc;
2402}
2403
2404
2405/**
2406 * Associates a critical section with a timer.
2407 *
2408 * The critical section will be entered prior to doing the timer call back, thus
2409 * avoiding potential races between the timer thread and other threads trying to
2410 * stop or adjust the timer expiration while it's being delivered. The timer
2411 * thread will leave the critical section when the timer callback returns.
2412 *
2413 * In strict builds, ownership of the critical section will be asserted by
2414 * TMTimerSet, TMTimerStop, TMTimerGetExpire and TMTimerDestroy (when called at
2415 * runtime).
2416 *
2417 * @retval VINF_SUCCESS on success.
2418 * @retval VERR_INVALID_HANDLE if the timer handle is NULL or invalid
2419 * (asserted).
2420 * @retval VERR_INVALID_PARAMETER if pCritSect is NULL or has an invalid magic
2421 * (asserted).
2422 * @retval VERR_ALREADY_EXISTS if a critical section was already associated
2423 * with the timer (asserted).
2424 * @retval VERR_INVALID_STATE if the timer isn't stopped.
2425 *
2426 * @param pTimer The timer handle.
2427 * @param pCritSect The critical section. The caller must make sure this
2428 * is around for the life time of the timer.
2429 *
2430 * @thread Any, but the caller is responsible for making sure the timer is not
2431 * active.
2432 */
2433VMMR3DECL(int) TMR3TimerSetCritSect(PTMTIMERR3 pTimer, PPDMCRITSECT pCritSect)
2434{
2435 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
2436 AssertPtrReturn(pCritSect, VERR_INVALID_PARAMETER);
2437 const char *pszName = PDMR3CritSectName(pCritSect); /* exploited for validation */
2438 AssertReturn(pszName, VERR_INVALID_PARAMETER);
2439 AssertReturn(!pTimer->pCritSect, VERR_ALREADY_EXISTS);
2440 AssertReturn(pTimer->enmState == TMTIMERSTATE_STOPPED, VERR_INVALID_STATE);
2441 LogFlow(("pTimer=%p (%s) pCritSect=%p (%s)\n", pTimer, pTimer->pszDesc, pCritSect, pszName));
2442
2443 pTimer->pCritSect = pCritSect;
2444 return VINF_SUCCESS;
2445}
2446
2447
2448/**
2449 * Get the real world UTC time adjusted for VM lag.
2450 *
2451 * @returns pTime.
2452 * @param pVM The VM instance.
2453 * @param pTime Where to store the time.
2454 */
2455VMM_INT_DECL(PRTTIMESPEC) TMR3UtcNow(PVM pVM, PRTTIMESPEC pTime)
2456{
2457 RTTimeNow(pTime);
2458 RTTimeSpecSubNano(pTime, ASMAtomicReadU64(&pVM->tm.s.offVirtualSync) - ASMAtomicReadU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp));
2459 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
2460 return pTime;
2461}
2462
2463
2464/**
2465 * Pauses all clocks except TMCLOCK_REAL.
2466 *
2467 * @returns VBox status code, all errors are asserted.
2468 * @param pVM The VM handle.
2469 * @param pVCpu The virtual CPU handle.
2470 * @thread EMT corrsponding to the virtual CPU handle.
2471 */
2472VMMR3DECL(int) TMR3NotifySuspend(PVM pVM, PVMCPU pVCpu)
2473{
2474 VMCPU_ASSERT_EMT(pVCpu);
2475
2476 /*
2477 * The shared virtual clock (includes virtual sync which is tied to it).
2478 */
2479 tmTimerLock(pVM); /* Paranoia: Exploiting the timer lock here. */
2480 int rc = tmVirtualPauseLocked(pVM);
2481 tmTimerUnlock(pVM);
2482 if (RT_FAILURE(rc))
2483 return rc;
2484
2485 /*
2486 * Pause the TSC last since it is normally linked to the virtual
2487 * sync clock, so the above code may actually stop both clock.
2488 */
2489 rc = tmCpuTickPause(pVM, pVCpu);
2490 if (RT_FAILURE(rc))
2491 return rc;
2492
2493#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2494 /*
2495 * Update cNsTotal.
2496 */
2497 uint32_t uGen = ASMAtomicIncU32(&pVCpu->tm.s.uTimesGen); Assert(uGen & 1);
2498 pVCpu->tm.s.cNsTotal = RTTimeNanoTS() - pVCpu->tm.s.u64NsTsStartTotal;
2499 pVCpu->tm.s.cNsOther = pVCpu->tm.s.cNsTotal - pVCpu->tm.s.cNsExecuting - pVCpu->tm.s.cNsHalted;
2500 ASMAtomicWriteU32(&pVCpu->tm.s.uTimesGen, (uGen | 1) + 1);
2501#endif
2502
2503 return VINF_SUCCESS;
2504}
2505
2506
2507/**
2508 * Resumes all clocks except TMCLOCK_REAL.
2509 *
2510 * @returns VBox status code, all errors are asserted.
2511 * @param pVM The VM handle.
2512 * @param pVCpu The virtual CPU handle.
2513 * @thread EMT corrsponding to the virtual CPU handle.
2514 */
2515VMMR3DECL(int) TMR3NotifyResume(PVM pVM, PVMCPU pVCpu)
2516{
2517 VMCPU_ASSERT_EMT(pVCpu);
2518 int rc;
2519
2520#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2521 /*
2522 * Set u64NsTsStartTotal. There is no need to back this out if either of
2523 * the two calls below fail.
2524 */
2525 pVCpu->tm.s.u64NsTsStartTotal = RTTimeNanoTS() - pVCpu->tm.s.cNsTotal;
2526#endif
2527
2528 /*
2529 * Resume the TSC first since it is normally linked to the virtual sync
2530 * clock, so it may actually not be resumed until we've executed the code
2531 * below.
2532 */
2533 if (!pVM->tm.s.fTSCTiedToExecution)
2534 {
2535 rc = tmCpuTickResume(pVM, pVCpu);
2536 if (RT_FAILURE(rc))
2537 return rc;
2538 }
2539
2540 /*
2541 * The shared virtual clock (includes virtual sync which is tied to it).
2542 */
2543 tmTimerLock(pVM); /* Paranoia: Exploiting the timer lock here. */
2544 rc = tmVirtualResumeLocked(pVM);
2545 tmTimerUnlock(pVM);
2546
2547 return rc;
2548}
2549
2550
2551/**
2552 * Sets the warp drive percent of the virtual time.
2553 *
2554 * @returns VBox status code.
2555 * @param pVM The VM handle.
2556 * @param u32Percent The new percentage. 100 means normal operation.
2557 *
2558 * @todo Move to Ring-3!
2559 */
2560VMMDECL(int) TMR3SetWarpDrive(PVM pVM, uint32_t u32Percent)
2561{
2562 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)tmR3SetWarpDrive, 2, pVM, u32Percent);
2563}
2564
2565
2566/**
2567 * EMT worker for TMR3SetWarpDrive.
2568 *
2569 * @returns VBox status code.
2570 * @param pVM The VM handle.
2571 * @param u32Percent See TMR3SetWarpDrive().
2572 * @internal
2573 */
2574static DECLCALLBACK(int) tmR3SetWarpDrive(PVM pVM, uint32_t u32Percent)
2575{
2576 PVMCPU pVCpu = VMMGetCpu(pVM);
2577
2578 /*
2579 * Validate it.
2580 */
2581 AssertMsgReturn(u32Percent >= 2 && u32Percent <= 20000,
2582 ("%RX32 is not between 2 and 20000 (inclusive).\n", u32Percent),
2583 VERR_INVALID_PARAMETER);
2584
2585/** @todo This isn't a feature specific to virtual time, move the variables to
2586 * TM level and make it affect TMR3UCTNow as well! */
2587
2588 /*
2589 * If the time is running we'll have to pause it before we can change
2590 * the warp drive settings.
2591 */
2592 tmTimerLock(pVM); /* Paranoia: Exploiting the timer lock here. */
2593 bool fPaused = !!pVM->tm.s.cVirtualTicking;
2594 if (fPaused) /** @todo this isn't really working, but wtf. */
2595 TMR3NotifySuspend(pVM, pVCpu);
2596
2597 pVM->tm.s.u32VirtualWarpDrivePercentage = u32Percent;
2598 pVM->tm.s.fVirtualWarpDrive = u32Percent != 100;
2599 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32 fVirtualWarpDrive=%RTbool\n",
2600 pVM->tm.s.u32VirtualWarpDrivePercentage, pVM->tm.s.fVirtualWarpDrive));
2601
2602 if (fPaused)
2603 TMR3NotifyResume(pVM, pVCpu);
2604 tmTimerUnlock(pVM);
2605 return VINF_SUCCESS;
2606}
2607
2608
2609/**
2610 * Gets the performance information for one virtual CPU as seen by the VMM.
2611 *
2612 * The returned times covers the period where the VM is running and will be
2613 * reset when restoring a previous VM state (at least for the time being).
2614 *
2615 * @retval VINF_SUCCESS on success.
2616 * @retval VERR_NOT_IMPLEMENTED if not compiled in.
2617 * @retval VERR_INVALID_STATE if the VM handle is bad.
2618 * @retval VERR_INVALID_PARAMETER if idCpu is out of range.
2619 *
2620 * @param pVM The VM handle.
2621 * @param idCpu The ID of the virtual CPU which times to get.
2622 * @param pcNsTotal Where to store the total run time (nano seconds) of
2623 * the CPU, i.e. the sum of the three other returns.
2624 * Optional.
2625 * @param pcNsExecuting Where to store the time (nano seconds) spent
2626 * executing guest code. Optional.
2627 * @param pcNsHalted Where to store the time (nano seconds) spent
2628 * halted. Optional
2629 * @param pcNsOther Where to store the time (nano seconds) spent
2630 * preempted by the host scheduler, on virtualization
2631 * overhead and on other tasks.
2632 */
2633VMMR3DECL(int) TMR3GetCpuLoadTimes(PVM pVM, VMCPUID idCpu, uint64_t *pcNsTotal, uint64_t *pcNsExecuting,
2634 uint64_t *pcNsHalted, uint64_t *pcNsOther)
2635{
2636 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_STATE);
2637 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_PARAMETER);
2638
2639#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2640 /*
2641 * Get a stable result set.
2642 * This should be way quicker than an EMT request.
2643 */
2644 PVMCPU pVCpu = &pVM->aCpus[idCpu];
2645 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2646 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
2647 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
2648 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
2649 uint64_t cNsOther = pVCpu->tm.s.cNsOther;
2650 while ( (uTimesGen & 1) /* update in progress */
2651 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen))
2652 {
2653 RTThreadYield();
2654 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2655 cNsTotal = pVCpu->tm.s.cNsTotal;
2656 cNsExecuting = pVCpu->tm.s.cNsExecuting;
2657 cNsHalted = pVCpu->tm.s.cNsHalted;
2658 cNsOther = pVCpu->tm.s.cNsOther;
2659 }
2660
2661 /*
2662 * Fill in the return values.
2663 */
2664 if (pcNsTotal)
2665 *pcNsTotal = cNsTotal;
2666 if (pcNsExecuting)
2667 *pcNsExecuting = cNsExecuting;
2668 if (pcNsHalted)
2669 *pcNsHalted = cNsHalted;
2670 if (pcNsOther)
2671 *pcNsOther = cNsOther;
2672
2673 return VINF_SUCCESS;
2674
2675#else
2676 return VERR_NOT_IMPLEMENTED;
2677#endif
2678}
2679
2680
2681/**
2682 * Display all timers.
2683 *
2684 * @param pVM VM Handle.
2685 * @param pHlp The info helpers.
2686 * @param pszArgs Arguments, ignored.
2687 */
2688static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2689{
2690 NOREF(pszArgs);
2691 pHlp->pfnPrintf(pHlp,
2692 "Timers (pVM=%p)\n"
2693 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
2694 pVM,
2695 sizeof(RTR3PTR) * 2, "pTimerR3 ",
2696 sizeof(int32_t) * 2, "offNext ",
2697 sizeof(int32_t) * 2, "offPrev ",
2698 sizeof(int32_t) * 2, "offSched ",
2699 "Time",
2700 "Expire",
2701 "State");
2702 tmTimerLock(pVM);
2703 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
2704 {
2705 pHlp->pfnPrintf(pHlp,
2706 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
2707 pTimer,
2708 pTimer->offNext,
2709 pTimer->offPrev,
2710 pTimer->offScheduleNext,
2711 pTimer->enmClock == TMCLOCK_REAL ? "Real " : "Virt ",
2712 TMTimerGet(pTimer),
2713 pTimer->u64Expire,
2714 tmTimerState(pTimer->enmState),
2715 pTimer->pszDesc);
2716 }
2717 tmTimerUnlock(pVM);
2718}
2719
2720
2721/**
2722 * Display all active timers.
2723 *
2724 * @param pVM VM Handle.
2725 * @param pHlp The info helpers.
2726 * @param pszArgs Arguments, ignored.
2727 */
2728static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2729{
2730 NOREF(pszArgs);
2731 pHlp->pfnPrintf(pHlp,
2732 "Active Timers (pVM=%p)\n"
2733 "%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
2734 pVM,
2735 sizeof(RTR3PTR) * 2, "pTimerR3 ",
2736 sizeof(int32_t) * 2, "offNext ",
2737 sizeof(int32_t) * 2, "offPrev ",
2738 sizeof(int32_t) * 2, "offSched ",
2739 "Time",
2740 "Expire",
2741 "State");
2742 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
2743 {
2744 tmTimerLock(pVM);
2745 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
2746 pTimer;
2747 pTimer = TMTIMER_GET_NEXT(pTimer))
2748 {
2749 pHlp->pfnPrintf(pHlp,
2750 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
2751 pTimer,
2752 pTimer->offNext,
2753 pTimer->offPrev,
2754 pTimer->offScheduleNext,
2755 pTimer->enmClock == TMCLOCK_REAL
2756 ? "Real "
2757 : pTimer->enmClock == TMCLOCK_VIRTUAL
2758 ? "Virt "
2759 : pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC
2760 ? "VrSy "
2761 : "TSC ",
2762 TMTimerGet(pTimer),
2763 pTimer->u64Expire,
2764 tmTimerState(pTimer->enmState),
2765 pTimer->pszDesc);
2766 }
2767 tmTimerUnlock(pVM);
2768 }
2769}
2770
2771
2772/**
2773 * Display all clocks.
2774 *
2775 * @param pVM VM Handle.
2776 * @param pHlp The info helpers.
2777 * @param pszArgs Arguments, ignored.
2778 */
2779static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2780{
2781 NOREF(pszArgs);
2782
2783 /*
2784 * Read the times first to avoid more than necessary time variation.
2785 */
2786 const uint64_t u64Virtual = TMVirtualGet(pVM);
2787 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
2788 const uint64_t u64Real = TMRealGet(pVM);
2789
2790 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2791 {
2792 PVMCPU pVCpu = &pVM->aCpus[i];
2793 uint64_t u64TSC = TMCpuTickGet(pVCpu);
2794
2795 /*
2796 * TSC
2797 */
2798 pHlp->pfnPrintf(pHlp,
2799 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
2800 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
2801 pVCpu->tm.s.fTSCTicking ? "ticking" : "paused",
2802 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
2803 if (pVM->tm.s.fTSCUseRealTSC)
2804 {
2805 pHlp->pfnPrintf(pHlp, " - real tsc");
2806 if (pVCpu->tm.s.offTSCRawSrc)
2807 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVCpu->tm.s.offTSCRawSrc);
2808 }
2809 else
2810 pHlp->pfnPrintf(pHlp, " - virtual clock");
2811 pHlp->pfnPrintf(pHlp, "\n");
2812 }
2813
2814 /*
2815 * virtual
2816 */
2817 pHlp->pfnPrintf(pHlp,
2818 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
2819 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
2820 pVM->tm.s.cVirtualTicking ? "ticking" : "paused");
2821 if (pVM->tm.s.fVirtualWarpDrive)
2822 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
2823 pHlp->pfnPrintf(pHlp, "\n");
2824
2825 /*
2826 * virtual sync
2827 */
2828 pHlp->pfnPrintf(pHlp,
2829 "VirtSync: %18RU64 (%#016RX64) %s%s",
2830 u64VirtualSync, u64VirtualSync,
2831 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
2832 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
2833 if (pVM->tm.s.offVirtualSync)
2834 {
2835 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
2836 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
2837 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
2838 }
2839 pHlp->pfnPrintf(pHlp, "\n");
2840
2841 /*
2842 * real
2843 */
2844 pHlp->pfnPrintf(pHlp,
2845 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
2846 u64Real, u64Real, TMRealGetFreq(pVM));
2847}
2848
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