VirtualBox

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

Last change on this file since 72522 was 72522, checked in by vboxsync, 6 years ago

NEM,TM: Work on TSC and NEM/win. bugref:9044 [=>office]

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

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