VirtualBox

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

Last change on this file since 54308 was 54308, checked in by vboxsync, 10 years ago

VMM,SUP: Apply the tsc delta where it matters. Made sense out of the paravirt-tsc-mode enable/disable code.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette