[NTVDM]
[reactos.git] / subsystems / ntvdm / emulator.c
index c0915ce..ab2fabe 100644 (file)
 #define NDEBUG
 
 #include "emulator.h"
-#include "bios.h"
-#include "dos.h"
-#include "vga.h"
-#include "pic.h"
-#include "ps2.h"
-#include "timer.h"
+#include "callback.h"
+
+#include "clock.h"
+#include "bios/rom.h"
+#include "hardware/cmos.h"
+#include "hardware/pic.h"
+#include "hardware/ps2.h"
+#include "hardware/speaker.h"
+#include "hardware/timer.h"
+#include "hardware/vga.h"
+
+#include "bop.h"
+#include "vddsup.h"
+#include "io.h"
+
+#include <isvbop.h>
 
 /* PRIVATE VARIABLES **********************************************************/
 
-#ifndef NEW_EMULATOR
-softx86_ctx EmulatorContext;
-softx87_ctx FpuEmulatorContext;
-#else
-EMULATOR_CONTEXT EmulatorContext;
-#endif
+FAST486_STATE EmulatorContext;
+BOOLEAN CpuSimulate = FALSE;
 
-static BOOLEAN A20Line = FALSE;
+/* No more than 'MaxCpuCallLevel' recursive CPU calls are allowed */
+const static INT MaxCpuCallLevel = 32;
+static INT CpuCallLevel = 0;
 
-/* PRIVATE FUNCTIONS **********************************************************/
+LPVOID  BaseAddress = NULL;
+BOOLEAN VdmRunning  = TRUE;
+
+static BOOLEAN A20Line   = FALSE;
+static BYTE Port61hState = 0x00;
+
+static HANDLE InputThread = NULL;
+
+LPCWSTR ExceptionName[] =
+{
+    L"Division By Zero",
+    L"Debug",
+    L"Unexpected Error",
+    L"Breakpoint",
+    L"Integer Overflow",
+    L"Bound Range Exceeded",
+    L"Invalid Opcode",
+    L"FPU Not Available"
+};
+
+/* BOP Identifiers */
+#define BOP_DEBUGGER    0x56    // Break into the debugger from a 16-bit app
 
-#ifndef NEW_EMULATOR
+/* PRIVATE FUNCTIONS **********************************************************/
 
-static VOID EmulatorReadMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID WINAPI EmulatorReadMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
-    UNREFERENCED_PARAMETER(Context);
+    UNREFERENCED_PARAMETER(State);
+
+    // BIG HACK!!!! To make BIOS images working correctly,
+    // until Aleksander rewrites memory management!!
+    if (Address >= 0xFFFFFFF0) Address -= 0xFFF00000;
 
     /* If the A20 line is disabled, mask bit 20 */
     if (!A20Line) Address &= ~(1 << 20);
@@ -43,24 +76,33 @@ static VOID EmulatorReadMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT S
     /* Make sure the requested address is valid */
     if ((Address + Size) >= MAX_ADDRESS) return;
 
-    /* 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 */
+    /*
+     * Check if we are going to read the VGA memory and
+     * copy it into the virtual address space if needed.
+     */
     if (((Address + Size) >= VgaGetVideoBaseAddress())
         && (Address < VgaGetVideoLimitAddress()))
     {
         DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
-        LPBYTE VgaBuffer = &Buffer[VgaAddress - Address];
+        DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
+                           - VgaAddress + 1;
+        LPBYTE DestBuffer = (LPBYTE)REAL_TO_PHYS(VgaAddress);
 
         /* Read from the VGA memory */
-        VgaReadMemory(VgaAddress, VgaBuffer, Size);
+        VgaReadMemory(VgaAddress, DestBuffer, ActualSize);
     }
+
+    /* Read the data from the virtual address space and store it in the buffer */
+    RtlCopyMemory(Buffer, REAL_TO_PHYS(Address), Size);
 }
 
-static VOID EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID WINAPI EmulatorWriteMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
-    UNREFERENCED_PARAMETER(Context);
+    UNREFERENCED_PARAMETER(State);
+
+    // BIG HACK!!!! To make BIOS images working correctly,
+    // until Aleksander rewrites memory management!!
+    if (Address >= 0xFFFFFFF0) Address -= 0xFFF00000;
 
     /* If the A20 line is disabled, mask bit 20 */
     if (!A20Line) Address &= ~(1 << 20);
@@ -72,509 +114,397 @@ static VOID EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT
     if ((Address + Size) >= ROM_AREA_START && (Address < ROM_AREA_END)) return;
 
     /* Read the data from the buffer and store it in the virtual address space */
-    RtlCopyMemory((LPVOID)((ULONG_PTR)BaseAddress + Address), Buffer, Size);
+    RtlCopyMemory(REAL_TO_PHYS(Address), Buffer, Size);
 
-    /* Check if we modified the console video memory */
+    /*
+     * Check if we modified the VGA memory.
+     */
     if (((Address + Size) >= VgaGetVideoBaseAddress())
         && (Address < VgaGetVideoLimitAddress()))
     {
         DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
-        LPBYTE VgaBuffer = &Buffer[VgaAddress - Address];
+        DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
+                           - VgaAddress + 1;
+        LPBYTE SrcBuffer = (LPBYTE)REAL_TO_PHYS(VgaAddress);
 
         /* Write to the VGA memory */
-        VgaWriteMemory(VgaAddress, VgaBuffer, Size);
+        VgaWriteMemory(VgaAddress, SrcBuffer, ActualSize);
     }
 }
 
-static VOID EmulatorReadIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+UCHAR WINAPI EmulatorIntAcknowledge(PFAST486_STATE State)
 {
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Size);
+    UNREFERENCED_PARAMETER(State);
 
-    switch (Address)
-    {
-        case PIC_MASTER_CMD:
-        case PIC_SLAVE_CMD:
-        {
-            *Buffer = PicReadCommand(Address);
-            break;
-        }
-
-        case PIC_MASTER_DATA:
-        case PIC_SLAVE_DATA:
-        {
-            *Buffer = PicReadData(Address);
-            break;
-        }
-
-        case PIT_DATA_PORT(0):
-        case PIT_DATA_PORT(1):
-        case PIT_DATA_PORT(2):
-        {
-            *Buffer = PitReadData(Address - PIT_DATA_PORT(0));
-            break;
-        }
-
-        case PS2_CONTROL_PORT:
-        {
-            *Buffer = KeyboardReadStatus();
-            break;
-        }
-
-        case PS2_DATA_PORT:
-        {
-            *Buffer = 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:
-        {
-            *Buffer = VgaReadPort(Address);
-            break;
-        }
-
-        default:
-        {
-            DPRINT1("Read from unknown port: 0x%X\n", Address);
-        }
-    }
+    /* Get the interrupt number from the PIC */
+    return PicGetInterrupt();
 }
 
-static VOID EmulatorWriteIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID EmulatorException(BYTE ExceptionNumber, LPWORD Stack)
 {
-    BYTE Byte = *Buffer;
-
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Size);
+    WORD CodeSegment, InstructionPointer;
+    PBYTE Opcode;
+
+    ASSERT(ExceptionNumber < 8);
+
+    /* Get the CS:IP */
+    InstructionPointer = Stack[STACK_IP];
+    CodeSegment = Stack[STACK_CS];
+    Opcode = (PBYTE)SEG_OFF_TO_PTR(CodeSegment, InstructionPointer);
+
+    /* Display a message to the user */
+    DisplayMessage(L"Exception: %s occured at %04X:%04X\n"
+                   L"Opcode: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",
+                   ExceptionName[ExceptionNumber],
+                   CodeSegment,
+                   InstructionPointer,
+                   Opcode[0],
+                   Opcode[1],
+                   Opcode[2],
+                   Opcode[3],
+                   Opcode[4],
+                   Opcode[5],
+                   Opcode[6],
+                   Opcode[7],
+                   Opcode[8],
+                   Opcode[9]);
+
+    /* Stop the VDM */
+    VdmRunning = FALSE;
+    return;
+}
 
-    switch (Address)
-    {
-        case PIT_COMMAND_PORT:
-        {
-            PitWriteCommand(Byte);
-            break;
-        }
-
-        case PIT_DATA_PORT(0):
-        case PIT_DATA_PORT(1):
-        case PIT_DATA_PORT(2):
-        {
-            PitWriteData(Address - PIT_DATA_PORT(0), Byte);
-            break;
-        }
-
-        case PIC_MASTER_CMD:
-        case PIC_SLAVE_CMD:
-        {
-            PicWriteCommand(Address, Byte);
-            break;
-        }
-
-        case PIC_MASTER_DATA:
-        case PIC_SLAVE_DATA:
-        {
-            PicWriteData(Address, Byte);
-            break;
-        }
-
-        case PS2_CONTROL_PORT:
-        {
-            KeyboardWriteCommand(Byte);
-            break;
-        }
-
-        case PS2_DATA_PORT:
-        {
-            KeyboardWriteData(Byte);
-            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:
-        {
-            VgaWritePort(Address, Byte);
-            break;
-        }
-
-        default:
-        {
-            DPRINT1("Write to unknown port: 0x%X\n", Address);
-        }
-    }
+// FIXME: This function assumes 16-bit mode!!!
+VOID EmulatorExecute(WORD Segment, WORD Offset)
+{
+    /* Tell Fast486 to move the instruction pointer */
+    Fast486ExecuteAt(&EmulatorContext, Segment, Offset);
 }
 
-static VOID EmulatorBop(WORD Code)
+VOID EmulatorStep(VOID)
 {
-    WORD StackSegment, StackPointer, CodeSegment, InstructionPointer;
-    BYTE IntNum;
-    LPWORD Stack;
-
-    /* Get the SS:SP */
-#ifndef NEW_EMULATOR
-    StackSegment = EmulatorContext.state->segment_reg[SX86_SREG_SS].val;
-    StackPointer = EmulatorContext.state->general_reg[SX86_REG_SP].val;
-#else
-    StackSegment = EmulatorContext.Registers[EMULATOR_REG_SS].LowWord;
-    StackPointer = EmulatorContext.Registers[EMULATOR_REG_SP].LowWord;
-#endif
+    /* Dump the state for debugging purposes */
+    // Fast486DumpState(&EmulatorContext);
 
-    /* Get the stack */
-    Stack = (LPWORD)((ULONG_PTR)BaseAddress + TO_LINEAR(StackSegment, StackPointer));
+    /* Execute the next instruction */
+    Fast486StepInto(&EmulatorContext);
+}
 
-    if (Code == EMULATOR_INT_BOP)
+VOID EmulatorSimulate(VOID)
+{
+    if (CpuCallLevel > MaxCpuCallLevel)
     {
-        /* Get the interrupt number */
-        IntNum = LOBYTE(Stack[STACK_INT_NUM]);
-
-        /* Get the CS:IP */
-        InstructionPointer = Stack[STACK_IP];
-        CodeSegment = Stack[STACK_CS];
-
-        /* Check if this was an exception */
-        if (IntNum < 8)
-        {
-            /* Display a message to the user */
-            DisplayMessage(L"Exception: %s occured at %04X:%04X",
-                           ExceptionName[IntNum],
-                           CodeSegment,
-                           InstructionPointer);
-
-            /* Stop the VDM */
-            VdmRunning = FALSE;
-            return;
-        }
-
-        /* Check if this was an PIC IRQ */
-        if (IntNum >= BIOS_PIC_MASTER_INT && IntNum < BIOS_PIC_MASTER_INT + 8)
-        {
-            /* It was an IRQ from the master PIC */
-            BiosHandleIrq(IntNum - BIOS_PIC_MASTER_INT, Stack);
-            return;
-        }
-        else if (IntNum >= BIOS_PIC_SLAVE_INT && IntNum < BIOS_PIC_SLAVE_INT + 8)
-        {
-            /* It was an IRQ from the slave PIC */
-            BiosHandleIrq(IntNum - BIOS_PIC_SLAVE_INT + 8, Stack);
-            return;
-        }
-
-        switch (IntNum)
-        {
-            case BIOS_VIDEO_INTERRUPT:
-            {
-                /* This is the video BIOS interrupt, call the BIOS */
-                BiosVideoService(Stack);
-                break;
-            }
-            case BIOS_EQUIPMENT_INTERRUPT:
-            {
-                /* This is the BIOS "get equipment" command, call the BIOS */
-                BiosEquipmentService(Stack);
-                break;
-            }
-            case BIOS_KBD_INTERRUPT:
-            {
-                /* This is the keyboard BIOS interrupt, call the BIOS */
-                BiosKeyboardService(Stack);
-                break;
-            }
-            case BIOS_TIME_INTERRUPT:
-            {
-                /* This is the time BIOS interrupt, call the BIOS */
-                BiosTimeService(Stack);
-                break;
-            }
-            case BIOS_SYS_TIMER_INTERRUPT:
-            {
-                /* BIOS timer update */
-                BiosSystemTimerInterrupt(Stack);
-                break;
-            }
-            case 0x20:
-            {
-                DosInt20h(Stack);
-                break;
-            }
-            case 0x21:
-            {
-                DosInt21h(Stack);
-                break;
-            }
-            case 0x23:
-            {
-                DosBreakInterrupt(Stack);
-                break;
-            }
-            default:
-            {
-                DPRINT1("Unhandled interrupt: 0x%02X\n", IntNum);
-                break;
-            }
-        }
+        DisplayMessage(L"Too many CPU levels of recursion (%d, expected maximum %d)",
+                       CpuCallLevel, MaxCpuCallLevel);
+
+        /* Stop the VDM */
+        VdmRunning = FALSE;
+        return;
     }
-}
+    CpuCallLevel++;
 
-static VOID EmulatorSoftwareInt(PVOID Context, BYTE Number)
-{
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Number);
+    CpuSimulate = TRUE;
+    while (VdmRunning && CpuSimulate) ClockUpdate();
+
+    CpuCallLevel--;
+    if (CpuCallLevel < 0) CpuCallLevel = 0;
 
-    /* Do nothing */
+    /* This takes into account for reentrance */
+    CpuSimulate = TRUE;
 }
 
-static VOID EmulatorHardwareInt(PVOID Context, BYTE Number)
+VOID EmulatorUnsimulate(VOID)
 {
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Number);
-
-    /* Do nothing */
+    /* Stop simulation */
+    CpuSimulate = FALSE;
 }
 
-static VOID EmulatorHardwareIntAck(PVOID Context, BYTE Number)
+VOID EmulatorInterrupt(BYTE Number)
 {
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Number);
-
-    /* Do nothing */
+    /* Call the Fast486 API */
+    Fast486Interrupt(&EmulatorContext, Number);
 }
 
-#endif
-
-/* PUBLIC FUNCTIONS ***********************************************************/
-
-BOOLEAN EmulatorInitialize()
+VOID EmulatorInterruptSignal(VOID)
 {
-    /* Allocate memory for the 16-bit address space */
-    BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
-    if (BaseAddress == NULL) return FALSE;
-
-#ifndef NEW_EMULATOR
-    /* Initialize the softx86 CPU emulator */
-    if (!softx86_init(&EmulatorContext, SX86_CPULEVEL_80286))
-    {
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
-        return FALSE;
-    }
-
-    /* Initialize the softx87 FPU emulator*/
-    if(!softx87_init(&FpuEmulatorContext, SX87_FPULEVEL_8087))
-    {
-        softx86_free(&EmulatorContext);
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
-        return FALSE;
-    }
-
-    /* Set memory read/write callbacks */
-    EmulatorContext.callbacks->on_read_memory = EmulatorReadMemory;
-    EmulatorContext.callbacks->on_write_memory = EmulatorWriteMemory;
-
-    /* Set MMIO read/write callbacks */
-    EmulatorContext.callbacks->on_read_io = EmulatorReadIo;
-    EmulatorContext.callbacks->on_write_io = EmulatorWriteIo;
-
-    /* Set interrupt callbacks */
-    EmulatorContext.callbacks->on_sw_int = EmulatorSoftwareInt;
-    EmulatorContext.callbacks->on_hw_int = EmulatorHardwareInt;
-    EmulatorContext.callbacks->on_hw_int_ack = EmulatorHardwareIntAck;
-
-    /* Connect the emulated FPU to the emulated CPU */
-    softx87_connect_to_CPU(&EmulatorContext, &FpuEmulatorContext);
-#else
-    // TODO: NOT IMPLEMENTED
-#endif
+    /* Call the Fast486 API */
+    Fast486InterruptSignal(&EmulatorContext);
+}
 
-    /* Enable interrupts */
-    EmulatorSetFlag(EMULATOR_FLAG_IF);
+VOID EmulatorSetA20(BOOLEAN Enabled)
+{
+    A20Line = Enabled;
+}
 
-    return TRUE;
+VOID WINAPI EmulatorDebugBreakBop(LPWORD Stack)
+{
+    DPRINT1("NTVDM: BOP_DEBUGGER\n");
+    DebugBreak();
 }
 
