VirtualBox

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

Last change on this file since 82255 was 81153, checked in by vboxsync, 5 years ago

VMM: Removed most VBOX_WITH_REM preprocessor stuff. bugref:9576

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

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