VirtualBox

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

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

VMM/TM,SUP: Made it thru TM init in driverless mode... bugref:10138

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