VirtualBox

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

最後變更 在這個檔案從87773是 87773,由 vboxsync 提交於 4 年 前

VMM/TM,Devices: Store the timer name in the TMTIMER structure and limit it to 31 characters. Shortened most timer names. bugref:9943

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

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