VirtualBox

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

最後變更 在這個檔案從51867是 51867,由 vboxsync 提交於 11 年 前

TM: Made the SYNC_TSC_PAUSE code default.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Id Revision
檔案大小: 138.4 KB
 
1/* $Id: TM.cpp 51867 2014-07-04 12:53:36Z 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.alldomusa.eu.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 STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/TSC/Pause", STAMUNIT_OCCURENCES, "The number of times the TSC was paused.");
701 STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/TSC/Resume", STAMUNIT_OCCURENCES, "The number of times the TSC was resumed.");
702#endif /* VBOX_WITH_STATISTICS */
703
704 for (VMCPUID i = 0; i < pVM->cCpus; i++)
705 {
706 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);
707#ifndef VBOX_WITHOUT_NS_ACCOUNTING
708# if defined(VBOX_WITH_STATISTICS) || defined(VBOX_WITH_NS_ACCOUNTING_STATS)
709 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.StatNsTotal, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Resettable: Total CPU run time.", "/TM/CPU/%02u", i);
710 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);
711 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);
712 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);
713 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);
714 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);
715 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);
716# endif
717 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsTotal, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Total CPU run time.", "/TM/CPU/%02u/cNsTotal", i);
718 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsExecuting, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent executing guest code.", "/TM/CPU/%02u/cNsExecuting", i);
719 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cNsHalted, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_NS, "Time spent halted.", "/TM/CPU/%02u/cNsHalted", i);
720 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);
721 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cPeriodsExecuting, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT, "Times executed guest code.", "/TM/CPU/%02u/cPeriodsExecuting", i);
722 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.cPeriodsHalted, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT, "Times halted.", "/TM/CPU/%02u/cPeriodsHalted", i);
723 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);
724 STAMR3RegisterF(pVM, &pVM->aCpus[i].tm.s.CpuLoad.cPctHalted, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent halted recently.", "/TM/CPU/%02u/pctHalted", i);
725 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);
726#endif
727 }
728#ifndef VBOX_WITHOUT_NS_ACCOUNTING
729 STAMR3RegisterF(pVM, &pVM->tm.s.CpuLoad.cPctExecuting, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent executing guest code recently.", "/TM/CPU/pctExecuting");
730 STAMR3RegisterF(pVM, &pVM->tm.s.CpuLoad.cPctHalted, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent halted recently.", "/TM/CPU/pctHalted");
731 STAMR3RegisterF(pVM, &pVM->tm.s.CpuLoad.cPctOther, STAMTYPE_U8, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "Time spent in the VMM or preempted recently.", "/TM/CPU/pctOther");
732#endif
733
734#ifdef VBOX_WITH_STATISTICS
735 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.");
736 STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
737 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)");
738 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.");
739 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
740 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++.)");
741 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
742 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
743 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.");
744 STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
745 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.)");
746 for (unsigned i = 0; i < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods); i++)
747 {
748 STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
749 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
750 STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
751 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);
752 }
753#endif /* VBOX_WITH_STATISTICS */
754
755 /*
756 * Register info handlers.
757 */
758 DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
759 DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
760 DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
761
762 return VINF_SUCCESS;
763}
764
765
766/**
767 * Checks if the host CPU has a fixed TSC frequency.
768 *
769 * @returns true if it has, false if it hasn't.
770 *
771 * @remark This test doesn't bother with very old CPUs that don't do power
772 * management or any other stuff that might influence the TSC rate.
773 * This isn't currently relevant.
774 */
775static bool tmR3HasFixedTSC(PVM pVM)
776{
777 if (ASMHasCpuId())
778 {
779 uint32_t uEAX, uEBX, uECX, uEDX;
780
781 if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_AMD)
782 {
783 /*
784 * AuthenticAMD - Check for APM support and that TscInvariant is set.
785 *
786 * This test isn't correct with respect to fixed/non-fixed TSC and
787 * older models, but this isn't relevant since the result is currently
788 * only used for making a decision on AMD-V models.
789 */
790 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
791 if (uEAX >= 0x80000007)
792 {
793 PSUPGLOBALINFOPAGE pGip = g_pSUPGlobalInfoPage;
794
795 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
796 if ( (uEDX & X86_CPUID_AMD_ADVPOWER_EDX_TSCINVAR) /* TscInvariant */
797 && pGip->u32Mode == SUPGIPMODE_SYNC_TSC /* no fixed tsc if the gip timer is in async mode */)
798 return true;
799 }
800 }
801 else if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_INTEL)
802 {
803 /*
804 * GenuineIntel - Check the model number.
805 *
806 * This test is lacking in the same way and for the same reasons
807 * as the AMD test above.
808 */
809 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
810 unsigned uModel = (uEAX >> 4) & 0x0f;
811 unsigned uFamily = (uEAX >> 8) & 0x0f;
812 if (uFamily == 0x0f)
813 uFamily += (uEAX >> 20) & 0xff;
814 if (uFamily >= 0x06)
815 uModel += ((uEAX >> 16) & 0x0f) << 4;
816 if ( (uFamily == 0x0f /*P4*/ && uModel >= 0x03)
817 || (uFamily == 0x06 /*P2/P3*/ && uModel >= 0x0e))
818 return true;
819 }
820 else if (CPUMGetHostCpuVendor(pVM) == CPUMCPUVENDOR_VIA)
821 {
822 /*
823 * CentaurHauls - Check the model, family and stepping.
824 *
825 * This only checks for VIA CPU models Nano X2, Nano X3,
826 * Eden X2 and QuadCore.
827 */
828 ASMCpuId(1, &uEAX, &uEBX, &uECX, &uEDX);
829 unsigned uStepping = (uEAX & 0x0f);
830 unsigned uModel = (uEAX >> 4) & 0x0f;
831 unsigned uFamily = (uEAX >> 8) & 0x0f;
832 if ( uFamily == 0x06
833 && uModel == 0x0f
834 && uStepping >= 0x0c
835 && uStepping <= 0x0f)
836 {
837 return true;
838 }
839 }
840 }
841 return false;
842}
843
844
845/**
846 * Calibrate the CPU tick.
847 *
848 * @returns Number of ticks per second.
849 */
850static uint64_t tmR3CalibrateTSC(PVM pVM)
851{
852 /*
853 * Use GIP when available present.
854 */
855 uint64_t u64Hz = SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage);
856 if (u64Hz != UINT64_MAX)
857 {
858 if (tmR3HasFixedTSC(pVM))
859 /* Sleep a bit to get a more reliable CpuHz value. */
860 RTThreadSleep(32);
861 else
862 {
863 /* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
864 const uint64_t u64 = RTTimeMilliTS();
865 while ((RTTimeMilliTS() - u64) < 40 /*ms*/)
866 /* nothing */;
867 }
868
869 u64Hz = SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage);
870 if (u64Hz != UINT64_MAX)
871 return u64Hz;
872 }
873
874 /* call this once first to make sure it's initialized. */
875 RTTimeNanoTS();
876
877 /*
878 * Yield the CPU to increase our chances of getting
879 * a correct value.
880 */
881 RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
882 static const unsigned s_auSleep[5] = { 50, 30, 30, 40, 40 };
883 uint64_t au64Samples[5];
884 unsigned i;
885 for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
886 {
887 RTMSINTERVAL cMillies;
888 int cTries = 5;
889 uint64_t u64Start = ASMReadTSC();
890 uint64_t u64End;
891 uint64_t StartTS = RTTimeNanoTS();
892 uint64_t EndTS;
893 do
894 {
895 RTThreadSleep(s_auSleep[i]);
896 u64End = ASMReadTSC();
897 EndTS = RTTimeNanoTS();
898 cMillies = (RTMSINTERVAL)((EndTS - StartTS + 500000) / 1000000);
899 } while ( cMillies == 0 /* the sleep may be interrupted... */
900 || (cMillies < 20 && --cTries > 0));
901 uint64_t u64Diff = u64End - u64Start;
902
903 au64Samples[i] = (u64Diff * 1000) / cMillies;
904 AssertMsg(cTries > 0, ("cMillies=%d i=%d\n", cMillies, i));
905 }
906
907 /*
908 * Discard the highest and lowest results and calculate the average.
909 */
910 unsigned iHigh = 0;
911 unsigned iLow = 0;
912 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
913 {
914 if (au64Samples[i] < au64Samples[iLow])
915 iLow = i;
916 if (au64Samples[i] > au64Samples[iHigh])
917 iHigh = i;
918 }
919 au64Samples[iLow] = 0;
920 au64Samples[iHigh] = 0;
921
922 u64Hz = au64Samples[0];
923 for (i = 1; i < RT_ELEMENTS(au64Samples); i++)
924 u64Hz += au64Samples[i];
925 u64Hz /= RT_ELEMENTS(au64Samples) - 2;
926
927 return u64Hz;
928}
929
930
931/**
932 * Finalizes the TM initialization.
933 *
934 * @returns VBox status code.
935 * @param pVM Pointer to the VM.
936 */
937VMM_INT_DECL(int) TMR3InitFinalize(PVM pVM)
938{
939 int rc;
940
941 /*
942 * Resolve symbols.
943 */
944 if (!HMIsEnabled(pVM))
945 {
946 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
947 AssertRCReturn(rc, rc);
948 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
949 AssertRCReturn(rc, rc);
950 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
951 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
952 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
953 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
954 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
955 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
956 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
957 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
958 else
959 AssertFatalFailed();
960 AssertRCReturn(rc, rc);
961 }
962
963 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
964 AssertRCReturn(rc, rc);
965 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
966 AssertRCReturn(rc, rc);
967 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
968 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawR0);
969 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
970 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawR0);
971 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
972 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawR0);
973 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
974 rc = PDMR3LdrGetSymbolR0(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawR0);
975 else
976 AssertFatalFailed();
977 AssertRCReturn(rc, rc);
978
979#ifndef VBOX_WITHOUT_NS_ACCOUNTING
980 /*
981 * Create a timer for refreshing the CPU load stats.
982 */
983 PTMTIMER pTimer;
984 rc = TMR3TimerCreateInternal(pVM, TMCLOCK_REAL, tmR3CpuLoadTimer, NULL, "CPU Load Timer", &pTimer);
985 if (RT_SUCCESS(rc))
986 rc = TMTimerSetMillies(pTimer, 1000);
987#endif
988
989 return rc;
990}
991
992
993/**
994 * Applies relocations to data and code managed by this
995 * component. This function will be called at init and
996 * whenever the VMM need to relocate it self inside the GC.
997 *
998 * @param pVM The VM.
999 * @param offDelta Relocation delta relative to old location.
1000 */
1001VMM_INT_DECL(void) TMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
1002{
1003 int rc;
1004 LogFlow(("TMR3Relocate\n"));
1005 NOREF(offDelta);
1006
1007 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pVM->tm.s.paTimerQueuesR3);
1008
1009 if (!HMIsEnabled(pVM))
1010 {
1011 pVM->tm.s.pvGIPRC = MMHyperR3ToRC(pVM, pVM->tm.s.pvGIPR3);
1012 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pVM->tm.s.paTimerQueuesR3);
1013 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
1014 AssertFatal(pVM->tm.s.VirtualGetRawDataRC.pu64Prev);
1015 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
1016 AssertFatalRC(rc);
1017 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
1018 AssertFatalRC(rc);
1019
1020 if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceSync)
1021 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLFenceSync", &pVM->tm.s.pfnVirtualGetRawRC);
1022 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLFenceAsync)
1023 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLFenceAsync", &pVM->tm.s.pfnVirtualGetRawRC);
1024 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacySync)
1025 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLegacySync", &pVM->tm.s.pfnVirtualGetRawRC);
1026 else if (pVM->tm.s.pfnVirtualGetRawR3 == RTTimeNanoTSLegacyAsync)
1027 rc = PDMR3LdrGetSymbolRC(pVM, NULL, "RTTimeNanoTSLegacyAsync", &pVM->tm.s.pfnVirtualGetRawRC);
1028 else
1029 AssertFatalFailed();
1030 AssertFatalRC(rc);
1031 }
1032
1033 /*
1034 * Iterate the timers updating the pVMRC pointers.
1035 */
1036 for (PTMTIMER pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
1037 {
1038 pTimer->pVMRC = pVM->pVMRC;
1039 pTimer->pVMR0 = pVM->pVMR0;
1040 }
1041}
1042
1043
1044/**
1045 * Terminates the TM.
1046 *
1047 * Termination means cleaning up and freeing all resources,
1048 * the VM it self is at this point powered off or suspended.
1049 *
1050 * @returns VBox status code.
1051 * @param pVM Pointer to the VM.
1052 */
1053VMM_INT_DECL(int) TMR3Term(PVM pVM)
1054{
1055 AssertMsg(pVM->tm.s.offVM, ("bad init order!\n"));
1056 if (pVM->tm.s.pTimer)
1057 {
1058 int rc = RTTimerDestroy(pVM->tm.s.pTimer);
1059 AssertRC(rc);
1060 pVM->tm.s.pTimer = NULL;
1061 }
1062
1063 return VINF_SUCCESS;
1064}
1065
1066
1067/**
1068 * The VM is being reset.
1069 *
1070 * For the TM component this means that a rescheduling is preformed,
1071 * the FF is cleared and but without running the queues. We'll have to
1072 * check if this makes sense or not, but it seems like a good idea now....
1073 *
1074 * @param pVM Pointer to the VM.
1075 */
1076VMM_INT_DECL(void) TMR3Reset(PVM pVM)
1077{
1078 LogFlow(("TMR3Reset:\n"));
1079 VM_ASSERT_EMT(pVM);
1080 TM_LOCK_TIMERS(pVM);
1081
1082 /*
1083 * Abort any pending catch up.
1084 * This isn't perfect...
1085 */
1086 if (pVM->tm.s.fVirtualSyncCatchUp)
1087 {
1088 const uint64_t offVirtualNow = TMVirtualGetNoCheck(pVM);
1089 const uint64_t offVirtualSyncNow = TMVirtualSyncGetNoCheck(pVM);
1090 if (pVM->tm.s.fVirtualSyncCatchUp)
1091 {
1092 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
1093
1094 const uint64_t offOld = pVM->tm.s.offVirtualSyncGivenUp;
1095 const uint64_t offNew = offVirtualNow - offVirtualSyncNow;
1096 Assert(offOld <= offNew);
1097 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
1098 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSync, offNew);
1099 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
1100 LogRel(("TM: Aborting catch-up attempt on reset with a %'RU64 ns lag on reset; new total: %'RU64 ns\n", offNew - offOld, offNew));
1101 }
1102 }
1103
1104 /*
1105 * Process the queues.
1106 */
1107 for (int i = 0; i < TMCLOCK_MAX; i++)
1108 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[i]);
1109#ifdef VBOX_STRICT
1110 tmTimerQueuesSanityChecks(pVM, "TMR3Reset");
1111#endif
1112
1113 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1114 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /** @todo FIXME: this isn't right. */
1115 TM_UNLOCK_TIMERS(pVM);
1116}
1117
1118
1119/**
1120 * Resolve a builtin RC symbol.
1121 * Called by PDM when loading or relocating GC modules.
1122 *
1123 * @returns VBox status
1124 * @param pVM Pointer to the VM.
1125 * @param pszSymbol Symbol to resolve.
1126 * @param pRCPtrValue Where to store the symbol value.
1127 * @remark This has to work before TMR3Relocate() is called.
1128 */
1129VMM_INT_DECL(int) TMR3GetImportRC(PVM pVM, const char *pszSymbol, PRTRCPTR pRCPtrValue)
1130{
1131 if (!strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
1132 *pRCPtrValue = MMHyperR3ToRC(pVM, &pVM->tm.s.pvGIPRC);
1133 //else if (..)
1134 else
1135 return VERR_SYMBOL_NOT_FOUND;
1136 return VINF_SUCCESS;
1137}
1138
1139
1140/**
1141 * Execute state save operation.
1142 *
1143 * @returns VBox status code.
1144 * @param pVM Pointer to the VM.
1145 * @param pSSM SSM operation handle.
1146 */
1147static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM)
1148{
1149 LogFlow(("tmR3Save:\n"));
1150#ifdef VBOX_STRICT
1151 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1152 {
1153 PVMCPU pVCpu = &pVM->aCpus[i];
1154 Assert(!pVCpu->tm.s.fTSCTicking);
1155 }
1156 Assert(!pVM->tm.s.cVirtualTicking);
1157 Assert(!pVM->tm.s.fVirtualSyncTicking);
1158 Assert(!pVM->tm.s.cTSCsTicking);
1159#endif
1160
1161 /*
1162 * Save the virtual clocks.
1163 */
1164 /* the virtual clock. */
1165 SSMR3PutU64(pSSM, TMCLOCK_FREQ_VIRTUAL);
1166 SSMR3PutU64(pSSM, pVM->tm.s.u64Virtual);
1167
1168 /* the virtual timer synchronous clock. */
1169 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSync);
1170 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSync);
1171 SSMR3PutU64(pSSM, pVM->tm.s.offVirtualSyncGivenUp);
1172 SSMR3PutU64(pSSM, pVM->tm.s.u64VirtualSyncCatchUpPrev);
1173 SSMR3PutBool(pSSM, pVM->tm.s.fVirtualSyncCatchUp);
1174
1175 /* real time clock */
1176 SSMR3PutU64(pSSM, TMCLOCK_FREQ_REAL);
1177
1178 /* the cpu tick clock. */
1179 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1180 {
1181 PVMCPU pVCpu = &pVM->aCpus[i];
1182 SSMR3PutU64(pSSM, TMCpuTickGet(pVCpu));
1183 }
1184 return SSMR3PutU64(pSSM, pVM->tm.s.cTSCTicksPerSecond);
1185}
1186
1187
1188/**
1189 * Execute state load operation.
1190 *
1191 * @returns VBox status code.
1192 * @param pVM Pointer to the VM.
1193 * @param pSSM SSM operation handle.
1194 * @param uVersion Data layout version.
1195 * @param uPass The data pass.
1196 */
1197static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
1198{
1199 LogFlow(("tmR3Load:\n"));
1200
1201 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
1202#ifdef VBOX_STRICT
1203 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1204 {
1205 PVMCPU pVCpu = &pVM->aCpus[i];
1206 Assert(!pVCpu->tm.s.fTSCTicking);
1207 }
1208 Assert(!pVM->tm.s.cVirtualTicking);
1209 Assert(!pVM->tm.s.fVirtualSyncTicking);
1210 Assert(!pVM->tm.s.cTSCsTicking);
1211#endif
1212
1213 /*
1214 * Validate version.
1215 */
1216 if (uVersion != TM_SAVED_STATE_VERSION)
1217 {
1218 AssertMsgFailed(("tmR3Load: Invalid version uVersion=%d!\n", uVersion));
1219 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1220 }
1221
1222 /*
1223 * Load the virtual clock.
1224 */
1225 pVM->tm.s.cVirtualTicking = 0;
1226 pVM->tm.s.cTSCsTicking = 0;
1227 /* the virtual clock. */
1228 uint64_t u64Hz;
1229 int rc = SSMR3GetU64(pSSM, &u64Hz);
1230 if (RT_FAILURE(rc))
1231 return rc;
1232 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
1233 {
1234 AssertMsgFailed(("The virtual clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1235 u64Hz, TMCLOCK_FREQ_VIRTUAL));
1236 return VERR_SSM_VIRTUAL_CLOCK_HZ;
1237 }
1238 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
1239 pVM->tm.s.u64VirtualOffset = 0;
1240
1241 /* the virtual timer synchronous clock. */
1242 pVM->tm.s.fVirtualSyncTicking = false;
1243 uint64_t u64;
1244 SSMR3GetU64(pSSM, &u64);
1245 pVM->tm.s.u64VirtualSync = u64;
1246 SSMR3GetU64(pSSM, &u64);
1247 pVM->tm.s.offVirtualSync = u64;
1248 SSMR3GetU64(pSSM, &u64);
1249 pVM->tm.s.offVirtualSyncGivenUp = u64;
1250 SSMR3GetU64(pSSM, &u64);
1251 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1252 bool f;
1253 SSMR3GetBool(pSSM, &f);
1254 pVM->tm.s.fVirtualSyncCatchUp = f;
1255
1256 /* the real clock */
1257 rc = SSMR3GetU64(pSSM, &u64Hz);
1258 if (RT_FAILURE(rc))
1259 return rc;
1260 if (u64Hz != TMCLOCK_FREQ_REAL)
1261 {
1262 AssertMsgFailed(("The real clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1263 u64Hz, TMCLOCK_FREQ_REAL));
1264 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* misleading... */
1265 }
1266
1267 /* the cpu tick clock. */
1268 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1269 {
1270 PVMCPU pVCpu = &pVM->aCpus[i];
1271
1272 pVCpu->tm.s.fTSCTicking = false;
1273 SSMR3GetU64(pSSM, &pVCpu->tm.s.u64TSC);
1274
1275 if (pVM->tm.s.fTSCUseRealTSC)
1276 pVCpu->tm.s.offTSCRawSrc = 0; /** @todo TSC restore stuff and HWACC. */
1277 }
1278
1279 rc = SSMR3GetU64(pSSM, &u64Hz);
1280 if (RT_FAILURE(rc))
1281 return rc;
1282 if (!pVM->tm.s.fTSCUseRealTSC)
1283 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1284
1285 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%'RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1286 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1287
1288 /*
1289 * Make sure timers get rescheduled immediately.
1290 */
1291 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1292 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1293
1294 return VINF_SUCCESS;
1295}
1296
1297
1298/**
1299 * Internal TMR3TimerCreate worker.
1300 *
1301 * @returns VBox status code.
1302 * @param pVM Pointer to the VM.
1303 * @param enmClock The timer clock.
1304 * @param pszDesc The timer description.
1305 * @param ppTimer Where to store the timer pointer on success.
1306 */
1307static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1308{
1309 VM_ASSERT_EMT(pVM);
1310
1311 /*
1312 * Allocate the timer.
1313 */
1314 PTMTIMERR3 pTimer = NULL;
1315 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1316 {
1317 pTimer = pVM->tm.s.pFree;
1318 pVM->tm.s.pFree = pTimer->pBigNext;
1319 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1320 }
1321
1322 if (!pTimer)
1323 {
1324 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1325 if (RT_FAILURE(rc))
1326 return rc;
1327 Log3(("TM: Allocated new timer %p\n", pTimer));
1328 }
1329
1330 /*
1331 * Initialize it.
1332 */
1333 pTimer->u64Expire = 0;
1334 pTimer->enmClock = enmClock;
1335 pTimer->pVMR3 = pVM;
1336 pTimer->pVMR0 = pVM->pVMR0;
1337 pTimer->pVMRC = pVM->pVMRC;
1338 pTimer->enmState = TMTIMERSTATE_STOPPED;
1339 pTimer->offScheduleNext = 0;
1340 pTimer->offNext = 0;
1341 pTimer->offPrev = 0;
1342 pTimer->pvUser = NULL;
1343 pTimer->pCritSect = NULL;
1344 pTimer->pszDesc = pszDesc;
1345
1346 /* insert into the list of created timers. */
1347 TM_LOCK_TIMERS(pVM);
1348 pTimer->pBigPrev = NULL;
1349 pTimer->pBigNext = pVM->tm.s.pCreated;
1350 pVM->tm.s.pCreated = pTimer;
1351 if (pTimer->pBigNext)
1352 pTimer->pBigNext->pBigPrev = pTimer;
1353#ifdef VBOX_STRICT
1354 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1355#endif
1356 TM_UNLOCK_TIMERS(pVM);
1357
1358 *ppTimer = pTimer;
1359 return VINF_SUCCESS;
1360}
1361
1362
1363/**
1364 * Creates a device timer.
1365 *
1366 * @returns VBox status.
1367 * @param pVM The VM to create the timer in.
1368 * @param pDevIns Device instance.
1369 * @param enmClock The clock to use on this timer.
1370 * @param pfnCallback Callback function.
1371 * @param pvUser The user argument to the callback.
1372 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1373 * @param pszDesc Pointer to description string which must stay around
1374 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1375 * @param ppTimer Where to store the timer on success.
1376 */
1377VMM_INT_DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock,
1378 PFNTMTIMERDEV pfnCallback, void *pvUser,
1379 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1380{
1381 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1382
1383 /*
1384 * Allocate and init stuff.
1385 */
1386 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1387 if (RT_SUCCESS(rc))
1388 {
1389 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1390 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1391 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1392 (*ppTimer)->pvUser = pvUser;
1393 if (!(fFlags & TMTIMER_FLAGS_NO_CRIT_SECT))
1394 (*ppTimer)->pCritSect = PDMR3DevGetCritSect(pVM, pDevIns);
1395 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1396 }
1397
1398 return rc;
1399}
1400
1401
1402
1403
1404/**
1405 * Creates a USB device timer.
1406 *
1407 * @returns VBox status.
1408 * @param pVM The VM to create the timer in.
1409 * @param pUsbIns The USB device instance.
1410 * @param enmClock The clock to use on this timer.
1411 * @param pfnCallback Callback function.
1412 * @param pvUser The user argument to the callback.
1413 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1414 * @param pszDesc Pointer to description string which must stay around
1415 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1416 * @param ppTimer Where to store the timer on success.
1417 */
1418VMM_INT_DECL(int) TMR3TimerCreateUsb(PVM pVM, PPDMUSBINS pUsbIns, TMCLOCK enmClock,
1419 PFNTMTIMERUSB pfnCallback, void *pvUser,
1420 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1421{
1422 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1423
1424 /*
1425 * Allocate and init stuff.
1426 */
1427 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1428 if (RT_SUCCESS(rc))
1429 {
1430 (*ppTimer)->enmType = TMTIMERTYPE_USB;
1431 (*ppTimer)->u.Usb.pfnTimer = pfnCallback;
1432 (*ppTimer)->u.Usb.pUsbIns = pUsbIns;
1433 (*ppTimer)->pvUser = pvUser;
1434 //if (!(fFlags & TMTIMER_FLAGS_NO_CRIT_SECT))
1435 //{
1436 // if (pDevIns->pCritSectR3)
1437 // (*ppTimer)->pCritSect = pUsbIns->pCritSectR3;
1438 // else
1439 // (*ppTimer)->pCritSect = IOMR3GetCritSect(pVM);
1440 //}
1441 Log(("TM: Created USB device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1442 }
1443
1444 return rc;
1445}
1446
1447
1448/**
1449 * Creates a driver timer.
1450 *
1451 * @returns VBox status.
1452 * @param pVM The VM to create the timer in.
1453 * @param pDrvIns Driver instance.
1454 * @param enmClock The clock to use on this timer.
1455 * @param pfnCallback Callback function.
1456 * @param pvUser The user argument to the callback.
1457 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1458 * @param pszDesc Pointer to description string which must stay around
1459 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1460 * @param ppTimer Where to store the timer on success.
1461 */
1462VMM_INT_DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, void *pvUser,
1463 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1464{
1465 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1466
1467 /*
1468 * Allocate and init stuff.
1469 */
1470 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1471 if (RT_SUCCESS(rc))
1472 {
1473 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1474 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1475 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1476 (*ppTimer)->pvUser = pvUser;
1477 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1478 }
1479
1480 return rc;
1481}
1482
1483
1484/**
1485 * Creates an internal timer.
1486 *
1487 * @returns VBox status.
1488 * @param pVM The VM to create the timer in.
1489 * @param enmClock The clock to use on this timer.
1490 * @param pfnCallback Callback function.
1491 * @param pvUser User argument to be passed to the callback.
1492 * @param pszDesc Pointer to description string which must stay around
1493 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1494 * @param ppTimer Where to store the timer on success.
1495 */
1496VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1497{
1498 /*
1499 * Allocate and init stuff.
1500 */
1501 PTMTIMER pTimer;
1502 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1503 if (RT_SUCCESS(rc))
1504 {
1505 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1506 pTimer->u.Internal.pfnTimer = pfnCallback;
1507 pTimer->pvUser = pvUser;
1508 *ppTimer = pTimer;
1509 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1510 }
1511
1512 return rc;
1513}
1514
1515/**
1516 * Creates an external timer.
1517 *
1518 * @returns Timer handle on success.
1519 * @returns NULL on failure.
1520 * @param pVM The VM to create the timer in.
1521 * @param enmClock The clock to use on this timer.
1522 * @param pfnCallback Callback function.
1523 * @param pvUser User argument.
1524 * @param pszDesc Pointer to description string which must stay around
1525 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1526 */
1527VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1528{
1529 /*
1530 * Allocate and init stuff.
1531 */
1532 PTMTIMERR3 pTimer;
1533 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1534 if (RT_SUCCESS(rc))
1535 {
1536 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1537 pTimer->u.External.pfnTimer = pfnCallback;
1538 pTimer->pvUser = pvUser;
1539 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1540 return pTimer;
1541 }
1542
1543 return NULL;
1544}
1545
1546
1547/**
1548 * Destroy a timer
1549 *
1550 * @returns VBox status.
1551 * @param pTimer Timer handle as returned by one of the create functions.
1552 */
1553VMMR3DECL(int) TMR3TimerDestroy(PTMTIMER pTimer)
1554{
1555 /*
1556 * Be extra careful here.
1557 */
1558 if (!pTimer)
1559 return VINF_SUCCESS;
1560 AssertPtr(pTimer);
1561 Assert((unsigned)pTimer->enmClock < (unsigned)TMCLOCK_MAX);
1562
1563 PVM pVM = pTimer->CTX_SUFF(pVM);
1564 PTMTIMERQUEUE pQueue = &pVM->tm.s.CTX_SUFF(paTimerQueues)[pTimer->enmClock];
1565 bool fActive = false;
1566 bool fPending = false;
1567
1568 AssertMsg( !pTimer->pCritSect
1569 || VMR3GetState(pVM) != VMSTATE_RUNNING
1570 || PDMCritSectIsOwner(pTimer->pCritSect), ("%s\n", pTimer->pszDesc));
1571
1572 /*
1573 * The rest of the game happens behind the lock, just
1574 * like create does. All the work is done here.
1575 */
1576 TM_LOCK_TIMERS(pVM);
1577 for (int cRetries = 1000;; cRetries--)
1578 {
1579 /*
1580 * Change to the DESTROY state.
1581 */
1582 TMTIMERSTATE const enmState = pTimer->enmState;
1583 Log2(("TMTimerDestroy: %p:{.enmState=%s, .pszDesc='%s'} cRetries=%d\n",
1584 pTimer, tmTimerState(enmState), R3STRING(pTimer->pszDesc), cRetries));
1585 switch (enmState)
1586 {
1587 case TMTIMERSTATE_STOPPED:
1588 case TMTIMERSTATE_EXPIRED_DELIVER:
1589 break;
1590
1591 case TMTIMERSTATE_ACTIVE:
1592 fActive = true;
1593 break;
1594
1595 case TMTIMERSTATE_PENDING_STOP:
1596 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1597 case TMTIMERSTATE_PENDING_RESCHEDULE:
1598 fActive = true;
1599 fPending = true;
1600 break;
1601
1602 case TMTIMERSTATE_PENDING_SCHEDULE:
1603 fPending = true;
1604 break;
1605
1606 /*
1607 * This shouldn't happen as the caller should make sure there are no races.
1608 */
1609 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
1610 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1611 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1612 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1613 TM_UNLOCK_TIMERS(pVM);
1614 if (!RTThreadYield())
1615 RTThreadSleep(1);
1616 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1617 VERR_TM_UNSTABLE_STATE);
1618 TM_LOCK_TIMERS(pVM);
1619 continue;
1620
1621 /*
1622 * Invalid states.
1623 */
1624 case TMTIMERSTATE_FREE:
1625 case TMTIMERSTATE_DESTROY:
1626 TM_UNLOCK_TIMERS(pVM);
1627 AssertLogRelMsgFailedReturn(("pTimer=%p %s\n", pTimer, tmTimerState(enmState)), VERR_TM_INVALID_STATE);
1628
1629 default:
1630 AssertMsgFailed(("Unknown timer state %d (%s)\n", enmState, R3STRING(pTimer->pszDesc)));
1631 TM_UNLOCK_TIMERS(pVM);
1632 return VERR_TM_UNKNOWN_STATE;
1633 }
1634
1635 /*
1636 * Try switch to the destroy state.
1637 * This should always succeed as the caller should make sure there are no race.
1638 */
1639 bool fRc;
1640 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_DESTROY, enmState, fRc);
1641 if (fRc)
1642 break;
1643 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1644 TM_UNLOCK_TIMERS(pVM);
1645 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1646 VERR_TM_UNSTABLE_STATE);
1647 TM_LOCK_TIMERS(pVM);
1648 }
1649
1650 /*
1651 * Unlink from the active list.
1652 */
1653 if (fActive)
1654 {
1655 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1656 const PTMTIMER pNext = TMTIMER_GET_NEXT(pTimer);
1657 if (pPrev)
1658 TMTIMER_SET_NEXT(pPrev, pNext);
1659 else
1660 {
1661 TMTIMER_SET_HEAD(pQueue, pNext);
1662 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1663 }
1664 if (pNext)
1665 TMTIMER_SET_PREV(pNext, pPrev);
1666 pTimer->offNext = 0;
1667 pTimer->offPrev = 0;
1668 }
1669
1670 /*
1671 * Unlink from the schedule list by running it.
1672 */
1673 if (fPending)
1674 {
1675 Log3(("TMR3TimerDestroy: tmTimerQueueSchedule\n"));
1676 STAM_PROFILE_START(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1677 Assert(pQueue->offSchedule);
1678 tmTimerQueueSchedule(pVM, pQueue);
1679 STAM_PROFILE_STOP(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1680 }
1681
1682 /*
1683 * Read to move the timer from the created list and onto the free list.
1684 */
1685 Assert(!pTimer->offNext); Assert(!pTimer->offPrev); Assert(!pTimer->offScheduleNext);
1686
1687 /* unlink from created list */
1688 if (pTimer->pBigPrev)
1689 pTimer->pBigPrev->pBigNext = pTimer->pBigNext;
1690 else
1691 pVM->tm.s.pCreated = pTimer->pBigNext;
1692 if (pTimer->pBigNext)
1693 pTimer->pBigNext->pBigPrev = pTimer->pBigPrev;
1694 pTimer->pBigNext = 0;
1695 pTimer->pBigPrev = 0;
1696
1697 /* free */
1698 Log2(("TM: Inserting %p into the free list ahead of %p!\n", pTimer, pVM->tm.s.pFree));
1699 TM_SET_STATE(pTimer, TMTIMERSTATE_FREE);
1700 pTimer->pBigNext = pVM->tm.s.pFree;
1701 pVM->tm.s.pFree = pTimer;
1702
1703#ifdef VBOX_STRICT
1704 tmTimerQueuesSanityChecks(pVM, "TMR3TimerDestroy");
1705#endif
1706 TM_UNLOCK_TIMERS(pVM);
1707 return VINF_SUCCESS;
1708}
1709
1710
1711/**
1712 * Destroy all timers owned by a device.
1713 *
1714 * @returns VBox status.
1715 * @param pVM Pointer to the VM.
1716 * @param pDevIns Device which timers should be destroyed.
1717 */
1718VMM_INT_DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1719{
1720 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1721 if (!pDevIns)
1722 return VERR_INVALID_PARAMETER;
1723
1724 TM_LOCK_TIMERS(pVM);
1725 PTMTIMER pCur = pVM->tm.s.pCreated;
1726 while (pCur)
1727 {
1728 PTMTIMER pDestroy = pCur;
1729 pCur = pDestroy->pBigNext;
1730 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1731 && pDestroy->u.Dev.pDevIns == pDevIns)
1732 {
1733 int rc = TMR3TimerDestroy(pDestroy);
1734 AssertRC(rc);
1735 }
1736 }
1737 TM_UNLOCK_TIMERS(pVM);
1738
1739 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1740 return VINF_SUCCESS;
1741}
1742
1743
1744/**
1745 * Destroy all timers owned by a USB device.
1746 *
1747 * @returns VBox status.
1748 * @param pVM Pointer to the VM.
1749 * @param pUsbIns USB device which timers should be destroyed.
1750 */
1751VMM_INT_DECL(int) TMR3TimerDestroyUsb(PVM pVM, PPDMUSBINS pUsbIns)
1752{
1753 LogFlow(("TMR3TimerDestroyUsb: pUsbIns=%p\n", pUsbIns));
1754 if (!pUsbIns)
1755 return VERR_INVALID_PARAMETER;
1756
1757 TM_LOCK_TIMERS(pVM);
1758 PTMTIMER pCur = pVM->tm.s.pCreated;
1759 while (pCur)
1760 {
1761 PTMTIMER pDestroy = pCur;
1762 pCur = pDestroy->pBigNext;
1763 if ( pDestroy->enmType == TMTIMERTYPE_USB
1764 && pDestroy->u.Usb.pUsbIns == pUsbIns)
1765 {
1766 int rc = TMR3TimerDestroy(pDestroy);
1767 AssertRC(rc);
1768 }
1769 }
1770 TM_UNLOCK_TIMERS(pVM);
1771
1772 LogFlow(("TMR3TimerDestroyUsb: returns VINF_SUCCESS\n"));
1773 return VINF_SUCCESS;
1774}
1775
1776
1777/**
1778 * Destroy all timers owned by a driver.
1779 *
1780 * @returns VBox status.
1781 * @param pVM Pointer to the VM.
1782 * @param pDrvIns Driver which timers should be destroyed.
1783 */
1784VMM_INT_DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1785{
1786 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1787 if (!pDrvIns)
1788 return VERR_INVALID_PARAMETER;
1789
1790 TM_LOCK_TIMERS(pVM);
1791 PTMTIMER pCur = pVM->tm.s.pCreated;
1792 while (pCur)
1793 {
1794 PTMTIMER pDestroy = pCur;
1795 pCur = pDestroy->pBigNext;
1796 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1797 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1798 {
1799 int rc = TMR3TimerDestroy(pDestroy);
1800 AssertRC(rc);
1801 }
1802 }
1803 TM_UNLOCK_TIMERS(pVM);
1804
1805 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1806 return VINF_SUCCESS;
1807}
1808
1809
1810/**
1811 * Internal function for getting the clock time.
1812 *
1813 * @returns clock time.
1814 * @param pVM Pointer to the VM.
1815 * @param enmClock The clock.
1816 */
1817DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
1818{
1819 switch (enmClock)
1820 {
1821 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
1822 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
1823 case TMCLOCK_REAL: return TMRealGet(pVM);
1824 case TMCLOCK_TSC: return TMCpuTickGet(&pVM->aCpus[0] /* just take VCPU 0 */);
1825 default:
1826 AssertMsgFailed(("enmClock=%d\n", enmClock));
1827 return ~(uint64_t)0;
1828 }
1829}
1830
1831
1832/**
1833 * Checks if the sync queue has one or more expired timers.
1834 *
1835 * @returns true / false.
1836 *
1837 * @param pVM Pointer to the VM.
1838 * @param enmClock The queue.
1839 */
1840DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1841{
1842 const uint64_t u64Expire = pVM->tm.s.CTX_SUFF(paTimerQueues)[enmClock].u64Expire;
1843 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1844}
1845
1846
1847/**
1848 * Checks for expired timers in all the queues.
1849 *
1850 * @returns true / false.
1851 * @param pVM Pointer to the VM.
1852 */
1853DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1854{
1855 /*
1856 * Combine the time calculation for the first two since we're not on EMT
1857 * TMVirtualSyncGet only permits EMT.
1858 */
1859 uint64_t u64Now = TMVirtualGetNoCheck(pVM);
1860 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1861 return true;
1862 u64Now = pVM->tm.s.fVirtualSyncTicking
1863 ? u64Now - pVM->tm.s.offVirtualSync
1864 : pVM->tm.s.u64VirtualSync;
1865 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1866 return true;
1867
1868 /*
1869 * The remaining timers.
1870 */
1871 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1872 return true;
1873 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1874 return true;
1875 return false;
1876}
1877
1878
1879/**
1880 * Schedule timer callback.
1881 *
1882 * @param pTimer Timer handle.
1883 * @param pvUser Pointer to the VM.
1884 * @thread Timer thread.
1885 *
1886 * @remark We cannot do the scheduling and queues running from a timer handler
1887 * since it's not executing in EMT, and even if it was it would be async
1888 * and we wouldn't know the state of the affairs.
1889 * So, we'll just raise the timer FF and force any REM execution to exit.
1890 */
1891static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1892{
1893 PVM pVM = (PVM)pvUser;
1894 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1895 NOREF(pTimer);
1896
1897 AssertCompile(TMCLOCK_MAX == 4);
1898#ifdef DEBUG_Sander /* very annoying, keep it private. */
1899 if (VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER))
1900 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1901#endif
1902 if ( !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
1903 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule /** @todo FIXME - reconsider offSchedule as a reason for running the timer queues. */
1904 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1905 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1906 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1907 || tmR3AnyExpiredTimers(pVM)
1908 )
1909 && !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
1910 && !pVM->tm.s.fRunningQueues
1911 )
1912 {
1913 Log5(("TM(%u): FF: 0 -> 1\n", __LINE__));
1914 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1915#ifdef VBOX_WITH_REM
1916 REMR3NotifyTimerPending(pVM, pVCpuDst);
1917#endif
1918 VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM /** @todo | VMNOTIFYFF_FLAGS_POKE ?*/);
1919 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1920 }
1921}
1922
1923
1924/**
1925 * Schedules and runs any pending timers.
1926 *
1927 * This is normally called from a forced action handler in EMT.
1928 *
1929 * @param pVM The VM to run the timers for.
1930 *
1931 * @thread EMT (actually EMT0, but we fend off the others)
1932 */
1933VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1934{
1935 /*
1936 * Only the dedicated timer EMT should do stuff here.
1937 * (fRunningQueues is only used as an indicator.)
1938 */
1939 Assert(pVM->tm.s.idTimerCpu < pVM->cCpus);
1940 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1941 if (VMMGetCpu(pVM) != pVCpuDst)
1942 {
1943 Assert(pVM->cCpus > 1);
1944 return;
1945 }
1946 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1947 Log2(("TMR3TimerQueuesDo:\n"));
1948 Assert(!pVM->tm.s.fRunningQueues);
1949 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, true);
1950 TM_LOCK_TIMERS(pVM);
1951
1952 /*
1953 * Process the queues.
1954 */
1955 AssertCompile(TMCLOCK_MAX == 4);
1956
1957 /* TMCLOCK_VIRTUAL_SYNC (see also TMR3VirtualSyncFF) */
1958 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
1959 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
1960 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
1961 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /* Clear the FF once we started working for real. */
1962
1963 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule);
1964 tmR3TimerQueueRunVirtualSync(pVM);
1965 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
1966 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
1967
1968 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
1969 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
1970 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
1971
1972 /* TMCLOCK_VIRTUAL */
1973 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
1974 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule)
1975 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1976 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1977 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
1978
1979 /* TMCLOCK_TSC */
1980 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offActive); /* not used */
1981
1982 /* TMCLOCK_REAL */
1983 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
1984 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule)
1985 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1986 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1987 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
1988
1989#ifdef VBOX_STRICT
1990 /* check that we didn't screw up. */
1991 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1992#endif
1993
1994 /* done */
1995 Log2(("TMR3TimerQueuesDo: returns void\n"));
1996 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, false);
1997 TM_UNLOCK_TIMERS(pVM);
1998 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
1999}
2000
2001//RT_C_DECLS_BEGIN
2002//int iomLock(PVM pVM);
2003//void iomUnlock(PVM pVM);
2004//RT_C_DECLS_END
2005
2006
2007/**
2008 * Schedules and runs any pending times in the specified queue.
2009 *
2010 * This is normally called from a forced action handler in EMT.
2011 *
2012 * @param pVM The VM to run the timers for.
2013 * @param pQueue The queue to run.
2014 */
2015static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
2016{
2017 VM_ASSERT_EMT(pVM);
2018
2019 /*
2020 * Run timers.
2021 *
2022 * We check the clock once and run all timers which are ACTIVE
2023 * and have an expire time less or equal to the time we read.
2024 *
2025 * N.B. A generic unlink must be applied since other threads
2026 * are allowed to mess with any active timer at any time.
2027 * However, we only allow EMT to handle EXPIRED_PENDING
2028 * timers, thus enabling the timer handler function to
2029 * arm the timer again.
2030 */
2031 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
2032 if (!pNext)
2033 return;
2034 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
2035 while (pNext && pNext->u64Expire <= u64Now)
2036 {
2037 PTMTIMER pTimer = pNext;
2038 pNext = TMTIMER_GET_NEXT(pTimer);
2039 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2040 if (pCritSect)
2041 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2042 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2043 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2044 bool fRc;
2045 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_GET_UNLINK, TMTIMERSTATE_ACTIVE, fRc);
2046 if (fRc)
2047 {
2048 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
2049
2050 /* unlink */
2051 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
2052 if (pPrev)
2053 TMTIMER_SET_NEXT(pPrev, pNext);
2054 else
2055 {
2056 TMTIMER_SET_HEAD(pQueue, pNext);
2057 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
2058 }
2059 if (pNext)
2060 TMTIMER_SET_PREV(pNext, pPrev);
2061 pTimer->offNext = 0;
2062 pTimer->offPrev = 0;
2063
2064 /* fire */
2065 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2066 switch (pTimer->enmType)
2067 {
2068 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2069 case TMTIMERTYPE_USB: pTimer->u.Usb.pfnTimer(pTimer->u.Usb.pUsbIns, pTimer, pTimer->pvUser); break;
2070 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2071 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2072 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2073 default:
2074 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2075 break;
2076 }
2077
2078 /* change the state if it wasn't changed already in the handler. */
2079 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2080 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2081 }
2082 if (pCritSect)
2083 PDMCritSectLeave(pCritSect);
2084 } /* run loop */
2085}
2086
2087
2088/**
2089 * Schedules and runs any pending times in the timer queue for the
2090 * synchronous virtual clock.
2091 *
2092 * This scheduling is a bit different from the other queues as it need
2093 * to implement the special requirements of the timer synchronous virtual
2094 * clock, thus this 2nd queue run function.
2095 *
2096 * @param pVM The VM to run the timers for.
2097 *
2098 * @remarks The caller must the Virtual Sync lock. Owning the TM lock is no
2099 * longer important.
2100 */
2101static void tmR3TimerQueueRunVirtualSync(PVM pVM)
2102{
2103 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
2104 VM_ASSERT_EMT(pVM);
2105 Assert(PDMCritSectIsOwner(&pVM->tm.s.VirtualSyncLock));
2106
2107 /*
2108 * Any timers?
2109 */
2110 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
2111 if (RT_UNLIKELY(!pNext))
2112 {
2113 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.cVirtualTicking);
2114 return;
2115 }
2116 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
2117
2118 /*
2119 * Calculate the time frame for which we will dispatch timers.
2120 *
2121 * We use a time frame ranging from the current sync time (which is most likely the
2122 * same as the head timer) and some configurable period (100000ns) up towards the
2123 * current virtual time. This period might also need to be restricted by the catch-up
2124 * rate so frequent calls to this function won't accelerate the time too much, however
2125 * this will be implemented at a later point if necessary.
2126 *
2127 * Without this frame we would 1) having to run timers much more frequently
2128 * and 2) lag behind at a steady rate.
2129 */
2130 const uint64_t u64VirtualNow = TMVirtualGetNoCheck(pVM);
2131 uint64_t const offSyncGivenUp = pVM->tm.s.offVirtualSyncGivenUp;
2132 uint64_t u64Now;
2133 if (!pVM->tm.s.fVirtualSyncTicking)
2134 {
2135 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
2136 u64Now = pVM->tm.s.u64VirtualSync;
2137 Assert(u64Now <= pNext->u64Expire);
2138 }
2139 else
2140 {
2141 /* Calc 'now'. */
2142 bool fStopCatchup = false;
2143 bool fUpdateStuff = false;
2144 uint64_t off = pVM->tm.s.offVirtualSync;
2145 if (pVM->tm.s.fVirtualSyncCatchUp)
2146 {
2147 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
2148 if (RT_LIKELY(!(u64Delta >> 32)))
2149 {
2150 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
2151 if (off > u64Sub + offSyncGivenUp)
2152 {
2153 off -= u64Sub;
2154 Log4(("TM: %'RU64/-%'8RU64: sub %'RU64 [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow - off, off - offSyncGivenUp, u64Sub));
2155 }
2156 else
2157 {
2158 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2159 fStopCatchup = true;
2160 off = offSyncGivenUp;
2161 }
2162 fUpdateStuff = true;
2163 }
2164 }
2165 u64Now = u64VirtualNow - off;
2166
2167 /* Adjust against last returned time. */
2168 uint64_t u64Last = ASMAtomicUoReadU64(&pVM->tm.s.u64VirtualSync);
2169 if (u64Last > u64Now)
2170 {
2171 u64Now = u64Last + 1;
2172 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetAdjLast);
2173 }
2174
2175 /* Check if stopped by expired timer. */
2176 uint64_t const u64Expire = pNext->u64Expire;
2177 if (u64Now >= u64Expire)
2178 {
2179 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
2180 u64Now = u64Expire;
2181 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2182 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2183 Log4(("TM: %'RU64/-%'8RU64: exp tmr [tmR3TimerQueueRunVirtualSync]\n", u64Now, u64VirtualNow - u64Now - offSyncGivenUp));
2184 }
2185 else
2186 {
2187 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2188 if (fUpdateStuff)
2189 {
2190 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, off);
2191 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev, u64VirtualNow);
2192 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2193 if (fStopCatchup)
2194 {
2195 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2196 Log4(("TM: %'RU64/0: caught up [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow));
2197 }
2198 }
2199 }
2200 }
2201
2202 /* calc end of frame. */
2203 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
2204 if (u64Max > u64VirtualNow - offSyncGivenUp)
2205 u64Max = u64VirtualNow - offSyncGivenUp;
2206
2207 /* assert sanity */
2208 Assert(u64Now <= u64VirtualNow - offSyncGivenUp);
2209 Assert(u64Max <= u64VirtualNow - offSyncGivenUp);
2210 Assert(u64Now <= u64Max);
2211 Assert(offSyncGivenUp == pVM->tm.s.offVirtualSyncGivenUp);
2212
2213 /*
2214 * Process the expired timers moving the clock along as we progress.
2215 */
2216#ifdef VBOX_STRICT
2217 uint64_t u64Prev = u64Now; NOREF(u64Prev);
2218#endif
2219 while (pNext && pNext->u64Expire <= u64Max)
2220 {
2221 /* Advance */
2222 PTMTIMER pTimer = pNext;
2223 pNext = TMTIMER_GET_NEXT(pTimer);
2224
2225 /* Take the associated lock. */
2226 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2227 if (pCritSect)
2228 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2229
2230 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2231 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2232
2233 /* Advance the clock - don't permit timers to be out of order or armed
2234 in the 'past'. */
2235#ifdef VBOX_STRICT
2236 AssertMsg(pTimer->u64Expire >= u64Prev, ("%'RU64 < %'RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
2237 u64Prev = pTimer->u64Expire;
2238#endif
2239 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
2240 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2241
2242 /* Unlink it, change the state and do the callout. */
2243 tmTimerQueueUnlinkActive(pQueue, pTimer);
2244 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2245 switch (pTimer->enmType)
2246 {
2247 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2248 case TMTIMERTYPE_USB: pTimer->u.Usb.pfnTimer(pTimer->u.Usb.pUsbIns, pTimer, pTimer->pvUser); break;
2249 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2250 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2251 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2252 default:
2253 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2254 break;
2255 }
2256
2257 /* Change the state if it wasn't changed already in the handler.
2258 Reset the Hz hint too since this is the same as TMTimerStop. */
2259 bool fRc;
2260 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2261 if (fRc && pTimer->uHzHint)
2262 {
2263 if (pTimer->uHzHint >= pVM->tm.s.uMaxHzHint)
2264 ASMAtomicWriteBool(&pVM->tm.s.fHzHintNeedsUpdating, true);
2265 pTimer->uHzHint = 0;
2266 }
2267 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2268
2269 /* Leave the associated lock. */
2270 if (pCritSect)
2271 PDMCritSectLeave(pCritSect);
2272 } /* run loop */
2273
2274
2275 /*
2276 * Restart the clock if it was stopped to serve any timers,
2277 * and start/adjust catch-up if necessary.
2278 */
2279 if ( !pVM->tm.s.fVirtualSyncTicking
2280 && pVM->tm.s.cVirtualTicking)
2281 {
2282 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
2283
2284 /* calc the slack we've handed out. */
2285 const uint64_t u64VirtualNow2 = TMVirtualGetNoCheck(pVM);
2286 Assert(u64VirtualNow2 >= u64VirtualNow);
2287 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%'RU64 < %'RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
2288 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
2289 STAM_STATS({
2290 if (offSlack)
2291 {
2292 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
2293 p->cPeriods++;
2294 p->cTicks += offSlack;
2295 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
2296 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
2297 }
2298 });
2299
2300 /* Let the time run a little bit while we were busy running timers(?). */
2301 uint64_t u64Elapsed;
2302#define MAX_ELAPSED 30000U /* ns */
2303 if (offSlack > MAX_ELAPSED)
2304 u64Elapsed = 0;
2305 else
2306 {
2307 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
2308 if (u64Elapsed > MAX_ELAPSED)
2309 u64Elapsed = MAX_ELAPSED;
2310 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
2311 }
2312#undef MAX_ELAPSED
2313
2314 /* Calc the current offset. */
2315 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
2316 Assert(!(offNew & RT_BIT_64(63)));
2317 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
2318 Assert(!(offLag & RT_BIT_64(63)));
2319
2320 /*
2321 * Deal with starting, adjusting and stopping catchup.
2322 */
2323 if (pVM->tm.s.fVirtualSyncCatchUp)
2324 {
2325 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
2326 {
2327 /* stop */
2328 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2329 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2330 Log4(("TM: %'RU64/-%'8RU64: caught up [pt]\n", u64VirtualNow2 - offNew, offLag));
2331 }
2332 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2333 {
2334 /* adjust */
2335 unsigned i = 0;
2336 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2337 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2338 i++;
2339 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
2340 {
2341 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
2342 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2343 Log4(("TM: %'RU64/%'8RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2344 }
2345 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
2346 }
2347 else
2348 {
2349 /* give up */
2350 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
2351 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2352 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2353 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2354 Log4(("TM: %'RU64/%'8RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2355 LogRel(("TM: Giving up catch-up attempt at a %'RU64 ns lag; new total: %'RU64 ns\n", offLag, offNew));
2356 }
2357 }
2358 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
2359 {
2360 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2361 {
2362 /* start */
2363 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
2364 unsigned i = 0;
2365 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2366 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2367 i++;
2368 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
2369 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2370 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
2371 Log4(("TM: %'RU64/%'8RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2372 }
2373 else
2374 {
2375 /* don't bother */
2376 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
2377 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2378 Log4(("TM: %'RU64/%'8RU64: give up\n", u64VirtualNow2 - offNew, offLag));
2379 LogRel(("TM: Not bothering to attempt catching up a %'RU64 ns lag; new total: %'RU64\n", offLag, offNew));
2380 }
2381 }
2382
2383 /*
2384 * Update the offset and restart the clock.
2385 */
2386 Assert(!(offNew & RT_BIT_64(63)));
2387 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, offNew);
2388 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, true);
2389 }
2390}
2391
2392
2393/**
2394 * Deals with stopped Virtual Sync clock.
2395 *
2396 * This is called by the forced action flag handling code in EM when it
2397 * encounters the VM_FF_TM_VIRTUAL_SYNC flag. It is called by all VCPUs and they
2398 * will block on the VirtualSyncLock until the pending timers has been executed
2399 * and the clock restarted.
2400 *
2401 * @param pVM The VM to run the timers for.
2402 * @param pVCpu The virtual CPU we're running at.
2403 *
2404 * @thread EMTs
2405 */
2406VMMR3_INT_DECL(void) TMR3VirtualSyncFF(PVM pVM, PVMCPU pVCpu)
2407{
2408 Log2(("TMR3VirtualSyncFF:\n"));
2409
2410 /*
2411 * The EMT doing the timers is diverted to them.
2412 */
2413 if (pVCpu->idCpu == pVM->tm.s.idTimerCpu)
2414 TMR3TimerQueuesDo(pVM);
2415 /*
2416 * The other EMTs will block on the virtual sync lock and the first owner
2417 * will run the queue and thus restarting the clock.
2418 *
2419 * Note! This is very suboptimal code wrt to resuming execution when there
2420 * are more than two Virtual CPUs, since they will all have to enter
2421 * the critical section one by one. But it's a very simple solution
2422 * which will have to do the job for now.
2423 */
2424 else
2425 {
2426 STAM_PROFILE_START(&pVM->tm.s.StatVirtualSyncFF, a);
2427 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2428 if (pVM->tm.s.fVirtualSyncTicking)
2429 {
2430 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2431 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2432 Log2(("TMR3VirtualSyncFF: ticking\n"));
2433 }
2434 else
2435 {
2436 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2437
2438 /* try run it. */
2439 TM_LOCK_TIMERS(pVM);
2440 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2441 if (pVM->tm.s.fVirtualSyncTicking)
2442 Log2(("TMR3VirtualSyncFF: ticking (2)\n"));
2443 else
2444 {
2445 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
2446 Log2(("TMR3VirtualSyncFF: running queue\n"));
2447
2448 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule);
2449 tmR3TimerQueueRunVirtualSync(pVM);
2450 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
2451 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
2452
2453 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
2454 }
2455 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2456 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2457 TM_UNLOCK_TIMERS(pVM);
2458 }
2459 }
2460}
2461
2462
2463/** @name Saved state values
2464 * @{ */
2465#define TMTIMERSTATE_SAVED_PENDING_STOP 4
2466#define TMTIMERSTATE_SAVED_PENDING_SCHEDULE 7
2467/** @} */
2468
2469
2470/**
2471 * Saves the state of a timer to a saved state.
2472 *
2473 * @returns VBox status.
2474 * @param pTimer Timer to save.
2475 * @param pSSM Save State Manager handle.
2476 */
2477VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2478{
2479 LogFlow(("TMR3TimerSave: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2480 switch (pTimer->enmState)
2481 {
2482 case TMTIMERSTATE_STOPPED:
2483 case TMTIMERSTATE_PENDING_STOP:
2484 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
2485 return SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_STOP);
2486
2487 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
2488 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
2489 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
2490 if (!RTThreadYield())
2491 RTThreadSleep(1);
2492 /* fall thru */
2493 case TMTIMERSTATE_ACTIVE:
2494 case TMTIMERSTATE_PENDING_SCHEDULE:
2495 case TMTIMERSTATE_PENDING_RESCHEDULE:
2496 SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_SCHEDULE);
2497 return SSMR3PutU64(pSSM, pTimer->u64Expire);
2498
2499 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
2500 case TMTIMERSTATE_EXPIRED_DELIVER:
2501 case TMTIMERSTATE_DESTROY:
2502 case TMTIMERSTATE_FREE:
2503 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
2504 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
2505 }
2506
2507 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
2508 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
2509}
2510
2511
2512/**
2513 * Loads the state of a timer from a saved state.
2514 *
2515 * @returns VBox status.
2516 * @param pTimer Timer to restore.
2517 * @param pSSM Save State Manager handle.
2518 */
2519VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2520{
2521 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
2522 LogFlow(("TMR3TimerLoad: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2523
2524 /*
2525 * Load the state and validate it.
2526 */
2527 uint8_t u8State;
2528 int rc = SSMR3GetU8(pSSM, &u8State);
2529 if (RT_FAILURE(rc))
2530 return rc;
2531#if 1 /* Workaround for accidental state shift in r47786 (2009-05-26 19:12:12). */ /** @todo remove this in a few weeks! */
2532 if ( u8State == TMTIMERSTATE_SAVED_PENDING_STOP + 1
2533 || u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE + 1)
2534 u8State--;
2535#endif
2536 if ( u8State != TMTIMERSTATE_SAVED_PENDING_STOP
2537 && u8State != TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2538 {
2539 AssertLogRelMsgFailed(("u8State=%d\n", u8State));
2540 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
2541 }
2542
2543 /* Enter the critical sections to make TMTimerSet/Stop happy. */
2544 if (pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC)
2545 PDMCritSectEnter(&pTimer->pVMR3->tm.s.VirtualSyncLock, VERR_IGNORED);
2546 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2547 if (pCritSect)
2548 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2549
2550 if (u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2551 {
2552 /*
2553 * Load the expire time.
2554 */
2555 uint64_t u64Expire;
2556 rc = SSMR3GetU64(pSSM, &u64Expire);
2557 if (RT_FAILURE(rc))
2558 return rc;
2559
2560 /*
2561 * Set it.
2562 */
2563 Log(("u8State=%d u64Expire=%llu\n", u8State, u64Expire));
2564 rc = TMTimerSet(pTimer, u64Expire);
2565 }
2566 else
2567 {
2568 /*
2569 * Stop it.
2570 */
2571 Log(("u8State=%d\n", u8State));
2572 rc = TMTimerStop(pTimer);
2573 }
2574
2575 if (pCritSect)
2576 PDMCritSectLeave(pCritSect);
2577 if (pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC)
2578 PDMCritSectLeave(&pTimer->pVMR3->tm.s.VirtualSyncLock);
2579
2580 /*
2581 * On failure set SSM status.
2582 */
2583 if (RT_FAILURE(rc))
2584 rc = SSMR3HandleSetStatus(pSSM, rc);
2585 return rc;
2586}
2587
2588
2589/**
2590 * Associates a critical section with a timer.
2591 *
2592 * The critical section will be entered prior to doing the timer call back, thus
2593 * avoiding potential races between the timer thread and other threads trying to
2594 * stop or adjust the timer expiration while it's being delivered. The timer
2595 * thread will leave the critical section when the timer callback returns.
2596 *
2597 * In strict builds, ownership of the critical section will be asserted by
2598 * TMTimerSet, TMTimerStop, TMTimerGetExpire and TMTimerDestroy (when called at
2599 * runtime).
2600 *
2601 * @retval VINF_SUCCESS on success.
2602 * @retval VERR_INVALID_HANDLE if the timer handle is NULL or invalid
2603 * (asserted).
2604 * @retval VERR_INVALID_PARAMETER if pCritSect is NULL or has an invalid magic
2605 * (asserted).
2606 * @retval VERR_ALREADY_EXISTS if a critical section was already associated
2607 * with the timer (asserted).
2608 * @retval VERR_INVALID_STATE if the timer isn't stopped.
2609 *
2610 * @param pTimer The timer handle.
2611 * @param pCritSect The critical section. The caller must make sure this
2612 * is around for the life time of the timer.
2613 *
2614 * @thread Any, but the caller is responsible for making sure the timer is not
2615 * active.
2616 */
2617VMMR3DECL(int) TMR3TimerSetCritSect(PTMTIMERR3 pTimer, PPDMCRITSECT pCritSect)
2618{
2619 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
2620 AssertPtrReturn(pCritSect, VERR_INVALID_PARAMETER);
2621 const char *pszName = PDMR3CritSectName(pCritSect); /* exploited for validation */
2622 AssertReturn(pszName, VERR_INVALID_PARAMETER);
2623 AssertReturn(!pTimer->pCritSect, VERR_ALREADY_EXISTS);
2624 AssertReturn(pTimer->enmState == TMTIMERSTATE_STOPPED, VERR_INVALID_STATE);
2625 LogFlow(("pTimer=%p (%s) pCritSect=%p (%s)\n", pTimer, pTimer->pszDesc, pCritSect, pszName));
2626
2627 pTimer->pCritSect = pCritSect;
2628 return VINF_SUCCESS;
2629}
2630
2631
2632/**
2633 * Get the real world UTC time adjusted for VM lag.
2634 *
2635 * @returns pTime.
2636 * @param pVM The VM instance.
2637 * @param pTime Where to store the time.
2638 */
2639VMMR3_INT_DECL(PRTTIMESPEC) TMR3UtcNow(PVM pVM, PRTTIMESPEC pTime)
2640{
2641 /* Get a stable set of VirtualSync parameters before querying UTC. */
2642 uint64_t offVirtualSync;
2643 uint64_t offVirtualSyncGivenUp;
2644 do
2645 {
2646 offVirtualSync = ASMAtomicReadU64(&pVM->tm.s.offVirtualSync);
2647 offVirtualSyncGivenUp = ASMAtomicReadU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp);
2648 } while (ASMAtomicReadU64(&pVM->tm.s.offVirtualSync) != offVirtualSync);
2649
2650 Assert(offVirtualSync >= offVirtualSyncGivenUp);
2651 uint64_t const offLag = offVirtualSync - offVirtualSyncGivenUp;
2652
2653 RTTimeNow(pTime);
2654 RTTimeSpecSubNano(pTime, offLag);
2655 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
2656 return pTime;
2657}
2658
2659
2660/**
2661 * Pauses all clocks except TMCLOCK_REAL.
2662 *
2663 * @returns VBox status code, all errors are asserted.
2664 * @param pVM Pointer to the VM.
2665 * @param pVCpu Pointer to the VMCPU.
2666 * @thread EMT corresponding to Pointer to the VMCPU.
2667 */
2668VMMR3DECL(int) TMR3NotifySuspend(PVM pVM, PVMCPU pVCpu)
2669{
2670 VMCPU_ASSERT_EMT(pVCpu);
2671
2672 /*
2673 * The shared virtual clock (includes virtual sync which is tied to it).
2674 */
2675 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2676 int rc = tmVirtualPauseLocked(pVM);
2677 TM_UNLOCK_TIMERS(pVM);
2678 if (RT_FAILURE(rc))
2679 return rc;
2680
2681 /*
2682 * Pause the TSC last since it is normally linked to the virtual
2683 * sync clock, so the above code may actually stop both clocks.
2684 */
2685 if (!pVM->tm.s.fTSCTiedToExecution)
2686 {
2687 TM_LOCK_TIMERS(pVM); /* Exploit the timer lock for synchronization. */
2688 rc = tmCpuTickPauseLocked(pVM, pVCpu);
2689 TM_UNLOCK_TIMERS(pVM);
2690 if (RT_FAILURE(rc))
2691 return rc;
2692 }
2693
2694#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2695 /*
2696 * Update cNsTotal.
2697 */
2698 uint32_t uGen = ASMAtomicIncU32(&pVCpu->tm.s.uTimesGen); Assert(uGen & 1);
2699 pVCpu->tm.s.cNsTotal = RTTimeNanoTS() - pVCpu->tm.s.u64NsTsStartTotal;
2700 pVCpu->tm.s.cNsOther = pVCpu->tm.s.cNsTotal - pVCpu->tm.s.cNsExecuting - pVCpu->tm.s.cNsHalted;
2701 ASMAtomicWriteU32(&pVCpu->tm.s.uTimesGen, (uGen | 1) + 1);
2702#endif
2703
2704 return VINF_SUCCESS;
2705}
2706
2707
2708/**
2709 * Resumes all clocks except TMCLOCK_REAL.
2710 *
2711 * @returns VBox status code, all errors are asserted.
2712 * @param pVM Pointer to the VM.
2713 * @param pVCpu Pointer to the VMCPU.
2714 * @thread EMT corresponding to Pointer to the VMCPU.
2715 */
2716VMMR3DECL(int) TMR3NotifyResume(PVM pVM, PVMCPU pVCpu)
2717{
2718 VMCPU_ASSERT_EMT(pVCpu);
2719 int rc;
2720
2721#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2722 /*
2723 * Set u64NsTsStartTotal. There is no need to back this out if either of
2724 * the two calls below fail.
2725 */
2726 pVCpu->tm.s.u64NsTsStartTotal = RTTimeNanoTS() - pVCpu->tm.s.cNsTotal;
2727#endif
2728
2729 /*
2730 * Resume the TSC first since it is normally linked to the virtual sync
2731 * clock, so it may actually not be resumed until we've executed the code
2732 * below.
2733 */
2734 if (!pVM->tm.s.fTSCTiedToExecution)
2735 {
2736 TM_LOCK_TIMERS(pVM); /* Exploit the timer lock for synchronization. */
2737 rc = tmCpuTickResumeLocked(pVM, pVCpu);
2738 TM_UNLOCK_TIMERS(pVM);
2739 if (RT_FAILURE(rc))
2740 return rc;
2741 }
2742
2743 /*
2744 * The shared virtual clock (includes virtual sync which is tied to it).
2745 */
2746 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2747 rc = tmVirtualResumeLocked(pVM);
2748 TM_UNLOCK_TIMERS(pVM);
2749
2750 return rc;
2751}
2752
2753
2754/**
2755 * Sets the warp drive percent of the virtual time.
2756 *
2757 * @returns VBox status code.
2758 * @param pVM Pointer to the VM.
2759 * @param u32Percent The new percentage. 100 means normal operation.
2760 */
2761VMMDECL(int) TMR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent)
2762{
2763 return VMR3ReqPriorityCallWaitU(pUVM, VMCPUID_ANY, (PFNRT)tmR3SetWarpDrive, 2, pUVM, u32Percent);
2764}
2765
2766
2767/**
2768 * EMT worker for TMR3SetWarpDrive.
2769 *
2770 * @returns VBox status code.
2771 * @param pUVM The user mode VM handle.
2772 * @param u32Percent See TMR3SetWarpDrive().
2773 * @internal
2774 */
2775static DECLCALLBACK(int) tmR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent)
2776{
2777 PVM pVM = pUVM->pVM;
2778 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2779 PVMCPU pVCpu = VMMGetCpu(pVM);
2780
2781 /*
2782 * Validate it.
2783 */
2784 AssertMsgReturn(u32Percent >= 2 && u32Percent <= 20000,
2785 ("%RX32 is not between 2 and 20000 (inclusive).\n", u32Percent),
2786 VERR_INVALID_PARAMETER);
2787
2788/** @todo This isn't a feature specific to virtual time, move the variables to
2789 * TM level and make it affect TMR3UTCNow as well! */
2790
2791 /*
2792 * If the time is running we'll have to pause it before we can change
2793 * the warp drive settings.
2794 */
2795 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2796 bool fPaused = !!pVM->tm.s.cVirtualTicking;
2797 if (fPaused) /** @todo this isn't really working, but wtf. */
2798 TMR3NotifySuspend(pVM, pVCpu);
2799
2800 pVM->tm.s.u32VirtualWarpDrivePercentage = u32Percent;
2801 pVM->tm.s.fVirtualWarpDrive = u32Percent != 100;
2802 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32 fVirtualWarpDrive=%RTbool\n",
2803 pVM->tm.s.u32VirtualWarpDrivePercentage, pVM->tm.s.fVirtualWarpDrive));
2804
2805 if (fPaused)
2806 TMR3NotifyResume(pVM, pVCpu);
2807 TM_UNLOCK_TIMERS(pVM);
2808 return VINF_SUCCESS;
2809}
2810
2811
2812/**
2813 * Gets the current warp drive percent.
2814 *
2815 * @returns The warp drive percent.
2816 * @param pVM Pointer to the VM.
2817 */
2818VMMR3DECL(uint32_t) TMR3GetWarpDrive(PUVM pUVM)
2819{
2820 UVM_ASSERT_VALID_EXT_RETURN(pUVM, UINT32_MAX);
2821 PVM pVM = pUVM->pVM;
2822 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
2823 return pVM->tm.s.u32VirtualWarpDrivePercentage;
2824}
2825
2826
2827/**
2828 * Gets the performance information for one virtual CPU as seen by the VMM.
2829 *
2830 * The returned times covers the period where the VM is running and will be
2831 * reset when restoring a previous VM state (at least for the time being).
2832 *
2833 * @retval VINF_SUCCESS on success.
2834 * @retval VERR_NOT_IMPLEMENTED if not compiled in.
2835 * @retval VERR_INVALID_STATE if the VM handle is bad.
2836 * @retval VERR_INVALID_PARAMETER if idCpu is out of range.
2837 *
2838 * @param pVM Pointer to the VM.
2839 * @param idCpu The ID of the virtual CPU which times to get.
2840 * @param pcNsTotal Where to store the total run time (nano seconds) of
2841 * the CPU, i.e. the sum of the three other returns.
2842 * Optional.
2843 * @param pcNsExecuting Where to store the time (nano seconds) spent
2844 * executing guest code. Optional.
2845 * @param pcNsHalted Where to store the time (nano seconds) spent
2846 * halted. Optional
2847 * @param pcNsOther Where to store the time (nano seconds) spent
2848 * preempted by the host scheduler, on virtualization
2849 * overhead and on other tasks.
2850 */
2851VMMR3DECL(int) TMR3GetCpuLoadTimes(PVM pVM, VMCPUID idCpu, uint64_t *pcNsTotal, uint64_t *pcNsExecuting,
2852 uint64_t *pcNsHalted, uint64_t *pcNsOther)
2853{
2854 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_STATE);
2855 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_PARAMETER);
2856
2857#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2858 /*
2859 * Get a stable result set.
2860 * This should be way quicker than an EMT request.
2861 */
2862 PVMCPU pVCpu = &pVM->aCpus[idCpu];
2863 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2864 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
2865 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
2866 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
2867 uint64_t cNsOther = pVCpu->tm.s.cNsOther;
2868 while ( (uTimesGen & 1) /* update in progress */
2869 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen))
2870 {
2871 RTThreadYield();
2872 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2873 cNsTotal = pVCpu->tm.s.cNsTotal;
2874 cNsExecuting = pVCpu->tm.s.cNsExecuting;
2875 cNsHalted = pVCpu->tm.s.cNsHalted;
2876 cNsOther = pVCpu->tm.s.cNsOther;
2877 }
2878
2879 /*
2880 * Fill in the return values.
2881 */
2882 if (pcNsTotal)
2883 *pcNsTotal = cNsTotal;
2884 if (pcNsExecuting)
2885 *pcNsExecuting = cNsExecuting;
2886 if (pcNsHalted)
2887 *pcNsHalted = cNsHalted;
2888 if (pcNsOther)
2889 *pcNsOther = cNsOther;
2890
2891 return VINF_SUCCESS;
2892
2893#else
2894 return VERR_NOT_IMPLEMENTED;
2895#endif
2896}
2897
2898#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2899
2900/**
2901 * Helper for tmR3CpuLoadTimer.
2902 * @returns
2903 * @param pState The state to update.
2904 * @param cNsTotalDelta Total time.
2905 * @param cNsExecutingDelta Time executing.
2906 * @param cNsHaltedDelta Time halted.
2907 */
2908DECLINLINE(void) tmR3CpuLoadTimerMakeUpdate(PTMCPULOADSTATE pState,
2909 uint64_t cNsTotal,
2910 uint64_t cNsExecuting,
2911 uint64_t cNsHalted)
2912{
2913 /* Calc deltas */
2914 uint64_t cNsTotalDelta = cNsTotal - pState->cNsPrevTotal;
2915 pState->cNsPrevTotal = cNsTotal;
2916
2917 uint64_t cNsExecutingDelta = cNsExecuting - pState->cNsPrevExecuting;
2918 pState->cNsPrevExecuting = cNsExecuting;
2919
2920 uint64_t cNsHaltedDelta = cNsHalted - pState->cNsPrevHalted;
2921 pState->cNsPrevHalted = cNsHalted;
2922
2923 /* Calc pcts. */
2924 if (!cNsTotalDelta)
2925 {
2926 pState->cPctExecuting = 0;
2927 pState->cPctHalted = 100;
2928 pState->cPctOther = 0;
2929 }
2930 else if (cNsTotalDelta < UINT64_MAX / 4)
2931 {
2932 pState->cPctExecuting = (uint8_t)(cNsExecutingDelta * 100 / cNsTotalDelta);
2933 pState->cPctHalted = (uint8_t)(cNsHaltedDelta * 100 / cNsTotalDelta);
2934 pState->cPctOther = (uint8_t)((cNsTotalDelta - cNsExecutingDelta - cNsHaltedDelta) * 100 / cNsTotalDelta);
2935 }
2936 else
2937 {
2938 pState->cPctExecuting = 0;
2939 pState->cPctHalted = 100;
2940 pState->cPctOther = 0;
2941 }
2942}
2943
2944
2945/**
2946 * Timer callback that calculates the CPU load since the last time it was
2947 * called.
2948 *
2949 * @param pVM Pointer to the VM.
2950 * @param pTimer The timer.
2951 * @param pvUser NULL, unused.
2952 */
2953static DECLCALLBACK(void) tmR3CpuLoadTimer(PVM pVM, PTMTIMER pTimer, void *pvUser)
2954{
2955 /*
2956 * Re-arm the timer first.
2957 */
2958 int rc = TMTimerSetMillies(pTimer, 1000);
2959 AssertLogRelRC(rc);
2960 NOREF(pvUser);
2961
2962 /*
2963 * Update the values for each CPU.
2964 */
2965 uint64_t cNsTotalAll = 0;
2966 uint64_t cNsExecutingAll = 0;
2967 uint64_t cNsHaltedAll = 0;
2968 for (VMCPUID iCpu = 0; iCpu < pVM->cCpus; iCpu++)
2969 {
2970 PVMCPU pVCpu = &pVM->aCpus[iCpu];
2971
2972 /* Try get a stable data set. */
2973 uint32_t cTries = 3;
2974 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2975 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
2976 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
2977 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
2978 while (RT_UNLIKELY( (uTimesGen & 1) /* update in progress */
2979 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen)))
2980 {
2981 if (!--cTries)
2982 break;
2983 ASMNopPause();
2984 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2985 cNsTotal = pVCpu->tm.s.cNsTotal;
2986 cNsExecuting = pVCpu->tm.s.cNsExecuting;
2987 cNsHalted = pVCpu->tm.s.cNsHalted;
2988 }
2989
2990 /* Totals */
2991 cNsTotalAll += cNsTotal;
2992 cNsExecutingAll += cNsExecuting;
2993 cNsHaltedAll += cNsHalted;
2994
2995 /* Calc the PCTs and update the state. */
2996 tmR3CpuLoadTimerMakeUpdate(&pVCpu->tm.s.CpuLoad, cNsTotal, cNsExecuting, cNsHalted);
2997 }
2998
2999 /*
3000 * Update the value for all the CPUs.
3001 */
3002 tmR3CpuLoadTimerMakeUpdate(&pVM->tm.s.CpuLoad, cNsTotalAll, cNsExecutingAll, cNsHaltedAll);
3003
3004 /** @todo Try add 1, 5 and 15 min load stats. */
3005
3006}
3007
3008#endif /* !VBOX_WITHOUT_NS_ACCOUNTING */
3009
3010/**
3011 * Gets the 5 char clock name for the info tables.
3012 *
3013 * @returns The name.
3014 * @param enmClock The clock.
3015 */
3016DECLINLINE(const char *) tmR3Get5CharClockName(TMCLOCK enmClock)
3017{
3018 switch (enmClock)
3019 {
3020 case TMCLOCK_REAL: return "Real ";
3021 case TMCLOCK_VIRTUAL: return "Virt ";
3022 case TMCLOCK_VIRTUAL_SYNC: return "VrSy ";
3023 case TMCLOCK_TSC: return "TSC ";
3024 default: return "Bad ";
3025 }
3026}
3027
3028
3029/**
3030 * Display all timers.
3031 *
3032 * @param pVM Pointer to the VM.
3033 * @param pHlp The info helpers.
3034 * @param pszArgs Arguments, ignored.
3035 */
3036static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3037{
3038 NOREF(pszArgs);
3039 pHlp->pfnPrintf(pHlp,
3040 "Timers (pVM=%p)\n"
3041 "%.*s %.*s %.*s %.*s Clock %18s %18s %6s %-25s Description\n",
3042 pVM,
3043 sizeof(RTR3PTR) * 2, "pTimerR3 ",
3044 sizeof(int32_t) * 2, "offNext ",
3045 sizeof(int32_t) * 2, "offPrev ",
3046 sizeof(int32_t) * 2, "offSched ",
3047 "Time",
3048 "Expire",
3049 "HzHint",
3050 "State");
3051 TM_LOCK_TIMERS(pVM);
3052 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
3053 {
3054 pHlp->pfnPrintf(pHlp,
3055 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %6RU32 %-25s %s\n",
3056 pTimer,
3057 pTimer->offNext,
3058 pTimer->offPrev,
3059 pTimer->offScheduleNext,
3060 tmR3Get5CharClockName(pTimer->enmClock),
3061 TMTimerGet(pTimer),
3062 pTimer->u64Expire,
3063 pTimer->uHzHint,
3064 tmTimerState(pTimer->enmState),
3065 pTimer->pszDesc);
3066 }
3067 TM_UNLOCK_TIMERS(pVM);
3068}
3069
3070
3071/**
3072 * Display all active timers.
3073 *
3074 * @param pVM Pointer to the VM.
3075 * @param pHlp The info helpers.
3076 * @param pszArgs Arguments, ignored.
3077 */
3078static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3079{
3080 NOREF(pszArgs);
3081 pHlp->pfnPrintf(pHlp,
3082 "Active Timers (pVM=%p)\n"
3083 "%.*s %.*s %.*s %.*s Clock %18s %18s %6s %-25s Description\n",
3084 pVM,
3085 sizeof(RTR3PTR) * 2, "pTimerR3 ",
3086 sizeof(int32_t) * 2, "offNext ",
3087 sizeof(int32_t) * 2, "offPrev ",
3088 sizeof(int32_t) * 2, "offSched ",
3089 "Time",
3090 "Expire",
3091 "HzHint",
3092 "State");
3093 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
3094 {
3095 TM_LOCK_TIMERS(pVM);
3096 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
3097 pTimer;
3098 pTimer = TMTIMER_GET_NEXT(pTimer))
3099 {
3100 pHlp->pfnPrintf(pHlp,
3101 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %6RU32 %-25s %s\n",
3102 pTimer,
3103 pTimer->offNext,
3104 pTimer->offPrev,
3105 pTimer->offScheduleNext,
3106 tmR3Get5CharClockName(pTimer->enmClock),
3107 TMTimerGet(pTimer),
3108 pTimer->u64Expire,
3109 pTimer->uHzHint,
3110 tmTimerState(pTimer->enmState),
3111 pTimer->pszDesc);
3112 }
3113 TM_UNLOCK_TIMERS(pVM);
3114 }
3115}
3116
3117
3118/**
3119 * Display all clocks.
3120 *
3121 * @param pVM Pointer to the VM.
3122 * @param pHlp The info helpers.
3123 * @param pszArgs Arguments, ignored.
3124 */
3125static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3126{
3127 NOREF(pszArgs);
3128
3129 /*
3130 * Read the times first to avoid more than necessary time variation.
3131 */
3132 const uint64_t u64Virtual = TMVirtualGet(pVM);
3133 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
3134 const uint64_t u64Real = TMRealGet(pVM);
3135
3136 for (VMCPUID i = 0; i < pVM->cCpus; i++)
3137 {
3138 PVMCPU pVCpu = &pVM->aCpus[i];
3139 uint64_t u64TSC = TMCpuTickGet(pVCpu);
3140
3141 /*
3142 * TSC
3143 */
3144 pHlp->pfnPrintf(pHlp,
3145 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
3146 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
3147 pVCpu->tm.s.fTSCTicking ? "ticking" : "paused",
3148 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
3149 if (pVM->tm.s.fTSCUseRealTSC)
3150 {
3151 pHlp->pfnPrintf(pHlp, " - real tsc");
3152 if (pVCpu->tm.s.offTSCRawSrc)
3153 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVCpu->tm.s.offTSCRawSrc);
3154 }
3155 else
3156 pHlp->pfnPrintf(pHlp, " - virtual clock");
3157 pHlp->pfnPrintf(pHlp, "\n");
3158 }
3159
3160 /*
3161 * virtual
3162 */
3163 pHlp->pfnPrintf(pHlp,
3164 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
3165 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
3166 pVM->tm.s.cVirtualTicking ? "ticking" : "paused");
3167 if (pVM->tm.s.fVirtualWarpDrive)
3168 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
3169 pHlp->pfnPrintf(pHlp, "\n");
3170
3171 /*
3172 * virtual sync
3173 */
3174 pHlp->pfnPrintf(pHlp,
3175 "VirtSync: %18RU64 (%#016RX64) %s%s",
3176 u64VirtualSync, u64VirtualSync,
3177 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
3178 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
3179 if (pVM->tm.s.offVirtualSync)
3180 {
3181 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
3182 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
3183 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
3184 }
3185 pHlp->pfnPrintf(pHlp, "\n");
3186
3187 /*
3188 * real
3189 */
3190 pHlp->pfnPrintf(pHlp,
3191 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
3192 u64Real, u64Real, TMRealGetFreq(pVM));
3193}
3194
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette