VirtualBox

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

Last change on this file since 53403 was 53326, checked in by vboxsync, 10 years ago

VMM/TM: When UseRealTSC is forced, use it even for SMP.

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

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