VirtualBox

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

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

VMM: More arm64 adjustments. bugref:9898

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

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