VirtualBox

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

Last change on this file since 91999 was 91988, checked in by vboxsync, 3 years ago

VMM/TM: Fixed race while switching TSC modes.

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