VirtualBox

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

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

VMM, recompiler: Purge deprecated macros.

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