VirtualBox

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

Last change on this file since 37414 was 37414, checked in by vboxsync, 13 years ago

TM: Added TMTimerLock, TMTimerUnlock and TMTimerIsLockOwner for locking the virtual sync clock to avoid races.

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