-VOID EmulatorSetStack(WORD Segment, WORD Offset)
+VOID WINAPI EmulatorUnsimulateBop(LPWORD Stack)
 {
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_set_stack_ptr(&EmulatorContext, Segment, Offset);
-#else
-    // TODO: NOT IMPLEMENTED
-#endif
+    EmulatorUnsimulate();
 }
 
-VOID EmulatorExecute(WORD Segment, WORD Offset)
+static BYTE WINAPI Port61hRead(ULONG Port)
 {
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_set_instruction_ptr(&EmulatorContext, Segment, Offset);
-#else
-    // TODO: NOT IMPLEMENTED
-#endif
+    return Port61hState;
 }
 
-VOID EmulatorInterrupt(BYTE Number)
+static VOID WINAPI Port61hWrite(ULONG Port, BYTE Data)
 {
-    LPDWORD IntVecTable = (LPDWORD)((ULONG_PTR)BaseAddress);
-    UINT Segment, Offset;
+    // BOOLEAN SpeakerChange = FALSE;
+    BYTE OldPort61hState = Port61hState;
 
-    /* Get the segment and offset */
-    Segment = HIWORD(IntVecTable[Number]);
-    Offset = LOWORD(IntVecTable[Number]);
+    /* Only the four lowest bytes can be written */
+    Port61hState = (Port61hState & 0xF0) | (Data & 0x0F);
 
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_make_simple_interrupt_call(&EmulatorContext, &Segment, &Offset);
-#else
-    UNREFERENCED_PARAMETER(Segment);
-    UNREFERENCED_PARAMETER(Offset);
-    // TODO: NOT IMPLEMENTED
-#endif
+    if ((OldPort61hState ^ Port61hState) & 0x01)
+    {
+        DPRINT("PIT 2 Gate %s\n", Port61hState & 0x01 ? "on" : "off");
+        // SpeakerChange = TRUE;
+    }
+
+    PitSetGate(2, !!(Port61hState & 0x01));
+
+    if ((OldPort61hState ^ Port61hState) & 0x02)
+    {
+        /* There were some change for the speaker... */
+        DPRINT("Speaker %s\n", Port61hState & 0x02 ? "on" : "off");
+        // SpeakerChange = TRUE;
+    }
+    // if (SpeakerChange) SpeakerChange();
+    SpeakerChange();
 }
 
-VOID EmulatorExternalInterrupt(BYTE Number)
+static VOID WINAPI PitChan0Out(LPVOID Param, BOOLEAN State)
 {
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_ext_hw_signal(&EmulatorContext, Number);
-#endif
+    if (State)
+    {
+        DPRINT("PicInterruptRequest\n");
+        PicInterruptRequest(0); // Raise IRQ 0
+    }
+    // else < Lower IRQ 0 >
 }
 
-ULONG EmulatorGetRegister(ULONG Register)
+static VOID WINAPI PitChan1Out(LPVOID Param, BOOLEAN State)
 {
-#ifndef NEW_EMULATOR
-    if (Register < EMULATOR_REG_ES)
+#if 0
+    if (State)
     {
-        return EmulatorContext.state->general_reg[Register].val;
+        /* Set bit 4 of Port 61h */
+        Port61hState |= 1 << 4;
     }
     else
     {
-        return EmulatorContext.state->segment_reg[Register - EMULATOR_REG_ES].val;
+        /* Clear bit 4 of Port 61h */
+        Port61hState &= ~(1 << 4);
     }
 #else
-    return EmulatorContext.Registers[Register].Long;
+    Port61hState = (Port61hState & 0xEF) | (State << 4);
 #endif
 }
 
-VOID EmulatorSetRegister(ULONG Register, ULONG Value)
+static VOID WINAPI PitChan2Out(LPVOID Param, BOOLEAN State)
 {
-#ifndef NEW_EMULATOR
-    if (Register < EMULATOR_REG_CS)
+    // BYTE OldPort61hState = Port61hState;
+
+#if 0
+    if (State)
     {
-        EmulatorContext.state->general_reg[Register].val = Value;
+        /* Set bit 5 of Port 61h */
+        Port61hState |= 1 << 5;
     }
     else
     {
-        EmulatorContext.state->segment_reg[Register - EMULATOR_REG_ES].val = (WORD)Value;
+        /* Clear bit 5 of Port 61h */
+        Port61hState &= ~(1 << 5);
     }
 #else
-    // TODO: NOT IMPLEMENTED
+    Port61hState = (Port61hState & 0xDF) | (State << 5);
 #endif
+    DPRINT("Speaker PIT out\n");
+    // if ((OldPort61hState ^ Port61hState) & 0x20)
+        // SpeakerChange();
 }
 
