[FAST486][NTVDM]
[reactos.git] / subsystems / ntvdm / emulator.c
index 313067c..1b5f4df 100644 (file)
@@ -8,33 +8,56 @@
 
 /* INCLUDES *******************************************************************/
 
-#include "ntvdm.h"
-#include <softx86/softx86.h>
-#include <softx86/softx87.h>
+#define NDEBUG
 
-softx86_ctx EmulatorContext;
-softx87_ctx FpuEmulatorContext;
+#include "emulator.h"
+#include "bios.h"
+#include "dos.h"
+#include "vga.h"
+#include "pic.h"
+#include "ps2.h"
+#include "timer.h"
 
-static VOID EmulatorReadMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+/* PRIVATE VARIABLES **********************************************************/
+
+FAST486_STATE EmulatorContext;
+
+static BOOLEAN A20Line = FALSE;
+
+/* PRIVATE FUNCTIONS **********************************************************/
+
+static VOID WINAPI EmulatorReadMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
+    UNREFERENCED_PARAMETER(State);
+
+    /* If the A20 line is disabled, mask bit 20 */
+    if (!A20Line) Address &= ~(1 << 20);
+
     /* Make sure the requested address is valid */
     if ((Address + Size) >= MAX_ADDRESS) return;
 
-    /* Are we reading some of the console video memory? */
-    if (((Address + Size) >= CONSOLE_VIDEO_MEM_START)
-        && (Address < CONSOLE_VIDEO_MEM_END))
-    {
-        /* Call the VDM BIOS to update the video memory */
-        BiosUpdateConsole(max(Address, CONSOLE_VIDEO_MEM_START),
-                          min(Address + Size, CONSOLE_VIDEO_MEM_END));
-    }
-
     /* Read the data from the virtual address space and store it in the buffer */
     RtlCopyMemory(Buffer, (LPVOID)((ULONG_PTR)BaseAddress + Address), Size);
+
+    /* Check if we modified the console video memory */
+    if (((Address + Size) >= VgaGetVideoBaseAddress())
+        && (Address < VgaGetVideoLimitAddress()))
+    {
+        DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
+        LPBYTE VgaBuffer = (LPBYTE)((ULONG_PTR)Buffer + VgaAddress - Address);
+
+        /* Read from the VGA memory */
+        VgaReadMemory(VgaAddress, VgaBuffer, Size);
+    }
 }
 
-static VOID EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+static VOID WINAPI EmulatorWriteMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
+    UNREFERENCED_PARAMETER(State);
+
+    /* If the A20 line is disabled, mask bit 20 */
+    if (!A20Line) Address &= ~(1 << 20);
+
     /* Make sure the requested address is valid */
     if ((Address + Size) >= MAX_ADDRESS) return;
 
@@ -45,208 +68,312 @@ static VOID EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT
     RtlCopyMemory((LPVOID)((ULONG_PTR)BaseAddress + Address), Buffer, Size);
 
     /* Check if we modified the console video memory */
-    if (((Address + Size) >= CONSOLE_VIDEO_MEM_START)
-        && (Address < CONSOLE_VIDEO_MEM_END))
+    if (((Address + Size) >= VgaGetVideoBaseAddress())
+        && (Address < VgaGetVideoLimitAddress()))
     {
-        /* Call the VDM BIOS to update the screen */
-        BiosUpdateConsole(max(Address, CONSOLE_VIDEO_MEM_START),
-                          min(Address + Size, CONSOLE_VIDEO_MEM_END));
+        DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
+        LPBYTE VgaBuffer = (LPBYTE)((ULONG_PTR)Buffer + VgaAddress - Address);
+
+        /* Write to the VGA memory */
+        VgaWriteMemory(VgaAddress, VgaBuffer, Size);
     }
 }
 
-static VOID EmulatorReadIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+static VOID WINAPI EmulatorReadIo(PFAST486_STATE State, ULONG Port, PVOID Buffer, ULONG Size)
 {
-    // TODO: NOT IMPLEMENTED!
-}
+    LPBYTE Address = (LPBYTE)Buffer;
 
-static VOID EmulatorWriteIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
-{
-    // TODO: NOT IMPLEMENTED!
+    UNREFERENCED_PARAMETER(State);
+    UNREFERENCED_PARAMETER(Size);
+
+    switch (Port)
+    {
+        case PIC_MASTER_CMD:
+        case PIC_SLAVE_CMD:
+        {
+            *Address = PicReadCommand(Port);
+            break;
+        }
+
+        case PIC_MASTER_DATA:
+        case PIC_SLAVE_DATA:
+        {
+            *Address = PicReadData(Port);
+            break;
+        }
+
+        case PIT_DATA_PORT(0):
+        case PIT_DATA_PORT(1):
+        case PIT_DATA_PORT(2):
+        {
+            *Address = PitReadData(Port - PIT_DATA_PORT(0));
+            break;
+        }
+
+        case PS2_CONTROL_PORT:
+        {
+            *Address = KeyboardReadStatus();
+            break;
+        }
+
+        case PS2_DATA_PORT:
+        {
+            *Address = KeyboardReadData();
+            break;
+        }
+
+        case VGA_AC_WRITE:
+        case VGA_AC_READ:
+        case VGA_SEQ_INDEX:
+        case VGA_SEQ_DATA:
+        case VGA_DAC_READ_INDEX:
+        case VGA_DAC_WRITE_INDEX:
+        case VGA_DAC_DATA:
+        case VGA_MISC_READ:
+        case VGA_MISC_WRITE:
+        case VGA_CRTC_INDEX:
+        case VGA_CRTC_DATA:
+        case VGA_GC_INDEX:
+        case VGA_GC_DATA:
+        case VGA_STAT_MONO:
+        case VGA_STAT_COLOR:
+        {
+            *Address = VgaReadPort(Port);
+            break;
+        }
+
+        default:
+        {
+            DPRINT1("Read from unknown port: 0x%X\n", Port);
+        }
+    }
 }
 
-static VOID EmulatorSoftwareInt(PVOID Context, BYTE Number)
+static VOID WINAPI EmulatorWriteIo(PFAST486_STATE State, ULONG Port, PVOID Buffer, ULONG Size)
 {
-    WORD StackSegment, StackPointer, CodeSegment, InstructionPointer;
-    BYTE IntNum;
+    BYTE Byte = *(LPBYTE)Buffer;
+
+    UNREFERENCED_PARAMETER(State);
+    UNREFERENCED_PARAMETER(Size);
 
-    /* Check if this is the special interrupt */
-    if (Number == SPECIAL_INT_NUM)
+    switch (Port)
     {
-        /* Get the SS:SP */
-        StackSegment = EmulatorContext.state->segment_reg[SX86_SREG_SS].val;
-        StackPointer = EmulatorContext.state->general_reg[SX86_REG_SP].val;
+        case PIT_COMMAND_PORT:
+        {
+            PitWriteCommand(Byte);
+            break;
+        }
 
-        /* Get the interrupt number */
-        IntNum = *(LPBYTE)((ULONG_PTR)BaseAddress + TO_LINEAR(StackSegment, StackPointer));
+        case PIT_DATA_PORT(0):
+        case PIT_DATA_PORT(1):
+        case PIT_DATA_PORT(2):
+        {
+            PitWriteData(Port - PIT_DATA_PORT(0), Byte);
+            break;
+        }
 
-        /* Move the stack pointer forward one word to skip the interrupt number */
-        StackPointer += sizeof(WORD);
+        case PIC_MASTER_CMD:
+        case PIC_SLAVE_CMD:
+        {
+            PicWriteCommand(Port, Byte);
+            break;
+        }
 
-        /* Get the CS:IP */
-        InstructionPointer = *(LPWORD)((ULONG_PTR)BaseAddress
-                             + TO_LINEAR(StackSegment, StackPointer));
-        CodeSegment = *(LPWORD)((ULONG_PTR)BaseAddress
-                      + TO_LINEAR(StackSegment, StackPointer + sizeof(WORD)));
+        case PIC_MASTER_DATA:
+        case PIC_SLAVE_DATA:
+        {
+            PicWriteData(Port, Byte);
+            break;
+        }
+
+        case PS2_CONTROL_PORT:
+        {
+            KeyboardWriteCommand(Byte);
+            break;
+        }
+
+        case PS2_DATA_PORT:
+        {
+            KeyboardWriteData(Byte);
+            break;
+        }
 
-        /* Check if this was an exception */
-        if (IntNum < 8)
+        case VGA_AC_WRITE:
+        case VGA_AC_READ:
+        case VGA_SEQ_INDEX:
+        case VGA_SEQ_DATA:
+        case VGA_DAC_READ_INDEX:
+        case VGA_DAC_WRITE_INDEX:
+        case VGA_DAC_DATA:
+        case VGA_MISC_READ:
+        case VGA_MISC_WRITE:
+        case VGA_CRTC_INDEX:
+        case VGA_CRTC_DATA:
+        case VGA_GC_INDEX:
+        case VGA_GC_DATA:
+        case VGA_STAT_MONO:
+        case VGA_STAT_COLOR:
         {
-            /* Display a message to the user */
-            DisplayMessage(L"Exception: %s occured at %04X:%04X",
-                           ExceptionName[IntNum],
-                           CodeSegment,
-                           InstructionPointer);
-
-            /* Stop the VDM */
-            VdmRunning = FALSE;
-            return;
+            VgaWritePort(Port, Byte);
+            break;
         }
 
-        switch (IntNum)
+        default:
         {
-            case VIDEO_BIOS_INTERRUPT:
-            {
-                /* This is the video BIOS interrupt, call the BIOS */
-                BiosVideoService();
-                break;
-            }
-            case 0x20:
-            {
-                DosInt20h(CodeSegment);
-                break;
-            }
-            case 0x21:
-            {
-                DosInt21h(CodeSegment);
-                break;
-            }
-            case 0x23:
-            {
-                DosBreakInterrupt();
-                break;
-            }
+            DPRINT1("Write to unknown port: 0x%X\n", Port);
         }
     }
 }
 
-/* PUBLIC FUNCTIONS ***********************************************************/
-
-BOOLEAN EmulatorInitialize()
+VOID WINAPI ControlBop(LPWORD Stack);
+static VOID WINAPI EmulatorBiosOperation(PFAST486_STATE State, UCHAR BopCode)
 {
-    /* Allocate memory for the 16-bit address space */
-    BaseAddress = HeapAlloc(GetProcessHeap(), 0, MAX_ADDRESS);
-    if (BaseAddress == NULL) return FALSE;
+    WORD StackSegment, StackPointer;
+    LPWORD Stack;
 
-    /* Initialize the softx86 CPU emulator */
-    if (!softx86_init(&EmulatorContext, SX86_CPULEVEL_80186))
-    {
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
-        return FALSE;
-    }
+    /* Get the SS:SP */
+    StackSegment = State->SegmentRegs[FAST486_REG_SS].Selector;
+    StackPointer = State->GeneralRegs[FAST486_REG_ESP].LowWord;
+
+    /* Get the stack */
+    Stack = (LPWORD)SEG_OFF_TO_PTR(StackSegment, StackPointer);
 
-    /* Initialize the softx87 FPU emulator*/
-    if(!softx87_init(&FpuEmulatorContext, SX87_FPULEVEL_8087))
+    switch (BopCode)
     {
-        softx86_free(&EmulatorContext);
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
-        return FALSE;
+        case EMULATOR_INT_BOP:
+            ControlBop(Stack);
+            break;
+
+        default:
+            DPRINT1("Invalid BOP code %u\n", BopCode);
+            break;
     }
+}
 
-    /* Set memory read/write callbacks */
-    EmulatorContext.callbacks->on_read_memory = EmulatorReadMemory;
-    EmulatorContext.callbacks->on_write_memory = EmulatorWriteMemory;
+static VOID WINAPI EmulatorIdle(PFAST486_STATE State)
+{
+}
+
+static UCHAR WINAPI EmulatorIntAcknowledge(PFAST486_STATE State)
+{
+    UNREFERENCED_PARAMETER(State);
+
+    /* Get the interrupt number from the PIC */
+    return PicGetInterrupt();
+}
+
+/* PUBLIC FUNCTIONS ***********************************************************/
+
+BOOLEAN EmulatorInitialize()
+{
+    /* Allocate memory for the 16-bit address space */
+    BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
+    if (BaseAddress == NULL) return FALSE;
 
-    /* Set MMIO read/write callbacks */
-    EmulatorContext.callbacks->on_read_io = EmulatorReadIo;
-    EmulatorContext.callbacks->on_write_io = EmulatorWriteIo;
+    /* Set the callbacks */
+    EmulatorContext.MemReadCallback  = EmulatorReadMemory;
+    EmulatorContext.MemWriteCallback = EmulatorWriteMemory;
+    EmulatorContext.IoReadCallback   = EmulatorReadIo;  // Must be != NULL
+    EmulatorContext.IoWriteCallback  = EmulatorWriteIo; // Must be != NULL
+    EmulatorContext.IdleCallback     = EmulatorIdle;    // Must be != NULL
+    EmulatorContext.BopCallback      = EmulatorBiosOperation;
+    EmulatorContext.IntAckCallback   = EmulatorIntAcknowledge;
 
-    /* Set interrupt callbacks */
-    EmulatorContext.callbacks->on_sw_int = EmulatorSoftwareInt;
+    /* Reset the CPU */
+    Fast486Reset(&EmulatorContext);
 
-    /* Connect the emulated FPU to the emulated CPU */
-    softx87_connect_to_CPU(&EmulatorContext, &FpuEmulatorContext);
+    /* Enable interrupts */
+    EmulatorSetFlag(EMULATOR_FLAG_IF);
 
     return TRUE;
 }
 
