VirtualBox

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

Last change on this file since 44410 was 44346, checked in by vboxsync, 12 years ago

TM: PVM -> PUVM in two APIs used by Main. VMReq: Validate pUVM properly for external acalls as well.

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