-BOOLEAN EmulatorGetFlag(ULONG Flag)
+/* PUBLIC FUNCTIONS ***********************************************************/
+
+DWORD WINAPI PumpConsoleInput(LPVOID Parameter);
+
+BOOLEAN EmulatorInitialize(HANDLE ConsoleInput, HANDLE ConsoleOutput)
 {
-#ifndef NEW_EMULATOR
-    return (EmulatorContext.state->reg_flags.val & Flag) ? TRUE : FALSE;
-#else
-    return (EmulatorContext.Flags.Long & Flag) ? TRUE : FALSE;
-#endif
+    /* Allocate memory for the 16-bit address space */
+    BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
+    if (BaseAddress == NULL)
+    {
+        wprintf(L"FATAL: Failed to allocate VDM memory.\n");
+        return FALSE;
+    }
+
+    /* Initialize I/O ports */
+    /* Initialize RAM */
+
+    /* Initialize the internal clock */
+    if (!ClockInitialize())
+    {
+        wprintf(L"FATAL: Failed to initialize the clock\n");
+        return FALSE;
+    }
+
+    /* Initialize the CPU */
+    Fast486Initialize(&EmulatorContext,
+                      EmulatorReadMemory,
+                      EmulatorWriteMemory,
+                      EmulatorReadIo,
+                      EmulatorWriteIo,
+                      NULL,
+                      EmulatorBiosOperation,
+                      EmulatorIntAcknowledge,
+                      NULL /* TODO: Use a TLB */);
+
+    /* Initialize DMA */
+
+    /* Initialize the PIC, the PIT, the CMOS and the PC Speaker */
+    PicInitialize();
+    PitInitialize();
+    CmosInitialize();
+    SpeakerInitialize();
+
+    /* Set output functions */
+    PitSetOutFunction(0, NULL, PitChan0Out);
+    PitSetOutFunction(1, NULL, PitChan1Out);
+    PitSetOutFunction(2, NULL, PitChan2Out);
+
+    /* Register the I/O Ports */
+    RegisterIoPort(CONTROL_SYSTEM_PORT61H, Port61hRead, Port61hWrite);
+
+    /* Initialize the PS2 port */
+    PS2Initialize(ConsoleInput);
+
+    /* Set the console input mode */
+    // FIXME: Activate ENABLE_WINDOW_INPUT when we will want to perform actions
+    // upon console window events (screen buffer resize, ...).
+    SetConsoleMode(ConsoleInput, ENABLE_PROCESSED_INPUT /* | ENABLE_WINDOW_INPUT */);
+
+    /* Start the input thread */
+    InputThread = CreateThread(NULL, 0, &PumpConsoleInput, ConsoleInput, 0, NULL);
+    // if (InputThread == NULL) return FALSE;
+
+    /* Initialize the VGA */
+    // if (!VgaInitialize(ConsoleOutput)) return FALSE;
+    VgaInitialize(ConsoleOutput);
+
+    /* Initialize the software callback system and register the emulator BOPs */
+    InitializeCallbacks();
+    RegisterBop(BOP_DEBUGGER  , EmulatorDebugBreakBop);
+    RegisterBop(BOP_UNSIMULATE, EmulatorUnsimulateBop);
+
+    /* Initialize VDD support */
+    VDDSupInitialize();
+
+    return TRUE;
 }
 
-VOID EmulatorSetFlag(ULONG Flag)
+VOID EmulatorCleanup(VOID)
 {
-#ifndef NEW_EMULATOR
-    EmulatorContext.state->reg_flags.val |= Flag;
-#else
-    EmulatorContext.Flags.Long |= Flag;
-#endif
+    VgaCleanup();
+
+    /* Close the input thread handle */
+    if (InputThread != NULL) CloseHandle(InputThread);
+    InputThread = NULL;
+
+    PS2Cleanup();
+
+    SpeakerCleanup();
+    CmosCleanup();
+    // PitCleanup();
+    // PicCleanup();
+
+    // Fast486Cleanup();
+
+    /* Free the memory allocated for the 16-bit address space */
+    if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
 }
 