-VOID EmulatorSetStack(WORD Segment, WORD Offset)
+VOID EmulatorSetStack(WORD Segment, DWORD Offset)
 {
-    /* Call the softx86 API */
-    softx86_set_stack_ptr(&EmulatorContext, Segment, Offset);
+    Fast486SetStack(&EmulatorContext, Segment, Offset);
 }
 
+// FIXME: This function assumes 16-bit mode!!!
 VOID EmulatorExecute(WORD Segment, WORD Offset)
 {
-    /* Call the softx86 API */
-    softx86_set_instruction_ptr(&EmulatorContext, Segment, Offset);
+    /* Tell Fast486 to move the instruction pointer */
+    Fast486ExecuteAt(&EmulatorContext, Segment, Offset);
 }
 
 VOID EmulatorInterrupt(BYTE Number)
 {
-    LPWORD IntVecTable = (LPWORD)((ULONG_PTR)BaseAddress);
-    UINT Segment, Offset;
-
-    /* Get the segment and offset */
-    Segment = HIWORD(IntVecTable[Number]);
-    Offset = LOWORD(IntVecTable[Number]);
+    /* Call the Fast486 API */
+    Fast486Interrupt(&EmulatorContext, Number);
+}
 
-    /* Call the softx86 API */
-    softx86_make_simple_interrupt_call(&EmulatorContext, &Segment, &Offset);
+VOID EmulatorInterruptSignal(VOID)
+{
+    /* Call the Fast486 API */
+    Fast486InterruptSignal(&EmulatorContext);
 }
 
 ULONG EmulatorGetRegister(ULONG Register)
 {
-    if (Register < EMULATOR_REG_CS)
+    if (Register < EMULATOR_REG_ES)
     {
-        return EmulatorContext.state->general_reg[Register].val;
+        return EmulatorContext.GeneralRegs[Register].Long;
     }
     else
     {
-        return EmulatorContext.state->segment_reg[(Register >> 3) - 1].val;
+        return EmulatorContext.SegmentRegs[Register - EMULATOR_REG_ES].Selector;
     }
 }
 
 VOID EmulatorSetRegister(ULONG Register, ULONG Value)
 {
-    if (Register < EMULATOR_REG_CS)
+    if (Register < EMULATOR_REG_ES)
     {
-        EmulatorContext.state->general_reg[Register].val = Value;
+        EmulatorContext.GeneralRegs[Register].Long = Value;
     }
     else
     {
-        EmulatorContext.state->segment_reg[(Register >> 3) - 1].val = Value;
+        Fast486SetSegment(&EmulatorContext, Register - EMULATOR_REG_ES, (USHORT)Value);
     }
 }
 
+ULONG EmulatorGetProgramCounter(VOID)
+{
+    return EmulatorContext.InstPtr.Long;
+}
+
 BOOLEAN EmulatorGetFlag(ULONG Flag)
 {
-    return (EmulatorContext.state->reg_flags.val & Flag);
+    return (EmulatorContext.Flags.Long & Flag) ? TRUE : FALSE;
 }
 
 VOID EmulatorSetFlag(ULONG Flag)
 {
-    EmulatorContext.state->reg_flags.val |= Flag;
+    EmulatorContext.Flags.Long |= Flag;
 }
 
 VOID EmulatorClearFlag(ULONG Flag)
 {
-    EmulatorContext.state->reg_flags.val &= ~Flag;
+    EmulatorContext.Flags.Long &= ~Flag;
 }
 
-VOID EmulatorStep()
+VOID EmulatorStep(VOID)
 {
-    /* Call the softx86 API */
-    softx86_step(&EmulatorContext);
+    /* Dump the state for debugging purposes */
+    // Fast486DumpState(&EmulatorContext);
+
+    /* Execute the next instruction */
+    Fast486StepInto(&EmulatorContext);
 }
 
-VOID EmulatorCleanup()
+VOID EmulatorCleanup(VOID)
 {
     /* Free the memory allocated for the 16-bit address space */
     if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
+}
 
-    /* Free the softx86 CPU and FPU emulator */
-    softx86_free(&EmulatorContext);
-    softx87_free(&FpuEmulatorContext);
+VOID EmulatorSetA20(BOOLEAN Enabled)
+{
+    A20Line = Enabled;
 }
 
 /* EOF */