DevPit-i8254.cpp revision ec231f99272496dd79e402040cc7ca087ef7ccd6
/** @file
*
* VBox basic PC devices:
* Intel 8254 programmable interval timer
*/
/*
* Copyright (C) 2006 InnoTek Systemberatung GmbH
*
* 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 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.
*
* If you received this file as part of a commercial VirtualBox
* distribution, then only the terms of your commercial VirtualBox
* license agreement apply instead of the previous paragraph.
*
* --------------------------------------------------------------------
*
* This code is based on:
*
* QEMU 8253/8254 interval timer emulation
*
* Copyright (c) 2003-2004 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_DEV_PIT
#include "Builtins.h"
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** The PIT frequency. */
#define PIT_FREQ 1193182
#define RW_STATE_LSB 1
#define RW_STATE_MSB 2
#define RW_STATE_WORD0 3
#define RW_STATE_WORD1 4
/** The version of the saved state. */
#define PIT_SAVED_STATE_VERSION 2
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
typedef struct PITChannelState
{
/** Pointer to the instance data - HCPtr. */
/** The timer - HCPtr. */
/** Pointer to the instance data - GCPtr. */
/** The timer - HCPtr. */
/** The virtual time stamp at the last reload. (only used in mode 2 for now) */
/** The actual time of the next tick.
* As apposed to the next_transition_time which contains the correct time of the next tick. */
#ifndef VBOX_WITH_VIRTUAL_SYNC_TIMERS
/** When to give up catching up. (negative number) */
#endif
/** (count_load_time is only set by TMTimerGet() which returns uint64_t) */
/* irq handling */
typedef struct PITState
{
/** Speaker data. */
/** Speaker dummy. */
/** Pointer to the device instance. */
#if HC_ARCH_BITS == 32
#endif
/** Number of IRQs that's been raised. */
/** Profiling the timer callback handler. */
#ifndef VBOX_WITH_VIRTUAL_SYNC_TIMERS
/** The number of times we've had to speed up the time because we lagged too far behind. */
/** The number of times we've lagged too far behind for it to be worth trying to catch up. */
#endif
} PITState;
#ifndef VBOX_DEVICE_STRUCT_TESTCASE
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
PDMBOTHCBDECL(int) pitIOPortRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb);
PDMBOTHCBDECL(int) pitIOPortWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb);
PDMBOTHCBDECL(int) pitIOPortSpeakerRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb);
#ifdef IN_RING3
PDMBOTHCBDECL(int) pitIOPortSpeakerWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb);
#endif
static int pit_get_count(PITChannelState *s)
{
uint64_t d;
int counter;
{
#if 0
d = TMTimerGet(pTimer);
d -= s->u64ReloadTS;
#else /* variable time because of catch up */
if (s->u64NextTS == UINT64_MAX)
return 1; /** @todo check this value. */
d = TMTimerGet(pTimer);
#endif
if (d >= s->count)
return 1;
return s->count - d;
}
d = ASMMultU64ByU32DivByU32(TMTimerGet(pTimer) - s->count_load_time, PIT_FREQ, TMTimerGetFreq(pTimer));
switch(s->mode) {
case 0:
case 1:
case 4:
case 5:
break;
case 3:
/* XXX: may be incorrect for odd counts */
break;
default:
break;
}
/** @todo check that we don't return 0, in most modes (all?) the counter shouldn't be zero. */
return counter;
}
/* get pit output bit */
{
uint64_t d;
int out;
switch(s->mode) {
default:
case 0:
break;
case 1:
break;
case 2:
if ((d % s->count) == 0 && d != 0)
out = 1;
else
out = 0;
break;
case 3:
break;
case 4:
case 5:
break;
}
return out;
}
{
return pit_get_out1(s, current_time);
}
{
return s->gate;
}
/* if already latched, do not latch again */
static void pit_latch_count(PITChannelState *s)
{
if (!s->count_latched) {
s->latched_count = pit_get_count(s);
s->count_latched = s->rw_mode;
LogFlow(("pit_latch_count: latched_count=%#06x / %10RU64 ns (c=%#06x m=%d)\n",
s->latched_count, ASMMultU64ByU32DivByU32(s->count - s->latched_count, 1000000000, PIT_FREQ), s->count, s->mode));
}
}
#ifdef IN_RING3
/* val must be 0 or 1 */
{
switch(s->mode) {
default:
case 0:
case 4:
break;
case 1:
case 5:
/* restart counting on rising edge */
pit_irq_timer_update(s, s->count_load_time);
}
break;
case 2:
case 3:
/* restart counting on rising edge */
pit_irq_timer_update(s, s->count_load_time);
}
break;
}
}
{
if (val == 0)
val = 0x10000;
pit_irq_timer_update(s, s->count_load_time);
}
/* return -1 if no transition will occur. */
{
switch(s->mode) {
default:
case 0:
case 1:
if (d < s->count)
else
return -1;
break;
/*
* Mode 2: The period is count + 1 PIT ticks.
* When the counter reaches 1 we sent the output low (for channel 0 that
* means raise an irq). On the next tick, where we should be decrementing
* from 1 to 0, the count is loaded and the output goes high (channel 0
* means clearing the irq).
*
* In VBox we simplify the tick cycle between 1 and 0 and immediately clears
* the irq. We also don't set it until we reach 0, which is a tick late - will
* try fix that later some day.
*/
case 2:
#ifndef VBOX /* see above */
if ((d - base) == 0 && d != 0)
else
#endif
break;
case 3:
else
break;
case 4:
case 5:
if (d < s->count)
else if (d == s->count)
else
return -1;
break;
}
/* convert to timer units */
next_time = s->count_load_time + ASMMultU64ByU32DivByU32(next_time, TMTimerGetFreq(pTimer), PIT_FREQ);
/* fix potential rounding problems */
/* XXX: better solution: use a clock at PIT_FREQ Hz */
if (next_time <= current_time)
return next_time;
}
{
int irq_level;
return;
/* We just flip-flop the irq level to save that extra timer call, which isn't generally required (we haven't served it for months). */
if (irq_level)
if (irq_level)
{
s->u64ReloadTS = now;
}
if (expire_time != -1)
{
s->u64NextTS = expire_time;
}
#else
/* check if it expires too soon - move at 4x rate if it does. */
if (expire_time != -1)
{
{
if (delta >= s->i64MaxCatchupTS)
{
/* If we set the timer to 'expire_time' we could end up with flooding the guest
* with timer interrupts because the next interrupt(s) would probably raise
* immediately. Therefore we set the timer to 'now + quarter' with quarter>0.
* This delays the adaption a little bit. */
LogFlow(("PIT: m=%d cnt=%#4x irq=%#x delay=%8RI64 next=%20RI64 now=%20RI64 load=%20RI64 %9RI64 delta=%9RI64\n",
ASMMultU64ByU32DivByU32(s->u64NextTS - s->count_load_time, PIT_FREQ, TMTimerGetFreq(pTimer)), delta));
}
else
{
/* We are too far away from the real time. Hard synchronize. */
LogFlow(("PIT: m=%d cnt=%#4x irq=%#x delay=%8RI64 next=%20RI64 now=%20RI64 load=%20RI64 %9RI64 delta=%9RI64 giving up!\n",
ASMMultU64ByU32DivByU32(s->u64NextTS - s->count_load_time, PIT_FREQ, TMTimerGetFreq(pTimer)), delta));
}
}
else
{
/* Everything is fine, just set the timer to the regular next expire_time. */
s->u64NextTS = expire_time;
LogFlow(("PIT: m=%d cnt=%#4x irq=%#x delay=%8RI64 next=%20RI64 now=%20RI64 load=%20RI64 %9RI64\n",
}
}
#endif
else
{
s->u64NextTS = UINT64_MAX;
}
}
#endif /* IN_RING3 */
/**
* Port I/O Handler for IN operations.
*
* @returns VBox status code.
*
* @param pDevIns The device instance.
* @param pvUser User argument - ignored.
* @param Port Port number used for the IN operation.
* @param pu32 Where to store the result.
* @param cb Number of bytes read.
*/
PDMBOTHCBDECL(int) pitIOPortRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
{
Port &= 3;
{
return VERR_IOM_IOPORT_UNUSED;
}
int ret;
if (s->status_latched)
{
s->status_latched = 0;
}
else if (s->count_latched)
{
switch (s->count_latched)
{
default:
case RW_STATE_LSB:
s->count_latched = 0;
break;
case RW_STATE_MSB:
s->count_latched = 0;
break;
case RW_STATE_WORD0:
s->count_latched = RW_STATE_MSB;
break;
}
}
else
{
int count;
switch (s->read_state)
{
default:
case RW_STATE_LSB:
count = pit_get_count(s);
break;
case RW_STATE_MSB:
count = pit_get_count(s);
break;
case RW_STATE_WORD0:
count = pit_get_count(s);
s->read_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
count = pit_get_count(s);
s->read_state = RW_STATE_WORD0;
break;
}
}
return VINF_SUCCESS;
}
/**
* Port I/O Handler for OUT operations.
*
* @returns VBox status code.
*
* @param pDevIns The device instance.
* @param pvUser User argument - ignored.
* @param Port Port number used for the IN operation.
* @param u32 The value to output.
* @param cb The value size in bytes.
*/
PDMBOTHCBDECL(int) pitIOPortWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
{
if (cb != 1)
return VINF_SUCCESS;
Port &= 3;
if (Port == 3)
{
/*
* 7 6 5 4 3 2 1 0
* * * . . . . . . Select channel: 0 0 = Channel 0
* 0 1 = Channel 1
* 1 0 = Channel 2
* 1 1 = Read-back command (8254 only)
* (Illegal on 8253)
* (Illegal on PS/2 {JAM})
* 0 1 = Access mode: lobyte only
* 1 0 = Access mode: hibyte only
* . . . . * * * . Operating mode: 0 0 0 = Mode 0, 0 0 1 = Mode 1,
* 0 1 0 = Mode 2, 0 1 1 = Mode 3,
* 1 0 0 = Mode 4, 1 0 1 = Mode 5,
* 1 1 0 = Mode 2, 1 1 1 = Mode 3
*/
if (channel == 3)
{
/* read-back command */
{
if (!(u32 & 0x20))
pit_latch_count(s);
{
/* status latch */
/* XXX: add BCD and null count */
| (s->rw_mode << 4)
| (s->mode << 1)
| s->bcd;
s->status_latched = 1;
}
}
}
}
else
{
if (access == 0)
pit_latch_count(s);
else
{
s->read_state = access;
s->write_state = access;
/* XXX: update irq timer ? */
}
}
}
else
{
#ifndef IN_RING3
return VINF_IOM_HC_IOPORT_WRITE;
#else /* IN_RING3 */
/*
* Port 40-42h - Channel Data Ports.
*/
switch(s->write_state)
{
default:
case RW_STATE_LSB:
pit_load_count(s, u32);
break;
case RW_STATE_MSB:
break;
case RW_STATE_WORD0:
s->write_latch = u32;
s->write_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
s->write_state = RW_STATE_WORD0;
break;
}
#endif /* !IN_RING3 */
}
return VINF_SUCCESS;
}
/**
* Port I/O Handler for speaker IN operations.
*
* @returns VBox status code.
*
* @param pDevIns The device instance.
* @param pvUser User argument - ignored.
* @param Port Port number used for the IN operation.
* @param pu32 Where to store the result.
* @param cb Number of bytes read.
*/
PDMBOTHCBDECL(int) pitIOPortSpeakerRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
{
if (cb == 1)
{
*pu32 = (pData->speaker_data_on << 1) | pit_get_gate(pData, 2) | (out << 5) | (pData->dummy_refresh_clock << 4);
return VINF_SUCCESS;
}
return VERR_IOM_IOPORT_UNUSED;
}
#ifdef IN_RING3
/**
* Port I/O Handler for speaker OUT operations.
*
* @returns VBox status code.
*
* @param pDevIns The device instance.
* @param pvUser User argument - ignored.
* @param Port Port number used for the IN operation.
* @param u32 The value to output.
* @param cb The value size in bytes.
*/
PDMBOTHCBDECL(int) pitIOPortSpeakerWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
{
if (cb == 1)
{
}
return VINF_SUCCESS;
}
/**
* Saves a state of the programmable interval timer device.
*
* @returns VBox status code.
* @param pDevIns The device instance.
* @param pSSMHandle The handle to save the state to.
*/
{
unsigned i;
{
}
}
/**
* Loads a saved programmable interval timer device state.
*
* @returns VBox status code.
* @param pDevIns The device instance.
* @param pSSMHandle The handle to the saved state.
* @param u32Version The data unit version number.
*/
static DECLCALLBACK(int) pitLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSMHandle, uint32_t u32Version)
{
unsigned i;
if (u32Version != PIT_SAVED_STATE_VERSION)
{
}
}
/**
* Device timer callback function.
*
* @param pDevIns Device instance of the device which registered the timer.
* @param pTimer The timer handle.
*/
{
}
/**
* Relocation notification.
*
* @returns VBox status.
* @param pDevIns The device instance data.
* @param offDelta The delta relative to the old address.
*/
{
unsigned i;
LogFlow(("pitRelocate: \n"));
{
}
}
/** @todo remove this! */
/**
* Reset notification.
*
* @returns VBox status.
* @param pDevIns The device instance data.
*/
{
unsigned i;
LogFlow(("pitReset: \n"));
{
#if 1 /* Set everything back to virgin state. (might not be strictly correct) */
s->latched_count = 0;
s->count_latched = 0;
s->status_latched = 0;
s->status = 0;
s->read_state = 0;
s->write_state = 0;
s->write_latch = 0;
s->rw_mode = 0;
s->bcd = 0;
#endif
s->mode = 3;
s->gate = (i != 2);
pit_load_count(s, 0);
}
/** @todo remove when #1589 is resolved. */
}
/**
* Info handler, device version.
*
* @param pDevIns Device instance which registered the info.
* @param pHlp Callback functions for doing output.
* @param pszArgs Argument string. Optional and specific to the handler.
*/
{
unsigned i;
{
"PIT (i8254) channel %d status: irq=%#x\n"
" count=%08x" " latched_count=%04x count_latched=%02x\n"
" status=%02x status_latched=%02x read_state=%02x\n"
" write_state=%02x write_latch=%02x rw_mode=%02x\n"
" mode=%02x bcd=%02x gate=%02x\n"
" count_load_time=%016RX64 next_transition_time=%016RX64\n"
" u64ReloadTS=%016RX64 u64NextTS=%016RX64\n"
,
}
}
/**
* Construct a device instance for a VM.
*
* @returns VBox status.
* @param pDevIns The device instance data.
* If the registration structure is needed, pDevIns->pDevReg points to it.
* @param iInstance Instance number. Use this to figure out which registers and such to use.
* The device number is also found in pDevIns->iInstance, but since it's
* likely to be freqently used PDM passes it as parameter.
* @param pCfgHandle Configuration node handle for the device. Use this to obtain the configuration
* of the device instance. It's also found in pDevIns->pCfgHandle, but like
* iInstance it's expected to be used a bit in this function.
*/
{
int rc;
bool fSpeaker;
bool fGCEnabled;
bool fR0Enabled;
unsigned i;
/*
* Validate configuration.
*/
/*
* Init the data.
*/
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
u8Irq = 0;
else if (VBOX_FAILURE(rc))
N_("Configuration error: Querying \"Irq\" as a uint8_t failed"));
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
u16Base = 0x40;
else if (VBOX_FAILURE(rc))
N_("Configuration error: Querying \"Base\" as a uint16_t failed"));
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
fSpeaker = true;
else if (VBOX_FAILURE(rc))
N_("Configuration error: Querying \"SpeakerEnabled\" as a bool failed"));
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
fGCEnabled = true;
else if (VBOX_FAILURE(rc))
N_("Configuration error: Querying \"GCEnabled\" as a bool failed"));
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
fR0Enabled = true;
else if (VBOX_FAILURE(rc))
N_("Configuration error: failed to read R0Enabled as boolean"));
{
}
/*
* Create timer, register I/O Ports and save state.
*/
rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, pitTimer, "i8254 Programmable Interval Timer",
#else
rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL, pitTimer, "i8254 Programmable Interval Timer",
#endif
if (VBOX_FAILURE(rc))
{
return rc;
}
rc = PDMDevHlpIOPortRegister(pDevIns, u16Base, 4, NULL, pitIOPortWrite, pitIOPortRead, NULL, NULL, "i8254 Programmable Interval Timer");
if (VBOX_FAILURE(rc))
return rc;
if (fGCEnabled)
{
rc = PDMDevHlpIOPortRegisterGC(pDevIns, u16Base, 4, 0, "pitIOPortWrite", "pitIOPortRead", NULL, NULL, "i8254 Programmable Interval Timer");
if (VBOX_FAILURE(rc))
return rc;
}
if (fR0Enabled)
{
rc = PDMDevHlpIOPortRegisterR0(pDevIns, u16Base, 4, 0, "pitIOPortWrite", "pitIOPortRead", NULL, NULL, "i8254 Programmable Interval Timer");
if (VBOX_FAILURE(rc))
return rc;
}
if (fSpeaker)
{
rc = PDMDevHlpIOPortRegister(pDevIns, 0x61, 1, NULL, pitIOPortSpeakerWrite, pitIOPortSpeakerRead, NULL, NULL, "PC Speaker");
if (VBOX_FAILURE(rc))
return rc;
if (fGCEnabled)
{
rc = PDMDevHlpIOPortRegisterGC(pDevIns, 0x61, 1, 0, NULL, "pitIOPortSpeakerRead", NULL, NULL, "PC Speaker");
if (VBOX_FAILURE(rc))
return rc;
}
}
rc = PDMDevHlpSSMRegister(pDevIns, pDevIns->pDevReg->szDeviceName, iInstance, PIT_SAVED_STATE_VERSION, sizeof(*pData),
if (VBOX_FAILURE(rc))
return rc;
#ifndef VBOX_WITH_VIRTUAL_SYNC_TIMERS
/*
* Calculate max catchup time.
*/
= pData->channels[2].i64MaxCatchupTS = -TMTimerFromMilli(pData->channels[0].CTXSUFF(pTimer), 1000*60*2); /* 2 min */
#endif
/*
* Initialize the device state.
*/
/*
* Register statistics and debug info.
*/
PDMDevHlpSTAMRegister(pDevIns, &pData->StatPITIrq, STAMTYPE_COUNTER, "/TM/PIT/Irq", STAMUNIT_OCCURENCES, "The number of times a timer interrupt was triggered.");
PDMDevHlpSTAMRegister(pDevIns, &pData->StatPITHandler, STAMTYPE_PROFILE, "/TM/PIT/Handler", STAMUNIT_TICKS_PER_CALL, "Profiling timer callback handler.");
#ifndef VBOX_WITH_VIRTUAL_SYNC_TIMERS
PDMDevHlpSTAMRegister(pDevIns, &pData->StatPITCatchup, STAMTYPE_COUNTER, "/TM/PIT/Catchup", STAMUNIT_OCCURENCES, "The number of times we lagged too far behind.");
PDMDevHlpSTAMRegister(pDevIns, &pData->StatPITGiveup, STAMTYPE_COUNTER, "/TM/PIT/Giveup", STAMUNIT_OCCURENCES, "The number of times we lagged so far behind that we simply gave up.");
#endif
return VINF_SUCCESS;
}
/**
* The device registration structure.
*/
const PDMDEVREG g_DeviceI8254 =
{
/* u32Version */
/* szDeviceName */
"i8254",
/* szGCMod */
"VBoxDDGC.gc",
/* szR0Mod */
"VBoxDDR0.r0",
/* pszDescription */
"i8254 Programmable Interval Timer And Dummy Speaker",
/* fFlags */
PDM_DEVREG_FLAGS_HOST_BITS_DEFAULT | PDM_DEVREG_FLAGS_GUEST_BITS_32_64 | PDM_DEVREG_FLAGS_PAE36 | PDM_DEVREG_FLAGS_GC | PDM_DEVREG_FLAGS_R0,
/* fClass */
/* cMaxInstances */
1,
/* cbInstance */
sizeof(PITState),
/* pfnConstruct */
/* pfnDestruct */
NULL,
/* pfnRelocate */
/* pfnIOCtl */
NULL,
/* pfnPowerOn */
NULL,
/* pfnReset */
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnAttach */
NULL,
/* pfnDetach */
NULL,
/* pfnQueryInterface. */
};
#endif /* IN_RING3 */
#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */