VirtualBox

source: vbox/trunk/src/VBox/VMM/EM.cpp@ 448

Last change on this file since 448 was 448, checked in by vboxsync, 18 years ago

Drop the AMD64 assertions.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 141.9 KB
Line 
1/* $Id: EM.cpp 448 2007-01-30 22:36:08Z vboxsync $ */
2/** @file
3 * EM - Execution Monitor/Manager.
4 */
5
6/*
7 * Copyright (C) 2006 InnoTek Systemberatung 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 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22
23/** @page pg_em EM - The Execution Monitor/Manager
24 *
25 * The Execution Monitor/Manager is responsible for running the VM, scheduling
26 * the right kind of execution (Raw, Recompiled, Interpreted,..), and keeping
27 * the CPU states in sync. The function RMR3ExecuteVM() is the 'main-loop' of
28 * the VM.
29 *
30 */
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#define LOG_GROUP LOG_GROUP_EM
36#include <VBox/em.h>
37#include <VBox/vmm.h>
38#include <VBox/patm.h>
39#include <VBox/csam.h>
40#include <VBox/selm.h>
41#include <VBox/trpm.h>
42#include <VBox/iom.h>
43#include <VBox/dbgf.h>
44#include <VBox/pgm.h>
45#include <VBox/rem.h>
46#include <VBox/tm.h>
47#include <VBox/mm.h>
48#include <VBox/pdm.h>
49#include <VBox/hwaccm.h>
50#include <VBox/patm.h>
51#include "EMInternal.h"
52#include <VBox/vm.h>
53#include <VBox/cpumdis.h>
54#include <VBox/dis.h>
55#include <VBox/disopcode.h>
56
57#include <VBox/log.h>
58#include <iprt/thread.h>
59#include <iprt/assert.h>
60#include <iprt/asm.h>
61#include <iprt/semaphore.h>
62#include <iprt/string.h>
63#include <iprt/avl.h>
64#include <iprt/stream.h>
65#include <VBox/param.h>
66#include <VBox/err.h>
67
68
69/*******************************************************************************
70* Internal Functions *
71*******************************************************************************/
72static DECLCALLBACK(int) emR3Save(PVM pVM, PSSMHANDLE pSSM);
73static DECLCALLBACK(int) emR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
74static int emR3Debug(PVM pVM, int rc);
75static int emR3RemStep(PVM pVM);
76static int emR3RemExecute(PVM pVM, bool *pfFFDone);
77static int emR3RawResumeHyper(PVM pVM);
78static int emR3RawStep(PVM pVM);
79DECLINLINE(int) emR3RawHandleRC(PVM pVM, PCPUMCTX pCtx, int rc);
80DECLINLINE(int) emR3RawUpdateForceFlag(PVM pVM, PCPUMCTX pCtx, int rc);
81static int emR3RawForcedActions(PVM pVM, PCPUMCTX pCtx);
82static int emR3RawExecute(PVM pVM, bool *pfFFDone);
83DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, const char *pszPrefix, int rcGC = VINF_SUCCESS);
84static int emR3HighPriorityPostForcedActions(PVM pVM, int rc);
85static int emR3ForcedActions(PVM pVM, int rc);
86static int emR3RawGuestTrap(PVM pVM);
87
88
89/**
90 * Initializes the EM.
91 *
92 * @returns VBox status code.
93 * @param pVM The VM to operate on.
94 */
95EMR3DECL(int) EMR3Init(PVM pVM)
96{
97 LogFlow(("EMR3Init\n"));
98 /*
99 * Assert alignment and sizes.
100 */
101 AssertRelease(!(RT_OFFSETOF(VM, em.s) & 31));
102 AssertRelease(sizeof(pVM->em.s) <= sizeof(pVM->em.padding));
103 AssertReleaseMsg(sizeof(pVM->em.s.u.FatalLongJump) <= sizeof(pVM->em.s.u.achPaddingFatalLongJump),
104 ("%d bytes, padding %d\n", sizeof(pVM->em.s.u.FatalLongJump), sizeof(pVM->em.s.u.achPaddingFatalLongJump)));
105
106 /*
107 * Init the structure.
108 */
109 pVM->em.s.offVM = RT_OFFSETOF(VM, em.s);
110 int rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "RawR3Enabled", &pVM->fRawR3Enabled);
111 if (VBOX_FAILURE(rc))
112 pVM->fRawR3Enabled = true;
113 rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "RawR0Enabled", &pVM->fRawR0Enabled);
114 if (VBOX_FAILURE(rc))
115 pVM->fRawR0Enabled = true;
116 Log(("EMR3Init: fRawR3Enabled=%d fRawR0Enabled=%d\n", pVM->fRawR3Enabled, pVM->fRawR0Enabled));
117 pVM->em.s.enmState = EMSTATE_NONE;
118 pVM->em.s.fForceRAW = false;
119
120 rc = CPUMQueryGuestCtxPtr(pVM, &pVM->em.s.pCtx);
121 AssertMsgRC(rc, ("CPUMQueryGuestCtxPtr -> %Vrc\n", rc));
122 pVM->em.s.pPatmGCState = PATMR3QueryGCStateHC(pVM);
123 AssertMsg(pVM->em.s.pPatmGCState, ("PATMR3QueryGCStateHC failed!\n"));
124
125 /*
126 * Saved state.
127 */
128 rc = SSMR3RegisterInternal(pVM, "em", 0, EM_SAVED_STATE_VERSION, 16,
129 NULL, emR3Save, NULL,
130 NULL, emR3Load, NULL);
131 if (VBOX_FAILURE(rc))
132 return rc;
133
134 /*
135 * Statistics.
136 */
137#ifdef VBOX_WITH_STATISTICS
138 PEMSTATS pStats;
139 rc = MMHyperAlloc(pVM, sizeof(*pStats), 0, MM_TAG_EM, (void **)&pStats);
140 if (VBOX_FAILURE(rc))
141 return rc;
142 pVM->em.s.pStatsHC = pStats;
143 pVM->em.s.pStatsGC = MMHyperHC2GC(pVM, pStats);
144
145 STAM_REG(pVM, &pStats->StatGCEmulate, STAMTYPE_PROFILE, "/EM/GC/Interpret", STAMUNIT_TICKS_PER_CALL, "Profiling of EMInterpretInstruction.");
146 STAM_REG(pVM, &pStats->StatHCEmulate, STAMTYPE_PROFILE, "/EM/HC/Interpret", STAMUNIT_TICKS_PER_CALL, "Profiling of EMInterpretInstruction.");
147
148 STAM_REG(pVM, &pStats->StatGCInterpretSucceeded, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success", STAMUNIT_OCCURENCES, "The number of times an instruction was successfully interpreted.");
149 STAM_REG(pVM, &pStats->StatHCInterpretSucceeded, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success", STAMUNIT_OCCURENCES, "The number of times an instruction was successfully interpreted.");
150
151 STAM_REG_USED(pVM, &pStats->StatGCAnd, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/And", STAMUNIT_OCCURENCES, "The number of times AND was successfully interpreted.");
152 STAM_REG_USED(pVM, &pStats->StatHCAnd, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/And", STAMUNIT_OCCURENCES, "The number of times AND was successfully interpreted.");
153 STAM_REG_USED(pVM, &pStats->StatGCAdd, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Add", STAMUNIT_OCCURENCES, "The number of times ADD was successfully interpreted.");
154 STAM_REG_USED(pVM, &pStats->StatHCAdd, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Add", STAMUNIT_OCCURENCES, "The number of times ADD was successfully interpreted.");
155 STAM_REG_USED(pVM, &pStats->StatGCAdc, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Adc", STAMUNIT_OCCURENCES, "The number of times ADC was successfully interpreted.");
156 STAM_REG_USED(pVM, &pStats->StatHCAdc, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Adc", STAMUNIT_OCCURENCES, "The number of times ADC was successfully interpreted.");
157 STAM_REG_USED(pVM, &pStats->StatGCSub, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Sub", STAMUNIT_OCCURENCES, "The number of times SUB was successfully interpreted.");
158 STAM_REG_USED(pVM, &pStats->StatHCSub, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Sub", STAMUNIT_OCCURENCES, "The number of times SUB was successfully interpreted.");
159 STAM_REG_USED(pVM, &pStats->StatGCCpuId, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/CpuId", STAMUNIT_OCCURENCES, "The number of times CPUID was successfully interpreted.");
160 STAM_REG_USED(pVM, &pStats->StatHCCpuId, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/CpuId", STAMUNIT_OCCURENCES, "The number of times CPUID was successfully interpreted.");
161 STAM_REG_USED(pVM, &pStats->StatGCDec, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Dec", STAMUNIT_OCCURENCES, "The number of times DEC was successfully interpreted.");
162 STAM_REG_USED(pVM, &pStats->StatHCDec, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Dec", STAMUNIT_OCCURENCES, "The number of times DEC was successfully interpreted.");
163 STAM_REG_USED(pVM, &pStats->StatGCHlt, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Hlt", STAMUNIT_OCCURENCES, "The number of times HLT was successfully interpreted.");
164 STAM_REG_USED(pVM, &pStats->StatHCHlt, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Hlt", STAMUNIT_OCCURENCES, "The number of times HLT was successfully interpreted.");
165 STAM_REG_USED(pVM, &pStats->StatGCInc, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Inc", STAMUNIT_OCCURENCES, "The number of times INC was successfully interpreted.");
166 STAM_REG_USED(pVM, &pStats->StatHCInc, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Inc", STAMUNIT_OCCURENCES, "The number of times INC was successfully interpreted.");
167 STAM_REG_USED(pVM, &pStats->StatGCInvlPg, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Invlpg", STAMUNIT_OCCURENCES, "The number of times INVLPG was successfully interpreted.");
168 STAM_REG_USED(pVM, &pStats->StatHCInvlPg, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Invlpg", STAMUNIT_OCCURENCES, "The number of times INVLPG was successfully interpreted.");
169 STAM_REG_USED(pVM, &pStats->StatGCIret, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Iret", STAMUNIT_OCCURENCES, "The number of times IRET was successfully interpreted.");
170 STAM_REG_USED(pVM, &pStats->StatHCIret, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Iret", STAMUNIT_OCCURENCES, "The number of times IRET was successfully interpreted.");
171 STAM_REG_USED(pVM, &pStats->StatGCLLdt, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/LLdt", STAMUNIT_OCCURENCES, "The number of times LLDT was successfully interpreted.");
172 STAM_REG_USED(pVM, &pStats->StatHCLLdt, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/LLdt", STAMUNIT_OCCURENCES, "The number of times LLDT was successfully interpreted.");
173 STAM_REG_USED(pVM, &pStats->StatGCMov, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Mov", STAMUNIT_OCCURENCES, "The number of times MOV was successfully interpreted.");
174 STAM_REG_USED(pVM, &pStats->StatHCMov, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Mov", STAMUNIT_OCCURENCES, "The number of times MOV was successfully interpreted.");
175 STAM_REG_USED(pVM, &pStats->StatGCMovCRx, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/MovCRx", STAMUNIT_OCCURENCES, "The number of times MOV CRx was successfully interpreted.");
176 STAM_REG_USED(pVM, &pStats->StatHCMovCRx, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/MovCRx", STAMUNIT_OCCURENCES, "The number of times MOV CRx was successfully interpreted.");
177 STAM_REG_USED(pVM, &pStats->StatGCMovDRx, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/MovDRx", STAMUNIT_OCCURENCES, "The number of times MOV DRx was successfully interpreted.");
178 STAM_REG_USED(pVM, &pStats->StatHCMovDRx, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/MovDRx", STAMUNIT_OCCURENCES, "The number of times MOV DRx was successfully interpreted.");
179 STAM_REG_USED(pVM, &pStats->StatGCOr, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Or", STAMUNIT_OCCURENCES, "The number of times OR was successfully interpreted.");
180 STAM_REG_USED(pVM, &pStats->StatHCOr, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Or", STAMUNIT_OCCURENCES, "The number of times OR was successfully interpreted.");
181 STAM_REG_USED(pVM, &pStats->StatGCPop, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Pop", STAMUNIT_OCCURENCES, "The number of times POP was successfully interpreted.");
182 STAM_REG_USED(pVM, &pStats->StatHCPop, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Pop", STAMUNIT_OCCURENCES, "The number of times POP was successfully interpreted.");
183 STAM_REG_USED(pVM, &pStats->StatGCSti, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Sti", STAMUNIT_OCCURENCES, "The number of times STI was successfully interpreted.");
184 STAM_REG_USED(pVM, &pStats->StatHCSti, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Sti", STAMUNIT_OCCURENCES, "The number of times STI was successfully interpreted.");
185 STAM_REG_USED(pVM, &pStats->StatGCXchg, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Xchg", STAMUNIT_OCCURENCES, "The number of times XCHG was successfully interpreted.");
186 STAM_REG_USED(pVM, &pStats->StatHCXchg, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Xchg", STAMUNIT_OCCURENCES, "The number of times XCHG was successfully interpreted.");
187 STAM_REG_USED(pVM, &pStats->StatGCXor, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Xor", STAMUNIT_OCCURENCES, "The number of times XOR was successfully interpreted.");
188 STAM_REG_USED(pVM, &pStats->StatHCXor, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Xor", STAMUNIT_OCCURENCES, "The number of times XOR was successfully interpreted.");
189 STAM_REG_USED(pVM, &pStats->StatGCMonitor, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/Monitor", STAMUNIT_OCCURENCES, "The number of times MONITOR was successfully interpreted.");
190 STAM_REG_USED(pVM, &pStats->StatHCMonitor, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/Monitor", STAMUNIT_OCCURENCES, "The number of times MONITOR was successfully interpreted.");
191 STAM_REG_USED(pVM, &pStats->StatGCMWait, STAMTYPE_COUNTER, "/EM/GC/Interpret/Success/MWait", STAMUNIT_OCCURENCES, "The number of times MONITOR was successfully interpreted.");
192 STAM_REG_USED(pVM, &pStats->StatHCMWait, STAMTYPE_COUNTER, "/EM/HC/Interpret/Success/MWait", STAMUNIT_OCCURENCES, "The number of times MONITOR was successfully interpreted.");
193
194 STAM_REG(pVM, &pStats->StatGCInterpretFailed, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed", STAMUNIT_OCCURENCES, "The number of times an instruction was not interpreted.");
195 STAM_REG(pVM, &pStats->StatHCInterpretFailed, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed", STAMUNIT_OCCURENCES, "The number of times an instruction was not interpreted.");
196
197 STAM_REG_USED(pVM, &pStats->StatGCFailedAnd, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/And", STAMUNIT_OCCURENCES, "The number of times AND was not interpreted.");
198 STAM_REG_USED(pVM, &pStats->StatHCFailedAnd, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/And", STAMUNIT_OCCURENCES, "The number of times AND was not interpreted.");
199 STAM_REG_USED(pVM, &pStats->StatGCFailedCpuId, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/CpuId", STAMUNIT_OCCURENCES, "The number of times CPUID was not interpreted.");
200 STAM_REG_USED(pVM, &pStats->StatHCFailedCpuId, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/CpuId", STAMUNIT_OCCURENCES, "The number of times CPUID was not interpreted.");
201 STAM_REG_USED(pVM, &pStats->StatGCFailedDec, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Dec", STAMUNIT_OCCURENCES, "The number of times DEC was not interpreted.");
202 STAM_REG_USED(pVM, &pStats->StatHCFailedDec, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Dec", STAMUNIT_OCCURENCES, "The number of times DEC was not interpreted.");
203 STAM_REG_USED(pVM, &pStats->StatGCFailedHlt, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Hlt", STAMUNIT_OCCURENCES, "The number of times HLT was not interpreted.");
204 STAM_REG_USED(pVM, &pStats->StatHCFailedHlt, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Hlt", STAMUNIT_OCCURENCES, "The number of times HLT was not interpreted.");
205 STAM_REG_USED(pVM, &pStats->StatGCFailedInc, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Inc", STAMUNIT_OCCURENCES, "The number of times INC was not interpreted.");
206 STAM_REG_USED(pVM, &pStats->StatHCFailedInc, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Inc", STAMUNIT_OCCURENCES, "The number of times INC was not interpreted.");
207 STAM_REG_USED(pVM, &pStats->StatGCFailedInvlPg, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/InvlPg", STAMUNIT_OCCURENCES, "The number of times INVLPG was not interpreted.");
208 STAM_REG_USED(pVM, &pStats->StatHCFailedInvlPg, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/InvlPg", STAMUNIT_OCCURENCES, "The number of times INVLPG was not interpreted.");
209 STAM_REG_USED(pVM, &pStats->StatGCFailedIret, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Iret", STAMUNIT_OCCURENCES, "The number of times IRET was not interpreted.");
210 STAM_REG_USED(pVM, &pStats->StatHCFailedIret, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Iret", STAMUNIT_OCCURENCES, "The number of times IRET was not interpreted.");
211 STAM_REG_USED(pVM, &pStats->StatGCFailedLLdt, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/LLdt", STAMUNIT_OCCURENCES, "The number of times LLDT was not interpreted.");
212 STAM_REG_USED(pVM, &pStats->StatHCFailedLLdt, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/LLdt", STAMUNIT_OCCURENCES, "The number of times LLDT was not interpreted.");
213 STAM_REG_USED(pVM, &pStats->StatGCFailedMov, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Mov", STAMUNIT_OCCURENCES, "The number of times MOV was not interpreted.");
214 STAM_REG_USED(pVM, &pStats->StatHCFailedMov, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Mov", STAMUNIT_OCCURENCES, "The number of times MOV was not interpreted.");
215 STAM_REG_USED(pVM, &pStats->StatGCFailedMovCRx, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/MovCRx", STAMUNIT_OCCURENCES, "The number of times MOV CRx was not interpreted.");
216 STAM_REG_USED(pVM, &pStats->StatHCFailedMovCRx, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/MovCRx", STAMUNIT_OCCURENCES, "The number of times MOV CRx was not interpreted.");
217 STAM_REG_USED(pVM, &pStats->StatGCFailedMovDRx, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/MovDRx", STAMUNIT_OCCURENCES, "The number of times MOV DRx was not interpreted.");
218 STAM_REG_USED(pVM, &pStats->StatHCFailedMovDRx, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/MovDRx", STAMUNIT_OCCURENCES, "The number of times MOV DRx was not interpreted.");
219 STAM_REG_USED(pVM, &pStats->StatGCFailedOr, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Or", STAMUNIT_OCCURENCES, "The number of times OR was not interpreted.");
220 STAM_REG_USED(pVM, &pStats->StatHCFailedOr, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Or", STAMUNIT_OCCURENCES, "The number of times OR was not interpreted.");
221 STAM_REG_USED(pVM, &pStats->StatGCFailedPop, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Pop", STAMUNIT_OCCURENCES, "The number of times POP was not interpreted.");
222 STAM_REG_USED(pVM, &pStats->StatHCFailedPop, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Pop", STAMUNIT_OCCURENCES, "The number of times POP was not interpreted.");
223 STAM_REG_USED(pVM, &pStats->StatGCFailedSti, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Sti", STAMUNIT_OCCURENCES, "The number of times STI was not interpreted.");
224 STAM_REG_USED(pVM, &pStats->StatHCFailedSti, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Sti", STAMUNIT_OCCURENCES, "The number of times STI was not interpreted.");
225 STAM_REG_USED(pVM, &pStats->StatGCFailedXchg, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Xchg", STAMUNIT_OCCURENCES, "The number of times XCHG was not interpreted.");
226 STAM_REG_USED(pVM, &pStats->StatHCFailedXchg, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Xchg", STAMUNIT_OCCURENCES, "The number of times XCHG was not interpreted.");
227 STAM_REG_USED(pVM, &pStats->StatGCFailedXor, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Xor", STAMUNIT_OCCURENCES, "The number of times XOR was not interpreted.");
228 STAM_REG_USED(pVM, &pStats->StatHCFailedXor, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Xor", STAMUNIT_OCCURENCES, "The number of times XOR was not interpreted.");
229 STAM_REG_USED(pVM, &pStats->StatGCFailedMonitor, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Monitor", STAMUNIT_OCCURENCES, "The number of times MONITOR was not interpreted.");
230 STAM_REG_USED(pVM, &pStats->StatHCFailedMonitor, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Monitor", STAMUNIT_OCCURENCES, "The number of times MONITOR was not interpreted.");
231 STAM_REG_USED(pVM, &pStats->StatGCFailedMWait, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/MWait", STAMUNIT_OCCURENCES, "The number of times MONITOR was not interpreted.");
232 STAM_REG_USED(pVM, &pStats->StatHCFailedMWait, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/MWait", STAMUNIT_OCCURENCES, "The number of times MONITOR was not interpreted.");
233
234 STAM_REG_USED(pVM, &pStats->StatGCFailedMisc, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Misc", STAMUNIT_OCCURENCES, "The number of times some misc instruction was encountered.");
235 STAM_REG_USED(pVM, &pStats->StatHCFailedMisc, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Misc", STAMUNIT_OCCURENCES, "The number of times some misc instruction was encountered.");
236 STAM_REG_USED(pVM, &pStats->StatGCFailedAdd, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Add", STAMUNIT_OCCURENCES, "The number of times ADD was not interpreted.");
237 STAM_REG_USED(pVM, &pStats->StatHCFailedAdd, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Add", STAMUNIT_OCCURENCES, "The number of times ADD was not interpreted.");
238 STAM_REG_USED(pVM, &pStats->StatGCFailedAdc, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Adc", STAMUNIT_OCCURENCES, "The number of times ADC was not interpreted.");
239 STAM_REG_USED(pVM, &pStats->StatHCFailedAdc, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Adc", STAMUNIT_OCCURENCES, "The number of times ADC was not interpreted.");
240 STAM_REG_USED(pVM, &pStats->StatGCFailedBtr, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Btr", STAMUNIT_OCCURENCES, "The number of times BTR was not interpreted.");
241 STAM_REG_USED(pVM, &pStats->StatHCFailedBtr, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Btr", STAMUNIT_OCCURENCES, "The number of times BTR was not interpreted.");
242 STAM_REG_USED(pVM, &pStats->StatGCFailedBts, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Bts", STAMUNIT_OCCURENCES, "The number of times BTS was not interpreted.");
243 STAM_REG_USED(pVM, &pStats->StatHCFailedBts, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Bts", STAMUNIT_OCCURENCES, "The number of times BTS was not interpreted.");
244 STAM_REG_USED(pVM, &pStats->StatGCFailedCli, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Cli", STAMUNIT_OCCURENCES, "The number of times CLI was not interpreted.");
245 STAM_REG_USED(pVM, &pStats->StatHCFailedCli, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Cli", STAMUNIT_OCCURENCES, "The number of times CLI was not interpreted.");
246 STAM_REG_USED(pVM, &pStats->StatGCFailedCmpXchg, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/CmpXchg", STAMUNIT_OCCURENCES, "The number of times CMPXCHG was not interpreted.");
247 STAM_REG_USED(pVM, &pStats->StatHCFailedCmpXchg, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/CmpXchg", STAMUNIT_OCCURENCES, "The number of times CMPXCHG was not interpreted.");
248 STAM_REG_USED(pVM, &pStats->StatGCFailedMovNTPS, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/MovNTPS", STAMUNIT_OCCURENCES, "The number of times MOVNTPS was not interpreted.");
249 STAM_REG_USED(pVM, &pStats->StatHCFailedMovNTPS, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/MovNTPS", STAMUNIT_OCCURENCES, "The number of times MOVNTPS was not interpreted.");
250 STAM_REG_USED(pVM, &pStats->StatGCFailedStosWD, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/StosWD", STAMUNIT_OCCURENCES, "The number of times STOSWD was not interpreted.");
251 STAM_REG_USED(pVM, &pStats->StatHCFailedStosWD, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/StosWD", STAMUNIT_OCCURENCES, "The number of times STOSWD was not interpreted.");
252 STAM_REG_USED(pVM, &pStats->StatGCFailedSub, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Sub", STAMUNIT_OCCURENCES, "The number of times SUB was not interpreted.");
253 STAM_REG_USED(pVM, &pStats->StatHCFailedSub, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Sub", STAMUNIT_OCCURENCES, "The number of times SUB was not interpreted.");
254 STAM_REG_USED(pVM, &pStats->StatGCFailedWbInvd, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/WbInvd", STAMUNIT_OCCURENCES, "The number of times WBINVD was not interpreted.");
255 STAM_REG_USED(pVM, &pStats->StatHCFailedWbInvd, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/WbInvd", STAMUNIT_OCCURENCES, "The number of times WBINVD was not interpreted.");
256
257 STAM_REG_USED(pVM, &pStats->StatGCFailedUserMode, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/UserMode", STAMUNIT_OCCURENCES, "The number of rejections because of CPL.");
258 STAM_REG_USED(pVM, &pStats->StatHCFailedUserMode, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/UserMode", STAMUNIT_OCCURENCES, "The number of rejections because of CPL.");
259 STAM_REG_USED(pVM, &pStats->StatGCFailedPrefix, STAMTYPE_COUNTER, "/EM/GC/Interpret/Failed/Prefix", STAMUNIT_OCCURENCES, "The number of rejections because of prefix .");
260 STAM_REG_USED(pVM, &pStats->StatHCFailedPrefix, STAMTYPE_COUNTER, "/EM/HC/Interpret/Failed/Prefix", STAMUNIT_OCCURENCES, "The number of rejections because of prefix .");
261
262 STAM_REG_USED(pVM, &pStats->StatCli, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Cli", STAMUNIT_OCCURENCES, "Number of cli instructions.");
263 STAM_REG_USED(pVM, &pStats->StatSti, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Sti", STAMUNIT_OCCURENCES, "Number of sli instructions.");
264 STAM_REG_USED(pVM, &pStats->StatIn, STAMTYPE_COUNTER, "/EM/HC/PrivInst/In", STAMUNIT_OCCURENCES, "Number of in instructions.");
265 STAM_REG_USED(pVM, &pStats->StatOut, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Out", STAMUNIT_OCCURENCES, "Number of out instructions.");
266 STAM_REG_USED(pVM, &pStats->StatHlt, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Hlt", STAMUNIT_OCCURENCES, "Number of hlt instructions not handled in GC because of PATM.");
267 STAM_REG_USED(pVM, &pStats->StatInvlpg, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Invlpg", STAMUNIT_OCCURENCES, "Number of invlpg instructions.");
268 STAM_REG_USED(pVM, &pStats->StatMisc, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Misc", STAMUNIT_OCCURENCES, "Number of misc. instructions.");
269 STAM_REG_USED(pVM, &pStats->StatMovWriteCR[0], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov CR0, X", STAMUNIT_OCCURENCES, "Number of mov CR0 read instructions.");
270 STAM_REG_USED(pVM, &pStats->StatMovWriteCR[1], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov CR1, X", STAMUNIT_OCCURENCES, "Number of mov CR1 read instructions.");
271 STAM_REG_USED(pVM, &pStats->StatMovWriteCR[2], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov CR2, X", STAMUNIT_OCCURENCES, "Number of mov CR2 read instructions.");
272 STAM_REG_USED(pVM, &pStats->StatMovWriteCR[3], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov CR3, X", STAMUNIT_OCCURENCES, "Number of mov CR3 read instructions.");
273 STAM_REG_USED(pVM, &pStats->StatMovWriteCR[4], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov CR4, X", STAMUNIT_OCCURENCES, "Number of mov CR4 read instructions.");
274 STAM_REG_USED(pVM, &pStats->StatMovReadCR[0], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov X, CR0", STAMUNIT_OCCURENCES, "Number of mov CR0 write instructions.");
275 STAM_REG_USED(pVM, &pStats->StatMovReadCR[1], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov X, CR1", STAMUNIT_OCCURENCES, "Number of mov CR1 write instructions.");
276 STAM_REG_USED(pVM, &pStats->StatMovReadCR[2], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov X, CR2", STAMUNIT_OCCURENCES, "Number of mov CR2 write instructions.");
277 STAM_REG_USED(pVM, &pStats->StatMovReadCR[3], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov X, CR3", STAMUNIT_OCCURENCES, "Number of mov CR3 write instructions.");
278 STAM_REG_USED(pVM, &pStats->StatMovReadCR[4], STAMTYPE_COUNTER, "/EM/HC/PrivInst/Mov X, CR4", STAMUNIT_OCCURENCES, "Number of mov CR4 write instructions.");
279 STAM_REG_USED(pVM, &pStats->StatMovDRx, STAMTYPE_COUNTER, "/EM/HC/PrivInst/MovDRx", STAMUNIT_OCCURENCES, "Number of mov DRx instructions.");
280 STAM_REG_USED(pVM, &pStats->StatIret, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Iret", STAMUNIT_OCCURENCES, "Number of iret instructions.");
281 STAM_REG_USED(pVM, &pStats->StatMovLgdt, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Lgdt", STAMUNIT_OCCURENCES, "Number of lgdt instructions.");
282 STAM_REG_USED(pVM, &pStats->StatMovLidt, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Lidt", STAMUNIT_OCCURENCES, "Number of lidt instructions.");
283 STAM_REG_USED(pVM, &pStats->StatMovLldt, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Lldt", STAMUNIT_OCCURENCES, "Number of lldt instructions.");
284 STAM_REG_USED(pVM, &pStats->StatSysEnter, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Sysenter", STAMUNIT_OCCURENCES, "Number of sysenter instructions.");
285 STAM_REG_USED(pVM, &pStats->StatSysExit, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Sysexit", STAMUNIT_OCCURENCES, "Number of sysexit instructions.");
286 STAM_REG_USED(pVM, &pStats->StatSysCall, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Syscall", STAMUNIT_OCCURENCES, "Number of syscall instructions.");
287 STAM_REG_USED(pVM, &pStats->StatSysRet, STAMTYPE_COUNTER, "/EM/HC/PrivInst/Sysret", STAMUNIT_OCCURENCES, "Number of sysret instructions.");
288
289 STAM_REG(pVM, &pVM->em.s.StatTotalClis, STAMTYPE_COUNTER, "/EM/Cli/Total", STAMUNIT_OCCURENCES, "Total number of cli instructions executed.");
290 pVM->em.s.pCliStatTree = 0;
291#endif /* VBOX_WITH_STATISTICS */
292
293/* these should be considered for release statistics. */
294 STAM_REG(pVM, &pVM->em.s.StatForcedActions, STAMTYPE_PROFILE, "/PROF/EM/ForcedActions", STAMUNIT_TICKS_PER_CALL, "Profiling forced action execution.");
295 STAM_REG(pVM, &pVM->em.s.StatHalted, STAMTYPE_PROFILE, "/PROF/EM/Halted", STAMUNIT_TICKS_PER_CALL, "Profiling halted state (VMR3WaitHalted).");
296 STAM_REG(pVM, &pVM->em.s.StatHwAccEntry, STAMTYPE_PROFILE, "/PROF/EM/HwAccEnter", STAMUNIT_TICKS_PER_CALL, "Profiling Hardware Accelerated Mode entry overhead.");
297 STAM_REG(pVM, &pVM->em.s.StatHwAccExec, STAMTYPE_PROFILE, "/PROF/EM/HwAccExec", STAMUNIT_TICKS_PER_CALL, "Profiling Hardware Accelerated Mode execution.");
298 STAM_REG(pVM, &pVM->em.s.StatIOEmu, STAMTYPE_PROFILE, "/PROF/EM/Emulation/IO", STAMUNIT_TICKS_PER_CALL, "Profiling of emR3RawExecuteIOInstruction.");
299 STAM_REG(pVM, &pVM->em.s.StatPrivEmu, STAMTYPE_PROFILE, "/PROF/EM/Emulation/Priv", STAMUNIT_TICKS_PER_CALL, "Profiling of emR3RawPrivileged.");
300 STAM_REG(pVM, &pVM->em.s.StatMiscEmu, STAMTYPE_PROFILE, "/PROF/EM/Emulation/Misc", STAMUNIT_TICKS_PER_CALL, "Profiling of emR3RawExecuteInstruction.");
301 STAM_REG(pVM, &pVM->em.s.StatREMEmu, STAMTYPE_PROFILE, "/PROF/EM/REMEmuSingle", STAMUNIT_TICKS_PER_CALL, "Profiling single instruction REM execution.");
302 STAM_REG(pVM, &pVM->em.s.StatREMExec, STAMTYPE_PROFILE, "/PROF/EM/REMExec", STAMUNIT_TICKS_PER_CALL, "Profiling REM execution.");
303 STAM_REG(pVM, &pVM->em.s.StatREMSync, STAMTYPE_PROFILE, "/PROF/EM/REMSync", STAMUNIT_TICKS_PER_CALL, "Profiling REM context syncing.");
304 STAM_REG(pVM, &pVM->em.s.StatREMTotal, STAMTYPE_PROFILE, "/PROF/EM/REMTotal", STAMUNIT_TICKS_PER_CALL, "Profiling emR3RemExecute (excluding FFs).");
305 STAM_REG(pVM, &pVM->em.s.StatRAWEntry, STAMTYPE_PROFILE, "/PROF/EM/RAWEnter", STAMUNIT_TICKS_PER_CALL, "Profiling Raw Mode entry overhead.");
306 STAM_REG(pVM, &pVM->em.s.StatRAWExec, STAMTYPE_PROFILE, "/PROF/EM/RAWExec", STAMUNIT_TICKS_PER_CALL, "Profiling Raw Mode execution.");
307 STAM_REG(pVM, &pVM->em.s.StatRAWTail, STAMTYPE_PROFILE, "/PROF/EM/RAWTail", STAMUNIT_TICKS_PER_CALL, "Profiling Raw Mode tail overhead.");
308 STAM_REG(pVM, &pVM->em.s.StatRAWTotal, STAMTYPE_PROFILE, "/PROF/EM/RAWTotal", STAMUNIT_TICKS_PER_CALL, "Profiling emR3RawExecute (excluding FFs).");
309 STAM_REG(pVM, &pVM->em.s.StatTotal, STAMTYPE_PROFILE, "/PROF/EM/Total", STAMUNIT_TICKS_PER_CALL, "Profiling EMR3ExecuteVM.");
310
311
312 return VINF_SUCCESS;
313}
314
315
316
317/**
318 * Applies relocations to data and code managed by this
319 * component. This function will be called at init and
320 * whenever the VMM need to relocate it self inside the GC.
321 *
322 * @param pVM The VM.
323 */
324EMR3DECL(void) EMR3Relocate(PVM pVM)
325{
326 LogFlow(("EMR3Relocate\n"));
327 if (pVM->em.s.pStatsHC)
328 pVM->em.s.pStatsGC = MMHyperHC2GC(pVM, pVM->em.s.pStatsHC);
329}
330
331
332/**
333 * Reset notification.
334 *
335 * @param pVM
336 */
337EMR3DECL(void) EMR3Reset(PVM pVM)
338{
339 LogFlow(("EMR3Reset: \n"));
340 pVM->em.s.fForceRAW = false;
341}
342
343
344/**
345 * Terminates the EM.
346 *
347 * Termination means cleaning up and freeing all resources,
348 * the VM it self is at this point powered off or suspended.
349 *
350 * @returns VBox status code.
351 * @param pVM The VM to operate on.
352 */
353EMR3DECL(int) EMR3Term(PVM pVM)
354{
355 AssertMsg(pVM->em.s.offVM, ("bad init order!\n"));
356
357 return VINF_SUCCESS;
358}
359
360
361/**
362 * Execute state save operation.
363 *
364 * @returns VBox status code.
365 * @param pVM VM Handle.
366 * @param pSSM SSM operation handle.
367 */
368static DECLCALLBACK(int) emR3Save(PVM pVM, PSSMHANDLE pSSM)
369{
370 return SSMR3PutBool(pSSM, pVM->em.s.fForceRAW);
371}
372
373
374/**
375 * Execute state load operation.
376 *
377 * @returns VBox status code.
378 * @param pVM VM Handle.
379 * @param pSSM SSM operation handle.
380 * @param u32Version Data layout version.
381 */
382static DECLCALLBACK(int) emR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
383{
384 /*
385 * Validate version.
386 */
387 if (u32Version != EM_SAVED_STATE_VERSION)
388 {
389 Log(("emR3Load: Invalid version u32Version=%d (current %d)!\n", u32Version, EM_SAVED_STATE_VERSION));
390 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
391 }
392
393 /*
394 * Load the saved state.
395 */
396 int rc = SSMR3GetBool(pSSM, &pVM->em.s.fForceRAW);
397 if (VBOX_FAILURE(rc))
398 pVM->em.s.fForceRAW = false;
399
400 Assert(pVM->em.s.pCliStatTree == 0);
401 return rc;
402}
403
404
405/**
406 * Enables or disables a set of raw-mode execution modes.
407 *
408 * @returns VINF_SUCCESS on success.
409 * @returns VINF_RESCHEDULE if a rescheduling might be required.
410 * @returns VERR_INVALID_PARAMETER on an invalid enmMode value.
411 *
412 * @param pVM The VM to operate on.
413 * @param enmMode The execution mode change.
414 * @thread The emulation thread.
415 */
416EMR3DECL(int) EMR3RawSetMode(PVM pVM, EMRAWMODE enmMode)
417{
418 switch (enmMode)
419 {
420 case EMRAW_NONE:
421 pVM->fRawR3Enabled = false;
422 pVM->fRawR0Enabled = false;
423 break;
424 case EMRAW_RING3_ENABLE:
425 pVM->fRawR3Enabled = true;
426 break;
427 case EMRAW_RING3_DISABLE:
428 pVM->fRawR3Enabled = false;
429 break;
430 case EMRAW_RING0_ENABLE:
431 pVM->fRawR0Enabled = true;
432 break;
433 case EMRAW_RING0_DISABLE:
434 pVM->fRawR0Enabled = false;
435 break;
436 default:
437 AssertMsgFailed(("Invalid enmMode=%d\n", enmMode));
438 return VERR_INVALID_PARAMETER;
439 }
440 Log(("EMR3SetRawMode: fRawR3Enabled=%RTbool fRawR0Enabled=%RTbool pVM->fRawR3Enabled=%RTbool\n",
441 pVM->fRawR3Enabled, pVM->fRawR0Enabled, pVM->fRawR3Enabled));
442 return pVM->em.s.enmState == EMSTATE_RAW ? VINF_EM_RESCHEDULE : VINF_SUCCESS;
443}
444
445
446/**
447 * Raise a fatal error.
448 *
449 * Safely terminate the VM with full state report and stuff. This function
450 * will naturally never return.
451 *
452 * @param pVM VM handle.
453 * @param rc VBox status code.
454 */
455EMR3DECL(void) EMR3FatalError(PVM pVM, int rc)
456{
457 longjmp(pVM->em.s.u.FatalLongJump, rc);
458 AssertReleaseMsgFailed(("longjmp returned!\n"));
459}
460
461
462/**
463 * Gets the EM state name.
464 *
465 * @returns pointer to read only state name,
466 * @param enmState The state.
467 */
468EMR3DECL(const char *) EMR3GetStateName(EMSTATE enmState)
469{
470 switch (enmState)
471 {
472 case EMSTATE_RAW: return "EMSTATE_RAW";
473 case EMSTATE_HWACC: return "EMSTATE_HWACC";
474 case EMSTATE_REM: return "EMSTATE_REM";
475 case EMSTATE_HALTED: return "EMSTATE_HALTED";
476 case EMSTATE_SUSPENDED: return "EMSTATE_SUSPENDED";
477 case EMSTATE_TERMINATING: return "EMSTATE_TERMINATING";
478 case EMSTATE_DEBUG_GUEST_RAW: return "EMSTATE_DEBUG_GUEST_RAW";
479 case EMSTATE_DEBUG_GUEST_REM: return "EMSTATE_DEBUG_GUEST_REM";
480 case EMSTATE_DEBUG_HYPER: return "EMSTATE_DEBUG_HYPER";
481 case EMSTATE_GURU_MEDITATION: return "EMSTATE_GURU_MEDITATION";
482 default: return "Unknown!";
483 }
484}
485
486
487#ifdef VBOX_WITH_STATISTICS
488/**
489 * Just a braindead function to keep track of cli addresses.
490 * @param pVM VM handle.
491 * @param pInstrGC The EIP of the cli instruction.
492 */
493static void emR3RecordCli(PVM pVM, RTGCPTR pInstrGC)
494{
495 PCLISTAT pRec;
496
497 pRec = (PCLISTAT)RTAvlPVGet(&pVM->em.s.pCliStatTree, (AVLPVKEY)pInstrGC);
498 if (!pRec)
499 {
500 /* New cli instruction; insert into the tree. */
501 pRec = (PCLISTAT)MMR3HeapAllocZ(pVM, MM_TAG_EM, sizeof(*pRec));
502 Assert(pRec);
503 if (!pRec)
504 return;
505 pRec->Core.Key = (AVLPVKEY)pInstrGC;
506
507 char szCliStatName[32];
508 RTStrPrintf(szCliStatName, sizeof(szCliStatName), "/EM/Cli/0x%VGv", pInstrGC);
509 STAM_REG(pVM, &pRec->Counter, STAMTYPE_COUNTER, szCliStatName, STAMUNIT_OCCURENCES, "Number of times cli was executed.");
510
511 bool fRc = RTAvlPVInsert(&pVM->em.s.pCliStatTree, &pRec->Core);
512 Assert(fRc); NOREF(fRc);
513 }
514 STAM_COUNTER_INC(&pRec->Counter);
515 STAM_COUNTER_INC(&pVM->em.s.StatTotalClis);
516}
517#endif /* VBOX_WITH_STATISTICS */
518
519
520/**
521 * Debug loop.
522 *
523 * @returns VBox status code for EM.
524 * @param pVM VM handle.
525 * @param rc Current EM VBox status code..
526 */
527static int emR3Debug(PVM pVM, int rc)
528{
529 for (;;)
530 {
531 Log(("emR3Debug: rc=%Vrc\n", rc));
532 const int rcLast = rc;
533
534 /*
535 * Debug related RC.
536 */
537 switch (rc)
538 {
539 /*
540 * Single step an instruction.
541 */
542 case VINF_EM_DBG_STEP:
543 if ( pVM->em.s.enmState == EMSTATE_DEBUG_GUEST_RAW
544 || pVM->em.s.enmState == EMSTATE_DEBUG_HYPER
545 || pVM->em.s.fForceRAW /* paranoia */)
546 rc = emR3RawStep(pVM);
547 else
548 {
549 Assert(pVM->em.s.enmState == EMSTATE_DEBUG_GUEST_REM);
550 rc = emR3RemStep(pVM);
551 }
552 break;
553
554 /*
555 * Simple events: stepped, breakpoint, stop/assertion.
556 */
557 case VINF_EM_DBG_STEPPED:
558 rc = DBGFR3Event(pVM, DBGFEVENT_STEPPED);
559 break;
560
561 case VINF_EM_DBG_BREAKPOINT:
562 rc = DBGFR3EventBreakpoint(pVM, DBGFEVENT_BREAKPOINT);
563 break;
564
565 case VINF_EM_DBG_STOP:
566 rc = DBGFR3EventSrc(pVM, DBGFEVENT_DEV_STOP, NULL, 0, NULL, NULL);
567 break;
568
569 case VINF_EM_DBG_HYPER_STEPPED:
570 rc = DBGFR3Event(pVM, DBGFEVENT_STEPPED_HYPER);
571 break;
572
573 case VINF_EM_DBG_HYPER_BREAKPOINT:
574 rc = DBGFR3EventBreakpoint(pVM, DBGFEVENT_BREAKPOINT_HYPER);
575 break;
576
577 case VINF_EM_DBG_HYPER_ASSERTION:
578 RTPrintf("\nVINF_EM_DBG_HYPER_ASSERTION:\n%s%s\n", VMMR3GetGCAssertMsg1(pVM), VMMR3GetGCAssertMsg2(pVM));
579 rc = DBGFR3EventAssertion(pVM, DBGFEVENT_ASSERTION_HYPER, VMMR3GetGCAssertMsg1(pVM), VMMR3GetGCAssertMsg2(pVM));
580 break;
581
582 /*
583 * Guru meditation.
584 */
585 default: /** @todo don't use default for guru, but make special errors code! */
586 rc = DBGFR3Event(pVM, DBGFEVENT_FATAL_ERROR);
587 break;
588 }
589
590 /*
591 * Process the result.
592 */
593 do
594 {
595 switch (rc)
596 {
597 /*
598 * Continue the debugging loop.
599 */
600 case VINF_EM_DBG_STEP:
601 case VINF_EM_DBG_STOP:
602 case VINF_EM_DBG_STEPPED:
603 case VINF_EM_DBG_BREAKPOINT:
604 case VINF_EM_DBG_HYPER_STEPPED:
605 case VINF_EM_DBG_HYPER_BREAKPOINT:
606 case VINF_EM_DBG_HYPER_ASSERTION:
607 break;
608
609 /*
610 * Resuming execution (in some form) has to be done here if we got
611 * a hypervisor debug event.
612 */
613 case VINF_SUCCESS:
614 case VINF_EM_RESUME:
615 case VINF_EM_SUSPEND:
616 case VINF_EM_RESCHEDULE:
617 case VINF_EM_RESCHEDULE_RAW:
618 case VINF_EM_RESCHEDULE_REM:
619 case VINF_EM_HALT:
620 if (pVM->em.s.enmState == EMSTATE_DEBUG_HYPER)
621 {
622 rc = emR3RawResumeHyper(pVM);
623 if (rc != VINF_SUCCESS && VBOX_SUCCESS(rc))
624 continue;
625 }
626 if (rc == VINF_SUCCESS)
627 rc = VINF_EM_RESCHEDULE;
628 return rc;
629
630 /*
631 * The debugger isn't attached.
632 * We'll simply turn the thing off since that's the easiest thing to do.
633 */
634 case VERR_DBGF_NOT_ATTACHED:
635 switch (rcLast)
636 {
637 case VINF_EM_DBG_HYPER_ASSERTION:
638 case VINF_EM_DBG_HYPER_STEPPED:
639 case VINF_EM_DBG_HYPER_BREAKPOINT:
640 return rcLast;
641 }
642 return VINF_EM_OFF;
643
644 /*
645 * Status codes terminating the VM in one or another sense.
646 */
647 case VINF_EM_TERMINATE:
648 case VINF_EM_OFF:
649 case VINF_EM_RESET:
650 case VINF_EM_RAW_STALE_SELECTOR:
651 case VINF_EM_RAW_IRET_TRAP:
652 case VERR_TRPM_PANIC:
653 case VERR_TRPM_DONT_PANIC:
654 case VERR_INTERNAL_ERROR:
655 return rc;
656
657 /*
658 * The rest is unexpected, and will keep us here.
659 */
660 default:
661 AssertMsgFailed(("Unxpected rc %Vrc!\n", rc));
662 break;
663 }
664 } while (false);
665 } /* debug for ever */
666}
667
668
669/**
670 * Steps recompiled code.
671 *
672 * @returns VBox status code. The most important ones are: VINF_EM_STEP_EVENT,
673 * VINF_EM_RESCHEDULE, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
674 *
675 * @param pVM VM handle.
676 */
677static int emR3RemStep(PVM pVM)
678{
679 LogFlow(("emR3RemStep: cs:eip=%04x:%08x\n", CPUMGetGuestCS(pVM), CPUMGetGuestEIP(pVM)));
680
681 /*
682 * Switch to REM, step instruction, switch back.
683 */
684 int rc = REMR3State(pVM);
685 if (VBOX_SUCCESS(rc))
686 {
687 rc = REMR3Step(pVM);
688 REMR3StateBack(pVM);
689 }
690 LogFlow(("emR3RemStep: returns %Vrc cs:eip=%04x:%08x\n", rc, CPUMGetGuestCS(pVM), CPUMGetGuestEIP(pVM)));
691 return rc;
692}
693
694/**
695 * Executes recompiled code.
696 *
697 * This function contains the recompiler version of the inner
698 * execution loop (the outer loop being in EMR3ExecuteVM()).
699 *
700 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE,
701 * VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
702 *
703 * @param pVM VM handle.
704 * @param pfFFDone Where to store an indicator telling wheter or not
705 * FFs were done before returning.
706 *
707 */
708static int emR3RemExecute(PVM pVM, bool *pfFFDone)
709{
710#ifdef LOG_ENABLED
711 PCPUMCTX pCtx = pVM->em.s.pCtx;
712 if ((pCtx->ss & X86_SEL_RPL) == 0)
713 Log(("EMR0: %08X ESP=%08X IF=%d CPL=%d\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, (pCtx->ss & X86_SEL_RPL)));
714#endif
715 STAM_PROFILE_ADV_START(&pVM->em.s.StatREMTotal, a);
716
717#if defined(VBOX_STRICT) && defined(DEBUG_bird)
718 AssertMsg( VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3|VM_FF_PGM_SYNC_CR3_NON_GLOBAL)
719 || !MMHyperIsInsideArea(pVM, CPUMGetGuestEIP(pVM)), /** @todo #1419 - get flat address. */
720 ("cs:eip=%RX16:%RX32\n", CPUMGetGuestCS(pVM), CPUMGetGuestEIP(pVM)));
721#endif
722
723 /*
724 * Spin till we get a forced action which returns anything but VINF_SUCCESS
725 * or the REM suggests raw-mode execution.
726 */
727 *pfFFDone = false;
728 bool fInREMState = false;
729 int rc = VINF_SUCCESS;
730 for (;;)
731 {
732 /*
733 * Update REM state if not already in sync.
734 */
735 if (!fInREMState)
736 {
737 STAM_PROFILE_START(&pVM->em.s.StatREMSync, b);
738 rc = REMR3State(pVM);
739 STAM_PROFILE_STOP(&pVM->em.s.StatREMSync, b);
740 if (VBOX_FAILURE(rc))
741 break;
742 fInREMState = true;
743
744 /*
745 * We might have missed the raising of VMREQ, TIMER and some other
746 * imporant FFs while we were busy switching the state. So, check again.
747 */
748 if (VM_FF_ISPENDING(pVM, VM_FF_REQUEST | VM_FF_TIMER | VM_FF_PDM_QUEUES | VM_FF_DBGF | VM_FF_TERMINATE | VM_FF_RESET))
749 {
750 LogFlow(("emR3RemExecute: Skipping run, because FF is set. %#x\n", pVM->fForcedActions));
751 goto l_REMDoForcedActions;
752 }
753 }
754
755
756 /*
757 * Execute REM.
758 */
759 STAM_PROFILE_START(&pVM->em.s.StatREMExec, c);
760 rc = REMR3Run(pVM);
761 STAM_PROFILE_STOP(&pVM->em.s.StatREMExec, c);
762
763
764 /*
765 * Deal with high priority post execution FFs before doing anything else.
766 */
767 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK))
768 rc = emR3HighPriorityPostForcedActions(pVM, rc);
769
770 /*
771 * Process the returned status code.
772 * (Try keep this short! Call functions!)
773 */
774 if (rc != VINF_SUCCESS)
775 {
776 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
777 break;
778 if (rc != VINF_REM_INTERRUPED_FF)
779 {
780 /*
781 * Anything which is not known to us means an internal error
782 * and the termination of the VM!
783 */
784 AssertMsgFailed(("Unknown GC return code: %Vra\n", rc));
785 break;
786 }
787 }
788
789
790 /*
791 * Check and execute forced actions.
792 * Sync back the VM state before calling any of these.
793 */
794#ifdef VBOX_HIGH_RES_TIMERS_HACK
795 TMTimerPoll(pVM);
796#endif
797 if (VM_FF_ISPENDING(pVM, VM_FF_ALL_BUT_RAW_MASK & ~(VM_FF_CSAM_FLUSH_DIRTY_PAGE | VM_FF_CSAM_SCAN_PAGE)))
798 {
799l_REMDoForcedActions:
800 if (fInREMState)
801 {
802 STAM_PROFILE_START(&pVM->em.s.StatREMSync, d);
803 REMR3StateBack(pVM);
804 STAM_PROFILE_STOP(&pVM->em.s.StatREMSync, d);
805 fInREMState = false;
806 }
807 STAM_PROFILE_ADV_SUSPEND(&pVM->em.s.StatREMTotal, a);
808 rc = emR3ForcedActions(pVM, rc);
809 STAM_PROFILE_ADV_RESUME(&pVM->em.s.StatREMTotal, a);
810 if ( rc != VINF_SUCCESS
811 && rc != VINF_EM_RESCHEDULE_REM)
812 {
813 *pfFFDone = true;
814 break;
815 }
816 }
817
818 } /* The Inner Loop, recompiled execution mode version. */
819
820
821 /*
822 * Returning. Sync back the VM state if required.
823 */
824 if (fInREMState)
825 {
826 STAM_PROFILE_START(&pVM->em.s.StatREMSync, e);
827 REMR3StateBack(pVM);
828 STAM_PROFILE_STOP(&pVM->em.s.StatREMSync, e);
829 }
830
831 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatREMTotal, a);
832 return rc;
833}
834
835
836/**
837 * Resumes executing hypervisor after a debug event.
838 *
839 * This is kind of special since our current guest state is
840 * potentially out of sync.
841 *
842 * @returns VBox status code.
843 * @param pVM The VM handle.
844 */
845static int emR3RawResumeHyper(PVM pVM)
846{
847 int rc;
848 PCPUMCTX pCtx = pVM->em.s.pCtx;
849 Assert(pVM->em.s.enmState == EMSTATE_DEBUG_HYPER);
850 Log(("emR3RawResumeHyper: cs:eip=%RTsel:%RGr efl=%RGr\n", pCtx->cs, pCtx->eip, pCtx->eflags));
851
852 /*
853 * Resume execution.
854 */
855 CPUMRawEnter(pVM, NULL);
856 CPUMSetHyperEFlags(pVM, CPUMGetHyperEFlags(pVM) | X86_EFL_RF);
857 rc = VMMR3ResumeHyper(pVM);
858 Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr - returned from GC with rc=%Vrc\n", pCtx->cs, pCtx->eip, pCtx->eflags, rc));
859 rc = CPUMRawLeave(pVM, NULL, rc);
860 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
861
862 /*
863 * Deal with the return code.
864 */
865 rc = emR3HighPriorityPostForcedActions(pVM, rc);
866 rc = emR3RawHandleRC(pVM, pCtx, rc);
867 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
868 return rc;
869}
870
871
872/**
873 * Steps rawmode.
874 *
875 * @returns VBox status code.
876 * @param pVM The VM handle.
877 */
878static int emR3RawStep(PVM pVM)
879{
880 Assert( pVM->em.s.enmState == EMSTATE_DEBUG_HYPER
881 || pVM->em.s.enmState == EMSTATE_DEBUG_GUEST_RAW
882 || pVM->em.s.enmState == EMSTATE_DEBUG_GUEST_REM);
883 int rc;
884 PCPUMCTX pCtx = pVM->em.s.pCtx;
885 bool fGuest = pVM->em.s.enmState != EMSTATE_DEBUG_HYPER;
886 Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr\n", fGuest ? CPUMGetGuestCS(pVM) : CPUMGetHyperCS(pVM),
887 fGuest ? CPUMGetGuestEIP(pVM) : CPUMGetHyperEIP(pVM), fGuest ? CPUMGetGuestEFlags(pVM) : CPUMGetHyperEFlags(pVM)));
888
889 if (fGuest)
890 {
891 /*
892 * Check vital forced actions, but ignore pending interrupts and timers.
893 */
894 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
895 {
896 rc = emR3RawForcedActions(pVM, pCtx);
897 if (VBOX_FAILURE(rc))
898 return rc;
899 }
900
901 /*
902 * Set flags for single stepping.
903 */
904 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) | X86_EFL_TF | X86_EFL_RF);
905 }
906 else
907 CPUMSetHyperEFlags(pVM, CPUMGetHyperEFlags(pVM) | X86_EFL_TF | X86_EFL_RF);
908
909 /*
910 * Single step.
911 * We do not start time or anything, if anything we should just do a few nanoseconds.
912 */
913 CPUMRawEnter(pVM, NULL);
914 do
915 {
916 if (pVM->em.s.enmState == EMSTATE_DEBUG_HYPER)
917 rc = VMMR3ResumeHyper(pVM);
918 else
919 rc = VMMR3RawRunGC(pVM);
920 Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr - GC rc %Vrc\n", fGuest ? CPUMGetGuestCS(pVM) : CPUMGetHyperCS(pVM),
921 fGuest ? CPUMGetGuestEIP(pVM) : CPUMGetHyperEIP(pVM), fGuest ? CPUMGetGuestEFlags(pVM) : CPUMGetHyperEFlags(pVM), rc));
922 } while ( rc == VINF_SUCCESS
923 || rc == VINF_EM_RAW_INTERRUPT);
924 rc = CPUMRawLeave(pVM, NULL, rc);
925 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
926
927 /*
928 * Make sure the trap flag is cleared.
929 * (Too bad if the guest is trying to single step too.)
930 */
931 if (fGuest)
932 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) & ~X86_EFL_TF);
933 else
934 CPUMSetHyperEFlags(pVM, CPUMGetHyperEFlags(pVM) & ~X86_EFL_TF);
935
936 /*
937 * Deal with the return codes.
938 */
939 rc = emR3HighPriorityPostForcedActions(pVM, rc);
940 rc = emR3RawHandleRC(pVM, pCtx, rc);
941 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
942 return rc;
943}
944
945
946/**
947 * Executes one (or perhaps a few more) instruction(s).
948 *
949 * @returns VBox status code suitable for EM.
950 *
951 * @param pVM VM handle.
952 * @param rcGC GC return code
953 * @param pszPrefix Disassembly prefix. If not NULL we'll disassemble the
954 * instruction and prefix the log output with this text.
955 */
956#ifdef LOG_ENABLED
957static int emR3RawExecuteInstructionWorker(PVM pVM, int rcGC, const char *pszPrefix)
958#else
959static int emR3RawExecuteInstructionWorker(PVM pVM, int rcGC)
960#endif
961{
962 PCPUMCTX pCtx = pVM->em.s.pCtx;
963 int rc;
964
965 /*
966 *
967 * The simple solution is to use the recompiler.
968 * The better solution is to disassemble the current instruction and
969 * try handle as many as possible without using REM.
970 *
971 */
972
973#ifdef LOG_ENABLED
974 /*
975 * Disassemble the instruction if requested.
976 */
977 if (pszPrefix)
978 {
979 DBGFR3InfoLog(pVM, "cpumguest", pszPrefix);
980 DBGFR3DisasInstrCurrentLog(pVM, pszPrefix);
981 }
982#endif /* LOG_ENABLED */
983
984
985 Assert((pCtx->ss & X86_SEL_RPL) != 1);
986
987 /*
988 * PATM is making life more interesting.
989 * We cannot hand anything to REM which has an EIP inside patch code. So, we'll
990 * tell PATM there is a trap in this code and have it take the appropriate actions
991 * to allow us execute the code in REM.
992 */
993 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
994 {
995 Log(("emR3RawExecuteInstruction: In patch block. eip=%VGv\n", pCtx->eip));
996
997 RTGCPTR pNewEip;
998 rc = PATMR3HandleTrap(pVM, pCtx, pCtx->eip, &pNewEip);
999 switch (rc)
1000 {
1001 /*
1002 * It's not very useful to emulate a single instruction and then go back to raw
1003 * mode; just execute the whole block until IF is set again.
1004 */
1005 case VINF_SUCCESS:
1006 Log(("emR3RawExecuteInstruction: Executing instruction starting at new address %VGv IF=%d VMIF=%x\n",
1007 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1008 pCtx->eip = pNewEip;
1009 Assert(pCtx->eip);
1010
1011 if (pCtx->eflags.Bits.u1IF)
1012 {
1013 /*
1014 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1015 */
1016 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1017 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1018 }
1019#if 0 /** @note no noticable change; revisit later when we can emulate iret ourselves. */
1020 else if (rcGC == VINF_PATM_PENDING_IRQ_AFTER_IRET)
1021 {
1022 /* special case: iret, that sets IF, detected a pending irq/event */
1023 return emR3RawExecuteInstruction(pVM, "PATCHIRET");
1024 }
1025#endif
1026 return VINF_EM_RESCHEDULE_REM;
1027
1028 /*
1029 * One instruction.
1030 */
1031 case VINF_PATCH_EMULATE_INSTR:
1032 Log(("emR3RawExecuteInstruction: Emulate patched instruction at %VGv IF=%d VMIF=%x\n",
1033 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1034 pCtx->eip = pNewEip;
1035 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1036
1037 /*
1038 * The patch was disabled, hand it to the REM.
1039 */
1040 case VERR_PATCH_DISABLED:
1041 Log(("emR3RawExecuteInstruction: Disabled patch -> new eip %VGv IF=%d VMIF=%x\n",
1042 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1043 pCtx->eip = pNewEip;
1044 if (pCtx->eflags.Bits.u1IF)
1045 {
1046 /*
1047 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1048 */
1049 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1050 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1051 }
1052 return VINF_EM_RESCHEDULE_REM;
1053
1054 /* Force continued patch exection; usually due to write monitored stack. */
1055 case VINF_PATCH_CONTINUE:
1056 return VINF_SUCCESS;
1057
1058 default:
1059 AssertReleaseMsgFailed(("Unknown return code %Vrc from PATMR3HandleTrap\n", rc));
1060 return VERR_INTERNAL_ERROR;
1061 }
1062 }
1063
1064#if 0 /// @todo Sander, this breaks the linux image (panics). So, I'm disabling it for now. (OP_MOV triggers it btw.)
1065 DISCPUSTATE Cpu;
1066 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "GEN EMU");
1067 if (VBOX_SUCCESS(rc))
1068 {
1069 uint32_t size;
1070
1071 switch (Cpu.pCurInstr->opcode)
1072 {
1073 case OP_MOV:
1074 case OP_AND:
1075 case OP_OR:
1076 case OP_XOR:
1077 case OP_POP:
1078 case OP_INC:
1079 case OP_DEC:
1080 case OP_XCHG:
1081 STAM_PROFILE_START(&pVM->em.s.StatMiscEmu, a);
1082 rc = EMInterpretInstructionCPU(pVM, &Cpu, CPUMCTX2CORE(pCtx), 0, &size);
1083 if (VBOX_SUCCESS(rc))
1084 {
1085 pCtx->eip += Cpu.opsize;
1086 STAM_PROFILE_STOP(&pVM->em.s.StatMiscEmu, a);
1087 return rc;
1088 }
1089 if (rc != VERR_EM_INTERPRETER)
1090 AssertMsgFailedReturn(("rc=%Vrc\n", rc), rc);
1091 STAM_PROFILE_STOP(&pVM->em.s.StatMiscEmu, a);
1092 break;
1093 }
1094 }
1095#endif
1096 STAM_PROFILE_START(&pVM->em.s.StatREMEmu, a);
1097 rc = REMR3EmulateInstruction(pVM);
1098 STAM_PROFILE_STOP(&pVM->em.s.StatREMEmu, a);
1099
1100 return rc;
1101}
1102
1103
1104/**
1105 * Executes one (or perhaps a few more) instruction(s).
1106 * This is just a wrapper for discarding pszPrefix in non-logging builds.
1107 *
1108 * @returns VBox status code suitable for EM.
1109 * @param pVM VM handle.
1110 * @param pszPrefix Disassembly prefix. If not NULL we'll disassemble the
1111 * instruction and prefix the log output with this text.
1112 * @param rcGC GC return code
1113 */
1114DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, const char *pszPrefix, int rcGC)
1115{
1116#ifdef LOG_ENABLED
1117 return emR3RawExecuteInstructionWorker(pVM, rcGC, pszPrefix);
1118#else
1119 return emR3RawExecuteInstructionWorker(pVM, rcGC);
1120#endif
1121}
1122
1123/**
1124 * Executes one (or perhaps a few more) IO instruction(s).
1125 *
1126 * @returns VBox status code suitable for EM.
1127 * @param pVM VM handle.
1128 */
1129int emR3RawExecuteIOInstruction(PVM pVM)
1130{
1131 int rc;
1132 PCPUMCTX pCtx = pVM->em.s.pCtx;
1133
1134 STAM_PROFILE_START(&pVM->em.s.StatIOEmu, a);
1135
1136 /** @todo probably we should fall back to the recompiler; otherwise we'll go back and forth between HC & GC
1137 * as io instructions tend to come in packages of more than one
1138 */
1139 DISCPUSTATE Cpu;
1140 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "IO EMU");
1141 if (VBOX_SUCCESS(rc))
1142 {
1143#ifdef VBOX_WITH_STATISTICS
1144 switch (Cpu.pCurInstr->opcode)
1145 {
1146 case OP_INSB:
1147 case OP_INSWD:
1148 case OP_IN:
1149 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatIn);
1150 break;
1151
1152 case OP_OUTSB:
1153 case OP_OUTSWD:
1154 case OP_OUT:
1155 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatOut);
1156 break;
1157 }
1158#endif
1159
1160 if (!(Cpu.prefix & (PREFIX_REP | PREFIX_REPNE)))
1161 {
1162 OP_PARAMVAL ParmVal;
1163 int rc;
1164 switch (Cpu.pCurInstr->opcode)
1165 {
1166 case OP_IN:
1167 {
1168 rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), &Cpu, &Cpu.param2, &ParmVal, PARAM_SOURCE);
1169 if ( VBOX_FAILURE(rc)
1170 || ParmVal.type != PARMTYPE_IMMEDIATE)
1171 break;
1172
1173 if (!(Cpu.param1.flags & (USE_REG_GEN8 | USE_REG_GEN16 | USE_REG_GEN32)))
1174 break;
1175
1176 /* Make sure port access is allowed */
1177 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), ParmVal.val.val16, Cpu.param1.size);
1178 if (rc != VINF_SUCCESS)
1179 {
1180 if (rc == VINF_EM_RAW_GUEST_TRAP)
1181 rc = emR3RawGuestTrap(pVM);
1182
1183 return rc;
1184 }
1185
1186 uint32_t u32Value = 0;
1187 switch (Cpu.param1.size)
1188 {
1189 case 1:
1190 Assert(Cpu.param1.base.reg_gen8 == USE_REG_AL);
1191 rc = IOMIOPortRead(pVM, ParmVal.val.val16, &u32Value, sizeof(uint8_t));
1192 if (VBOX_SUCCESS(rc))
1193 {
1194 pCtx->eax = (pCtx->eax & ~0xFF) | (uint8_t)u32Value;
1195 Log(("EMU: in8 %x, %x\n", ParmVal.val.val16, pCtx->eax & 0xFF));
1196 pCtx->eip += Cpu.opsize;
1197 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1198 return rc;
1199 }
1200 AssertRC(rc);
1201 break;
1202
1203 case 2:
1204 Assert(Cpu.param1.base.reg_gen16 == USE_REG_AX);
1205 rc = IOMIOPortRead(pVM, ParmVal.val.val16, &u32Value, sizeof(uint16_t));
1206 if (VBOX_SUCCESS(rc))
1207 {
1208 pCtx->eax = (pCtx->eax & ~0xFFFF) | (uint16_t)u32Value;
1209 Log(("EMU: in16 %x, %x\n", ParmVal.val.val16, pCtx->eax & 0xFFFF));
1210 pCtx->eip += Cpu.opsize;
1211 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1212 return rc;
1213 }
1214 AssertRC(rc);
1215 break;
1216
1217 case 4:
1218 Assert(Cpu.param1.base.reg_gen32 == USE_REG_EAX);
1219 rc = IOMIOPortRead(pVM, ParmVal.val.val16, &u32Value, sizeof(uint32_t));
1220 if (VBOX_SUCCESS(rc))
1221 {
1222 pCtx->eax = u32Value;
1223 Log(("EMU: in32 %x, %x\n", ParmVal.val.val16, pCtx->eax));
1224 pCtx->eip += Cpu.opsize;
1225 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1226 return rc;
1227 }
1228 AssertRC(rc);
1229 break;
1230
1231 default:
1232 AssertMsgFailed(("Unexpected port size %d\n", ParmVal.size));
1233 break;
1234 }
1235 break;
1236 }
1237
1238 case OP_OUT:
1239 {
1240 // it really is the destination, but we're interested in the destination value. hence we specify PARAM_SOURCE (bit of a hack)
1241 rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), &Cpu, &Cpu.param1, &ParmVal, PARAM_SOURCE);
1242 if ( VBOX_FAILURE(rc)
1243 || ParmVal.type != PARMTYPE_IMMEDIATE)
1244 break;
1245 OP_PARAMVAL ParmVal2;
1246 rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), &Cpu, &Cpu.param2, &ParmVal2, PARAM_SOURCE);
1247 if ( VBOX_FAILURE(rc)
1248 || ParmVal2.type != PARMTYPE_IMMEDIATE)
1249 break;
1250
1251 /* Make sure port access is allowed */
1252 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), ParmVal.val.val16, Cpu.param1.size);
1253 if (rc != VINF_SUCCESS)
1254 {
1255 if (rc == VINF_EM_RAW_GUEST_TRAP)
1256 rc = emR3RawGuestTrap(pVM);
1257
1258 return rc;
1259 }
1260
1261 AssertMsg(Cpu.param2.size == ParmVal2.size, ("size %d vs %d\n", Cpu.param2.size, ParmVal2.size));
1262 switch (ParmVal2.size)
1263 {
1264 case 1:
1265 Log(("EMU: out8 %x, %x\n", ParmVal.val.val16, ParmVal2.val.val8));
1266 rc = IOMIOPortWrite(pVM, ParmVal.val.val16, ParmVal2.val.val8, sizeof(ParmVal2.val.val8));
1267 if (VBOX_SUCCESS(rc))
1268 {
1269 pCtx->eip += Cpu.opsize;
1270 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1271 return rc;
1272 }
1273 AssertRC(rc);
1274 break;
1275
1276 case 2:
1277 Log(("EMU: out16 %x, %x\n", ParmVal.val.val16, ParmVal2.val.val16));
1278 rc = IOMIOPortWrite(pVM, ParmVal.val.val16, ParmVal2.val.val16, sizeof(ParmVal2.val.val16));
1279 if (VBOX_SUCCESS(rc))
1280 {
1281 pCtx->eip += Cpu.opsize;
1282 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1283 return rc;
1284 }
1285 AssertRC(rc);
1286 break;
1287
1288 case 4:
1289 Log(("EMU: out32 %x, %x\n", ParmVal.val.val16, ParmVal2.val.val32));
1290 rc = IOMIOPortWrite(pVM, ParmVal.val.val16, ParmVal2.val.val32, sizeof(ParmVal2.val.val32));
1291 if (VBOX_SUCCESS(rc))
1292 {
1293 pCtx->eip += Cpu.opsize;
1294 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1295 return rc;
1296 }
1297 AssertRC(rc);
1298 break;
1299
1300 default:
1301 AssertMsgFailed(("Unexpected port size %d\n", ParmVal2.size));
1302 break;
1303 }
1304 break;
1305 }
1306
1307 default:
1308 break;
1309 }
1310 }//if(!(Cpu.prefix & (PREFIX_REP|PREFIX_REPNE))
1311 else if (Cpu.prefix & PREFIX_REP)
1312 {
1313 switch (Cpu.pCurInstr->opcode)
1314 {
1315 case OP_INSB:
1316 case OP_INSWD:
1317 {
1318 /*
1319 * Do not optimize the destination address decrement case (not worth the effort)
1320 * and likewise for 16 bit address size (would need to use and update only cx/di).
1321 */
1322 if (pCtx->eflags.Bits.u1DF || Cpu.addrmode != CPUMODE_32BIT)
1323 break;
1324 /*
1325 * Get port number and transfer count directly from the registers (no need to bother the
1326 * disassembler). And get the I/O register size from the opcode / prefix.
1327 */
1328 uint32_t uPort = pCtx->edx & 0xffff;
1329 RTGCUINTREG cTransfers = pCtx->ecx;
1330 unsigned cbUnit;
1331 if (Cpu.pCurInstr->opcode == OP_INSB)
1332 cbUnit = 1;
1333 else
1334 cbUnit = Cpu.opmode == CPUMODE_32BIT ? 4 : 2;
1335
1336 RTGCPTR GCPtrDst = pCtx->edi;
1337 /* Access verification first; we can't recover from traps inside this instruction, as the port read cannot be repeated. */
1338 rc = PGMVerifyAccess(pVM, GCPtrDst, cTransfers * cbUnit,
1339 X86_PTE_RW | (((pCtx->ss & X86_SEL_RPL) == 3) ? X86_PTE_US : 0));
1340 if (rc != VINF_SUCCESS)
1341 {
1342 Log(("EMU: rep ins%d will generate a trap -> fallback, rc=%d\n", cbUnit * 8, rc));
1343 break;
1344 }
1345
1346 Log(("EMU: rep ins%d port %#x count %d\n", cbUnit * 8, uPort, cTransfers));
1347
1348 /* Make sure port access is allowed */
1349 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), uPort, cbUnit);
1350 if (rc != VINF_SUCCESS)
1351 {
1352 if (rc == VINF_EM_RAW_GUEST_TRAP)
1353 rc = emR3RawGuestTrap(pVM);
1354
1355 return rc;
1356 }
1357
1358 /*
1359 * If the device supports string transfers, ask it to do as
1360 * much as it wants. The rest is done with single-word transfers.
1361 */
1362 rc = IOMIOPortReadString(pVM, uPort, &GCPtrDst, &cTransfers, cbUnit);
1363 AssertRC(rc); Assert(cTransfers <= pCtx->ecx);
1364
1365 while (cTransfers && rc == VINF_SUCCESS)
1366 {
1367 uint32_t u32Value;
1368 rc = IOMIOPortRead(pVM, uPort, &u32Value, cbUnit);
1369 AssertRC(rc);
1370 int rc2 = PGMPhysWriteGCPtrDirty(pVM, GCPtrDst, &u32Value, cbUnit);
1371 AssertRC(rc2);
1372 GCPtrDst += cbUnit;
1373 cTransfers--;
1374 }
1375 pCtx->edi += (pCtx->ecx - cTransfers) * cbUnit;
1376 pCtx->ecx = cTransfers;
1377 if (!cTransfers && VBOX_SUCCESS(rc))
1378 pCtx->eip += Cpu.opsize;
1379 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1380 return rc;
1381 }
1382 case OP_OUTSB:
1383 case OP_OUTSWD:
1384 {
1385 /*
1386 * Do not optimize the source address decrement case (not worth the effort)
1387 * and likewise for 16 bit address size (would need to use and update only cx/si).
1388 */
1389 if (pCtx->eflags.Bits.u1DF || Cpu.addrmode != CPUMODE_32BIT)
1390 break;
1391 /*
1392 * Get port number and transfer count directly from the registers (no need to bother the
1393 * disassembler). And get the I/O register size from the opcode / prefix.
1394 */
1395 uint32_t uPort = pCtx->edx & 0xffff;
1396 RTGCUINTREG cTransfers = pCtx->ecx;
1397 unsigned cbUnit;
1398 if (Cpu.pCurInstr->opcode == OP_OUTSB)
1399 cbUnit = 1;
1400 else
1401 cbUnit = Cpu.opmode == CPUMODE_32BIT ? 4 : 2;
1402
1403 RTGCPTR GCPtrSrc = pCtx->esi;
1404 /* Access verification first; we currently can't recover properly from traps inside this instruction */
1405 rc = PGMVerifyAccess(pVM, GCPtrSrc, cTransfers * cbUnit, (((pCtx->ss & X86_SEL_RPL) == 3) ? X86_PTE_US : 0));
1406 if (rc != VINF_SUCCESS)
1407 {
1408 Log(("EMU: rep outs%d will generate a trap -> fallback, rc=%d\n", cbUnit * 8, rc));
1409 break;
1410 }
1411
1412 Log(("EMU: rep outs%d port %#x count %d\n", cbUnit * 8, uPort, cTransfers));
1413
1414 /* Make sure port access is allowed */
1415 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), uPort, cbUnit);
1416 if (rc != VINF_SUCCESS)
1417 {
1418 if (rc == VINF_EM_RAW_GUEST_TRAP)
1419 rc = emR3RawGuestTrap(pVM);
1420
1421 return rc;
1422 }
1423
1424 /*
1425 * If the device supports string transfers, ask it to do as
1426 * much as it wants. The rest is done with single-word transfers.
1427 */
1428 rc = IOMIOPortWriteString(pVM, uPort, &GCPtrSrc, &cTransfers, cbUnit);
1429 AssertRC(rc); Assert(cTransfers <= pCtx->ecx);
1430
1431 while (cTransfers && rc == VINF_SUCCESS)
1432 {
1433 uint32_t u32Value;
1434 rc = PGMPhysReadGCPtr(pVM, &u32Value, GCPtrSrc, cbUnit);
1435 Assert(rc == VINF_SUCCESS);
1436 rc = IOMIOPortWrite(pVM, uPort, u32Value, cbUnit);
1437 AssertRC(rc);
1438 GCPtrSrc += cbUnit;
1439 cTransfers--;
1440 }
1441 pCtx->esi += (pCtx->ecx - cTransfers) * cbUnit;
1442 pCtx->ecx = cTransfers;
1443 if (!cTransfers && VBOX_SUCCESS(rc))
1444 pCtx->eip += Cpu.opsize;
1445 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1446 return rc;
1447 }
1448 }
1449 }//if(Cpu.prefix & PREFIX_REP)
1450 }
1451
1452 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1453 return emR3RawExecuteInstruction(pVM, "IO: ");
1454}
1455
1456
1457/**
1458 * Handle a guest context trap.
1459 *
1460 * @returns VBox status code suitable for EM.
1461 * @param pVM VM handle.
1462 */
1463static int emR3RawGuestTrap(PVM pVM)
1464{
1465 PCPUMCTX pCtx = pVM->em.s.pCtx;
1466
1467 /*
1468 * Get the trap info.
1469 */
1470 uint8_t u8TrapNo;
1471 bool fSoftwareInterrupt;
1472 RTGCUINT uErrorCode;
1473 RTGCUINTPTR uCR2;
1474 int rc = TRPMQueryTrapAll(pVM, &u8TrapNo, &fSoftwareInterrupt, &uErrorCode, &uCR2);
1475 if (VBOX_FAILURE(rc))
1476 {
1477 AssertReleaseMsgFailed(("No trap! (rc=%Vrc)\n", rc));
1478 return rc;
1479 }
1480
1481 /* Traps can be directly forwarded in hardware accelerated mode. */
1482 if (HWACCMR3IsActive(pVM))
1483 {
1484#ifdef LOGGING_ENABLED
1485 DBGFR3InfoLog(pVM, "cpumguest", "Guest trap");
1486 DBGFR3DisasInstrCurrentLog(pVM, "Guest trap");
1487#endif
1488 return VINF_EM_RESCHEDULE_HWACC;
1489 }
1490
1491 /** Scan kernel code that traps; we might not get another chance. */
1492 if ( (pCtx->ss & X86_SEL_RPL) <= 1
1493 && pCtx->eflags.Bits.u1VM == 0)
1494 {
1495 Assert(!PATMIsPatchGCAddr(pVM, pCtx->eip));
1496 CSAMR3CheckEIP(pVM, pCtx->eip, SELMIsSelector32Bit(pVM, pCtx->cs, &pCtx->csHid));
1497 }
1498
1499 if (u8TrapNo == 6) /* (#UD) Invalid opcode. */
1500 {
1501 DISCPUSTATE cpu;
1502
1503 /* If MONITOR & MWAIT are supported, then interpret them here. */
1504 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &cpu, "Guest Trap (#UD): ");
1505 if ( VBOX_SUCCESS(rc)
1506 && (cpu.pCurInstr->opcode == OP_MONITOR || cpu.pCurInstr->opcode == OP_MWAIT))
1507 {
1508 uint32_t u32Dummy, u32Features, u32ExtFeatures, size;
1509
1510 CPUMGetGuestCpuId(pVM, 1, &u32Dummy, &u32Dummy, &u32ExtFeatures, &u32Features);
1511
1512 if (u32ExtFeatures & X86_CPUID_FEATURE_ECX_MONITOR)
1513 {
1514 rc = TRPMResetTrap(pVM);
1515 AssertRC(rc);
1516
1517 rc = EMInterpretInstructionCPU(pVM, &cpu, CPUMCTX2CORE(pCtx), 0, &size);
1518 if (VBOX_SUCCESS(rc))
1519 {
1520 pCtx->eip += cpu.opsize;
1521 return rc;
1522 }
1523 return emR3RawExecuteInstruction(pVM, "Monitor: ");
1524 }
1525 }
1526 }
1527 else if (u8TrapNo == 13) /* (#GP) Privileged exception */
1528 {
1529 DISCPUSTATE cpu;
1530
1531 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &cpu, "Guest Trap: ");
1532 if (VBOX_SUCCESS(rc) && (cpu.pCurInstr->optype & OPTYPE_PORTIO))
1533 {
1534 /*
1535 * We should really check the TSS for the IO bitmap, but it's not like this
1536 * lazy approach really makes things worse.
1537 */
1538 rc = TRPMResetTrap(pVM);
1539 AssertRC(rc);
1540 return emR3RawExecuteInstruction(pVM, "IO Guest Trap: ");
1541 }
1542 }
1543
1544#ifdef LOG_ENABLED
1545 DBGFR3InfoLog(pVM, "cpumguest", "Guest trap");
1546 DBGFR3DisasInstrCurrentLog(pVM, "Guest trap");
1547
1548 /* Get guest page information. */
1549 uint64_t fFlags = 0;
1550 RTGCPHYS GCPhys = 0;
1551 int rc2 = PGMGstGetPage(pVM, uCR2, &fFlags, &GCPhys);
1552 Log(("emR3RawGuestTrap: cs:eip=%04x:%08x: trap=%02x err=%08x cr2=%08x cr0=%08x%s: Phys=%VGp fFlags=%08llx %s %s %s%s rc2=%d\n",
1553 pCtx->cs, pCtx->eip, u8TrapNo, uErrorCode, uCR2, pCtx->cr0, fSoftwareInterrupt ? " software" : "", GCPhys, fFlags,
1554 fFlags & X86_PTE_P ? "P " : "NP", fFlags & X86_PTE_US ? "U" : "S",
1555 fFlags & X86_PTE_RW ? "RW" : "R0", fFlags & X86_PTE_G ? " G" : "", rc2));
1556#endif
1557
1558 /*
1559 * #PG has CR2.
1560 * (Because of stuff like above we must set CR2 in a delayed fashion.)
1561 */
1562 if (u8TrapNo == 14 /* #PG */)
1563 pCtx->cr2 = uCR2;
1564
1565 return VINF_EM_RESCHEDULE_REM;
1566}
1567
1568
1569/**
1570 * Handle a ring switch trap.
1571 * Need to do statistics and to install patches. The result is going to REM.
1572 *
1573 * @returns VBox status code suitable for EM.
1574 * @param pVM VM handle.
1575 */
1576int emR3RawRingSwitch(PVM pVM)
1577{
1578 int rc;
1579 DISCPUSTATE Cpu;
1580 PCPUMCTX pCtx = pVM->em.s.pCtx;
1581
1582 /*
1583 * sysenter, syscall & callgate
1584 */
1585 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "RSWITCH: ");
1586 if (VBOX_SUCCESS(rc))
1587 {
1588 if (Cpu.pCurInstr->opcode == OP_SYSENTER)
1589 {
1590 if (pCtx->SysEnter.cs != 0)
1591 {
1592 rc = PATMR3InstallPatch(pVM, pCtx->eip, SELMIsSelector32Bit(pVM, pCtx->cs, &pCtx->csHid) ? PATMFL_CODE32 : 0);
1593 if (VBOX_SUCCESS(rc))
1594 {
1595 DBGFR3DisasInstrCurrentLog(pVM, "Patched sysenter instruction");
1596 return VINF_EM_RESCHEDULE_RAW;
1597 }
1598 }
1599 }
1600
1601#ifdef VBOX_WITH_STATISTICS
1602 switch (Cpu.pCurInstr->opcode)
1603 {
1604 case OP_SYSENTER:
1605 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysEnter);
1606 break;
1607 case OP_SYSEXIT:
1608 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysExit);
1609 break;
1610 case OP_SYSCALL:
1611 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysCall);
1612 break;
1613 case OP_SYSRET:
1614 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysRet);
1615 break;
1616 }
1617#endif
1618 }
1619 else
1620 AssertRC(rc);
1621
1622 /* go to the REM to emulate a single instruction */
1623 return emR3RawExecuteInstruction(pVM, "RSWITCH: ");
1624}
1625
1626/**
1627 * Handle a trap (#PF or #GP) in patch code
1628 *
1629 * @returns VBox status code suitable for EM.
1630 * @param pVM VM handle.
1631 * @param pCtx CPU context
1632 * @param gcret GC return code
1633 */
1634int emR3PatchTrap(PVM pVM, PCPUMCTX pCtx, int gcret)
1635{
1636 uint8_t u8TrapNo;
1637 int rc;
1638 bool fSoftwareInterrupt;
1639 RTGCUINT uErrorCode;
1640 RTGCUINTPTR uCR2;
1641
1642 Assert(PATMIsPatchGCAddr(pVM, pCtx->eip));
1643
1644 if (gcret == VINF_PATM_PATCH_INT3)
1645 {
1646 u8TrapNo = 3;
1647 uCR2 = 0;
1648 uErrorCode = 0;
1649 }
1650 else
1651 if (gcret == VINF_PATM_PATCH_TRAP_GP)
1652 {
1653 /* No active trap in this case. Kind of ugly. */
1654 u8TrapNo = X86_XCPT_GP;
1655 uCR2 = 0;
1656 uErrorCode = 0;
1657 }
1658 else
1659 {
1660 rc = TRPMQueryTrapAll(pVM, &u8TrapNo, &fSoftwareInterrupt, &uErrorCode, &uCR2);
1661 if (VBOX_FAILURE(rc))
1662 {
1663 AssertReleaseMsgFailed(("emR3PatchTrap: no trap! (rc=%Vrc) gcret=%Vrc\n", rc, gcret));
1664 return rc;
1665 }
1666 /* Reset the trap as we'll execute the original instruction again. */
1667 TRPMResetTrap(pVM);
1668 }
1669
1670 /*
1671 * Deal with traps inside patch code.
1672 * (This code won't run outside GC.)
1673 */
1674 if (u8TrapNo != 1)
1675 {
1676#ifdef LOG_ENABLED
1677 DBGFR3InfoLog(pVM, "cpumguest", "Trap in patch code");
1678 DBGFR3DisasInstrCurrentLog(pVM, "Patch code");
1679#endif
1680 Log(("emR3PatchTrap: in patch: eip=%08x: trap=%02x err=%08x cr2=%08x cr0=%08x\n",
1681 pCtx->eip, u8TrapNo, uErrorCode, uCR2, pCtx->cr0));
1682
1683 RTGCPTR pNewEip;
1684 rc = PATMR3HandleTrap(pVM, pCtx, pCtx->eip, &pNewEip);
1685 switch (rc)
1686 {
1687 /*
1688 * Execute the faulting instruction.
1689 */
1690 case VINF_SUCCESS:
1691 {
1692 /** @todo execute a whole block */
1693 Log(("emR3PatchTrap: Executing faulting instruction at new address %VGv\n", pNewEip));
1694 if (!(pVM->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
1695 Log(("emR3PatchTrap: Virtual IF flag disabled!!\n"));
1696
1697 pCtx->eip = pNewEip;
1698 AssertRelease(pCtx->eip);
1699
1700 if (pCtx->eflags.Bits.u1IF)
1701 {
1702 /* Windows XP lets irets fault intentionally and then takes action based on the opcode; an
1703 * int3 patch overwrites it and leads to blue screens. Remove the patch in this case.
1704 */
1705 if ( u8TrapNo == X86_XCPT_GP
1706 && PATMIsInt3Patch(pVM, pCtx->eip, NULL, NULL))
1707 {
1708 /** @todo move to PATMR3HandleTrap */
1709 Log(("Possible Windows XP iret fault at %VGv\n", pCtx->eip));
1710 PATMR3RemovePatch(pVM, pCtx->eip);
1711 }
1712
1713 /** @todo Knoppix 5 regression when returning VINF_SUCCESS here and going back to raw mode. */
1714 /** @note possibly because a reschedule is required (e.g. iret to V86 code) */
1715
1716 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1717 /* Interrupts are enabled; just go back to the original instruction.
1718 return VINF_SUCCESS; */
1719 }
1720 return VINF_EM_RESCHEDULE_REM;
1721 }
1722
1723 /*
1724 * One instruction.
1725 */
1726 case VINF_PATCH_EMULATE_INSTR:
1727 Log(("emR3PatchTrap: Emulate patched instruction at %VGv IF=%d VMIF=%x\n",
1728 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1729 pCtx->eip = pNewEip;
1730 AssertRelease(pCtx->eip);
1731 return emR3RawExecuteInstruction(pVM, "PATCHEMUL: ");
1732
1733 /*
1734 * The patch was disabled, hand it to the REM.
1735 */
1736 case VERR_PATCH_DISABLED:
1737 if (!(pVM->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
1738 Log(("emR3PatchTrap: Virtual IF flag disabled!!\n"));
1739 pCtx->eip = pNewEip;
1740 AssertRelease(pCtx->eip);
1741
1742 if (pCtx->eflags.Bits.u1IF)
1743 {
1744 /*
1745 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1746 */
1747 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1748 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1749 }
1750 return VINF_EM_RESCHEDULE_REM;
1751
1752 /* Force continued patch exection; usually due to write monitored stack. */
1753 case VINF_PATCH_CONTINUE:
1754 return VINF_SUCCESS;
1755
1756 /*
1757 * Anything else is *fatal*.
1758 */
1759 default:
1760 AssertReleaseMsgFailed(("Unknown return code %Vrc from PATMR3HandleTrap!\n", rc));
1761 return VERR_INTERNAL_ERROR;
1762 }
1763 }
1764 return VINF_SUCCESS;
1765}
1766
1767
1768/**
1769 * Handle a privileged instruction.
1770 *
1771 * @returns VBox status code suitable for EM.
1772 * @param pVM VM handle.
1773 */
1774int emR3RawPrivileged(PVM pVM)
1775{
1776 STAM_PROFILE_START(&pVM->em.s.StatPrivEmu, a);
1777 PCPUMCTX pCtx = pVM->em.s.pCtx;
1778
1779 if (PATMIsEnabled(pVM))
1780 {
1781 /*
1782 * Check if in patch code.
1783 */
1784 if (PATMR3IsInsidePatchJump(pVM, pCtx->eip, NULL))
1785 {
1786#ifdef LOG_ENABLED
1787 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
1788#endif
1789 AssertMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08X\n", pCtx->eip));
1790 return VERR_EM_RAW_PATCH_CONFLICT;
1791 }
1792 if ( (pCtx->ss & X86_SEL_RPL) == 0
1793 && !PATMIsPatchGCAddr(pVM, pCtx->eip))
1794 {
1795 int rc = PATMR3InstallPatch(pVM, pCtx->eip, SELMIsSelector32Bit(pVM, pCtx->cs, &pCtx->csHid) ? PATMFL_CODE32 : 0);
1796 if (VBOX_SUCCESS(rc))
1797 {
1798#ifdef LOG_ENABLED
1799 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
1800#endif
1801 DBGFR3DisasInstrCurrentLog(pVM, "Patched privileged instruction");
1802 return VINF_SUCCESS;
1803 }
1804 }
1805 }
1806
1807#ifdef LOG_ENABLED
1808 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
1809 DBGFR3DisasInstrCurrentLog(pVM, "Privileged instr: ");
1810#endif
1811
1812 /*
1813 * Instruction statistics and logging.
1814 */
1815 DISCPUSTATE Cpu;
1816 int rc;
1817
1818 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "PRIV: ");
1819 if (VBOX_SUCCESS(rc))
1820 {
1821#ifdef VBOX_WITH_STATISTICS
1822 PEMSTATS pStats = pVM->em.s.CTXSUFF(pStats);
1823 switch (Cpu.pCurInstr->opcode)
1824 {
1825 case OP_INVLPG:
1826 STAM_COUNTER_INC(&pStats->StatInvlpg);
1827 break;
1828 case OP_IRET:
1829 STAM_COUNTER_INC(&pStats->StatIret);
1830 break;
1831 case OP_CLI:
1832 STAM_COUNTER_INC(&pStats->StatCli);
1833 emR3RecordCli(pVM, pCtx->eip);
1834 break;
1835 case OP_STI:
1836 STAM_COUNTER_INC(&pStats->StatSti);
1837 break;
1838 case OP_INSB:
1839 case OP_INSWD:
1840 case OP_IN:
1841 case OP_OUTSB:
1842 case OP_OUTSWD:
1843 case OP_OUT:
1844 AssertMsgFailed(("Unexpected privileged exception due to port IO\n"));
1845 break;
1846
1847 case OP_MOV_CR:
1848 if (Cpu.param1.flags & USE_REG_GEN32)
1849 {
1850 //read
1851 Assert(Cpu.param2.flags & USE_REG_CR);
1852 Assert(Cpu.param2.base.reg_ctrl <= USE_REG_CR4);
1853 STAM_COUNTER_INC(&pStats->StatMovReadCR[Cpu.param2.base.reg_ctrl]);
1854 }
1855 else
1856 {
1857 //write
1858 Assert(Cpu.param1.flags & USE_REG_CR);
1859 Assert(Cpu.param1.base.reg_ctrl <= USE_REG_CR4);
1860 STAM_COUNTER_INC(&pStats->StatMovWriteCR[Cpu.param1.base.reg_ctrl]);
1861 }
1862 break;
1863
1864 case OP_MOV_DR:
1865 STAM_COUNTER_INC(&pStats->StatMovDRx);
1866 break;
1867 case OP_LLDT:
1868 STAM_COUNTER_INC(&pStats->StatMovLldt);
1869 break;
1870 case OP_LIDT:
1871 STAM_COUNTER_INC(&pStats->StatMovLidt);
1872 break;
1873 case OP_LGDT:
1874 STAM_COUNTER_INC(&pStats->StatMovLgdt);
1875 break;
1876 case OP_SYSENTER:
1877 STAM_COUNTER_INC(&pStats->StatSysEnter);
1878 break;
1879 case OP_SYSEXIT:
1880 STAM_COUNTER_INC(&pStats->StatSysExit);
1881 break;
1882 case OP_SYSCALL:
1883 STAM_COUNTER_INC(&pStats->StatSysCall);
1884 break;
1885 case OP_SYSRET:
1886 STAM_COUNTER_INC(&pStats->StatSysRet);
1887 break;
1888 case OP_HLT:
1889 STAM_COUNTER_INC(&pStats->StatHlt);
1890 break;
1891 default:
1892 STAM_COUNTER_INC(&pStats->StatMisc);
1893 Log4(("emR3RawPrivileged: opcode=%d\n", Cpu.pCurInstr->opcode));
1894 break;
1895 }
1896#endif
1897 if ( (pCtx->ss & X86_SEL_RPL) == 0
1898 && SELMIsSelector32Bit(pVM, pCtx->cs, &pCtx->csHid))
1899 {
1900 uint32_t size;
1901
1902 STAM_PROFILE_START(&pVM->em.s.StatPrivEmu, a);
1903 switch (Cpu.pCurInstr->opcode)
1904 {
1905 case OP_CLI:
1906 pCtx->eflags.u32 &= ~X86_EFL_IF;
1907 Assert(Cpu.opsize == 1);
1908 pCtx->eip += Cpu.opsize;
1909 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
1910 return VINF_EM_RESCHEDULE_REM; /* must go to the recompiler now! */
1911
1912 case OP_STI:
1913 pCtx->eflags.u32 |= X86_EFL_IF;
1914 EMSetInhibitInterruptsPC(pVM, pCtx->eip + Cpu.opsize);
1915 Assert(Cpu.opsize == 1);
1916 pCtx->eip += Cpu.opsize;
1917 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
1918 return VINF_SUCCESS;
1919
1920 case OP_HLT:
1921 if (PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip))
1922 {
1923 PATMTRANSSTATE enmState;
1924 RTGCPTR pOrgInstrGC = PATMR3PatchToGCPtr(pVM, pCtx->eip, &enmState);
1925
1926 if (enmState == PATMTRANS_OVERWRITTEN)
1927 {
1928 rc = PATMR3DetectConflict(pVM, pOrgInstrGC, pOrgInstrGC);
1929 Assert(rc == VERR_PATCH_DISABLED);
1930 /* Conflict detected, patch disabled */
1931 Log(("emR3RawPrivileged: detected conflict -> disabled patch at %VGv\n", pCtx->eip));
1932
1933 enmState = PATMTRANS_SAFE;
1934 }
1935
1936 /* The translation had better be successful. Otherwise we can't recover. */
1937 AssertReleaseMsg(pOrgInstrGC && enmState != PATMTRANS_OVERWRITTEN, ("Unable to translate instruction address at %VGv\n", pCtx->eip));
1938 if (enmState != PATMTRANS_OVERWRITTEN)
1939 pCtx->eip = pOrgInstrGC;
1940 }
1941 /* no break; we could just return VINF_EM_HALT here */
1942
1943 case OP_MOV_CR:
1944 case OP_MOV_DR:
1945 rc = EMInterpretInstructionCPU(pVM, &Cpu, CPUMCTX2CORE(pCtx), 0, &size);
1946 if (VBOX_SUCCESS(rc))
1947 {
1948 pCtx->eip += Cpu.opsize;
1949 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
1950
1951 if ( Cpu.pCurInstr->opcode == OP_MOV_CR
1952 && Cpu.param1.flags == USE_REG_CR /* write */
1953 )
1954 {
1955 /* Reschedule is necessary as the execution/paging mode might have changed. */
1956 return VINF_EM_RESCHEDULE;
1957 }
1958 return rc; /* can return VINF_EM_HALT as well. */
1959 }
1960 AssertMsgReturn(rc == VERR_EM_INTERPRETER, ("%Vrc\n", rc), rc);
1961 break; /* fall back to the recompiler */
1962 }
1963 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
1964 }
1965 }
1966
1967 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
1968 return emR3PatchTrap(pVM, pCtx, VINF_PATM_PATCH_TRAP_GP);
1969
1970 return emR3RawExecuteInstruction(pVM, "PRIV");
1971}
1972
1973
1974/**
1975 * Update the forced rawmode execution modifier.
1976 *
1977 * This function is called when we're returning from the raw-mode loop(s). If we're
1978 * in patch code, it will set a flag forcing execution to be resumed in raw-mode,
1979 * if not in patch code, the flag will be cleared.
1980 *
1981 * We should never interrupt patch code while it's being executed. Cli patches can
1982 * contain big code blocks, but they are always executed with IF=0. Other patches
1983 * replace single instructions and should be atomic.
1984 *
1985 * @returns Updated rc.
1986 *
1987 * @param pVM The VM handle.
1988 * @param pCtx The guest CPU context.
1989 * @param rc The result code.
1990 */
1991DECLINLINE(int) emR3RawUpdateForceFlag(PVM pVM, PCPUMCTX pCtx, int rc)
1992{
1993 if (PATMIsPatchGCAddr(pVM, pCtx->eip)) /** @todo check cs selector base/type */
1994 {
1995 /* ignore reschedule attempts. */
1996 switch (rc)
1997 {
1998 case VINF_EM_RESCHEDULE:
1999 case VINF_EM_RESCHEDULE_REM:
2000 rc = VINF_SUCCESS;
2001 break;
2002 }
2003 pVM->em.s.fForceRAW = true;
2004 }
2005 else
2006 pVM->em.s.fForceRAW = false;
2007 return rc;
2008}
2009
2010
2011/**
2012 * Process a subset of the raw-mode return code.
2013 *
2014 * Since we have to share this with raw-mode single stepping, this inline
2015 * function has been created to avoid code duplication.
2016 *
2017 * @returns VINF_SUCCESS if it's ok to continue raw mode.
2018 * @returns VBox status code to return to the EM main loop.
2019 *
2020 * @param pVM The VM handle
2021 * @param rc The return code.
2022 * @param pCtx The guest cpu context.
2023 */
2024DECLINLINE(int) emR3RawHandleRC(PVM pVM, PCPUMCTX pCtx, int rc)
2025{
2026 switch (rc)
2027 {
2028 /*
2029 * Common & simple ones.
2030 */
2031 case VINF_SUCCESS:
2032 break;
2033 case VINF_EM_RESCHEDULE_RAW:
2034 case VINF_EM_RESCHEDULE_HWACC:
2035 case VINF_EM_RAW_INTERRUPT:
2036 case VINF_EM_RAW_TO_R3:
2037 case VINF_EM_RAW_TIMER_PENDING:
2038 case VINF_EM_PENDING_REQUEST:
2039 rc = VINF_SUCCESS;
2040 break;
2041
2042 /*
2043 * Privileged instruction.
2044 */
2045 case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
2046 case VINF_PATM_PATCH_TRAP_GP:
2047 rc = emR3RawPrivileged(pVM);
2048 break;
2049
2050 /*
2051 * Got a trap which needs dispatching.
2052 */
2053 case VINF_EM_RAW_GUEST_TRAP:
2054 if (PATMR3IsInsidePatchJump(pVM, pCtx->eip, NULL))
2055 {
2056 AssertReleaseMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08X\n", CPUMGetGuestEIP(pVM)));
2057 rc = VERR_EM_RAW_PATCH_CONFLICT;
2058 break;
2059 }
2060 uint8_t u8Interrupt;
2061
2062 Assert(TRPMHasTrap(pVM));
2063 Assert(!PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2064
2065 if (TRPMHasTrap(pVM))
2066 {
2067 u8Interrupt = TRPMGetTrapNo(pVM);
2068
2069 /* If the guest gate is marked unpatched, then we will check again if we can patch it. */
2070 if (TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) == TRPM_INVALID_HANDLER)
2071 {
2072 CSAMR3CheckGates(pVM, u8Interrupt, 1);
2073 Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8Interrupt, TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) != TRPM_INVALID_HANDLER));
2074 /** @note If it was successful, then we could go back to raw mode, but let's keep things simple for now. */
2075 }
2076 }
2077 rc = emR3RawGuestTrap(pVM);
2078 break;
2079
2080 /*
2081 * Trap in patch code.
2082 */
2083 case VINF_PATM_PATCH_TRAP_PF:
2084 case VINF_PATM_PATCH_INT3:
2085 rc = emR3PatchTrap(pVM, pCtx, rc);
2086 break;
2087
2088 case VINF_PATM_DUPLICATE_FUNCTION:
2089 Assert(PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2090 rc = PATMR3DuplicateFunctionRequest(pVM, pCtx);
2091 AssertRC(rc);
2092 rc = VINF_SUCCESS;
2093 break;
2094
2095 case VINF_PATM_CHECK_PATCH_PAGE:
2096 rc = PATMR3HandleMonitoredPage(pVM);
2097 AssertRC(rc);
2098 rc = VINF_SUCCESS;
2099 break;
2100
2101 /*
2102 * Patch manager.
2103 */
2104 case VERR_EM_RAW_PATCH_CONFLICT:
2105 AssertReleaseMsgFailed(("%Vrc handling is not yet implemented\n", rc));
2106 break;
2107
2108 /*
2109 * Memory mapped I/O access - attempt to patch the instruction
2110 */
2111 case VINF_PATM_HC_MMIO_PATCH_READ:
2112 rc = PATMR3InstallPatch(pVM, pCtx->eip, PATMFL_MMIO_ACCESS | (SELMIsSelector32Bit(pVM, pCtx->cs, &pCtx->csHid) ? PATMFL_CODE32 : 0));
2113 if (VBOX_FAILURE(rc))
2114 rc = emR3RawExecuteInstruction(pVM, "MMIO");
2115 break;
2116
2117 case VINF_PATM_HC_MMIO_PATCH_WRITE:
2118 AssertFailed(); /* not yet implemented. */
2119 rc = emR3RawExecuteInstruction(pVM, "MMIO");
2120 break;
2121
2122 /*
2123 * Conflict or out of page tables.
2124 *
2125 * VM_FF_PGM_SYNC_CR3 is set by the hypervisor and all we need to
2126 * do here is to execute the pending forced actions.
2127 */
2128 case VINF_PGM_SYNC_CR3:
2129 AssertMsg(VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL),
2130 ("VINF_PGM_SYNC_CR3 and no VM_FF_PGM_SYNC_CR3*!\n"));
2131 rc = VINF_SUCCESS;
2132 break;
2133
2134 /*
2135 * Paging mode change.
2136 */
2137 case VINF_PGM_CHANGE_MODE:
2138 rc = PGMChangeMode(pVM, pCtx->cr0, pCtx->cr4, 0);
2139 if (VBOX_SUCCESS(rc))
2140 rc = VINF_EM_RESCHEDULE;
2141 break;
2142
2143 /*
2144 * CSAM wants to perform a task in ring-3. It has set an FF action flag.
2145 */
2146 case VINF_CSAM_PENDING_ACTION:
2147 rc = VINF_SUCCESS;
2148 break;
2149
2150 /*
2151 * Invoked Interrupt gate - must directly (!) go to the recompiler.
2152 */
2153 case VINF_EM_RAW_INTERRUPT_PENDING:
2154 case VINF_EM_RAW_RING_SWITCH_INT:
2155 {
2156 uint8_t u8Interrupt;
2157
2158 Assert(TRPMHasTrap(pVM));
2159 Assert(!PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2160
2161 if (TRPMHasTrap(pVM))
2162 {
2163 u8Interrupt = TRPMGetTrapNo(pVM);
2164
2165 /* If the guest gate is marked unpatched, then we will check again if we can patch it. */
2166 if (TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) == TRPM_INVALID_HANDLER)
2167 {
2168 CSAMR3CheckGates(pVM, u8Interrupt, 1);
2169 Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8Interrupt, TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) != TRPM_INVALID_HANDLER));
2170 /** @note If it was successful, then we could go back to raw mode, but let's keep things simple for now. */
2171 }
2172 }
2173 rc = VINF_EM_RESCHEDULE_REM;
2174 break;
2175 }
2176
2177 /*
2178 * Other ring switch types.
2179 */
2180 case VINF_EM_RAW_RING_SWITCH:
2181 rc = emR3RawRingSwitch(pVM);
2182 break;
2183
2184 /*
2185 * REMGCNotifyInvalidatePage() failed because of overflow.
2186 */
2187 case VERR_REM_FLUSHED_PAGES_OVERFLOW:
2188 Assert((pCtx->ss & X86_SEL_RPL) != 1);
2189 REMR3ReplayInvalidatedPages(pVM);
2190 break;
2191
2192 /*
2193 * I/O Port access - emulate the instruction.
2194 */
2195 case VINF_IOM_HC_IOPORT_READ:
2196 case VINF_IOM_HC_IOPORT_WRITE:
2197 case VINF_IOM_HC_IOPORT_READWRITE:
2198 rc = emR3RawExecuteIOInstruction(pVM);
2199 break;
2200
2201 /*
2202 * Memory mapped I/O access - emulate the instruction.
2203 */
2204 case VINF_IOM_HC_MMIO_READ:
2205 case VINF_IOM_HC_MMIO_WRITE:
2206 case VINF_IOM_HC_MMIO_READ_WRITE:
2207 rc = emR3RawExecuteInstruction(pVM, "MMIO");
2208 break;
2209
2210 /*
2211 * Execute instruction.
2212 */
2213 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
2214 rc = emR3RawExecuteInstruction(pVM, "LDT FAULT: ");
2215 break;
2216 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
2217 rc = emR3RawExecuteInstruction(pVM, "GDT FAULT: ");
2218 break;
2219 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
2220 rc = emR3RawExecuteInstruction(pVM, "IDT FAULT: ");
2221 break;
2222 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
2223 rc = emR3RawExecuteInstruction(pVM, "TSS FAULT: ");
2224 break;
2225 case VINF_EM_RAW_EMULATE_INSTR_PD_FAULT:
2226 rc = emR3RawExecuteInstruction(pVM, "PD FAULT: ");
2227 break;
2228
2229 case VINF_EM_RAW_EMULATE_INSTR_HLT:
2230 /** @todo skip instruction and go directly to the halt state. (see REM for implementation details) */
2231 rc = emR3RawPrivileged(pVM);
2232 break;
2233
2234 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
2235 rc = emR3RawExecuteInstruction(pVM, "EMUL: ", VINF_PATM_PENDING_IRQ_AFTER_IRET);
2236 break;
2237
2238 case VINF_EM_RAW_EMULATE_INSTR:
2239 case VINF_PATCH_EMULATE_INSTR:
2240 rc = emR3RawExecuteInstruction(pVM, "EMUL: ");
2241 break;
2242
2243 /*
2244 * Stale selector and iret traps => REM.
2245 */
2246 case VINF_EM_RAW_STALE_SELECTOR:
2247 case VINF_EM_RAW_IRET_TRAP:
2248 /* We will not go to the recompiler if EIP points to patch code. */
2249 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2250 {
2251 pCtx->eip = PATMR3PatchToGCPtr(pVM, (RTGCPTR)pCtx->eip, 0);
2252 }
2253 LogFlow(("emR3RawHandleRC: %Vrc -> %Vrc\n", rc, VINF_EM_RESCHEDULE_REM));
2254 rc = VINF_EM_RESCHEDULE_REM;
2255 break;
2256
2257 /*
2258 * Up a level.
2259 */
2260 case VINF_EM_TERMINATE:
2261 case VINF_EM_OFF:
2262 case VINF_EM_RESET:
2263 case VINF_EM_SUSPEND:
2264 case VINF_EM_HALT:
2265 case VINF_EM_RESUME:
2266 case VINF_EM_RESCHEDULE:
2267 case VINF_EM_RESCHEDULE_REM:
2268 break;
2269
2270 /*
2271 * Up a level and invoke the debugger.
2272 */
2273 case VINF_EM_DBG_STEPPED:
2274 case VINF_EM_DBG_BREAKPOINT:
2275 case VINF_EM_DBG_STEP:
2276 case VINF_EM_DBG_HYPER_ASSERTION:
2277 case VINF_EM_DBG_HYPER_BREAKPOINT:
2278 case VINF_EM_DBG_HYPER_STEPPED:
2279 case VINF_EM_DBG_STOP:
2280 break;
2281
2282 /*
2283 * Up a level, dump and debug.
2284 */
2285 case VERR_TRPM_DONT_PANIC:
2286 case VERR_TRPM_PANIC:
2287 break;
2288
2289 /*
2290 * Anything which is not known to us means an internal error
2291 * and the termination of the VM!
2292 */
2293 default:
2294 AssertMsgFailed(("Unknown GC return code: %Vra\n", rc));
2295 break;
2296 }
2297 return rc;
2298}
2299
2300
2301/**
2302 * Process raw-mode specific forced actions.
2303 *
2304 * This function is called when any FFs in the VM_FF_HIGH_PRIORITY_PRE_RAW_MASK is pending.
2305 *
2306 * @returns VBox status code.
2307 * Only the normal success/failure stuff, no VINF_EM_*.
2308 * @param pVM The VM handle.
2309 * @param pCtx The guest CPUM register context.
2310 */
2311static int emR3RawForcedActions(PVM pVM, PCPUMCTX pCtx)
2312{
2313 /*
2314 * Note that the order is *vitally* important!
2315 * Also note that SELMR3UpdateFromCPUM may trigger VM_FF_SELM_SYNC_TSS.
2316 */
2317
2318
2319 /*
2320 * Sync selector tables.
2321 */
2322 if (VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT))
2323 {
2324 int rc = SELMR3UpdateFromCPUM(pVM);
2325 if (VBOX_FAILURE(rc))
2326 return rc;
2327 }
2328
2329 /*
2330 * Sync IDT.
2331 */
2332 if (VM_FF_ISSET(pVM, VM_FF_TRPM_SYNC_IDT))
2333 {
2334 int rc = TRPMR3SyncIDT(pVM);
2335 if (VBOX_FAILURE(rc))
2336 return rc;
2337 }
2338
2339 /*
2340 * Sync TSS.
2341 */
2342 if (VM_FF_ISSET(pVM, VM_FF_SELM_SYNC_TSS))
2343 {
2344 int rc = SELMR3SyncTSS(pVM);
2345 if (VBOX_FAILURE(rc))
2346 return rc;
2347 }
2348
2349 /*
2350 * Sync page directory.
2351 */
2352 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL))
2353 {
2354 int rc = PGMSyncCR3(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4, VM_FF_ISSET(pVM, VM_FF_PGM_SYNC_CR3));
2355 if (VBOX_FAILURE(rc))
2356 return rc;
2357
2358 Assert(!VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT));
2359
2360 /* Prefetch pages for EIP and ESP */
2361 /** @todo This is rather expensive. Should investigate if it really helps at all. */
2362 rc = PGMPrefetchPage(pVM, SELMToFlat(pVM, pCtx->cs, &pCtx->csHid, pCtx->eip));
2363 if (rc == VINF_SUCCESS)
2364 rc = PGMPrefetchPage(pVM, SELMToFlat(pVM, pCtx->ss, &pCtx->ssHid, pCtx->esp));
2365 if (rc != VINF_SUCCESS)
2366 {
2367 if (rc != VINF_PGM_SYNC_CR3)
2368 return rc;
2369 rc = PGMSyncCR3(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4, VM_FF_ISSET(pVM, VM_FF_PGM_SYNC_CR3));
2370 if (VBOX_FAILURE(rc))
2371 return rc;
2372 }
2373 /** @todo maybe prefetch the supervisor stack page as well */
2374 }
2375
2376 return VINF_SUCCESS;
2377}
2378
2379
2380/**
2381 * Executes raw code.
2382 *
2383 * This function contains the raw-mode version of the inner
2384 * execution loop (the outer loop being in EMR3ExecuteVM()).
2385 *
2386 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE,
2387 * VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
2388 *
2389 * @param pVM VM handle.
2390 * @param pfFFDone Where to store an indicator telling whether or not
2391 * FFs were done before returning.
2392 */
2393static int emR3RawExecute(PVM pVM, bool *pfFFDone)
2394{
2395 STAM_PROFILE_ADV_START(&pVM->em.s.StatRAWTotal, a);
2396
2397 int rc = VERR_INTERNAL_ERROR;
2398 PCPUMCTX pCtx = pVM->em.s.pCtx;
2399 LogFlow(("emR3RawExecute: (cs:eip=%04x:%08x)\n", pCtx->cs, pCtx->eip));
2400 pVM->em.s.fForceRAW = false;
2401 *pfFFDone = false;
2402
2403
2404 /*
2405 *
2406 * Spin till we get a forced action or raw mode status code resulting in
2407 * in anything but VINF_SUCCESS or VINF_EM_RESCHEDULE_RAW.
2408 *
2409 */
2410 for (;;)
2411 {
2412 STAM_PROFILE_ADV_START(&pVM->em.s.StatRAWEntry, b);
2413
2414 /*
2415 * Check various preconditions.
2416 */
2417#ifdef VBOX_STRICT
2418 Assert(REMR3QueryPendingInterrupt(pVM) == REM_NO_PENDING_IRQ);
2419 Assert(!(pCtx->cr4 & X86_CR4_PAE));
2420 Assert((pCtx->ss & X86_SEL_RPL) == 3 || (pCtx->ss & X86_SEL_RPL) == 0);
2421 AssertMsg( (pCtx->eflags.u32 & X86_EFL_IF)
2422 || PATMShouldUseRawMode(pVM, (RTGCPTR)pCtx->eip),
2423 ("Tried to execute code with IF at EIP=%08x!\n", pCtx->eip));
2424 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL)
2425 && PGMR3MapHasConflicts(pVM, pCtx->cr3, pVM->fRawR0Enabled))
2426 {
2427 AssertMsgFailed(("We should not get conflicts any longer!!!\n"));
2428 return VERR_INTERNAL_ERROR;
2429 }
2430#endif /* VBOX_STRICT */
2431
2432 /*
2433 * Process high priority pre-execution raw-mode FFs.
2434 */
2435 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2436 {
2437 rc = emR3RawForcedActions(pVM, pCtx);
2438 if (VBOX_FAILURE(rc))
2439 break;
2440 }
2441
2442 /*
2443 * If we're going to execute ring-0 code, the guest state needs to
2444 * be modified a bit and some of the state components (IF, SS/CS RPL,
2445 * and perhaps EIP) needs to be stored with PATM.
2446 */
2447 rc = CPUMRawEnter(pVM, NULL);
2448 if (rc != VINF_SUCCESS)
2449 {
2450 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWEntry, b);
2451 break;
2452 }
2453
2454 /*
2455 * Scan code before executing it. Don't bother with user mode or V86 code
2456 */
2457 if ( (pCtx->ss & X86_SEL_RPL) <= 1
2458 && pCtx->eflags.Bits.u1VM == 0
2459 && !PATMIsPatchGCAddr(pVM, pCtx->eip))
2460 {
2461 STAM_PROFILE_ADV_SUSPEND(&pVM->em.s.StatRAWEntry, b);
2462 CSAMR3CheckEIP(pVM, pCtx->eip, SELMIsSelector32Bit(pVM, pCtx->cs, &pCtx->csHid));
2463 STAM_PROFILE_ADV_RESUME(&pVM->em.s.StatRAWEntry, b);
2464 }
2465
2466#ifdef LOG_ENABLED
2467 /*
2468 * Log important stuff before entering GC.
2469 */
2470 bool fSingleStep = false;
2471 PPATMGCSTATE pGCState = PATMR3QueryGCStateHC(pVM);
2472 if ((pCtx->ss & X86_SEL_RPL) == 1 && !fSingleStep)
2473 {
2474 bool fCSAMScanned = CSAMIsPageScanned(pVM, (RTGCPTR)pCtx->eip);
2475 Log(("RR0: %08X ESP=%08X IF=%d VMFlags=%x PIF=%d CPL=%d (Scanned=%d)\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags, pGCState->fPIF, (pCtx->ss & X86_SEL_RPL), fCSAMScanned));
2476 }
2477 else if ((pCtx->ss & X86_SEL_RPL) == 3 && !fSingleStep && pCtx->eflags.Bits.u1VM)
2478 Log(("RV86: %08X IF=%d VMFlags=%x\n", pCtx->eip, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags));
2479 else if ((pCtx->ss & X86_SEL_RPL) == 3 && !fSingleStep)
2480 Log(("RR3: %08X ESP=%08X IF=%d VMFlags=%x\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags));
2481#endif /* LOG_ENABLED */
2482
2483
2484
2485 /*
2486 * Execute the code.
2487 */
2488 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWEntry, b);
2489 STAM_PROFILE_START(&pVM->em.s.StatRAWExec, c);
2490 VMMR3Unlock(pVM);
2491 rc = VMMR3RawRunGC(pVM);
2492 VMMR3Lock(pVM);
2493 STAM_PROFILE_STOP(&pVM->em.s.StatRAWExec, c);
2494 STAM_PROFILE_ADV_START(&pVM->em.s.StatRAWTail, d);
2495
2496 LogFlow(("RR0-E: %08X ESP=%08X IF=%d VMFlags=%x PIF=%d CPL=%d\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags, pGCState->fPIF, (pCtx->ss & X86_SEL_RPL)));
2497 LogFlow(("VMMR3RawRunGC returned %Vrc\n", rc));
2498
2499
2500 /*
2501 * Restore the real CPU state and deal with high priority post
2502 * execution FFs before doing anything else.
2503 */
2504 rc = CPUMRawLeave(pVM, NULL, rc);
2505 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
2506 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK))
2507 rc = emR3HighPriorityPostForcedActions(pVM, rc);
2508
2509#ifdef PGM_CACHE_VERY_STRICT
2510 /*
2511 * Page manager cache checks.
2512 */
2513 if ( rc == VINF_EM_RAW_INTERRUPT
2514 || rc == VINF_EM_RAW_GUEST_TRAP
2515 || rc == VINF_IOM_HC_IOPORT_READ
2516 || rc == VINF_IOM_HC_IOPORT_WRITE
2517 || rc == VINF_IOM_HC_IOPORT_READWRITE
2518 //|| rc == VINF_PATM_PATCH_INT3
2519 )
2520 pgmCacheCheckPD(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4);
2521#endif
2522
2523#ifdef VBOX_STRICT
2524 /*
2525 * Assert TSS consistency & rc vs patch code.
2526 */
2527 if ( !VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_TSS | VM_FF_SELM_SYNC_GDT) /* GDT implies TSS at the moment. */
2528 && EMIsRawRing0Enabled(pVM))
2529 SELMR3CheckTSS(pVM);
2530 switch (rc)
2531 {
2532 case VINF_SUCCESS:
2533 case VINF_EM_RAW_INTERRUPT:
2534 case VINF_PATM_PATCH_TRAP_PF:
2535 case VINF_PATM_PATCH_TRAP_GP:
2536 case VINF_PATM_PATCH_INT3:
2537 case VINF_PATM_CHECK_PATCH_PAGE:
2538 case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
2539 case VINF_EM_RAW_GUEST_TRAP:
2540 case VINF_EM_RESCHEDULE_RAW:
2541 break;
2542
2543 default:
2544 if (PATMIsPatchGCAddr(pVM, pCtx->eip) && !(pCtx->eflags.u32 & X86_EFL_TF))
2545 LogIt(NULL, 0, LOG_GROUP_PATM, ("Patch code interrupted at %VGv for reason %Vrc\n", CPUMGetGuestEIP(pVM), rc));
2546 break;
2547 }
2548 /*
2549 * Let's go paranoid!
2550 */
2551 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL)
2552 && PGMR3MapHasConflicts(pVM, pCtx->cr3, pVM->fRawR0Enabled))
2553 {
2554 AssertMsgFailed(("We should not get conflicts any longer!!!\n"));
2555 return VERR_INTERNAL_ERROR;
2556 }
2557#endif /* VBOX_STRICT */
2558
2559 /*
2560 * Process the returned status code.
2561 */
2562 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
2563 {
2564 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTail, d);
2565 break;
2566 }
2567 rc = emR3RawHandleRC(pVM, pCtx, rc);
2568 if (rc != VINF_SUCCESS)
2569 {
2570 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
2571 if (rc != VINF_SUCCESS)
2572 {
2573 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTail, d);
2574 break;
2575 }
2576 }
2577
2578 /*
2579 * Check and execute forced actions.
2580 */
2581#ifdef VBOX_HIGH_RES_TIMERS_HACK
2582 TMTimerPoll(pVM);
2583#endif
2584 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTail, d);
2585 if (VM_FF_ISPENDING(pVM, ~VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2586 {
2587 Assert((pCtx->ss & X86_SEL_RPL) != 1);
2588
2589 STAM_PROFILE_ADV_SUSPEND(&pVM->em.s.StatRAWTotal, a);
2590 rc = emR3ForcedActions(pVM, rc);
2591 STAM_PROFILE_ADV_RESUME(&pVM->em.s.StatRAWTotal, a);
2592 if ( rc != VINF_SUCCESS
2593 && rc != VINF_EM_RESCHEDULE_RAW)
2594 {
2595 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
2596 if (rc != VINF_SUCCESS)
2597 {
2598 *pfFFDone = true;
2599 break;
2600 }
2601 }
2602 }
2603 }
2604
2605 /*
2606 * Return to outer loop.
2607 */
2608#if defined(LOG_ENABLED) && defined(DEBUG)
2609 RTLogFlush(NULL);
2610#endif
2611 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTotal, a);
2612 return rc;
2613}
2614
2615
2616/**
2617 * Executes hardware accelerated raw code. (Intel VMX & AMD SVM)
2618 *
2619 * This function contains the raw-mode version of the inner
2620 * execution loop (the outer loop being in EMR3ExecuteVM()).
2621 *
2622 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE, VINF_EM_RESCHEDULE_RAW,
2623 * VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
2624 *
2625 * @param pVM VM handle.
2626 * @param pfFFDone Where to store an indicator telling whether or not
2627 * FFs were done before returning.
2628 */
2629static int emR3HwAccExecute(PVM pVM, bool *pfFFDone)
2630{
2631 int rc = VERR_INTERNAL_ERROR;
2632 PCPUMCTX pCtx = pVM->em.s.pCtx;
2633
2634 LogFlow(("emR3HwAccExecute: (cs:eip=%04x:%08x)\n", pCtx->cs, pCtx->eip));
2635 *pfFFDone = false;
2636
2637 STAM_COUNTER_INC(&pVM->em.s.StatHwAccExecuteEntry);
2638
2639 /*
2640 * Spin till we get a forced action which returns anything but VINF_SUCCESS.
2641 */
2642 for (;;)
2643 {
2644 STAM_PROFILE_ADV_START(&pVM->em.s.StatHwAccEntry, a);
2645
2646 /*
2647 * Check various preconditions.
2648 */
2649 Assert(!(pCtx->cr4 & X86_CR4_PAE));
2650
2651 VM_FF_CLEAR(pVM, (VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT | VM_FF_TRPM_SYNC_IDT | VM_FF_SELM_SYNC_TSS));
2652
2653 /*
2654 * Sync page directory.
2655 */
2656 if (VM_FF_ISPENDING(pVM, (VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL)))
2657 {
2658 rc = PGMSyncCR3(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4, VM_FF_ISSET(pVM, VM_FF_PGM_SYNC_CR3));
2659 if (VBOX_FAILURE(rc))
2660 return rc;
2661
2662 Assert(!VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT));
2663
2664 /* Prefetch pages for EIP and ESP */
2665 rc = PGMPrefetchPage(pVM, SELMToFlat(pVM, pCtx->cs, &pCtx->csHid, pCtx->eip));
2666 if (rc == VINF_SUCCESS)
2667 rc = PGMPrefetchPage(pVM, SELMToFlat(pVM, pCtx->ss, &pCtx->ssHid, pCtx->esp));
2668 if (rc != VINF_SUCCESS)
2669 {
2670 if (rc != VINF_PGM_SYNC_CR3)
2671 return rc;
2672 rc = PGMSyncCR3(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4, VM_FF_ISSET(pVM, VM_FF_PGM_SYNC_CR3));
2673 if (VBOX_FAILURE(rc))
2674 return rc;
2675 }
2676
2677 /** @todo maybe prefetch the supervisor stack page as well */
2678 }
2679
2680#ifdef LOG_ENABLED
2681 uint8_t u8Vector;
2682
2683 rc = TRPMQueryTrapAll(pVM, &u8Vector, 0, 0, 0);
2684 if (rc == VINF_SUCCESS)
2685 {
2686 Log(("Pending hardware interrupt %d\n", u8Vector));
2687 }
2688 /*
2689 * Log important stuff before entering GC.
2690 */
2691 bool fSingleStep = false;
2692 if ((pCtx->ss & X86_SEL_RPL) == 0 && !fSingleStep)
2693 Log(("HWR0: %08X ESP=%08X IF=%d CPL=%d\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, (pCtx->ss & X86_SEL_RPL)));
2694 else if ((pCtx->ss & X86_SEL_RPL) == 3 && !fSingleStep && pCtx->eflags.Bits.u1VM)
2695 Log(("HWV86: %08X IF=%d\n", pCtx->eip, pCtx->eflags.Bits.u1IF));
2696 else if ((pCtx->ss & X86_SEL_RPL) == 3 && !fSingleStep)
2697 Log(("HWR3: %08X ESP=%08X IF=%d\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF));
2698#endif
2699
2700
2701 /*
2702 * Execute the code.
2703 */
2704 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatHwAccEntry, a);
2705 STAM_PROFILE_START(&pVM->em.s.StatHwAccExec, x);
2706 VMMR3Unlock(pVM);
2707 rc = VMMR3HwAccRunGC(pVM);
2708 VMMR3Lock(pVM);
2709 STAM_PROFILE_STOP(&pVM->em.s.StatHwAccExec, x);
2710
2711
2712 /*
2713 * Deal with high priority post execution FFs before doing anything else.
2714 */
2715 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
2716 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK))
2717 rc = emR3HighPriorityPostForcedActions(pVM, rc);
2718
2719 /*
2720 * Process the returned status code.
2721 */
2722 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
2723 break;
2724
2725 rc = emR3RawHandleRC(pVM, pCtx, rc);
2726 if (rc != VINF_SUCCESS)
2727 break;
2728
2729 /*
2730 * Check and execute forced actions.
2731 */
2732#ifdef VBOX_HIGH_RES_TIMERS_HACK
2733 TMTimerPoll(pVM);
2734#endif
2735 if (VM_FF_ISPENDING(pVM, VM_FF_ALL_MASK))
2736 {
2737 rc = emR3ForcedActions(pVM, rc);
2738 if ( rc != VINF_SUCCESS
2739 && rc != VINF_EM_RESCHEDULE_HWACC)
2740 {
2741 *pfFFDone = true;
2742 break;
2743 }
2744 }
2745 }
2746 /*
2747 * Return to outer loop.
2748 */
2749#if defined(LOG_ENABLED) && defined(DEBUG)
2750 RTLogFlush(NULL);
2751#endif
2752 return rc;
2753}
2754
2755
2756/**
2757 * Decides whether to execute RAW, HWACC or REM.
2758 *
2759 * @returns new EM state
2760 * @param pVM The VM.
2761 * @param pCtx The CPU context.
2762 */
2763inline EMSTATE emR3Reschedule(PVM pVM, PCPUMCTX pCtx)
2764{
2765 /*
2766 * When forcing raw-mode execution, things are simple.
2767 */
2768 if (pVM->em.s.fForceRAW)
2769 return EMSTATE_RAW;
2770
2771 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
2772 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
2773 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
2774
2775 X86EFLAGS EFlags = pCtx->eflags;
2776 if (HWACCMIsEnabled(pVM))
2777 {
2778 /* Hardware accelerated raw-mode:
2779 *
2780 * Typically only 32-bits protected mode, with paging enabled, code is allowed here.
2781 */
2782 if (HWACCMR3CanExecuteGuest(pVM, pCtx) == true)
2783 return EMSTATE_HWACC;
2784
2785 /** @note Raw mode and hw accelerated mode are incompatible. The latter turns off monitoring features essential for raw mode! */
2786 return EMSTATE_REM;
2787 }
2788
2789 /* Standard raw-mode:
2790 *
2791 * Here we only support 16 & 32 bits protected mode ring 3 code that has no IO privileges
2792 * or 32 bits protected mode ring 0 code
2793 *
2794 * The tests are ordered by the likelyhood of being true during normal execution.
2795 */
2796 if (EFlags.u32 & (X86_EFL_TF /* | HF_INHIBIT_IRQ_MASK*/))
2797 {
2798 Log2(("raw mode refused: EFlags=%#x\n", EFlags.u32));
2799 return EMSTATE_REM;
2800 }
2801
2802#ifndef VBOX_RAW_V86
2803 if (EFlags.u32 & X86_EFL_VM) {
2804 Log2(("raw mode refused: VM_MASK\n"));
2805 return EMSTATE_REM;
2806 }
2807#endif
2808
2809 /** @todo check up the X86_CR0_AM flag in respect to raw mode!!! We're probably not emulating it right! */
2810 uint32_t u32CR0 = pCtx->cr0;
2811 if ((u32CR0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
2812 {
2813 //Log2(("raw mode refused: %s%s%s\n", (u32CR0 & X86_CR0_PG) ? "" : " !PG", (u32CR0 & X86_CR0_PE) ? "" : " !PE", (u32CR0 & X86_CR0_AM) ? "" : " !AM"));
2814 return EMSTATE_REM;
2815 }
2816
2817 if (pCtx->cr4 & X86_CR4_PAE)
2818 {
2819 //Log2(("raw mode refused: PAE\n"));
2820 return EMSTATE_REM;
2821 }
2822
2823 unsigned uSS = pCtx->ss;
2824 if ((uSS & X86_SEL_RPL) == 3)
2825 {
2826 if (!EMIsRawRing3Enabled(pVM))
2827 return EMSTATE_REM;
2828
2829 if (!(EFlags.u32 & X86_EFL_IF))
2830 {
2831#ifdef VBOX_RAW_V86
2832 if(!(EFlags.u32 & X86_EFL_VM))
2833 return EMSTATE_REM;
2834#else
2835 Log2(("raw mode refused: IF (RawR3)\n"));
2836 return EMSTATE_REM;
2837#endif
2838 }
2839
2840 if (!(u32CR0 & X86_CR0_WP) && EMIsRawRing0Enabled(pVM))
2841 {
2842 Log2(("raw mode refused: CR0.WP + RawR0\n"));
2843 return EMSTATE_REM;
2844 }
2845 }
2846 else
2847 {
2848 if (!EMIsRawRing0Enabled(pVM))
2849 return EMSTATE_REM;
2850
2851 /* Only ring 0 supervisor code. */
2852 if ((uSS & X86_SEL_RPL) != 0)
2853 {
2854 Log2(("raw r0 mode refused: CPL %d\n", uSS & X86_SEL_RPL));
2855 return EMSTATE_REM;
2856 }
2857
2858 // Let's start with pure 32 bits ring 0 code first
2859 /** @todo What's pure 32-bit mode? flat? */
2860 if ( !(pCtx->ssHid.Attr.n.u1DefBig)
2861 || !(pCtx->csHid.Attr.n.u1DefBig))
2862 {
2863 Log2(("raw r0 mode refused: SS/CS not 32bit\n"));
2864 return EMSTATE_REM;
2865 }
2866
2867 /* Write protection muts be turned on, or else the guest can overwrite our hypervisor code and data. */
2868 if (!(u32CR0 & X86_CR0_WP))
2869 {
2870 Log2(("raw r0 mode refused: CR0.WP=0!\n"));
2871 return EMSTATE_REM;
2872 }
2873
2874 if (PATMShouldUseRawMode(pVM, (RTGCPTR)pCtx->eip))
2875 {
2876 Log2(("raw r0 mode forced: patch code\n"));
2877 return EMSTATE_RAW;
2878 }
2879
2880#if !defined(VBOX_ALLOW_IF0) && !defined(VBOX_RUN_INTERRUPT_GATE_HANDLERS)
2881 if (!(EFlags.u32 & X86_EFL_IF))
2882 {
2883 ////Log2(("R0: IF=0 VIF=%d %08X\n", eip, pVMeflags));
2884 //Log2(("RR0: Interrupts turned off; fall back to emulation\n"));
2885 return EMSTATE_REM;
2886 }
2887#endif
2888
2889 /** @todo still necessary??? */
2890 if (EFlags.Bits.u2IOPL != 0)
2891 {
2892 Log2(("raw r0 mode refused: IOPL %d\n", EFlags.Bits.u2IOPL));
2893 return EMSTATE_REM;
2894 }
2895 }
2896
2897 Assert(PGMPhysIsA20Enabled(pVM));
2898 return EMSTATE_RAW;
2899}
2900
2901
2902/**
2903 * Executes all high priority post execution force actions.
2904 *
2905 * @returns rc or a fatal status code.
2906 *
2907 * @param pVM VM handle.
2908 * @param rc The current rc.
2909 */
2910static int emR3HighPriorityPostForcedActions(PVM pVM, int rc)
2911{
2912 if (VM_FF_ISSET(pVM, VM_FF_PDM_CRITSECT))
2913 PDMR3CritSectFF(pVM);
2914
2915 if (VM_FF_ISSET(pVM, VM_FF_CSAM_FLUSH_DIRTY_PAGE))
2916 CSAMR3FlushDirtyPages(pVM);
2917
2918 return rc;
2919}
2920
2921
2922/**
2923 * Executes all pending forced actions.
2924 *
2925 * Forced actions can cause execution delays and execution
2926 * rescheduling. The first we deal with using action priority, so
2927 * that for instance pending timers aren't scheduled and ran until
2928 * right before execution. The rescheduling we deal with using
2929 * return codes. The same goes for VM termination, only in that case
2930 * we exit everything.
2931 *
2932 * @returns VBox status code of equal or greater importance/severity than rc.
2933 * The most important ones are: VINF_EM_RESCHEDULE,
2934 * VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
2935 *
2936 * @param pVM VM handle.
2937 * @param rc The current rc.
2938 *
2939 */
2940static int emR3ForcedActions(PVM pVM, int rc)
2941{
2942#ifdef VBOX_STRICT
2943 int rcIrq = VINF_SUCCESS;
2944#endif
2945 STAM_PROFILE_START(&pVM->em.s.StatForcedActions, a);
2946
2947#define UPDATE_RC() \
2948 do { \
2949 AssertMsg(rc2 <= 0 || (rc2 >= VINF_EM_FIRST && rc2 <= VINF_EM_LAST), ("Invalid FF return code: %Vra\n", rc2)); \
2950 if (rc2 == VINF_SUCCESS || rc < VINF_SUCCESS) \
2951 break; \
2952 if (!rc || rc2 < rc) \
2953 rc = rc2; \
2954 } while (0)
2955
2956 int rc2;
2957
2958 /*
2959 * Post execution chunk first.
2960 */
2961 if (VM_FF_ISPENDING(pVM, VM_FF_NORMAL_PRIORITY_POST_MASK))
2962 {
2963 /*
2964 * Termination request.
2965 */
2966 if (VM_FF_ISSET(pVM, VM_FF_TERMINATE))
2967 {
2968 Log2(("emR3ForcedActions: returns VINF_EM_TERMINATE\n"));
2969 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
2970 return VINF_EM_TERMINATE;
2971 }
2972
2973 /*
2974 * Debugger Facility polling.
2975 */
2976 if (VM_FF_ISSET(pVM, VM_FF_DBGF))
2977 {
2978 rc2 = DBGFR3VMMForcedAction(pVM);
2979 UPDATE_RC();
2980 }
2981
2982 /*
2983 * Postponed reset request.
2984 */
2985 if (VM_FF_ISSET(pVM, VM_FF_RESET))
2986 {
2987 rc2 = VMR3Reset(pVM);
2988 UPDATE_RC();
2989 VM_FF_CLEAR(pVM, VM_FF_RESET);
2990 }
2991
2992 /*
2993 * CSAM page scanning.
2994 */
2995 if (VM_FF_ISSET(pVM, VM_FF_CSAM_SCAN_PAGE))
2996 {
2997 /** @todo: check for 16 or 32 bits code! (D bit in the code selector) */
2998 Log(("Forced action VM_FF_CSAM_SCAN_PAGE\n"));
2999 CSAMR3CheckEIP(pVM, CPUMGetGuestEIP(pVM), true);
3000 VM_FF_CLEAR(pVM, VM_FF_CSAM_SCAN_PAGE);
3001 }
3002
3003 /* check that we got them all */
3004 Assert(!(VM_FF_NORMAL_PRIORITY_POST_MASK & ~(VM_FF_TERMINATE | VM_FF_DBGF | VM_FF_RESET | VM_FF_CSAM_SCAN_PAGE)));
3005 }
3006
3007 /*
3008 * Normal priority then.
3009 * (Executed in no particular order.)
3010 */
3011 if (VM_FF_ISPENDING(pVM, VM_FF_NORMAL_PRIORITY_MASK))
3012 {
3013 /*
3014 * PDM Queues are pending.
3015 */
3016 if (VM_FF_ISSET(pVM, VM_FF_PDM_QUEUES))
3017 PDMR3QueueFlushAll(pVM);
3018
3019 /*
3020 * PDM DMA transfers are pending.
3021 */
3022 if (VM_FF_ISSET(pVM, VM_FF_PDM_DMA))
3023 PDMR3DmaRun(pVM);
3024
3025 /*
3026 * Requests from other threads.
3027 */
3028 if (VM_FF_ISSET(pVM, VM_FF_REQUEST))
3029 {
3030 rc2 = VMR3ReqProcess(pVM);
3031 if (rc2 == VINF_EM_OFF || rc2 == VINF_EM_TERMINATE)
3032 {
3033 Log2(("emR3ForcedActions: returns %Vrc\n", rc2));
3034 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3035 return rc2;
3036 }
3037 UPDATE_RC();
3038 }
3039
3040 /* check that we got them all */
3041 Assert(!(VM_FF_NORMAL_PRIORITY_MASK & ~(VM_FF_REQUEST | VM_FF_PDM_QUEUES | VM_FF_PDM_DMA)));
3042 }
3043
3044 /*
3045 * Execute polling function ever so often.
3046 * THIS IS A HACK, IT WILL BE *REPLACED* BY PROPER ASYNC NETWORKING SOON!
3047 */
3048 static unsigned cLast = 0;
3049 if (!((++cLast) % 4))
3050 PDMR3Poll(pVM);
3051
3052 /*
3053 * High priority pre execution chunk last.
3054 * (Executed in ascending priority order.)
3055 */
3056 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_MASK))
3057 {
3058 /*
3059 * Timers before interrupts.
3060 */
3061 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
3062 TMR3TimerQueuesDo(pVM);
3063
3064 /*
3065 * The instruction following an emulated STI should *always* be executed!
3066 */
3067 if (VM_FF_ISSET(pVM, VM_FF_INHIBIT_INTERRUPTS))
3068 {
3069 Log(("VM_FF_EMULATED_STI at %VGv successor %VGv\n", CPUMGetGuestEIP(pVM), EMGetInhibitInterruptsPC(pVM)));
3070 if (CPUMGetGuestEIP(pVM) != EMGetInhibitInterruptsPC(pVM))
3071 {
3072 /** @note we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here if the eip is the same as the inhibited instr address.
3073 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
3074 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
3075 * break the guest. Sounds very unlikely, but such timing sensitive problem are not as rare as you might think.
3076 */
3077 VM_FF_CLEAR(pVM, VM_FF_INHIBIT_INTERRUPTS);
3078 }
3079 if (HWACCMR3IsActive(pVM))
3080 rc2 = VINF_EM_RESCHEDULE_HWACC;
3081 else
3082 rc2 = PATMAreInterruptsEnabled(pVM) ? VINF_EM_RESCHEDULE_RAW : VINF_EM_RESCHEDULE_REM;
3083
3084 UPDATE_RC();
3085 }
3086
3087 /*
3088 * Interrupts.
3089 */
3090 if ( !VM_FF_ISSET(pVM, VM_FF_INHIBIT_INTERRUPTS)
3091 && (!rc || rc >= VINF_EM_RESCHEDULE_RAW)
3092 && !TRPMHasTrap(pVM) /* an interrupt could already be scheduled for dispatching in the recompiler. */
3093 && PATMAreInterruptsEnabled(pVM)
3094 && !HWACCMR3IsEventPending(pVM))
3095 {
3096 if (VM_FF_ISPENDING(pVM, VM_FF_INTERRUPT_APIC | VM_FF_INTERRUPT_PIC))
3097 {
3098 /** @note it's important to make sure the return code from TRPMR3InjectEvent isn't ignored! */
3099 /** @todo this really isn't nice, should properly handle this */
3100 rc2 = TRPMR3InjectEvent(pVM, TRPM_HARDWARE_INT);
3101#ifdef VBOX_STRICT
3102 rcIrq = rc2;
3103#endif
3104 UPDATE_RC();
3105 }
3106 /** @todo really ugly; if we entered the hlt state when exiting the recompiler and an interrupt was pending, we previously got stuck in the halted state. */
3107 else if (REMR3QueryPendingInterrupt(pVM) != REM_NO_PENDING_IRQ)
3108 {
3109 rc2 = VINF_EM_RESCHEDULE_REM;
3110 UPDATE_RC();
3111 }
3112 }
3113
3114 /*
3115 * Debugger Facility request.
3116 */
3117 if (VM_FF_ISSET(pVM, VM_FF_DBGF))
3118 {
3119 rc2 = DBGFR3VMMForcedAction(pVM);
3120 UPDATE_RC();
3121 }
3122
3123 /*
3124 * Termination request.
3125 */
3126 if (VM_FF_ISSET(pVM, VM_FF_TERMINATE))
3127 {
3128 Log2(("emR3ForcedActions: returns VINF_EM_TERMINATE\n"));
3129 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3130 return VINF_EM_TERMINATE;
3131 }
3132
3133#ifdef DEBUG
3134 /*
3135 * Debug, pause the VM.
3136 */
3137 if (VM_FF_ISSET(pVM, VM_FF_DEBUG_SUSPEND))
3138 {
3139 VM_FF_CLEAR(pVM, VM_FF_DEBUG_SUSPEND);
3140 Log(("emR3ForcedActions: returns VINF_EM_SUSPEND\n"));
3141 return VINF_EM_SUSPEND;
3142 }
3143
3144#endif
3145 /* check that we got them all */
3146 Assert(!(VM_FF_HIGH_PRIORITY_PRE_MASK & ~(VM_FF_TIMER | VM_FF_INTERRUPT_APIC | VM_FF_INTERRUPT_PIC | VM_FF_DBGF | VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL | VM_FF_SELM_SYNC_TSS | VM_FF_TRPM_SYNC_IDT | VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT | VM_FF_TERMINATE | VM_FF_DEBUG_SUSPEND | VM_FF_INHIBIT_INTERRUPTS)));
3147 }
3148
3149#undef UPDATE_RC
3150 Log2(("emR3ForcedActions: returns %Vrc\n", rc));
3151 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3152 Assert(rcIrq == VINF_SUCCESS || rcIrq == rc);
3153 return rc;
3154}
3155
3156
3157/**
3158 * Execute VM.
3159 *
3160 * This function is the main loop of the VM. The emulation thread
3161 * calls this function when the VM has been successfully constructed
3162 * and we're ready for executing the VM.
3163 *
3164 * Returning from this function means that the VM is turned off or
3165 * suspended (state already saved) and deconstruction in next in line.
3166 *
3167 * All interaction from other thread are done using forced actions
3168 * and signaling of the wait object.
3169 *
3170 * @returns VBox status code.
3171 * @param pVM The VM to operate on.
3172 */
3173EMR3DECL(int) EMR3ExecuteVM(PVM pVM)
3174{
3175 LogFlow(("EMR3ExecuteVM: pVM=%p enmVMState=%d enmState=%d (%s) fForceRAW=%d\n", pVM, pVM->enmVMState,
3176 pVM->em.s.enmState, EMR3GetStateName(pVM->em.s.enmState), pVM->em.s.fForceRAW));
3177 VM_ASSERT_EMT(pVM);
3178 Assert(pVM->em.s.enmState == EMSTATE_NONE || pVM->em.s.enmState == EMSTATE_SUSPENDED);
3179
3180 VMMR3Lock(pVM);
3181
3182 int rc = setjmp(pVM->em.s.u.FatalLongJump);
3183 if (rc == 0)
3184 {
3185 /*
3186 * Start the virtual time.
3187 */
3188 rc = TMVirtualResume(pVM);
3189 Assert(rc == VINF_SUCCESS);
3190
3191 /*
3192 * The Outer Main Loop.
3193 */
3194 bool fFFDone = false;
3195 rc = VINF_EM_RESCHEDULE;
3196 pVM->em.s.enmState = EMSTATE_REM;
3197 STAM_PROFILE_ADV_START(&pVM->em.s.StatTotal, x);
3198 for (;;)
3199 {
3200 /*
3201 * Before we can schedule anything (we're here because
3202 * scheduling is required) we must service any pending
3203 * forced actions to avoid any pending action causing
3204 * immidate rescheduling upon entering an inner loop
3205 *
3206 * Do forced actions.
3207 */
3208 if ( !fFFDone
3209 && rc != VINF_EM_TERMINATE
3210 && rc != VINF_EM_OFF
3211 && VM_FF_ISPENDING(pVM, VM_FF_ALL_BUT_RAW_MASK))
3212 {
3213 rc = emR3ForcedActions(pVM, rc);
3214 if ( ( rc == VINF_EM_RESCHEDULE_REM
3215 || rc == VINF_EM_RESCHEDULE_HWACC)
3216 && pVM->em.s.fForceRAW)
3217 rc = VINF_EM_RESCHEDULE_RAW;
3218 }
3219 else if (fFFDone)
3220 fFFDone = false;
3221
3222 /*
3223 * Now what to do?
3224 */
3225 Log2(("EMR3ExecuteVM: rc=%Vrc\n", rc));
3226 switch (rc)
3227 {
3228 /*
3229 * Keep doing what we're currently doing.
3230 */
3231 case VINF_SUCCESS:
3232 break;
3233
3234 /*
3235 * Reschedule - to raw-mode execution.
3236 */
3237 case VINF_EM_RESCHEDULE_RAW:
3238 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_RAW: %d -> %d (EMSTATE_RAW)\n", pVM->em.s.enmState, EMSTATE_RAW));
3239 pVM->em.s.enmState = EMSTATE_RAW;
3240 break;
3241
3242 /*
3243 * Reschedule - to hardware accelerated raw-mode execution.
3244 */
3245 case VINF_EM_RESCHEDULE_HWACC:
3246 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_HWACC: %d -> %d (EMSTATE_HWACC)\n", pVM->em.s.enmState, EMSTATE_HWACC));
3247 Assert(!pVM->em.s.fForceRAW);
3248 pVM->em.s.enmState = EMSTATE_HWACC;
3249 break;
3250
3251 /*
3252 * Reschedule - to recompiled execution.
3253 */
3254 case VINF_EM_RESCHEDULE_REM:
3255 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_REM: %d -> %d (EMSTATE_REM)\n", pVM->em.s.enmState, EMSTATE_REM));
3256 pVM->em.s.enmState = EMSTATE_REM;
3257 break;
3258
3259 /*
3260 * Resume.
3261 */
3262 case VINF_EM_RESUME:
3263 Log2(("EMR3ExecuteVM: VINF_EM_RESUME: %d -> VINF_EM_RESCHEDULE\n", pVM->em.s.enmState));
3264 /* fall through and get scheduled. */
3265
3266 /*
3267 * Reschedule.
3268 */
3269 case VINF_EM_RESCHEDULE:
3270 {
3271 EMSTATE enmState = emR3Reschedule(pVM, pVM->em.s.pCtx);
3272 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE: %d -> %d (%s)\n", pVM->em.s.enmState, enmState, EMR3GetStateName(enmState)));
3273 pVM->em.s.enmState = enmState;
3274 break;
3275 }
3276
3277 /*
3278 * Halted.
3279 */
3280 case VINF_EM_HALT:
3281 Log2(("EMR3ExecuteVM: VINF_EM_HALT: %d -> %d\n", pVM->em.s.enmState, EMSTATE_HALTED));
3282 pVM->em.s.enmState = EMSTATE_HALTED;
3283 break;
3284
3285 /*
3286 * Suspend.
3287 */
3288 case VINF_EM_SUSPEND:
3289 Log2(("EMR3ExecuteVM: VINF_EM_SUSPEND: %d -> %d\n", pVM->em.s.enmState, EMSTATE_SUSPENDED));
3290 pVM->em.s.enmState = EMSTATE_SUSPENDED;
3291 break;
3292
3293 /*
3294 * Reset.
3295 * We might end up doing a double reset for now, we'll have to clean up the mess later.
3296 */
3297 case VINF_EM_RESET:
3298 Log2(("EMR3ExecuteVM: VINF_EM_RESET: %d -> %d\n", pVM->em.s.enmState, EMSTATE_REM));
3299 pVM->em.s.enmState = EMSTATE_REM;
3300 break;
3301
3302 /*
3303 * Power Off.
3304 */
3305 case VINF_EM_OFF:
3306 pVM->em.s.enmState = EMSTATE_TERMINATING;
3307 Log2(("EMR3ExecuteVM: returns VINF_EM_OFF (%d -> %d)\n", pVM->em.s.enmState, EMSTATE_TERMINATING));
3308 TMVirtualPause(pVM);
3309 VMMR3Unlock(pVM);
3310 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3311 return rc;
3312
3313 /*
3314 * Terminate the VM.
3315 */
3316 case VINF_EM_TERMINATE:
3317 pVM->em.s.enmState = EMSTATE_TERMINATING;
3318 Log(("EMR3ExecuteVM returns VINF_EM_TERMINATE (%d -> %d)\n", pVM->em.s.enmState, EMSTATE_TERMINATING));
3319 TMVirtualPause(pVM);
3320 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3321 return rc;
3322
3323 /*
3324 * Guest debug events.
3325 */
3326 case VINF_EM_DBG_STEPPED:
3327 AssertMsgFailed(("VINF_EM_DBG_STEPPED cannot be here!"));
3328 case VINF_EM_DBG_STOP:
3329 case VINF_EM_DBG_BREAKPOINT:
3330 case VINF_EM_DBG_STEP:
3331 if (pVM->em.s.enmState == EMSTATE_RAW)
3332 {
3333 Log2(("EMR3ExecuteVM: %Vrc: %d -> %d\n", rc, pVM->em.s.enmState, EMSTATE_DEBUG_GUEST_RAW));
3334 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_RAW;
3335 }
3336 else
3337 {
3338 Log2(("EMR3ExecuteVM: %Vrc: %d -> %d\n", rc, pVM->em.s.enmState, EMSTATE_DEBUG_GUEST_REM));
3339 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_REM;
3340 }
3341 break;
3342
3343 /*
3344 * Hypervisor debug events.
3345 */
3346 case VINF_EM_DBG_HYPER_STEPPED:
3347 case VINF_EM_DBG_HYPER_BREAKPOINT:
3348 case VINF_EM_DBG_HYPER_ASSERTION:
3349 Log2(("EMR3ExecuteVM: %Vrc: %d -> %d\n", rc, pVM->em.s.enmState, EMSTATE_DEBUG_HYPER));
3350 pVM->em.s.enmState = EMSTATE_DEBUG_HYPER;
3351 break;
3352
3353 /*
3354 * Any error code showing up here other than the ones we
3355 * know and process above are considered to be FATAL.
3356 *
3357 * Unknown warnings and informational status codes are also
3358 * included in this.
3359 */
3360 default:
3361 if (VBOX_SUCCESS(rc))
3362 {
3363 AssertMsgFailed(("Unexpected warning or informational status code %Vra!\n", rc));
3364 rc = VERR_EM_INTERNAL_ERROR;
3365 }
3366 pVM->em.s.enmState = EMSTATE_GURU_MEDITATION;
3367 Log(("EMR3ExecuteVM returns %d\n", rc));
3368 break;
3369 }
3370
3371
3372 /*
3373 * Any waiters can now be woken up
3374 */
3375 VMMR3Unlock(pVM);
3376 VMMR3Lock(pVM);
3377
3378 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3379 STAM_PROFILE_ADV_START(&pVM->em.s.StatTotal, x);
3380
3381 /*
3382 * Act on the state.
3383 */
3384 switch (pVM->em.s.enmState)
3385 {
3386 /*
3387 * Execute raw.
3388 */
3389 case EMSTATE_RAW:
3390 rc = emR3RawExecute(pVM, &fFFDone);
3391 break;
3392
3393 /*
3394 * Execute hardware accelerated raw.
3395 */
3396 case EMSTATE_HWACC:
3397 rc = emR3HwAccExecute(pVM, &fFFDone);
3398 break;
3399
3400 /*
3401 * Execute recompiled.
3402 */
3403 case EMSTATE_REM:
3404#if 0
3405 /* simulate a runtime error */
3406 VMSetRuntimeError (pVM, true, "simulatedError", "pVM=%p", pVM);
3407#endif
3408 rc = emR3RemExecute(pVM, &fFFDone);
3409 Log2(("EMR3ExecuteVM: emR3RemExecute -> %Vrc\n", rc));
3410 break;
3411
3412 /*
3413 * hlt - execution halted until interrupt.
3414 */
3415 case EMSTATE_HALTED:
3416 {
3417 STAM_PROFILE_START(&pVM->em.s.StatHalted, y);
3418 rc = VMR3WaitHalted(pVM, !(CPUMGetGuestEFlags(pVM) & X86_EFL_IF));
3419 STAM_PROFILE_STOP(&pVM->em.s.StatHalted, y);
3420 break;
3421 }
3422
3423 /*
3424 * Suspended - return to VM.cpp.
3425 */
3426 case EMSTATE_SUSPENDED:
3427 TMVirtualPause(pVM);
3428 VMMR3Unlock(pVM);
3429 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3430 return VINF_EM_SUSPEND;
3431
3432 /*
3433 * Debugging in the guest.
3434 */
3435 case EMSTATE_DEBUG_GUEST_REM:
3436 case EMSTATE_DEBUG_GUEST_RAW:
3437 TMVirtualPause(pVM);
3438 rc = emR3Debug(pVM, rc);
3439 TMVirtualResume(pVM);
3440 Log2(("EMR3ExecuteVM: enmr3Debug -> %Vrc (state %d)\n", rc, pVM->em.s.enmState));
3441 break;
3442
3443 /*
3444 * Debugging in the hypervisor.
3445 */
3446 case EMSTATE_DEBUG_HYPER:
3447 {
3448 TMVirtualPause(pVM);
3449 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3450
3451 rc = emR3Debug(pVM, rc);
3452 Log2(("EMR3ExecuteVM: enmr3Debug -> %Vrc (state %d)\n", rc, pVM->em.s.enmState));
3453 if (rc != VINF_SUCCESS)
3454 {
3455 /* switch to guru meditation mode */
3456 pVM->em.s.enmState = EMSTATE_GURU_MEDITATION;
3457 VMMR3FatalDump(pVM, rc);
3458 return rc;
3459 }
3460
3461 STAM_PROFILE_ADV_START(&pVM->em.s.StatTotal, x);
3462 TMVirtualResume(pVM);
3463 break;
3464 }
3465
3466 /*
3467 * Guru meditation takes place in the debugger.
3468 */
3469 case EMSTATE_GURU_MEDITATION:
3470 {
3471 /** @todo this ain't entirely safe. make a better return code check and specify this in DBGF/emR3Debug. */
3472 TMVirtualPause(pVM);
3473 VMMR3FatalDump(pVM, rc);
3474 int rc2 = emR3Debug(pVM, rc);
3475 if (rc2 == VERR_DBGF_NOT_ATTACHED)
3476 {
3477 VMMR3Unlock(pVM);
3478 /** @todo change the VM state! */
3479 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3480 return rc;
3481 }
3482 TMVirtualResume(pVM);
3483 rc = rc2;
3484 /** @todo we're not doing the right thing in emR3Debug and will cause code to be executed on disconnect and stuff.. */
3485 Log2(("EMR3ExecuteVM: enmr3Debug -> %Vrc (state %d)\n", rc, pVM->em.s.enmState));
3486 break;
3487 }
3488
3489 /*
3490 * The states we don't expect here.
3491 */
3492 case EMSTATE_NONE:
3493 case EMSTATE_TERMINATING:
3494 default:
3495 AssertMsgFailed(("EMR3ExecuteVM: Invalid state %d!\n", pVM->em.s.enmState));
3496 pVM->em.s.enmState = EMSTATE_GURU_MEDITATION;
3497 TMVirtualPause(pVM);
3498 VMMR3Unlock(pVM);
3499 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3500 return VERR_EM_INTERNAL_ERROR;
3501 }
3502 } /* The Outer Main Loop */
3503 }
3504 else
3505 {
3506 /*
3507 * Fatal error.
3508 */
3509 LogFlow(("EMR3ExecuteVM: returns %Vrc (longjmp / fatal error)\n", rc));
3510 TMVirtualPause(pVM);
3511 VMMR3FatalDump(pVM, rc);
3512 emR3Debug(pVM, rc);
3513 VMMR3Unlock(pVM);
3514 /** @todo change the VM state! */
3515 return rc;
3516 }
3517
3518 /* (won't ever get here). */
3519 AssertFailed();
3520}
3521
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