VirtualBox

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

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

GVMMR0,TM,STAM: Periodic preemption timer fixes, adjustments and statistics. (still disabled)

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

© 2023 Oracle
ContactPrivacy policyTerms of Use