VirtualBox

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

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

VMM/*: Eliminated MMHyperR3ToRC, TMR3GetImportRC and few other things. bugref:9517

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

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