VirtualBox

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

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

TMR3UtcNow: Get stable offVirtualSync and offVirtualSyncGivenUp values.

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