VirtualBox

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

Last change on this file since 42493 was 42493, checked in by vboxsync, 12 years ago

VMM/VMMR3/TM: Fixed-rate TSC detection for VIA Cpus.

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