TM.cpp revision da10da4742b1663ebb84280ff1b00e37cd41127f
/* $Id$ */
/** @file
* TM - Time Manager.
*/
/*
* Copyright (C) 2006-2007 Sun Microsystems, Inc.
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
/** @page pg_tm TM - The Time Manager
*
* The Time Manager abstracts the CPU clocks and manages timers used by the VMM,
* device and drivers.
*
* @see grp_tm
*
*
* @section sec_tm_clocks Clocks
*
* There are currently 4 clocks:
* - Virtual (guest).
* - Synchronous virtual (guest).
* - CPU Tick (TSC) (guest). Only current use is rdtsc emulation. Usually a
* function of the virtual clock.
* - Real (host). This is only used for display updates atm.
*
* The most important clocks are the three first ones and of these the second is
* the most interesting.
*
*
* The synchronous virtual clock is tied to the virtual clock except that it
* will take into account timer delivery lag caused by host scheduling. It will
* normally never advance beyond the head timer, and when lagging too far behind
* it will gradually speed up to catch up with the virtual clock. All devices
* implementing time sources accessible to and used by the guest is using this
* clock (for timers and other things). This ensures consistency between the
* time sources.
*
* The virtual clock is implemented as an offset to a monotonic, high
* resolution, wall clock. The current time source is using the RTTimeNanoTS()
* machinery based upon the Global Info Pages (GIP), that is, we're using TSC
* deltas (usually 10 ms) to fill the gaps between GIP updates. The result is
* a fairly high res clock that works in all contexts and on all hosts. The
* virtual clock is paused when the VM isn't in the running state.
*
* The CPU tick (TSC) is normally virtualized as a function of the synchronous
* virtual clock, where the frequency defaults to the host cpu frequency (as we
* measure it). In this mode it is possible to configure the frequency. Another
* (non-default) option is to use the raw unmodified host TSC values. And yet
* another, to tie it to time spent executing guest code. All these things are
* configurable should non-default behavior be desirable.
*
* The real clock is a monotonic clock (when available) with relatively low
* resolution, though this a bit host specific. Note that we're currently not
* servicing timers using the real clock when the VM is not running, this is
* simply because it has not been needed yet therefore not implemented.
*
*
* @subsection subsec_tm_timesync Guest Time Sync / UTC time
*
* Guest time syncing is primarily taken care of by the VMM device. The
* principle is very simple, the guest additions periodically asks the VMM
* device what the current UTC time is and makes adjustments accordingly.
*
* A complicating factor is that the synchronous virtual clock might be doing
* catchups and the guest perception is currently a little bit behind the world
* but it will (hopefully) be catching up soon as we're feeding timer interrupts
* at a slightly higher rate. Adjusting the guest clock to the current wall
* time in the real world would be a bad idea then because the guest will be
* advancing too fast and run ahead of world time (if the catchup works out).
* To solve this problem TM provides the VMM device with an UTC time source that
* gets adjusted with the current lag, so that when the guest eventually catches
* up the lag it will be showing correct real world time.
*
*
* @section sec_tm_timers Timers
*
* The timers can use any of the TM clocks described in the previous section.
* Each clock has its own scheduling facility, or timer queue if you like.
* There are a few factors which makes it a bit complex. First, there is the
* usual R0 vs R3 vs. RC thing. Then there are multiple threads, and then there
* is the timer thread that periodically checks whether any timers has expired
* without EMT noticing. On the API level, all but the create and save APIs
* must be mulithreaded. EMT will always run the timers.
*
* The design is using a doubly linked list of active timers which is ordered
* by expire date. This list is only modified by the EMT thread. Updates to
* the list are batched in a singly linked list, which is then processed by the
* EMT thread at the first opportunity (immediately, next time EMT modifies a
* timer on that clock, or next timer timeout). Both lists are offset based and
* all the elements are therefore allocated from the hyper heap.
*
* For figuring out when there is need to schedule and run timers TM will:
* - Poll whenever somebody queries the virtual clock.
* - Poll the virtual clocks from the EM and REM loops.
* - Poll the virtual clocks from trap exit path.
* - Poll the virtual clocks and calculate first timeout from the halt loop.
* - Employ a thread which periodically (100Hz) polls all the timer queues.
*
*
* @image html TMTIMER-Statechart-Diagram.gif
*
* @section sec_tm_timer Logging
*
* Level 2: Logs a most of the timer state transitions and queue servicing.
* Level 3: Logs a few oddments.
* Level 4: Logs TMCLOCK_VIRTUAL_SYNC catch-up events.
*
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_TM
#include "TMInternal.h"
#include <iprt/semaphore.h>
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** The current saved state version.*/
#define TM_SAVED_STATE_VERSION 3
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
/**
* Initializes the TM.
*
* @returns VBox status code.
* @param pVM The VM to operate on.
*/
{
LogFlow(("TMR3Init:\n"));
/*
* Assert alignment and sizes.
*/
/*
* Init the structure.
*/
void *pv;
/*
* We directly use the GIP to calculate the virtual time. We map the
* the GIP into the guest context so we can do this calculation there
* as well and save costly world switches.
*/
if (RT_FAILURE(rc))
{
return rc;
}
/* Check assumptions made in TMAllVirtual.cpp about the GIP update interval. */
N_("The GIP update interval is too big. u32UpdateIntervalNS=%RU32 (u32UpdateHz=%RU32)"),
/*
* Setup the VirtualGetRaw backend.
*/
{
else
}
else
{
else
}
/* The rest is done in TMR3InitFinalize since it's too early to call PDM. */
/*
* Init the locks.
*/
if (RT_FAILURE(rc))
return rc;
if (RT_FAILURE(rc))
return rc;
/*
* Get our CFGM node, create it if necessary.
*/
if (!pCfgHandle)
{
}
/*
* Determin the TSC configuration and frequency.
*/
/* mode */
/** @cfgm{/TM/TSCVirtualized,bool,true}
* Use a virtualize TSC, i.e. trap all TSC access. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
/* source */
/** @cfgm{/TM/UseRealTSC,bool,false}
* Use the real TSC as time source for the TSC instead of the synchronous
* virtual clock (false, default). */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying bool value \"UseRealTSC\""));
/* TSC reliability */
/** @cfgm{/TM/MaybeUseOffsettedHostTSC,bool,detect}
* Whether the CPU has a fixed TSC rate and may be used in offsetted mode with
* default. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
{
{
/* @todo simple case for guest SMP; always emulate RDTSC */
}
else
}
/** @cfgm{TM/TSCTicksPerSecond, uint32_t, Current TSC frequency from GIP}
* The number of TSC ticks per second (i.e. the TSC frequency). This will
* override TSCUseRealTSC, TSCVirtualized and MaybeUseOffsettedHostTSC.
*/
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
{
{
}
}
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying uint64_t value \"TSCTicksPerSecond\""));
N_("Configuration error: \"TSCTicksPerSecond\" = %RI64 is not in the range 1MHz..4GHz-1"),
else
{
}
/** @cfgm{TM/TSCTiedToExecution, bool, false}
* Whether the TSC should be tied to execution. This will exclude most of the
* virtualization overhead, but will by default include the time spent in the
* halt state (see TM/TSCNotTiedToHalt). This setting will override all other
* TSC settings except for TSCTicksPerSecond and TSCNotTiedToHalt, which should
* be used avoided or used with great care. Note that this will only work right
* together with VT-x or AMD-V, and with a single virtual CPU. */
if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying bool value \"TSCTiedToExecution\""));
{
/* tied to execution, override all other settings. */
}
/** @cfgm{TM/TSCNotTiedToHalt, bool, true}
* For overriding the default of TM/TSCTiedToExecution, i.e. set this to false
* to make the TSC freeze during HLT. */
if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying bool value \"TSCNotTiedToHalt\""));
/* setup and report */
else
LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool\n"
"TM: fMaybeUseOffsettedHostTSC=%RTbool TSCTiedToExecution=%RTbool TSCNotTiedToHalt=%RTbool\n",
pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC,
/*
* Configure the timer synchronous virtual time.
*/
/** @cfgm{TM/ScheduleSlack, uint32_t, ns, 0, UINT32_MAX, 100000}
* Scheduling slack when processing timers. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying 32-bit integer value \"ScheduleSlack\""));
/** @cfgm{TM/CatchUpStopThreshold, uint64_t, ns, 0, UINT64_MAX, 500000}
* When to stop a catch-up, considering it successful. */
rc = CFGMR3QueryU64(pCfgHandle, "CatchUpStopThreshold", &pVM->tm.s.u64VirtualSyncCatchUpStopThreshold);
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpStopThreshold\""));
/** @cfgm{TM/CatchUpGiveUpThreshold, uint64_t, ns, 0, UINT64_MAX, 60000000000}
* When to give up a catch-up attempt. */
rc = CFGMR3QueryU64(pCfgHandle, "CatchUpGiveUpThreshold", &pVM->tm.s.u64VirtualSyncCatchUpGiveUpThreshold);
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpGiveUpThreshold\""));
/** @cfgm{TM/CatchUpPrecentage[0..9], uint32_t, %, 1, 2000, various}
* The catch-up percent for a given period. */
/** @cfgm{TM/CatchUpStartThreshold[0..9], uint64_t, ns, 0, UINT64_MAX,
* The catch-up period threshold, or if you like, when a period starts. */
do \
{ \
if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
else if (RT_FAILURE(rc)) \
return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 64-bit integer value \"CatchUpThreshold" #iPeriod "\"")); \
return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Configuration error: Invalid start of period #" #iPeriod ": %RU64"), u64); \
rc = CFGMR3QueryU32(pCfgHandle, "CatchUpPrecentage" #iPeriod, &pVM->tm.s.aVirtualSyncCatchUpPeriods[iPeriod].u32Percentage); \
if (rc == VERR_CFGM_VALUE_NOT_FOUND) \
else if (RT_FAILURE(rc)) \
return VMSetError(pVM, rc, RT_SRC_POS, N_("Configuration error: Failed to querying 32-bit integer value \"CatchUpPrecentage" #iPeriod "\"")); \
} while (0)
/* This needs more tuning. Not sure if we really need so many period and be so gentle. */
/*
* Configure real world time (UTC).
*/
* The UTC offset. This is used to put the guest back or forwards in time. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying 64-bit integer value \"UTCOffset\""));
/*
* Setup the warp drive.
*/
/** @cfgm{TM/WarpDrivePercentage, uint32_t, %, 0, 20000, 100}
* The warp drive percentage, 100% is normal speed. This is used to speed up
* or slow down the virtual clock, which can be useful for fast forwarding
* borring periods during tests. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "WarpDrivePercentage", &pVM->tm.s.u32VirtualWarpDrivePercentage); /* legacy */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to querying uint32_t value \"WarpDrivePercent\""));
N_("Configuration error: \"WarpDrivePercent\" = %RI32 is not in the range 2..20000"),
/*
* Start the timer (guard against REM not yielding).
*/
/** @cfgm{TM/TimerMillies, uint32_t, ms, 1, 1000, 10}
* The watchdog timer interval. */
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
u32Millies = 10;
else if (RT_FAILURE(rc))
N_("Configuration error: Failed to query uint32_t value \"TimerMillies\""));
if (RT_FAILURE(rc))
{
return rc;
}
/*
* Register saved state.
*/
if (RT_FAILURE(rc))
return rc;
/*
* Register statistics.
*/
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).");
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).");
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).");
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).");
STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.c1nsSteps,STAMTYPE_U32, "/TM/GC/1nsSteps", STAMUNIT_OCCURENCES, "Virtual time 1ns steps (due to TSC / GIP variations).");
STAM_REL_REG_USED(pVM,(void*)&pVM->tm.s.VirtualGetRawDataRC.cBadPrev, STAMTYPE_U32, "/TM/GC/cBadPrev", STAMUNIT_OCCURENCES, "Times the previous virtual time was considered erratic (shouldn't ever happen).");
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)");
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 attemted caught up with.");
#ifdef VBOX_WITH_STATISTICS
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).");
STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR3.cUpdateRaces,STAMTYPE_U32, "/TM/R3/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
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).");
STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataR0.cUpdateRaces,STAMTYPE_U32, "/TM/R0/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cExpired, STAMTYPE_U32, "/TM/GC/cExpired", STAMUNIT_OCCURENCES, "Times the TSC interval expired (overlaps 1ns steps).");
STAM_REG_USED(pVM,(void *)&pVM->tm.s.VirtualGetRawDataRC.cUpdateRaces,STAMTYPE_U32, "/TM/GC/cUpdateRaces", STAMUNIT_OCCURENCES, "Thread races when updating the previous timestamp.");
STAM_REG(pVM, &pVM->tm.s.StatDoQueues, STAMTYPE_PROFILE, "/TM/DoQueues", STAMUNIT_TICKS_PER_CALL, "Profiling timer TMR3TimerQueuesDo.");
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.");
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.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatPoll, STAMTYPE_COUNTER, "/TM/Poll", STAMUNIT_OCCURENCES, "TMTimerPoll calls.");
STAM_REG(pVM, &pVM->tm.s.StatPollAlreadySet, STAMTYPE_COUNTER, "/TM/Poll/AlreadySet", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the FF was already set.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatPollMiss, STAMTYPE_COUNTER, "/TM/Poll/Miss", STAMUNIT_OCCURENCES, "TMTimerPoll calls where nothing had expired.");
STAM_REG(pVM, &pVM->tm.s.StatPollRunning, STAMTYPE_COUNTER, "/TM/Poll/Running", STAMUNIT_OCCURENCES, "TMTimerPoll calls where the queues were being run.");
STAM_REG(pVM, &pVM->tm.s.StatPollSimple, STAMTYPE_COUNTER, "/TM/Poll/Simple", STAMUNIT_OCCURENCES, "TMTimerPoll calls where we could take the simple path.");
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.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatPollGIP, STAMTYPE_COUNTER, "/TM/PollGIP", STAMUNIT_OCCURENCES, "TMTimerPollGIP calls.");
STAM_REG(pVM, &pVM->tm.s.StatPollGIPAlreadySet, STAMTYPE_COUNTER, "/TM/PollGIP/AlreadySet", STAMUNIT_OCCURENCES, "TMTimerPollGIP calls where the FF was already set.");
STAM_REG(pVM, &pVM->tm.s.StatPollGIPVirtual, STAMTYPE_COUNTER, "/TM/PollGIP/HitsVirtual", STAMUNIT_OCCURENCES, "The number of times TMTimerPollGIP found an expired TMCLOCK_VIRTUAL queue.");
STAM_REG(pVM, &pVM->tm.s.StatPollGIPVirtualSync, STAMTYPE_COUNTER, "/TM/PollGIP/HitsVirtualSync", STAMUNIT_OCCURENCES, "The number of times TMTimerPollGIP found an expired TMCLOCK_VIRTUAL_SYNC queue.");
STAM_REG(pVM, &pVM->tm.s.StatPollGIPMiss, STAMTYPE_COUNTER, "/TM/PollGIP/Miss", STAMUNIT_OCCURENCES, "TMTimerPollGIP calls where nothing had expired.");
STAM_REG(pVM, &pVM->tm.s.StatPollGIPRunning, STAMTYPE_COUNTER, "/TM/PollGIP/Running", STAMUNIT_OCCURENCES, "TMTimerPollGIP calls where the queues were being run.");
STAM_REG(pVM, &pVM->tm.s.StatPostponedR3, STAMTYPE_COUNTER, "/TM/PostponedR3", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-3.");
STAM_REG(pVM, &pVM->tm.s.StatPostponedRZ, STAMTYPE_COUNTER, "/TM/PostponedRZ", STAMUNIT_OCCURENCES, "Postponed due to unschedulable state, in ring-0 / RC.");
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.");
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.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatTimerSetR3, STAMTYPE_PROFILE, "/TM/TimerSetR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-3.");
STAM_REG(pVM, &pVM->tm.s.StatTimerSetRZ, STAMTYPE_PROFILE, "/TM/TimerSetRZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerSet calls made in ring-0 / RC.");
STAM_REG(pVM, &pVM->tm.s.StatTimerStopR3, STAMTYPE_PROFILE, "/TM/TimerStopR3", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-3.");
STAM_REG(pVM, &pVM->tm.s.StatTimerStopRZ, STAMTYPE_PROFILE, "/TM/TimerStopRZ", STAMUNIT_TICKS_PER_CALL, "Profiling TMTimerStop calls made in ring-0 / RC.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualGetSetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling TMTimerGet.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGet, STAMTYPE_COUNTER, "/TM/VirtualSyncGet", STAMUNIT_OCCURENCES, "The number of times tmVirtualSyncGetEx was called.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetExpired, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Expired", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx encountered an expired timer stopping the clock.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetLocked, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Locked", STAMUNIT_OCCURENCES, "Times we successfully acquired the lock in tmVirtualSyncGetEx.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetLockless, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/Lockless", STAMUNIT_OCCURENCES, "Times tmVirtualSyncGetEx returned without needing to take the lock.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGetSetFF, STAMTYPE_COUNTER, "/TM/VirtualSyncGet/SetFF", STAMUNIT_OCCURENCES, "Times we set the FF when calling tmVirtualSyncGetEx.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualPause, STAMTYPE_COUNTER, "/TM/VirtualPause", STAMUNIT_OCCURENCES, "The number of times TMR3TimerPause was called.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualResume, STAMTYPE_COUNTER, "/TM/VirtualResume", STAMUNIT_OCCURENCES, "The number of times TMR3TimerResume was called.");
STAM_REG(pVM, &pVM->tm.s.StatTimerCallbackSetFF, STAMTYPE_COUNTER, "/TM/CallbackSetFF", STAMUNIT_OCCURENCES, "The number of times the timer callback set FF.");
STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE010, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE010", STAMUNIT_OCCURENCES, "In catch-up mode, 10% or lower.");
STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE025, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE025", STAMUNIT_OCCURENCES, "In catch-up mode, 25%-11%.");
STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupLE100, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupLE100", STAMUNIT_OCCURENCES, "In catch-up mode, 100%-26%.");
STAM_REG(pVM, &pVM->tm.s.StatTSCCatchupOther, STAMTYPE_COUNTER, "/TM/TSC/Intercept/CatchupOther", STAMUNIT_OCCURENCES, "In catch-up mode, > 100%.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatTSCNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/NotTicking", STAMUNIT_OCCURENCES, "TSC is not ticking.");
STAM_REG(pVM, &pVM->tm.s.StatTSCSyncNotTicking, STAMTYPE_COUNTER, "/TM/TSC/Intercept/SyncNotTicking", STAMUNIT_OCCURENCES, "VirtualSync isn't ticking.");
STAM_REG(pVM, &pVM->tm.s.StatTSCWarp, STAMTYPE_COUNTER, "/TM/TSC/Intercept/Warp", STAMUNIT_OCCURENCES, "Warpdrive is active.");
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.");
STAM_REG(pVM, (void *)&pVM->tm.s.fVirtualSyncCatchUp, STAMTYPE_U8, "/TM/VirtualSync/CatchUpActive", STAMUNIT_NONE, "Catch-Up active indicator.");
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)");
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.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncGiveUp, STAMTYPE_COUNTER, "/TM/VirtualSync/GiveUp", STAMUNIT_OCCURENCES, "Times the catch-up was abandoned.");
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++.)");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRun, STAMTYPE_COUNTER, "/TM/VirtualSync/Run", STAMUNIT_OCCURENCES, "Times the virtual sync timer queue was considered.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunRestart, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/Restarts", STAMUNIT_OCCURENCES, "Times the clock was restarted after a run.");
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.");
STAM_REG(pVM, &pVM->tm.s.StatVirtualSyncRunStoppedAlready, STAMTYPE_COUNTER, "/TM/VirtualSync/Run/StoppedAlready", STAMUNIT_OCCURENCES, "Times the clock was already stopped elsewhere (TMVirtualSyncGet).");
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.)");
{
STAMR3RegisterF(pVM, &pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_PCT, "The catch-up percentage.", "/TM/VirtualSync/Periods/%u", i);
STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupAdjust[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times adjusted to this period.", "/TM/VirtualSync/Periods/%u/Adjust", i);
STAMR3RegisterF(pVM, &pVM->tm.s.aStatVirtualSyncCatchupInitial[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Times started in this period.", "/TM/VirtualSync/Periods/%u/Initial", i);
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);
}
#endif /* VBOX_WITH_STATISTICS */
/*
* Register info handlers.
*/
DBGFR3InfoRegisterInternalEx(pVM, "timers", "Dumps all timers. No arguments.", tmR3TimerInfo, DBGFINFO_FLAGS_RUN_ON_EMT);
DBGFR3InfoRegisterInternalEx(pVM, "activetimers", "Dumps active all timers. No arguments.", tmR3TimerInfoActive, DBGFINFO_FLAGS_RUN_ON_EMT);
DBGFR3InfoRegisterInternalEx(pVM, "clocks", "Display the time of the various clocks.", tmR3InfoClocks, DBGFINFO_FLAGS_RUN_ON_EMT);
return VINF_SUCCESS;
}
/**
* Initializes the per-VCPU TM.
*
* @returns VBox status code.
* @param pVM The VM to operate on.
*/
{
LogFlow(("TMR3InitCPU\n"));
return VINF_SUCCESS;
}
/**
* Checks if the host CPU has a fixed TSC frequency.
*
* @returns true if it has, false if it hasn't.
*
* @remark This test doesn't bother with very old CPUs that don't do power
* management or any other stuff that might influence the TSC rate.
* This isn't currently relevant.
*/
{
if (ASMHasCpuId())
{
{
/*
* AuthenticAMD - Check for APM support and that TscInvariant is set.
*
* older models, but this isn't relevant since the result is currently
* only used for making a descision on AMD-V models.
*/
if (uEAX >= 0x80000007)
{
return true;
}
}
{
/*
* GenuineIntel - Check the model number.
*
* This test is lacking in the same way and for the same reasons
* as the AMD test above.
*/
if (uFamily == 0x0f)
if (uFamily >= 0x06)
return true;
}
}
return false;
}
/**
* Calibrate the CPU tick.
*
* @returns Number of ticks per second.
*/
{
/*
* Use GIP when available present.
*/
if ( pGip
{
AssertReleaseMsgFailed(("iCpu=%d - the ApicId is too high. send VBox.log and hardware specs!\n", iCpu));
else
{
if (tmR3HasFixedTSC(pVM))
/* Sleep a bit to get a more reliable CpuHz value. */
RTThreadSleep(32);
else
{
/* Spin for 40ms to try push up the CPU frequency and get a more reliable CpuHz value. */
/* nothing */;
}
if ( pGip
return u64Hz;
}
}
/* call this once first to make sure it's initialized. */
RTTimeNanoTS();
/*
* Yield the CPU to increase our chances of getting
* a correct value.
*/
RTThreadYield(); /* Try avoid interruptions between TSC and NanoTS samplings. */
unsigned i;
for (i = 0; i < RT_ELEMENTS(au64Samples); i++)
{
unsigned cMillies;
int cTries = 5;
do
{
RTThreadSleep(s_auSleep[i]);
u64End = ASMReadTSC();
EndTS = RTTimeNanoTS();
} while ( cMillies == 0 /* the sleep may be interrupted... */
}
/*
* Discard the highest and lowest results and calculate the average.
*/
unsigned iHigh = 0;
unsigned iLow = 0;
{
iLow = i;
iHigh = i;
}
au64Samples[iLow] = 0;
au64Samples[iHigh] = 0;
u64Hz = au64Samples[0];
u64Hz += au64Samples[i];
return u64Hz;
}
/**
* Finalizes the TM initialization.
*
* @returns VBox status code.
* @param pVM The VM to operate on.
*/
{
int rc;
rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
else
rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataR0.pfnBad);
rc = PDMR3LdrGetSymbolR0Lazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataR0.pfnRediscover);
else
return VINF_SUCCESS;
}
/**
* Applies relocations to data and code managed by this
* component. This function will be called at init and
* whenever the VMM need to relocate it self inside the GC.
*
* @param pVM The VM.
* @param offDelta Relocation delta relative to old location.
*/
{
int rc;
LogFlow(("TMR3Relocate\n"));
rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSBad", &pVM->tm.s.VirtualGetRawDataRC.pfnBad);
rc = PDMR3LdrGetSymbolRCLazy(pVM, NULL, "tmVirtualNanoTSRediscover", &pVM->tm.s.VirtualGetRawDataRC.pfnRediscover);
else
/*
* Iterate the timers updating the pVMRC pointers.
*/
{
}
}
/**
* Terminates the TM.
*
* Termination means cleaning up and freeing all resources,
* the VM it self is at this point powered off or suspended.
*
* @returns VBox status code.
* @param pVM The VM to operate on.
*/
{
{
}
return VINF_SUCCESS;
}
/**
* Terminates the per-VCPU TM.
*
* Termination means cleaning up and freeing all resources,
* the VM it self is at this point powered off or suspended.
*
* @returns VBox status code.
* @param pVM The VM to operate on.
*/
{
return 0;
}
/**
* The VM is being reset.
*
* For the TM component this means that a rescheduling is preformed,
* the FF is cleared and but without running the queues. We'll have to
* check if this makes sense or not, but it seems like a good idea now....
*
* @param pVM VM handle.
*/
{
LogFlow(("TMR3Reset:\n"));
/*
* Abort any pending catch up.
* This isn't perfect...
*/
{
{
LogRel(("TM: Aborting catch-up attempt on reset with a %RU64 ns lag on reset; new total: %RU64 ns\n", offNew - offOld, offNew));
}
}
/*
* Process the queues.
*/
for (int i = 0; i < TMCLOCK_MAX; i++)
#ifdef VBOX_STRICT
#endif
}
/**
* Resolve a builtin RC symbol.
* Called by PDM when loading or relocating GC modules.
*
* @returns VBox status
* @param pVM VM Handle.
* @param pszSymbol Symbol to resolve.
* @param pRCPtrValue Where to store the symbol value.
* @remark This has to work before TMR3Relocate() is called.
*/
{
//else if (..)
else
return VERR_SYMBOL_NOT_FOUND;
return VINF_SUCCESS;
}
/**
* Execute state save operation.
*
* @returns VBox status code.
* @param pVM VM Handle.
* @param pSSM SSM operation handle.
*/
{
LogFlow(("tmR3Save:\n"));
#ifdef VBOX_STRICT
{
}
#endif
/*
* Save the virtual clocks.
*/
/* the virtual clock. */
/* the virtual timer synchronous clock. */
/* real time clock */
{
/* the cpu tick clock. */
}
}
/**
* Execute state load operation.
*
* @returns VBox status code.
* @param pVM VM Handle.
* @param pSSM SSM operation handle.
* @param u32Version Data layout version.
*/
{
LogFlow(("tmR3Load:\n"));
#ifdef VBOX_STRICT
{
}
#endif
/*
* Validate version.
*/
if (u32Version != TM_SAVED_STATE_VERSION)
{
}
/*
* Load the virtual clock.
*/
/* the virtual clock. */
if (RT_FAILURE(rc))
return rc;
if (u64Hz != TMCLOCK_FREQ_VIRTUAL)
{
AssertMsgFailed(("The virtual clock frequency differs! Saved: %RU64 Binary: %RU64\n",
return VERR_SSM_VIRTUAL_CLOCK_HZ;
}
/* the virtual timer synchronous clock. */
bool f;
SSMR3GetBool(pSSM, &f);
/* the real clock */
if (RT_FAILURE(rc))
return rc;
if (u64Hz != TMCLOCK_FREQ_REAL)
{
AssertMsgFailed(("The real clock frequency differs! Saved: %RU64 Binary: %RU64\n",
return VERR_SSM_VIRTUAL_CLOCK_HZ; /* missleading... */
}
/* the cpu tick clock. */
{
}
if (RT_FAILURE(rc))
return rc;
LogRel(("TM: cTSCTicksPerSecond=%#RX64 (%RU64) fTSCVirtualized=%RTbool fTSCUseRealTSC=%RTbool (state load)\n",
pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.cTSCTicksPerSecond, pVM->tm.s.fTSCVirtualized, pVM->tm.s.fTSCUseRealTSC));
/*
* Make sure timers get rescheduled immediately.
*/
return VINF_SUCCESS;
}
/**
* Internal TMR3TimerCreate worker.
*
* @returns VBox status code.
* @param pVM The VM handle.
* @param enmClock The timer clock.
* @param pszDesc The timer description.
* @param ppTimer Where to store the timer pointer on success.
*/
{
/*
* Allocate the timer.
*/
{
}
if (!pTimer)
{
if (RT_FAILURE(rc))
return rc;
}
/*
* Initialize it.
*/
pTimer->offScheduleNext = 0;
/* insert into the list of created timers. */
#ifdef VBOX_STRICT
#endif
return VINF_SUCCESS;
}
/**
* Creates a device timer.
*
* @returns VBox status.
* @param pVM The VM to create the timer in.
* @param pDevIns Device instance.
* @param enmClock The clock to use on this timer.
* @param pfnCallback Callback function.
* @param pszDesc Pointer to description string which must stay around
* until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
* @param ppTimer Where to store the timer on success.
*/
VMMR3DECL(int) TMR3TimerCreateDevice(PVM pVM, PPDMDEVINS pDevIns, TMCLOCK enmClock, PFNTMTIMERDEV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
{
/*
* Allocate and init stuff.
*/
if (RT_SUCCESS(rc))
{
Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
}
return rc;
}
/**
* Creates a driver timer.
*
* @returns VBox status.
* @param pVM The VM to create the timer in.
* @param pDrvIns Driver instance.
* @param enmClock The clock to use on this timer.
* @param pfnCallback Callback function.
* @param pszDesc Pointer to description string which must stay around
* until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
* @param ppTimer Where to store the timer on success.
*/
VMMR3DECL(int) TMR3TimerCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, TMCLOCK enmClock, PFNTMTIMERDRV pfnCallback, const char *pszDesc, PPTMTIMERR3 ppTimer)
{
/*
* Allocate and init stuff.
*/
if (RT_SUCCESS(rc))
{
Log(("TM: Created device timer %p clock %d callback %p '%s'\n", (*ppTimer), enmClock, pfnCallback, pszDesc));
}
return rc;
}
/**
* Creates an internal timer.
*
* @returns VBox status.
* @param pVM The VM to create the timer in.
* @param enmClock The clock to use on this timer.
* @param pfnCallback Callback function.
* @param pvUser User argument to be passed to the callback.
* @param pszDesc Pointer to description string which must stay around
* until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
* @param ppTimer Where to store the timer on success.
*/
VMMR3DECL(int) TMR3TimerCreateInternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMERINT pfnCallback, void *pvUser, const char *pszDesc, PPTMTIMERR3 ppTimer)
{
/*
* Allocate and init stuff.
*/
if (RT_SUCCESS(rc))
{
Log(("TM: Created internal timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
}
return rc;
}
/**
* Creates an external timer.
*
* @returns Timer handle on success.
* @returns NULL on failure.
* @param pVM The VM to create the timer in.
* @param enmClock The clock to use on this timer.
* @param pfnCallback Callback function.
* @param pvUser User argument.
* @param pszDesc Pointer to description string which must stay around
* until the timer is fully destroyed (i.e. a bit after TMTimerDestroy()).
*/
VMMR3DECL(PTMTIMERR3) TMR3TimerCreateExternal(PVM pVM, TMCLOCK enmClock, PFNTMTIMEREXT pfnCallback, void *pvUser, const char *pszDesc)
{
/*
* Allocate and init stuff.
*/
if (RT_SUCCESS(rc))
{
Log(("TM: Created external timer %p clock %d callback %p '%s'\n", pTimer, enmClock, pfnCallback, pszDesc));
return pTimer;
}
return NULL;
}
/**
* Destroy a timer
*
* @returns VBox status.
* @param pTimer Timer handle as returned by one of the create functions.
*/
{
/*
* Be extra careful here.
*/
if (!pTimer)
return VINF_SUCCESS;
bool fActive = false;
bool fPending = false;
/*
* The rest of the game happens behind the lock, just
* like create does. All the work is done here.
*/
{
/*
* Change to the DESTROY state.
*/
Log2(("TMTimerDestroy: %p:{.enmState=%s, .pszDesc='%s'} cRetries=%d\n",
switch (enmState)
{
case TMTIMERSTATE_STOPPED:
case TMTIMERSTATE_EXPIRED:
break;
case TMTIMERSTATE_ACTIVE:
fActive = true;
break;
fActive = true;
fPending = true;
break;
fPending = true;
break;
/*
* This shouldn't happen as the caller should make sure there are no races.
*/
if (!RTThreadYield())
RTThreadSleep(1);
AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
continue;
/*
* Invalid states.
*/
case TMTIMERSTATE_FREE:
case TMTIMERSTATE_DESTROY:
AssertLogRelMsgFailedReturn(("pTimer=%p %s\n", pTimer, tmTimerState(enmState)), VERR_TM_INVALID_STATE);
default:
return VERR_TM_UNKNOWN_STATE;
}
/*
* Try switch to the destroy state.
* This should always succeed as the caller should make sure there are no race.
*/
bool fRc;
if (fRc)
break;
AssertMsgReturn(cRetries > 0, ("Failed waiting for stable state. state=%d (%s)\n", pTimer->enmState, pTimer->pszDesc),
}
/*
* Unlink from the active list.
*/
if (fActive)
{
if (pPrev)
else
{
}
if (pNext)
}
/*
* Unlink from the schedule list by running it.
*/
if (fPending)
{
Log3(("TMR3TimerDestroy: tmTimerQueueSchedule\n"));
}
/*
* Read to move the timer from the created list and onto the free list.
*/
/* unlink from created list */
else
/* free */
#ifdef VBOX_STRICT
#endif
return VINF_SUCCESS;
}
/**
* Destroy all timers owned by a device.
*
* @returns VBox status.
* @param pVM VM handle.
* @param pDevIns Device which timers should be destroyed.
*/
{
if (!pDevIns)
return VERR_INVALID_PARAMETER;
while (pCur)
{
{
}
}
LogFlow(("TMR3TimerDestroyDevice: returns VINF_SUCCESS\n"));
return VINF_SUCCESS;
}
/**
* Destroy all timers owned by a driver.
*
* @returns VBox status.
* @param pVM VM handle.
* @param pDrvIns Driver which timers should be destroyed.
*/
{
if (!pDrvIns)
return VERR_INVALID_PARAMETER;
while (pCur)
{
{
}
}
LogFlow(("TMR3TimerDestroyDriver: returns VINF_SUCCESS\n"));
return VINF_SUCCESS;
}
/**
* Internal function for getting the clock time.
*
* @returns clock time.
* @param pVM The VM handle.
* @param enmClock The clock.
*/
{
switch (enmClock)
{
default:
return ~(uint64_t)0;
}
}
/**
* Checks if the sync queue has one or more expired timers.
*
* @returns true / false.
*
* @param pVM The VM handle.
* @param enmClock The queue.
*/
{
}
/**
* Checks for expired timers in all the queues.
*
* @returns true / false.
* @param pVM The VM handle.
*/
{
/*
* Combine the time calculation for the first two since we're not on EMT
* TMVirtualSyncGet only permits EMT.
*/
return true;
return true;
/*
* The remaining timers.
*/
return true;
return true;
return false;
}
/**
* Schedulation timer callback.
*
* @param pTimer Timer handle.
* @param pvUser VM handle.
* @thread Timer thread.
*
* @remark We cannot do the scheduling and queues running from a timer handler
* since it's not executing in EMT, and even if it was it would be async
* and we wouldn't know the state of the affairs.
* So, we'll just raise the timer FF and force any REM execution to exit.
*/
{
#ifdef DEBUG_Sander /* very annoying, keep it private. */
Log(("tmR3TimerCallback: timer event still pending!!\n"));
#endif
&& ( pVM->tm.s.paTimerQueuesR3[TMCLOCK_VIRTUAL_SYNC].offSchedule /** @todo FIXME - reconsider offSchedule as a reason for running the timer queues. */
)
)
{
VMR3NotifyCpuFFU(pVCpuDst->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM /** @todo | VMNOTIFYFF_FLAGS_POKE ?*/);
}
}
/**
* Schedules and runs any pending timers.
*
* This is normally called from a forced action handler in EMT.
*
* @param pVM The VM to run the timers for.
*
* @thread EMT (actually EMT0, but we fend off the others)
*/
{
/*
* Only the dedicated timer EMT should do stuff here.
* (fRunningQueues is only used as an indicator.)
*/
{
return;
}
Log2(("TMR3TimerQueuesDo:\n"));
/*
* Process the queues.
*/
/* TMCLOCK_VIRTUAL_SYNC (see also TMR3VirtualSyncFF) */
/* TMCLOCK_VIRTUAL */
/* TMCLOCK_TSC */
/* TMCLOCK_REAL */
#ifdef VBOX_STRICT
/* check that we didn't screwup. */
#endif
/* done */
Log2(("TMR3TimerQueuesDo: returns void\n"));
}
//__BEGIN_DECLS
//int iomLock(PVM pVM);
//void iomUnlock(PVM pVM);
//__END_DECLS
/**
* Schedules and runs any pending times in the specified queue.
*
* This is normally called from a forced action handler in EMT.
*
* @param pVM The VM to run the timers for.
* @param pQueue The queue to run.
*/
{
/*
* Run timers.
*
* We check the clock once and run all timers which are ACTIVE
* and have an expire time less or equal to the time we read.
*
* N.B. A generic unlink must be applied since other threads
* are allowed to mess with any active timer at any time.
* However, we only allow EMT to handle EXPIRED_PENDING
* timers, thus enabling the timer handler function to
* arm the timer again.
*/
if (!pNext)
return;
{
Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
bool fRc;
if (fRc)
{
/* unlink */
if (pPrev)
else
{
}
if (pNext)
/* fire */
// tmUnlock(pVM);
{
case TMTIMERTYPE_DEV:
// iomLock(pVM);
// iomUnlock(pVM);
break;
case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
default:
break;
}
// tmLock(pVM);
/* change the state if it wasn't changed already in the handler. */
}
} /* run loop */
}
/**
* Schedules and runs any pending times in the timer queue for the
* synchronous virtual clock.
*
* This scheduling is a bit different from the other queues as it need
* to implement the special requirements of the timer synchronous virtual
* clock, thus this 2nd queue run funcion.
*
* @param pVM The VM to run the timers for.
*
*/
{
/*
* Any timers?
*/
if (RT_UNLIKELY(!pNext))
{
return;
}
/*
* Calculate the time frame for which we will dispatch timers.
*
* We use a time frame ranging from the current sync time (which is most likely the
* same as the head timer) and some configurable period (100000ns) up towards the
* current virtual time. This period might also need to be restricted by the catch-up
* rate so frequent calls to this function won't accelerate the time too much, however
* this will be implemented at a later point if neccessary.
*
* Without this frame we would 1) having to run timers much more frequently
* and 2) lag behind at a steady rate.
*/
{
}
else
{
/* Calc 'now'. */
bool fStopCatchup = false;
bool fUpdateStuff = false;
{
{
uint64_t u64Sub = ASMMultU64ByU32DivByU32(u64Delta, pVM->tm.s.u32VirtualSyncCatchUpPercentage, 100);
{
}
else
{
fStopCatchup = true;
}
}
}
/* Check if stopped by expired timer. */
{
}
else if (fUpdateStuff)
{
if (fStopCatchup)
}
}
/* calc end of frame. */
/* assert sanity */
/*
* Process the expired timers moving the clock along as we progress.
*/
#ifdef VBOX_STRICT
#endif
{
Log2(("tmR3TimerQueueRun: %p:{.enmState=%s, .enmClock=%d, .enmType=%d, u64Expire=%llx (now=%llx) .pszDesc=%s}\n",
pTimer, tmTimerState(pTimer->enmState), pTimer->enmClock, pTimer->enmType, pTimer->u64Expire, u64Now, pTimer->pszDesc));
bool fRc;
if (fRc)
{
/* unlink */
if (pPrev)
else
{
}
if (pNext)
/* advance the clock - don't permit timers to be out of order or armed in the 'past'. */
#ifdef VBOX_STRICT
AssertMsg(pTimer->u64Expire >= u64Prev, ("%RU64 < %RU64 %s\n", pTimer->u64Expire, u64Prev, pTimer->pszDesc));
#endif
/* fire */
{
case TMTIMERTYPE_INTERNAL: pTimer->u.Internal.pfnTimer(pVM, pTimer, pTimer->u.Internal.pvUser); break;
default:
break;
}
/* change the state if it wasn't changed already in the handler. */
}
} /* run loop */
/*
* Restart the clock if it was stopped to serve any timers,
*/
{
/* calc the slack we've handed out. */
AssertMsg(pVM->tm.s.u64VirtualSync >= u64Now, ("%RU64 < %RU64\n", pVM->tm.s.u64VirtualSync, u64Now));
if (offSlack)
{
p->cPeriods++;
}
});
/* Let the time run a little bit while we were busy running timers(?). */
if (offSlack > MAX_ELAPSED)
u64Elapsed = 0;
else
{
if (u64Elapsed > MAX_ELAPSED)
}
/* Calc the current offset. */
/*
* Deal with starting, adjusting and stopping catchup.
*/
{
{
/* stop */
}
{
/* adjust */
unsigned i = 0;
i++;
if (pVM->tm.s.u32VirtualSyncCatchUpPercentage < pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage)
{
ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
Log4(("TM: %RU64/%RU64: adj %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
}
}
else
{
/* give up */
Log4(("TM: %RU64/%RU64: give up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
LogRel(("TM: Giving up catch-up attempt at a %RU64 ns lag; new total: %RU64 ns\n", offLag, offNew));
}
}
{
{
/* start */
unsigned i = 0;
i++;
ASMAtomicWriteU32(&pVM->tm.s.u32VirtualSyncCatchUpPercentage, pVM->tm.s.aVirtualSyncCatchUpPeriods[i].u32Percentage);
Log4(("TM: %RU64/%RU64: catch-up %u%%\n", u64VirtualNow2 - offNew, offLag, pVM->tm.s.u32VirtualSyncCatchUpPercentage));
}
else
{
/* don't bother */
LogRel(("TM: Not bothering to attempt catching up a %RU64 ns lag; new total: %RU64\n", offLag, offNew));
}
}
/*
* Update the offset and restart the clock.
*/
}
}
/**
* Deals with stopped Virtual Sync clock.
*
* This is called by the forced action flag handling code in EM when it
* encounters the VM_FF_TM_VIRTUAL_SYNC flag. It is called by all VCPUs and they
* will block on the VirtualSyncLock until the pending timers has been executed
* and the clock restarted.
*
* @param pVM The VM to run the timers for.
* @param pVCpu The virtual CPU we're running at.
*
* @thread EMTs
*/
{
Log2(("TMR3VirtualSyncFF:\n"));
/*
* The EMT doing the timers is diverted to them.
*/
/*
* The other EMTs will block on the virtual sync lock and the first owner
* will run the queue and thus restarting the clock.
*
* Note! This is very suboptimal code wrt to resuming execution when there
* are more than two Virtual CPUs, since they will all have to enter
* the critical section one by one. But it's a very simple solution
* which will have to do the job for now.
*/
else
{
{
Log2(("TMR3VirtualSyncFF: ticking\n"));
}
else
{
/* try run it. */
Log2(("TMR3VirtualSyncFF: ticking (2)\n"));
else
{
Log2(("TMR3VirtualSyncFF: running queue\n"));
}
}
}
}
/**
* Saves the state of a timer to a saved state.
*
* @returns VBox status.
* @param pTimer Timer to save.
* @param pSSM Save State Manager handle.
*/
{
LogFlow(("TMR3TimerSave: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
{
case TMTIMERSTATE_STOPPED:
if (!RTThreadYield())
RTThreadSleep(1);
/* fall thru */
case TMTIMERSTATE_ACTIVE:
case TMTIMERSTATE_EXPIRED:
case TMTIMERSTATE_DESTROY:
case TMTIMERSTATE_FREE:
AssertMsgFailed(("Invalid timer state %d %s (%s)\n", pTimer->enmState, tmTimerState(pTimer->enmState), pTimer->pszDesc));
}
}
/**
* Loads the state of a timer from a saved state.
*
* @returns VBox status.
* @param pTimer Timer to restore.
* @param pSSM Save State Manager handle.
*/
{
LogFlow(("TMR3TimerLoad: %p:{enmState=%s, .pszDesc={%s}} pSSM=%p\n", pTimer, tmTimerState(pTimer->enmState), pTimer->pszDesc, pSSM));
/*
* Load the state and validate it.
*/
if (RT_FAILURE(rc))
return rc;
if ( enmState != TMTIMERSTATE_PENDING_STOP
{
}
{
/*
* Load the expire time.
*/
if (RT_FAILURE(rc))
return rc;
/*
* Set it.
*/
}
else
{
/*
* Stop it.
*/
}
/*
* On failure set SSM status.
*/
if (RT_FAILURE(rc))
return rc;
}
/**
* Get the real world UTC time adjusted for VM lag.
*
* @returns pTime.
* @param pVM The VM instance.
* @param pTime Where to store the time.
*/
{
RTTimeSpecSubNano(pTime, ASMAtomicReadU64(&pVM->tm.s.offVirtualSync) - ASMAtomicReadU64((uint64_t volatile *)&pVM->tm.s.offVirtualSyncGivenUp));
return pTime;
}
/**
* Pauses all clocks except TMCLOCK_REAL.
*
* @returns VBox status code, all errors are asserted.
* @param pVM The VM handle.
* @param pVCpu The virtual CPU handle.
* @thread EMT corrsponding to the virtual CPU handle.
*/
{
/*
* The shared virtual clock (includes virtual sync which is tied to it).
*/
if (RT_FAILURE(rc))
return rc;
/*
* Pause the TSC last since it is normally linked to the virtual
* sync clock, so the above code may actually stop both clock.
*/
}
/**
* Resumes all clocks except TMCLOCK_REAL.
*
* @returns VBox status code, all errors are asserted.
* @param pVM The VM handle.
* @param pVCpu The virtual CPU handle.
* @thread EMT corrsponding to the virtual CPU handle.
*/
{
int rc;
/*
* Resume the TSC first since it is normally linked to the virtual sync
* clock, so it may actually not be resumed until we've executed the code
* below.
*/
{
if (RT_FAILURE(rc))
return rc;
}
/*
* The shared virtual clock (includes virtual sync which is tied to it).
*/
return rc;
}
/**
* Sets the warp drive percent of the virtual time.
*
* @returns VBox status code.
* @param pVM The VM handle.
* @param u32Percent The new percentage. 100 means normal operation.
*
* @todo Move to Ring-3!
*/
{
if (RT_SUCCESS(rc))
return rc;
}
/**
* EMT worker for TMR3SetWarpDrive.
*
* @returns VBox status code.
* @param pVM The VM handle.
* @param u32Percent See TMR3SetWarpDrive().
* @internal
*/
{
/*
* Validate it.
*/
("%RX32 is not between 2 and 20000 (inclusive).\n", u32Percent),
/** @todo This isn't a feature specific to virtual time, move the variables to
* TM level and make it affect TMR3UCTNow as well! */
/*
* If the time is running we'll have to pause it before we can change
* the warp drive settings.
*/
if (fPaused) /** @todo this isn't really working, but wtf. */
LogRel(("TM: u32VirtualWarpDrivePercentage=%RI32 fVirtualWarpDrive=%RTbool\n",
if (fPaused)
return VINF_SUCCESS;
}
/**
* Display all timers.
*
* @param pVM VM Handle.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
{
"Timers (pVM=%p)\n"
"%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
pVM,
"Time",
"Expire",
"State");
{
"%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
}
}
/**
* Display all active timers.
*
* @param pVM VM Handle.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
{
"Active Timers (pVM=%p)\n"
"%.*s %.*s %.*s %.*s Clock %-18s %-18s %-25s Description\n",
pVM,
"Time",
"Expire",
"State");
{
{
"%p %08RX32 %08RX32 %08RX32 %s %18RU64 %18RU64 %-25s %s\n",
? "Real "
? "Virt "
? "VrSy "
: "TSC ",
}
}
}
/**
* Display all clocks.
*
* @param pVM VM Handle.
* @param pHlp The info helpers.
* @param pszArgs Arguments, ignored.
*/
{
/*
* Read the times first to avoid more than necessary time variation.
*/
{
/*
* TSC
*/
"Cpu Tick: %18RU64 (%#016RX64) %RU64Hz %s%s",
{
}
else
}
/*
* virtual
*/
" Virtual: %18RU64 (%#016RX64) %RU64Hz %s",
/*
* virtual sync
*/
"VirtSync: %18RU64 (%#016RX64) %s%s",
{
}
/*
* real
*/
" Real: %18RU64 (%#016RX64) %RU64Hz\n",
}