VirtualBox

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

Last change on this file since 45530 was 45436, checked in by vboxsync, 11 years ago

VMM/TM.cpp: disable TSC offsetting for SMP VMs as a workaround for the problem that TSC can go backwards when mixing offsetting and taking RDTSC exits between VCPUs

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

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