VirtualBox

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

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

TM: Add the same TSC offset to each VCPU when pausing/resuming (not yet enabled).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 138.5 KB
Line 
1/* $Id: TM.cpp 51852 2014-07-03 15:09:01Z 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//#define SYNC_TSC_PAUSE
166/*******************************************************************************
167* Internal Functions *
168*******************************************************************************/
169static bool tmR3HasFixedTSC(PVM pVM);
170static uint64_t tmR3CalibrateTSC(PVM pVM);
171static DECLCALLBACK(int) tmR3Save(PVM pVM, PSSMHANDLE pSSM);
172static DECLCALLBACK(int) tmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
173static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
174static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue);
175static void tmR3TimerQueueRunVirtualSync(PVM pVM);
176static DECLCALLBACK(int) tmR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent);
177#ifndef VBOX_WITHOUT_NS_ACCOUNTING
178static DECLCALLBACK(void) tmR3CpuLoadTimer(PVM pVM, PTMTIMER pTimer, void *pvUser);
179#endif
180static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
181static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
182static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
183
184
185/**
186 * Initializes the TM.
187 *
188 * @returns VBox status code.
189 * @param pVM Pointer to the VM.
190 */
191VMM_INT_DECL(int) TMR3Init(PVM pVM)
192{
193 LogFlow(("TMR3Init:\n"));
194
195 /*
196 * Assert alignment and sizes.
197 */
198 AssertCompileMemberAlignment(VM, tm.s, 32);
199 AssertCompile(sizeof(pVM->tm.s) <= sizeof(pVM->tm.padding));
200 AssertCompileMemberAlignment(TM, TimerCritSect, 8);
201 AssertCompileMemberAlignment(TM, VirtualSyncLock, 8);
202
203 /*
204 * Init the structure.
205 */
206 void *pv;
207 int rc = MMHyperAlloc(pVM, sizeof(pVM->tm.s.paTimerQueuesR3[0]) * TMCLOCK_MAX, 0, MM_TAG_TM, &pv);
208 AssertRCReturn(rc, rc);
209 pVM->tm.s.paTimerQueuesR3 = (PTMTIMERQUEUE)pv;
210 pVM->tm.s.paTimerQueuesR0 = MMHyperR3ToR0(pVM, pv);
211 pVM->tm.s.paTimerQueuesRC = MMHyperR3ToRC(pVM, pv);
212
213 pVM->tm.s.offVM = RT_OFFSETOF(VM, tm.s);
214 pVM->tm.s.idTimerCpu = pVM->cCpus - 1; /* The last CPU. */
215 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].enmClock = TMCLOCK_VIRTUAL;
216 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].u64Expire = INT64_MAX;
217 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].enmClock = TMCLOCK_VIRTUAL_SYNC;
218 pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].u64Expire = INT64_MAX;
219 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].enmClock = TMCLOCK_REAL;
220 pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].u64Expire = INT64_MAX;
221 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].enmClock = TMCLOCK_TSC;
222 pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].u64Expire = INT64_MAX;
223
224
225 /*
226 * We directly use the GIP to calculate the virtual time. We map the
227 * the GIP into the guest context so we can do this calculation there
228 * as well and save costly world switches.
229 */
230 pVM->tm.s.pvGIPR3 = (void *)g_pSUPGlobalInfoPage;
231 AssertMsgReturn(pVM->tm.s.pvGIPR3, ("GIP support is now required!\n"), VERR_TM_GIP_REQUIRED);
232 AssertMsgReturn((g_pSUPGlobalInfoPage->u32Version >> 16) == (SUPGLOBALINFOPAGE_VERSION >> 16),
233 ("Unsupported GIP version!\n"), VERR_TM_GIP_VERSION);
234
235 RTHCPHYS HCPhysGIP;
236 rc = SUPR3GipGetPhys(&HCPhysGIP);
237 AssertMsgRCReturn(rc, ("Failed to get GIP physical address!\n"), rc);
238
239 RTGCPTR GCPtr;
240#ifdef SUP_WITH_LOTS_OF_CPUS
241 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, NIL_RTR0PTR, HCPhysGIP, (size_t)g_pSUPGlobalInfoPage->cPages * PAGE_SIZE,
242 "GIP", &GCPtr);
243#else
244 rc = MMR3HyperMapHCPhys(pVM, pVM->tm.s.pvGIPR3, NIL_RTR0PTR, HCPhysGIP, PAGE_SIZE, "GIP", &GCPtr);
245#endif
246 if (RT_FAILURE(rc))
247 {
248 AssertMsgFailed(("Failed to map GIP into GC, rc=%Rrc!\n", rc));
249 return rc;
250 }
251 pVM->tm.s.pvGIPRC = GCPtr;
252 LogFlow(("TMR3Init: HCPhysGIP=%RHp at %RRv\n", HCPhysGIP, pVM->tm.s.pvGIPRC));
253 MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);
254
255 /* Check assumptions made in TMAllVirtual.cpp about the GIP update interval. */
256 if ( g_pSUPGlobalInfoPage->u32Magic == SUPGLOBALINFOPAGE_MAGIC
257 && g_pSUPGlobalInfoPage->u32UpdateIntervalNS >= 250000000 /* 0.25s */)
258 return VMSetError(pVM, VERR_TM_GIP_UPDATE_INTERVAL_TOO_BIG, RT_SRC_POS,
259 N_("The GIP update interval is too big. u32UpdateIntervalNS=%RU32 (u32UpdateHz=%RU32)"),
260 g_pSUPGlobalInfoPage->u32UpdateIntervalNS, g_pSUPGlobalInfoPage->u32UpdateHz);
261 LogRel(("TM: GIP - u32Mode=%d (%s) u32UpdateHz=%u\n", g_pSUPGlobalInfoPage->u32Mode,
262 g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC ? "SyncTSC"
263 : g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_ASYNC_TSC ? "AsyncTSC" : "Unknown",
264 g_pSUPGlobalInfoPage->u32UpdateHz));
265
266 /*
267 * Setup the VirtualGetRaw backend.
268 */
269 pVM->tm.s.VirtualGetRawDataR3.pu64Prev = &pVM->tm.s.u64VirtualRawPrev;
270 pVM->tm.s.VirtualGetRawDataR3.pfnBad = tmVirtualNanoTSBad;
271 pVM->tm.s.VirtualGetRawDataR3.pfnRediscover = tmVirtualNanoTSRediscover;
272 if (ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2)
273 {
274 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
275 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceSync;
276 else
277 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLFenceAsync;
278 }
279 else
280 {
281 if (g_pSUPGlobalInfoPage->u32Mode == SUPGIPMODE_SYNC_TSC)
282 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacySync;
283 else
284 pVM->tm.s.pfnVirtualGetRawR3 = RTTimeNanoTSLegacyAsync;
285 }
286
287 pVM->tm.s.VirtualGetRawDataRC.pu64Prev = MMHyperR3ToRC(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
288 pVM->tm.s.VirtualGetRawDataR0.pu64Prev = MMHyperR3ToR0(pVM, (void *)&pVM->tm.s.u64VirtualRawPrev);
289 AssertRelease(pVM->tm.s.VirtualGetRawDataR0.pu64Prev);
290 /* The rest is done in TMR3InitFinalize since it's too early to call PDM. */
291
292 /*
293 * Init the locks.
294 */
295 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.TimerCritSect, RT_SRC_POS, "TM Timer Lock");
296 if (RT_FAILURE(rc))
297 return rc;
298 rc = PDMR3CritSectInit(pVM, &pVM->tm.s.VirtualSyncLock, RT_SRC_POS, "TM VirtualSync Lock");
299 if (RT_FAILURE(rc))
300 return rc;
301
302 /*
303 * Get our CFGM node, create it if necessary.
304 */
305 PCFGMNODE pCfgHandle = CFGMR3GetChild(CFGMR3GetRoot(pVM), "TM");
306 if (!pCfgHandle)
307 {
308 rc = CFGMR3InsertNode(CFGMR3GetRoot(pVM), "TM", &pCfgHandle);
309 AssertRCReturn(rc, rc);
310 }
311
312 /*
313 * Determine the TSC configuration and frequency.
314 */
315 /* mode */
316 /** @cfgm{/TM/TSCVirtualized,bool,true}
317 * Use a virtualize TSC, i.e. trap all TSC access. */
318 rc = CFGMR3QueryBool(pCfgHandle, "TSCVirtualized", &pVM->tm.s.fTSCVirtualized);
319 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
320 pVM->tm.s.fTSCVirtualized = true; /* trap rdtsc */
321 else if (RT_FAILURE(rc))
322 return VMSetError(pVM, rc, RT_SRC_POS,
323 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
324
325 /* source */
326 /** @cfgm{/TM/UseRealTSC,bool,false}
327 * Use the real TSC as time source for the TSC instead of the synchronous
328 * virtual clock (false, default). */
329 rc = CFGMR3QueryBool(pCfgHandle, "UseRealTSC", &pVM->tm.s.fTSCUseRealTSC);
330 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
331 pVM->tm.s.fTSCUseRealTSC = false; /* use virtual time */
332 else if (RT_FAILURE(rc))
333 return VMSetError(pVM, rc, RT_SRC_POS,
334 N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
335 if (!pVM->tm.s.fTSCUseRealTSC)
336 pVM->tm.s.fTSCVirtualized = true;
337
338 /* TSC reliability */
339 /** @cfgm{/TM/MaybeUseOffsettedHostTSC,bool,detect}
340 * Whether the CPU has a fixed TSC rate and may be used in offsetted mode with
341 * VT-x/AMD-V execution. This is autodetected in a very restrictive way by
342 * default. */
343 rc = CFGMR3QueryBool(pCfgHandle, "MaybeUseOffsettedHostTSC", &pVM->tm.s.fMaybeUseOffsettedHostTSC);
344 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
345 {
346 if (!pVM->tm.s.fTSCUseRealTSC)
347 pVM->tm.s.fMaybeUseOffsettedHostTSC = tmR3HasFixedTSC(pVM);
348 else
349 pVM->tm.s.fMaybeUseOffsettedHostTSC = true;
350 /** @todo needs a better fix, for now disable offsetted mode for VMs
351 * with more than one VCPU. With the current TSC handling (frequent
352 * switching between offsetted mode and taking VM exits, on all VCPUs
353 * without any kind of coordination) it will lead to inconsistent TSC
354 * behavior with guest SMP, including TSC going backwards. */
355 if (pVM->cCpus != 1)
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 pVM->tm.s.cTSCsTicking = 0;
1228 /* the virtual clock. */
1229 uint64_t u64Hz;
1230 int rc = SSMR3GetU64(pSSM, &u64Hz);
1231 if (RT_FAILURE(rc))
1232 return rc;
1233 if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
1234 {
1235 AssertMsgFailed(("The virtual clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1236 u64Hz, TMCLOCK_FREQ_VIRTUAL));
1237 return VERR_SSM_VIRTUAL_CLOCK_HZ;
1238 }
1239 SSMR3GetU64(pSSM, &pVM->tm.s.u64Virtual);
1240 pVM->tm.s.u64VirtualOffset = 0;
1241
1242 /* the virtual timer synchronous clock. */
1243 pVM->tm.s.fVirtualSyncTicking = false;
1244 uint64_t u64;
1245 SSMR3GetU64(pSSM, &u64);
1246 pVM->tm.s.u64VirtualSync = u64;
1247 SSMR3GetU64(pSSM, &u64);
1248 pVM->tm.s.offVirtualSync = u64;
1249 SSMR3GetU64(pSSM, &u64);
1250 pVM->tm.s.offVirtualSyncGivenUp = u64;
1251 SSMR3GetU64(pSSM, &u64);
1252 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64;
1253 bool f;
1254 SSMR3GetBool(pSSM, &f);
1255 pVM->tm.s.fVirtualSyncCatchUp = f;
1256
1257 /* the real clock */
1258 rc = SSMR3GetU64(pSSM, &u64Hz);
1259 if (RT_FAILURE(rc))
1260 return rc;
1261 if (u64Hz != TMCLOCK_FREQ_REAL)
1262 {
1263 AssertMsgFailed(("The real clock frequency differs! Saved: %'RU64 Binary: %'RU64\n",
1264 u64Hz, TMCLOCK_FREQ_REAL));
1265 return VERR_SSM_VIRTUAL_CLOCK_HZ; /* misleading... */
1266 }
1267
1268 /* the cpu tick clock. */
1269 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1270 {
1271 PVMCPU pVCpu = &pVM->aCpus[i];
1272
1273 pVCpu->tm.s.fTSCTicking = false;
1274 SSMR3GetU64(pSSM, &pVCpu->tm.s.u64TSC);
1275
1276 if (pVM->tm.s.fTSCUseRealTSC)
1277 pVCpu->tm.s.offTSCRawSrc = 0; /** @todo TSC restore stuff and HWACC. */
1278 }
1279
1280 rc = SSMR3GetU64(pSSM, &u64Hz);
1281 if (RT_FAILURE(rc))
1282 return rc;
1283 if (!pVM->tm.s.fTSCUseRealTSC)
1284 pVM->tm.s.cTSCTicksPerSecond = u64Hz;
1285
1286 LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%'RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
1287 pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
1288
1289 /*
1290 * Make sure timers get rescheduled immediately.
1291 */
1292 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1293 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1294
1295 return VINF_SUCCESS;
1296}
1297
1298
1299/**
1300 * Internal TMR3TimerCreate worker.
1301 *
1302 * @returns VBox status code.
1303 * @param pVM Pointer to the VM.
1304 * @param enmClock The timer clock.
1305 * @param pszDesc The timer description.
1306 * @param ppTimer Where to store the timer pointer on success.
1307 */
1308static int tmr3TimerCreate(PVM pVM, TMCLOCK enmClock, const char *pszDesc, PPTMTIMERR3 ppTimer)
1309{
1310 VM_ASSERT_EMT(pVM);
1311
1312 /*
1313 * Allocate the timer.
1314 */
1315 PTMTIMERR3 pTimer = NULL;
1316 if (pVM->tm.s.pFree && VM_IS_EMT(pVM))
1317 {
1318 pTimer = pVM->tm.s.pFree;
1319 pVM->tm.s.pFree = pTimer->pBigNext;
1320 Log3(("TM: Recycling timer %p, new free head %p.\n", pTimer, pTimer->pBigNext));
1321 }
1322
1323 if (!pTimer)
1324 {
1325 int rc = MMHyperAlloc(pVM, sizeof(*pTimer), 0, MM_TAG_TM, (void **)&pTimer);
1326 if (RT_FAILURE(rc))
1327 return rc;
1328 Log3(("TM: Allocated new timer %p\n", pTimer));
1329 }
1330
1331 /*
1332 * Initialize it.
1333 */
1334 pTimer->u64Expire = 0;
1335 pTimer->enmClock = enmClock;
1336 pTimer->pVMR3 = pVM;
1337 pTimer->pVMR0 = pVM->pVMR0;
1338 pTimer->pVMRC = pVM->pVMRC;
1339 pTimer->enmState = TMTIMERSTATE_STOPPED;
1340 pTimer->offScheduleNext = 0;
1341 pTimer->offNext = 0;
1342 pTimer->offPrev = 0;
1343 pTimer->pvUser = NULL;
1344 pTimer->pCritSect = NULL;
1345 pTimer->pszDesc = pszDesc;
1346
1347 /* insert into the list of created timers. */
1348 TM_LOCK_TIMERS(pVM);
1349 pTimer->pBigPrev = NULL;
1350 pTimer->pBigNext = pVM->tm.s.pCreated;
1351 pVM->tm.s.pCreated = pTimer;
1352 if (pTimer->pBigNext)
1353 pTimer->pBigNext->pBigPrev = pTimer;
1354#ifdef VBOX_STRICT
1355 tmTimerQueuesSanityChecks(pVM, "tmR3TimerCreate");
1356#endif
1357 TM_UNLOCK_TIMERS(pVM);
1358
1359 *ppTimer = pTimer;
1360 return VINF_SUCCESS;
1361}
1362
1363
1364/**
1365 * Creates a device timer.
1366 *
1367 * @returns VBox status.
1368 * @param pVM The VM to create the timer in.
1369 * @param pDevIns Device instance.
1370 * @param enmClock The clock to use on this timer.
1371 * @param pfnCallback Callback function.
1372 * @param pvUser The user argument to the callback.
1373 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1374 * @param pszDesc Pointer to description string which must stay around
1375 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1376 * @param ppTimer Where to store the timer on success.
1377 */
1378VMM_INT_DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock,
1379 PFNTMTIMERDEV pfnCallback, void *pvUser,
1380 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1381{
1382 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1383
1384 /*
1385 * Allocate and init stuff.
1386 */
1387 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1388 if (RT_SUCCESS(rc))
1389 {
1390 (*ppTimer)->enmType = TMTIMERTYPE_DEV;
1391 (*ppTimer)->u.Dev.pfnTimer = pfnCallback;
1392 (*ppTimer)->u.Dev.pDevIns = pDevIns;
1393 (*ppTimer)->pvUser = pvUser;
1394 if (!(fFlags & TMTIMER_FLAGS_NO_CRIT_SECT))
1395 (*ppTimer)->pCritSect = PDMR3DevGetCritSect(pVM, pDevIns);
1396 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1397 }
1398
1399 return rc;
1400}
1401
1402
1403
1404
1405/**
1406 * Creates a USB device timer.
1407 *
1408 * @returns VBox status.
1409 * @param pVM The VM to create the timer in.
1410 * @param pUsbIns The USB device instance.
1411 * @param enmClock The clock to use on this timer.
1412 * @param pfnCallback Callback function.
1413 * @param pvUser The user argument to the callback.
1414 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1415 * @param pszDesc Pointer to description string which must stay around
1416 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1417 * @param ppTimer Where to store the timer on success.
1418 */
1419VMM_INT_DECL(int) TMR3TimerCreateUsb(PVM pVM, PPDMUSBINS pUsbIns, TMCLOCK enmClock,
1420 PFNTMTIMERUSB pfnCallback, void *pvUser,
1421 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1422{
1423 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1424
1425 /*
1426 * Allocate and init stuff.
1427 */
1428 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1429 if (RT_SUCCESS(rc))
1430 {
1431 (*ppTimer)->enmType = TMTIMERTYPE_USB;
1432 (*ppTimer)->u.Usb.pfnTimer = pfnCallback;
1433 (*ppTimer)->u.Usb.pUsbIns = pUsbIns;
1434 (*ppTimer)->pvUser = pvUser;
1435 //if (!(fFlags & TMTIMER_FLAGS_NO_CRIT_SECT))
1436 //{
1437 // if (pDevIns->pCritSectR3)
1438 // (*ppTimer)->pCritSect = pUsbIns->pCritSectR3;
1439 // else
1440 // (*ppTimer)->pCritSect = IOMR3GetCritSect(pVM);
1441 //}
1442 Log(("TM: Created USB device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1443 }
1444
1445 return rc;
1446}
1447
1448
1449/**
1450 * Creates a driver timer.
1451 *
1452 * @returns VBox status.
1453 * @param pVM The VM to create the timer in.
1454 * @param pDrvIns Driver instance.
1455 * @param enmClock The clock to use on this timer.
1456 * @param pfnCallback Callback function.
1457 * @param pvUser The user argument to the callback.
1458 * @param fFlags Timer creation flags, see grp_tm_timer_flags.
1459 * @param pszDesc Pointer to description string which must stay around
1460 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1461 * @param ppTimer Where to store the timer on success.
1462 */
1463VMM_INT_DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, void *pvUser,
1464 uint32_t fFlags, const char *pszDesc, PPTMTIMERR3 ppTimer)
1465{
1466 AssertReturn(!(fFlags & ~(TMTIMER_FLAGS_NO_CRIT_SECT)), VERR_INVALID_PARAMETER);
1467
1468 /*
1469 * Allocate and init stuff.
1470 */
1471 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, ppTimer);
1472 if (RT_SUCCESS(rc))
1473 {
1474 (*ppTimer)->enmType = TMTIMERTYPE_DRV;
1475 (*ppTimer)->u.Drv.pfnTimer = pfnCallback;
1476 (*ppTimer)->u.Drv.pDrvIns = pDrvIns;
1477 (*ppTimer)->pvUser = pvUser;
1478 Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
1479 }
1480
1481 return rc;
1482}
1483
1484
1485/**
1486 * Creates an internal timer.
1487 *
1488 * @returns VBox status.
1489 * @param pVM The VM to create the timer in.
1490 * @param enmClock The clock to use on this timer.
1491 * @param pfnCallback Callback function.
1492 * @param pvUser User argument to be passed to the callback.
1493 * @param pszDesc Pointer to description string which must stay around
1494 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1495 * @param ppTimer Where to store the timer on success.
1496 */
1497VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
1498{
1499 /*
1500 * Allocate and init stuff.
1501 */
1502 PTMTIMER pTimer;
1503 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1504 if (RT_SUCCESS(rc))
1505 {
1506 pTimer->enmType = TMTIMERTYPE_INTERNAL;
1507 pTimer->u.Internal.pfnTimer = pfnCallback;
1508 pTimer->pvUser = pvUser;
1509 *ppTimer = pTimer;
1510 Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1511 }
1512
1513 return rc;
1514}
1515
1516/**
1517 * Creates an external timer.
1518 *
1519 * @returns Timer handle on success.
1520 * @returns NULL on failure.
1521 * @param pVM The VM to create the timer in.
1522 * @param enmClock The clock to use on this timer.
1523 * @param pfnCallback Callback function.
1524 * @param pvUser User argument.
1525 * @param pszDesc Pointer to description string which must stay around
1526 * until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
1527 */
1528VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
1529{
1530 /*
1531 * Allocate and init stuff.
1532 */
1533 PTMTIMERR3 pTimer;
1534 int rc = tmr3TimerCreate(pVM, enmClock, pszDesc, &pTimer);
1535 if (RT_SUCCESS(rc))
1536 {
1537 pTimer->enmType = TMTIMERTYPE_EXTERNAL;
1538 pTimer->u.External.pfnTimer = pfnCallback;
1539 pTimer->pvUser = pvUser;
1540 Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
1541 return pTimer;
1542 }
1543
1544 return NULL;
1545}
1546
1547
1548/**
1549 * Destroy a timer
1550 *
1551 * @returns VBox status.
1552 * @param pTimer Timer handle as returned by one of the create functions.
1553 */
1554VMMR3DECL(int) TMR3TimerDestroy(PTMTIMER pTimer)
1555{
1556 /*
1557 * Be extra careful here.
1558 */
1559 if (!pTimer)
1560 return VINF_SUCCESS;
1561 AssertPtr(pTimer);
1562 Assert((unsigned)pTimer->enmClock < (unsigned)TMCLOCK_MAX);
1563
1564 PVM pVM = pTimer->CTX_SUFF(pVM);
1565 PTMTIMERQUEUE pQueue = &pVM->tm.s.CTX_SUFF(paTimerQueues)[pTimer->enmClock];
1566 bool fActive = false;
1567 bool fPending = false;
1568
1569 AssertMsg( !pTimer->pCritSect
1570 || VMR3GetState(pVM) != VMSTATE_RUNNING
1571 || PDMCritSectIsOwner(pTimer->pCritSect), ("%s\n", pTimer->pszDesc));
1572
1573 /*
1574 * The rest of the game happens behind the lock, just
1575 * like create does. All the work is done here.
1576 */
1577 TM_LOCK_TIMERS(pVM);
1578 for (int cRetries = 1000;; cRetries--)
1579 {
1580 /*
1581 * Change to the DESTROY state.
1582 */
1583 TMTIMERSTATE const enmState = pTimer->enmState;
1584 Log2(("TMTimerDestroy: %p:{.enmState=%s, .pszDesc='%s'} cRetries=%d\n",
1585 pTimer, tmTimerState(enmState), R3STRING(pTimer->pszDesc), cRetries));
1586 switch (enmState)
1587 {
1588 case TMTIMERSTATE_STOPPED:
1589 case TMTIMERSTATE_EXPIRED_DELIVER:
1590 break;
1591
1592 case TMTIMERSTATE_ACTIVE:
1593 fActive = true;
1594 break;
1595
1596 case TMTIMERSTATE_PENDING_STOP:
1597 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
1598 case TMTIMERSTATE_PENDING_RESCHEDULE:
1599 fActive = true;
1600 fPending = true;
1601 break;
1602
1603 case TMTIMERSTATE_PENDING_SCHEDULE:
1604 fPending = true;
1605 break;
1606
1607 /*
1608 * This shouldn't happen as the caller should make sure there are no races.
1609 */
1610 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
1611 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
1612 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
1613 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1614 TM_UNLOCK_TIMERS(pVM);
1615 if (!RTThreadYield())
1616 RTThreadSleep(1);
1617 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1618 VERR_TM_UNSTABLE_STATE);
1619 TM_LOCK_TIMERS(pVM);
1620 continue;
1621
1622 /*
1623 * Invalid states.
1624 */
1625 case TMTIMERSTATE_FREE:
1626 case TMTIMERSTATE_DESTROY:
1627 TM_UNLOCK_TIMERS(pVM);
1628 AssertLogRelMsgFailedReturn(("pTimer=%p %s\n", pTimer, tmTimerState(enmState)), VERR_TM_INVALID_STATE);
1629
1630 default:
1631 AssertMsgFailed(("Unknown timer state %d (%s)\n", enmState, R3STRING(pTimer->pszDesc)));
1632 TM_UNLOCK_TIMERS(pVM);
1633 return VERR_TM_UNKNOWN_STATE;
1634 }
1635
1636 /*
1637 * Try switch to the destroy state.
1638 * This should always succeed as the caller should make sure there are no race.
1639 */
1640 bool fRc;
1641 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_DESTROY, enmState, fRc);
1642 if (fRc)
1643 break;
1644 AssertMsgFailed(("%p:.enmState=%s %s\n", pTimer, tmTimerState(enmState), pTimer->pszDesc));
1645 TM_UNLOCK_TIMERS(pVM);
1646 AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
1647 VERR_TM_UNSTABLE_STATE);
1648 TM_LOCK_TIMERS(pVM);
1649 }
1650
1651 /*
1652 * Unlink from the active list.
1653 */
1654 if (fActive)
1655 {
1656 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
1657 const PTMTIMER pNext = TMTIMER_GET_NEXT(pTimer);
1658 if (pPrev)
1659 TMTIMER_SET_NEXT(pPrev, pNext);
1660 else
1661 {
1662 TMTIMER_SET_HEAD(pQueue, pNext);
1663 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
1664 }
1665 if (pNext)
1666 TMTIMER_SET_PREV(pNext, pPrev);
1667 pTimer->offNext = 0;
1668 pTimer->offPrev = 0;
1669 }
1670
1671 /*
1672 * Unlink from the schedule list by running it.
1673 */
1674 if (fPending)
1675 {
1676 Log3(("TMR3TimerDestroy: tmTimerQueueSchedule\n"));
1677 STAM_PROFILE_START(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1678 Assert(pQueue->offSchedule);
1679 tmTimerQueueSchedule(pVM, pQueue);
1680 STAM_PROFILE_STOP(&pVM->tm.s.CTX_SUFF_Z(StatScheduleOne), a);
1681 }
1682
1683 /*
1684 * Read to move the timer from the created list and onto the free list.
1685 */
1686 Assert(!pTimer->offNext); Assert(!pTimer->offPrev); Assert(!pTimer->offScheduleNext);
1687
1688 /* unlink from created list */
1689 if (pTimer->pBigPrev)
1690 pTimer->pBigPrev->pBigNext = pTimer->pBigNext;
1691 else
1692 pVM->tm.s.pCreated = pTimer->pBigNext;
1693 if (pTimer->pBigNext)
1694 pTimer->pBigNext->pBigPrev = pTimer->pBigPrev;
1695 pTimer->pBigNext = 0;
1696 pTimer->pBigPrev = 0;
1697
1698 /* free */
1699 Log2(("TM: Inserting %p into the free list ahead of %p!\n", pTimer, pVM->tm.s.pFree));
1700 TM_SET_STATE(pTimer, TMTIMERSTATE_FREE);
1701 pTimer->pBigNext = pVM->tm.s.pFree;
1702 pVM->tm.s.pFree = pTimer;
1703
1704#ifdef VBOX_STRICT
1705 tmTimerQueuesSanityChecks(pVM, "TMR3TimerDestroy");
1706#endif
1707 TM_UNLOCK_TIMERS(pVM);
1708 return VINF_SUCCESS;
1709}
1710
1711
1712/**
1713 * Destroy all timers owned by a device.
1714 *
1715 * @returns VBox status.
1716 * @param pVM Pointer to the VM.
1717 * @param pDevIns Device which timers should be destroyed.
1718 */
1719VMM_INT_DECL(int) TMR3TimerDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
1720{
1721 LogFlow(("TMR3TimerDestroyDevice: pDevIns=%p\n", pDevIns));
1722 if (!pDevIns)
1723 return VERR_INVALID_PARAMETER;
1724
1725 TM_LOCK_TIMERS(pVM);
1726 PTMTIMER pCur = pVM->tm.s.pCreated;
1727 while (pCur)
1728 {
1729 PTMTIMER pDestroy = pCur;
1730 pCur = pDestroy->pBigNext;
1731 if ( pDestroy->enmType == TMTIMERTYPE_DEV
1732 && pDestroy->u.Dev.pDevIns == pDevIns)
1733 {
1734 int rc = TMR3TimerDestroy(pDestroy);
1735 AssertRC(rc);
1736 }
1737 }
1738 TM_UNLOCK_TIMERS(pVM);
1739
1740 LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
1741 return VINF_SUCCESS;
1742}
1743
1744
1745/**
1746 * Destroy all timers owned by a USB device.
1747 *
1748 * @returns VBox status.
1749 * @param pVM Pointer to the VM.
1750 * @param pUsbIns USB device which timers should be destroyed.
1751 */
1752VMM_INT_DECL(int) TMR3TimerDestroyUsb(PVM pVM, PPDMUSBINS pUsbIns)
1753{
1754 LogFlow(("TMR3TimerDestroyUsb: pUsbIns=%p\n", pUsbIns));
1755 if (!pUsbIns)
1756 return VERR_INVALID_PARAMETER;
1757
1758 TM_LOCK_TIMERS(pVM);
1759 PTMTIMER pCur = pVM->tm.s.pCreated;
1760 while (pCur)
1761 {
1762 PTMTIMER pDestroy = pCur;
1763 pCur = pDestroy->pBigNext;
1764 if ( pDestroy->enmType == TMTIMERTYPE_USB
1765 && pDestroy->u.Usb.pUsbIns == pUsbIns)
1766 {
1767 int rc = TMR3TimerDestroy(pDestroy);
1768 AssertRC(rc);
1769 }
1770 }
1771 TM_UNLOCK_TIMERS(pVM);
1772
1773 LogFlow(("TMR3TimerDestroyUsb: returns VINF_SUCCESS\n"));
1774 return VINF_SUCCESS;
1775}
1776
1777
1778/**
1779 * Destroy all timers owned by a driver.
1780 *
1781 * @returns VBox status.
1782 * @param pVM Pointer to the VM.
1783 * @param pDrvIns Driver which timers should be destroyed.
1784 */
1785VMM_INT_DECL(int) TMR3TimerDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
1786{
1787 LogFlow(("TMR3TimerDestroyDriver: pDrvIns=%p\n", pDrvIns));
1788 if (!pDrvIns)
1789 return VERR_INVALID_PARAMETER;
1790
1791 TM_LOCK_TIMERS(pVM);
1792 PTMTIMER pCur = pVM->tm.s.pCreated;
1793 while (pCur)
1794 {
1795 PTMTIMER pDestroy = pCur;
1796 pCur = pDestroy->pBigNext;
1797 if ( pDestroy->enmType == TMTIMERTYPE_DRV
1798 && pDestroy->u.Drv.pDrvIns == pDrvIns)
1799 {
1800 int rc = TMR3TimerDestroy(pDestroy);
1801 AssertRC(rc);
1802 }
1803 }
1804 TM_UNLOCK_TIMERS(pVM);
1805
1806 LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
1807 return VINF_SUCCESS;
1808}
1809
1810
1811/**
1812 * Internal function for getting the clock time.
1813 *
1814 * @returns clock time.
1815 * @param pVM Pointer to the VM.
1816 * @param enmClock The clock.
1817 */
1818DECLINLINE(uint64_t) tmClock(PVM pVM, TMCLOCK enmClock)
1819{
1820 switch (enmClock)
1821 {
1822 case TMCLOCK_VIRTUAL: return TMVirtualGet(pVM);
1823 case TMCLOCK_VIRTUAL_SYNC: return TMVirtualSyncGet(pVM);
1824 case TMCLOCK_REAL: return TMRealGet(pVM);
1825 case TMCLOCK_TSC: return TMCpuTickGet(&pVM->aCpus[0] /* just take VCPU 0 */);
1826 default:
1827 AssertMsgFailed(("enmClock=%d\n", enmClock));
1828 return ~(uint64_t)0;
1829 }
1830}
1831
1832
1833/**
1834 * Checks if the sync queue has one or more expired timers.
1835 *
1836 * @returns true / false.
1837 *
1838 * @param pVM Pointer to the VM.
1839 * @param enmClock The queue.
1840 */
1841DECLINLINE(bool) tmR3HasExpiredTimer(PVM pVM, TMCLOCK enmClock)
1842{
1843 const uint64_t u64Expire = pVM->tm.s.CTX_SUFF(paTimerQueues)[enmClock].u64Expire;
1844 return u64Expire != INT64_MAX && u64Expire <= tmClock(pVM, enmClock);
1845}
1846
1847
1848/**
1849 * Checks for expired timers in all the queues.
1850 *
1851 * @returns true / false.
1852 * @param pVM Pointer to the VM.
1853 */
1854DECLINLINE(bool) tmR3AnyExpiredTimers(PVM pVM)
1855{
1856 /*
1857 * Combine the time calculation for the first two since we're not on EMT
1858 * TMVirtualSyncGet only permits EMT.
1859 */
1860 uint64_t u64Now = TMVirtualGetNoCheck(pVM);
1861 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL].u64Expire <= u64Now)
1862 return true;
1863 u64Now = pVM->tm.s.fVirtualSyncTicking
1864 ? u64Now - pVM->tm.s.offVirtualSync
1865 : pVM->tm.s.u64VirtualSync;
1866 if (pVM->tm.s.CTX_SUFF(paTimerQueues)[TMCLOCK_VIRTUAL_SYNC].u64Expire <= u64Now)
1867 return true;
1868
1869 /*
1870 * The remaining timers.
1871 */
1872 if (tmR3HasExpiredTimer(pVM, TMCLOCK_REAL))
1873 return true;
1874 if (tmR3HasExpiredTimer(pVM, TMCLOCK_TSC))
1875 return true;
1876 return false;
1877}
1878
1879
1880/**
1881 * Schedule timer callback.
1882 *
1883 * @param pTimer Timer handle.
1884 * @param pvUser Pointer to the VM.
1885 * @thread Timer thread.
1886 *
1887 * @remark We cannot do the scheduling and queues running from a timer handler
1888 * since it's not executing in EMT, and even if it was it would be async
1889 * and we wouldn't know the state of the affairs.
1890 * So, we'll just raise the timer FF and force any REM execution to exit.
1891 */
1892static DECLCALLBACK(void) tmR3TimerCallback(PRTTIMER pTimer, void *pvUser, uint64_t /*iTick*/)
1893{
1894 PVM pVM = (PVM)pvUser;
1895 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1896 NOREF(pTimer);
1897
1898 AssertCompile(TMCLOCK_MAX == 4);
1899#ifdef DEBUG_Sander /* very annoying, keep it private. */
1900 if (VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER))
1901 Log(("tmR3TimerCallback: timer event still pending!!\n"));
1902#endif
1903 if ( !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
1904 && ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule /** @todo FIXME - reconsider offSchedule as a reason for running the timer queues. */
1905 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule
1906 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule
1907 || pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offSchedule
1908 || tmR3AnyExpiredTimers(pVM)
1909 )
1910 && !VMCPU_FF_IS_SET(pVCpuDst, VMCPU_FF_TIMER)
1911 && !pVM->tm.s.fRunningQueues
1912 )
1913 {
1914 Log5(("TM(%u): FF: 0 -> 1\n", __LINE__));
1915 VMCPU_FF_SET(pVCpuDst, VMCPU_FF_TIMER);
1916#ifdef VBOX_WITH_REM
1917 REMR3NotifyTimerPending(pVM, pVCpuDst);
1918#endif
1919 VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM /** @todo | VMNOTIFYFF_FLAGS_POKE ?*/);
1920 STAM_COUNTER_INC(&pVM->tm.s.StatTimerCallbackSetFF);
1921 }
1922}
1923
1924
1925/**
1926 * Schedules and runs any pending timers.
1927 *
1928 * This is normally called from a forced action handler in EMT.
1929 *
1930 * @param pVM The VM to run the timers for.
1931 *
1932 * @thread EMT (actually EMT0, but we fend off the others)
1933 */
1934VMMR3DECL(void) TMR3TimerQueuesDo(PVM pVM)
1935{
1936 /*
1937 * Only the dedicated timer EMT should do stuff here.
1938 * (fRunningQueues is only used as an indicator.)
1939 */
1940 Assert(pVM->tm.s.idTimerCpu < pVM->cCpus);
1941 PVMCPU pVCpuDst = &pVM->aCpus[pVM->tm.s.idTimerCpu];
1942 if (VMMGetCpu(pVM) != pVCpuDst)
1943 {
1944 Assert(pVM->cCpus > 1);
1945 return;
1946 }
1947 STAM_PROFILE_START(&pVM->tm.s.StatDoQueues, a);
1948 Log2(("TMR3TimerQueuesDo:\n"));
1949 Assert(!pVM->tm.s.fRunningQueues);
1950 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, true);
1951 TM_LOCK_TIMERS(pVM);
1952
1953 /*
1954 * Process the queues.
1955 */
1956 AssertCompile(TMCLOCK_MAX == 4);
1957
1958 /* TMCLOCK_VIRTUAL_SYNC (see also TMR3VirtualSyncFF) */
1959 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
1960 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
1961 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
1962 VMCPU_FF_CLEAR(pVCpuDst, VMCPU_FF_TIMER); /* Clear the FF once we started working for real. */
1963
1964 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule);
1965 tmR3TimerQueueRunVirtualSync(pVM);
1966 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
1967 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
1968
1969 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
1970 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
1971 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL_SYNC], s1);
1972
1973 /* TMCLOCK_VIRTUAL */
1974 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
1975 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL].offSchedule)
1976 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1977 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL]);
1978 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_VIRTUAL], s2);
1979
1980 /* TMCLOCK_TSC */
1981 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_TSC].offActive); /* not used */
1982
1983 /* TMCLOCK_REAL */
1984 STAM_PROFILE_ADV_START(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
1985 if (pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL].offSchedule)
1986 tmTimerQueueSchedule(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1987 tmR3TimerQueueRun(pVM, &pVM->tm.s.paTimerQueuesR3[TMCLOCK_REAL]);
1988 STAM_PROFILE_ADV_STOP(&pVM->tm.s.aStatDoQueues[TMCLOCK_REAL], s3);
1989
1990#ifdef VBOX_STRICT
1991 /* check that we didn't screw up. */
1992 tmTimerQueuesSanityChecks(pVM, "TMR3TimerQueuesDo");
1993#endif
1994
1995 /* done */
1996 Log2(("TMR3TimerQueuesDo: returns void\n"));
1997 ASMAtomicWriteBool(&pVM->tm.s.fRunningQueues, false);
1998 TM_UNLOCK_TIMERS(pVM);
1999 STAM_PROFILE_STOP(&pVM->tm.s.StatDoQueues, a);
2000}
2001
2002//RT_C_DECLS_BEGIN
2003//int iomLock(PVM pVM);
2004//void iomUnlock(PVM pVM);
2005//RT_C_DECLS_END
2006
2007
2008/**
2009 * Schedules and runs any pending times in the specified queue.
2010 *
2011 * This is normally called from a forced action handler in EMT.
2012 *
2013 * @param pVM The VM to run the timers for.
2014 * @param pQueue The queue to run.
2015 */
2016static void tmR3TimerQueueRun(PVM pVM, PTMTIMERQUEUE pQueue)
2017{
2018 VM_ASSERT_EMT(pVM);
2019
2020 /*
2021 * Run timers.
2022 *
2023 * We check the clock once and run all timers which are ACTIVE
2024 * and have an expire time less or equal to the time we read.
2025 *
2026 * N.B. A generic unlink must be applied since other threads
2027 * are allowed to mess with any active timer at any time.
2028 * However, we only allow EMT to handle EXPIRED_PENDING
2029 * timers, thus enabling the timer handler function to
2030 * arm the timer again.
2031 */
2032 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
2033 if (!pNext)
2034 return;
2035 const uint64_t u64Now = tmClock(pVM, pQueue->enmClock);
2036 while (pNext && pNext->u64Expire <= u64Now)
2037 {
2038 PTMTIMER pTimer = pNext;
2039 pNext = TMTIMER_GET_NEXT(pTimer);
2040 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2041 if (pCritSect)
2042 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2043 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2044 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2045 bool fRc;
2046 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_GET_UNLINK, TMTIMERSTATE_ACTIVE, fRc);
2047 if (fRc)
2048 {
2049 Assert(!pTimer->offScheduleNext); /* this can trigger falsely */
2050
2051 /* unlink */
2052 const PTMTIMER pPrev = TMTIMER_GET_PREV(pTimer);
2053 if (pPrev)
2054 TMTIMER_SET_NEXT(pPrev, pNext);
2055 else
2056 {
2057 TMTIMER_SET_HEAD(pQueue, pNext);
2058 pQueue->u64Expire = pNext ? pNext->u64Expire : INT64_MAX;
2059 }
2060 if (pNext)
2061 TMTIMER_SET_PREV(pNext, pPrev);
2062 pTimer->offNext = 0;
2063 pTimer->offPrev = 0;
2064
2065 /* fire */
2066 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2067 switch (pTimer->enmType)
2068 {
2069 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2070 case TMTIMERTYPE_USB: pTimer->u.Usb.pfnTimer(pTimer->u.Usb.pUsbIns, pTimer, pTimer->pvUser); break;
2071 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2072 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2073 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2074 default:
2075 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2076 break;
2077 }
2078
2079 /* change the state if it wasn't changed already in the handler. */
2080 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2081 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2082 }
2083 if (pCritSect)
2084 PDMCritSectLeave(pCritSect);
2085 } /* run loop */
2086}
2087
2088
2089/**
2090 * Schedules and runs any pending times in the timer queue for the
2091 * synchronous virtual clock.
2092 *
2093 * This scheduling is a bit different from the other queues as it need
2094 * to implement the special requirements of the timer synchronous virtual
2095 * clock, thus this 2nd queue run function.
2096 *
2097 * @param pVM The VM to run the timers for.
2098 *
2099 * @remarks The caller must the Virtual Sync lock. Owning the TM lock is no
2100 * longer important.
2101 */
2102static void tmR3TimerQueueRunVirtualSync(PVM pVM)
2103{
2104 PTMTIMERQUEUE const pQueue = &pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC];
2105 VM_ASSERT_EMT(pVM);
2106 Assert(PDMCritSectIsOwner(&pVM->tm.s.VirtualSyncLock));
2107
2108 /*
2109 * Any timers?
2110 */
2111 PTMTIMER pNext = TMTIMER_GET_HEAD(pQueue);
2112 if (RT_UNLIKELY(!pNext))
2113 {
2114 Assert(pVM->tm.s.fVirtualSyncTicking || !pVM->tm.s.cVirtualTicking);
2115 return;
2116 }
2117 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRun);
2118
2119 /*
2120 * Calculate the time frame for which we will dispatch timers.
2121 *
2122 * We use a time frame ranging from the current sync time (which is most likely the
2123 * same as the head timer) and some configurable period (100000ns) up towards the
2124 * current virtual time. This period might also need to be restricted by the catch-up
2125 * rate so frequent calls to this function won't accelerate the time too much, however
2126 * this will be implemented at a later point if necessary.
2127 *
2128 * Without this frame we would 1) having to run timers much more frequently
2129 * and 2) lag behind at a steady rate.
2130 */
2131 const uint64_t u64VirtualNow = TMVirtualGetNoCheck(pVM);
2132 uint64_t const offSyncGivenUp = pVM->tm.s.offVirtualSyncGivenUp;
2133 uint64_t u64Now;
2134 if (!pVM->tm.s.fVirtualSyncTicking)
2135 {
2136 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStoppedAlready);
2137 u64Now = pVM->tm.s.u64VirtualSync;
2138 Assert(u64Now <= pNext->u64Expire);
2139 }
2140 else
2141 {
2142 /* Calc 'now'. */
2143 bool fStopCatchup = false;
2144 bool fUpdateStuff = false;
2145 uint64_t off = pVM->tm.s.offVirtualSync;
2146 if (pVM->tm.s.fVirtualSyncCatchUp)
2147 {
2148 uint64_t u64Delta = u64VirtualNow - pVM->tm.s.u64VirtualSyncCatchUpPrev;
2149 if (RT_LIKELY(!(u64Delta >> 32)))
2150 {
2151 uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
2152 if (off > u64Sub + offSyncGivenUp)
2153 {
2154 off -= u64Sub;
2155 Log4(("TM: %'RU64/-%'8RU64: sub %'RU64 [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow - off, off - offSyncGivenUp, u64Sub));
2156 }
2157 else
2158 {
2159 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2160 fStopCatchup = true;
2161 off = offSyncGivenUp;
2162 }
2163 fUpdateStuff = true;
2164 }
2165 }
2166 u64Now = u64VirtualNow - off;
2167
2168 /* Adjust against last returned time. */
2169 uint64_t u64Last = ASMAtomicUoReadU64(&pVM->tm.s.u64VirtualSync);
2170 if (u64Last > u64Now)
2171 {
2172 u64Now = u64Last + 1;
2173 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGetAdjLast);
2174 }
2175
2176 /* Check if stopped by expired timer. */
2177 uint64_t const u64Expire = pNext->u64Expire;
2178 if (u64Now >= u64Expire)
2179 {
2180 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunStop);
2181 u64Now = u64Expire;
2182 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2183 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2184 Log4(("TM: %'RU64/-%'8RU64: exp tmr [tmR3TimerQueueRunVirtualSync]\n", u64Now, u64VirtualNow - u64Now - offSyncGivenUp));
2185 }
2186 else
2187 {
2188 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2189 if (fUpdateStuff)
2190 {
2191 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, off);
2192 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSyncCatchUpPrev, u64VirtualNow);
2193 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, u64Now);
2194 if (fStopCatchup)
2195 {
2196 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2197 Log4(("TM: %'RU64/0: caught up [tmR3TimerQueueRunVirtualSync]\n", u64VirtualNow));
2198 }
2199 }
2200 }
2201 }
2202
2203 /* calc end of frame. */
2204 uint64_t u64Max = u64Now + pVM->tm.s.u32VirtualSyncScheduleSlack;
2205 if (u64Max > u64VirtualNow - offSyncGivenUp)
2206 u64Max = u64VirtualNow - offSyncGivenUp;
2207
2208 /* assert sanity */
2209 Assert(u64Now <= u64VirtualNow - offSyncGivenUp);
2210 Assert(u64Max <= u64VirtualNow - offSyncGivenUp);
2211 Assert(u64Now <= u64Max);
2212 Assert(offSyncGivenUp == pVM->tm.s.offVirtualSyncGivenUp);
2213
2214 /*
2215 * Process the expired timers moving the clock along as we progress.
2216 */
2217#ifdef VBOX_STRICT
2218 uint64_t u64Prev = u64Now; NOREF(u64Prev);
2219#endif
2220 while (pNext && pNext->u64Expire <= u64Max)
2221 {
2222 /* Advance */
2223 PTMTIMER pTimer = pNext;
2224 pNext = TMTIMER_GET_NEXT(pTimer);
2225
2226 /* Take the associated lock. */
2227 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2228 if (pCritSect)
2229 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2230
2231 Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
2232 pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
2233
2234 /* Advance the clock - don't permit timers to be out of order or armed
2235 in the 'past'. */
2236#ifdef VBOX_STRICT
2237 AssertMsg(pTimer->u64Expire >= u64Prev, ("%'RU64 < %'RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
2238 u64Prev = pTimer->u64Expire;
2239#endif
2240 ASMAtomicWriteU64(&pVM->tm.s.u64VirtualSync, pTimer->u64Expire);
2241 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, false);
2242
2243 /* Unlink it, change the state and do the callout. */
2244 tmTimerQueueUnlinkActive(pQueue, pTimer);
2245 TM_SET_STATE(pTimer, TMTIMERSTATE_EXPIRED_DELIVER);
2246 switch (pTimer->enmType)
2247 {
2248 case TMTIMERTYPE_DEV: pTimer->u.Dev.pfnTimer(pTimer->u.Dev.pDevIns, pTimer, pTimer->pvUser); break;
2249 case TMTIMERTYPE_USB: pTimer->u.Usb.pfnTimer(pTimer->u.Usb.pUsbIns, pTimer, pTimer->pvUser); break;
2250 case TMTIMERTYPE_DRV: pTimer->u.Drv.pfnTimer(pTimer->u.Drv.pDrvIns, pTimer, pTimer->pvUser); break;
2251 case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->pvUser); break;
2252 case TMTIMERTYPE_EXTERNAL: pTimer->u.External.pfnTimer(pTimer->pvUser); break;
2253 default:
2254 AssertMsgFailed(("Invalid timer type %d (%s)\n", pTimer->enmType, pTimer->pszDesc));
2255 break;
2256 }
2257
2258 /* Change the state if it wasn't changed already in the handler.
2259 Reset the Hz hint too since this is the same as TMTimerStop. */
2260 bool fRc;
2261 TM_TRY_SET_STATE(pTimer, TMTIMERSTATE_STOPPED, TMTIMERSTATE_EXPIRED_DELIVER, fRc);
2262 if (fRc && pTimer->uHzHint)
2263 {
2264 if (pTimer->uHzHint >= pVM->tm.s.uMaxHzHint)
2265 ASMAtomicWriteBool(&pVM->tm.s.fHzHintNeedsUpdating, true);
2266 pTimer->uHzHint = 0;
2267 }
2268 Log2(("tmR3TimerQueueRun: new state %s\n", tmTimerState(pTimer->enmState)));
2269
2270 /* Leave the associated lock. */
2271 if (pCritSect)
2272 PDMCritSectLeave(pCritSect);
2273 } /* run loop */
2274
2275
2276 /*
2277 * Restart the clock if it was stopped to serve any timers,
2278 * and start/adjust catch-up if necessary.
2279 */
2280 if ( !pVM->tm.s.fVirtualSyncTicking
2281 && pVM->tm.s.cVirtualTicking)
2282 {
2283 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncRunRestart);
2284
2285 /* calc the slack we've handed out. */
2286 const uint64_t u64VirtualNow2 = TMVirtualGetNoCheck(pVM);
2287 Assert(u64VirtualNow2 >= u64VirtualNow);
2288 AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%'RU64 < %'RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
2289 const uint64_t offSlack = pVM->tm.s.u64VirtualSync - u64Now;
2290 STAM_STATS({
2291 if (offSlack)
2292 {
2293 PSTAMPROFILE p = &pVM->tm.s.StatVirtualSyncRunSlack;
2294 p->cPeriods++;
2295 p->cTicks += offSlack;
2296 if (p->cTicksMax < offSlack) p->cTicksMax = offSlack;
2297 if (p->cTicksMin > offSlack) p->cTicksMin = offSlack;
2298 }
2299 });
2300
2301 /* Let the time run a little bit while we were busy running timers(?). */
2302 uint64_t u64Elapsed;
2303#define MAX_ELAPSED 30000U /* ns */
2304 if (offSlack > MAX_ELAPSED)
2305 u64Elapsed = 0;
2306 else
2307 {
2308 u64Elapsed = u64VirtualNow2 - u64VirtualNow;
2309 if (u64Elapsed > MAX_ELAPSED)
2310 u64Elapsed = MAX_ELAPSED;
2311 u64Elapsed = u64Elapsed > offSlack ? u64Elapsed - offSlack : 0;
2312 }
2313#undef MAX_ELAPSED
2314
2315 /* Calc the current offset. */
2316 uint64_t offNew = u64VirtualNow2 - pVM->tm.s.u64VirtualSync - u64Elapsed;
2317 Assert(!(offNew & RT_BIT_64(63)));
2318 uint64_t offLag = offNew - pVM->tm.s.offVirtualSyncGivenUp;
2319 Assert(!(offLag & RT_BIT_64(63)));
2320
2321 /*
2322 * Deal with starting, adjusting and stopping catchup.
2323 */
2324 if (pVM->tm.s.fVirtualSyncCatchUp)
2325 {
2326 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpStopThreshold)
2327 {
2328 /* stop */
2329 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2330 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2331 Log4(("TM: %'RU64/-%'8RU64: caught up [pt]\n", u64VirtualNow2 - offNew, offLag));
2332 }
2333 else if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2334 {
2335 /* adjust */
2336 unsigned i = 0;
2337 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2338 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2339 i++;
2340 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
2341 {
2342 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupAdjust[i]);
2343 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2344 Log4(("TM: %'RU64/%'8RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2345 }
2346 pVM->tm.s.u64VirtualSyncCatchUpPrev = u64VirtualNow2;
2347 }
2348 else
2349 {
2350 /* give up */
2351 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUp);
2352 STAM_PROFILE_ADV_STOP(&pVM->tm.s.StatVirtualSyncCatchup, c);
2353 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2354 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, false);
2355 Log4(("TM: %'RU64/%'8RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2356 LogRel(("TM: Giving up catch-up attempt at a %'RU64 ns lag; new total: %'RU64 ns\n", offLag, offNew));
2357 }
2358 }
2359 else if (offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[0].u64Start)
2360 {
2361 if (offLag <= pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold)
2362 {
2363 /* start */
2364 STAM_PROFILE_ADV_START(&pVM->tm.s.StatVirtualSyncCatchup, c);
2365 unsigned i = 0;
2366 while ( i + 1 < RT_ELEMENTS(pVM->tm.s.aVirtualSyncCatchUpPeriods)
2367 && offLag >= pVM->tm.s.aVirtualSyncCatchUpPeriods[i + 1].u64Start)
2368 i++;
2369 STAM_COUNTER_INC(&pVM->tm.s.aStatVirtualSyncCatchupInitial[i]);
2370 ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
2371 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncCatchUp, true);
2372 Log4(("TM: %'RU64/%'8RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
2373 }
2374 else
2375 {
2376 /* don't bother */
2377 STAM_COUNTER_INC(&pVM->tm.s.StatVirtualSyncGiveUpBeforeStarting);
2378 ASMAtomicWriteU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp, offNew);
2379 Log4(("TM: %'RU64/%'8RU64: give up\n", u64VirtualNow2 - offNew, offLag));
2380 LogRel(("TM: Not bothering to attempt catching up a %'RU64 ns lag; new total: %'RU64\n", offLag, offNew));
2381 }
2382 }
2383
2384 /*
2385 * Update the offset and restart the clock.
2386 */
2387 Assert(!(offNew & RT_BIT_64(63)));
2388 ASMAtomicWriteU64(&pVM->tm.s.offVirtualSync, offNew);
2389 ASMAtomicWriteBool(&pVM->tm.s.fVirtualSyncTicking, true);
2390 }
2391}
2392
2393
2394/**
2395 * Deals with stopped Virtual Sync clock.
2396 *
2397 * This is called by the forced action flag handling code in EM when it
2398 * encounters the VM_FF_TM_VIRTUAL_SYNC flag. It is called by all VCPUs and they
2399 * will block on the VirtualSyncLock until the pending timers has been executed
2400 * and the clock restarted.
2401 *
2402 * @param pVM The VM to run the timers for.
2403 * @param pVCpu The virtual CPU we're running at.
2404 *
2405 * @thread EMTs
2406 */
2407VMMR3_INT_DECL(void) TMR3VirtualSyncFF(PVM pVM, PVMCPU pVCpu)
2408{
2409 Log2(("TMR3VirtualSyncFF:\n"));
2410
2411 /*
2412 * The EMT doing the timers is diverted to them.
2413 */
2414 if (pVCpu->idCpu == pVM->tm.s.idTimerCpu)
2415 TMR3TimerQueuesDo(pVM);
2416 /*
2417 * The other EMTs will block on the virtual sync lock and the first owner
2418 * will run the queue and thus restarting the clock.
2419 *
2420 * Note! This is very suboptimal code wrt to resuming execution when there
2421 * are more than two Virtual CPUs, since they will all have to enter
2422 * the critical section one by one. But it's a very simple solution
2423 * which will have to do the job for now.
2424 */
2425 else
2426 {
2427 STAM_PROFILE_START(&pVM->tm.s.StatVirtualSyncFF, a);
2428 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2429 if (pVM->tm.s.fVirtualSyncTicking)
2430 {
2431 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2432 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2433 Log2(("TMR3VirtualSyncFF: ticking\n"));
2434 }
2435 else
2436 {
2437 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2438
2439 /* try run it. */
2440 TM_LOCK_TIMERS(pVM);
2441 PDMCritSectEnter(&pVM->tm.s.VirtualSyncLock, VERR_IGNORED);
2442 if (pVM->tm.s.fVirtualSyncTicking)
2443 Log2(("TMR3VirtualSyncFF: ticking (2)\n"));
2444 else
2445 {
2446 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, true);
2447 Log2(("TMR3VirtualSyncFF: running queue\n"));
2448
2449 Assert(!pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule);
2450 tmR3TimerQueueRunVirtualSync(pVM);
2451 if (pVM->tm.s.fVirtualSyncTicking) /** @todo move into tmR3TimerQueueRunVirtualSync - FIXME */
2452 VM_FF_CLEAR(pVM, VM_FF_TM_VIRTUAL_SYNC);
2453
2454 ASMAtomicWriteBool(&pVM->tm.s.fRunningVirtualSyncQueue, false);
2455 }
2456 STAM_PROFILE_STOP(&pVM->tm.s.StatVirtualSyncFF, a); /* before the unlock! */
2457 PDMCritSectLeave(&pVM->tm.s.VirtualSyncLock);
2458 TM_UNLOCK_TIMERS(pVM);
2459 }
2460 }
2461}
2462
2463
2464/** @name Saved state values
2465 * @{ */
2466#define TMTIMERSTATE_SAVED_PENDING_STOP 4
2467#define TMTIMERSTATE_SAVED_PENDING_SCHEDULE 7
2468/** @} */
2469
2470
2471/**
2472 * Saves the state of a timer to a saved state.
2473 *
2474 * @returns VBox status.
2475 * @param pTimer Timer to save.
2476 * @param pSSM Save State Manager handle.
2477 */
2478VMMR3DECL(int) TMR3TimerSave(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2479{
2480 LogFlow(("TMR3TimerSave: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2481 switch (pTimer->enmState)
2482 {
2483 case TMTIMERSTATE_STOPPED:
2484 case TMTIMERSTATE_PENDING_STOP:
2485 case TMTIMERSTATE_PENDING_STOP_SCHEDULE:
2486 return SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_STOP);
2487
2488 case TMTIMERSTATE_PENDING_SCHEDULE_SET_EXPIRE:
2489 case TMTIMERSTATE_PENDING_RESCHEDULE_SET_EXPIRE:
2490 AssertMsgFailed(("u64Expire is being updated! (%s)\n", pTimer->pszDesc));
2491 if (!RTThreadYield())
2492 RTThreadSleep(1);
2493 /* fall thru */
2494 case TMTIMERSTATE_ACTIVE:
2495 case TMTIMERSTATE_PENDING_SCHEDULE:
2496 case TMTIMERSTATE_PENDING_RESCHEDULE:
2497 SSMR3PutU8(pSSM, TMTIMERSTATE_SAVED_PENDING_SCHEDULE);
2498 return SSMR3PutU64(pSSM, pTimer->u64Expire);
2499
2500 case TMTIMERSTATE_EXPIRED_GET_UNLINK:
2501 case TMTIMERSTATE_EXPIRED_DELIVER:
2502 case TMTIMERSTATE_DESTROY:
2503 case TMTIMERSTATE_FREE:
2504 AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
2505 return SSMR3HandleSetStatus(pSSM, VERR_TM_INVALID_STATE);
2506 }
2507
2508 AssertMsgFailed(("Unknown timer state %d (%s)\n", pTimer->enmState, pTimer->pszDesc));
2509 return SSMR3HandleSetStatus(pSSM, VERR_TM_UNKNOWN_STATE);
2510}
2511
2512
2513/**
2514 * Loads the state of a timer from a saved state.
2515 *
2516 * @returns VBox status.
2517 * @param pTimer Timer to restore.
2518 * @param pSSM Save State Manager handle.
2519 */
2520VMMR3DECL(int) TMR3TimerLoad(PTMTIMERR3 pTimer, PSSMHANDLE pSSM)
2521{
2522 Assert(pTimer); Assert(pSSM); VM_ASSERT_EMT(pTimer->pVMR3);
2523 LogFlow(("TMR3TimerLoad: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
2524
2525 /*
2526 * Load the state and validate it.
2527 */
2528 uint8_t u8State;
2529 int rc = SSMR3GetU8(pSSM, &u8State);
2530 if (RT_FAILURE(rc))
2531 return rc;
2532#if 1 /* Workaround for accidental state shift in r47786 (2009-05-26 19:12:12). */ /** @todo remove this in a few weeks! */
2533 if ( u8State == TMTIMERSTATE_SAVED_PENDING_STOP + 1
2534 || u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE + 1)
2535 u8State--;
2536#endif
2537 if ( u8State != TMTIMERSTATE_SAVED_PENDING_STOP
2538 && u8State != TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2539 {
2540 AssertLogRelMsgFailed(("u8State=%d\n", u8State));
2541 return SSMR3HandleSetStatus(pSSM, VERR_TM_LOAD_STATE);
2542 }
2543
2544 /* Enter the critical sections to make TMTimerSet/Stop happy. */
2545 if (pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC)
2546 PDMCritSectEnter(&pTimer->pVMR3->tm.s.VirtualSyncLock, VERR_IGNORED);
2547 PPDMCRITSECT pCritSect = pTimer->pCritSect;
2548 if (pCritSect)
2549 PDMCritSectEnter(pCritSect, VERR_IGNORED);
2550
2551 if (u8State == TMTIMERSTATE_SAVED_PENDING_SCHEDULE)
2552 {
2553 /*
2554 * Load the expire time.
2555 */
2556 uint64_t u64Expire;
2557 rc = SSMR3GetU64(pSSM, &u64Expire);
2558 if (RT_FAILURE(rc))
2559 return rc;
2560
2561 /*
2562 * Set it.
2563 */
2564 Log(("u8State=%d u64Expire=%llu\n", u8State, u64Expire));
2565 rc = TMTimerSet(pTimer, u64Expire);
2566 }
2567 else
2568 {
2569 /*
2570 * Stop it.
2571 */
2572 Log(("u8State=%d\n", u8State));
2573 rc = TMTimerStop(pTimer);
2574 }
2575
2576 if (pCritSect)
2577 PDMCritSectLeave(pCritSect);
2578 if (pTimer->enmClock == TMCLOCK_VIRTUAL_SYNC)
2579 PDMCritSectLeave(&pTimer->pVMR3->tm.s.VirtualSyncLock);
2580
2581 /*
2582 * On failure set SSM status.
2583 */
2584 if (RT_FAILURE(rc))
2585 rc = SSMR3HandleSetStatus(pSSM, rc);
2586 return rc;
2587}
2588
2589
2590/**
2591 * Associates a critical section with a timer.
2592 *
2593 * The critical section will be entered prior to doing the timer call back, thus
2594 * avoiding potential races between the timer thread and other threads trying to
2595 * stop or adjust the timer expiration while it's being delivered. The timer
2596 * thread will leave the critical section when the timer callback returns.
2597 *
2598 * In strict builds, ownership of the critical section will be asserted by
2599 * TMTimerSet, TMTimerStop, TMTimerGetExpire and TMTimerDestroy (when called at
2600 * runtime).
2601 *
2602 * @retval VINF_SUCCESS on success.
2603 * @retval VERR_INVALID_HANDLE if the timer handle is NULL or invalid
2604 * (asserted).
2605 * @retval VERR_INVALID_PARAMETER if pCritSect is NULL or has an invalid magic
2606 * (asserted).
2607 * @retval VERR_ALREADY_EXISTS if a critical section was already associated
2608 * with the timer (asserted).
2609 * @retval VERR_INVALID_STATE if the timer isn't stopped.
2610 *
2611 * @param pTimer The timer handle.
2612 * @param pCritSect The critical section. The caller must make sure this
2613 * is around for the life time of the timer.
2614 *
2615 * @thread Any, but the caller is responsible for making sure the timer is not
2616 * active.
2617 */
2618VMMR3DECL(int) TMR3TimerSetCritSect(PTMTIMERR3 pTimer, PPDMCRITSECT pCritSect)
2619{
2620 AssertPtrReturn(pTimer, VERR_INVALID_HANDLE);
2621 AssertPtrReturn(pCritSect, VERR_INVALID_PARAMETER);
2622 const char *pszName = PDMR3CritSectName(pCritSect); /* exploited for validation */
2623 AssertReturn(pszName, VERR_INVALID_PARAMETER);
2624 AssertReturn(!pTimer->pCritSect, VERR_ALREADY_EXISTS);
2625 AssertReturn(pTimer->enmState == TMTIMERSTATE_STOPPED, VERR_INVALID_STATE);
2626 LogFlow(("pTimer=%p (%s) pCritSect=%p (%s)\n", pTimer, pTimer->pszDesc, pCritSect, pszName));
2627
2628 pTimer->pCritSect = pCritSect;
2629 return VINF_SUCCESS;
2630}
2631
2632
2633/**
2634 * Get the real world UTC time adjusted for VM lag.
2635 *
2636 * @returns pTime.
2637 * @param pVM The VM instance.
2638 * @param pTime Where to store the time.
2639 */
2640VMMR3_INT_DECL(PRTTIMESPEC) TMR3UtcNow(PVM pVM, PRTTIMESPEC pTime)
2641{
2642 /* Get a stable set of VirtualSync parameters before querying UTC. */
2643 uint64_t offVirtualSync;
2644 uint64_t offVirtualSyncGivenUp;
2645 do
2646 {
2647 offVirtualSync = ASMAtomicReadU64(&pVM->tm.s.offVirtualSync);
2648 offVirtualSyncGivenUp = ASMAtomicReadU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp);
2649 } while (ASMAtomicReadU64(&pVM->tm.s.offVirtualSync) != offVirtualSync);
2650
2651 Assert(offVirtualSync >= offVirtualSyncGivenUp);
2652 uint64_t const offLag = offVirtualSync - offVirtualSyncGivenUp;
2653
2654 RTTimeNow(pTime);
2655 RTTimeSpecSubNano(pTime, offLag);
2656 RTTimeSpecAddNano(pTime, pVM->tm.s.offUTC);
2657 return pTime;
2658}
2659
2660
2661/**
2662 * Pauses all clocks except TMCLOCK_REAL.
2663 *
2664 * @returns VBox status code, all errors are asserted.
2665 * @param pVM Pointer to the VM.
2666 * @param pVCpu Pointer to the VMCPU.
2667 * @thread EMT corresponding to Pointer to the VMCPU.
2668 */
2669VMMR3DECL(int) TMR3NotifySuspend(PVM pVM, PVMCPU pVCpu)
2670{
2671 VMCPU_ASSERT_EMT(pVCpu);
2672
2673 /*
2674 * The shared virtual clock (includes virtual sync which is tied to it).
2675 */
2676 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2677 int rc = tmVirtualPauseLocked(pVM);
2678 TM_UNLOCK_TIMERS(pVM);
2679 if (RT_FAILURE(rc))
2680 return rc;
2681
2682 /*
2683 * Pause the TSC last since it is normally linked to the virtual
2684 * sync clock, so the above code may actually stop both clocks.
2685 */
2686 if (!pVM->tm.s.fTSCTiedToExecution)
2687 {
2688#ifdef SYNC_TSC_PAUSE
2689 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2690 rc = tmCpuTickPauseLocked(pVM, pVCpu);
2691 TM_UNLOCK_TIMERS(pVM);
2692#else
2693 rc = tmCpuTickPause(pVCpu);
2694#endif
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#ifdef SYNC_TSC_PAUSE
2742 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2743 rc = tmCpuTickResumeLocked(pVM, pVCpu);
2744 TM_UNLOCK_TIMERS(pVM);
2745#else
2746 rc = tmCpuTickResume(pVM, pVCpu);
2747#endif
2748 if (RT_FAILURE(rc))
2749 return rc;
2750 }
2751
2752 /*
2753 * The shared virtual clock (includes virtual sync which is tied to it).
2754 */
2755 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2756 rc = tmVirtualResumeLocked(pVM);
2757 TM_UNLOCK_TIMERS(pVM);
2758
2759 return rc;
2760}
2761
2762
2763/**
2764 * Sets the warp drive percent of the virtual time.
2765 *
2766 * @returns VBox status code.
2767 * @param pVM Pointer to the VM.
2768 * @param u32Percent The new percentage. 100 means normal operation.
2769 */
2770VMMDECL(int) TMR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent)
2771{
2772 return VMR3ReqPriorityCallWaitU(pUVM, VMCPUID_ANY, (PFNRT)tmR3SetWarpDrive, 2, pUVM, u32Percent);
2773}
2774
2775
2776/**
2777 * EMT worker for TMR3SetWarpDrive.
2778 *
2779 * @returns VBox status code.
2780 * @param pUVM The user mode VM handle.
2781 * @param u32Percent See TMR3SetWarpDrive().
2782 * @internal
2783 */
2784static DECLCALLBACK(int) tmR3SetWarpDrive(PUVM pUVM, uint32_t u32Percent)
2785{
2786 PVM pVM = pUVM->pVM;
2787 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2788 PVMCPU pVCpu = VMMGetCpu(pVM);
2789
2790 /*
2791 * Validate it.
2792 */
2793 AssertMsgReturn(u32Percent >= 2 && u32Percent <= 20000,
2794 ("%RX32 is not between 2 and 20000 (inclusive).\n", u32Percent),
2795 VERR_INVALID_PARAMETER);
2796
2797/** @todo This isn't a feature specific to virtual time, move the variables to
2798 * TM level and make it affect TMR3UTCNow as well! */
2799
2800 /*
2801 * If the time is running we'll have to pause it before we can change
2802 * the warp drive settings.
2803 */
2804 TM_LOCK_TIMERS(pVM); /* Paranoia: Exploiting the timer lock here. */
2805 bool fPaused = !!pVM->tm.s.cVirtualTicking;
2806 if (fPaused) /** @todo this isn't really working, but wtf. */
2807 TMR3NotifySuspend(pVM, pVCpu);
2808
2809 pVM->tm.s.u32VirtualWarpDrivePercentage = u32Percent;
2810 pVM->tm.s.fVirtualWarpDrive = u32Percent != 100;
2811 LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32 fVirtualWarpDrive=%RTbool\n",
2812 pVM->tm.s.u32VirtualWarpDrivePercentage, pVM->tm.s.fVirtualWarpDrive));
2813
2814 if (fPaused)
2815 TMR3NotifyResume(pVM, pVCpu);
2816 TM_UNLOCK_TIMERS(pVM);
2817 return VINF_SUCCESS;
2818}
2819
2820
2821/**
2822 * Gets the current warp drive percent.
2823 *
2824 * @returns The warp drive percent.
2825 * @param pVM Pointer to the VM.
2826 */
2827VMMR3DECL(uint32_t) TMR3GetWarpDrive(PUVM pUVM)
2828{
2829 UVM_ASSERT_VALID_EXT_RETURN(pUVM, UINT32_MAX);
2830 PVM pVM = pUVM->pVM;
2831 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
2832 return pVM->tm.s.u32VirtualWarpDrivePercentage;
2833}
2834
2835
2836/**
2837 * Gets the performance information for one virtual CPU as seen by the VMM.
2838 *
2839 * The returned times covers the period where the VM is running and will be
2840 * reset when restoring a previous VM state (at least for the time being).
2841 *
2842 * @retval VINF_SUCCESS on success.
2843 * @retval VERR_NOT_IMPLEMENTED if not compiled in.
2844 * @retval VERR_INVALID_STATE if the VM handle is bad.
2845 * @retval VERR_INVALID_PARAMETER if idCpu is out of range.
2846 *
2847 * @param pVM Pointer to the VM.
2848 * @param idCpu The ID of the virtual CPU which times to get.
2849 * @param pcNsTotal Where to store the total run time (nano seconds) of
2850 * the CPU, i.e. the sum of the three other returns.
2851 * Optional.
2852 * @param pcNsExecuting Where to store the time (nano seconds) spent
2853 * executing guest code. Optional.
2854 * @param pcNsHalted Where to store the time (nano seconds) spent
2855 * halted. Optional
2856 * @param pcNsOther Where to store the time (nano seconds) spent
2857 * preempted by the host scheduler, on virtualization
2858 * overhead and on other tasks.
2859 */
2860VMMR3DECL(int) TMR3GetCpuLoadTimes(PVM pVM, VMCPUID idCpu, uint64_t *pcNsTotal, uint64_t *pcNsExecuting,
2861 uint64_t *pcNsHalted, uint64_t *pcNsOther)
2862{
2863 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_STATE);
2864 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_PARAMETER);
2865
2866#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2867 /*
2868 * Get a stable result set.
2869 * This should be way quicker than an EMT request.
2870 */
2871 PVMCPU pVCpu = &pVM->aCpus[idCpu];
2872 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2873 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
2874 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
2875 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
2876 uint64_t cNsOther = pVCpu->tm.s.cNsOther;
2877 while ( (uTimesGen & 1) /* update in progress */
2878 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen))
2879 {
2880 RTThreadYield();
2881 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2882 cNsTotal = pVCpu->tm.s.cNsTotal;
2883 cNsExecuting = pVCpu->tm.s.cNsExecuting;
2884 cNsHalted = pVCpu->tm.s.cNsHalted;
2885 cNsOther = pVCpu->tm.s.cNsOther;
2886 }
2887
2888 /*
2889 * Fill in the return values.
2890 */
2891 if (pcNsTotal)
2892 *pcNsTotal = cNsTotal;
2893 if (pcNsExecuting)
2894 *pcNsExecuting = cNsExecuting;
2895 if (pcNsHalted)
2896 *pcNsHalted = cNsHalted;
2897 if (pcNsOther)
2898 *pcNsOther = cNsOther;
2899
2900 return VINF_SUCCESS;
2901
2902#else
2903 return VERR_NOT_IMPLEMENTED;
2904#endif
2905}
2906
2907#ifndef VBOX_WITHOUT_NS_ACCOUNTING
2908
2909/**
2910 * Helper for tmR3CpuLoadTimer.
2911 * @returns
2912 * @param pState The state to update.
2913 * @param cNsTotalDelta Total time.
2914 * @param cNsExecutingDelta Time executing.
2915 * @param cNsHaltedDelta Time halted.
2916 */
2917DECLINLINE(void) tmR3CpuLoadTimerMakeUpdate(PTMCPULOADSTATE pState,
2918 uint64_t cNsTotal,
2919 uint64_t cNsExecuting,
2920 uint64_t cNsHalted)
2921{
2922 /* Calc deltas */
2923 uint64_t cNsTotalDelta = cNsTotal - pState->cNsPrevTotal;
2924 pState->cNsPrevTotal = cNsTotal;
2925
2926 uint64_t cNsExecutingDelta = cNsExecuting - pState->cNsPrevExecuting;
2927 pState->cNsPrevExecuting = cNsExecuting;
2928
2929 uint64_t cNsHaltedDelta = cNsHalted - pState->cNsPrevHalted;
2930 pState->cNsPrevHalted = cNsHalted;
2931
2932 /* Calc pcts. */
2933 if (!cNsTotalDelta)
2934 {
2935 pState->cPctExecuting = 0;
2936 pState->cPctHalted = 100;
2937 pState->cPctOther = 0;
2938 }
2939 else if (cNsTotalDelta < UINT64_MAX / 4)
2940 {
2941 pState->cPctExecuting = (uint8_t)(cNsExecutingDelta * 100 / cNsTotalDelta);
2942 pState->cPctHalted = (uint8_t)(cNsHaltedDelta * 100 / cNsTotalDelta);
2943 pState->cPctOther = (uint8_t)((cNsTotalDelta - cNsExecutingDelta - cNsHaltedDelta) * 100 / cNsTotalDelta);
2944 }
2945 else
2946 {
2947 pState->cPctExecuting = 0;
2948 pState->cPctHalted = 100;
2949 pState->cPctOther = 0;
2950 }
2951}
2952
2953
2954/**
2955 * Timer callback that calculates the CPU load since the last time it was
2956 * called.
2957 *
2958 * @param pVM Pointer to the VM.
2959 * @param pTimer The timer.
2960 * @param pvUser NULL, unused.
2961 */
2962static DECLCALLBACK(void) tmR3CpuLoadTimer(PVM pVM, PTMTIMER pTimer, void *pvUser)
2963{
2964 /*
2965 * Re-arm the timer first.
2966 */
2967 int rc = TMTimerSetMillies(pTimer, 1000);
2968 AssertLogRelRC(rc);
2969 NOREF(pvUser);
2970
2971 /*
2972 * Update the values for each CPU.
2973 */
2974 uint64_t cNsTotalAll = 0;
2975 uint64_t cNsExecutingAll = 0;
2976 uint64_t cNsHaltedAll = 0;
2977 for (VMCPUID iCpu = 0; iCpu < pVM->cCpus; iCpu++)
2978 {
2979 PVMCPU pVCpu = &pVM->aCpus[iCpu];
2980
2981 /* Try get a stable data set. */
2982 uint32_t cTries = 3;
2983 uint32_t uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2984 uint64_t cNsTotal = pVCpu->tm.s.cNsTotal;
2985 uint64_t cNsExecuting = pVCpu->tm.s.cNsExecuting;
2986 uint64_t cNsHalted = pVCpu->tm.s.cNsHalted;
2987 while (RT_UNLIKELY( (uTimesGen & 1) /* update in progress */
2988 || uTimesGen != ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen)))
2989 {
2990 if (!--cTries)
2991 break;
2992 ASMNopPause();
2993 uTimesGen = ASMAtomicReadU32(&pVCpu->tm.s.uTimesGen);
2994 cNsTotal = pVCpu->tm.s.cNsTotal;
2995 cNsExecuting = pVCpu->tm.s.cNsExecuting;
2996 cNsHalted = pVCpu->tm.s.cNsHalted;
2997 }
2998
2999 /* Totals */
3000 cNsTotalAll += cNsTotal;
3001 cNsExecutingAll += cNsExecuting;
3002 cNsHaltedAll += cNsHalted;
3003
3004 /* Calc the PCTs and update the state. */
3005 tmR3CpuLoadTimerMakeUpdate(&pVCpu->tm.s.CpuLoad, cNsTotal, cNsExecuting, cNsHalted);
3006 }
3007
3008 /*
3009 * Update the value for all the CPUs.
3010 */
3011 tmR3CpuLoadTimerMakeUpdate(&pVM->tm.s.CpuLoad, cNsTotalAll, cNsExecutingAll, cNsHaltedAll);
3012
3013 /** @todo Try add 1, 5 and 15 min load stats. */
3014
3015}
3016
3017#endif /* !VBOX_WITHOUT_NS_ACCOUNTING */
3018
3019/**
3020 * Gets the 5 char clock name for the info tables.
3021 *
3022 * @returns The name.
3023 * @param enmClock The clock.
3024 */
3025DECLINLINE(const char *) tmR3Get5CharClockName(TMCLOCK enmClock)
3026{
3027 switch (enmClock)
3028 {
3029 case TMCLOCK_REAL: return "Real ";
3030 case TMCLOCK_VIRTUAL: return "Virt ";
3031 case TMCLOCK_VIRTUAL_SYNC: return "VrSy ";
3032 case TMCLOCK_TSC: return "TSC ";
3033 default: return "Bad ";
3034 }
3035}
3036
3037
3038/**
3039 * Display all timers.
3040 *
3041 * @param pVM Pointer to the VM.
3042 * @param pHlp The info helpers.
3043 * @param pszArgs Arguments, ignored.
3044 */
3045static DECLCALLBACK(void) tmR3TimerInfo(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3046{
3047 NOREF(pszArgs);
3048 pHlp->pfnPrintf(pHlp,
3049 "Timers (pVM=%p)\n"
3050 "%.*s %.*s %.*s %.*s Clock %18s %18s %6s %-25s Description\n",
3051 pVM,
3052 sizeof(RTR3PTR) * 2, "pTimerR3 ",
3053 sizeof(int32_t) * 2, "offNext ",
3054 sizeof(int32_t) * 2, "offPrev ",
3055 sizeof(int32_t) * 2, "offSched ",
3056 "Time",
3057 "Expire",
3058 "HzHint",
3059 "State");
3060 TM_LOCK_TIMERS(pVM);
3061 for (PTMTIMERR3 pTimer = pVM->tm.s.pCreated; pTimer; pTimer = pTimer->pBigNext)
3062 {
3063 pHlp->pfnPrintf(pHlp,
3064 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %6RU32 %-25s %s\n",
3065 pTimer,
3066 pTimer->offNext,
3067 pTimer->offPrev,
3068 pTimer->offScheduleNext,
3069 tmR3Get5CharClockName(pTimer->enmClock),
3070 TMTimerGet(pTimer),
3071 pTimer->u64Expire,
3072 pTimer->uHzHint,
3073 tmTimerState(pTimer->enmState),
3074 pTimer->pszDesc);
3075 }
3076 TM_UNLOCK_TIMERS(pVM);
3077}
3078
3079
3080/**
3081 * Display all active timers.
3082 *
3083 * @param pVM Pointer to the VM.
3084 * @param pHlp The info helpers.
3085 * @param pszArgs Arguments, ignored.
3086 */
3087static DECLCALLBACK(void) tmR3TimerInfoActive(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3088{
3089 NOREF(pszArgs);
3090 pHlp->pfnPrintf(pHlp,
3091 "Active Timers (pVM=%p)\n"
3092 "%.*s %.*s %.*s %.*s Clock %18s %18s %6s %-25s Description\n",
3093 pVM,
3094 sizeof(RTR3PTR) * 2, "pTimerR3 ",
3095 sizeof(int32_t) * 2, "offNext ",
3096 sizeof(int32_t) * 2, "offPrev ",
3097 sizeof(int32_t) * 2, "offSched ",
3098 "Time",
3099 "Expire",
3100 "HzHint",
3101 "State");
3102 for (unsigned iQueue = 0; iQueue < TMCLOCK_MAX; iQueue++)
3103 {
3104 TM_LOCK_TIMERS(pVM);
3105 for (PTMTIMERR3 pTimer = TMTIMER_GET_HEAD(&pVM->tm.s.paTimerQueuesR3[iQueue]);
3106 pTimer;
3107 pTimer = TMTIMER_GET_NEXT(pTimer))
3108 {
3109 pHlp->pfnPrintf(pHlp,
3110 "%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %6RU32 %-25s %s\n",
3111 pTimer,
3112 pTimer->offNext,
3113 pTimer->offPrev,
3114 pTimer->offScheduleNext,
3115 tmR3Get5CharClockName(pTimer->enmClock),
3116 TMTimerGet(pTimer),
3117 pTimer->u64Expire,
3118 pTimer->uHzHint,
3119 tmTimerState(pTimer->enmState),
3120 pTimer->pszDesc);
3121 }
3122 TM_UNLOCK_TIMERS(pVM);
3123 }
3124}
3125
3126
3127/**
3128 * Display all clocks.
3129 *
3130 * @param pVM Pointer to the VM.
3131 * @param pHlp The info helpers.
3132 * @param pszArgs Arguments, ignored.
3133 */
3134static DECLCALLBACK(void) tmR3InfoClocks(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
3135{
3136 NOREF(pszArgs);
3137
3138 /*
3139 * Read the times first to avoid more than necessary time variation.
3140 */
3141 const uint64_t u64Virtual = TMVirtualGet(pVM);
3142 const uint64_t u64VirtualSync = TMVirtualSyncGet(pVM);
3143 const uint64_t u64Real = TMRealGet(pVM);
3144
3145 for (VMCPUID i = 0; i < pVM->cCpus; i++)
3146 {
3147 PVMCPU pVCpu = &pVM->aCpus[i];
3148 uint64_t u64TSC = TMCpuTickGet(pVCpu);
3149
3150 /*
3151 * TSC
3152 */
3153 pHlp->pfnPrintf(pHlp,
3154 "Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
3155 u64TSC, u64TSC, TMCpuTicksPerSecond(pVM),
3156 pVCpu->tm.s.fTSCTicking ? "ticking" : "paused",
3157 pVM->tm.s.fTSCVirtualized ? " - virtualized" : "");
3158 if (pVM->tm.s.fTSCUseRealTSC)
3159 {
3160 pHlp->pfnPrintf(pHlp, " - real tsc");
3161 if (pVCpu->tm.s.offTSCRawSrc)
3162 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVCpu->tm.s.offTSCRawSrc);
3163 }
3164 else
3165 pHlp->pfnPrintf(pHlp, " - virtual clock");
3166 pHlp->pfnPrintf(pHlp, "\n");
3167 }
3168
3169 /*
3170 * virtual
3171 */
3172 pHlp->pfnPrintf(pHlp,
3173 " Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
3174 u64Virtual, u64Virtual, TMVirtualGetFreq(pVM),
3175 pVM->tm.s.cVirtualTicking ? "ticking" : "paused");
3176 if (pVM->tm.s.fVirtualWarpDrive)
3177 pHlp->pfnPrintf(pHlp, " WarpDrive %RU32 %%", pVM->tm.s.u32VirtualWarpDrivePercentage);
3178 pHlp->pfnPrintf(pHlp, "\n");
3179
3180 /*
3181 * virtual sync
3182 */
3183 pHlp->pfnPrintf(pHlp,
3184 "VirtSync: %18RU64 (%#016RX64) %s%s",
3185 u64VirtualSync, u64VirtualSync,
3186 pVM->tm.s.fVirtualSyncTicking ? "ticking" : "paused",
3187 pVM->tm.s.fVirtualSyncCatchUp ? " - catchup" : "");
3188 if (pVM->tm.s.offVirtualSync)
3189 {
3190 pHlp->pfnPrintf(pHlp, "\n offset %RU64", pVM->tm.s.offVirtualSync);
3191 if (pVM->tm.s.u32VirtualSyncCatchUpPercentage)
3192 pHlp->pfnPrintf(pHlp, " catch-up rate %u %%", pVM->tm.s.u32VirtualSyncCatchUpPercentage);
3193 }
3194 pHlp->pfnPrintf(pHlp, "\n");
3195
3196 /*
3197 * real
3198 */
3199 pHlp->pfnPrintf(pHlp,
3200 " Real: %18RU64 (%#016RX64) %RU64Hz\n",
3201 u64Real, u64Real, TMRealGetFreq(pVM));
3202}
3203
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use