VirtualBox

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

Last change on this file since 37324 was 37324, checked in by vboxsync, 14 years ago

TM,Devices: Fixed default critical section screwup and adjusted its usage in the devices.

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