-VOID EmulatorClearFlag(ULONG Flag)
+
+
+VOID
+WINAPI
+VDDSimulate16(VOID)
 {
-#ifndef NEW_EMULATOR
-    EmulatorContext.state->reg_flags.val &= ~Flag;
-#else
-    EmulatorContext.Flags.Long &= ~Flag;
-#endif
+    EmulatorSimulate();
 }
 
-VOID EmulatorStep(VOID)
+VOID
+WINAPI
+VDDTerminateVDM(VOID)
 {
-    LPWORD Instruction;
-
-#ifndef NEW_EMULATOR
-    /* Print the current position - useful for debugging */
-    DPRINT("Executing at CS:IP = %04X:%04X\n",
-           EmulatorGetRegister(EMULATOR_REG_CS),
-           EmulatorContext.state->reg_ip);
-
-    Instruction = (LPWORD)((ULONG_PTR)BaseAddress
-                           + TO_LINEAR(EmulatorGetRegister(EMULATOR_REG_CS),
-                           EmulatorContext.state->reg_ip));
+    /* Stop the VDM */
+    VdmRunning = FALSE;
+}
 
-    /* Check for the BIOS operation (BOP) sequence */
-    if (Instruction[0] == EMULATOR_BOP)
-    {
-        /* Skip the opcodes */
-        EmulatorContext.state->reg_ip += 4;
+PBYTE
+WINAPI
+Sim32pGetVDMPointer(IN ULONG   Address,
+                    IN BOOLEAN ProtectedMode)
+{
+    // FIXME
+    UNREFERENCED_PARAMETER(ProtectedMode);
+
+    /*
+     * HIWORD(Address) == Segment  (if ProtectedMode == FALSE)
+     *                 or Selector (if ProtectedMode == TRUE )
+     * LOWORD(Address) == Offset
+     */
+    return (PBYTE)FAR_POINTER(Address);
+}
 
-        // HACK: Refresh the display because the called function may wait.
-        VgaRefreshDisplay();
+PBYTE
+WINAPI
+MGetVdmPointer(IN ULONG   Address,
+               IN ULONG   Size,
+               IN BOOLEAN ProtectedMode)
+{
+    UNREFERENCED_PARAMETER(Size);
+    return Sim32pGetVDMPointer(Address, ProtectedMode);
+}
 
-        /* Call the BOP handler */
-        EmulatorBop(Instruction[1]);
-    }
+PVOID
+WINAPI
+VdmMapFlat(IN USHORT   Segment,
+           IN ULONG    Offset,
+           IN VDM_MODE Mode)
+{
+    // FIXME
+    UNREFERENCED_PARAMETER(Mode);
 
-    /* Call the softx86 API */
-    if (!softx86_step(&EmulatorContext))
-    {
-        /* Invalid opcode */
-        EmulatorInterrupt(EMULATOR_EXCEPTION_INVALID_OPCODE);
-    }
-#else
-    // TODO: NOT IMPLEMENTED
-#endif
+    return SEG_OFF_TO_PTR(Segment, Offset);
 }
 
-VOID EmulatorCleanup(VOID)
+BOOL
+WINAPI
+VdmFlushCache(IN USHORT   Segment,
+              IN ULONG    Offset,
+              IN ULONG    Size,
+              IN VDM_MODE Mode)
 {
-#ifndef NEW_EMULATOR
-    /* Free the softx86 CPU and FPU emulator */
-    softx87_free(&FpuEmulatorContext);
-    softx86_free(&EmulatorContext);
-#endif
-
-    /* Free the memory allocated for the 16-bit address space */
-    if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
+    // FIXME
+    UNIMPLEMENTED;
+    return TRUE;
 }
 
-VOID EmulatorSetA20(BOOLEAN Enabled)
+BOOL
+WINAPI
+VdmUnmapFlat(IN USHORT   Segment,
+             IN ULONG    Offset,
+             IN PVOID    Buffer,
+             IN VDM_MODE Mode)
 {
-    A20Line = Enabled;
+    // FIXME
+    UNIMPLEMENTED;
+    return TRUE;
 }
 
 /* EOF */