VirtualBox

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

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

Doxygen, comment typos.

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