VirtualBox

source: vbox/trunk/src/recompiler/VBoxRecompiler.c@ 4337

Last change on this file since 4337 was 4245, checked in by vboxsync, 17 years ago

Predict success on out/in.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 169.3 KB
Line 
1/* $Id: VBoxRecompiler.c 4245 2007-08-20 18:43:30Z vboxsync $ */
2/** @file
3 * VBox Recompiler - QEMU.
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_REM
23#include "vl.h"
24#include "exec-all.h"
25
26#include <VBox/rem.h>
27#include <VBox/vmapi.h>
28#include <VBox/tm.h>
29#include <VBox/ssm.h>
30#include <VBox/em.h>
31#include <VBox/trpm.h>
32#include <VBox/iom.h>
33#include <VBox/mm.h>
34#include <VBox/pgm.h>
35#include <VBox/pdm.h>
36#include <VBox/dbgf.h>
37#include <VBox/dbg.h>
38#include <VBox/hwaccm.h>
39#include <VBox/patm.h>
40#include <VBox/csam.h>
41#include "REMInternal.h"
42#include <VBox/vm.h>
43#include <VBox/param.h>
44#include <VBox/err.h>
45
46#include <VBox/log.h>
47#include <iprt/semaphore.h>
48#include <iprt/asm.h>
49#include <iprt/assert.h>
50#include <iprt/thread.h>
51#include <iprt/string.h>
52
53/* Don't wanna include everything. */
54extern void cpu_x86_update_cr3(CPUX86State *env, target_ulong new_cr3);
55extern void cpu_x86_update_cr0(CPUX86State *env, uint32_t new_cr0);
56extern void cpu_x86_update_cr4(CPUX86State *env, uint32_t new_cr4);
57extern void tlb_flush_page(CPUX86State *env, uint32_t addr);
58extern void tlb_flush(CPUState *env, int flush_global);
59extern void sync_seg(CPUX86State *env1, int seg_reg, int selector);
60extern void sync_ldtr(CPUX86State *env1, int selector);
61extern int sync_tr(CPUX86State *env1, int selector);
62
63#ifdef VBOX_STRICT
64unsigned long get_phys_page_offset(target_ulong addr);
65#endif
66
67
68/*******************************************************************************
69* Defined Constants And Macros *
70*******************************************************************************/
71
72/** Copy 80-bit fpu register at pSrc to pDst.
73 * This is probably faster than *calling* memcpy.
74 */
75#define REM_COPY_FPU_REG(pDst, pSrc) \
76 do { *(PX86FPUMMX)(pDst) = *(const X86FPUMMX *)(pSrc); } while (0)
77
78
79/*******************************************************************************
80* Internal Functions *
81*******************************************************************************/
82static DECLCALLBACK(int) remR3Save(PVM pVM, PSSMHANDLE pSSM);
83static DECLCALLBACK(int) remR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
84static void remR3StateUpdate(PVM pVM);
85
86#if defined(PGM_DYNAMIC_RAM_ALLOC) && !defined(REM_PHYS_ADDR_IN_TLB)
87DECLINLINE(target_ulong) remR3HCVirt2GCPhysInlined(PVM pVM, void *addr);
88DECLINLINE(void *) remR3GCPhys2HCVirtInlined(PVM pVM, target_ulong addr);
89#endif
90
91static uint32_t remR3MMIOReadU8(void *pvVM, target_phys_addr_t GCPhys);
92static uint32_t remR3MMIOReadU16(void *pvVM, target_phys_addr_t GCPhys);
93static uint32_t remR3MMIOReadU32(void *pvVM, target_phys_addr_t GCPhys);
94static void remR3MMIOWriteU8(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32);
95static void remR3MMIOWriteU16(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32);
96static void remR3MMIOWriteU32(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32);
97
98static uint32_t remR3HandlerReadU8(void *pvVM, target_phys_addr_t GCPhys);
99static uint32_t remR3HandlerReadU16(void *pvVM, target_phys_addr_t GCPhys);
100static uint32_t remR3HandlerReadU32(void *pvVM, target_phys_addr_t GCPhys);
101static void remR3HandlerWriteU8(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32);
102static void remR3HandlerWriteU16(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32);
103static void remR3HandlerWriteU32(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32);
104
105
106/*******************************************************************************
107* Global Variables *
108*******************************************************************************/
109
110/** @todo Move stats to REM::s some rainy day we have nothing do to. */
111#ifdef VBOX_WITH_STATISTICS
112static STAMPROFILEADV gStatExecuteSingleInstr;
113static STAMPROFILEADV gStatCompilationQEmu;
114static STAMPROFILEADV gStatRunCodeQEmu;
115static STAMPROFILEADV gStatTotalTimeQEmu;
116static STAMPROFILEADV gStatTimers;
117static STAMPROFILEADV gStatTBLookup;
118static STAMPROFILEADV gStatIRQ;
119static STAMPROFILEADV gStatRawCheck;
120static STAMPROFILEADV gStatMemRead;
121static STAMPROFILEADV gStatMemWrite;
122#ifndef REM_PHYS_ADDR_IN_TLB
123static STAMPROFILEADV gStatMemReadHCPtr;
124static STAMPROFILEADV gStatMemWriteHCPtr;
125#endif
126#ifdef PGM_DYNAMIC_RAM_ALLOC
127static STAMPROFILE gStatGCPhys2HCVirt;
128static STAMPROFILE gStatHCVirt2GCPhys;
129#endif
130static STAMCOUNTER gStatCpuGetTSC;
131static STAMCOUNTER gStatRefuseTFInhibit;
132static STAMCOUNTER gStatRefuseVM86;
133static STAMCOUNTER gStatRefusePaging;
134static STAMCOUNTER gStatRefusePAE;
135static STAMCOUNTER gStatRefuseIOPLNot0;
136static STAMCOUNTER gStatRefuseIF0;
137static STAMCOUNTER gStatRefuseCode16;
138static STAMCOUNTER gStatRefuseWP0;
139static STAMCOUNTER gStatRefuseRing1or2;
140static STAMCOUNTER gStatRefuseCanExecute;
141static STAMCOUNTER gStatREMGDTChange;
142static STAMCOUNTER gStatREMIDTChange;
143static STAMCOUNTER gStatREMLDTRChange;
144static STAMCOUNTER gStatREMTRChange;
145static STAMCOUNTER gStatSelOutOfSync[6];
146static STAMCOUNTER gStatSelOutOfSyncStateBack[6];
147#endif
148
149/*
150 * Global stuff.
151 */
152
153/** MMIO read callbacks. */
154CPUReadMemoryFunc *g_apfnMMIORead[3] =
155{
156 remR3MMIOReadU8,
157 remR3MMIOReadU16,
158 remR3MMIOReadU32
159};
160
161/** MMIO write callbacks. */
162CPUWriteMemoryFunc *g_apfnMMIOWrite[3] =
163{
164 remR3MMIOWriteU8,
165 remR3MMIOWriteU16,
166 remR3MMIOWriteU32
167};
168
169/** Handler read callbacks. */
170CPUReadMemoryFunc *g_apfnHandlerRead[3] =
171{
172 remR3HandlerReadU8,
173 remR3HandlerReadU16,
174 remR3HandlerReadU32
175};
176
177/** Handler write callbacks. */
178CPUWriteMemoryFunc *g_apfnHandlerWrite[3] =
179{
180 remR3HandlerWriteU8,
181 remR3HandlerWriteU16,
182 remR3HandlerWriteU32
183};
184
185
186#if defined(VBOX_WITH_DEBUGGER) && !(defined(RT_OS_WINDWS) && defined(RT_ARCH_AMD64))
187/*
188 * Debugger commands.
189 */
190static DECLCALLBACK(int) remR3CmdDisasEnableStepping(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult);
191
192/** '.remstep' arguments. */
193static const DBGCVARDESC g_aArgRemStep[] =
194{
195 /* cTimesMin, cTimesMax, enmCategory, fFlags, pszName, pszDescription */
196 { 0, ~0, DBGCVAR_CAT_NUMBER, 0, "on/off", "Boolean value/mnemonic indicating the new state." },
197};
198
199/** Command descriptors. */
200static const DBGCCMD g_aCmds[] =
201{
202 {
203 .pszCmd ="remstep",
204 .cArgsMin = 0,
205 .cArgsMax = 1,
206 .paArgDescs = &g_aArgRemStep[0],
207 .cArgDescs = ELEMENTS(g_aArgRemStep),
208 .pResultDesc = NULL,
209 .fFlags = 0,
210 .pfnHandler = remR3CmdDisasEnableStepping,
211 .pszSyntax = "[on/off]",
212 .pszDescription = "Enable or disable the single stepping with logged disassembly. "
213 "If no arguments show the current state."
214 }
215};
216#endif
217
218
219/* Instantiate the structure signatures. */
220#define REM_STRUCT_OP 0
221#include "InnoTek/structs.h"
222
223
224
225/*******************************************************************************
226* Internal Functions *
227*******************************************************************************/
228static void remAbort(int rc, const char *pszTip);
229extern int testmath(void);
230
231/* Put them here to avoid unused variable warning. */
232AssertCompile(RT_SIZEOFMEMB(VM, rem.padding) >= RT_SIZEOFMEMB(VM, rem.s));
233#if !defined(IPRT_NO_CRT) && (defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS))
234AssertCompileMemberSize(REM, Env, REM_ENV_SIZE);
235#else
236AssertCompile(RT_SIZEOFMEMB(REM, Env) <= REM_ENV_SIZE);
237#endif
238
239
240/**
241 * Initializes the REM.
242 *
243 * @returns VBox status code.
244 * @param pVM The VM to operate on.
245 */
246REMR3DECL(int) REMR3Init(PVM pVM)
247{
248 uint32_t u32Dummy;
249 unsigned i;
250
251 /*
252 * Assert sanity.
253 */
254 AssertReleaseMsg(sizeof(pVM->rem.padding) >= sizeof(pVM->rem.s), ("%#x >= %#x; sizeof(Env)=%#x\n", sizeof(pVM->rem.padding), sizeof(pVM->rem.s), sizeof(pVM->rem.s.Env)));
255 AssertReleaseMsg(sizeof(pVM->rem.s.Env) <= REM_ENV_SIZE, ("%#x == %#x\n", sizeof(pVM->rem.s.Env), REM_ENV_SIZE));
256 AssertReleaseMsg(!(RT_OFFSETOF(VM, rem) & 31), ("off=%#x\n", RT_OFFSETOF(VM, rem)));
257#ifdef DEBUG
258 Assert(!testmath());
259#endif
260 ASSERT_STRUCT_TABLE(Misc);
261 ASSERT_STRUCT_TABLE(TLB);
262 ASSERT_STRUCT_TABLE(SegmentCache);
263 ASSERT_STRUCT_TABLE(XMMReg);
264 ASSERT_STRUCT_TABLE(MMXReg);
265 ASSERT_STRUCT_TABLE(float_status);
266 ASSERT_STRUCT_TABLE(float32u);
267 ASSERT_STRUCT_TABLE(float64u);
268 ASSERT_STRUCT_TABLE(floatx80u);
269 ASSERT_STRUCT_TABLE(CPUState);
270
271 /*
272 * Init some internal data members.
273 */
274 pVM->rem.s.offVM = RT_OFFSETOF(VM, rem.s);
275 pVM->rem.s.Env.pVM = pVM;
276#ifdef CPU_RAW_MODE_INIT
277 pVM->rem.s.state |= CPU_RAW_MODE_INIT;
278#endif
279
280 /* ctx. */
281 int rc = CPUMQueryGuestCtxPtr(pVM, &pVM->rem.s.pCtx);
282 if (VBOX_FAILURE(rc))
283 {
284 AssertMsgFailed(("Failed to obtain guest ctx pointer. rc=%Vrc\n", rc));
285 return rc;
286 }
287 AssertMsg(MMR3PhysGetRamSize(pVM) == 0, ("Init order have changed! REM depends on notification about ALL physical memory registrations\n"));
288
289 /* ignore all notifications */
290 pVM->rem.s.fIgnoreAll = true;
291
292 /*
293 * Init the recompiler.
294 */
295 if (!cpu_x86_init(&pVM->rem.s.Env))
296 {
297 AssertMsgFailed(("cpu_x86_init failed - impossible!\n"));
298 return VERR_GENERAL_FAILURE;
299 }
300 CPUMGetGuestCpuId(pVM, 1, &u32Dummy, &u32Dummy, &pVM->rem.s.Env.cpuid_ext_features, &pVM->rem.s.Env.cpuid_features);
301 CPUMGetGuestCpuId(pVM, 0x80000001, &u32Dummy, &u32Dummy, &u32Dummy, &pVM->rem.s.Env.cpuid_ext2_features);
302
303 /* allocate code buffer for single instruction emulation. */
304 pVM->rem.s.Env.cbCodeBuffer = 4096;
305 pVM->rem.s.Env.pvCodeBuffer = RTMemExecAlloc(pVM->rem.s.Env.cbCodeBuffer);
306 AssertMsgReturn(pVM->rem.s.Env.pvCodeBuffer, ("Failed to allocate code buffer!\n"), VERR_NO_MEMORY);
307
308 /* finally, set the cpu_single_env global. */
309 cpu_single_env = &pVM->rem.s.Env;
310
311 /* Nothing is pending by default */
312 pVM->rem.s.u32PendingInterrupt = REM_NO_PENDING_IRQ;
313
314 /*
315 * Register ram types.
316 */
317 pVM->rem.s.iMMIOMemType = cpu_register_io_memory(-1, g_apfnMMIORead, g_apfnMMIOWrite, pVM);
318 AssertReleaseMsg(pVM->rem.s.iMMIOMemType >= 0, ("pVM->rem.s.iMMIOMemType=%d\n", pVM->rem.s.iMMIOMemType));
319 pVM->rem.s.iHandlerMemType = cpu_register_io_memory(-1, g_apfnHandlerRead, g_apfnHandlerWrite, pVM);
320 AssertReleaseMsg(pVM->rem.s.iHandlerMemType >= 0, ("pVM->rem.s.iHandlerMemType=%d\n", pVM->rem.s.iHandlerMemType));
321 Log2(("REM: iMMIOMemType=%d iHandlerMemType=%d\n", pVM->rem.s.iMMIOMemType, pVM->rem.s.iHandlerMemType));
322
323 /* stop ignoring. */
324 pVM->rem.s.fIgnoreAll = false;
325
326 /*
327 * Register the saved state data unit.
328 */
329 rc = SSMR3RegisterInternal(pVM, "rem", 1, REM_SAVED_STATE_VERSION, sizeof(uint32_t) * 10,
330 NULL, remR3Save, NULL,
331 NULL, remR3Load, NULL);
332 if (VBOX_FAILURE(rc))
333 return rc;
334
335#if defined(VBOX_WITH_DEBUGGER) && !(defined(RT_OS_WINDOWS) && defined(RT_ARCH_AMD64))
336 /*
337 * Debugger commands.
338 */
339 static bool fRegisteredCmds = false;
340 if (!fRegisteredCmds)
341 {
342 int rc = DBGCRegisterCommands(&g_aCmds[0], ELEMENTS(g_aCmds));
343 if (VBOX_SUCCESS(rc))
344 fRegisteredCmds = true;
345 }
346#endif
347
348#ifdef VBOX_WITH_STATISTICS
349 /*
350 * Statistics.
351 */
352 STAM_REG(pVM, &gStatExecuteSingleInstr, STAMTYPE_PROFILE, "/PROF/REM/SingleInstr",STAMUNIT_TICKS_PER_CALL, "Profiling single instruction emulation.");
353 STAM_REG(pVM, &gStatCompilationQEmu, STAMTYPE_PROFILE, "/PROF/REM/Compile", STAMUNIT_TICKS_PER_CALL, "Profiling QEmu compilation.");
354 STAM_REG(pVM, &gStatRunCodeQEmu, STAMTYPE_PROFILE, "/PROF/REM/Runcode", STAMUNIT_TICKS_PER_CALL, "Profiling QEmu code execution.");
355 STAM_REG(pVM, &gStatTotalTimeQEmu, STAMTYPE_PROFILE, "/PROF/REM/Emulate", STAMUNIT_TICKS_PER_CALL, "Profiling code emulation.");
356 STAM_REG(pVM, &gStatTimers, STAMTYPE_PROFILE, "/PROF/REM/Timers", STAMUNIT_TICKS_PER_CALL, "Profiling timer scheduling.");
357 STAM_REG(pVM, &gStatTBLookup, STAMTYPE_PROFILE, "/PROF/REM/TBLookup", STAMUNIT_TICKS_PER_CALL, "Profiling timer scheduling.");
358 STAM_REG(pVM, &gStatIRQ, STAMTYPE_PROFILE, "/PROF/REM/IRQ", STAMUNIT_TICKS_PER_CALL, "Profiling timer scheduling.");
359 STAM_REG(pVM, &gStatRawCheck, STAMTYPE_PROFILE, "/PROF/REM/RawCheck", STAMUNIT_TICKS_PER_CALL, "Profiling timer scheduling.");
360 STAM_REG(pVM, &gStatMemRead, STAMTYPE_PROFILE, "/PROF/REM/MemRead", STAMUNIT_TICKS_PER_CALL, "Profiling memory access.");
361 STAM_REG(pVM, &gStatMemWrite, STAMTYPE_PROFILE, "/PROF/REM/MemWrite", STAMUNIT_TICKS_PER_CALL, "Profiling memory access.");
362#ifndef REM_PHYS_ADDR_IN_TLB
363 STAM_REG(pVM, &gStatMemReadHCPtr, STAMTYPE_PROFILE, "/PROF/REM/MemReadHCPtr", STAMUNIT_TICKS_PER_CALL, "Profiling memory access.");
364 STAM_REG(pVM, &gStatMemWriteHCPtr, STAMTYPE_PROFILE, "/PROF/REM/MemWriteHCPtr", STAMUNIT_TICKS_PER_CALL, "Profiling memory access.");
365#endif
366#ifdef PGM_DYNAMIC_RAM_ALLOC
367 STAM_REG(pVM, &gStatHCVirt2GCPhys, STAMTYPE_PROFILE, "/PROF/REM/HCVirt2GCPhys", STAMUNIT_TICKS_PER_CALL, "Profiling memory convertion.");
368 STAM_REG(pVM, &gStatGCPhys2HCVirt, STAMTYPE_PROFILE, "/PROF/REM/GCPhys2HCVirt", STAMUNIT_TICKS_PER_CALL, "Profiling memory convertion.");
369#endif
370
371 STAM_REG(pVM, &gStatCpuGetTSC, STAMTYPE_COUNTER, "/REM/CpuGetTSC", STAMUNIT_OCCURENCES, "cpu_get_tsc calls");
372
373 STAM_REG(pVM, &gStatRefuseTFInhibit, STAMTYPE_COUNTER, "/REM/Refuse/TFInibit", STAMUNIT_OCCURENCES, "Raw mode refused because of TF or irq inhibit");
374 STAM_REG(pVM, &gStatRefuseVM86, STAMTYPE_COUNTER, "/REM/Refuse/VM86", STAMUNIT_OCCURENCES, "Raw mode refused because of VM86");
375 STAM_REG(pVM, &gStatRefusePaging, STAMTYPE_COUNTER, "/REM/Refuse/Paging", STAMUNIT_OCCURENCES, "Raw mode refused because of disabled paging/pm");
376 STAM_REG(pVM, &gStatRefusePAE, STAMTYPE_COUNTER, "/REM/Refuse/PAE", STAMUNIT_OCCURENCES, "Raw mode refused because of PAE");
377 STAM_REG(pVM, &gStatRefuseIOPLNot0, STAMTYPE_COUNTER, "/REM/Refuse/IOPLNot0", STAMUNIT_OCCURENCES, "Raw mode refused because of IOPL != 0");
378 STAM_REG(pVM, &gStatRefuseIF0, STAMTYPE_COUNTER, "/REM/Refuse/IF0", STAMUNIT_OCCURENCES, "Raw mode refused because of IF=0");
379 STAM_REG(pVM, &gStatRefuseCode16, STAMTYPE_COUNTER, "/REM/Refuse/Code16", STAMUNIT_OCCURENCES, "Raw mode refused because of 16 bit code");
380 STAM_REG(pVM, &gStatRefuseWP0, STAMTYPE_COUNTER, "/REM/Refuse/WP0", STAMUNIT_OCCURENCES, "Raw mode refused because of WP=0");
381 STAM_REG(pVM, &gStatRefuseRing1or2, STAMTYPE_COUNTER, "/REM/Refuse/Ring1or2", STAMUNIT_OCCURENCES, "Raw mode refused because of ring 1/2 execution");
382 STAM_REG(pVM, &gStatRefuseCanExecute, STAMTYPE_COUNTER, "/REM/Refuse/CanExecuteRaw", STAMUNIT_OCCURENCES, "Raw mode refused because of cCanExecuteRaw");
383
384 STAM_REG(pVM, &gStatREMGDTChange, STAMTYPE_COUNTER, "/REM/Change/GDTBase", STAMUNIT_OCCURENCES, "GDT base changes");
385 STAM_REG(pVM, &gStatREMLDTRChange, STAMTYPE_COUNTER, "/REM/Change/LDTR", STAMUNIT_OCCURENCES, "LDTR changes");
386 STAM_REG(pVM, &gStatREMIDTChange, STAMTYPE_COUNTER, "/REM/Change/IDTBase", STAMUNIT_OCCURENCES, "IDT base changes");
387 STAM_REG(pVM, &gStatREMTRChange, STAMTYPE_COUNTER, "/REM/Change/TR", STAMUNIT_OCCURENCES, "TR selector changes");
388
389 STAM_REG(pVM, &gStatSelOutOfSync[0], STAMTYPE_COUNTER, "/REM/State/SelOutOfSync/ES", STAMUNIT_OCCURENCES, "ES out of sync");
390 STAM_REG(pVM, &gStatSelOutOfSync[1], STAMTYPE_COUNTER, "/REM/State/SelOutOfSync/CS", STAMUNIT_OCCURENCES, "CS out of sync");
391 STAM_REG(pVM, &gStatSelOutOfSync[2], STAMTYPE_COUNTER, "/REM/State/SelOutOfSync/SS", STAMUNIT_OCCURENCES, "SS out of sync");
392 STAM_REG(pVM, &gStatSelOutOfSync[3], STAMTYPE_COUNTER, "/REM/State/SelOutOfSync/DS", STAMUNIT_OCCURENCES, "DS out of sync");
393 STAM_REG(pVM, &gStatSelOutOfSync[4], STAMTYPE_COUNTER, "/REM/State/SelOutOfSync/FS", STAMUNIT_OCCURENCES, "FS out of sync");
394 STAM_REG(pVM, &gStatSelOutOfSync[5], STAMTYPE_COUNTER, "/REM/State/SelOutOfSync/GS", STAMUNIT_OCCURENCES, "GS out of sync");
395
396 STAM_REG(pVM, &gStatSelOutOfSyncStateBack[0], STAMTYPE_COUNTER, "/REM/StateBack/SelOutOfSync/ES", STAMUNIT_OCCURENCES, "ES out of sync");
397 STAM_REG(pVM, &gStatSelOutOfSyncStateBack[1], STAMTYPE_COUNTER, "/REM/StateBack/SelOutOfSync/CS", STAMUNIT_OCCURENCES, "CS out of sync");
398 STAM_REG(pVM, &gStatSelOutOfSyncStateBack[2], STAMTYPE_COUNTER, "/REM/StateBack/SelOutOfSync/SS", STAMUNIT_OCCURENCES, "SS out of sync");
399 STAM_REG(pVM, &gStatSelOutOfSyncStateBack[3], STAMTYPE_COUNTER, "/REM/StateBack/SelOutOfSync/DS", STAMUNIT_OCCURENCES, "DS out of sync");
400 STAM_REG(pVM, &gStatSelOutOfSyncStateBack[4], STAMTYPE_COUNTER, "/REM/StateBack/SelOutOfSync/FS", STAMUNIT_OCCURENCES, "FS out of sync");
401 STAM_REG(pVM, &gStatSelOutOfSyncStateBack[5], STAMTYPE_COUNTER, "/REM/StateBack/SelOutOfSync/GS", STAMUNIT_OCCURENCES, "GS out of sync");
402
403
404#endif
405
406#ifdef DEBUG_ALL_LOGGING
407 loglevel = ~0;
408#endif
409
410 return rc;
411}
412
413
414/**
415 * Terminates the REM.
416 *
417 * Termination means cleaning up and freeing all resources,
418 * the VM it self is at this point powered off or suspended.
419 *
420 * @returns VBox status code.
421 * @param pVM The VM to operate on.
422 */
423REMR3DECL(int) REMR3Term(PVM pVM)
424{
425 return VINF_SUCCESS;
426}
427
428
429/**
430 * The VM is being reset.
431 *
432 * For the REM component this means to call the cpu_reset() and
433 * reinitialize some state variables.
434 *
435 * @param pVM VM handle.
436 */
437REMR3DECL(void) REMR3Reset(PVM pVM)
438{
439 /*
440 * Reset the REM cpu.
441 */
442 pVM->rem.s.fIgnoreAll = true;
443 cpu_reset(&pVM->rem.s.Env);
444 pVM->rem.s.cInvalidatedPages = 0;
445 pVM->rem.s.fIgnoreAll = false;
446}
447
448
449/**
450 * Execute state save operation.
451 *
452 * @returns VBox status code.
453 * @param pVM VM Handle.
454 * @param pSSM SSM operation handle.
455 */
456static DECLCALLBACK(int) remR3Save(PVM pVM, PSSMHANDLE pSSM)
457{
458 LogFlow(("remR3Save:\n"));
459
460 /*
461 * Save the required CPU Env bits.
462 * (Not much because we're never in REM when doing the save.)
463 */
464 PREM pRem = &pVM->rem.s;
465 Assert(!pRem->fInREM);
466 SSMR3PutU32(pSSM, pRem->Env.hflags);
467 SSMR3PutMem(pSSM, &pRem->Env, RT_OFFSETOF(CPUState, jmp_env));
468 SSMR3PutU32(pSSM, ~0); /* separator */
469
470 /* Remember if we've entered raw mode (vital for ring 1 checks in e.g. iret emulation). */
471 SSMR3PutU32(pSSM, !!(pRem->Env.state & CPU_RAW_RING0));
472
473 /*
474 * Save the REM stuff.
475 */
476 SSMR3PutUInt(pSSM, pRem->cInvalidatedPages);
477 unsigned i;
478 for (i = 0; i < pRem->cInvalidatedPages; i++)
479 SSMR3PutGCPtr(pSSM, pRem->aGCPtrInvalidatedPages[i]);
480
481 SSMR3PutUInt(pSSM, pVM->rem.s.u32PendingInterrupt);
482
483 return SSMR3PutU32(pSSM, ~0); /* terminator */
484}
485
486
487/**
488 * Execute state load operation.
489 *
490 * @returns VBox status code.
491 * @param pVM VM Handle.
492 * @param pSSM SSM operation handle.
493 * @param u32Version Data layout version.
494 */
495static DECLCALLBACK(int) remR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
496{
497 uint32_t u32Dummy;
498 uint32_t fRawRing0 = false;
499 LogFlow(("remR3Load:\n"));
500
501 /*
502 * Validate version.
503 */
504 if (u32Version != REM_SAVED_STATE_VERSION)
505 {
506 Log(("remR3Load: Invalid version u32Version=%d!\n", u32Version));
507 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
508 }
509
510 /*
511 * Do a reset to be on the safe side...
512 */
513 REMR3Reset(pVM);
514
515 /*
516 * Ignore all ignorable notifications.
517 * (Not doing this will cause serious trouble.)
518 */
519 pVM->rem.s.fIgnoreAll = true;
520
521 /*
522 * Load the required CPU Env bits.
523 * (Not much because we're never in REM when doing the save.)
524 */
525 PREM pRem = &pVM->rem.s;
526 Assert(!pRem->fInREM);
527 SSMR3GetU32(pSSM, &pRem->Env.hflags);
528 SSMR3GetMem(pSSM, &pRem->Env, RT_OFFSETOF(CPUState, jmp_env));
529 uint32_t u32Sep;
530 int rc = SSMR3GetU32(pSSM, &u32Sep); /* separator */
531 if (VBOX_FAILURE(rc))
532 return rc;
533 if (u32Sep != ~0)
534 {
535 AssertMsgFailed(("u32Sep=%#x\n", u32Sep));
536 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
537 }
538
539 /* Remember if we've entered raw mode (vital for ring 1 checks in e.g. iret emulation). */
540 SSMR3GetUInt(pSSM, &fRawRing0);
541 if (fRawRing0)
542 pRem->Env.state |= CPU_RAW_RING0;
543
544 /*
545 * Load the REM stuff.
546 */
547 rc = SSMR3GetUInt(pSSM, &pRem->cInvalidatedPages);
548 if (VBOX_FAILURE(rc))
549 return rc;
550 if (pRem->cInvalidatedPages > ELEMENTS(pRem->aGCPtrInvalidatedPages))
551 {
552 AssertMsgFailed(("cInvalidatedPages=%#x\n", pRem->cInvalidatedPages));
553 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
554 }
555 unsigned i;
556 for (i = 0; i < pRem->cInvalidatedPages; i++)
557 SSMR3GetGCPtr(pSSM, &pRem->aGCPtrInvalidatedPages[i]);
558
559 rc = SSMR3GetUInt(pSSM, &pVM->rem.s.u32PendingInterrupt);
560 if (VBOX_FAILURE(rc))
561 return rc;
562
563 /* check the terminator. */
564 rc = SSMR3GetU32(pSSM, &u32Sep);
565 if (VBOX_FAILURE(rc))
566 return rc;
567 if (u32Sep != ~0)
568 {
569 AssertMsgFailed(("u32Sep=%#x (term)\n", u32Sep));
570 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
571 }
572
573 /*
574 * Get the CPUID features.
575 */
576 CPUMGetGuestCpuId(pVM, 1, &u32Dummy, &u32Dummy, &pVM->rem.s.Env.cpuid_ext_features, &pVM->rem.s.Env.cpuid_features);
577 CPUMGetGuestCpuId(pVM, 0x80000001, &u32Dummy, &u32Dummy, &u32Dummy, &pVM->rem.s.Env.cpuid_ext2_features);
578
579 /*
580 * Sync the Load Flush the TLB
581 */
582 tlb_flush(&pRem->Env, 1);
583
584#if 0 /** @todo r=bird: this doesn't make sense. WHY? */
585 /*
586 * Clear all lazy flags (only FPU sync for now).
587 */
588 CPUMGetAndClearFPUUsedREM(pVM);
589#endif
590
591 /*
592 * Stop ignoring ignornable notifications.
593 */
594 pVM->rem.s.fIgnoreAll = false;
595
596 return VINF_SUCCESS;
597}
598
599
600
601#undef LOG_GROUP
602#define LOG_GROUP LOG_GROUP_REM_RUN
603
604/**
605 * Single steps an instruction in recompiled mode.
606 *
607 * Before calling this function the REM state needs to be in sync with
608 * the VM. Call REMR3State() to perform the sync. It's only necessary
609 * (and permitted) to sync at the first call to REMR3Step()/REMR3Run()
610 * and after calling REMR3StateBack().
611 *
612 * @returns VBox status code.
613 *
614 * @param pVM VM Handle.
615 */
616REMR3DECL(int) REMR3Step(PVM pVM)
617{
618 /*
619 * Lock the REM - we don't wanna have anyone interrupting us
620 * while stepping - and enabled single stepping. We also ignore
621 * pending interrupts and suchlike.
622 */
623 int interrupt_request = pVM->rem.s.Env.interrupt_request;
624 Assert(!(interrupt_request & ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_EXIT | CPU_INTERRUPT_EXITTB | CPU_INTERRUPT_TIMER | CPU_INTERRUPT_EXTERNAL_HARD | CPU_INTERRUPT_EXTERNAL_EXIT | CPU_INTERRUPT_EXTERNAL_TIMER)));
625 pVM->rem.s.Env.interrupt_request = 0;
626 cpu_single_step(&pVM->rem.s.Env, 1);
627
628 /*
629 * If we're standing at a breakpoint, that have to be disabled before we start stepping.
630 */
631 RTGCPTR GCPtrPC = pVM->rem.s.Env.eip + pVM->rem.s.Env.segs[R_CS].base;
632 bool fBp = !cpu_breakpoint_remove(&pVM->rem.s.Env, GCPtrPC);
633
634 /*
635 * Execute and handle the return code.
636 * We execute without enabling the cpu tick, so on success we'll
637 * just flip it on and off to make sure it moves
638 */
639 int rc = cpu_exec(&pVM->rem.s.Env);
640 if (rc == EXCP_DEBUG)
641 {
642 TMCpuTickResume(pVM);
643 TMCpuTickPause(pVM);
644 TMVirtualResume(pVM);
645 TMVirtualPause(pVM);
646 rc = VINF_EM_DBG_STEPPED;
647 }
648 else
649 {
650 AssertMsgFailed(("Damn, this shouldn't happen! cpu_exec returned %d while singlestepping\n", rc));
651 switch (rc)
652 {
653 case EXCP_INTERRUPT: rc = VINF_SUCCESS; break;
654 case EXCP_HLT:
655 case EXCP_HALTED: rc = VINF_EM_HALT; break;
656 case EXCP_RC:
657 rc = pVM->rem.s.rc;
658 pVM->rem.s.rc = VERR_INTERNAL_ERROR;
659 break;
660 default:
661 AssertReleaseMsgFailed(("This really shouldn't happen, rc=%d!\n", rc));
662 rc = VERR_INTERNAL_ERROR;
663 break;
664 }
665 }
666
667 /*
668 * Restore the stuff we changed to prevent interruption.
669 * Unlock the REM.
670 */
671 if (fBp)
672 {
673 int rc2 = cpu_breakpoint_insert(&pVM->rem.s.Env, GCPtrPC);
674 Assert(rc2 == 0); NOREF(rc2);
675 }
676 cpu_single_step(&pVM->rem.s.Env, 0);
677 pVM->rem.s.Env.interrupt_request = interrupt_request;
678
679 return rc;
680}
681
682
683/**
684 * Set a breakpoint using the REM facilities.
685 *
686 * @returns VBox status code.
687 * @param pVM The VM handle.
688 * @param Address The breakpoint address.
689 * @thread The emulation thread.
690 */
691REMR3DECL(int) REMR3BreakpointSet(PVM pVM, RTGCUINTPTR Address)
692{
693 VM_ASSERT_EMT(pVM);
694 if (!cpu_breakpoint_insert(&pVM->rem.s.Env, Address))
695 {
696 LogFlow(("REMR3BreakpointSet: Address=%VGv\n", Address));
697 return VINF_SUCCESS;
698 }
699 LogFlow(("REMR3BreakpointSet: Address=%VGv - failed!\n", Address));
700 return VERR_REM_NO_MORE_BP_SLOTS;
701}
702
703
704/**
705 * Clears a breakpoint set by REMR3BreakpointSet().
706 *
707 * @returns VBox status code.
708 * @param pVM The VM handle.
709 * @param Address The breakpoint address.
710 * @thread The emulation thread.
711 */
712REMR3DECL(int) REMR3BreakpointClear(PVM pVM, RTGCUINTPTR Address)
713{
714 VM_ASSERT_EMT(pVM);
715 if (!cpu_breakpoint_remove(&pVM->rem.s.Env, Address))
716 {
717 LogFlow(("REMR3BreakpointClear: Address=%VGv\n", Address));
718 return VINF_SUCCESS;
719 }
720 LogFlow(("REMR3BreakpointClear: Address=%VGv - not found!\n", Address));
721 return VERR_REM_BP_NOT_FOUND;
722}
723
724
725/**
726 * Emulate an instruction.
727 *
728 * This function executes one instruction without letting anyone
729 * interrupt it. This is intended for being called while being in
730 * raw mode and thus will take care of all the state syncing between
731 * REM and the rest.
732 *
733 * @returns VBox status code.
734 * @param pVM VM handle.
735 */
736REMR3DECL(int) REMR3EmulateInstruction(PVM pVM)
737{
738 Log2(("REMR3EmulateInstruction: (cs:eip=%04x:%08x)\n", pVM->rem.s.pCtx->cs, pVM->rem.s.pCtx->eip));
739
740 /*
741 * Sync the state and enable single instruction / single stepping.
742 */
743 int rc = REMR3State(pVM);
744 if (VBOX_SUCCESS(rc))
745 {
746 int interrupt_request = pVM->rem.s.Env.interrupt_request;
747 Assert(!(interrupt_request & ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_EXIT | CPU_INTERRUPT_EXITTB | CPU_INTERRUPT_TIMER | CPU_INTERRUPT_EXTERNAL_HARD | CPU_INTERRUPT_EXTERNAL_EXIT | CPU_INTERRUPT_EXTERNAL_TIMER)));
748 Assert(!pVM->rem.s.Env.singlestep_enabled);
749#if 1
750
751 /*
752 * Now we set the execute single instruction flag and enter the cpu_exec loop.
753 */
754 pVM->rem.s.Env.interrupt_request = CPU_INTERRUPT_SINGLE_INSTR;
755 rc = cpu_exec(&pVM->rem.s.Env);
756 switch (rc)
757 {
758 /*
759 * Executed without anything out of the way happening.
760 */
761 case EXCP_SINGLE_INSTR:
762 rc = VINF_EM_RESCHEDULE;
763 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_SINGLE_INSTR\n"));
764 break;
765
766 /*
767 * If we take a trap or start servicing a pending interrupt, we might end up here.
768 * (Timer thread or some other thread wishing EMT's attention.)
769 */
770 case EXCP_INTERRUPT:
771 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_INTERRUPT\n"));
772 rc = VINF_EM_RESCHEDULE;
773 break;
774
775 /*
776 * Single step, we assume!
777 * If there was a breakpoint there we're fucked now.
778 */
779 case EXCP_DEBUG:
780 {
781 /* breakpoint or single step? */
782 RTGCPTR GCPtrPC = pVM->rem.s.Env.eip + pVM->rem.s.Env.segs[R_CS].base;
783 int iBP;
784 rc = VINF_EM_DBG_STEPPED;
785 for (iBP = 0; iBP < pVM->rem.s.Env.nb_breakpoints; iBP++)
786 if (pVM->rem.s.Env.breakpoints[iBP] == GCPtrPC)
787 {
788 rc = VINF_EM_DBG_BREAKPOINT;
789 break;
790 }
791 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_DEBUG rc=%Vrc iBP=%d GCPtrPC=%VGv\n", rc, iBP, GCPtrPC));
792 break;
793 }
794
795 /*
796 * hlt instruction.
797 */
798 case EXCP_HLT:
799 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_HLT\n"));
800 rc = VINF_EM_HALT;
801 break;
802
803 /*
804 * The VM has halted.
805 */
806 case EXCP_HALTED:
807 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_HALTED\n"));
808 rc = VINF_EM_HALT;
809 break;
810
811 /*
812 * Switch to RAW-mode.
813 */
814 case EXCP_EXECUTE_RAW:
815 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_EXECUTE_RAW\n"));
816 rc = VINF_EM_RESCHEDULE_RAW;
817 break;
818
819 /*
820 * Switch to hardware accelerated RAW-mode.
821 */
822 case EXCP_EXECUTE_HWACC:
823 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_EXECUTE_HWACC\n"));
824 rc = VINF_EM_RESCHEDULE_HWACC;
825 break;
826
827 /*
828 * An EM RC was raised (VMR3Reset/Suspend/PowerOff/some-fatal-error).
829 */
830 case EXCP_RC:
831 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_RC\n"));
832 rc = pVM->rem.s.rc;
833 pVM->rem.s.rc = VERR_INTERNAL_ERROR;
834 break;
835
836 /*
837 * Figure out the rest when they arrive....
838 */
839 default:
840 AssertMsgFailed(("rc=%d\n", rc));
841 Log2(("REMR3EmulateInstruction: cpu_exec -> %d\n", rc));
842 rc = VINF_EM_RESCHEDULE;
843 break;
844 }
845
846 /*
847 * Switch back the state.
848 */
849#else
850 pVM->rem.s.Env.interrupt_request = 0;
851 cpu_single_step(&pVM->rem.s.Env, 1);
852
853 /*
854 * Execute and handle the return code.
855 * We execute without enabling the cpu tick, so on success we'll
856 * just flip it on and off to make sure it moves.
857 *
858 * (We do not use emulate_single_instr() because that doesn't enter the
859 * right way in will cause serious trouble if a longjmp was attempted.)
860 */
861# ifdef DEBUG_bird
862 remR3DisasInstr(&pVM->rem.s.Env, 1, "REMR3EmulateInstruction");
863# endif
864 int cTimesMax = 16384;
865 uint32_t eip = pVM->rem.s.Env.eip;
866 do
867 {
868 rc = cpu_exec(&pVM->rem.s.Env);
869
870 } while ( eip == pVM->rem.s.Env.eip
871 && (rc == EXCP_DEBUG || rc == EXCP_EXECUTE_RAW)
872 && --cTimesMax > 0);
873 switch (rc)
874 {
875 /*
876 * Single step, we assume!
877 * If there was a breakpoint there we're fucked now.
878 */
879 case EXCP_DEBUG:
880 {
881 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_DEBUG\n"));
882 rc = VINF_EM_RESCHEDULE;
883 break;
884 }
885
886 /*
887 * We cannot be interrupted!
888 */
889 case EXCP_INTERRUPT:
890 AssertMsgFailed(("Shouldn't happen! Everything was locked!\n"));
891 rc = VERR_INTERNAL_ERROR;
892 break;
893
894 /*
895 * hlt instruction.
896 */
897 case EXCP_HLT:
898 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_HLT\n"));
899 rc = VINF_EM_HALT;
900 break;
901
902 /*
903 * The VM has halted.
904 */
905 case EXCP_HALTED:
906 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_HALTED\n"));
907 rc = VINF_EM_HALT;
908 break;
909
910 /*
911 * Switch to RAW-mode.
912 */
913 case EXCP_EXECUTE_RAW:
914 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_EXECUTE_RAW\n"));
915 rc = VINF_EM_RESCHEDULE_RAW;
916 break;
917
918 /*
919 * Switch to hardware accelerated RAW-mode.
920 */
921 case EXCP_EXECUTE_HWACC:
922 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_EXECUTE_HWACC\n"));
923 rc = VINF_EM_RESCHEDULE_HWACC;
924 break;
925
926 /*
927 * An EM RC was raised (VMR3Reset/Suspend/PowerOff/some-fatal-error).
928 */
929 case EXCP_RC:
930 Log2(("REMR3EmulateInstruction: cpu_exec -> EXCP_RC rc=%Vrc\n", pVM->rem.s.rc));
931 rc = pVM->rem.s.rc;
932 pVM->rem.s.rc = VERR_INTERNAL_ERROR;
933 break;
934
935 /*
936 * Figure out the rest when they arrive....
937 */
938 default:
939 AssertMsgFailed(("rc=%d\n", rc));
940 Log2(("REMR3EmulateInstruction: cpu_exec -> %d\n", rc));
941 rc = VINF_SUCCESS;
942 break;
943 }
944
945 /*
946 * Switch back the state.
947 */
948 cpu_single_step(&pVM->rem.s.Env, 0);
949#endif
950 pVM->rem.s.Env.interrupt_request = interrupt_request;
951 int rc2 = REMR3StateBack(pVM);
952 AssertRC(rc2);
953 }
954
955 Log2(("REMR3EmulateInstruction: returns %Vrc (cs:eip=%04x:%08x)\n",
956 rc, pVM->rem.s.Env.segs[R_CS].selector, pVM->rem.s.Env.eip));
957 return rc;
958}
959
960
961/**
962 * Runs code in recompiled mode.
963 *
964 * Before calling this function the REM state needs to be in sync with
965 * the VM. Call REMR3State() to perform the sync. It's only necessary
966 * (and permitted) to sync at the first call to REMR3Step()/REMR3Run()
967 * and after calling REMR3StateBack().
968 *
969 * @returns VBox status code.
970 *
971 * @param pVM VM Handle.
972 */
973REMR3DECL(int) REMR3Run(PVM pVM)
974{
975 Log2(("REMR3Run: (cs:eip=%04x:%08x)\n", pVM->rem.s.Env.segs[R_CS].selector, pVM->rem.s.Env.eip));
976 Assert(pVM->rem.s.fInREM);
977////Keyboard / tb stuff:
978//if ( pVM->rem.s.Env.segs[R_CS].selector == 0xf000
979// && pVM->rem.s.Env.eip >= 0xe860
980// && pVM->rem.s.Env.eip <= 0xe880)
981// pVM->rem.s.Env.state |= CPU_EMULATE_SINGLE_STEP;
982////A20:
983//if ( pVM->rem.s.Env.segs[R_CS].selector == 0x9020
984// && pVM->rem.s.Env.eip >= 0x970
985// && pVM->rem.s.Env.eip <= 0x9a0)
986// pVM->rem.s.Env.state |= CPU_EMULATE_SINGLE_STEP;
987////Speaker (port 61h)
988//if ( pVM->rem.s.Env.segs[R_CS].selector == 0x0010
989// && ( (pVM->rem.s.Env.eip >= 0x90278c10 && pVM->rem.s.Env.eip <= 0x90278c30)
990// || (pVM->rem.s.Env.eip >= 0x9010e250 && pVM->rem.s.Env.eip <= 0x9010e260)
991// )
992// )
993// pVM->rem.s.Env.state |= CPU_EMULATE_SINGLE_STEP;
994//DBGFR3InfoLog(pVM, "timers", NULL);
995
996
997 int rc = cpu_exec(&pVM->rem.s.Env);
998 switch (rc)
999 {
1000 /*
1001 * This happens when the execution was interrupted
1002 * by an external event, like pending timers.
1003 */
1004 case EXCP_INTERRUPT:
1005 Log2(("REMR3Run: cpu_exec -> EXCP_INTERRUPT\n"));
1006 rc = VINF_SUCCESS;
1007 break;
1008
1009 /*
1010 * hlt instruction.
1011 */
1012 case EXCP_HLT:
1013 Log2(("REMR3Run: cpu_exec -> EXCP_HLT\n"));
1014 rc = VINF_EM_HALT;
1015 break;
1016
1017 /*
1018 * The VM has halted.
1019 */
1020 case EXCP_HALTED:
1021 Log2(("REMR3Run: cpu_exec -> EXCP_HALTED\n"));
1022 rc = VINF_EM_HALT;
1023 break;
1024
1025 /*
1026 * Breakpoint/single step.
1027 */
1028 case EXCP_DEBUG:
1029 {
1030#if 0//def DEBUG_bird
1031 static int iBP = 0;
1032 printf("howdy, breakpoint! iBP=%d\n", iBP);
1033 switch (iBP)
1034 {
1035 case 0:
1036 cpu_breakpoint_remove(&pVM->rem.s.Env, pVM->rem.s.Env.eip + pVM->rem.s.Env.segs[R_CS].base);
1037 pVM->rem.s.Env.state |= CPU_EMULATE_SINGLE_STEP;
1038 //pVM->rem.s.Env.interrupt_request = 0;
1039 //pVM->rem.s.Env.exception_index = -1;
1040 //g_fInterruptDisabled = 1;
1041 rc = VINF_SUCCESS;
1042 asm("int3");
1043 break;
1044 default:
1045 asm("int3");
1046 break;
1047 }
1048 iBP++;
1049#else
1050 /* breakpoint or single step? */
1051 RTGCPTR GCPtrPC = pVM->rem.s.Env.eip + pVM->rem.s.Env.segs[R_CS].base;
1052 int iBP;
1053 rc = VINF_EM_DBG_STEPPED;
1054 for (iBP = 0; iBP < pVM->rem.s.Env.nb_breakpoints; iBP++)
1055 if (pVM->rem.s.Env.breakpoints[iBP] == GCPtrPC)
1056 {
1057 rc = VINF_EM_DBG_BREAKPOINT;
1058 break;
1059 }
1060 Log2(("REMR3Run: cpu_exec -> EXCP_DEBUG rc=%Vrc iBP=%d GCPtrPC=%VGv\n", rc, iBP, GCPtrPC));
1061#endif
1062 break;
1063 }
1064
1065 /*
1066 * Switch to RAW-mode.
1067 */
1068 case EXCP_EXECUTE_RAW:
1069 Log2(("REMR3Run: cpu_exec -> EXCP_EXECUTE_RAW\n"));
1070 rc = VINF_EM_RESCHEDULE_RAW;
1071 break;
1072
1073 /*
1074 * Switch to hardware accelerated RAW-mode.
1075 */
1076 case EXCP_EXECUTE_HWACC:
1077 Log2(("REMR3Run: cpu_exec -> EXCP_EXECUTE_HWACC\n"));
1078 rc = VINF_EM_RESCHEDULE_HWACC;
1079 break;
1080
1081 /*
1082 * An EM RC was raised (VMR3Reset/Suspend/PowerOff/some-fatal-error).
1083 */
1084 case EXCP_RC:
1085 Log2(("REMR3Run: cpu_exec -> EXCP_RC rc=%Vrc\n", pVM->rem.s.rc));
1086 rc = pVM->rem.s.rc;
1087 pVM->rem.s.rc = VERR_INTERNAL_ERROR;
1088 break;
1089
1090 /*
1091 * Figure out the rest when they arrive....
1092 */
1093 default:
1094 AssertMsgFailed(("rc=%d\n", rc));
1095 Log2(("REMR3Run: cpu_exec -> %d\n", rc));
1096 rc = VINF_SUCCESS;
1097 break;
1098 }
1099
1100 Log2(("REMR3Run: returns %Vrc (cs:eip=%04x:%08x)\n", rc, pVM->rem.s.Env.segs[R_CS].selector, pVM->rem.s.Env.eip));
1101 return rc;
1102}
1103
1104
1105/**
1106 * Check if the cpu state is suitable for Raw execution.
1107 *
1108 * @returns boolean
1109 * @param env The CPU env struct.
1110 * @param eip The EIP to check this for (might differ from env->eip).
1111 * @param fFlags hflags OR'ed with IOPL, TF and VM from eflags.
1112 * @param pExceptionIndex Stores EXCP_EXECUTE_RAW/HWACC in case raw mode is supported in this context
1113 *
1114 * @remark This function must be kept in perfect sync with the scheduler in EM.cpp!
1115 */
1116bool remR3CanExecuteRaw(CPUState *env, RTGCPTR eip, unsigned fFlags, uint32_t *pExceptionIndex)
1117{
1118 /* !!! THIS MUST BE IN SYNC WITH emR3Reschedule !!! */
1119 /* !!! THIS MUST BE IN SYNC WITH emR3Reschedule !!! */
1120 /* !!! THIS MUST BE IN SYNC WITH emR3Reschedule !!! */
1121
1122 /* Update counter. */
1123 env->pVM->rem.s.cCanExecuteRaw++;
1124
1125 if (HWACCMIsEnabled(env->pVM))
1126 {
1127 env->state |= CPU_RAW_HWACC;
1128
1129 /*
1130 * Create partial context for HWACCMR3CanExecuteGuest
1131 */
1132 CPUMCTX Ctx;
1133 Ctx.cr0 = env->cr[0];
1134 Ctx.cr3 = env->cr[3];
1135 Ctx.cr4 = env->cr[4];
1136
1137 Ctx.tr = env->tr.selector;
1138 Ctx.trHid.u32Base = (uint32_t)env->tr.base;
1139 Ctx.trHid.u32Limit = env->tr.limit;
1140 Ctx.trHid.Attr.u = (env->tr.flags >> 8) & 0xF0FF;
1141
1142 Ctx.idtr.cbIdt = env->idt.limit;
1143 Ctx.idtr.pIdt = (uint32_t)env->idt.base;
1144
1145 Ctx.eflags.u32 = env->eflags;
1146
1147 Ctx.cs = env->segs[R_CS].selector;
1148 Ctx.csHid.u32Base = (uint32_t)env->segs[R_CS].base;
1149 Ctx.csHid.u32Limit = env->segs[R_CS].limit;
1150 Ctx.csHid.Attr.u = (env->segs[R_CS].flags >> 8) & 0xF0FF;
1151
1152 Ctx.ss = env->segs[R_SS].selector;
1153 Ctx.ssHid.u32Base = (uint32_t)env->segs[R_SS].base;
1154 Ctx.ssHid.u32Limit = env->segs[R_SS].limit;
1155 Ctx.ssHid.Attr.u = (env->segs[R_SS].flags >> 8) & 0xF0FF;
1156
1157 /* Hardware accelerated raw-mode:
1158 *
1159 * Typically only 32-bits protected mode, with paging enabled, code is allowed here.
1160 */
1161 if (HWACCMR3CanExecuteGuest(env->pVM, &Ctx) == true)
1162 {
1163 *pExceptionIndex = EXCP_EXECUTE_HWACC;
1164 return true;
1165 }
1166 return false;
1167 }
1168
1169 /*
1170 * Here we only support 16 & 32 bits protected mode ring 3 code that has no IO privileges
1171 * or 32 bits protected mode ring 0 code
1172 *
1173 * The tests are ordered by the likelyhood of being true during normal execution.
1174 */
1175 if (fFlags & (HF_TF_MASK | HF_INHIBIT_IRQ_MASK))
1176 {
1177 STAM_COUNTER_INC(&gStatRefuseTFInhibit);
1178 Log2(("raw mode refused: fFlags=%#x\n", fFlags));
1179 return false;
1180 }
1181
1182#ifndef VBOX_RAW_V86
1183 if (fFlags & VM_MASK) {
1184 STAM_COUNTER_INC(&gStatRefuseVM86);
1185 Log2(("raw mode refused: VM_MASK\n"));
1186 return false;
1187 }
1188#endif
1189
1190 if (env->state & CPU_EMULATE_SINGLE_INSTR)
1191 {
1192#ifndef DEBUG_bird
1193 Log2(("raw mode refused: CPU_EMULATE_SINGLE_INSTR\n"));
1194#endif
1195 return false;
1196 }
1197
1198 if (env->singlestep_enabled)
1199 {
1200 //Log2(("raw mode refused: Single step\n"));
1201 return false;
1202 }
1203
1204 if (env->nb_breakpoints > 0)
1205 {
1206 //Log2(("raw mode refused: Breakpoints\n"));
1207 return false;
1208 }
1209
1210 uint32_t u32CR0 = env->cr[0];
1211 if ((u32CR0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
1212 {
1213 STAM_COUNTER_INC(&gStatRefusePaging);
1214 //Log2(("raw mode refused: %s%s%s\n", (u32CR0 & X86_CR0_PG) ? "" : " !PG", (u32CR0 & X86_CR0_PE) ? "" : " !PE", (u32CR0 & X86_CR0_AM) ? "" : " !AM"));
1215 return false;
1216 }
1217
1218 if (env->cr[4] & CR4_PAE_MASK)
1219 {
1220 STAM_COUNTER_INC(&gStatRefusePAE);
1221 //Log2(("raw mode refused: PAE\n"));
1222 return false;
1223 }
1224
1225 if (((fFlags >> HF_CPL_SHIFT) & 3) == 3)
1226 {
1227 if (!EMIsRawRing3Enabled(env->pVM))
1228 return false;
1229
1230 if (!(env->eflags & IF_MASK))
1231 {
1232 STAM_COUNTER_INC(&gStatRefuseIF0);
1233 Log2(("raw mode refused: IF (RawR3)\n"));
1234 return false;
1235 }
1236
1237 if (!(u32CR0 & CR0_WP_MASK) && EMIsRawRing0Enabled(env->pVM))
1238 {
1239 STAM_COUNTER_INC(&gStatRefuseWP0);
1240 Log2(("raw mode refused: CR0.WP + RawR0\n"));
1241 return false;
1242 }
1243 }
1244 else
1245 {
1246 if (!EMIsRawRing0Enabled(env->pVM))
1247 return false;
1248
1249 // Let's start with pure 32 bits ring 0 code first
1250 if ((fFlags & (HF_SS32_MASK | HF_CS32_MASK)) != (HF_SS32_MASK | HF_CS32_MASK))
1251 {
1252 STAM_COUNTER_INC(&gStatRefuseCode16);
1253 Log2(("raw r0 mode refused: HF_[S|C]S32_MASK fFlags=%#x\n", fFlags));
1254 return false;
1255 }
1256
1257 // Only R0
1258 if (((fFlags >> HF_CPL_SHIFT) & 3) != 0)
1259 {
1260 STAM_COUNTER_INC(&gStatRefuseRing1or2);
1261 Log2(("raw r0 mode refused: CPL %d\n", ((fFlags >> HF_CPL_SHIFT) & 3) ));
1262 return false;
1263 }
1264
1265 if (!(u32CR0 & CR0_WP_MASK))
1266 {
1267 STAM_COUNTER_INC(&gStatRefuseWP0);
1268 Log2(("raw r0 mode refused: CR0.WP=0!\n"));
1269 return false;
1270 }
1271
1272 if (PATMIsPatchGCAddr(env->pVM, eip))
1273 {
1274 Log2(("raw r0 mode forced: patch code\n"));
1275 *pExceptionIndex = EXCP_EXECUTE_RAW;
1276 return true;
1277 }
1278
1279#if !defined(VBOX_ALLOW_IF0) && !defined(VBOX_RUN_INTERRUPT_GATE_HANDLERS)
1280 if (!(env->eflags & IF_MASK))
1281 {
1282 STAM_COUNTER_INC(&gStatRefuseIF0);
1283 ////Log2(("R0: IF=0 VIF=%d %08X\n", eip, *env->pVMeflags));
1284 //Log2(("RR0: Interrupts turned off; fall back to emulation\n"));
1285 return false;
1286 }
1287#endif
1288
1289 env->state |= CPU_RAW_RING0;
1290 }
1291
1292 /*
1293 * Don't reschedule the first time we're called, because there might be
1294 * special reasons why we're here that is not covered by the above checks.
1295 */
1296 if (env->pVM->rem.s.cCanExecuteRaw == 1)
1297 {
1298 Log2(("raw mode refused: first scheduling\n"));
1299 STAM_COUNTER_INC(&gStatRefuseCanExecute);
1300 return false;
1301 }
1302
1303 Assert(PGMPhysIsA20Enabled(env->pVM));
1304 *pExceptionIndex = EXCP_EXECUTE_RAW;
1305 return true;
1306}
1307
1308
1309/**
1310 * Fetches a code byte.
1311 *
1312 * @returns Success indicator (bool) for ease of use.
1313 * @param env The CPU environment structure.
1314 * @param GCPtrInstr Where to fetch code.
1315 * @param pu8Byte Where to store the byte on success
1316 */
1317bool remR3GetOpcode(CPUState *env, RTGCPTR GCPtrInstr, uint8_t *pu8Byte)
1318{
1319 int rc = PATMR3QueryOpcode(env->pVM, GCPtrInstr, pu8Byte);
1320 if (VBOX_SUCCESS(rc))
1321 return true;
1322 return false;
1323}
1324
1325
1326/**
1327 * Flush (or invalidate if you like) page table/dir entry.
1328 *
1329 * (invlpg instruction; tlb_flush_page)
1330 *
1331 * @param env Pointer to cpu environment.
1332 * @param GCPtr The virtual address which page table/dir entry should be invalidated.
1333 */
1334void remR3FlushPage(CPUState *env, RTGCPTR GCPtr)
1335{
1336 PVM pVM = env->pVM;
1337
1338 /*
1339 * When we're replaying invlpg instructions or restoring a saved
1340 * state we disable this path.
1341 */
1342 if (pVM->rem.s.fIgnoreInvlPg || pVM->rem.s.fIgnoreAll)
1343 return;
1344 Log(("remR3FlushPage: GCPtr=%VGv\n", GCPtr));
1345 Assert(pVM->rem.s.fInREM);
1346
1347 //RAWEx_ProfileStop(env, STATS_QEMU_TOTAL);
1348
1349 /*
1350 * Update the control registers before calling PGMFlushPage.
1351 */
1352 PCPUMCTX pCtx = (PCPUMCTX)pVM->rem.s.pCtx;
1353 pCtx->cr0 = env->cr[0];
1354 pCtx->cr3 = env->cr[3];
1355 pCtx->cr4 = env->cr[4];
1356
1357 /*
1358 * Let PGM do the rest.
1359 */
1360 int rc = PGMInvalidatePage(pVM, GCPtr);
1361 if (VBOX_FAILURE(rc))
1362 {
1363 AssertMsgFailed(("remR3FlushPage %x %x %x %d failed!!\n", GCPtr));
1364 VM_FF_SET(pVM, VM_FF_PGM_SYNC_CR3);
1365 }
1366 //RAWEx_ProfileStart(env, STATS_QEMU_TOTAL);
1367}
1368
1369/**
1370 * Set page table/dir entry. (called from tlb_set_page)
1371 *
1372 * @param env Pointer to cpu environment.
1373 */
1374void remR3SetPage(CPUState *env, CPUTLBEntry *pTLBEntry, CPUTLBEntry *pTLBEntryIgnored, int prot, int is_user)
1375{
1376 target_ulong virt_addr;
1377 if (env->pVM->rem.s.fIgnoreSetPage || env->pVM->rem.s.fIgnoreAll)
1378 return;
1379 Assert(env->pVM->rem.s.fInREM || env->pVM->rem.s.fInStateSync);
1380
1381#ifndef PGM_DYNAMIC_RAM_ALLOC
1382 if(!is_user && !(env->state & CPU_RAW_RING0))
1383 return; /* We are currently not interested in kernel pages */
1384#endif
1385
1386#if !defined(PGM_DYNAMIC_RAM_ALLOC) && !defined(REM_PHYS_ADDR_IN_TLB)
1387 Log2(("tlb_set_page_raw (r=%x|w=%x)-%x prot %x is_user %d phys base %x\n",
1388 pTLBEntry->addr_read, pTLBEntry->addr_write, pTLBEntry->addend, prot, is_user, phys_ram_base));
1389#else /* PGM_DYNAMIC_RAM_ALLOC */
1390 Log2(("tlb_set_page_raw (r=%x|w=%x)-%x prot %x is_user %d\n",
1391 pTLBEntry->addr_read, pTLBEntry->addr_write, pTLBEntry->addend, prot, is_user));
1392#endif/* PGM_DYNAMIC_RAM_ALLOC */
1393
1394 /*
1395 * Extract the virtual address.
1396 */
1397 if (prot & PAGE_WRITE)
1398 virt_addr = pTLBEntry->addr_write;
1399 else if (prot & PAGE_READ)
1400 virt_addr = pTLBEntry->addr_read;
1401 else
1402 AssertMsgFailedReturnVoid(("tlb_set_page_raw unexpected protection flags %x\n", prot));
1403 virt_addr &= TARGET_PAGE_MASK;
1404
1405 /*
1406 * Update the control registers before calling PGMFlushPage.
1407 */
1408 PCPUMCTX pCtx = (PCPUMCTX)env->pVM->rem.s.pCtx;
1409 pCtx->cr0 = env->cr[0];
1410 pCtx->cr3 = env->cr[3];
1411 pCtx->cr4 = env->cr[4];
1412
1413 /*
1414 * Let PGM do the rest.
1415 */
1416 int rc = PGMInvalidatePage(env->pVM, (RTGCPTR)virt_addr);
1417 if (VBOX_FAILURE(rc))
1418 {
1419#ifdef VBOX_STRICT
1420 target_ulong addend = pTLBEntry->addend;
1421 target_ulong phys_addr;
1422
1423 if (!(addend & IO_MEM_ROM))
1424# ifdef REM_PHYS_ADDR_IN_TLB
1425 phys_addr = virt_addr + addend;
1426# elif defined(PGM_DYNAMIC_RAM_ALLOC)
1427 phys_addr = remR3HCVirt2GCPhysInlined(env->pVM, (void *)(virt_addr + addend));
1428# else
1429 phys_addr = virt_addr - (uintptr_t)phys_ram_base + addend;
1430# endif
1431 else
1432 phys_addr = addend;
1433 AssertMsgFailed(("RAWEx_SetPageEntry %x %x %x %d failed!!\n", virt_addr, phys_addr, prot, is_user));
1434#endif /* VBOX_STRICT */
1435 VM_FF_SET(env->pVM, VM_FF_PGM_SYNC_CR3);
1436 }
1437}
1438
1439/**
1440 * Called from tlb_protect_code in order to write monitor a code page.
1441 *
1442 * @param env Pointer to the CPU environment.
1443 * @param GCPtr Code page to monitor
1444 */
1445void remR3ProtectCode(CPUState *env, RTGCPTR GCPtr)
1446{
1447 Assert(env->pVM->rem.s.fInREM);
1448 if ( (env->cr[0] & X86_CR0_PG) /* paging must be enabled */
1449 && !(env->state & CPU_EMULATE_SINGLE_INSTR) /* ignore during single instruction execution */
1450 && (((env->hflags >> HF_CPL_SHIFT) & 3) == 0) /* supervisor mode only */
1451 && !(env->eflags & VM_MASK) /* no V86 mode */
1452 && !HWACCMIsEnabled(env->pVM))
1453 CSAMR3MonitorPage(env->pVM, GCPtr, CSAM_TAG_REM);
1454}
1455
1456/**
1457 * Called when the CPU is initialized, any of the CRx registers are changed or
1458 * when the A20 line is modified.
1459 *
1460 * @param env Pointer to the CPU environment.
1461 * @param fGlobal Set if the flush is global.
1462 */
1463void remR3FlushTLB(CPUState *env, bool fGlobal)
1464{
1465 PVM pVM = env->pVM;
1466
1467 /*
1468 * When we're replaying invlpg instructions or restoring a saved
1469 * state we disable this path.
1470 */
1471 if (pVM->rem.s.fIgnoreCR3Load || pVM->rem.s.fIgnoreAll)
1472 return;
1473 Assert(pVM->rem.s.fInREM);
1474
1475 /*
1476 * The caller doesn't check cr4, so we have to do that for ourselves.
1477 */
1478 if (!fGlobal && !(env->cr[4] & X86_CR4_PGE))
1479 fGlobal = true;
1480 Log(("remR3FlushTLB: CR0=%VGp CR3=%VGp CR4=%VGp %s\n", env->cr[0], env->cr[3], env->cr[4], fGlobal ? " global" : ""));
1481
1482 /*
1483 * Update the control registers before calling PGMR3FlushTLB.
1484 */
1485 PCPUMCTX pCtx = (PCPUMCTX)pVM->rem.s.pCtx;
1486 pCtx->cr0 = env->cr[0];
1487 pCtx->cr3 = env->cr[3];
1488 pCtx->cr4 = env->cr[4];
1489
1490 /*
1491 * Let PGM do the rest.
1492 */
1493 PGMFlushTLB(pVM, env->cr[3], fGlobal);
1494}
1495
1496
1497/**
1498 * Called when any of the cr0, cr4 or efer registers is updated.
1499 *
1500 * @param env Pointer to the CPU environment.
1501 */
1502void remR3ChangeCpuMode(CPUState *env)
1503{
1504 int rc;
1505 PVM pVM = env->pVM;
1506
1507 /*
1508 * When we're replaying loads or restoring a saved
1509 * state this path is disabled.
1510 */
1511 if (pVM->rem.s.fIgnoreCpuMode || pVM->rem.s.fIgnoreAll)
1512 return;
1513 Assert(pVM->rem.s.fInREM);
1514
1515 /*
1516 * Update the control registers before calling PGMR3ChangeMode()
1517 * as it may need to map whatever cr3 is pointing to.
1518 */
1519 PCPUMCTX pCtx = (PCPUMCTX)pVM->rem.s.pCtx;
1520 pCtx->cr0 = env->cr[0];
1521 pCtx->cr3 = env->cr[3];
1522 pCtx->cr4 = env->cr[4];
1523
1524#ifdef TARGET_X86_64
1525 rc = PGMChangeMode(pVM, env->cr[0], env->cr[4], env->efer);
1526 if (rc != VINF_SUCCESS)
1527 cpu_abort(env, "PGMChangeMode(, %08x, %08x, %016llx) -> %Vrc\n", env->cr[0], env->cr[4], env->efer, rc);
1528#else
1529 rc = PGMChangeMode(pVM, env->cr[0], env->cr[4], 0);
1530 if (rc != VINF_SUCCESS)
1531 cpu_abort(env, "PGMChangeMode(, %08x, %08x, %016llx) -> %Vrc\n", env->cr[0], env->cr[4], 0LL, rc);
1532#endif
1533}
1534
1535
1536/**
1537 * Called from compiled code to run dma.
1538 *
1539 * @param env Pointer to the CPU environment.
1540 */
1541void remR3DmaRun(CPUState *env)
1542{
1543 remR3ProfileStop(STATS_QEMU_RUN_EMULATED_CODE);
1544 PDMR3DmaRun(env->pVM);
1545 remR3ProfileStart(STATS_QEMU_RUN_EMULATED_CODE);
1546}
1547
1548/**
1549 * Called from compiled code to schedule pending timers in VMM
1550 *
1551 * @param env Pointer to the CPU environment.
1552 */
1553void remR3TimersRun(CPUState *env)
1554{
1555 remR3ProfileStop(STATS_QEMU_RUN_EMULATED_CODE);
1556 remR3ProfileStart(STATS_QEMU_RUN_TIMERS);
1557 TMR3TimerQueuesDo(env->pVM);
1558 remR3ProfileStop(STATS_QEMU_RUN_TIMERS);
1559 remR3ProfileStart(STATS_QEMU_RUN_EMULATED_CODE);
1560}
1561
1562/**
1563 * Record trap occurance
1564 *
1565 * @returns VBox status code
1566 * @param env Pointer to the CPU environment.
1567 * @param uTrap Trap nr
1568 * @param uErrorCode Error code
1569 * @param pvNextEIP Next EIP
1570 */
1571int remR3NotifyTrap(CPUState *env, uint32_t uTrap, uint32_t uErrorCode, uint32_t pvNextEIP)
1572{
1573 PVM pVM = (PVM)env->pVM;
1574#ifdef VBOX_WITH_STATISTICS
1575 static STAMCOUNTER aStatTrap[255];
1576 static bool aRegisters[ELEMENTS(aStatTrap)];
1577#endif
1578
1579#ifdef VBOX_WITH_STATISTICS
1580 if (uTrap < 255)
1581 {
1582 if (!aRegisters[uTrap])
1583 {
1584 aRegisters[uTrap] = true;
1585 char szStatName[64];
1586 RTStrPrintf(szStatName, sizeof(szStatName), "/REM/Trap/0x%02X", uTrap);
1587 STAM_REG(env->pVM, &aStatTrap[uTrap], STAMTYPE_COUNTER, szStatName, STAMUNIT_OCCURENCES, "Trap stats.");
1588 }
1589 STAM_COUNTER_INC(&aStatTrap[uTrap]);
1590 }
1591#endif
1592 Log(("remR3NotifyTrap: uTrap=%x error=%x next_eip=%VGv eip=%VGv cr2=%08x\n", uTrap, uErrorCode, pvNextEIP, env->eip, env->cr[2]));
1593 if( uTrap < 0x20
1594 && (env->cr[0] & X86_CR0_PE)
1595 && !(env->eflags & X86_EFL_VM))
1596 {
1597#ifdef DEBUG
1598 remR3DisasInstr(env, 1, "remR3NotifyTrap: ");
1599#endif
1600 if(pVM->rem.s.uPendingException == uTrap && ++pVM->rem.s.cPendingExceptions > 512)
1601 {
1602 LogRel(("VERR_REM_TOO_MANY_TRAPS -> uTrap=%x error=%x next_eip=%VGv eip=%VGv cr2=%08x\n", uTrap, uErrorCode, pvNextEIP, env->eip, env->cr[2]));
1603 remR3RaiseRC(env->pVM, VERR_REM_TOO_MANY_TRAPS);
1604 return VERR_REM_TOO_MANY_TRAPS;
1605 }
1606 if(pVM->rem.s.uPendingException != uTrap || pVM->rem.s.uPendingExcptEIP != env->eip || pVM->rem.s.uPendingExcptCR2 != env->cr[2])
1607 pVM->rem.s.cPendingExceptions = 1;
1608 pVM->rem.s.uPendingException = uTrap;
1609 pVM->rem.s.uPendingExcptEIP = env->eip;
1610 pVM->rem.s.uPendingExcptCR2 = env->cr[2];
1611 }
1612 else
1613 {
1614 pVM->rem.s.cPendingExceptions = 0;
1615 pVM->rem.s.uPendingException = uTrap;
1616 pVM->rem.s.uPendingExcptEIP = env->eip;
1617 pVM->rem.s.uPendingExcptCR2 = env->cr[2];
1618 }
1619 return VINF_SUCCESS;
1620}
1621
1622/*
1623 * Clear current active trap
1624 *
1625 * @param pVM VM Handle.
1626 */
1627void remR3TrapClear(PVM pVM)
1628{
1629 pVM->rem.s.cPendingExceptions = 0;
1630 pVM->rem.s.uPendingException = 0;
1631 pVM->rem.s.uPendingExcptEIP = 0;
1632 pVM->rem.s.uPendingExcptCR2 = 0;
1633}
1634
1635
1636/**
1637 * Syncs the internal REM state with the VM.
1638 *
1639 * This must be called before REMR3Run() is invoked whenever when the REM
1640 * state is not up to date. Calling it several times in a row is not
1641 * permitted.
1642 *
1643 * @returns VBox status code.
1644 *
1645 * @param pVM VM Handle.
1646 *
1647 * @remark The caller has to check for important FFs before calling REMR3Run. REMR3State will
1648 * no do this since the majority of the callers don't want any unnecessary of events
1649 * pending that would immediatly interrupt execution.
1650 */
1651REMR3DECL(int) REMR3State(PVM pVM)
1652{
1653 Log2(("REMR3State:\n"));
1654 STAM_PROFILE_START(&pVM->rem.s.StatsState, a);
1655 register const CPUMCTX *pCtx = pVM->rem.s.pCtx;
1656 register unsigned fFlags;
1657 bool fHiddenSelRegsValid = CPUMAreHiddenSelRegsValid(pVM);
1658
1659 Assert(!pVM->rem.s.fInREM);
1660 pVM->rem.s.fInStateSync = true;
1661
1662 /*
1663 * Copy the registers which requires no special handling.
1664 */
1665 Assert(R_EAX == 0);
1666 pVM->rem.s.Env.regs[R_EAX] = pCtx->eax;
1667 Assert(R_ECX == 1);
1668 pVM->rem.s.Env.regs[R_ECX] = pCtx->ecx;
1669 Assert(R_EDX == 2);
1670 pVM->rem.s.Env.regs[R_EDX] = pCtx->edx;
1671 Assert(R_EBX == 3);
1672 pVM->rem.s.Env.regs[R_EBX] = pCtx->ebx;
1673 Assert(R_ESP == 4);
1674 pVM->rem.s.Env.regs[R_ESP] = pCtx->esp;
1675 Assert(R_EBP == 5);
1676 pVM->rem.s.Env.regs[R_EBP] = pCtx->ebp;
1677 Assert(R_ESI == 6);
1678 pVM->rem.s.Env.regs[R_ESI] = pCtx->esi;
1679 Assert(R_EDI == 7);
1680 pVM->rem.s.Env.regs[R_EDI] = pCtx->edi;
1681 pVM->rem.s.Env.eip = pCtx->eip;
1682
1683 pVM->rem.s.Env.eflags = pCtx->eflags.u32;
1684
1685 pVM->rem.s.Env.cr[2] = pCtx->cr2;
1686
1687 /** @todo we could probably benefit from using a CPUM_CHANGED_DRx flag too! */
1688 pVM->rem.s.Env.dr[0] = pCtx->dr0;
1689 pVM->rem.s.Env.dr[1] = pCtx->dr1;
1690 pVM->rem.s.Env.dr[2] = pCtx->dr2;
1691 pVM->rem.s.Env.dr[3] = pCtx->dr3;
1692 pVM->rem.s.Env.dr[4] = pCtx->dr4;
1693 pVM->rem.s.Env.dr[5] = pCtx->dr5;
1694 pVM->rem.s.Env.dr[6] = pCtx->dr6;
1695 pVM->rem.s.Env.dr[7] = pCtx->dr7;
1696
1697 /*
1698 * Clear the halted hidden flag (the interrupt waking up the CPU can
1699 * have been dispatched in raw mode).
1700 */
1701 pVM->rem.s.Env.hflags &= ~HF_HALTED_MASK;
1702
1703 /*
1704 * Replay invlpg?
1705 */
1706 if (pVM->rem.s.cInvalidatedPages)
1707 {
1708 pVM->rem.s.fIgnoreInvlPg = true;
1709 RTUINT i;
1710 for (i = 0; i < pVM->rem.s.cInvalidatedPages; i++)
1711 {
1712 Log2(("REMR3State: invlpg %VGv\n", pVM->rem.s.aGCPtrInvalidatedPages[i]));
1713 tlb_flush_page(&pVM->rem.s.Env, pVM->rem.s.aGCPtrInvalidatedPages[i]);
1714 }
1715 pVM->rem.s.fIgnoreInvlPg = false;
1716 pVM->rem.s.cInvalidatedPages = 0;
1717 }
1718
1719 /*
1720 * Registers which are rarely changed and require special handling / order when changed.
1721 */
1722 fFlags = CPUMGetAndClearChangedFlagsREM(pVM);
1723 if (fFlags & ( CPUM_CHANGED_CR4 | CPUM_CHANGED_CR3 | CPUM_CHANGED_CR0
1724 | CPUM_CHANGED_GDTR | CPUM_CHANGED_IDTR | CPUM_CHANGED_LDTR | CPUM_CHANGED_TR
1725 | CPUM_CHANGED_FPU_REM | CPUM_CHANGED_SYSENTER_MSR))
1726 {
1727 if (fFlags & CPUM_CHANGED_FPU_REM)
1728 save_raw_fp_state(&pVM->rem.s.Env, (uint8_t *)&pCtx->fpu); /* 'save' is an excellent name. */
1729
1730 if (fFlags & CPUM_CHANGED_GLOBAL_TLB_FLUSH)
1731 {
1732 pVM->rem.s.fIgnoreCR3Load = true;
1733 tlb_flush(&pVM->rem.s.Env, true);
1734 pVM->rem.s.fIgnoreCR3Load = false;
1735 }
1736
1737 if (fFlags & CPUM_CHANGED_CR4)
1738 {
1739 pVM->rem.s.fIgnoreCR3Load = true;
1740 pVM->rem.s.fIgnoreCpuMode = true;
1741 cpu_x86_update_cr4(&pVM->rem.s.Env, pCtx->cr4);
1742 pVM->rem.s.fIgnoreCpuMode = false;
1743 pVM->rem.s.fIgnoreCR3Load = false;
1744 }
1745
1746 if (fFlags & CPUM_CHANGED_CR0)
1747 {
1748 pVM->rem.s.fIgnoreCR3Load = true;
1749 pVM->rem.s.fIgnoreCpuMode = true;
1750 cpu_x86_update_cr0(&pVM->rem.s.Env, pCtx->cr0);
1751 pVM->rem.s.fIgnoreCpuMode = false;
1752 pVM->rem.s.fIgnoreCR3Load = false;
1753 }
1754
1755 if (fFlags & CPUM_CHANGED_CR3)
1756 {
1757 pVM->rem.s.fIgnoreCR3Load = true;
1758 cpu_x86_update_cr3(&pVM->rem.s.Env, pCtx->cr3);
1759 pVM->rem.s.fIgnoreCR3Load = false;
1760 }
1761
1762 if (fFlags & CPUM_CHANGED_GDTR)
1763 {
1764 pVM->rem.s.Env.gdt.base = pCtx->gdtr.pGdt;
1765 pVM->rem.s.Env.gdt.limit = pCtx->gdtr.cbGdt;
1766 }
1767
1768 if (fFlags & CPUM_CHANGED_IDTR)
1769 {
1770 pVM->rem.s.Env.idt.base = pCtx->idtr.pIdt;
1771 pVM->rem.s.Env.idt.limit = pCtx->idtr.cbIdt;
1772 }
1773
1774 if (fFlags & CPUM_CHANGED_SYSENTER_MSR)
1775 {
1776 pVM->rem.s.Env.sysenter_cs = pCtx->SysEnter.cs;
1777 pVM->rem.s.Env.sysenter_eip = pCtx->SysEnter.eip;
1778 pVM->rem.s.Env.sysenter_esp = pCtx->SysEnter.esp;
1779 }
1780
1781 if (fFlags & CPUM_CHANGED_LDTR)
1782 {
1783 if (fHiddenSelRegsValid)
1784 {
1785 pVM->rem.s.Env.ldt.selector = pCtx->ldtr;
1786 pVM->rem.s.Env.ldt.base = pCtx->ldtrHid.u32Base;
1787 pVM->rem.s.Env.ldt.limit = pCtx->ldtrHid.u32Limit;
1788 pVM->rem.s.Env.ldt.flags = (pCtx->ldtrHid.Attr.u << 8) & 0xFFFFFF;;
1789 }
1790 else
1791 sync_ldtr(&pVM->rem.s.Env, pCtx->ldtr);
1792 }
1793
1794 if (fFlags & CPUM_CHANGED_TR)
1795 {
1796 if (fHiddenSelRegsValid)
1797 {
1798 pVM->rem.s.Env.tr.selector = pCtx->tr;
1799 pVM->rem.s.Env.tr.base = pCtx->trHid.u32Base;
1800 pVM->rem.s.Env.tr.limit = pCtx->trHid.u32Limit;
1801 pVM->rem.s.Env.tr.flags = (pCtx->trHid.Attr.u << 8) & 0xFFFFFF;;
1802 }
1803 else
1804 sync_tr(&pVM->rem.s.Env, pCtx->tr);
1805
1806 /** @note do_interrupt will fault if the busy flag is still set.... */
1807 pVM->rem.s.Env.tr.flags &= ~DESC_TSS_BUSY_MASK;
1808 }
1809 }
1810
1811 /*
1812 * Update selector registers.
1813 * This must be done *after* we've synced gdt, ldt and crX registers
1814 * since we're reading the GDT/LDT om sync_seg. This will happen with
1815 * saved state which takes a quick dip into rawmode for instance.
1816 */
1817 /*
1818 * Stack; Note first check this one as the CPL might have changed. The
1819 * wrong CPL can cause QEmu to raise an exception in sync_seg!!
1820 */
1821
1822 if (fHiddenSelRegsValid)
1823 {
1824 /* The hidden selector registers are valid in the CPU context. */
1825 /** @note QEmu saves the 2nd dword of the descriptor; we should convert the attribute word back! */
1826
1827 /* Set current CPL */
1828 cpu_x86_set_cpl(&pVM->rem.s.Env, CPUMGetGuestCPL(pVM, CPUMCTX2CORE(pCtx)));
1829
1830 cpu_x86_load_seg_cache(&pVM->rem.s.Env, R_CS, pCtx->cs, pCtx->csHid.u32Base, pCtx->csHid.u32Limit, (pCtx->csHid.Attr.u << 8) & 0xFFFFFF);
1831 cpu_x86_load_seg_cache(&pVM->rem.s.Env, R_SS, pCtx->ss, pCtx->ssHid.u32Base, pCtx->ssHid.u32Limit, (pCtx->ssHid.Attr.u << 8) & 0xFFFFFF);
1832 cpu_x86_load_seg_cache(&pVM->rem.s.Env, R_DS, pCtx->ds, pCtx->dsHid.u32Base, pCtx->dsHid.u32Limit, (pCtx->dsHid.Attr.u << 8) & 0xFFFFFF);
1833 cpu_x86_load_seg_cache(&pVM->rem.s.Env, R_ES, pCtx->es, pCtx->esHid.u32Base, pCtx->esHid.u32Limit, (pCtx->esHid.Attr.u << 8) & 0xFFFFFF);
1834 cpu_x86_load_seg_cache(&pVM->rem.s.Env, R_FS, pCtx->fs, pCtx->fsHid.u32Base, pCtx->fsHid.u32Limit, (pCtx->fsHid.Attr.u << 8) & 0xFFFFFF);
1835 cpu_x86_load_seg_cache(&pVM->rem.s.Env, R_GS, pCtx->gs, pCtx->gsHid.u32Base, pCtx->gsHid.u32Limit, (pCtx->gsHid.Attr.u << 8) & 0xFFFFFF);
1836 }
1837 else
1838 {
1839 /* In 'normal' raw mode we don't have access to the hidden selector registers. */
1840 if (pVM->rem.s.Env.segs[R_SS].selector != (uint16_t)pCtx->ss)
1841 {
1842 Log2(("REMR3State: SS changed from %04x to %04x!\n", pVM->rem.s.Env.segs[R_SS].selector, pCtx->ss));
1843
1844 cpu_x86_set_cpl(&pVM->rem.s.Env, (pCtx->eflags.Bits.u1VM) ? 3 : (pCtx->ss & 3));
1845 sync_seg(&pVM->rem.s.Env, R_SS, pCtx->ss);
1846#ifdef VBOX_WITH_STATISTICS
1847 if (pVM->rem.s.Env.segs[R_SS].newselector)
1848 {
1849 STAM_COUNTER_INC(&gStatSelOutOfSync[R_SS]);
1850 }
1851#endif
1852 }
1853 else
1854 pVM->rem.s.Env.segs[R_SS].newselector = 0;
1855
1856 if (pVM->rem.s.Env.segs[R_ES].selector != pCtx->es)
1857 {
1858 Log2(("REMR3State: ES changed from %04x to %04x!\n", pVM->rem.s.Env.segs[R_ES].selector, pCtx->es));
1859 sync_seg(&pVM->rem.s.Env, R_ES, pCtx->es);
1860#ifdef VBOX_WITH_STATISTICS
1861 if (pVM->rem.s.Env.segs[R_ES].newselector)
1862 {
1863 STAM_COUNTER_INC(&gStatSelOutOfSync[R_ES]);
1864 }
1865#endif
1866 }
1867 else
1868 pVM->rem.s.Env.segs[R_ES].newselector = 0;
1869
1870 if (pVM->rem.s.Env.segs[R_CS].selector != pCtx->cs)
1871 {
1872 Log2(("REMR3State: CS changed from %04x to %04x!\n", pVM->rem.s.Env.segs[R_CS].selector, pCtx->cs));
1873 sync_seg(&pVM->rem.s.Env, R_CS, pCtx->cs);
1874#ifdef VBOX_WITH_STATISTICS
1875 if (pVM->rem.s.Env.segs[R_CS].newselector)
1876 {
1877 STAM_COUNTER_INC(&gStatSelOutOfSync[R_CS]);
1878 }
1879#endif
1880 }
1881 else
1882 pVM->rem.s.Env.segs[R_CS].newselector = 0;
1883
1884 if (pVM->rem.s.Env.segs[R_DS].selector != pCtx->ds)
1885 {
1886 Log2(("REMR3State: DS changed from %04x to %04x!\n", pVM->rem.s.Env.segs[R_DS].selector, pCtx->ds));
1887 sync_seg(&pVM->rem.s.Env, R_DS, pCtx->ds);
1888#ifdef VBOX_WITH_STATISTICS
1889 if (pVM->rem.s.Env.segs[R_DS].newselector)
1890 {
1891 STAM_COUNTER_INC(&gStatSelOutOfSync[R_DS]);
1892 }
1893#endif
1894 }
1895 else
1896 pVM->rem.s.Env.segs[R_DS].newselector = 0;
1897
1898 /** @todo need to find a way to communicate potential GDT/LDT changes and thread switches. The selector might
1899 * be the same but not the base/limit. */
1900 if (pVM->rem.s.Env.segs[R_FS].selector != pCtx->fs)
1901 {
1902 Log2(("REMR3State: FS changed from %04x to %04x!\n", pVM->rem.s.Env.segs[R_FS].selector, pCtx->fs));
1903 sync_seg(&pVM->rem.s.Env, R_FS, pCtx->fs);
1904#ifdef VBOX_WITH_STATISTICS
1905 if (pVM->rem.s.Env.segs[R_FS].newselector)
1906 {
1907 STAM_COUNTER_INC(&gStatSelOutOfSync[R_FS]);
1908 }
1909#endif
1910 }
1911 else
1912 pVM->rem.s.Env.segs[R_FS].newselector = 0;
1913
1914 if (pVM->rem.s.Env.segs[R_GS].selector != pCtx->gs)
1915 {
1916 Log2(("REMR3State: GS changed from %04x to %04x!\n", pVM->rem.s.Env.segs[R_GS].selector, pCtx->gs));
1917 sync_seg(&pVM->rem.s.Env, R_GS, pCtx->gs);
1918#ifdef VBOX_WITH_STATISTICS
1919 if (pVM->rem.s.Env.segs[R_GS].newselector)
1920 {
1921 STAM_COUNTER_INC(&gStatSelOutOfSync[R_GS]);
1922 }
1923#endif
1924 }
1925 else
1926 pVM->rem.s.Env.segs[R_GS].newselector = 0;
1927 }
1928
1929 /*
1930 * Check for traps.
1931 */
1932 pVM->rem.s.Env.exception_index = -1; /** @todo this won't work :/ */
1933 TRPMEVENT enmType;
1934 uint8_t u8TrapNo;
1935 int rc = TRPMQueryTrap(pVM, &u8TrapNo, &enmType);
1936 if (VBOX_SUCCESS(rc))
1937 {
1938 #ifdef DEBUG
1939 if (u8TrapNo == 0x80)
1940 {
1941 remR3DumpLnxSyscall(pVM);
1942 remR3DumpOBsdSyscall(pVM);
1943 }
1944 #endif
1945
1946 pVM->rem.s.Env.exception_index = u8TrapNo;
1947 if (enmType != TRPM_SOFTWARE_INT)
1948 {
1949 pVM->rem.s.Env.exception_is_int = 0;
1950 pVM->rem.s.Env.exception_next_eip = pVM->rem.s.Env.eip;
1951 }
1952 else
1953 {
1954 /*
1955 * The there are two 1 byte opcodes and one 2 byte opcode for software interrupts.
1956 * We ASSUME that there are no prefixes and sets the default to 2 byte, and checks
1957 * for int03 and into.
1958 */
1959 pVM->rem.s.Env.exception_is_int = 1;
1960 pVM->rem.s.Env.exception_next_eip = pCtx->eip + 2;
1961 /* int 3 may be generated by one-byte 0xcc */
1962 if (u8TrapNo == 3)
1963 {
1964 if (read_byte(&pVM->rem.s.Env, pVM->rem.s.Env.segs[R_CS].base + pCtx->eip) == 0xcc)
1965 pVM->rem.s.Env.exception_next_eip = pCtx->eip + 1;
1966 }
1967 /* int 4 may be generated by one-byte 0xce */
1968 else if (u8TrapNo == 4)
1969 {
1970 if (read_byte(&pVM->rem.s.Env, pVM->rem.s.Env.segs[R_CS].base + pCtx->eip) == 0xce)
1971 pVM->rem.s.Env.exception_next_eip = pCtx->eip + 1;
1972 }
1973 }
1974
1975 /* get error code and cr2 if needed. */
1976 switch (u8TrapNo)
1977 {
1978 case 0x0e:
1979 pVM->rem.s.Env.cr[2] = TRPMGetFaultAddress(pVM);
1980 /* fallthru */
1981 case 0x0a: case 0x0b: case 0x0c: case 0x0d:
1982 pVM->rem.s.Env.error_code = TRPMGetErrorCode(pVM);
1983 break;
1984
1985 case 0x11: case 0x08:
1986 default:
1987 pVM->rem.s.Env.error_code = 0;
1988 break;
1989 }
1990
1991 /*
1992 * We can now reset the active trap since the recompiler is gonna have a go at it.
1993 */
1994 rc = TRPMResetTrap(pVM);
1995 AssertRC(rc);
1996 Log2(("REMR3State: trap=%02x errcd=%VGv cr2=%VGv nexteip=%VGv%s\n", pVM->rem.s.Env.exception_index, pVM->rem.s.Env.error_code,
1997 pVM->rem.s.Env.cr[2], pVM->rem.s.Env.exception_next_eip, pVM->rem.s.Env.exception_is_int ? " software" : ""));
1998 }
1999
2000 /*
2001 * Clear old interrupt request flags; Check for pending hardware interrupts.
2002 * (See @remark for why we don't check for other FFs.)
2003 */
2004 pVM->rem.s.Env.interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_EXIT | CPU_INTERRUPT_EXITTB | CPU_INTERRUPT_TIMER);
2005 if ( pVM->rem.s.u32PendingInterrupt != REM_NO_PENDING_IRQ
2006 || VM_FF_ISPENDING(pVM, VM_FF_INTERRUPT_APIC | VM_FF_INTERRUPT_PIC))
2007 pVM->rem.s.Env.interrupt_request |= CPU_INTERRUPT_HARD;
2008
2009 /*
2010 * We're now in REM mode.
2011 */
2012 pVM->rem.s.fInREM = true;
2013 pVM->rem.s.fInStateSync = false;
2014 pVM->rem.s.cCanExecuteRaw = 0;
2015 STAM_PROFILE_STOP(&pVM->rem.s.StatsState, a);
2016 Log2(("REMR3State: returns VINF_SUCCESS\n"));
2017 return VINF_SUCCESS;
2018}
2019
2020
2021/**
2022 * Syncs back changes in the REM state to the the VM state.
2023 *
2024 * This must be called after invoking REMR3Run().
2025 * Calling it several times in a row is not permitted.
2026 *
2027 * @returns VBox status code.
2028 *
2029 * @param pVM VM Handle.
2030 */
2031REMR3DECL(int) REMR3StateBack(PVM pVM)
2032{
2033 Log2(("REMR3StateBack:\n"));
2034 Assert(pVM->rem.s.fInREM);
2035 STAM_PROFILE_START(&pVM->rem.s.StatsStateBack, a);
2036 register PCPUMCTX pCtx = pVM->rem.s.pCtx;
2037
2038 /*
2039 * Copy back the registers.
2040 * This is done in the order they are declared in the CPUMCTX structure.
2041 */
2042
2043 /** @todo FOP */
2044 /** @todo FPUIP */
2045 /** @todo CS */
2046 /** @todo FPUDP */
2047 /** @todo DS */
2048 /** @todo Fix MXCSR support in QEMU so we don't overwrite MXCSR with 0 when we shouldn't! */
2049 pCtx->fpu.MXCSR = 0;
2050 pCtx->fpu.MXCSR_MASK = 0;
2051
2052 /** @todo check if FPU/XMM was actually used in the recompiler */
2053 restore_raw_fp_state(&pVM->rem.s.Env, (uint8_t *)&pCtx->fpu);
2054//// dprintf2(("FPU state CW=%04X TT=%04X SW=%04X (%04X)\n", env->fpuc, env->fpstt, env->fpus, pVMCtx->fpu.FSW));
2055
2056 pCtx->edi = pVM->rem.s.Env.regs[R_EDI];
2057 pCtx->esi = pVM->rem.s.Env.regs[R_ESI];
2058 pCtx->ebp = pVM->rem.s.Env.regs[R_EBP];
2059 pCtx->eax = pVM->rem.s.Env.regs[R_EAX];
2060 pCtx->ebx = pVM->rem.s.Env.regs[R_EBX];
2061 pCtx->edx = pVM->rem.s.Env.regs[R_EDX];
2062 pCtx->ecx = pVM->rem.s.Env.regs[R_ECX];
2063
2064 pCtx->esp = pVM->rem.s.Env.regs[R_ESP];
2065 pCtx->ss = pVM->rem.s.Env.segs[R_SS].selector;
2066
2067#ifdef VBOX_WITH_STATISTICS
2068 if (pVM->rem.s.Env.segs[R_SS].newselector)
2069 {
2070 STAM_COUNTER_INC(&gStatSelOutOfSyncStateBack[R_SS]);
2071 }
2072 if (pVM->rem.s.Env.segs[R_GS].newselector)
2073 {
2074 STAM_COUNTER_INC(&gStatSelOutOfSyncStateBack[R_GS]);
2075 }
2076 if (pVM->rem.s.Env.segs[R_FS].newselector)
2077 {
2078 STAM_COUNTER_INC(&gStatSelOutOfSyncStateBack[R_FS]);
2079 }
2080 if (pVM->rem.s.Env.segs[R_ES].newselector)
2081 {
2082 STAM_COUNTER_INC(&gStatSelOutOfSyncStateBack[R_ES]);
2083 }
2084 if (pVM->rem.s.Env.segs[R_DS].newselector)
2085 {
2086 STAM_COUNTER_INC(&gStatSelOutOfSyncStateBack[R_DS]);
2087 }
2088 if (pVM->rem.s.Env.segs[R_CS].newselector)
2089 {
2090 STAM_COUNTER_INC(&gStatSelOutOfSyncStateBack[R_CS]);
2091 }
2092#endif
2093 pCtx->gs = pVM->rem.s.Env.segs[R_GS].selector;
2094 pCtx->fs = pVM->rem.s.Env.segs[R_FS].selector;
2095 pCtx->es = pVM->rem.s.Env.segs[R_ES].selector;
2096 pCtx->ds = pVM->rem.s.Env.segs[R_DS].selector;
2097 pCtx->cs = pVM->rem.s.Env.segs[R_CS].selector;
2098
2099 pCtx->eip = pVM->rem.s.Env.eip;
2100 pCtx->eflags.u32 = pVM->rem.s.Env.eflags;
2101
2102 pCtx->cr0 = pVM->rem.s.Env.cr[0];
2103 pCtx->cr2 = pVM->rem.s.Env.cr[2];
2104 pCtx->cr3 = pVM->rem.s.Env.cr[3];
2105 pCtx->cr4 = pVM->rem.s.Env.cr[4];
2106
2107 pCtx->dr0 = pVM->rem.s.Env.dr[0];
2108 pCtx->dr1 = pVM->rem.s.Env.dr[1];
2109 pCtx->dr2 = pVM->rem.s.Env.dr[2];
2110 pCtx->dr3 = pVM->rem.s.Env.dr[3];
2111 pCtx->dr4 = pVM->rem.s.Env.dr[4];
2112 pCtx->dr5 = pVM->rem.s.Env.dr[5];
2113 pCtx->dr6 = pVM->rem.s.Env.dr[6];
2114 pCtx->dr7 = pVM->rem.s.Env.dr[7];
2115
2116 pCtx->gdtr.cbGdt = pVM->rem.s.Env.gdt.limit;
2117 if (pCtx->gdtr.pGdt != (uint32_t)pVM->rem.s.Env.gdt.base)
2118 {
2119 pCtx->gdtr.pGdt = (uint32_t)pVM->rem.s.Env.gdt.base;
2120 STAM_COUNTER_INC(&gStatREMGDTChange);
2121 VM_FF_SET(pVM, VM_FF_SELM_SYNC_GDT);
2122 }
2123
2124 pCtx->idtr.cbIdt = pVM->rem.s.Env.idt.limit;
2125 if (pCtx->idtr.pIdt != (uint32_t)pVM->rem.s.Env.idt.base)
2126 {
2127 pCtx->idtr.pIdt = (uint32_t)pVM->rem.s.Env.idt.base;
2128 STAM_COUNTER_INC(&gStatREMIDTChange);
2129 VM_FF_SET(pVM, VM_FF_TRPM_SYNC_IDT);
2130 }
2131
2132 if (pCtx->ldtr != pVM->rem.s.Env.ldt.selector)
2133 {
2134 pCtx->ldtr = pVM->rem.s.Env.ldt.selector;
2135 STAM_COUNTER_INC(&gStatREMLDTRChange);
2136 VM_FF_SET(pVM, VM_FF_SELM_SYNC_LDT);
2137 }
2138 if (pCtx->tr != pVM->rem.s.Env.tr.selector)
2139 {
2140 pCtx->tr = pVM->rem.s.Env.tr.selector;
2141 STAM_COUNTER_INC(&gStatREMTRChange);
2142 VM_FF_SET(pVM, VM_FF_SELM_SYNC_TSS);
2143 }
2144
2145 /** @todo These values could still be out of sync! */
2146 pCtx->csHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_CS].base;
2147 pCtx->csHid.u32Limit = pVM->rem.s.Env.segs[R_CS].limit;
2148 /** @note QEmu saves the 2nd dword of the descriptor; we should store the attribute word only! */
2149 pCtx->csHid.Attr.u = (pVM->rem.s.Env.segs[R_CS].flags >> 8) & 0xF0FF;
2150
2151 pCtx->dsHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_DS].base;
2152 pCtx->dsHid.u32Limit = pVM->rem.s.Env.segs[R_DS].limit;
2153 pCtx->dsHid.Attr.u = (pVM->rem.s.Env.segs[R_DS].flags >> 8) & 0xF0FF;
2154
2155 pCtx->esHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_ES].base;
2156 pCtx->esHid.u32Limit = pVM->rem.s.Env.segs[R_ES].limit;
2157 pCtx->esHid.Attr.u = (pVM->rem.s.Env.segs[R_ES].flags >> 8) & 0xF0FF;
2158
2159 pCtx->fsHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_FS].base;
2160 pCtx->fsHid.u32Limit = pVM->rem.s.Env.segs[R_FS].limit;
2161 pCtx->fsHid.Attr.u = (pVM->rem.s.Env.segs[R_FS].flags >> 8) & 0xF0FF;
2162
2163 pCtx->gsHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_GS].base;
2164 pCtx->gsHid.u32Limit = pVM->rem.s.Env.segs[R_GS].limit;
2165 pCtx->gsHid.Attr.u = (pVM->rem.s.Env.segs[R_GS].flags >> 8) & 0xF0FF;
2166
2167 pCtx->ssHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_SS].base;
2168 pCtx->ssHid.u32Limit = pVM->rem.s.Env.segs[R_SS].limit;
2169 pCtx->ssHid.Attr.u = (pVM->rem.s.Env.segs[R_SS].flags >> 8) & 0xF0FF;
2170
2171 pCtx->ldtrHid.u32Base = (uint32_t)pVM->rem.s.Env.ldt.base;
2172 pCtx->ldtrHid.u32Limit = pVM->rem.s.Env.ldt.limit;
2173 pCtx->ldtrHid.Attr.u = (pVM->rem.s.Env.ldt.flags >> 8) & 0xF0FF;
2174
2175 pCtx->trHid.u32Base = (uint32_t)pVM->rem.s.Env.tr.base;
2176 pCtx->trHid.u32Limit = pVM->rem.s.Env.tr.limit;
2177 pCtx->trHid.Attr.u = (pVM->rem.s.Env.tr.flags >> 8) & 0xF0FF;
2178
2179 /* Sysenter MSR */
2180 pCtx->SysEnter.cs = pVM->rem.s.Env.sysenter_cs;
2181 pCtx->SysEnter.eip = pVM->rem.s.Env.sysenter_eip;
2182 pCtx->SysEnter.esp = pVM->rem.s.Env.sysenter_esp;
2183
2184 remR3TrapClear(pVM);
2185
2186 /*
2187 * Check for traps.
2188 */
2189 if ( pVM->rem.s.Env.exception_index >= 0
2190 && pVM->rem.s.Env.exception_index < 256)
2191 {
2192 Log(("REMR3StateBack: Pending trap %x %d\n", pVM->rem.s.Env.exception_index, pVM->rem.s.Env.exception_is_int));
2193 int rc = TRPMAssertTrap(pVM, pVM->rem.s.Env.exception_index, (pVM->rem.s.Env.exception_is_int) ? TRPM_SOFTWARE_INT : TRPM_HARDWARE_INT);
2194 AssertRC(rc);
2195 switch (pVM->rem.s.Env.exception_index)
2196 {
2197 case 0x0e:
2198 TRPMSetFaultAddress(pVM, pCtx->cr2);
2199 /* fallthru */
2200 case 0x0a: case 0x0b: case 0x0c: case 0x0d:
2201 case 0x11: case 0x08: /* 0 */
2202 TRPMSetErrorCode(pVM, pVM->rem.s.Env.error_code);
2203 break;
2204 }
2205
2206 }
2207
2208 /*
2209 * We're not longer in REM mode.
2210 */
2211 pVM->rem.s.fInREM = false;
2212 STAM_PROFILE_STOP(&pVM->rem.s.StatsStateBack, a);
2213 Log2(("REMR3StateBack: returns VINF_SUCCESS\n"));
2214 return VINF_SUCCESS;
2215}
2216
2217
2218/**
2219 * This is called by the disassembler when it wants to update the cpu state
2220 * before for instance doing a register dump.
2221 */
2222static void remR3StateUpdate(PVM pVM)
2223{
2224 Assert(pVM->rem.s.fInREM);
2225 register PCPUMCTX pCtx = pVM->rem.s.pCtx;
2226
2227 /*
2228 * Copy back the registers.
2229 * This is done in the order they are declared in the CPUMCTX structure.
2230 */
2231
2232 /** @todo FOP */
2233 /** @todo FPUIP */
2234 /** @todo CS */
2235 /** @todo FPUDP */
2236 /** @todo DS */
2237 /** @todo Fix MXCSR support in QEMU so we don't overwrite MXCSR with 0 when we shouldn't! */
2238 pCtx->fpu.MXCSR = 0;
2239 pCtx->fpu.MXCSR_MASK = 0;
2240
2241 /** @todo check if FPU/XMM was actually used in the recompiler */
2242 restore_raw_fp_state(&pVM->rem.s.Env, (uint8_t *)&pCtx->fpu);
2243//// dprintf2(("FPU state CW=%04X TT=%04X SW=%04X (%04X)\n", env->fpuc, env->fpstt, env->fpus, pVMCtx->fpu.FSW));
2244
2245 pCtx->edi = pVM->rem.s.Env.regs[R_EDI];
2246 pCtx->esi = pVM->rem.s.Env.regs[R_ESI];
2247 pCtx->ebp = pVM->rem.s.Env.regs[R_EBP];
2248 pCtx->eax = pVM->rem.s.Env.regs[R_EAX];
2249 pCtx->ebx = pVM->rem.s.Env.regs[R_EBX];
2250 pCtx->edx = pVM->rem.s.Env.regs[R_EDX];
2251 pCtx->ecx = pVM->rem.s.Env.regs[R_ECX];
2252
2253 pCtx->esp = pVM->rem.s.Env.regs[R_ESP];
2254 pCtx->ss = pVM->rem.s.Env.segs[R_SS].selector;
2255
2256 pCtx->gs = pVM->rem.s.Env.segs[R_GS].selector;
2257 pCtx->fs = pVM->rem.s.Env.segs[R_FS].selector;
2258 pCtx->es = pVM->rem.s.Env.segs[R_ES].selector;
2259 pCtx->ds = pVM->rem.s.Env.segs[R_DS].selector;
2260 pCtx->cs = pVM->rem.s.Env.segs[R_CS].selector;
2261
2262 pCtx->eip = pVM->rem.s.Env.eip;
2263 pCtx->eflags.u32 = pVM->rem.s.Env.eflags;
2264
2265 pCtx->cr0 = pVM->rem.s.Env.cr[0];
2266 pCtx->cr2 = pVM->rem.s.Env.cr[2];
2267 pCtx->cr3 = pVM->rem.s.Env.cr[3];
2268 pCtx->cr4 = pVM->rem.s.Env.cr[4];
2269
2270 pCtx->dr0 = pVM->rem.s.Env.dr[0];
2271 pCtx->dr1 = pVM->rem.s.Env.dr[1];
2272 pCtx->dr2 = pVM->rem.s.Env.dr[2];
2273 pCtx->dr3 = pVM->rem.s.Env.dr[3];
2274 pCtx->dr4 = pVM->rem.s.Env.dr[4];
2275 pCtx->dr5 = pVM->rem.s.Env.dr[5];
2276 pCtx->dr6 = pVM->rem.s.Env.dr[6];
2277 pCtx->dr7 = pVM->rem.s.Env.dr[7];
2278
2279 pCtx->gdtr.cbGdt = pVM->rem.s.Env.gdt.limit;
2280 if (pCtx->gdtr.pGdt != (uint32_t)pVM->rem.s.Env.gdt.base)
2281 {
2282 pCtx->gdtr.pGdt = (uint32_t)pVM->rem.s.Env.gdt.base;
2283 STAM_COUNTER_INC(&gStatREMGDTChange);
2284 VM_FF_SET(pVM, VM_FF_SELM_SYNC_GDT);
2285 }
2286
2287 pCtx->idtr.cbIdt = pVM->rem.s.Env.idt.limit;
2288 if (pCtx->idtr.pIdt != (uint32_t)pVM->rem.s.Env.idt.base)
2289 {
2290 pCtx->idtr.pIdt = (uint32_t)pVM->rem.s.Env.idt.base;
2291 STAM_COUNTER_INC(&gStatREMIDTChange);
2292 VM_FF_SET(pVM, VM_FF_TRPM_SYNC_IDT);
2293 }
2294
2295 if (pCtx->ldtr != pVM->rem.s.Env.ldt.selector)
2296 {
2297 pCtx->ldtr = pVM->rem.s.Env.ldt.selector;
2298 STAM_COUNTER_INC(&gStatREMLDTRChange);
2299 VM_FF_SET(pVM, VM_FF_SELM_SYNC_LDT);
2300 }
2301 if (pCtx->tr != pVM->rem.s.Env.tr.selector)
2302 {
2303 pCtx->tr = pVM->rem.s.Env.tr.selector;
2304 STAM_COUNTER_INC(&gStatREMTRChange);
2305 VM_FF_SET(pVM, VM_FF_SELM_SYNC_TSS);
2306 }
2307
2308 /** @todo These values could still be out of sync! */
2309 pCtx->csHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_CS].base;
2310 pCtx->csHid.u32Limit = pVM->rem.s.Env.segs[R_CS].limit;
2311 /** @note QEmu saves the 2nd dword of the descriptor; we should store the attribute word only! */
2312 pCtx->csHid.Attr.u = (pVM->rem.s.Env.segs[R_CS].flags >> 8) & 0xFFFF;
2313
2314 pCtx->dsHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_DS].base;
2315 pCtx->dsHid.u32Limit = pVM->rem.s.Env.segs[R_DS].limit;
2316 pCtx->dsHid.Attr.u = (pVM->rem.s.Env.segs[R_DS].flags >> 8) & 0xFFFF;
2317
2318 pCtx->esHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_ES].base;
2319 pCtx->esHid.u32Limit = pVM->rem.s.Env.segs[R_ES].limit;
2320 pCtx->esHid.Attr.u = (pVM->rem.s.Env.segs[R_ES].flags >> 8) & 0xFFFF;
2321
2322 pCtx->fsHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_FS].base;
2323 pCtx->fsHid.u32Limit = pVM->rem.s.Env.segs[R_FS].limit;
2324 pCtx->fsHid.Attr.u = (pVM->rem.s.Env.segs[R_FS].flags >> 8) & 0xFFFF;
2325
2326 pCtx->gsHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_GS].base;
2327 pCtx->gsHid.u32Limit = pVM->rem.s.Env.segs[R_GS].limit;
2328 pCtx->gsHid.Attr.u = (pVM->rem.s.Env.segs[R_GS].flags >> 8) & 0xFFFF;
2329
2330 pCtx->ssHid.u32Base = (uint32_t)pVM->rem.s.Env.segs[R_SS].base;
2331 pCtx->ssHid.u32Limit = pVM->rem.s.Env.segs[R_SS].limit;
2332 pCtx->ssHid.Attr.u = (pVM->rem.s.Env.segs[R_SS].flags >> 8) & 0xFFFF;
2333
2334 pCtx->ldtrHid.u32Base = (uint32_t)pVM->rem.s.Env.ldt.base;
2335 pCtx->ldtrHid.u32Limit = pVM->rem.s.Env.ldt.limit;
2336 pCtx->ldtrHid.Attr.u = (pVM->rem.s.Env.ldt.flags >> 8) & 0xFFFF;
2337
2338 pCtx->trHid.u32Base = (uint32_t)pVM->rem.s.Env.tr.base;
2339 pCtx->trHid.u32Limit = pVM->rem.s.Env.tr.limit;
2340 pCtx->trHid.Attr.u = (pVM->rem.s.Env.tr.flags >> 8) & 0xFFFF;
2341
2342 /* Sysenter MSR */
2343 pCtx->SysEnter.cs = pVM->rem.s.Env.sysenter_cs;
2344 pCtx->SysEnter.eip = pVM->rem.s.Env.sysenter_eip;
2345 pCtx->SysEnter.esp = pVM->rem.s.Env.sysenter_esp;
2346}
2347
2348
2349/**
2350 * Update the VMM state information if we're currently in REM.
2351 *
2352 * This method is used by the DBGF and PDMDevice when there is any uncertainty of whether
2353 * we're currently executing in REM and the VMM state is invalid. This method will of
2354 * course check that we're executing in REM before syncing any data over to the VMM.
2355 *
2356 * @param pVM The VM handle.
2357 */
2358REMR3DECL(void) REMR3StateUpdate(PVM pVM)
2359{
2360 if (pVM->rem.s.fInREM)
2361 remR3StateUpdate(pVM);
2362}
2363
2364
2365#undef LOG_GROUP
2366#define LOG_GROUP LOG_GROUP_REM
2367
2368
2369/**
2370 * Notify the recompiler about Address Gate 20 state change.
2371 *
2372 * This notification is required since A20 gate changes are
2373 * initialized from a device driver and the VM might just as
2374 * well be in REM mode as in RAW mode.
2375 *
2376 * @param pVM VM handle.
2377 * @param fEnable True if the gate should be enabled.
2378 * False if the gate should be disabled.
2379 */
2380REMR3DECL(void) REMR3A20Set(PVM pVM, bool fEnable)
2381{
2382 LogFlow(("REMR3A20Set: fEnable=%d\n", fEnable));
2383 VM_ASSERT_EMT(pVM);
2384 cpu_x86_set_a20(&pVM->rem.s.Env, fEnable);
2385}
2386
2387
2388/**
2389 * Replays the invalidated recorded pages.
2390 * Called in response to VERR_REM_FLUSHED_PAGES_OVERFLOW from the RAW execution loop.
2391 *
2392 * @param pVM VM handle.
2393 */
2394REMR3DECL(void) REMR3ReplayInvalidatedPages(PVM pVM)
2395{
2396 VM_ASSERT_EMT(pVM);
2397
2398 /*
2399 * Sync the required registers.
2400 */
2401 pVM->rem.s.Env.cr[0] = pVM->rem.s.pCtx->cr0;
2402 pVM->rem.s.Env.cr[2] = pVM->rem.s.pCtx->cr2;
2403 pVM->rem.s.Env.cr[3] = pVM->rem.s.pCtx->cr3;
2404 pVM->rem.s.Env.cr[4] = pVM->rem.s.pCtx->cr4;
2405
2406 /*
2407 * Replay the flushes.
2408 */
2409 pVM->rem.s.fIgnoreInvlPg = true;
2410 RTUINT i;
2411 for (i = 0; i < pVM->rem.s.cInvalidatedPages; i++)
2412 {
2413 Log2(("REMR3ReplayInvalidatedPages: invlpg %VGv\n", pVM->rem.s.aGCPtrInvalidatedPages[i]));
2414 tlb_flush_page(&pVM->rem.s.Env, pVM->rem.s.aGCPtrInvalidatedPages[i]);
2415 }
2416 pVM->rem.s.fIgnoreInvlPg = false;
2417 pVM->rem.s.cInvalidatedPages = 0;
2418}
2419
2420
2421/**
2422 * Replays the invalidated recorded pages.
2423 * Called in response to VERR_REM_FLUSHED_PAGES_OVERFLOW from the RAW execution loop.
2424 *
2425 * @param pVM VM handle.
2426 */
2427REMR3DECL(void) REMR3ReplayHandlerNotifications(PVM pVM)
2428{
2429 LogFlow(("REMR3ReplayInvalidatedPages:\n"));
2430 VM_ASSERT_EMT(pVM);
2431
2432 /*
2433 * Replay the flushes.
2434 */
2435 RTUINT i;
2436 const RTUINT c = pVM->rem.s.cHandlerNotifications;
2437 pVM->rem.s.cHandlerNotifications = 0;
2438 for (i = 0; i < c; i++)
2439 {
2440 PREMHANDLERNOTIFICATION pRec = &pVM->rem.s.aHandlerNotifications[i];
2441 switch (pRec->enmKind)
2442 {
2443 case REMHANDLERNOTIFICATIONKIND_PHYSICAL_REGISTER:
2444 REMR3NotifyHandlerPhysicalRegister(pVM,
2445 pRec->u.PhysicalRegister.enmType,
2446 pRec->u.PhysicalRegister.GCPhys,
2447 pRec->u.PhysicalRegister.cb,
2448 pRec->u.PhysicalRegister.fHasHCHandler);
2449 break;
2450
2451 case REMHANDLERNOTIFICATIONKIND_PHYSICAL_DEREGISTER:
2452 REMR3NotifyHandlerPhysicalDeregister(pVM,
2453 pRec->u.PhysicalDeregister.enmType,
2454 pRec->u.PhysicalDeregister.GCPhys,
2455 pRec->u.PhysicalDeregister.cb,
2456 pRec->u.PhysicalDeregister.fHasHCHandler,
2457 pRec->u.PhysicalDeregister.pvHCPtr);
2458 break;
2459
2460 case REMHANDLERNOTIFICATIONKIND_PHYSICAL_MODIFY:
2461 REMR3NotifyHandlerPhysicalModify(pVM,
2462 pRec->u.PhysicalModify.enmType,
2463 pRec->u.PhysicalModify.GCPhysOld,
2464 pRec->u.PhysicalModify.GCPhysNew,
2465 pRec->u.PhysicalModify.cb,
2466 pRec->u.PhysicalModify.fHasHCHandler,
2467 pRec->u.PhysicalModify.pvHCPtr);
2468 break;
2469
2470 default:
2471 AssertReleaseMsgFailed(("enmKind=%d\n", pRec->enmKind));
2472 break;
2473 }
2474 }
2475}
2476
2477
2478/**
2479 * Notify REM about changed code page.
2480 *
2481 * @returns VBox status code.
2482 * @param pVM VM handle.
2483 * @param pvCodePage Code page address
2484 */
2485REMR3DECL(int) REMR3NotifyCodePageChanged(PVM pVM, RTGCPTR pvCodePage)
2486{
2487 int rc;
2488 RTGCPHYS PhysGC;
2489 uint64_t flags;
2490
2491 VM_ASSERT_EMT(pVM);
2492
2493 /*
2494 * Get the physical page address.
2495 */
2496 rc = PGMGstGetPage(pVM, pvCodePage, &flags, &PhysGC);
2497 if (rc == VINF_SUCCESS)
2498 {
2499 /*
2500 * Sync the required registers and flush the whole page.
2501 * (Easier to do the whole page than notifying it about each physical
2502 * byte that was changed.
2503 */
2504 pVM->rem.s.Env.cr[0] = pVM->rem.s.pCtx->cr0;
2505 pVM->rem.s.Env.cr[2] = pVM->rem.s.pCtx->cr2;
2506 pVM->rem.s.Env.cr[3] = pVM->rem.s.pCtx->cr3;
2507 pVM->rem.s.Env.cr[4] = pVM->rem.s.pCtx->cr4;
2508
2509 tb_invalidate_phys_page_range(PhysGC, PhysGC + PAGE_SIZE - 1, 0);
2510 }
2511 return VINF_SUCCESS;
2512}
2513
2514/**
2515 * Notification about a successful MMR3PhysRegister() call.
2516 *
2517 * @param pVM VM handle.
2518 * @param GCPhys The physical address the RAM.
2519 * @param cb Size of the memory.
2520 * @param pvRam The HC address of the RAM.
2521 * @param fFlags Flags of the MM_RAM_FLAGS_* defines.
2522 */
2523REMR3DECL(void) REMR3NotifyPhysRamRegister(PVM pVM, RTGCPHYS GCPhys, RTUINT cb, void *pvRam, unsigned fFlags)
2524{
2525 LogFlow(("REMR3NotifyPhysRamRegister: GCPhys=%VGp cb=%d pvRam=%p fFlags=%d\n", GCPhys, cb, pvRam, fFlags));
2526 VM_ASSERT_EMT(pVM);
2527
2528 /*
2529 * Validate input - we trust the caller.
2530 */
2531 Assert(!GCPhys || pvRam);
2532 Assert(RT_ALIGN_P(pvRam, PAGE_SIZE) == pvRam);
2533 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2534 Assert(cb);
2535 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb);
2536
2537 /*
2538 * Base ram?
2539 */
2540 if (!GCPhys)
2541 {
2542#if !defined(PGM_DYNAMIC_RAM_ALLOC) && !defined(REM_PHYS_ADDR_IN_TLB)
2543 AssertRelease(!phys_ram_base);
2544 phys_ram_base = pvRam;
2545#endif
2546 phys_ram_size = cb;
2547 phys_ram_dirty_size = cb >> PAGE_SHIFT;
2548#ifndef VBOX_STRICT
2549 phys_ram_dirty = MMR3HeapAlloc(pVM, MM_TAG_REM, phys_ram_dirty_size);
2550 AssertReleaseMsg(phys_ram_dirty, ("failed to allocate %d bytes of dirty bytes\n", phys_ram_dirty_size));
2551#else /* VBOX_STRICT: allocate a full map and make the out of bounds pages invalid. */
2552 phys_ram_dirty = RTMemPageAlloc(_4G >> PAGE_SHIFT);
2553 AssertReleaseMsg(phys_ram_dirty, ("failed to allocate %d bytes of dirty bytes\n", _4G >> PAGE_SHIFT));
2554 uint32_t cbBitmap = RT_ALIGN_32(phys_ram_dirty_size, PAGE_SIZE);
2555 int rc = RTMemProtect(phys_ram_dirty + cbBitmap, (_4G >> PAGE_SHIFT) - cbBitmap, RTMEM_PROT_NONE);
2556 AssertRC(rc);
2557 phys_ram_dirty += cbBitmap - phys_ram_dirty_size;
2558#endif
2559 memset(phys_ram_dirty, 0xff, phys_ram_dirty_size);
2560 }
2561
2562 /*
2563 * Register the ram.
2564 */
2565 Assert(!pVM->rem.s.fIgnoreAll);
2566 pVM->rem.s.fIgnoreAll = true;
2567
2568#ifdef PGM_DYNAMIC_RAM_ALLOC
2569 if (!GCPhys)
2570 cpu_register_physical_memory(GCPhys, cb, GCPhys | IO_MEM_RAM_MISSING);
2571 else
2572 {
2573# ifndef REM_PHYS_ADDR_IN_TLB
2574 uint32_t i;
2575# endif
2576
2577 cpu_register_physical_memory(GCPhys, cb, GCPhys | (fFlags & MM_RAM_FLAGS_RESERVED ? IO_MEM_UNASSIGNED : 0));
2578
2579# ifndef REM_PHYS_ADDR_IN_TLB
2580 AssertRelease(pVM->rem.s.cPhysRegistrations < REM_MAX_PHYS_REGISTRATIONS);
2581 for (i = 0; i < pVM->rem.s.cPhysRegistrations; i++)
2582 {
2583 if (pVM->rem.s.aPhysReg[i].GCPhys == GCPhys)
2584 {
2585 pVM->rem.s.aPhysReg[i].HCVirt = (RTHCUINTPTR)pvRam;
2586 pVM->rem.s.aPhysReg[i].cb = cb;
2587 break;
2588 }
2589 }
2590 if (i == pVM->rem.s.cPhysRegistrations)
2591 {
2592 pVM->rem.s.aPhysReg[i].GCPhys = GCPhys;
2593 pVM->rem.s.aPhysReg[i].HCVirt = (RTHCUINTPTR)pvRam;
2594 pVM->rem.s.aPhysReg[i].cb = cb;
2595 pVM->rem.s.cPhysRegistrations++;
2596 }
2597# endif /* !REM_PHYS_ADDR_IN_TLB */
2598 }
2599#elif defined(REM_PHYS_ADDR_IN_TLB)
2600 cpu_register_physical_memory(GCPhys, cb, GCPhys | (fFlags & MM_RAM_FLAGS_RESERVED ? IO_MEM_UNASSIGNED : 0));
2601#else
2602 AssertRelease(phys_ram_base);
2603 cpu_register_physical_memory(GCPhys, cb, ((uintptr_t)pvRam - (uintptr_t)phys_ram_base)
2604 | (fFlags & MM_RAM_FLAGS_RESERVED ? IO_MEM_UNASSIGNED : 0));
2605#endif
2606 Assert(pVM->rem.s.fIgnoreAll);
2607 pVM->rem.s.fIgnoreAll = false;
2608}
2609
2610
2611/**
2612 * Notification about a successful PGMR3PhysRegisterChunk() call.
2613 *
2614 * @param pVM VM handle.
2615 * @param GCPhys The physical address the RAM.
2616 * @param cb Size of the memory.
2617 * @param pvRam The HC address of the RAM.
2618 * @param fFlags Flags of the MM_RAM_FLAGS_* defines.
2619 */
2620REMR3DECL(void) REMR3NotifyPhysRamChunkRegister(PVM pVM, RTGCPHYS GCPhys, RTUINT cb, RTHCUINTPTR pvRam, unsigned fFlags)
2621{
2622#ifdef PGM_DYNAMIC_RAM_ALLOC
2623# ifndef REM_PHYS_ADDR_IN_TLB
2624 uint32_t idx;
2625#endif
2626
2627 Log(("REMR3NotifyPhysRamChunkRegister: GCPhys=%VGp cb=%d pvRam=%p fFlags=%d\n", GCPhys, cb, pvRam, fFlags));
2628 VM_ASSERT_EMT(pVM);
2629
2630 /*
2631 * Validate input - we trust the caller.
2632 */
2633 Assert(pvRam);
2634 Assert(RT_ALIGN(pvRam, PAGE_SIZE) == pvRam);
2635 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2636 Assert(cb == PGM_DYNAMIC_CHUNK_SIZE);
2637 Assert(fFlags == 0 /* normal RAM */);
2638
2639# ifndef REM_PHYS_ADDR_IN_TLB
2640 if (!pVM->rem.s.paHCVirtToGCPhys)
2641 {
2642 uint32_t size = (_4G >> PGM_DYNAMIC_CHUNK_SHIFT) * sizeof(REMCHUNKINFO);
2643
2644 Assert(phys_ram_size);
2645
2646 pVM->rem.s.paHCVirtToGCPhys = (PREMCHUNKINFO)MMR3HeapAllocZ(pVM, MM_TAG_REM, size);
2647 pVM->rem.s.paGCPhysToHCVirt = (RTHCPTR)MMR3HeapAllocZ(pVM, MM_TAG_REM, (phys_ram_size >> PGM_DYNAMIC_CHUNK_SHIFT)*sizeof(RTHCPTR));
2648 }
2649 pVM->rem.s.paGCPhysToHCVirt[GCPhys >> PGM_DYNAMIC_CHUNK_SHIFT] = pvRam;
2650
2651 idx = (pvRam >> PGM_DYNAMIC_CHUNK_SHIFT);
2652 if (!pVM->rem.s.paHCVirtToGCPhys[idx].pChunk1)
2653 {
2654 pVM->rem.s.paHCVirtToGCPhys[idx].pChunk1 = pvRam;
2655 pVM->rem.s.paHCVirtToGCPhys[idx].GCPhys1 = GCPhys;
2656 }
2657 else
2658 {
2659 Assert(!pVM->rem.s.paHCVirtToGCPhys[idx].pChunk2);
2660 pVM->rem.s.paHCVirtToGCPhys[idx].pChunk2 = pvRam;
2661 pVM->rem.s.paHCVirtToGCPhys[idx].GCPhys2 = GCPhys;
2662 }
2663 /* Does the region spawn two chunks? */
2664 if (pvRam & PGM_DYNAMIC_CHUNK_OFFSET_MASK)
2665 {
2666 if (!pVM->rem.s.paHCVirtToGCPhys[idx+1].pChunk1)
2667 {
2668 pVM->rem.s.paHCVirtToGCPhys[idx+1].pChunk1 = pvRam;
2669 pVM->rem.s.paHCVirtToGCPhys[idx+1].GCPhys1 = GCPhys;
2670 }
2671 else
2672 {
2673 Assert(!pVM->rem.s.paHCVirtToGCPhys[idx+1].pChunk2);
2674 pVM->rem.s.paHCVirtToGCPhys[idx+1].pChunk2 = pvRam;
2675 pVM->rem.s.paHCVirtToGCPhys[idx+1].GCPhys2 = GCPhys;
2676 }
2677 }
2678# endif /* !REM_PHYS_ADDR_IN_TLB */
2679
2680 Assert(!pVM->rem.s.fIgnoreAll);
2681 pVM->rem.s.fIgnoreAll = true;
2682
2683 cpu_register_physical_memory(GCPhys, cb, GCPhys);
2684
2685 Assert(pVM->rem.s.fIgnoreAll);
2686 pVM->rem.s.fIgnoreAll = false;
2687
2688#else
2689 AssertReleaseFailed();
2690#endif
2691}
2692
2693
2694#ifdef PGM_DYNAMIC_RAM_ALLOC
2695# ifndef REM_PHYS_ADDR_IN_TLB
2696#if 0
2697static const uint8_t gabZeroPage[PAGE_SIZE];
2698#endif
2699
2700/**
2701 * Convert GC physical address to HC virt
2702 *
2703 * @returns The HC virt address corresponding to addr.
2704 * @param env The cpu environment.
2705 * @param addr The physical address.
2706 */
2707DECLINLINE(void *) remR3GCPhys2HCVirtInlined(PVM pVM, target_ulong addr)
2708{
2709 uint32_t i;
2710 void *pv;
2711 STAM_PROFILE_START(&gStatGCPhys2HCVirt, a);
2712
2713#if 1
2714 /* lookup in pVM->rem.s.aPhysReg array first (for ROM range(s) inside the guest's RAM) */
2715 for (i = 0; i < pVM->rem.s.cPhysRegistrations; i++)
2716 {
2717 RTGCPHYS off = addr - pVM->rem.s.aPhysReg[i].GCPhys;
2718 if (off < pVM->rem.s.aPhysReg[i].cb)
2719 {
2720 pv = (void *)(pVM->rem.s.aPhysReg[i].HCVirt + off);
2721 Log2(("remR3GCPhys2HCVirt: %x -> %x\n", addr, pv));
2722 STAM_PROFILE_STOP(&gStatGCPhys2HCVirt, a);
2723 return pv;
2724 }
2725 }
2726 AssertMsg(addr < phys_ram_size, ("remR3GCPhys2HCVirt: unknown physical address %x\n", addr));
2727 pv = (void *)(pVM->rem.s.paGCPhysToHCVirt[addr >> PGM_DYNAMIC_CHUNK_SHIFT] + (addr & PGM_DYNAMIC_CHUNK_OFFSET_MASK));
2728 Log2(("remR3GCPhys2HCVirt: %x -> %x\n", addr, pv));
2729#else
2730 /** @todo figure out why this is faster than the above code. */
2731 int rc = PGMPhysGCPhys2HCPtr(pVM, addr & X86_PTE_PAE_PG_MASK, PAGE_SIZE, &pv);
2732 if (RT_FAILURE(rc))
2733 {
2734 AssertMsgFailed(("remR3GCPhys2HCVirt: unknown physical address %x\n", addr));
2735 pv = gabZeroPage;
2736 }
2737 pv = (void *)((uintptr_t)pv | (addr & PAGE_OFFSET_MASK));
2738#endif
2739 return pv;
2740}
2741
2742
2743/**
2744 * Convert GC physical address to HC virt
2745 *
2746 * @returns The HC virt address corresponding to addr.
2747 * @param env The cpu environment.
2748 * @param addr The physical address.
2749 */
2750DECLINLINE(target_ulong) remR3HCVirt2GCPhysInlined(PVM pVM, void *addr)
2751{
2752 RTHCUINTPTR HCVirt = (RTHCUINTPTR)addr;
2753 uint32_t idx = (HCVirt >> PGM_DYNAMIC_CHUNK_SHIFT);
2754 RTHCUINTPTR off;
2755 RTUINT i;
2756 target_ulong GCPhys;
2757
2758 off = HCVirt - pVM->rem.s.paHCVirtToGCPhys[idx].pChunk1;
2759
2760 if ( pVM->rem.s.paHCVirtToGCPhys[idx].pChunk1
2761 && off < PGM_DYNAMIC_CHUNK_SIZE)
2762 {
2763 GCPhys = pVM->rem.s.paHCVirtToGCPhys[idx].GCPhys1 + off;
2764 Log2(("remR3HCVirt2GCPhys %x -> %x\n", addr, GCPhys));
2765 return GCPhys;
2766 }
2767
2768 off = HCVirt - pVM->rem.s.paHCVirtToGCPhys[idx].pChunk2;
2769 if ( pVM->rem.s.paHCVirtToGCPhys[idx].pChunk2
2770 && off < PGM_DYNAMIC_CHUNK_SIZE)
2771 {
2772 GCPhys = pVM->rem.s.paHCVirtToGCPhys[idx].GCPhys2 + off;
2773 Log2(("remR3HCVirt2GCPhys %x -> %x\n", addr, GCPhys));
2774 return GCPhys;
2775 }
2776
2777 /* Must be externally registered RAM/ROM range */
2778 for (i = 0; i < pVM->rem.s.cPhysRegistrations; i++)
2779 {
2780 uint32_t off = HCVirt - pVM->rem.s.aPhysReg[i].HCVirt;
2781 if (off < pVM->rem.s.aPhysReg[i].cb)
2782 {
2783 GCPhys = pVM->rem.s.aPhysReg[i].GCPhys + off;
2784 Log2(("remR3HCVirt2GCPhys %x -> %x\n", addr, GCPhys));
2785 return GCPhys;
2786 }
2787 }
2788 AssertReleaseMsgFailed(("No translation for physical address %VHv???\n", addr));
2789 return 0;
2790}
2791
2792/**
2793 * Convert GC physical address to HC virt
2794 *
2795 * @returns The HC virt address corresponding to addr.
2796 * @param env The cpu environment.
2797 * @param addr The physical address.
2798 */
2799void *remR3GCPhys2HCVirt(void *env, target_ulong addr)
2800{
2801 PVM pVM = ((CPUState *)env)->pVM;
2802 void *pv;
2803 STAM_PROFILE_START(&gStatGCPhys2HCVirt, a);
2804 pv = remR3GCPhys2HCVirtInlined(pVM, addr);
2805 STAM_PROFILE_STOP(&gStatGCPhys2HCVirt, a);
2806 return pv;
2807}
2808
2809
2810/**
2811 * Convert GC physical address to HC virt
2812 *
2813 * @returns The HC virt address corresponding to addr.
2814 * @param env The cpu environment.
2815 * @param addr The physical address.
2816 */
2817target_ulong remR3HCVirt2GCPhys(void *env, void *addr)
2818{
2819 PVM pVM = ((CPUState *)env)->pVM;
2820 target_ulong GCPhys;
2821 STAM_PROFILE_START(&gStatHCVirt2GCPhys, a);
2822 GCPhys = remR3HCVirt2GCPhysInlined(pVM, addr);
2823 STAM_PROFILE_STOP(&gStatHCVirt2GCPhys, a);
2824 return GCPhys;
2825}
2826
2827# endif /* !REM_PHYS_ADDR_IN_TLB */
2828
2829/**
2830 * Grows dynamically allocated guest RAM.
2831 * Will raise a fatal error if the operation fails.
2832 *
2833 * @param physaddr The physical address.
2834 */
2835void remR3GrowDynRange(unsigned long physaddr)
2836{
2837 int rc;
2838 PVM pVM = cpu_single_env->pVM;
2839
2840 Log(("remR3GrowDynRange %VGp\n", physaddr));
2841 rc = PGM3PhysGrowRange(pVM, (RTGCPHYS)physaddr);
2842 if (VBOX_SUCCESS(rc))
2843 return;
2844
2845 LogRel(("\nUnable to allocate guest RAM chunk at %VGp\n", physaddr));
2846 cpu_abort(cpu_single_env, "Unable to allocate guest RAM chunk at %VGp\n", physaddr);
2847 AssertFatalFailed();
2848}
2849
2850#endif /* PGM_DYNAMIC_RAM_ALLOC */
2851
2852
2853/**
2854 * Notification about a successful MMR3PhysRomRegister() call.
2855 *
2856 * @param pVM VM handle.
2857 * @param GCPhys The physical address of the ROM.
2858 * @param cb The size of the ROM.
2859 * @param pvCopy Pointer to the ROM copy.
2860 */
2861REMR3DECL(void) REMR3NotifyPhysRomRegister(PVM pVM, RTGCPHYS GCPhys, RTUINT cb, void *pvCopy)
2862{
2863#if defined(PGM_DYNAMIC_RAM_ALLOC) && !defined(REM_PHYS_ADDR_IN_TLB)
2864 uint32_t i;
2865#endif
2866 LogFlow(("REMR3NotifyPhysRomRegister: GCPhys=%VGp cb=%d pvCopy=%p\n", GCPhys, cb, pvCopy));
2867 VM_ASSERT_EMT(pVM);
2868
2869 /*
2870 * Validate input - we trust the caller.
2871 */
2872 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2873 Assert(cb);
2874 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb);
2875 Assert(pvCopy);
2876 Assert(RT_ALIGN_P(pvCopy, PAGE_SIZE) == pvCopy);
2877
2878 /*
2879 * Register the rom.
2880 */
2881 Assert(!pVM->rem.s.fIgnoreAll);
2882 pVM->rem.s.fIgnoreAll = true;
2883
2884#ifdef REM_PHYS_ADDR_IN_TLB
2885 cpu_register_physical_memory(GCPhys, cb, GCPhys | IO_MEM_ROM);
2886#elif defined(PGM_DYNAMIC_RAM_ALLOC)
2887 cpu_register_physical_memory(GCPhys, cb, GCPhys | IO_MEM_ROM);
2888 AssertRelease(pVM->rem.s.cPhysRegistrations < REM_MAX_PHYS_REGISTRATIONS);
2889 for (i = 0; i < pVM->rem.s.cPhysRegistrations; i++)
2890 {
2891 if (pVM->rem.s.aPhysReg[i].GCPhys == GCPhys)
2892 {
2893 pVM->rem.s.aPhysReg[i].HCVirt = (RTHCUINTPTR)pvCopy;
2894 pVM->rem.s.aPhysReg[i].cb = cb;
2895 break;
2896 }
2897 }
2898 if (i == pVM->rem.s.cPhysRegistrations)
2899 {
2900 pVM->rem.s.aPhysReg[i].GCPhys = GCPhys;
2901 pVM->rem.s.aPhysReg[i].HCVirt = (RTHCUINTPTR)pvCopy;
2902 pVM->rem.s.aPhysReg[i].cb = cb;
2903 pVM->rem.s.cPhysRegistrations++;
2904 }
2905#else
2906 AssertRelease(phys_ram_base);
2907 cpu_register_physical_memory(GCPhys, cb, ((uintptr_t)pvCopy - (uintptr_t)phys_ram_base) | IO_MEM_ROM);
2908#endif
2909
2910 Log2(("%.64Vhxd\n", (char *)pvCopy + cb - 64));
2911
2912 Assert(pVM->rem.s.fIgnoreAll);
2913 pVM->rem.s.fIgnoreAll = false;
2914}
2915
2916
2917/**
2918 * Notification about a successful MMR3PhysRegister() call.
2919 *
2920 * @param pVM VM Handle.
2921 * @param GCPhys Start physical address.
2922 * @param cb The size of the range.
2923 */
2924REMR3DECL(void) REMR3NotifyPhysReserve(PVM pVM, RTGCPHYS GCPhys, RTUINT cb)
2925{
2926 LogFlow(("REMR3NotifyPhysReserve: GCPhys=%VGp cb=%d\n", GCPhys, cb));
2927 VM_ASSERT_EMT(pVM);
2928
2929 /*
2930 * Validate input - we trust the caller.
2931 */
2932 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2933 Assert(cb);
2934 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb);
2935
2936 /*
2937 * Unassigning the memory.
2938 */
2939 Assert(!pVM->rem.s.fIgnoreAll);
2940 pVM->rem.s.fIgnoreAll = true;
2941
2942 cpu_register_physical_memory(GCPhys, cb, IO_MEM_UNASSIGNED);
2943
2944 Assert(pVM->rem.s.fIgnoreAll);
2945 pVM->rem.s.fIgnoreAll = false;
2946}
2947
2948
2949/**
2950 * Notification about a successful PGMR3HandlerPhysicalRegister() call.
2951 *
2952 * @param pVM VM Handle.
2953 * @param enmType Handler type.
2954 * @param GCPhys Handler range address.
2955 * @param cb Size of the handler range.
2956 * @param fHasHCHandler Set if the handler has a HC callback function.
2957 *
2958 * @remark MMR3PhysRomRegister assumes that this function will not apply the
2959 * Handler memory type to memory which has no HC handler.
2960 */
2961REMR3DECL(void) REMR3NotifyHandlerPhysicalRegister(PVM pVM, PGMPHYSHANDLERTYPE enmType, RTGCPHYS GCPhys, RTGCPHYS cb, bool fHasHCHandler)
2962{
2963 LogFlow(("REMR3NotifyHandlerPhysicalRegister: enmType=%d GCPhys=%VGp cb=%d fHasHCHandler=%d\n",
2964 enmType, GCPhys, cb, fHasHCHandler));
2965 VM_ASSERT_EMT(pVM);
2966 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2967 Assert(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb);
2968
2969 if (pVM->rem.s.cHandlerNotifications)
2970 REMR3ReplayHandlerNotifications(pVM);
2971
2972 Assert(!pVM->rem.s.fIgnoreAll);
2973 pVM->rem.s.fIgnoreAll = true;
2974
2975 if (enmType == PGMPHYSHANDLERTYPE_MMIO)
2976 cpu_register_physical_memory(GCPhys, cb, pVM->rem.s.iMMIOMemType);
2977 else if (fHasHCHandler)
2978 cpu_register_physical_memory(GCPhys, cb, pVM->rem.s.iHandlerMemType);
2979
2980 Assert(pVM->rem.s.fIgnoreAll);
2981 pVM->rem.s.fIgnoreAll = false;
2982}
2983
2984
2985/**
2986 * Notification about a successful PGMR3HandlerPhysicalDeregister() operation.
2987 *
2988 * @param pVM VM Handle.
2989 * @param enmType Handler type.
2990 * @param GCPhys Handler range address.
2991 * @param cb Size of the handler range.
2992 * @param fHasHCHandler Set if the handler has a HC callback function.
2993 * @param pvHCPtr The HC virtual address corresponding to GCPhys if available.
2994 */
2995REMR3DECL(void) REMR3NotifyHandlerPhysicalDeregister(PVM pVM, PGMPHYSHANDLERTYPE enmType, RTGCPHYS GCPhys, RTGCPHYS cb, bool fHasHCHandler, void *pvHCPtr)
2996{
2997 LogFlow(("REMR3NotifyHandlerPhysicalDeregister: enmType=%d GCPhys=%VGp cb=%d fHasHCHandler=%d pvHCPtr=%p RAM=%08x\n",
2998 enmType, GCPhys, cb, fHasHCHandler, pvHCPtr, MMR3PhysGetRamSize(pVM)));
2999 VM_ASSERT_EMT(pVM);
3000
3001 if (pVM->rem.s.cHandlerNotifications)
3002 REMR3ReplayHandlerNotifications(pVM);
3003
3004 Assert(!pVM->rem.s.fIgnoreAll);
3005 pVM->rem.s.fIgnoreAll = true;
3006
3007 if (enmType == PGMPHYSHANDLERTYPE_MMIO)
3008 cpu_register_physical_memory(GCPhys, cb, IO_MEM_UNASSIGNED);
3009 else if (fHasHCHandler)
3010 {
3011 if (!pvHCPtr)
3012 {
3013 Assert(GCPhys > MMR3PhysGetRamSize(pVM));
3014 cpu_register_physical_memory(GCPhys, cb, IO_MEM_UNASSIGNED);
3015 }
3016 else
3017 {
3018 /* This is not perfect, but it'll do for PD monitoring... */
3019 Assert(cb == PAGE_SIZE);
3020 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
3021#ifdef REM_PHYS_ADDR_IN_TLB
3022 cpu_register_physical_memory(GCPhys, cb, GCPhys);
3023#elif defined(PGM_DYNAMIC_RAM_ALLOC)
3024 Assert(remR3HCVirt2GCPhysInlined(pVM, pvHCPtr) < MMR3PhysGetRamSize(pVM));
3025 cpu_register_physical_memory(GCPhys, cb, GCPhys);
3026#else
3027 Assert((uintptr_t)pvHCPtr - (uintptr_t)phys_ram_base < MMR3PhysGetRamSize(pVM));
3028 cpu_register_physical_memory(GCPhys, cb, (uintptr_t)pvHCPtr - (uintptr_t)phys_ram_base);
3029#endif
3030 }
3031 }
3032
3033 Assert(pVM->rem.s.fIgnoreAll);
3034 pVM->rem.s.fIgnoreAll = false;
3035}
3036
3037
3038/**
3039 * Notification about a successful PGMR3HandlerPhysicalModify() call.
3040 *
3041 * @param pVM VM Handle.
3042 * @param enmType Handler type.
3043 * @param GCPhysOld Old handler range address.
3044 * @param GCPhysNew New handler range address.
3045 * @param cb Size of the handler range.
3046 * @param fHasHCHandler Set if the handler has a HC callback function.
3047 * @param pvHCPtr The HC virtual address corresponding to GCPhys if available.
3048 */
3049REMR3DECL(void) REMR3NotifyHandlerPhysicalModify(PVM pVM, PGMPHYSHANDLERTYPE enmType, RTGCPHYS GCPhysOld, RTGCPHYS GCPhysNew, RTGCPHYS cb, bool fHasHCHandler, void *pvHCPtr)
3050{
3051 LogFlow(("REMR3NotifyHandlerPhysicalModify: enmType=%d GCPhysOld=%VGp GCPhysNew=%VGp cb=%d fHasHCHandler=%d pvHCPtr=%p\n",
3052 enmType, GCPhysOld, GCPhysNew, cb, fHasHCHandler, pvHCPtr));
3053 VM_ASSERT_EMT(pVM);
3054 AssertReleaseMsg(enmType != PGMPHYSHANDLERTYPE_MMIO, ("enmType=%d\n", enmType));
3055
3056 if (pVM->rem.s.cHandlerNotifications)
3057 REMR3ReplayHandlerNotifications(pVM);
3058
3059 if (fHasHCHandler)
3060 {
3061 Assert(!pVM->rem.s.fIgnoreAll);
3062 pVM->rem.s.fIgnoreAll = true;
3063
3064 /*
3065 * Reset the old page.
3066 */
3067 if (!pvHCPtr)
3068 cpu_register_physical_memory(GCPhysOld, cb, IO_MEM_UNASSIGNED);
3069 else
3070 {
3071 /* This is not perfect, but it'll do for PD monitoring... */
3072 Assert(cb == PAGE_SIZE);
3073 Assert(RT_ALIGN_T(GCPhysOld, PAGE_SIZE, RTGCPHYS) == GCPhysOld);
3074#ifdef REM_PHYS_ADDR_IN_TLB
3075 cpu_register_physical_memory(GCPhysOld, cb, GCPhysOld);
3076#elif defined(PGM_DYNAMIC_RAM_ALLOC)
3077 Assert(remR3HCVirt2GCPhysInlined(pVM, pvHCPtr) < MMR3PhysGetRamSize(pVM));
3078 cpu_register_physical_memory(GCPhysOld, cb, GCPhysOld);
3079#else
3080 AssertMsg((uintptr_t)pvHCPtr - (uintptr_t)phys_ram_base < MMR3PhysGetRamSize(pVM),
3081 ("pvHCPtr=%p phys_ram_base=%p size=%RX64 cb=%RGp\n", pvHCPtr, phys_ram_base, MMR3PhysGetRamSize(pVM), cb));
3082 cpu_register_physical_memory(GCPhysOld, cb, (uintptr_t)pvHCPtr - (uintptr_t)phys_ram_base);
3083#endif
3084 }
3085
3086 /*
3087 * Update the new page.
3088 */
3089 Assert(RT_ALIGN_T(GCPhysNew, PAGE_SIZE, RTGCPHYS) == GCPhysNew);
3090 Assert(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb);
3091 cpu_register_physical_memory(GCPhysNew, cb, pVM->rem.s.iHandlerMemType);
3092
3093 Assert(pVM->rem.s.fIgnoreAll);
3094 pVM->rem.s.fIgnoreAll = false;
3095 }
3096}
3097
3098
3099/**
3100 * Checks if we're handling access to this page or not.
3101 *
3102 * @returns true if we're trapping access.
3103 * @returns false if we aren't.
3104 * @param pVM The VM handle.
3105 * @param GCPhys The physical address.
3106 *
3107 * @remark This function will only work correctly in VBOX_STRICT builds!
3108 */
3109REMDECL(bool) REMR3IsPageAccessHandled(PVM pVM, RTGCPHYS GCPhys)
3110{
3111#ifdef VBOX_STRICT
3112 if (pVM->rem.s.cHandlerNotifications)
3113 REMR3ReplayHandlerNotifications(pVM);
3114
3115 unsigned long off = get_phys_page_offset(GCPhys);
3116 return (off & PAGE_OFFSET_MASK) == pVM->rem.s.iHandlerMemType
3117 || (off & PAGE_OFFSET_MASK) == pVM->rem.s.iMMIOMemType
3118 || (off & PAGE_OFFSET_MASK) == IO_MEM_ROM;
3119#else
3120 return false;
3121#endif
3122}
3123
3124
3125/**
3126 * Deals with a rare case in get_phys_addr_code where the code
3127 * is being monitored.
3128 *
3129 * It could also be an MMIO page, in which case we will raise a fatal error.
3130 *
3131 * @returns The physical address corresponding to addr.
3132 * @param env The cpu environment.
3133 * @param addr The virtual address.
3134 * @param pTLBEntry The TLB entry.
3135 */
3136target_ulong remR3PhysGetPhysicalAddressCode(CPUState *env, target_ulong addr, CPUTLBEntry *pTLBEntry)
3137{
3138 PVM pVM = env->pVM;
3139 if ((pTLBEntry->addr_code & ~TARGET_PAGE_MASK) == pVM->rem.s.iHandlerMemType)
3140 {
3141 target_ulong ret = pTLBEntry->addend + addr;
3142 AssertMsg2("remR3PhysGetPhysicalAddressCode: addr=%VGv addr_code=%VGv addend=%VGp ret=%VGp\n",
3143 (RTGCPTR)addr, (RTGCPTR)pTLBEntry->addr_code, (RTGCPHYS)pTLBEntry->addend, ret);
3144 return ret;
3145 }
3146 LogRel(("\nTrying to execute code with memory type addr_code=%VGv addend=%VGp at %VGv! (iHandlerMemType=%#x iMMIOMemType=%#x)\n"
3147 "*** handlers\n",
3148 (RTGCPTR)pTLBEntry->addr_code, (RTGCPHYS)pTLBEntry->addend, (RTGCPTR)addr, pVM->rem.s.iHandlerMemType, pVM->rem.s.iMMIOMemType));
3149 DBGFR3Info(pVM, "handlers", NULL, DBGFR3InfoLogRelHlp());
3150 LogRel(("*** mmio\n"));
3151 DBGFR3Info(pVM, "mmio", NULL, DBGFR3InfoLogRelHlp());
3152 LogRel(("*** phys\n"));
3153 DBGFR3Info(pVM, "phys", NULL, DBGFR3InfoLogRelHlp());
3154 cpu_abort(env, "Trying to execute code with memory type addr_code=%VGv addend=%VGp at %VGv. (iHandlerMemType=%#x iMMIOMemType=%#x)\n",
3155 (RTGCPTR)pTLBEntry->addr_code, (RTGCPHYS)pTLBEntry->addend, (RTGCPTR)addr, pVM->rem.s.iHandlerMemType, pVM->rem.s.iMMIOMemType);
3156 AssertFatalFailed();
3157}
3158
3159
3160/** Validate the physical address passed to the read functions.
3161 * Useful for finding non-guest-ram reads/writes. */
3162#if 1 /* disable if it becomes bothersome... */
3163# define VBOX_CHECK_ADDR(GCPhys) AssertMsg(PGMPhysIsGCPhysValid(cpu_single_env->pVM, (GCPhys)), ("%VGp\n", (GCPhys)))
3164#else
3165# define VBOX_CHECK_ADDR(GCPhys) do { } while (0)
3166#endif
3167
3168/**
3169 * Read guest RAM and ROM.
3170 *
3171 * @param SrcGCPhys The source address (guest physical).
3172 * @param pvDst The destination address.
3173 * @param cb Number of bytes
3174 */
3175void remR3PhysRead(RTGCPHYS SrcGCPhys, void *pvDst, unsigned cb)
3176{
3177 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3178 VBOX_CHECK_ADDR(SrcGCPhys);
3179 PGMPhysRead(cpu_single_env->pVM, SrcGCPhys, pvDst, cb);
3180 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3181}
3182
3183
3184/**
3185 * Read guest RAM and ROM, unsigned 8-bit.
3186 *
3187 * @param SrcGCPhys The source address (guest physical).
3188 */
3189uint8_t remR3PhysReadU8(RTGCPHYS SrcGCPhys)
3190{
3191 uint8_t val;
3192 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3193 VBOX_CHECK_ADDR(SrcGCPhys);
3194 val = PGMR3PhysReadByte(cpu_single_env->pVM, SrcGCPhys);
3195 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3196 return val;
3197}
3198
3199
3200/**
3201 * Read guest RAM and ROM, signed 8-bit.
3202 *
3203 * @param SrcGCPhys The source address (guest physical).
3204 */
3205int8_t remR3PhysReadS8(RTGCPHYS SrcGCPhys)
3206{
3207 int8_t val;
3208 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3209 VBOX_CHECK_ADDR(SrcGCPhys);
3210 val = PGMR3PhysReadByte(cpu_single_env->pVM, SrcGCPhys);
3211 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3212 return val;
3213}
3214
3215
3216/**
3217 * Read guest RAM and ROM, unsigned 16-bit.
3218 *
3219 * @param SrcGCPhys The source address (guest physical).
3220 */
3221uint16_t remR3PhysReadU16(RTGCPHYS SrcGCPhys)
3222{
3223 uint16_t val;
3224 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3225 VBOX_CHECK_ADDR(SrcGCPhys);
3226 val = PGMR3PhysReadWord(cpu_single_env->pVM, SrcGCPhys);
3227 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3228 return val;
3229}
3230
3231
3232/**
3233 * Read guest RAM and ROM, signed 16-bit.
3234 *
3235 * @param SrcGCPhys The source address (guest physical).
3236 */
3237int16_t remR3PhysReadS16(RTGCPHYS SrcGCPhys)
3238{
3239 uint16_t val;
3240 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3241 VBOX_CHECK_ADDR(SrcGCPhys);
3242 val = PGMR3PhysReadWord(cpu_single_env->pVM, SrcGCPhys);
3243 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3244 return val;
3245}
3246
3247
3248/**
3249 * Read guest RAM and ROM, unsigned 32-bit.
3250 *
3251 * @param SrcGCPhys The source address (guest physical).
3252 */
3253uint32_t remR3PhysReadU32(RTGCPHYS SrcGCPhys)
3254{
3255 uint32_t val;
3256 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3257 VBOX_CHECK_ADDR(SrcGCPhys);
3258 val = PGMR3PhysReadDword(cpu_single_env->pVM, SrcGCPhys);
3259 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3260 return val;
3261}
3262
3263
3264/**
3265 * Read guest RAM and ROM, signed 32-bit.
3266 *
3267 * @param SrcGCPhys The source address (guest physical).
3268 */
3269int32_t remR3PhysReadS32(RTGCPHYS SrcGCPhys)
3270{
3271 int32_t val;
3272 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3273 VBOX_CHECK_ADDR(SrcGCPhys);
3274 val = PGMR3PhysReadDword(cpu_single_env->pVM, SrcGCPhys);
3275 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3276 return val;
3277}
3278
3279
3280/**
3281 * Read guest RAM and ROM, unsigned 64-bit.
3282 *
3283 * @param SrcGCPhys The source address (guest physical).
3284 */
3285uint64_t remR3PhysReadU64(RTGCPHYS SrcGCPhys)
3286{
3287 uint64_t val;
3288 STAM_PROFILE_ADV_START(&gStatMemRead, a);
3289 VBOX_CHECK_ADDR(SrcGCPhys);
3290 val = PGMR3PhysReadDword(cpu_single_env->pVM, SrcGCPhys)
3291 | ((uint64_t)PGMR3PhysReadDword(cpu_single_env->pVM, SrcGCPhys + 4) << 32); /** @todo fix me! */
3292 STAM_PROFILE_ADV_STOP(&gStatMemRead, a);
3293 return val;
3294}
3295
3296
3297/**
3298 * Write guest RAM.
3299 *
3300 * @param DstGCPhys The destination address (guest physical).
3301 * @param pvSrc The source address.
3302 * @param cb Number of bytes to write
3303 */
3304void remR3PhysWrite(RTGCPHYS DstGCPhys, const void *pvSrc, unsigned cb)
3305{
3306 STAM_PROFILE_ADV_START(&gStatMemWrite, a);
3307 VBOX_CHECK_ADDR(DstGCPhys);
3308 PGMPhysWrite(cpu_single_env->pVM, DstGCPhys, pvSrc, cb);
3309 STAM_PROFILE_ADV_STOP(&gStatMemWrite, a);
3310}
3311
3312
3313/**
3314 * Write guest RAM, unsigned 8-bit.
3315 *
3316 * @param DstGCPhys The destination address (guest physical).
3317 * @param val Value
3318 */
3319void remR3PhysWriteU8(RTGCPHYS DstGCPhys, uint8_t val)
3320{
3321 STAM_PROFILE_ADV_START(&gStatMemWrite, a);
3322 VBOX_CHECK_ADDR(DstGCPhys);
3323 PGMR3PhysWriteByte(cpu_single_env->pVM, DstGCPhys, val);
3324 STAM_PROFILE_ADV_STOP(&gStatMemWrite, a);
3325}
3326
3327
3328/**
3329 * Write guest RAM, unsigned 8-bit.
3330 *
3331 * @param DstGCPhys The destination address (guest physical).
3332 * @param val Value
3333 */
3334void remR3PhysWriteU16(RTGCPHYS DstGCPhys, uint16_t val)
3335{
3336 STAM_PROFILE_ADV_START(&gStatMemWrite, a);
3337 VBOX_CHECK_ADDR(DstGCPhys);
3338 PGMR3PhysWriteWord(cpu_single_env->pVM, DstGCPhys, val);
3339 STAM_PROFILE_ADV_STOP(&gStatMemWrite, a);
3340}
3341
3342
3343/**
3344 * Write guest RAM, unsigned 32-bit.
3345 *
3346 * @param DstGCPhys The destination address (guest physical).
3347 * @param val Value
3348 */
3349void remR3PhysWriteU32(RTGCPHYS DstGCPhys, uint32_t val)
3350{
3351 STAM_PROFILE_ADV_START(&gStatMemWrite, a);
3352 VBOX_CHECK_ADDR(DstGCPhys);
3353 PGMR3PhysWriteDword(cpu_single_env->pVM, DstGCPhys, val);
3354 STAM_PROFILE_ADV_STOP(&gStatMemWrite, a);
3355}
3356
3357
3358/**
3359 * Write guest RAM, unsigned 64-bit.
3360 *
3361 * @param DstGCPhys The destination address (guest physical).
3362 * @param val Value
3363 */
3364void remR3PhysWriteU64(RTGCPHYS DstGCPhys, uint64_t val)
3365{
3366 STAM_PROFILE_ADV_START(&gStatMemWrite, a);
3367 VBOX_CHECK_ADDR(DstGCPhys);
3368 PGMR3PhysWriteDword(cpu_single_env->pVM, DstGCPhys, (uint32_t)val); /** @todo add U64 interface. */
3369 PGMR3PhysWriteDword(cpu_single_env->pVM, DstGCPhys + 4, val >> 32);
3370 STAM_PROFILE_ADV_STOP(&gStatMemWrite, a);
3371}
3372
3373
3374#ifndef REM_PHYS_ADDR_IN_TLB
3375
3376/**
3377 * Read guest RAM and ROM.
3378 *
3379 * @param pbSrcPhys The source address. Relative to guest RAM.
3380 * @param pvDst The destination address.
3381 * @param cb Number of bytes
3382 */
3383void remR3PhysReadHCPtr(uint8_t *pbSrcPhys, void *pvDst, unsigned cb)
3384{
3385 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3386
3387 /*
3388 * Calc the physical address ('off') and check that it's within the RAM.
3389 * ROM is accessed this way, even if it's not part of the RAM.
3390 */
3391#ifdef PGM_DYNAMIC_RAM_ALLOC
3392 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3393#else
3394 uintptr_t off = pbSrcPhys - phys_ram_base;
3395#endif
3396 PGMPhysRead(cpu_single_env->pVM, (RTGCPHYS)off, pvDst, cb);
3397 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3398}
3399
3400
3401/**
3402 * Read guest RAM and ROM, unsigned 8-bit.
3403 *
3404 * @param pbSrcPhys The source address. Relative to guest RAM.
3405 */
3406uint8_t remR3PhysReadHCPtrU8(uint8_t *pbSrcPhys)
3407{
3408 uint8_t val;
3409
3410 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3411
3412 /*
3413 * Calc the physical address ('off') and check that it's within the RAM.
3414 * ROM is accessed this way, even if it's not part of the RAM.
3415 */
3416#ifdef PGM_DYNAMIC_RAM_ALLOC
3417 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3418#else
3419 uintptr_t off = pbSrcPhys - phys_ram_base;
3420#endif
3421 val = PGMR3PhysReadByte(cpu_single_env->pVM, (RTGCPHYS)off);
3422 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3423 return val;
3424}
3425
3426
3427/**
3428 * Read guest RAM and ROM, signed 8-bit.
3429 *
3430 * @param pbSrcPhys The source address. Relative to guest RAM.
3431 */
3432int8_t remR3PhysReadHCPtrS8(uint8_t *pbSrcPhys)
3433{
3434 int8_t val;
3435
3436 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3437
3438 /*
3439 * Calc the physical address ('off') and check that it's within the RAM.
3440 * ROM is accessed this way, even if it's not part of the RAM.
3441 */
3442#ifdef PGM_DYNAMIC_RAM_ALLOC
3443 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3444#else
3445 uintptr_t off = pbSrcPhys - phys_ram_base;
3446#endif
3447 val = PGMR3PhysReadByte(cpu_single_env->pVM, (RTGCPHYS)off);
3448 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3449 return val;
3450}
3451
3452
3453/**
3454 * Read guest RAM and ROM, unsigned 16-bit.
3455 *
3456 * @param pbSrcPhys The source address. Relative to guest RAM.
3457 */
3458uint16_t remR3PhysReadHCPtrU16(uint8_t *pbSrcPhys)
3459{
3460 uint16_t val;
3461
3462 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3463
3464 /*
3465 * Calc the physical address ('off') and check that it's within the RAM.
3466 * ROM is accessed this way, even if it's not part of the RAM.
3467 */
3468#ifdef PGM_DYNAMIC_RAM_ALLOC
3469 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3470#else
3471 uintptr_t off = pbSrcPhys - phys_ram_base;
3472#endif
3473 val = PGMR3PhysReadWord(cpu_single_env->pVM, (RTGCPHYS)off);
3474 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3475 return val;
3476}
3477
3478
3479/**
3480 * Read guest RAM and ROM, signed 16-bit.
3481 *
3482 * @param pbSrcPhys The source address. Relative to guest RAM.
3483 */
3484int16_t remR3PhysReadHCPtrS16(uint8_t *pbSrcPhys)
3485{
3486 int16_t val;
3487
3488 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3489
3490 /*
3491 * Calc the physical address ('off') and check that it's within the RAM.
3492 * ROM is accessed this way, even if it's not part of the RAM.
3493 */
3494 /** @todo This is rather ugly, but there's no other way when we don't wish to touch *many* other files. */
3495#ifdef PGM_DYNAMIC_RAM_ALLOC
3496 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3497#else
3498 uintptr_t off = pbSrcPhys - phys_ram_base;
3499#endif
3500 val = PGMR3PhysReadWord(cpu_single_env->pVM, (RTGCPHYS)off);
3501 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3502 return val;
3503}
3504
3505
3506/**
3507 * Read guest RAM and ROM, unsigned 32-bit.
3508 *
3509 * @param pbSrcPhys The source address. Relative to guest RAM.
3510 */
3511uint32_t remR3PhysReadHCPtrU32(uint8_t *pbSrcPhys)
3512{
3513 uint32_t val;
3514
3515 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3516
3517 /*
3518 * Calc the physical address ('off') and check that it's within the RAM.
3519 * ROM is accessed this way, even if it's not part of the RAM.
3520 */
3521#ifdef PGM_DYNAMIC_RAM_ALLOC
3522 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3523#else
3524 uintptr_t off = pbSrcPhys - phys_ram_base;
3525#endif
3526 val = PGMR3PhysReadDword(cpu_single_env->pVM, (RTGCPHYS)off);
3527 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3528 return val;
3529}
3530
3531
3532/**
3533 * Read guest RAM and ROM, signed 32-bit.
3534 *
3535 * @param pbSrcPhys The source address. Relative to guest RAM.
3536 */
3537int32_t remR3PhysReadHCPtrS32(uint8_t *pbSrcPhys)
3538{
3539 int32_t val;
3540
3541 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3542
3543 /*
3544 * Calc the physical address ('off') and check that it's within the RAM.
3545 * ROM is accessed this way, even if it's not part of the RAM.
3546 */
3547#ifdef PGM_DYNAMIC_RAM_ALLOC
3548 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3549#else
3550 uintptr_t off = pbSrcPhys - phys_ram_base;
3551#endif
3552 val = PGMR3PhysReadDword(cpu_single_env->pVM, (RTGCPHYS)off);
3553 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3554 return val;
3555}
3556
3557
3558/**
3559 * Read guest RAM and ROM, unsigned 64-bit.
3560 *
3561 * @param pbSrcPhys The source address. Relative to guest RAM.
3562 */
3563uint64_t remR3PhysReadHCPtrU64(uint8_t *pbSrcPhys)
3564{
3565 uint64_t val;
3566
3567 STAM_PROFILE_ADV_START(&gStatMemReadHCPtr, a);
3568
3569 /*
3570 * Calc the physical address ('off') and check that it's within the RAM.
3571 * ROM is accessed this way, even if it's not part of the RAM.
3572 */
3573#ifdef PGM_DYNAMIC_RAM_ALLOC
3574 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbSrcPhys);
3575#else
3576 uintptr_t off = pbSrcPhys - phys_ram_base;
3577#endif
3578 val = PGMR3PhysReadDword(cpu_single_env->pVM, (RTGCPHYS)off)
3579 | ((uint64_t)PGMR3PhysReadDword(cpu_single_env->pVM, (RTGCPHYS)off + 4) << 32); /** @todo fix me! */
3580 STAM_PROFILE_ADV_STOP(&gStatMemReadHCPtr, a);
3581 return val;
3582}
3583
3584
3585/**
3586 * Write guest RAM.
3587 *
3588 * @param pbDstPhys The destination address. Relative to guest RAM.
3589 * @param pvSrc The source address.
3590 * @param cb Number of bytes to write
3591 */
3592void remR3PhysWriteHCPtr(uint8_t *pbDstPhys, const void *pvSrc, unsigned cb)
3593{
3594 STAM_PROFILE_ADV_START(&gStatMemWriteHCPtr, a);
3595 /*
3596 * Calc the physical address ('off') and check that it's within the RAM.
3597 */
3598#ifdef PGM_DYNAMIC_RAM_ALLOC
3599 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbDstPhys);
3600#else
3601 uintptr_t off = pbDstPhys - phys_ram_base;
3602#endif
3603 PGMPhysWrite(cpu_single_env->pVM, (RTGCPHYS)off, pvSrc, cb);
3604 STAM_PROFILE_ADV_STOP(&gStatMemWriteHCPtr, a);
3605}
3606
3607
3608/**
3609 * Write guest RAM, unsigned 8-bit.
3610 *
3611 * @param pbDstPhys The destination address. Relative to guest RAM.
3612 * @param val Value
3613 */
3614void remR3PhysWriteHCPtrU8(uint8_t *pbDstPhys, uint8_t val)
3615{
3616 STAM_PROFILE_ADV_START(&gStatMemWriteHCPtr, a);
3617 /*
3618 * Calc the physical address ('off') and check that it's within the RAM.
3619 */
3620#ifdef PGM_DYNAMIC_RAM_ALLOC
3621 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbDstPhys);
3622#else
3623 uintptr_t off = pbDstPhys - phys_ram_base;
3624#endif
3625 PGMR3PhysWriteByte(cpu_single_env->pVM, (RTGCPHYS)off, val);
3626 STAM_PROFILE_ADV_STOP(&gStatMemWriteHCPtr, a);
3627}
3628
3629
3630/**
3631 * Write guest RAM, unsigned 16-bit.
3632 *
3633 * @param pbDstPhys The destination address. Relative to guest RAM.
3634 * @param val Value
3635 */
3636void remR3PhysWriteHCPtrU16(uint8_t *pbDstPhys, uint16_t val)
3637{
3638 STAM_PROFILE_ADV_START(&gStatMemWriteHCPtr, a);
3639 /*
3640 * Calc the physical address ('off') and check that it's within the RAM.
3641 */
3642#ifdef PGM_DYNAMIC_RAM_ALLOC
3643 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbDstPhys);
3644#else
3645 uintptr_t off = pbDstPhys - phys_ram_base;
3646#endif
3647 PGMR3PhysWriteWord(cpu_single_env->pVM, (RTGCPHYS)off, val);
3648 STAM_PROFILE_ADV_STOP(&gStatMemWriteHCPtr, a);
3649}
3650
3651
3652/**
3653 * Write guest RAM, unsigned 32-bit.
3654 *
3655 * @param pbDstPhys The destination address. Relative to guest RAM.
3656 * @param val Value
3657 */
3658void remR3PhysWriteHCPtrU32(uint8_t *pbDstPhys, uint32_t val)
3659{
3660 STAM_PROFILE_ADV_START(&gStatMemWriteHCPtr, a);
3661 /*
3662 * Calc the physical address ('off') and check that it's within the RAM.
3663 */
3664#ifdef PGM_DYNAMIC_RAM_ALLOC
3665 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbDstPhys);
3666#else
3667 uintptr_t off = pbDstPhys - phys_ram_base;
3668#endif
3669 PGMR3PhysWriteDword(cpu_single_env->pVM, (RTGCPHYS)off, val);
3670 STAM_PROFILE_ADV_STOP(&gStatMemWriteHCPtr, a);
3671}
3672
3673
3674/**
3675 * Write guest RAM, unsigned 64-bit.
3676 *
3677 * @param pbDstPhys The destination address. Relative to guest RAM.
3678 * @param val Value
3679 */
3680void remR3PhysWriteHCPtrU64(uint8_t *pbDstPhys, uint64_t val)
3681{
3682 STAM_PROFILE_ADV_START(&gStatMemWriteHCPtr, a);
3683 /*
3684 * Calc the physical address ('off') and check that it's within the RAM.
3685 */
3686#ifdef PGM_DYNAMIC_RAM_ALLOC
3687 uintptr_t off = remR3HCVirt2GCPhysInlined(cpu_single_env->pVM, pbDstPhys);
3688#else
3689 uintptr_t off = pbDstPhys - phys_ram_base;
3690#endif
3691 PGMR3PhysWriteDword(cpu_single_env->pVM, (RTGCPHYS)off, (uint32_t)val); /** @todo add U64 interface. */
3692 PGMR3PhysWriteDword(cpu_single_env->pVM, (RTGCPHYS)off + 4, val >> 32);
3693 STAM_PROFILE_ADV_STOP(&gStatMemWriteHCPtr, a);
3694}
3695
3696#endif /* !REM_PHYS_ADDR_IN_TLB */
3697
3698
3699#undef LOG_GROUP
3700#define LOG_GROUP LOG_GROUP_REM_MMIO
3701
3702/** Read MMIO memory. */
3703static uint32_t remR3MMIOReadU8(void *pvVM, target_phys_addr_t GCPhys)
3704{
3705 uint32_t u32 = 0;
3706 int rc = IOMMMIORead((PVM)pvVM, GCPhys, &u32, 1);
3707 AssertMsg(rc == VINF_SUCCESS, ("rc=%Vrc\n", rc)); NOREF(rc);
3708 Log2(("remR3MMIOReadU8: GCPhys=%VGp -> %02x\n", GCPhys, u32));
3709 return u32;
3710}
3711
3712/** Read MMIO memory. */
3713static uint32_t remR3MMIOReadU16(void *pvVM, target_phys_addr_t GCPhys)
3714{
3715 uint32_t u32 = 0;
3716 int rc = IOMMMIORead((PVM)pvVM, GCPhys, &u32, 2);
3717 AssertMsg(rc == VINF_SUCCESS, ("rc=%Vrc\n", rc)); NOREF(rc);
3718 Log2(("remR3MMIOReadU16: GCPhys=%VGp -> %04x\n", GCPhys, u32));
3719 return u32;
3720}
3721
3722/** Read MMIO memory. */
3723static uint32_t remR3MMIOReadU32(void *pvVM, target_phys_addr_t GCPhys)
3724{
3725 uint32_t u32 = 0;
3726 int rc = IOMMMIORead((PVM)pvVM, GCPhys, &u32, 4);
3727 AssertMsg(rc == VINF_SUCCESS, ("rc=%Vrc\n", rc)); NOREF(rc);
3728 Log2(("remR3MMIOReadU32: GCPhys=%VGp -> %08x\n", GCPhys, u32));
3729 return u32;
3730}
3731
3732/** Write to MMIO memory. */
3733static void remR3MMIOWriteU8(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32)
3734{
3735 Log2(("remR3MMIOWriteU8: GCPhys=%VGp u32=%#x\n", GCPhys, u32));
3736 int rc = IOMMMIOWrite((PVM)pvVM, GCPhys, u32, 1);
3737 AssertMsg(rc == VINF_SUCCESS, ("rc=%Vrc\n", rc)); NOREF(rc);
3738}
3739
3740/** Write to MMIO memory. */
3741static void remR3MMIOWriteU16(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32)
3742{
3743 Log2(("remR3MMIOWriteU16: GCPhys=%VGp u32=%#x\n", GCPhys, u32));
3744 int rc = IOMMMIOWrite((PVM)pvVM, GCPhys, u32, 2);
3745 AssertMsg(rc == VINF_SUCCESS, ("rc=%Vrc\n", rc)); NOREF(rc);
3746}
3747
3748/** Write to MMIO memory. */
3749static void remR3MMIOWriteU32(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32)
3750{
3751 Log2(("remR3MMIOWriteU32: GCPhys=%VGp u32=%#x\n", GCPhys, u32));
3752 int rc = IOMMMIOWrite((PVM)pvVM, GCPhys, u32, 4);
3753 AssertMsg(rc == VINF_SUCCESS, ("rc=%Vrc\n", rc)); NOREF(rc);
3754}
3755
3756
3757#undef LOG_GROUP
3758#define LOG_GROUP LOG_GROUP_REM_HANDLER
3759
3760/* !!!WARNING!!! This is extremely hackish right now, we assume it's only for LFB access! !!!WARNING!!! */
3761
3762static uint32_t remR3HandlerReadU8(void *pvVM, target_phys_addr_t GCPhys)
3763{
3764 Log2(("remR3HandlerReadU8: GCPhys=%VGp\n", GCPhys));
3765 uint8_t u8;
3766 PGMPhysRead((PVM)pvVM, GCPhys, &u8, sizeof(u8));
3767 return u8;
3768}
3769
3770static uint32_t remR3HandlerReadU16(void *pvVM, target_phys_addr_t GCPhys)
3771{
3772 Log2(("remR3HandlerReadU16: GCPhys=%VGp\n", GCPhys));
3773 uint16_t u16;
3774 PGMPhysRead((PVM)pvVM, GCPhys, &u16, sizeof(u16));
3775 return u16;
3776}
3777
3778static uint32_t remR3HandlerReadU32(void *pvVM, target_phys_addr_t GCPhys)
3779{
3780 Log2(("remR3HandlerReadU32: GCPhys=%VGp\n", GCPhys));
3781 uint32_t u32;
3782 PGMPhysRead((PVM)pvVM, GCPhys, &u32, sizeof(u32));
3783 return u32;
3784}
3785
3786static void remR3HandlerWriteU8(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32)
3787{
3788 Log2(("remR3HandlerWriteU8: GCPhys=%VGp u32=%#x\n", GCPhys, u32));
3789 PGMPhysWrite((PVM)pvVM, GCPhys, &u32, sizeof(uint8_t));
3790}
3791
3792static void remR3HandlerWriteU16(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32)
3793{
3794 Log2(("remR3HandlerWriteU16: GCPhys=%VGp u32=%#x\n", GCPhys, u32));
3795 PGMPhysWrite((PVM)pvVM, GCPhys, &u32, sizeof(uint16_t));
3796}
3797
3798static void remR3HandlerWriteU32(void *pvVM, target_phys_addr_t GCPhys, uint32_t u32)
3799{
3800 Log2(("remR3HandlerWriteU32: GCPhys=%VGp u32=%#x\n", GCPhys, u32));
3801 PGMPhysWrite((PVM)pvVM, GCPhys, &u32, sizeof(uint32_t));
3802}
3803
3804/* -+- disassembly -+- */
3805
3806#undef LOG_GROUP
3807#define LOG_GROUP LOG_GROUP_REM_DISAS
3808
3809
3810/**
3811 * Enables or disables singled stepped disassembly.
3812 *
3813 * @returns VBox status code.
3814 * @param pVM VM handle.
3815 * @param fEnable To enable set this flag, to disable clear it.
3816 */
3817static DECLCALLBACK(int) remR3DisasEnableStepping(PVM pVM, bool fEnable)
3818{
3819 LogFlow(("remR3DisasEnableStepping: fEnable=%d\n", fEnable));
3820 VM_ASSERT_EMT(pVM);
3821
3822 if (fEnable)
3823 pVM->rem.s.Env.state |= CPU_EMULATE_SINGLE_STEP;
3824 else
3825 pVM->rem.s.Env.state &= ~CPU_EMULATE_SINGLE_STEP;
3826 return VINF_SUCCESS;
3827}
3828
3829
3830/**
3831 * Enables or disables singled stepped disassembly.
3832 *
3833 * @returns VBox status code.
3834 * @param pVM VM handle.
3835 * @param fEnable To enable set this flag, to disable clear it.
3836 */
3837REMR3DECL(int) REMR3DisasEnableStepping(PVM pVM, bool fEnable)
3838{
3839 PVMREQ pReq;
3840 int rc;
3841
3842 LogFlow(("REMR3DisasEnableStepping: fEnable=%d\n", fEnable));
3843 if (VM_IS_EMT(pVM))
3844 return remR3DisasEnableStepping(pVM, fEnable);
3845
3846 rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)remR3DisasEnableStepping, 2, pVM, fEnable);
3847 AssertRC(rc);
3848 if (VBOX_SUCCESS(rc))
3849 rc = pReq->iStatus;
3850 VMR3ReqFree(pReq);
3851 return rc;
3852}
3853
3854
3855#if defined(VBOX_WITH_DEBUGGER) && !(defined(RT_OS_WINDOWS) && defined(RT_ARCH_AMD64))
3856/**
3857 * External Debugger Command: .remstep [on|off|1|0]
3858 */
3859static DECLCALLBACK(int) remR3CmdDisasEnableStepping(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PVM pVM, PCDBGCVAR paArgs, unsigned cArgs, PDBGCVAR pResult)
3860{
3861 bool fEnable;
3862 int rc;
3863
3864 /* print status */
3865 if (cArgs == 0)
3866 return pCmdHlp->pfnPrintf(pCmdHlp, NULL, "DisasStepping is %s\n",
3867 pVM->rem.s.Env.state & CPU_EMULATE_SINGLE_STEP ? "enabled" : "disabled");
3868
3869 /* convert the argument and change the mode. */
3870 rc = pCmdHlp->pfnVarToBool(pCmdHlp, &paArgs[0], &fEnable);
3871 if (VBOX_FAILURE(rc))
3872 return pCmdHlp->pfnVBoxError(pCmdHlp, rc, "boolean conversion failed!\n");
3873 rc = REMR3DisasEnableStepping(pVM, fEnable);
3874 if (VBOX_FAILURE(rc))
3875 return pCmdHlp->pfnVBoxError(pCmdHlp, rc, "REMR3DisasEnableStepping failed!\n");
3876 return rc;
3877}
3878#endif
3879
3880
3881/**
3882 * Disassembles n instructions and prints them to the log.
3883 *
3884 * @returns Success indicator.
3885 * @param env Pointer to the recompiler CPU structure.
3886 * @param f32BitCode Indicates that whether or not the code should
3887 * be disassembled as 16 or 32 bit. If -1 the CS
3888 * selector will be inspected.
3889 * @param nrInstructions Nr of instructions to disassemble
3890 * @param pszPrefix
3891 * @remark not currently used for anything but ad-hoc debugging.
3892 */
3893bool remR3DisasBlock(CPUState *env, int f32BitCode, int nrInstructions, char *pszPrefix)
3894{
3895 int i;
3896
3897 /*
3898 * Determin 16/32 bit mode.
3899 */
3900 if (f32BitCode == -1)
3901 f32BitCode = !!(env->segs[R_CS].flags & X86_DESC_DB); /** @todo is this right?!!?!?!?!? */
3902
3903 /*
3904 * Convert cs:eip to host context address.
3905 * We don't care to much about cross page correctness presently.
3906 */
3907 RTGCPTR GCPtrPC = env->segs[R_CS].base + env->eip;
3908 void *pvPC;
3909 if (f32BitCode && (env->cr[0] & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG))
3910 {
3911 /* convert eip to physical address. */
3912 int rc = PGMPhysGCPtr2HCPtrByGstCR3(env->pVM,
3913 GCPtrPC,
3914 env->cr[3],
3915 env->cr[4] & (X86_CR4_PSE | X86_CR4_PAE), /** @todo add longmode flag */
3916 &pvPC);
3917 if (VBOX_FAILURE(rc))
3918 {
3919 if (!PATMIsPatchGCAddr(env->pVM, GCPtrPC))
3920 return false;
3921 pvPC = (char *)PATMR3QueryPatchMemHC(env->pVM, NULL)
3922 + (GCPtrPC - PATMR3QueryPatchMemGC(env->pVM, NULL));
3923 }
3924 }
3925 else
3926 {
3927 /* physical address */
3928 int rc = PGMPhysGCPhys2HCPtr(env->pVM, (RTGCPHYS)GCPtrPC, nrInstructions * 16, &pvPC);
3929 if (VBOX_FAILURE(rc))
3930 return false;
3931 }
3932
3933 /*
3934 * Disassemble.
3935 */
3936 RTINTPTR off = env->eip - (RTINTPTR)pvPC;
3937 DISCPUSTATE Cpu;
3938 Cpu.mode = f32BitCode ? CPUMODE_32BIT : CPUMODE_16BIT;
3939 Cpu.pfnReadBytes = NULL; /** @todo make cs:eip reader for the disassembler. */
3940 //Cpu.dwUserData[0] = (uintptr_t)pVM;
3941 //Cpu.dwUserData[1] = (uintptr_t)pvPC;
3942 //Cpu.dwUserData[2] = GCPtrPC;
3943
3944 for (i=0;i<nrInstructions;i++)
3945 {
3946 char szOutput[256];
3947 uint32_t cbOp;
3948 if (!DISInstr(&Cpu, (uintptr_t)pvPC, off, &cbOp, &szOutput[0]))
3949 return false;
3950 if (pszPrefix)
3951 Log(("%s: %s", pszPrefix, szOutput));
3952 else
3953 Log(("%s", szOutput));
3954
3955 pvPC += cbOp;
3956 }
3957 return true;
3958}
3959
3960
3961/** @todo need to test the new code, using the old code in the mean while. */
3962#define USE_OLD_DUMP_AND_DISASSEMBLY
3963
3964/**
3965 * Disassembles one instruction and prints it to the log.
3966 *
3967 * @returns Success indicator.
3968 * @param env Pointer to the recompiler CPU structure.
3969 * @param f32BitCode Indicates that whether or not the code should
3970 * be disassembled as 16 or 32 bit. If -1 the CS
3971 * selector will be inspected.
3972 * @param pszPrefix
3973 */
3974bool remR3DisasInstr(CPUState *env, int f32BitCode, char *pszPrefix)
3975{
3976#ifdef USE_OLD_DUMP_AND_DISASSEMBLY
3977 PVM pVM = env->pVM;
3978
3979 /*
3980 * Determin 16/32 bit mode.
3981 */
3982 if (f32BitCode == -1)
3983 f32BitCode = !!(env->segs[R_CS].flags & X86_DESC_DB); /** @todo is this right?!!?!?!?!? */
3984
3985 /*
3986 * Log registers
3987 */
3988 if (LogIs2Enabled())
3989 {
3990 remR3StateUpdate(pVM);
3991 DBGFR3InfoLog(pVM, "cpumguest", pszPrefix);
3992 }
3993
3994 /*
3995 * Convert cs:eip to host context address.
3996 * We don't care to much about cross page correctness presently.
3997 */
3998 RTGCPTR GCPtrPC = env->segs[R_CS].base + env->eip;
3999 void *pvPC;
4000 if ((env->cr[0] & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG))
4001 {
4002 /* convert eip to physical address. */
4003 int rc = PGMPhysGCPtr2HCPtrByGstCR3(pVM,
4004 GCPtrPC,
4005 env->cr[3],
4006 env->cr[4] & (X86_CR4_PSE | X86_CR4_PAE),
4007 &pvPC);
4008 if (VBOX_FAILURE(rc))
4009 {
4010 if (!PATMIsPatchGCAddr(pVM, GCPtrPC))
4011 return false;
4012 pvPC = (char *)PATMR3QueryPatchMemHC(pVM, NULL)
4013 + (GCPtrPC - PATMR3QueryPatchMemGC(pVM, NULL));
4014 }
4015 }
4016 else
4017 {
4018
4019 /* physical address */
4020 int rc = PGMPhysGCPhys2HCPtr(pVM, (RTGCPHYS)GCPtrPC, 16, &pvPC);
4021 if (VBOX_FAILURE(rc))
4022 return false;
4023 }
4024
4025 /*
4026 * Disassemble.
4027 */
4028 RTINTPTR off = env->eip - (RTINTPTR)pvPC;
4029 DISCPUSTATE Cpu;
4030 Cpu.mode = f32BitCode ? CPUMODE_32BIT : CPUMODE_16BIT;
4031 Cpu.pfnReadBytes = NULL; /** @todo make cs:eip reader for the disassembler. */
4032 //Cpu.dwUserData[0] = (uintptr_t)pVM;
4033 //Cpu.dwUserData[1] = (uintptr_t)pvPC;
4034 //Cpu.dwUserData[2] = GCPtrPC;
4035 char szOutput[256];
4036 uint32_t cbOp;
4037 if (!DISInstr(&Cpu, (uintptr_t)pvPC, off, &cbOp, &szOutput[0]))
4038 return false;
4039
4040 if (!f32BitCode)
4041 {
4042 if (pszPrefix)
4043 Log(("%s: %04X:%s", pszPrefix, env->segs[R_CS].selector, szOutput));
4044 else
4045 Log(("%04X:%s", env->segs[R_CS].selector, szOutput));
4046 }
4047 else
4048 {
4049 if (pszPrefix)
4050 Log(("%s: %s", pszPrefix, szOutput));
4051 else
4052 Log(("%s", szOutput));
4053 }
4054 return true;
4055
4056#else /* !USE_OLD_DUMP_AND_DISASSEMBLY */
4057 PVM pVM = env->pVM;
4058 const bool fLog = LogIsEnabled();
4059 const bool fLog2 = LogIs2Enabled();
4060 int rc = VINF_SUCCESS;
4061
4062 /*
4063 * Don't bother if there ain't any log output to do.
4064 */
4065 if (!fLog && !fLog2)
4066 return true;
4067
4068 /*
4069 * Update the state so DBGF reads the correct register values.
4070 */
4071 remR3StateUpdate(pVM);
4072
4073 /*
4074 * Log registers if requested.
4075 */
4076 if (!fLog2)
4077 DBGFR3InfoLog(pVM, "cpumguest", pszPrefix);
4078
4079 /*
4080 * Disassemble to log.
4081 */
4082 if (fLog)
4083 rc = DBGFR3DisasInstrCurrentLogInternal(pVM, pszPrefix);
4084
4085 return VBOX_SUCCESS(rc);
4086#endif
4087}
4088
4089
4090/**
4091 * Disassemble recompiled code.
4092 *
4093 * @param phFileIgnored Ignored, logfile usually.
4094 * @param pvCode Pointer to the code block.
4095 * @param cb Size of the code block.
4096 */
4097void disas(FILE *phFileIgnored, void *pvCode, unsigned long cb)
4098{
4099 if (LogIs2Enabled())
4100 {
4101 unsigned off = 0;
4102 char szOutput[256];
4103 DISCPUSTATE Cpu = {0};
4104 Cpu.mode = CPUMODE_32BIT;
4105
4106 RTLogPrintf("Recompiled Code: %p %#lx (%ld) bytes\n", pvCode, cb, cb);
4107 while (off < cb)
4108 {
4109 uint32_t cbInstr;
4110 if (DISInstr(&Cpu, (uintptr_t)pvCode + off, 0, &cbInstr, szOutput))
4111 RTLogPrintf("%s", szOutput);
4112 else
4113 {
4114 RTLogPrintf("disas error\n");
4115 cbInstr = 1;
4116 }
4117 off += cbInstr;
4118 }
4119 }
4120 NOREF(phFileIgnored);
4121}
4122
4123
4124/**
4125 * Disassemble guest code.
4126 *
4127 * @param phFileIgnored Ignored, logfile usually.
4128 * @param uCode The guest address of the code to disassemble. (flat?)
4129 * @param cb Number of bytes to disassemble.
4130 * @param fFlags Flags, probably something which tells if this is 16, 32 or 64 bit code.
4131 */
4132void target_disas(FILE *phFileIgnored, target_ulong uCode, target_ulong cb, int fFlags)
4133{
4134 if (LogIs2Enabled())
4135 {
4136 PVM pVM = cpu_single_env->pVM;
4137
4138 /*
4139 * Update the state so DBGF reads the correct register values (flags).
4140 */
4141 remR3StateUpdate(pVM);
4142
4143 /*
4144 * Do the disassembling.
4145 */
4146 RTLogPrintf("Guest Code: PC=%VGp #VGp (%VGp) bytes fFlags=%d\n", uCode, cb, cb, fFlags);
4147 RTSEL cs = cpu_single_env->segs[R_CS].selector;
4148 RTGCUINTPTR eip = uCode - cpu_single_env->segs[R_CS].base;
4149 for (;;)
4150 {
4151 char szBuf[256];
4152 uint32_t cbInstr;
4153 int rc = DBGFR3DisasInstrEx(pVM,
4154 cs,
4155 eip,
4156 0,
4157 szBuf, sizeof(szBuf),
4158 &cbInstr);
4159 if (VBOX_SUCCESS(rc))
4160 RTLogPrintf("%VGp %s\n", uCode, szBuf);
4161 else
4162 {
4163 RTLogPrintf("%VGp %04x:%VGp: %s\n", uCode, cs, eip, szBuf);
4164 cbInstr = 1;
4165 }
4166
4167 /* next */
4168 if (cb <= cbInstr)
4169 break;
4170 cb -= cbInstr;
4171 uCode += cbInstr;
4172 eip += cbInstr;
4173 }
4174 }
4175 NOREF(phFileIgnored);
4176}
4177
4178
4179/**
4180 * Looks up a guest symbol.
4181 *
4182 * @returns Pointer to symbol name. This is a static buffer.
4183 * @param orig_addr The address in question.
4184 */
4185const char *lookup_symbol(target_ulong orig_addr)
4186{
4187 RTGCINTPTR off = 0;
4188 DBGFSYMBOL Sym;
4189 PVM pVM = cpu_single_env->pVM;
4190 int rc = DBGFR3SymbolByAddr(pVM, orig_addr, &off, &Sym);
4191 if (VBOX_SUCCESS(rc))
4192 {
4193 static char szSym[sizeof(Sym.szName) + 48];
4194 if (!off)
4195 RTStrPrintf(szSym, sizeof(szSym), "%s\n", Sym.szName);
4196 else if (off > 0)
4197 RTStrPrintf(szSym, sizeof(szSym), "%s+%x\n", Sym.szName, off);
4198 else
4199 RTStrPrintf(szSym, sizeof(szSym), "%s-%x\n", Sym.szName, -off);
4200 return szSym;
4201 }
4202 return "<N/A>";
4203}
4204
4205
4206#undef LOG_GROUP
4207#define LOG_GROUP LOG_GROUP_REM
4208
4209
4210/* -+- FF notifications -+- */
4211
4212
4213/**
4214 * Notification about a pending interrupt.
4215 *
4216 * @param pVM VM Handle.
4217 * @param u8Interrupt Interrupt
4218 * @thread The emulation thread.
4219 */
4220REMR3DECL(void) REMR3NotifyPendingInterrupt(PVM pVM, uint8_t u8Interrupt)
4221{
4222 Assert(pVM->rem.s.u32PendingInterrupt == REM_NO_PENDING_IRQ);
4223 pVM->rem.s.u32PendingInterrupt = u8Interrupt;
4224}
4225
4226/**
4227 * Notification about a pending interrupt.
4228 *
4229 * @returns Pending interrupt or REM_NO_PENDING_IRQ
4230 * @param pVM VM Handle.
4231 * @thread The emulation thread.
4232 */
4233REMR3DECL(uint32_t) REMR3QueryPendingInterrupt(PVM pVM)
4234{
4235 return pVM->rem.s.u32PendingInterrupt;
4236}
4237
4238/**
4239 * Notification about the interrupt FF being set.
4240 *
4241 * @param pVM VM Handle.
4242 * @thread The emulation thread.
4243 */
4244REMR3DECL(void) REMR3NotifyInterruptSet(PVM pVM)
4245{
4246 LogFlow(("REMR3NotifyInterruptSet: fInRem=%d interrupts %s\n", pVM->rem.s.fInREM,
4247 (pVM->rem.s.Env.eflags & IF_MASK) && !(pVM->rem.s.Env.hflags & HF_INHIBIT_IRQ_MASK) ? "enabled" : "disabled"));
4248 if (pVM->rem.s.fInREM)
4249 {
4250 if (VM_IS_EMT(pVM))
4251 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_HARD);
4252 else
4253 ASMAtomicOrS32(&cpu_single_env->interrupt_request, CPU_INTERRUPT_EXTERNAL_HARD);
4254 }
4255}
4256
4257
4258/**
4259 * Notification about the interrupt FF being set.
4260 *
4261 * @param pVM VM Handle.
4262 * @thread The emulation thread.
4263 */
4264REMR3DECL(void) REMR3NotifyInterruptClear(PVM pVM)
4265{
4266 LogFlow(("REMR3NotifyInterruptClear:\n"));
4267 VM_ASSERT_EMT(pVM);
4268 if (pVM->rem.s.fInREM)
4269 cpu_reset_interrupt(cpu_single_env, CPU_INTERRUPT_HARD);
4270}
4271
4272
4273/**
4274 * Notification about pending timer(s).
4275 *
4276 * @param pVM VM Handle.
4277 * @thread Any.
4278 */
4279REMR3DECL(void) REMR3NotifyTimerPending(PVM pVM)
4280{
4281#ifndef DEBUG_bird
4282 LogFlow(("REMR3NotifyTimerPending: fInRem=%d\n", pVM->rem.s.fInREM));
4283#endif
4284 if (pVM->rem.s.fInREM)
4285 {
4286 if (VM_IS_EMT(pVM))
4287 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4288 else
4289 ASMAtomicOrS32(&cpu_single_env->interrupt_request, CPU_INTERRUPT_EXTERNAL_TIMER);
4290 }
4291}
4292
4293
4294/**
4295 * Notification about pending DMA transfers.
4296 *
4297 * @param pVM VM Handle.
4298 * @thread Any.
4299 */
4300REMR3DECL(void) REMR3NotifyDmaPending(PVM pVM)
4301{
4302 LogFlow(("REMR3NotifyDmaPending: fInRem=%d\n", pVM->rem.s.fInREM));
4303 if (pVM->rem.s.fInREM)
4304 {
4305 if (VM_IS_EMT(pVM))
4306 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4307 else
4308 ASMAtomicOrS32(&cpu_single_env->interrupt_request, CPU_INTERRUPT_EXTERNAL_DMA);
4309 }
4310}
4311
4312
4313/**
4314 * Notification about pending timer(s).
4315 *
4316 * @param pVM VM Handle.
4317 * @thread Any.
4318 */
4319REMR3DECL(void) REMR3NotifyQueuePending(PVM pVM)
4320{
4321 LogFlow(("REMR3NotifyQueuePending: fInRem=%d\n", pVM->rem.s.fInREM));
4322 if (pVM->rem.s.fInREM)
4323 {
4324 if (VM_IS_EMT(pVM))
4325 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4326 else
4327 ASMAtomicOrS32(&cpu_single_env->interrupt_request, CPU_INTERRUPT_EXTERNAL_EXIT);
4328 }
4329}
4330
4331
4332/**
4333 * Notification about pending FF set by an external thread.
4334 *
4335 * @param pVM VM handle.
4336 * @thread Any.
4337 */
4338REMR3DECL(void) REMR3NotifyFF(PVM pVM)
4339{
4340 LogFlow(("REMR3NotifyFF: fInRem=%d\n", pVM->rem.s.fInREM));
4341 if (pVM->rem.s.fInREM)
4342 {
4343 if (VM_IS_EMT(pVM))
4344 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4345 else
4346 ASMAtomicOrS32(&cpu_single_env->interrupt_request, CPU_INTERRUPT_EXTERNAL_EXIT);
4347 }
4348}
4349
4350
4351#ifdef VBOX_WITH_STATISTICS
4352void remR3ProfileStart(int statcode)
4353{
4354 STAMPROFILEADV *pStat;
4355 switch(statcode)
4356 {
4357 case STATS_EMULATE_SINGLE_INSTR:
4358 pStat = &gStatExecuteSingleInstr;
4359 break;
4360 case STATS_QEMU_COMPILATION:
4361 pStat = &gStatCompilationQEmu;
4362 break;
4363 case STATS_QEMU_RUN_EMULATED_CODE:
4364 pStat = &gStatRunCodeQEmu;
4365 break;
4366 case STATS_QEMU_TOTAL:
4367 pStat = &gStatTotalTimeQEmu;
4368 break;
4369 case STATS_QEMU_RUN_TIMERS:
4370 pStat = &gStatTimers;
4371 break;
4372 case STATS_TLB_LOOKUP:
4373 pStat= &gStatTBLookup;
4374 break;
4375 case STATS_IRQ_HANDLING:
4376 pStat= &gStatIRQ;
4377 break;
4378 case STATS_RAW_CHECK:
4379 pStat = &gStatRawCheck;
4380 break;
4381
4382 default:
4383 AssertMsgFailed(("unknown stat %d\n", statcode));
4384 return;
4385 }
4386 STAM_PROFILE_ADV_START(pStat, a);
4387}
4388
4389
4390void remR3ProfileStop(int statcode)
4391{
4392 STAMPROFILEADV *pStat;
4393 switch(statcode)
4394 {
4395 case STATS_EMULATE_SINGLE_INSTR:
4396 pStat = &gStatExecuteSingleInstr;
4397 break;
4398 case STATS_QEMU_COMPILATION:
4399 pStat = &gStatCompilationQEmu;
4400 break;
4401 case STATS_QEMU_RUN_EMULATED_CODE:
4402 pStat = &gStatRunCodeQEmu;
4403 break;
4404 case STATS_QEMU_TOTAL:
4405 pStat = &gStatTotalTimeQEmu;
4406 break;
4407 case STATS_QEMU_RUN_TIMERS:
4408 pStat = &gStatTimers;
4409 break;
4410 case STATS_TLB_LOOKUP:
4411 pStat= &gStatTBLookup;
4412 break;
4413 case STATS_IRQ_HANDLING:
4414 pStat= &gStatIRQ;
4415 break;
4416 case STATS_RAW_CHECK:
4417 pStat = &gStatRawCheck;
4418 break;
4419 default:
4420 AssertMsgFailed(("unknown stat %d\n", statcode));
4421 return;
4422 }
4423 STAM_PROFILE_ADV_STOP(pStat, a);
4424}
4425#endif
4426
4427/**
4428 * Raise an RC, force rem exit.
4429 *
4430 * @param pVM VM handle.
4431 * @param rc The rc.
4432 */
4433void remR3RaiseRC(PVM pVM, int rc)
4434{
4435 Log(("remR3RaiseRC: rc=%Vrc\n", rc));
4436 Assert(pVM->rem.s.fInREM);
4437 VM_ASSERT_EMT(pVM);
4438 pVM->rem.s.rc = rc;
4439 cpu_interrupt(&pVM->rem.s.Env, CPU_INTERRUPT_RC);
4440}
4441
4442
4443/* -+- timers -+- */
4444
4445uint64_t cpu_get_tsc(CPUX86State *env)
4446{
4447 STAM_COUNTER_INC(&gStatCpuGetTSC);
4448 return TMCpuTickGet(env->pVM);
4449}
4450
4451
4452/* -+- interrupts -+- */
4453
4454void cpu_set_ferr(CPUX86State *env)
4455{
4456 int rc = PDMIsaSetIrq(env->pVM, 13, 1);
4457 LogFlow(("cpu_set_ferr: rc=%d\n", rc)); NOREF(rc);
4458}
4459
4460int cpu_get_pic_interrupt(CPUState *env)
4461{
4462 uint8_t u8Interrupt;
4463 int rc;
4464
4465 /* When we fail to forward interrupts directly in raw mode, we fall back to the recompiler.
4466 * In that case we can't call PDMGetInterrupt anymore, because it has already cleared the interrupt
4467 * with the (a)pic.
4468 */
4469 /** @note We assume we will go directly to the recompiler to handle the pending interrupt! */
4470 /** @todo r=bird: In the long run we should just do the interrupt handling in EM/CPUM/TRPM/somewhere and
4471 * if we cannot execute the interrupt handler in raw-mode just reschedule to REM. Once that is done we
4472 * remove this kludge. */
4473 if (env->pVM->rem.s.u32PendingInterrupt != REM_NO_PENDING_IRQ)
4474 {
4475 rc = VINF_SUCCESS;
4476 Assert(env->pVM->rem.s.u32PendingInterrupt >= 0 && env->pVM->rem.s.u32PendingInterrupt <= 255);
4477 u8Interrupt = env->pVM->rem.s.u32PendingInterrupt;
4478 env->pVM->rem.s.u32PendingInterrupt = REM_NO_PENDING_IRQ;
4479 }
4480 else
4481 rc = PDMGetInterrupt(env->pVM, &u8Interrupt);
4482
4483 LogFlow(("cpu_get_pic_interrupt: u8Interrupt=%d rc=%Vrc\n", u8Interrupt, rc));
4484 if (VBOX_SUCCESS(rc))
4485 {
4486 if (VM_FF_ISPENDING(env->pVM, VM_FF_INTERRUPT_APIC | VM_FF_INTERRUPT_PIC))
4487 env->interrupt_request |= CPU_INTERRUPT_HARD;
4488 return u8Interrupt;
4489 }
4490 return -1;
4491}
4492
4493
4494/* -+- local apic -+- */
4495
4496void cpu_set_apic_base(CPUX86State *env, uint64_t val)
4497{
4498 int rc = PDMApicSetBase(env->pVM, val);
4499 LogFlow(("cpu_set_apic_base: val=%#llx rc=%Vrc\n", val, rc)); NOREF(rc);
4500}
4501
4502uint64_t cpu_get_apic_base(CPUX86State *env)
4503{
4504 uint64_t u64;
4505 int rc = PDMApicGetBase(env->pVM, &u64);
4506 if (VBOX_SUCCESS(rc))
4507 {
4508 LogFlow(("cpu_get_apic_base: returns %#llx \n", u64));
4509 return u64;
4510 }
4511 LogFlow(("cpu_get_apic_base: returns 0 (rc=%Vrc)\n", rc));
4512 return 0;
4513}
4514
4515void cpu_set_apic_tpr(CPUX86State *env, uint8_t val)
4516{
4517 int rc = PDMApicSetTPR(env->pVM, val);
4518 LogFlow(("cpu_set_apic_tpr: val=%#x rc=%Vrc\n", val, rc)); NOREF(rc);
4519}
4520
4521uint8_t cpu_get_apic_tpr(CPUX86State *env)
4522{
4523 uint8_t u8;
4524 int rc = PDMApicGetTPR(env->pVM, &u8);
4525 if (VBOX_SUCCESS(rc))
4526 {
4527 LogFlow(("cpu_get_apic_tpr: returns %#x\n", u8));
4528 return u8;
4529 }
4530 LogFlow(("cpu_get_apic_tpr: returns 0 (rc=%Vrc)\n", rc));
4531 return 0;
4532}
4533
4534
4535/* -+- I/O Ports -+- */
4536
4537#undef LOG_GROUP
4538#define LOG_GROUP LOG_GROUP_REM_IOPORT
4539
4540void cpu_outb(CPUState *env, int addr, int val)
4541{
4542 if (addr != 0x80 && addr != 0x70 && addr != 0x61)
4543 Log2(("cpu_outb: addr=%#06x val=%#x\n", addr, val));
4544
4545 int rc = IOMIOPortWrite(env->pVM, (RTIOPORT)addr, val, 1);
4546 if (RT_LIKELY(rc == VINF_SUCCESS))
4547 return;
4548 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
4549 {
4550 Log(("cpu_outb: addr=%#06x val=%#x -> %Vrc\n", addr, val, rc));
4551 remR3RaiseRC(env->pVM, rc);
4552 return;
4553 }
4554 remAbort(rc, __FUNCTION__);
4555}
4556
4557void cpu_outw(CPUState *env, int addr, int val)
4558{
4559 //Log2(("cpu_outw: addr=%#06x val=%#x\n", addr, val));
4560 int rc = IOMIOPortWrite(env->pVM, (RTIOPORT)addr, val, 2);
4561 if (RT_LIKELY(rc == VINF_SUCCESS))
4562 return;
4563 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
4564 {
4565 Log(("cpu_outw: addr=%#06x val=%#x -> %Vrc\n", addr, val, rc));
4566 remR3RaiseRC(env->pVM, rc);
4567 return;
4568 }
4569 remAbort(rc, __FUNCTION__);
4570}
4571
4572void cpu_outl(CPUState *env, int addr, int val)
4573{
4574 Log2(("cpu_outl: addr=%#06x val=%#x\n", addr, val));
4575 int rc = IOMIOPortWrite(env->pVM, (RTIOPORT)addr, val, 4);
4576 if (RT_LIKELY(rc == VINF_SUCCESS))
4577 return;
4578 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
4579 {
4580 Log(("cpu_outl: addr=%#06x val=%#x -> %Vrc\n", addr, val, rc));
4581 remR3RaiseRC(env->pVM, rc);
4582 return;
4583 }
4584 remAbort(rc, __FUNCTION__);
4585}
4586
4587int cpu_inb(CPUState *env, int addr)
4588{
4589 uint32_t u32 = 0;
4590 int rc = IOMIOPortRead(env->pVM, (RTIOPORT)addr, &u32, 1);
4591 if (RT_LIKELY(rc == VINF_SUCCESS))
4592 {
4593 if (/*addr != 0x61 && */addr != 0x71)
4594 Log2(("cpu_inb: addr=%#06x -> %#x\n", addr, u32));
4595 return (int)u32;
4596 }
4597 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
4598 {
4599 Log(("cpu_inb: addr=%#06x -> %#x rc=%Vrc\n", addr, u32, rc));
4600 remR3RaiseRC(env->pVM, rc);
4601 return (int)u32;
4602 }
4603 remAbort(rc, __FUNCTION__);
4604 return 0xff;
4605}
4606
4607int cpu_inw(CPUState *env, int addr)
4608{
4609 uint32_t u32 = 0;
4610 int rc = IOMIOPortRead(env->pVM, (RTIOPORT)addr, &u32, 2);
4611 if (RT_LIKELY(rc == VINF_SUCCESS))
4612 {
4613 Log2(("cpu_inw: addr=%#06x -> %#x\n", addr, u32));
4614 return (int)u32;
4615 }
4616 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
4617 {
4618 Log(("cpu_inw: addr=%#06x -> %#x rc=%Vrc\n", addr, u32, rc));
4619 remR3RaiseRC(env->pVM, rc);
4620 return (int)u32;
4621 }
4622 remAbort(rc, __FUNCTION__);
4623 return 0xffff;
4624}
4625
4626int cpu_inl(CPUState *env, int addr)
4627{
4628 uint32_t u32 = 0;
4629 int rc = IOMIOPortRead(env->pVM, (RTIOPORT)addr, &u32, 4);
4630 if (RT_LIKELY(rc == VINF_SUCCESS))
4631 {
4632//if (addr==0x01f0 && u32 == 0x6b6d)
4633// loglevel = ~0;
4634 Log2(("cpu_inl: addr=%#06x -> %#x\n", addr, u32));
4635 return (int)u32;
4636 }
4637 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
4638 {
4639 Log(("cpu_inl: addr=%#06x -> %#x rc=%Vrc\n", addr, u32, rc));
4640 remR3RaiseRC(env->pVM, rc);
4641 return (int)u32;
4642 }
4643 remAbort(rc, __FUNCTION__);
4644 return 0xffffffff;
4645}
4646
4647#undef LOG_GROUP
4648#define LOG_GROUP LOG_GROUP_REM
4649
4650
4651/* -+- helpers and misc other interfaces -+- */
4652
4653/**
4654 * Perform the CPUID instruction.
4655 *
4656 * ASMCpuId cannot be invoked from some source files where this is used because of global
4657 * register allocations.
4658 *
4659 * @param env Pointer to the recompiler CPU structure.
4660 * @param uOperator CPUID operation (eax).
4661 * @param pvEAX Where to store eax.
4662 * @param pvEBX Where to store ebx.
4663 * @param pvECX Where to store ecx.
4664 * @param pvEDX Where to store edx.
4665 */
4666void remR3CpuId(CPUState *env, unsigned uOperator, void *pvEAX, void *pvEBX, void *pvECX, void *pvEDX)
4667{
4668 CPUMGetGuestCpuId(env->pVM, uOperator, (uint32_t *)pvEAX, (uint32_t *)pvEBX, (uint32_t *)pvECX, (uint32_t *)pvEDX);
4669}
4670
4671
4672#if 0 /* not used */
4673/**
4674 * Interface for qemu hardware to report back fatal errors.
4675 */
4676void hw_error(const char *pszFormat, ...)
4677{
4678 /*
4679 * Bitch about it.
4680 */
4681 /** @todo Add support for nested arg lists in the LogPrintfV routine! I've code for
4682 * this in my Odin32 tree at home! */
4683 va_list args;
4684 va_start(args, pszFormat);
4685 RTLogPrintf("fatal error in virtual hardware:");
4686 RTLogPrintfV(pszFormat, args);
4687 va_end(args);
4688 AssertReleaseMsgFailed(("fatal error in virtual hardware: %s\n", pszFormat));
4689
4690 /*
4691 * If we're in REM context we'll sync back the state before 'jumping' to
4692 * the EMs failure handling.
4693 */
4694 PVM pVM = cpu_single_env->pVM;
4695 if (pVM->rem.s.fInREM)
4696 REMR3StateBack(pVM);
4697 EMR3FatalError(pVM, VERR_REM_VIRTUAL_HARDWARE_ERROR);
4698 AssertMsgFailed(("EMR3FatalError returned!\n"));
4699}
4700#endif
4701
4702/**
4703 * Interface for the qemu cpu to report unhandled situation
4704 * raising a fatal VM error.
4705 */
4706void cpu_abort(CPUState *env, const char *pszFormat, ...)
4707{
4708 /*
4709 * Bitch about it.
4710 */
4711 RTLogFlags(NULL, "nodisabled nobuffered");
4712 va_list args;
4713 va_start(args, pszFormat);
4714 RTLogPrintf("fatal error in recompiler cpu: %N\n", pszFormat, &args);
4715 va_end(args);
4716 va_start(args, pszFormat);
4717 AssertReleaseMsgFailed(("fatal error in recompiler cpu: %N\n", pszFormat, &args));
4718 va_end(args);
4719
4720 /*
4721 * If we're in REM context we'll sync back the state before 'jumping' to
4722 * the EMs failure handling.
4723 */
4724 PVM pVM = cpu_single_env->pVM;
4725 if (pVM->rem.s.fInREM)
4726 REMR3StateBack(pVM);
4727 EMR3FatalError(pVM, VERR_REM_VIRTUAL_CPU_ERROR);
4728 AssertMsgFailed(("EMR3FatalError returned!\n"));
4729}
4730
4731
4732/**
4733 * Aborts the VM.
4734 *
4735 * @param rc VBox error code.
4736 * @param pszTip Hint about why/when this happend.
4737 */
4738static void remAbort(int rc, const char *pszTip)
4739{
4740 /*
4741 * Bitch about it.
4742 */
4743 RTLogPrintf("internal REM fatal error: rc=%Vrc %s\n", rc, pszTip);
4744 AssertReleaseMsgFailed(("internal REM fatal error: rc=%Vrc %s\n", rc, pszTip));
4745
4746 /*
4747 * Jump back to where we entered the recompiler.
4748 */
4749 PVM pVM = cpu_single_env->pVM;
4750 if (pVM->rem.s.fInREM)
4751 REMR3StateBack(pVM);
4752 EMR3FatalError(pVM, rc);
4753 AssertMsgFailed(("EMR3FatalError returned!\n"));
4754}
4755
4756
4757/**
4758 * Dumps a linux system call.
4759 * @param pVM VM handle.
4760 */
4761void remR3DumpLnxSyscall(PVM pVM)
4762{
4763 static const char *apsz[] =
4764 {
4765 "sys_restart_syscall", /* 0 - old "setup()" system call, used for restarting */
4766 "sys_exit",
4767 "sys_fork",
4768 "sys_read",
4769 "sys_write",
4770 "sys_open", /* 5 */
4771 "sys_close",
4772 "sys_waitpid",
4773 "sys_creat",
4774 "sys_link",
4775 "sys_unlink", /* 10 */
4776 "sys_execve",
4777 "sys_chdir",
4778 "sys_time",
4779 "sys_mknod",
4780 "sys_chmod", /* 15 */
4781 "sys_lchown16",
4782 "sys_ni_syscall", /* old break syscall holder */
4783 "sys_stat",
4784 "sys_lseek",
4785 "sys_getpid", /* 20 */
4786 "sys_mount",
4787 "sys_oldumount",
4788 "sys_setuid16",
4789 "sys_getuid16",
4790 "sys_stime", /* 25 */
4791 "sys_ptrace",
4792 "sys_alarm",
4793 "sys_fstat",
4794 "sys_pause",
4795 "sys_utime", /* 30 */
4796 "sys_ni_syscall", /* old stty syscall holder */
4797 "sys_ni_syscall", /* old gtty syscall holder */
4798 "sys_access",
4799 "sys_nice",
4800 "sys_ni_syscall", /* 35 - old ftime syscall holder */
4801 "sys_sync",
4802 "sys_kill",
4803 "sys_rename",
4804 "sys_mkdir",
4805 "sys_rmdir", /* 40 */
4806 "sys_dup",
4807 "sys_pipe",
4808 "sys_times",
4809 "sys_ni_syscall", /* old prof syscall holder */
4810 "sys_brk", /* 45 */
4811 "sys_setgid16",
4812 "sys_getgid16",
4813 "sys_signal",
4814 "sys_geteuid16",
4815 "sys_getegid16", /* 50 */
4816 "sys_acct",
4817 "sys_umount", /* recycled never used phys() */
4818 "sys_ni_syscall", /* old lock syscall holder */
4819 "sys_ioctl",
4820 "sys_fcntl", /* 55 */
4821 "sys_ni_syscall", /* old mpx syscall holder */
4822 "sys_setpgid",
4823 "sys_ni_syscall", /* old ulimit syscall holder */
4824 "sys_olduname",
4825 "sys_umask", /* 60 */
4826 "sys_chroot",
4827 "sys_ustat",
4828 "sys_dup2",
4829 "sys_getppid",
4830 "sys_getpgrp", /* 65 */
4831 "sys_setsid",
4832 "sys_sigaction",
4833 "sys_sgetmask",
4834 "sys_ssetmask",
4835 "sys_setreuid16", /* 70 */
4836 "sys_setregid16",
4837 "sys_sigsuspend",
4838 "sys_sigpending",
4839 "sys_sethostname",
4840 "sys_setrlimit", /* 75 */
4841 "sys_old_getrlimit",
4842 "sys_getrusage",
4843 "sys_gettimeofday",
4844 "sys_settimeofday",
4845 "sys_getgroups16", /* 80 */
4846 "sys_setgroups16",
4847 "old_select",
4848 "sys_symlink",
4849 "sys_lstat",
4850 "sys_readlink", /* 85 */
4851 "sys_uselib",
4852 "sys_swapon",
4853 "sys_reboot",
4854 "old_readdir",
4855 "old_mmap", /* 90 */
4856 "sys_munmap",
4857 "sys_truncate",
4858 "sys_ftruncate",
4859 "sys_fchmod",
4860 "sys_fchown16", /* 95 */
4861 "sys_getpriority",
4862 "sys_setpriority",
4863 "sys_ni_syscall", /* old profil syscall holder */
4864 "sys_statfs",
4865 "sys_fstatfs", /* 100 */
4866 "sys_ioperm",
4867 "sys_socketcall",
4868 "sys_syslog",
4869 "sys_setitimer",
4870 "sys_getitimer", /* 105 */
4871 "sys_newstat",
4872 "sys_newlstat",
4873 "sys_newfstat",
4874 "sys_uname",
4875 "sys_iopl", /* 110 */
4876 "sys_vhangup",
4877 "sys_ni_syscall", /* old "idle" system call */
4878 "sys_vm86old",
4879 "sys_wait4",
4880 "sys_swapoff", /* 115 */
4881 "sys_sysinfo",
4882 "sys_ipc",
4883 "sys_fsync",
4884 "sys_sigreturn",
4885 "sys_clone", /* 120 */
4886 "sys_setdomainname",
4887 "sys_newuname",
4888 "sys_modify_ldt",
4889 "sys_adjtimex",
4890 "sys_mprotect", /* 125 */
4891 "sys_sigprocmask",
4892 "sys_ni_syscall", /* old "create_module" */
4893 "sys_init_module",
4894 "sys_delete_module",
4895 "sys_ni_syscall", /* 130: old "get_kernel_syms" */
4896 "sys_quotactl",
4897 "sys_getpgid",
4898 "sys_fchdir",
4899 "sys_bdflush",
4900 "sys_sysfs", /* 135 */
4901 "sys_personality",
4902 "sys_ni_syscall", /* reserved for afs_syscall */
4903 "sys_setfsuid16",
4904 "sys_setfsgid16",
4905 "sys_llseek", /* 140 */
4906 "sys_getdents",
4907 "sys_select",
4908 "sys_flock",
4909 "sys_msync",
4910 "sys_readv", /* 145 */
4911 "sys_writev",
4912 "sys_getsid",
4913 "sys_fdatasync",
4914 "sys_sysctl",
4915 "sys_mlock", /* 150 */
4916 "sys_munlock",
4917 "sys_mlockall",
4918 "sys_munlockall",
4919 "sys_sched_setparam",
4920 "sys_sched_getparam", /* 155 */
4921 "sys_sched_setscheduler",
4922 "sys_sched_getscheduler",
4923 "sys_sched_yield",
4924 "sys_sched_get_priority_max",
4925 "sys_sched_get_priority_min", /* 160 */
4926 "sys_sched_rr_get_interval",
4927 "sys_nanosleep",
4928 "sys_mremap",
4929 "sys_setresuid16",
4930 "sys_getresuid16", /* 165 */
4931 "sys_vm86",
4932 "sys_ni_syscall", /* Old sys_query_module */
4933 "sys_poll",
4934 "sys_nfsservctl",
4935 "sys_setresgid16", /* 170 */
4936 "sys_getresgid16",
4937 "sys_prctl",
4938 "sys_rt_sigreturn",
4939 "sys_rt_sigaction",
4940 "sys_rt_sigprocmask", /* 175 */
4941 "sys_rt_sigpending",
4942 "sys_rt_sigtimedwait",
4943 "sys_rt_sigqueueinfo",
4944 "sys_rt_sigsuspend",
4945 "sys_pread64", /* 180 */
4946 "sys_pwrite64",
4947 "sys_chown16",
4948 "sys_getcwd",
4949 "sys_capget",
4950 "sys_capset", /* 185 */
4951 "sys_sigaltstack",
4952 "sys_sendfile",
4953 "sys_ni_syscall", /* reserved for streams1 */
4954 "sys_ni_syscall", /* reserved for streams2 */
4955 "sys_vfork", /* 190 */
4956 "sys_getrlimit",
4957 "sys_mmap2",
4958 "sys_truncate64",
4959 "sys_ftruncate64",
4960 "sys_stat64", /* 195 */
4961 "sys_lstat64",
4962 "sys_fstat64",
4963 "sys_lchown",
4964 "sys_getuid",
4965 "sys_getgid", /* 200 */
4966 "sys_geteuid",
4967 "sys_getegid",
4968 "sys_setreuid",
4969 "sys_setregid",
4970 "sys_getgroups", /* 205 */
4971 "sys_setgroups",
4972 "sys_fchown",
4973 "sys_setresuid",
4974 "sys_getresuid",
4975 "sys_setresgid", /* 210 */
4976 "sys_getresgid",
4977 "sys_chown",
4978 "sys_setuid",
4979 "sys_setgid",
4980 "sys_setfsuid", /* 215 */
4981 "sys_setfsgid",
4982 "sys_pivot_root",
4983 "sys_mincore",
4984 "sys_madvise",
4985 "sys_getdents64", /* 220 */
4986 "sys_fcntl64",
4987 "sys_ni_syscall", /* reserved for TUX */
4988 "sys_ni_syscall",
4989 "sys_gettid",
4990 "sys_readahead", /* 225 */
4991 "sys_setxattr",
4992 "sys_lsetxattr",
4993 "sys_fsetxattr",
4994 "sys_getxattr",
4995 "sys_lgetxattr", /* 230 */
4996 "sys_fgetxattr",
4997 "sys_listxattr",
4998 "sys_llistxattr",
4999 "sys_flistxattr",
5000 "sys_removexattr", /* 235 */
5001 "sys_lremovexattr",
5002 "sys_fremovexattr",
5003 "sys_tkill",
5004 "sys_sendfile64",
5005 "sys_futex", /* 240 */
5006 "sys_sched_setaffinity",
5007 "sys_sched_getaffinity",
5008 "sys_set_thread_area",
5009 "sys_get_thread_area",
5010 "sys_io_setup", /* 245 */
5011 "sys_io_destroy",
5012 "sys_io_getevents",
5013 "sys_io_submit",
5014 "sys_io_cancel",
5015 "sys_fadvise64", /* 250 */
5016 "sys_ni_syscall",
5017 "sys_exit_group",
5018 "sys_lookup_dcookie",
5019 "sys_epoll_create",
5020 "sys_epoll_ctl", /* 255 */
5021 "sys_epoll_wait",
5022 "sys_remap_file_pages",
5023 "sys_set_tid_address",
5024 "sys_timer_create",
5025 "sys_timer_settime", /* 260 */
5026 "sys_timer_gettime",
5027 "sys_timer_getoverrun",
5028 "sys_timer_delete",
5029 "sys_clock_settime",
5030 "sys_clock_gettime", /* 265 */
5031 "sys_clock_getres",
5032 "sys_clock_nanosleep",
5033 "sys_statfs64",
5034 "sys_fstatfs64",
5035 "sys_tgkill", /* 270 */
5036 "sys_utimes",
5037 "sys_fadvise64_64",
5038 "sys_ni_syscall" /* sys_vserver */
5039 };
5040
5041 uint32_t uEAX = CPUMGetGuestEAX(pVM);
5042 switch (uEAX)
5043 {
5044 default:
5045 if (uEAX < ELEMENTS(apsz))
5046 Log(("REM: linux syscall %3d: %s (eip=%VGv ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x ebp=%08x)\n",
5047 uEAX, apsz[uEAX], CPUMGetGuestEIP(pVM), CPUMGetGuestEBX(pVM), CPUMGetGuestECX(pVM),
5048 CPUMGetGuestEDX(pVM), CPUMGetGuestESI(pVM), CPUMGetGuestEDI(pVM), CPUMGetGuestEBP(pVM)));
5049 else
5050 Log(("eip=%08x: linux syscall %d (#%x) unknown\n", CPUMGetGuestEIP(pVM), uEAX, uEAX));
5051 break;
5052
5053 }
5054}
5055
5056
5057/**
5058 * Dumps an OpenBSD system call.
5059 * @param pVM VM handle.
5060 */
5061void remR3DumpOBsdSyscall(PVM pVM)
5062{
5063 static const char *apsz[] =
5064 {
5065 "SYS_syscall", //0
5066 "SYS_exit", //1
5067 "SYS_fork", //2
5068 "SYS_read", //3
5069 "SYS_write", //4
5070 "SYS_open", //5
5071 "SYS_close", //6
5072 "SYS_wait4", //7
5073 "SYS_8",
5074 "SYS_link", //9
5075 "SYS_unlink", //10
5076 "SYS_11",
5077 "SYS_chdir", //12
5078 "SYS_fchdir", //13
5079 "SYS_mknod", //14
5080 "SYS_chmod", //15
5081 "SYS_chown", //16
5082 "SYS_break", //17
5083 "SYS_18",
5084 "SYS_19",
5085 "SYS_getpid", //20
5086 "SYS_mount", //21
5087 "SYS_unmount", //22
5088 "SYS_setuid", //23
5089 "SYS_getuid", //24
5090 "SYS_geteuid", //25
5091 "SYS_ptrace", //26
5092 "SYS_recvmsg", //27
5093 "SYS_sendmsg", //28
5094 "SYS_recvfrom", //29
5095 "SYS_accept", //30
5096 "SYS_getpeername", //31
5097 "SYS_getsockname", //32
5098 "SYS_access", //33
5099 "SYS_chflags", //34
5100 "SYS_fchflags", //35
5101 "SYS_sync", //36
5102 "SYS_kill", //37
5103 "SYS_38",
5104 "SYS_getppid", //39
5105 "SYS_40",
5106 "SYS_dup", //41
5107 "SYS_opipe", //42
5108 "SYS_getegid", //43
5109 "SYS_profil", //44
5110 "SYS_ktrace", //45
5111 "SYS_sigaction", //46
5112 "SYS_getgid", //47
5113 "SYS_sigprocmask", //48
5114 "SYS_getlogin", //49
5115 "SYS_setlogin", //50
5116 "SYS_acct", //51
5117 "SYS_sigpending", //52
5118 "SYS_osigaltstack", //53
5119 "SYS_ioctl", //54
5120 "SYS_reboot", //55
5121 "SYS_revoke", //56
5122 "SYS_symlink", //57
5123 "SYS_readlink", //58
5124 "SYS_execve", //59
5125 "SYS_umask", //60
5126 "SYS_chroot", //61
5127 "SYS_62",
5128 "SYS_63",
5129 "SYS_64",
5130 "SYS_65",
5131 "SYS_vfork", //66
5132 "SYS_67",
5133 "SYS_68",
5134 "SYS_sbrk", //69
5135 "SYS_sstk", //70
5136 "SYS_61",
5137 "SYS_vadvise", //72
5138 "SYS_munmap", //73
5139 "SYS_mprotect", //74
5140 "SYS_madvise", //75
5141 "SYS_76",
5142 "SYS_77",
5143 "SYS_mincore", //78
5144 "SYS_getgroups", //79
5145 "SYS_setgroups", //80
5146 "SYS_getpgrp", //81
5147 "SYS_setpgid", //82
5148 "SYS_setitimer", //83
5149 "SYS_84",
5150 "SYS_85",
5151 "SYS_getitimer", //86
5152 "SYS_87",
5153 "SYS_88",
5154 "SYS_89",
5155 "SYS_dup2", //90
5156 "SYS_91",
5157 "SYS_fcntl", //92
5158 "SYS_select", //93
5159 "SYS_94",
5160 "SYS_fsync", //95
5161 "SYS_setpriority", //96
5162 "SYS_socket", //97
5163 "SYS_connect", //98
5164 "SYS_99",
5165 "SYS_getpriority", //100
5166 "SYS_101",
5167 "SYS_102",
5168 "SYS_sigreturn", //103
5169 "SYS_bind", //104
5170 "SYS_setsockopt", //105
5171 "SYS_listen", //106
5172 "SYS_107",
5173 "SYS_108",
5174 "SYS_109",
5175 "SYS_110",
5176 "SYS_sigsuspend", //111
5177 "SYS_112",
5178 "SYS_113",
5179 "SYS_114",
5180 "SYS_115",
5181 "SYS_gettimeofday", //116
5182 "SYS_getrusage", //117
5183 "SYS_getsockopt", //118
5184 "SYS_119",
5185 "SYS_readv", //120
5186 "SYS_writev", //121
5187 "SYS_settimeofday", //122
5188 "SYS_fchown", //123
5189 "SYS_fchmod", //124
5190 "SYS_125",
5191 "SYS_setreuid", //126
5192 "SYS_setregid", //127
5193 "SYS_rename", //128
5194 "SYS_129",
5195 "SYS_130",
5196 "SYS_flock", //131
5197 "SYS_mkfifo", //132
5198 "SYS_sendto", //133
5199 "SYS_shutdown", //134
5200 "SYS_socketpair", //135
5201 "SYS_mkdir", //136
5202 "SYS_rmdir", //137
5203 "SYS_utimes", //138
5204 "SYS_139",
5205 "SYS_adjtime", //140
5206 "SYS_141",
5207 "SYS_142",
5208 "SYS_143",
5209 "SYS_144",
5210 "SYS_145",
5211 "SYS_146",
5212 "SYS_setsid", //147
5213 "SYS_quotactl", //148
5214 "SYS_149",
5215 "SYS_150",
5216 "SYS_151",
5217 "SYS_152",
5218 "SYS_153",
5219 "SYS_154",
5220 "SYS_nfssvc", //155
5221 "SYS_156",
5222 "SYS_157",
5223 "SYS_158",
5224 "SYS_159",
5225 "SYS_160",
5226 "SYS_getfh", //161
5227 "SYS_162",
5228 "SYS_163",
5229 "SYS_164",
5230 "SYS_sysarch", //165
5231 "SYS_166",
5232 "SYS_167",
5233 "SYS_168",
5234 "SYS_169",
5235 "SYS_170",
5236 "SYS_171",
5237 "SYS_172",
5238 "SYS_pread", //173
5239 "SYS_pwrite", //174
5240 "SYS_175",
5241 "SYS_176",
5242 "SYS_177",
5243 "SYS_178",
5244 "SYS_179",
5245 "SYS_180",
5246 "SYS_setgid", //181
5247 "SYS_setegid", //182
5248 "SYS_seteuid", //183
5249 "SYS_lfs_bmapv", //184
5250 "SYS_lfs_markv", //185
5251 "SYS_lfs_segclean", //186
5252 "SYS_lfs_segwait", //187
5253 "SYS_188",
5254 "SYS_189",
5255 "SYS_190",
5256 "SYS_pathconf", //191
5257 "SYS_fpathconf", //192
5258 "SYS_swapctl", //193
5259 "SYS_getrlimit", //194
5260 "SYS_setrlimit", //195
5261 "SYS_getdirentries", //196
5262 "SYS_mmap", //197
5263 "SYS___syscall", //198
5264 "SYS_lseek", //199
5265 "SYS_truncate", //200
5266 "SYS_ftruncate", //201
5267 "SYS___sysctl", //202
5268 "SYS_mlock", //203
5269 "SYS_munlock", //204
5270 "SYS_205",
5271 "SYS_futimes", //206
5272 "SYS_getpgid", //207
5273 "SYS_xfspioctl", //208
5274 "SYS_209",
5275 "SYS_210",
5276 "SYS_211",
5277 "SYS_212",
5278 "SYS_213",
5279 "SYS_214",
5280 "SYS_215",
5281 "SYS_216",
5282 "SYS_217",
5283 "SYS_218",
5284 "SYS_219",
5285 "SYS_220",
5286 "SYS_semget", //221
5287 "SYS_222",
5288 "SYS_223",
5289 "SYS_224",
5290 "SYS_msgget", //225
5291 "SYS_msgsnd", //226
5292 "SYS_msgrcv", //227
5293 "SYS_shmat", //228
5294 "SYS_229",
5295 "SYS_shmdt", //230
5296 "SYS_231",
5297 "SYS_clock_gettime", //232
5298 "SYS_clock_settime", //233
5299 "SYS_clock_getres", //234
5300 "SYS_235",
5301 "SYS_236",
5302 "SYS_237",
5303 "SYS_238",
5304 "SYS_239",
5305 "SYS_nanosleep", //240
5306 "SYS_241",
5307 "SYS_242",
5308 "SYS_243",
5309 "SYS_244",
5310 "SYS_245",
5311 "SYS_246",
5312 "SYS_247",
5313 "SYS_248",
5314 "SYS_249",
5315 "SYS_minherit", //250
5316 "SYS_rfork", //251
5317 "SYS_poll", //252
5318 "SYS_issetugid", //253
5319 "SYS_lchown", //254
5320 "SYS_getsid", //255
5321 "SYS_msync", //256
5322 "SYS_257",
5323 "SYS_258",
5324 "SYS_259",
5325 "SYS_getfsstat", //260
5326 "SYS_statfs", //261
5327 "SYS_fstatfs", //262
5328 "SYS_pipe", //263
5329 "SYS_fhopen", //264
5330 "SYS_265",
5331 "SYS_fhstatfs", //266
5332 "SYS_preadv", //267
5333 "SYS_pwritev", //268
5334 "SYS_kqueue", //269
5335 "SYS_kevent", //270
5336 "SYS_mlockall", //271
5337 "SYS_munlockall", //272
5338 "SYS_getpeereid", //273
5339 "SYS_274",
5340 "SYS_275",
5341 "SYS_276",
5342 "SYS_277",
5343 "SYS_278",
5344 "SYS_279",
5345 "SYS_280",
5346 "SYS_getresuid", //281
5347 "SYS_setresuid", //282
5348 "SYS_getresgid", //283
5349 "SYS_setresgid", //284
5350 "SYS_285",
5351 "SYS_mquery", //286
5352 "SYS_closefrom", //287
5353 "SYS_sigaltstack", //288
5354 "SYS_shmget", //289
5355 "SYS_semop", //290
5356 "SYS_stat", //291
5357 "SYS_fstat", //292
5358 "SYS_lstat", //293
5359 "SYS_fhstat", //294
5360 "SYS___semctl", //295
5361 "SYS_shmctl", //296
5362 "SYS_msgctl", //297
5363 "SYS_MAXSYSCALL", //298
5364 //299
5365 //300
5366 };
5367 uint32_t uEAX;
5368 if (!LogIsEnabled())
5369 return;
5370 uEAX = CPUMGetGuestEAX(pVM);
5371 switch (uEAX)
5372 {
5373 default:
5374 if (uEAX < ELEMENTS(apsz))
5375 {
5376 uint32_t au32Args[8] = {0};
5377 PGMPhysReadGCPtr(pVM, au32Args, CPUMGetGuestESP(pVM), sizeof(au32Args));
5378 RTLogPrintf("REM: OpenBSD syscall %3d: %s (eip=%08x %08x %08x %08x %08x %08x %08x %08x %08x)\n",
5379 uEAX, apsz[uEAX], CPUMGetGuestEIP(pVM), au32Args[0], au32Args[1], au32Args[2], au32Args[3],
5380 au32Args[4], au32Args[5], au32Args[6], au32Args[7]);
5381 }
5382 else
5383 RTLogPrintf("eip=%08x: OpenBSD syscall %d (#%x) unknown!!\n", CPUMGetGuestEIP(pVM), uEAX, uEAX);
5384 break;
5385 }
5386}
5387
5388
5389#if defined(IPRT_NO_CRT) && defined(RT_OS_WINDOWS) && defined(RT_ARCH_X86)
5390/**
5391 * The Dll main entry point (stub).
5392 */
5393bool __stdcall _DllMainCRTStartup(void *hModule, uint32_t dwReason, void *pvReserved)
5394{
5395 return true;
5396}
5397
5398void *memcpy(void *dst, const void *src, size_t size)
5399{
5400 uint8_t*pbDst = dst, *pbSrc = src;
5401 while (size-- > 0)
5402 *pbDst++ = *pbSrc++;
5403 return dst;
5404}
5405
5406#endif
5407
Note: See TracBrowser for help on using the repository browser.

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