VirtualBox

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

Last change on this file since 20399 was 20399, checked in by vboxsync, 16 years ago

Minor updates

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 165.2 KB
Line 
1/* $Id: EM.cpp 20399 2009-06-08 13:01:44Z vboxsync $ */
2/** @file
3 * EM - Execution Monitor / Manager.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
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 (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/** @page pg_em EM - The Execution Monitor / Manager
23 *
24 * The Execution Monitor/Manager is responsible for running the VM, scheduling
25 * the right kind of execution (Raw-mode, Hardware Assisted, Recompiled or
26 * Interpreted), and keeping the CPU states in sync. The function
27 * EMR3ExecuteVM() is the 'main-loop' of the VM, while each of the execution
28 * modes has different inner loops (emR3RawExecute, emR3HwAccExecute, and
29 * emR3RemExecute).
30 *
31 * The interpreted execution is only used to avoid switching between
32 * raw-mode/hwaccm and the recompiler when fielding virtualization traps/faults.
33 * The interpretation is thus implemented as part of EM.
34 *
35 * @see grp_em
36 */
37
38/*******************************************************************************
39* Header Files *
40*******************************************************************************/
41#define LOG_GROUP LOG_GROUP_EM
42#include <VBox/em.h>
43#include <VBox/vmm.h>
44#ifdef VBOX_WITH_VMI
45# include <VBox/parav.h>
46#endif
47#include <VBox/patm.h>
48#include <VBox/csam.h>
49#include <VBox/selm.h>
50#include <VBox/trpm.h>
51#include <VBox/iom.h>
52#include <VBox/dbgf.h>
53#include <VBox/pgm.h>
54#include <VBox/rem.h>
55#include <VBox/tm.h>
56#include <VBox/mm.h>
57#include <VBox/ssm.h>
58#include <VBox/pdmapi.h>
59#include <VBox/pdmcritsect.h>
60#include <VBox/pdmqueue.h>
61#include <VBox/hwaccm.h>
62#include <VBox/patm.h>
63#include "EMInternal.h"
64#include <VBox/vm.h>
65#include <VBox/cpumdis.h>
66#include <VBox/dis.h>
67#include <VBox/disopcode.h>
68#include <VBox/dbgf.h>
69
70#include <VBox/log.h>
71#include <iprt/thread.h>
72#include <iprt/assert.h>
73#include <iprt/asm.h>
74#include <iprt/semaphore.h>
75#include <iprt/string.h>
76#include <iprt/avl.h>
77#include <iprt/stream.h>
78#include <VBox/param.h>
79#include <VBox/err.h>
80
81
82/*******************************************************************************
83* Defined Constants And Macros *
84*******************************************************************************/
85#if 0 /* Disabled till after 2.1.0 when we've time to test it. */
86#define EM_NOTIFY_HWACCM
87#endif
88
89
90/*******************************************************************************
91* Internal Functions *
92*******************************************************************************/
93static DECLCALLBACK(int) emR3Save(PVM pVM, PSSMHANDLE pSSM);
94static DECLCALLBACK(int) emR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
95static int emR3Debug(PVM pVM, PVMCPU pVCpu, int rc);
96static int emR3RemStep(PVM pVM, PVMCPU pVCpu);
97static int emR3RemExecute(PVM pVM, PVMCPU pVCpu, bool *pfFFDone);
98static int emR3RawResumeHyper(PVM pVM, PVMCPU pVCpu);
99static int emR3RawStep(PVM pVM, PVMCPU pVCpu);
100DECLINLINE(int) emR3RawHandleRC(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rc);
101DECLINLINE(int) emR3RawUpdateForceFlag(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rc);
102static int emR3RawForcedActions(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
103static int emR3RawExecute(PVM pVM, PVMCPU pVCpu, bool *pfFFDone);
104DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, PVMCPU pVCpu, const char *pszPrefix, int rcGC = VINF_SUCCESS);
105static int emR3HighPriorityPostForcedActions(PVM pVM, PVMCPU pVCpu, int rc);
106static int emR3ForcedActions(PVM pVM, PVMCPU pVCpu, int rc);
107static int emR3RawGuestTrap(PVM pVM, PVMCPU pVCpu);
108static int emR3PatchTrap(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int gcret);
109static int emR3SingleStepExecRem(PVM pVM, uint32_t cIterations);
110static EMSTATE emR3Reschedule(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
111
112/**
113 * Initializes the EM.
114 *
115 * @returns VBox status code.
116 * @param pVM The VM to operate on.
117 */
118VMMR3DECL(int) EMR3Init(PVM pVM)
119{
120 LogFlow(("EMR3Init\n"));
121 /*
122 * Assert alignment and sizes.
123 */
124 AssertCompileMemberAlignment(VM, em.s, 32);
125 AssertCompile(sizeof(pVM->em.s) <= sizeof(pVM->em.padding));
126 AssertCompile(sizeof(pVM->aCpus[0].em.s.u.FatalLongJump) <= sizeof(pVM->aCpus[0].em.s.u.achPaddingFatalLongJump));
127 AssertCompileMemberAlignment(EM, CritSectREM, sizeof(uintptr_t));
128
129 /*
130 * Init the structure.
131 */
132 pVM->em.s.offVM = RT_OFFSETOF(VM, em.s);
133 int rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "RawR3Enabled", &pVM->fRawR3Enabled);
134 if (RT_FAILURE(rc))
135 pVM->fRawR3Enabled = true;
136 rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "RawR0Enabled", &pVM->fRawR0Enabled);
137 if (RT_FAILURE(rc))
138 pVM->fRawR0Enabled = true;
139 Log(("EMR3Init: fRawR3Enabled=%d fRawR0Enabled=%d\n", pVM->fRawR3Enabled, pVM->fRawR0Enabled));
140
141 /*
142 * Initialize the REM critical section.
143 */
144 rc = PDMR3CritSectInit(pVM, &pVM->em.s.CritSectREM, "EM-REM");
145 AssertRCReturn(rc, rc);
146
147 /*
148 * Saved state.
149 */
150 rc = SSMR3RegisterInternal(pVM, "em", 0, EM_SAVED_STATE_VERSION, 16,
151 NULL, emR3Save, NULL,
152 NULL, emR3Load, NULL);
153 if (RT_FAILURE(rc))
154 return rc;
155
156 for (unsigned i=0;i<pVM->cCPUs;i++)
157 {
158 PVMCPU pVCpu = &pVM->aCpus[i];
159
160 pVCpu->em.s.offVMCPU = RT_OFFSETOF(VMCPU, em.s);
161
162 pVCpu->em.s.enmState = (i == 0) ? EMSTATE_NONE : EMSTATE_WAIT_SIPI;
163 pVCpu->em.s.enmPrevState = EMSTATE_NONE;
164 pVCpu->em.s.fForceRAW = false;
165
166 pVCpu->em.s.pCtx = CPUMQueryGuestCtxPtr(pVCpu);
167 pVCpu->em.s.pPatmGCState = PATMR3QueryGCStateHC(pVM);
168 AssertMsg(pVCpu->em.s.pPatmGCState, ("PATMR3QueryGCStateHC failed!\n"));
169
170# define EM_REG_COUNTER(a, b, c) \
171 rc = STAMR3RegisterF(pVM, a, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, c, b, i); \
172 AssertRC(rc);
173
174# define EM_REG_COUNTER_USED(a, b, c) \
175 rc = STAMR3RegisterF(pVM, a, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES, c, b, i); \
176 AssertRC(rc);
177
178# define EM_REG_PROFILE(a, b, c) \
179 rc = STAMR3RegisterF(pVM, a, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, c, b, i); \
180 AssertRC(rc);
181
182# define EM_REG_PROFILE_ADV(a, b, c) \
183 rc = STAMR3RegisterF(pVM, a, STAMTYPE_PROFILE_ADV, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, c, b, i); \
184 AssertRC(rc);
185
186 /*
187 * Statistics.
188 */
189#ifdef VBOX_WITH_STATISTICS
190 PEMSTATS pStats;
191 rc = MMHyperAlloc(pVM, sizeof(*pStats), 0, MM_TAG_EM, (void **)&pStats);
192 if (RT_FAILURE(rc))
193 return rc;
194
195 pVCpu->em.s.pStatsR3 = pStats;
196 pVCpu->em.s.pStatsR0 = MMHyperR3ToR0(pVM, pStats);
197 pVCpu->em.s.pStatsRC = MMHyperR3ToRC(pVM, pStats);
198
199 EM_REG_PROFILE(&pStats->StatRZEmulate, "/EM/CPU%d/RZ/Interpret", "Profiling of EMInterpretInstruction.");
200 EM_REG_PROFILE(&pStats->StatR3Emulate, "/EM/CPU%d/R3/Interpret", "Profiling of EMInterpretInstruction.");
201
202 EM_REG_PROFILE(&pStats->StatRZInterpretSucceeded, "/EM/CPU%d/RZ/Interpret/Success", "The number of times an instruction was successfully interpreted.");
203 EM_REG_PROFILE(&pStats->StatR3InterpretSucceeded, "/EM/CPU%d/R3/Interpret/Success", "The number of times an instruction was successfully interpreted.");
204
205 EM_REG_COUNTER_USED(&pStats->StatRZAnd, "/EM/CPU%d/RZ/Interpret/Success/And", "The number of times AND was successfully interpreted.");
206 EM_REG_COUNTER_USED(&pStats->StatR3And, "/EM/CPU%d/R3/Interpret/Success/And", "The number of times AND was successfully interpreted.");
207 EM_REG_COUNTER_USED(&pStats->StatRZAdd, "/EM/CPU%d/RZ/Interpret/Success/Add", "The number of times ADD was successfully interpreted.");
208 EM_REG_COUNTER_USED(&pStats->StatR3Add, "/EM/CPU%d/R3/Interpret/Success/Add", "The number of times ADD was successfully interpreted.");
209 EM_REG_COUNTER_USED(&pStats->StatRZAdc, "/EM/CPU%d/RZ/Interpret/Success/Adc", "The number of times ADC was successfully interpreted.");
210 EM_REG_COUNTER_USED(&pStats->StatR3Adc, "/EM/CPU%d/R3/Interpret/Success/Adc", "The number of times ADC was successfully interpreted.");
211 EM_REG_COUNTER_USED(&pStats->StatRZSub, "/EM/CPU%d/RZ/Interpret/Success/Sub", "The number of times SUB was successfully interpreted.");
212 EM_REG_COUNTER_USED(&pStats->StatR3Sub, "/EM/CPU%d/R3/Interpret/Success/Sub", "The number of times SUB was successfully interpreted.");
213 EM_REG_COUNTER_USED(&pStats->StatRZCpuId, "/EM/CPU%d/RZ/Interpret/Success/CpuId", "The number of times CPUID was successfully interpreted.");
214 EM_REG_COUNTER_USED(&pStats->StatR3CpuId, "/EM/CPU%d/R3/Interpret/Success/CpuId", "The number of times CPUID was successfully interpreted.");
215 EM_REG_COUNTER_USED(&pStats->StatRZDec, "/EM/CPU%d/RZ/Interpret/Success/Dec", "The number of times DEC was successfully interpreted.");
216 EM_REG_COUNTER_USED(&pStats->StatR3Dec, "/EM/CPU%d/R3/Interpret/Success/Dec", "The number of times DEC was successfully interpreted.");
217 EM_REG_COUNTER_USED(&pStats->StatRZHlt, "/EM/CPU%d/RZ/Interpret/Success/Hlt", "The number of times HLT was successfully interpreted.");
218 EM_REG_COUNTER_USED(&pStats->StatR3Hlt, "/EM/CPU%d/R3/Interpret/Success/Hlt", "The number of times HLT was successfully interpreted.");
219 EM_REG_COUNTER_USED(&pStats->StatRZInc, "/EM/CPU%d/RZ/Interpret/Success/Inc", "The number of times INC was successfully interpreted.");
220 EM_REG_COUNTER_USED(&pStats->StatR3Inc, "/EM/CPU%d/R3/Interpret/Success/Inc", "The number of times INC was successfully interpreted.");
221 EM_REG_COUNTER_USED(&pStats->StatRZInvlPg, "/EM/CPU%d/RZ/Interpret/Success/Invlpg", "The number of times INVLPG was successfully interpreted.");
222 EM_REG_COUNTER_USED(&pStats->StatR3InvlPg, "/EM/CPU%d/R3/Interpret/Success/Invlpg", "The number of times INVLPG was successfully interpreted.");
223 EM_REG_COUNTER_USED(&pStats->StatRZIret, "/EM/CPU%d/RZ/Interpret/Success/Iret", "The number of times IRET was successfully interpreted.");
224 EM_REG_COUNTER_USED(&pStats->StatR3Iret, "/EM/CPU%d/R3/Interpret/Success/Iret", "The number of times IRET was successfully interpreted.");
225 EM_REG_COUNTER_USED(&pStats->StatRZLLdt, "/EM/CPU%d/RZ/Interpret/Success/LLdt", "The number of times LLDT was successfully interpreted.");
226 EM_REG_COUNTER_USED(&pStats->StatR3LLdt, "/EM/CPU%d/R3/Interpret/Success/LLdt", "The number of times LLDT was successfully interpreted.");
227 EM_REG_COUNTER_USED(&pStats->StatRZLIdt, "/EM/CPU%d/RZ/Interpret/Success/LIdt", "The number of times LIDT was successfully interpreted.");
228 EM_REG_COUNTER_USED(&pStats->StatR3LIdt, "/EM/CPU%d/R3/Interpret/Success/LIdt", "The number of times LIDT was successfully interpreted.");
229 EM_REG_COUNTER_USED(&pStats->StatRZLGdt, "/EM/CPU%d/RZ/Interpret/Success/LGdt", "The number of times LGDT was successfully interpreted.");
230 EM_REG_COUNTER_USED(&pStats->StatR3LGdt, "/EM/CPU%d/R3/Interpret/Success/LGdt", "The number of times LGDT was successfully interpreted.");
231 EM_REG_COUNTER_USED(&pStats->StatRZMov, "/EM/CPU%d/RZ/Interpret/Success/Mov", "The number of times MOV was successfully interpreted.");
232 EM_REG_COUNTER_USED(&pStats->StatR3Mov, "/EM/CPU%d/R3/Interpret/Success/Mov", "The number of times MOV was successfully interpreted.");
233 EM_REG_COUNTER_USED(&pStats->StatRZMovCRx, "/EM/CPU%d/RZ/Interpret/Success/MovCRx", "The number of times MOV CRx was successfully interpreted.");
234 EM_REG_COUNTER_USED(&pStats->StatR3MovCRx, "/EM/CPU%d/R3/Interpret/Success/MovCRx", "The number of times MOV CRx was successfully interpreted.");
235 EM_REG_COUNTER_USED(&pStats->StatRZMovDRx, "/EM/CPU%d/RZ/Interpret/Success/MovDRx", "The number of times MOV DRx was successfully interpreted.");
236 EM_REG_COUNTER_USED(&pStats->StatR3MovDRx, "/EM/CPU%d/R3/Interpret/Success/MovDRx", "The number of times MOV DRx was successfully interpreted.");
237 EM_REG_COUNTER_USED(&pStats->StatRZOr, "/EM/CPU%d/RZ/Interpret/Success/Or", "The number of times OR was successfully interpreted.");
238 EM_REG_COUNTER_USED(&pStats->StatR3Or, "/EM/CPU%d/R3/Interpret/Success/Or", "The number of times OR was successfully interpreted.");
239 EM_REG_COUNTER_USED(&pStats->StatRZPop, "/EM/CPU%d/RZ/Interpret/Success/Pop", "The number of times POP was successfully interpreted.");
240 EM_REG_COUNTER_USED(&pStats->StatR3Pop, "/EM/CPU%d/R3/Interpret/Success/Pop", "The number of times POP was successfully interpreted.");
241 EM_REG_COUNTER_USED(&pStats->StatRZRdtsc, "/EM/CPU%d/RZ/Interpret/Success/Rdtsc", "The number of times RDTSC was successfully interpreted.");
242 EM_REG_COUNTER_USED(&pStats->StatR3Rdtsc, "/EM/CPU%d/R3/Interpret/Success/Rdtsc", "The number of times RDTSC was successfully interpreted.");
243 EM_REG_COUNTER_USED(&pStats->StatRZRdpmc, "/EM/CPU%d/RZ/Interpret/Success/Rdpmc", "The number of times RDPMC was successfully interpreted.");
244 EM_REG_COUNTER_USED(&pStats->StatR3Rdpmc, "/EM/CPU%d/R3/Interpret/Success/Rdpmc", "The number of times RDPMC was successfully interpreted.");
245 EM_REG_COUNTER_USED(&pStats->StatRZSti, "/EM/CPU%d/RZ/Interpret/Success/Sti", "The number of times STI was successfully interpreted.");
246 EM_REG_COUNTER_USED(&pStats->StatR3Sti, "/EM/CPU%d/R3/Interpret/Success/Sti", "The number of times STI was successfully interpreted.");
247 EM_REG_COUNTER_USED(&pStats->StatRZXchg, "/EM/CPU%d/RZ/Interpret/Success/Xchg", "The number of times XCHG was successfully interpreted.");
248 EM_REG_COUNTER_USED(&pStats->StatR3Xchg, "/EM/CPU%d/R3/Interpret/Success/Xchg", "The number of times XCHG was successfully interpreted.");
249 EM_REG_COUNTER_USED(&pStats->StatRZXor, "/EM/CPU%d/RZ/Interpret/Success/Xor", "The number of times XOR was successfully interpreted.");
250 EM_REG_COUNTER_USED(&pStats->StatR3Xor, "/EM/CPU%d/R3/Interpret/Success/Xor", "The number of times XOR was successfully interpreted.");
251 EM_REG_COUNTER_USED(&pStats->StatRZMonitor, "/EM/CPU%d/RZ/Interpret/Success/Monitor", "The number of times MONITOR was successfully interpreted.");
252 EM_REG_COUNTER_USED(&pStats->StatR3Monitor, "/EM/CPU%d/R3/Interpret/Success/Monitor", "The number of times MONITOR was successfully interpreted.");
253 EM_REG_COUNTER_USED(&pStats->StatRZMWait, "/EM/CPU%d/RZ/Interpret/Success/MWait", "The number of times MWAIT was successfully interpreted.");
254 EM_REG_COUNTER_USED(&pStats->StatR3MWait, "/EM/CPU%d/R3/Interpret/Success/MWait", "The number of times MWAIT was successfully interpreted.");
255 EM_REG_COUNTER_USED(&pStats->StatRZBtr, "/EM/CPU%d/RZ/Interpret/Success/Btr", "The number of times BTR was successfully interpreted.");
256 EM_REG_COUNTER_USED(&pStats->StatR3Btr, "/EM/CPU%d/R3/Interpret/Success/Btr", "The number of times BTR was successfully interpreted.");
257 EM_REG_COUNTER_USED(&pStats->StatRZBts, "/EM/CPU%d/RZ/Interpret/Success/Bts", "The number of times BTS was successfully interpreted.");
258 EM_REG_COUNTER_USED(&pStats->StatR3Bts, "/EM/CPU%d/R3/Interpret/Success/Bts", "The number of times BTS was successfully interpreted.");
259 EM_REG_COUNTER_USED(&pStats->StatRZBtc, "/EM/CPU%d/RZ/Interpret/Success/Btc", "The number of times BTC was successfully interpreted.");
260 EM_REG_COUNTER_USED(&pStats->StatR3Btc, "/EM/CPU%d/R3/Interpret/Success/Btc", "The number of times BTC was successfully interpreted.");
261 EM_REG_COUNTER_USED(&pStats->StatRZCmpXchg, "/EM/CPU%d/RZ/Interpret/Success/CmpXchg", "The number of times CMPXCHG was successfully interpreted.");
262 EM_REG_COUNTER_USED(&pStats->StatR3CmpXchg, "/EM/CPU%d/R3/Interpret/Success/CmpXchg", "The number of times CMPXCHG was successfully interpreted.");
263 EM_REG_COUNTER_USED(&pStats->StatRZCmpXchg8b, "/EM/CPU%d/RZ/Interpret/Success/CmpXchg8b", "The number of times CMPXCHG8B was successfully interpreted.");
264 EM_REG_COUNTER_USED(&pStats->StatR3CmpXchg8b, "/EM/CPU%d/R3/Interpret/Success/CmpXchg8b", "The number of times CMPXCHG8B was successfully interpreted.");
265 EM_REG_COUNTER_USED(&pStats->StatRZXAdd, "/EM/CPU%d/RZ/Interpret/Success/XAdd", "The number of times XADD was successfully interpreted.");
266 EM_REG_COUNTER_USED(&pStats->StatR3XAdd, "/EM/CPU%d/R3/Interpret/Success/XAdd", "The number of times XADD was successfully interpreted.");
267 EM_REG_COUNTER_USED(&pStats->StatR3Rdmsr, "/EM/CPU%d/R3/Interpret/Success/Rdmsr", "The number of times RDMSR was successfully interpreted.");
268 EM_REG_COUNTER_USED(&pStats->StatRZRdmsr, "/EM/CPU%d/RZ/Interpret/Success/Rdmsr", "The number of times RDMSR was successfully interpreted.");
269 EM_REG_COUNTER_USED(&pStats->StatR3Wrmsr, "/EM/CPU%d/R3/Interpret/Success/Wrmsr", "The number of times WRMSR was successfully interpreted.");
270 EM_REG_COUNTER_USED(&pStats->StatRZWrmsr, "/EM/CPU%d/RZ/Interpret/Success/Wrmsr", "The number of times WRMSR was successfully interpreted.");
271 EM_REG_COUNTER_USED(&pStats->StatR3StosWD, "/EM/CPU%d/R3/Interpret/Success/Stoswd", "The number of times STOSWD was successfully interpreted.");
272 EM_REG_COUNTER_USED(&pStats->StatRZStosWD, "/EM/CPU%d/RZ/Interpret/Success/Stoswd", "The number of times STOSWD was successfully interpreted.");
273 EM_REG_COUNTER_USED(&pStats->StatRZWbInvd, "/EM/CPU%d/RZ/Interpret/Success/WbInvd", "The number of times WBINVD was successfully interpreted.");
274 EM_REG_COUNTER_USED(&pStats->StatR3WbInvd, "/EM/CPU%d/R3/Interpret/Success/WbInvd", "The number of times WBINVD was successfully interpreted.");
275 EM_REG_COUNTER_USED(&pStats->StatRZLmsw, "/EM/CPU%d/RZ/Interpret/Success/Lmsw", "The number of times LMSW was successfully interpreted.");
276 EM_REG_COUNTER_USED(&pStats->StatR3Lmsw, "/EM/CPU%d/R3/Interpret/Success/Lmsw", "The number of times LMSW was successfully interpreted.");
277
278 EM_REG_COUNTER(&pStats->StatRZInterpretFailed, "/EM/CPU%d/RZ/Interpret/Failed", "The number of times an instruction was not interpreted.");
279 EM_REG_COUNTER(&pStats->StatR3InterpretFailed, "/EM/CPU%d/R3/Interpret/Failed", "The number of times an instruction was not interpreted.");
280
281 EM_REG_COUNTER_USED(&pStats->StatRZFailedAnd, "/EM/CPU%d/RZ/Interpret/Failed/And", "The number of times AND was not interpreted.");
282 EM_REG_COUNTER_USED(&pStats->StatR3FailedAnd, "/EM/CPU%d/R3/Interpret/Failed/And", "The number of times AND was not interpreted.");
283 EM_REG_COUNTER_USED(&pStats->StatRZFailedCpuId, "/EM/CPU%d/RZ/Interpret/Failed/CpuId", "The number of times CPUID was not interpreted.");
284 EM_REG_COUNTER_USED(&pStats->StatR3FailedCpuId, "/EM/CPU%d/R3/Interpret/Failed/CpuId", "The number of times CPUID was not interpreted.");
285 EM_REG_COUNTER_USED(&pStats->StatRZFailedDec, "/EM/CPU%d/RZ/Interpret/Failed/Dec", "The number of times DEC was not interpreted.");
286 EM_REG_COUNTER_USED(&pStats->StatR3FailedDec, "/EM/CPU%d/R3/Interpret/Failed/Dec", "The number of times DEC was not interpreted.");
287 EM_REG_COUNTER_USED(&pStats->StatRZFailedHlt, "/EM/CPU%d/RZ/Interpret/Failed/Hlt", "The number of times HLT was not interpreted.");
288 EM_REG_COUNTER_USED(&pStats->StatR3FailedHlt, "/EM/CPU%d/R3/Interpret/Failed/Hlt", "The number of times HLT was not interpreted.");
289 EM_REG_COUNTER_USED(&pStats->StatRZFailedInc, "/EM/CPU%d/RZ/Interpret/Failed/Inc", "The number of times INC was not interpreted.");
290 EM_REG_COUNTER_USED(&pStats->StatR3FailedInc, "/EM/CPU%d/R3/Interpret/Failed/Inc", "The number of times INC was not interpreted.");
291 EM_REG_COUNTER_USED(&pStats->StatRZFailedInvlPg, "/EM/CPU%d/RZ/Interpret/Failed/InvlPg", "The number of times INVLPG was not interpreted.");
292 EM_REG_COUNTER_USED(&pStats->StatR3FailedInvlPg, "/EM/CPU%d/R3/Interpret/Failed/InvlPg", "The number of times INVLPG was not interpreted.");
293 EM_REG_COUNTER_USED(&pStats->StatRZFailedIret, "/EM/CPU%d/RZ/Interpret/Failed/Iret", "The number of times IRET was not interpreted.");
294 EM_REG_COUNTER_USED(&pStats->StatR3FailedIret, "/EM/CPU%d/R3/Interpret/Failed/Iret", "The number of times IRET was not interpreted.");
295 EM_REG_COUNTER_USED(&pStats->StatRZFailedLLdt, "/EM/CPU%d/RZ/Interpret/Failed/LLdt", "The number of times LLDT was not interpreted.");
296 EM_REG_COUNTER_USED(&pStats->StatR3FailedLLdt, "/EM/CPU%d/R3/Interpret/Failed/LLdt", "The number of times LLDT was not interpreted.");
297 EM_REG_COUNTER_USED(&pStats->StatRZFailedLIdt, "/EM/CPU%d/RZ/Interpret/Failed/LIdt", "The number of times LIDT was not interpreted.");
298 EM_REG_COUNTER_USED(&pStats->StatR3FailedLIdt, "/EM/CPU%d/R3/Interpret/Failed/LIdt", "The number of times LIDT was not interpreted.");
299 EM_REG_COUNTER_USED(&pStats->StatRZFailedLGdt, "/EM/CPU%d/RZ/Interpret/Failed/LGdt", "The number of times LGDT was not interpreted.");
300 EM_REG_COUNTER_USED(&pStats->StatR3FailedLGdt, "/EM/CPU%d/R3/Interpret/Failed/LGdt", "The number of times LGDT was not interpreted.");
301 EM_REG_COUNTER_USED(&pStats->StatRZFailedMov, "/EM/CPU%d/RZ/Interpret/Failed/Mov", "The number of times MOV was not interpreted.");
302 EM_REG_COUNTER_USED(&pStats->StatR3FailedMov, "/EM/CPU%d/R3/Interpret/Failed/Mov", "The number of times MOV was not interpreted.");
303 EM_REG_COUNTER_USED(&pStats->StatRZFailedMovCRx, "/EM/CPU%d/RZ/Interpret/Failed/MovCRx", "The number of times MOV CRx was not interpreted.");
304 EM_REG_COUNTER_USED(&pStats->StatR3FailedMovCRx, "/EM/CPU%d/R3/Interpret/Failed/MovCRx", "The number of times MOV CRx was not interpreted.");
305 EM_REG_COUNTER_USED(&pStats->StatRZFailedMovDRx, "/EM/CPU%d/RZ/Interpret/Failed/MovDRx", "The number of times MOV DRx was not interpreted.");
306 EM_REG_COUNTER_USED(&pStats->StatR3FailedMovDRx, "/EM/CPU%d/R3/Interpret/Failed/MovDRx", "The number of times MOV DRx was not interpreted.");
307 EM_REG_COUNTER_USED(&pStats->StatRZFailedOr, "/EM/CPU%d/RZ/Interpret/Failed/Or", "The number of times OR was not interpreted.");
308 EM_REG_COUNTER_USED(&pStats->StatR3FailedOr, "/EM/CPU%d/R3/Interpret/Failed/Or", "The number of times OR was not interpreted.");
309 EM_REG_COUNTER_USED(&pStats->StatRZFailedPop, "/EM/CPU%d/RZ/Interpret/Failed/Pop", "The number of times POP was not interpreted.");
310 EM_REG_COUNTER_USED(&pStats->StatR3FailedPop, "/EM/CPU%d/R3/Interpret/Failed/Pop", "The number of times POP was not interpreted.");
311 EM_REG_COUNTER_USED(&pStats->StatRZFailedSti, "/EM/CPU%d/RZ/Interpret/Failed/Sti", "The number of times STI was not interpreted.");
312 EM_REG_COUNTER_USED(&pStats->StatR3FailedSti, "/EM/CPU%d/R3/Interpret/Failed/Sti", "The number of times STI was not interpreted.");
313 EM_REG_COUNTER_USED(&pStats->StatRZFailedXchg, "/EM/CPU%d/RZ/Interpret/Failed/Xchg", "The number of times XCHG was not interpreted.");
314 EM_REG_COUNTER_USED(&pStats->StatR3FailedXchg, "/EM/CPU%d/R3/Interpret/Failed/Xchg", "The number of times XCHG was not interpreted.");
315 EM_REG_COUNTER_USED(&pStats->StatRZFailedXor, "/EM/CPU%d/RZ/Interpret/Failed/Xor", "The number of times XOR was not interpreted.");
316 EM_REG_COUNTER_USED(&pStats->StatR3FailedXor, "/EM/CPU%d/R3/Interpret/Failed/Xor", "The number of times XOR was not interpreted.");
317 EM_REG_COUNTER_USED(&pStats->StatRZFailedMonitor, "/EM/CPU%d/RZ/Interpret/Failed/Monitor", "The number of times MONITOR was not interpreted.");
318 EM_REG_COUNTER_USED(&pStats->StatR3FailedMonitor, "/EM/CPU%d/R3/Interpret/Failed/Monitor", "The number of times MONITOR was not interpreted.");
319 EM_REG_COUNTER_USED(&pStats->StatRZFailedMWait, "/EM/CPU%d/RZ/Interpret/Failed/MWait", "The number of times MONITOR was not interpreted.");
320 EM_REG_COUNTER_USED(&pStats->StatR3FailedMWait, "/EM/CPU%d/R3/Interpret/Failed/MWait", "The number of times MONITOR was not interpreted.");
321 EM_REG_COUNTER_USED(&pStats->StatRZFailedRdtsc, "/EM/CPU%d/RZ/Interpret/Failed/Rdtsc", "The number of times RDTSC was not interpreted.");
322 EM_REG_COUNTER_USED(&pStats->StatR3FailedRdtsc, "/EM/CPU%d/R3/Interpret/Failed/Rdtsc", "The number of times RDTSC was not interpreted.");
323 EM_REG_COUNTER_USED(&pStats->StatRZFailedRdpmc, "/EM/CPU%d/RZ/Interpret/Failed/Rdpmc", "The number of times RDPMC was not interpreted.");
324 EM_REG_COUNTER_USED(&pStats->StatR3FailedRdpmc, "/EM/CPU%d/R3/Interpret/Failed/Rdpmc", "The number of times RDPMC was not interpreted.");
325 EM_REG_COUNTER_USED(&pStats->StatRZFailedRdmsr, "/EM/CPU%d/RZ/Interpret/Failed/Rdmsr", "The number of times RDMSR was not interpreted.");
326 EM_REG_COUNTER_USED(&pStats->StatR3FailedRdmsr, "/EM/CPU%d/R3/Interpret/Failed/Rdmsr", "The number of times RDMSR was not interpreted.");
327 EM_REG_COUNTER_USED(&pStats->StatRZFailedWrmsr, "/EM/CPU%d/RZ/Interpret/Failed/Wrmsr", "The number of times WRMSR was not interpreted.");
328 EM_REG_COUNTER_USED(&pStats->StatR3FailedWrmsr, "/EM/CPU%d/R3/Interpret/Failed/Wrmsr", "The number of times WRMSR was not interpreted.");
329 EM_REG_COUNTER_USED(&pStats->StatRZFailedLmsw, "/EM/CPU%d/RZ/Interpret/Failed/Lmsw", "The number of times LMSW was not interpreted.");
330 EM_REG_COUNTER_USED(&pStats->StatR3FailedLmsw, "/EM/CPU%d/R3/Interpret/Failed/Lmsw", "The number of times LMSW was not interpreted.");
331
332 EM_REG_COUNTER_USED(&pStats->StatRZFailedMisc, "/EM/CPU%d/RZ/Interpret/Failed/Misc", "The number of times some misc instruction was encountered.");
333 EM_REG_COUNTER_USED(&pStats->StatR3FailedMisc, "/EM/CPU%d/R3/Interpret/Failed/Misc", "The number of times some misc instruction was encountered.");
334 EM_REG_COUNTER_USED(&pStats->StatRZFailedAdd, "/EM/CPU%d/RZ/Interpret/Failed/Add", "The number of times ADD was not interpreted.");
335 EM_REG_COUNTER_USED(&pStats->StatR3FailedAdd, "/EM/CPU%d/R3/Interpret/Failed/Add", "The number of times ADD was not interpreted.");
336 EM_REG_COUNTER_USED(&pStats->StatRZFailedAdc, "/EM/CPU%d/RZ/Interpret/Failed/Adc", "The number of times ADC was not interpreted.");
337 EM_REG_COUNTER_USED(&pStats->StatR3FailedAdc, "/EM/CPU%d/R3/Interpret/Failed/Adc", "The number of times ADC was not interpreted.");
338 EM_REG_COUNTER_USED(&pStats->StatRZFailedBtr, "/EM/CPU%d/RZ/Interpret/Failed/Btr", "The number of times BTR was not interpreted.");
339 EM_REG_COUNTER_USED(&pStats->StatR3FailedBtr, "/EM/CPU%d/R3/Interpret/Failed/Btr", "The number of times BTR was not interpreted.");
340 EM_REG_COUNTER_USED(&pStats->StatRZFailedBts, "/EM/CPU%d/RZ/Interpret/Failed/Bts", "The number of times BTS was not interpreted.");
341 EM_REG_COUNTER_USED(&pStats->StatR3FailedBts, "/EM/CPU%d/R3/Interpret/Failed/Bts", "The number of times BTS was not interpreted.");
342 EM_REG_COUNTER_USED(&pStats->StatRZFailedBtc, "/EM/CPU%d/RZ/Interpret/Failed/Btc", "The number of times BTC was not interpreted.");
343 EM_REG_COUNTER_USED(&pStats->StatR3FailedBtc, "/EM/CPU%d/R3/Interpret/Failed/Btc", "The number of times BTC was not interpreted.");
344 EM_REG_COUNTER_USED(&pStats->StatRZFailedCli, "/EM/CPU%d/RZ/Interpret/Failed/Cli", "The number of times CLI was not interpreted.");
345 EM_REG_COUNTER_USED(&pStats->StatR3FailedCli, "/EM/CPU%d/R3/Interpret/Failed/Cli", "The number of times CLI was not interpreted.");
346 EM_REG_COUNTER_USED(&pStats->StatRZFailedCmpXchg, "/EM/CPU%d/RZ/Interpret/Failed/CmpXchg", "The number of times CMPXCHG was not interpreted.");
347 EM_REG_COUNTER_USED(&pStats->StatR3FailedCmpXchg, "/EM/CPU%d/R3/Interpret/Failed/CmpXchg", "The number of times CMPXCHG was not interpreted.");
348 EM_REG_COUNTER_USED(&pStats->StatRZFailedCmpXchg8b, "/EM/CPU%d/RZ/Interpret/Failed/CmpXchg8b", "The number of times CMPXCHG8B was not interpreted.");
349 EM_REG_COUNTER_USED(&pStats->StatR3FailedCmpXchg8b, "/EM/CPU%d/R3/Interpret/Failed/CmpXchg8b", "The number of times CMPXCHG8B was not interpreted.");
350 EM_REG_COUNTER_USED(&pStats->StatRZFailedXAdd, "/EM/CPU%d/RZ/Interpret/Failed/XAdd", "The number of times XADD was not interpreted.");
351 EM_REG_COUNTER_USED(&pStats->StatR3FailedXAdd, "/EM/CPU%d/R3/Interpret/Failed/XAdd", "The number of times XADD was not interpreted.");
352 EM_REG_COUNTER_USED(&pStats->StatRZFailedMovNTPS, "/EM/CPU%d/RZ/Interpret/Failed/MovNTPS", "The number of times MOVNTPS was not interpreted.");
353 EM_REG_COUNTER_USED(&pStats->StatR3FailedMovNTPS, "/EM/CPU%d/R3/Interpret/Failed/MovNTPS", "The number of times MOVNTPS was not interpreted.");
354 EM_REG_COUNTER_USED(&pStats->StatRZFailedStosWD, "/EM/CPU%d/RZ/Interpret/Failed/StosWD", "The number of times STOSWD was not interpreted.");
355 EM_REG_COUNTER_USED(&pStats->StatR3FailedStosWD, "/EM/CPU%d/R3/Interpret/Failed/StosWD", "The number of times STOSWD was not interpreted.");
356 EM_REG_COUNTER_USED(&pStats->StatRZFailedSub, "/EM/CPU%d/RZ/Interpret/Failed/Sub", "The number of times SUB was not interpreted.");
357 EM_REG_COUNTER_USED(&pStats->StatR3FailedSub, "/EM/CPU%d/R3/Interpret/Failed/Sub", "The number of times SUB was not interpreted.");
358 EM_REG_COUNTER_USED(&pStats->StatRZFailedWbInvd, "/EM/CPU%d/RZ/Interpret/Failed/WbInvd", "The number of times WBINVD was not interpreted.");
359 EM_REG_COUNTER_USED(&pStats->StatR3FailedWbInvd, "/EM/CPU%d/R3/Interpret/Failed/WbInvd", "The number of times WBINVD was not interpreted.");
360
361 EM_REG_COUNTER_USED(&pStats->StatRZFailedUserMode, "/EM/CPU%d/RZ/Interpret/Failed/UserMode", "The number of rejections because of CPL.");
362 EM_REG_COUNTER_USED(&pStats->StatR3FailedUserMode, "/EM/CPU%d/R3/Interpret/Failed/UserMode", "The number of rejections because of CPL.");
363 EM_REG_COUNTER_USED(&pStats->StatRZFailedPrefix, "/EM/CPU%d/RZ/Interpret/Failed/Prefix", "The number of rejections because of prefix .");
364 EM_REG_COUNTER_USED(&pStats->StatR3FailedPrefix, "/EM/CPU%d/R3/Interpret/Failed/Prefix", "The number of rejections because of prefix .");
365
366 EM_REG_COUNTER_USED(&pStats->StatCli, "/EM/CPU%d/R3/PrivInst/Cli", "Number of cli instructions.");
367 EM_REG_COUNTER_USED(&pStats->StatSti, "/EM/CPU%d/R3/PrivInst/Sti", "Number of sli instructions.");
368 EM_REG_COUNTER_USED(&pStats->StatIn, "/EM/CPU%d/R3/PrivInst/In", "Number of in instructions.");
369 EM_REG_COUNTER_USED(&pStats->StatOut, "/EM/CPU%d/R3/PrivInst/Out", "Number of out instructions.");
370 EM_REG_COUNTER_USED(&pStats->StatHlt, "/EM/CPU%d/R3/PrivInst/Hlt", "Number of hlt instructions not handled in GC because of PATM.");
371 EM_REG_COUNTER_USED(&pStats->StatInvlpg, "/EM/CPU%d/R3/PrivInst/Invlpg", "Number of invlpg instructions.");
372 EM_REG_COUNTER_USED(&pStats->StatMisc, "/EM/CPU%d/R3/PrivInst/Misc", "Number of misc. instructions.");
373 EM_REG_COUNTER_USED(&pStats->StatMovWriteCR[0], "/EM/CPU%d/R3/PrivInst/Mov CR0, X", "Number of mov CR0 read instructions.");
374 EM_REG_COUNTER_USED(&pStats->StatMovWriteCR[1], "/EM/CPU%d/R3/PrivInst/Mov CR1, X", "Number of mov CR1 read instructions.");
375 EM_REG_COUNTER_USED(&pStats->StatMovWriteCR[2], "/EM/CPU%d/R3/PrivInst/Mov CR2, X", "Number of mov CR2 read instructions.");
376 EM_REG_COUNTER_USED(&pStats->StatMovWriteCR[3], "/EM/CPU%d/R3/PrivInst/Mov CR3, X", "Number of mov CR3 read instructions.");
377 EM_REG_COUNTER_USED(&pStats->StatMovWriteCR[4], "/EM/CPU%d/R3/PrivInst/Mov CR4, X", "Number of mov CR4 read instructions.");
378 EM_REG_COUNTER_USED(&pStats->StatMovReadCR[0], "/EM/CPU%d/R3/PrivInst/Mov X, CR0", "Number of mov CR0 write instructions.");
379 EM_REG_COUNTER_USED(&pStats->StatMovReadCR[1], "/EM/CPU%d/R3/PrivInst/Mov X, CR1", "Number of mov CR1 write instructions.");
380 EM_REG_COUNTER_USED(&pStats->StatMovReadCR[2], "/EM/CPU%d/R3/PrivInst/Mov X, CR2", "Number of mov CR2 write instructions.");
381 EM_REG_COUNTER_USED(&pStats->StatMovReadCR[3], "/EM/CPU%d/R3/PrivInst/Mov X, CR3", "Number of mov CR3 write instructions.");
382 EM_REG_COUNTER_USED(&pStats->StatMovReadCR[4], "/EM/CPU%d/R3/PrivInst/Mov X, CR4", "Number of mov CR4 write instructions.");
383 EM_REG_COUNTER_USED(&pStats->StatMovDRx, "/EM/CPU%d/R3/PrivInst/MovDRx", "Number of mov DRx instructions.");
384 EM_REG_COUNTER_USED(&pStats->StatIret, "/EM/CPU%d/R3/PrivInst/Iret", "Number of iret instructions.");
385 EM_REG_COUNTER_USED(&pStats->StatMovLgdt, "/EM/CPU%d/R3/PrivInst/Lgdt", "Number of lgdt instructions.");
386 EM_REG_COUNTER_USED(&pStats->StatMovLidt, "/EM/CPU%d/R3/PrivInst/Lidt", "Number of lidt instructions.");
387 EM_REG_COUNTER_USED(&pStats->StatMovLldt, "/EM/CPU%d/R3/PrivInst/Lldt", "Number of lldt instructions.");
388 EM_REG_COUNTER_USED(&pStats->StatSysEnter, "/EM/CPU%d/R3/PrivInst/Sysenter", "Number of sysenter instructions.");
389 EM_REG_COUNTER_USED(&pStats->StatSysExit, "/EM/CPU%d/R3/PrivInst/Sysexit", "Number of sysexit instructions.");
390 EM_REG_COUNTER_USED(&pStats->StatSysCall, "/EM/CPU%d/R3/PrivInst/Syscall", "Number of syscall instructions.");
391 EM_REG_COUNTER_USED(&pStats->StatSysRet, "/EM/CPU%d/R3/PrivInst/Sysret", "Number of sysret instructions.");
392
393 EM_REG_COUNTER(&pVCpu->em.s.StatTotalClis, "/EM/CPU%d/Cli/Total", "Total number of cli instructions executed.");
394 pVCpu->em.s.pCliStatTree = 0;
395
396 /* these should be considered for release statistics. */
397 EM_REG_COUNTER(&pVCpu->em.s.StatIOEmu, "/PROF/CPU%d/EM/Emulation/IO", "Profiling of emR3RawExecuteIOInstruction.");
398 EM_REG_COUNTER(&pVCpu->em.s.StatPrivEmu, "/PROF/CPU%d/EM/Emulation/Priv", "Profiling of emR3RawPrivileged.");
399 EM_REG_COUNTER(&pVCpu->em.s.StatMiscEmu, "/PROF/CPU%d/EM/Emulation/Misc", "Profiling of emR3RawExecuteInstruction.");
400 EM_REG_PROFILE(&pVCpu->em.s.StatHwAccEntry, "/PROF/CPU%d/EM/HwAccEnter", "Profiling Hardware Accelerated Mode entry overhead.");
401 EM_REG_PROFILE(&pVCpu->em.s.StatHwAccExec, "/PROF/CPU%d/EM/HwAccExec", "Profiling Hardware Accelerated Mode execution.");
402 EM_REG_PROFILE(&pVCpu->em.s.StatREMEmu, "/PROF/CPU%d/EM/REMEmuSingle", "Profiling single instruction REM execution.");
403 EM_REG_PROFILE(&pVCpu->em.s.StatREMExec, "/PROF/CPU%d/EM/REMExec", "Profiling REM execution.");
404 EM_REG_PROFILE(&pVCpu->em.s.StatREMSync, "/PROF/CPU%d/EM/REMSync", "Profiling REM context syncing.");
405 EM_REG_PROFILE(&pVCpu->em.s.StatRAWEntry, "/PROF/CPU%d/EM/RAWEnter", "Profiling Raw Mode entry overhead.");
406 EM_REG_PROFILE(&pVCpu->em.s.StatRAWExec, "/PROF/CPU%d/EM/RAWExec", "Profiling Raw Mode execution.");
407 EM_REG_PROFILE(&pVCpu->em.s.StatRAWTail, "/PROF/CPU%d/EM/RAWTail", "Profiling Raw Mode tail overhead.");
408
409#endif /* VBOX_WITH_STATISTICS */
410
411 EM_REG_COUNTER(&pVCpu->em.s.StatForcedActions, "/PROF/CPU%d/EM/ForcedActions", "Profiling forced action execution.");
412 EM_REG_COUNTER(&pVCpu->em.s.StatHalted, "/PROF/CPU%d/EM/Halted", "Profiling halted state (VMR3WaitHalted).");
413 EM_REG_COUNTER(&pVCpu->em.s.StatREMTotal, "/PROF/CPU%d/EM/REMTotal", "Profiling emR3RemExecute (excluding FFs).");
414 EM_REG_COUNTER(&pVCpu->em.s.StatRAWTotal, "/PROF/CPU%d/EM/RAWTotal", "Profiling emR3RawExecute (excluding FFs).");
415
416 EM_REG_PROFILE_ADV(&pVCpu->em.s.StatTotal, "/PROF/CPU%d/EM/Total", "Profiling EMR3ExecuteVM.");
417 }
418
419 return VINF_SUCCESS;
420}
421
422
423/**
424 * Initializes the per-VCPU EM.
425 *
426 * @returns VBox status code.
427 * @param pVM The VM to operate on.
428 */
429VMMR3DECL(int) EMR3InitCPU(PVM pVM)
430{
431 LogFlow(("EMR3InitCPU\n"));
432 return VINF_SUCCESS;
433}
434
435
436/**
437 * Applies relocations to data and code managed by this
438 * component. This function will be called at init and
439 * whenever the VMM need to relocate it self inside the GC.
440 *
441 * @param pVM The VM.
442 */
443VMMR3DECL(void) EMR3Relocate(PVM pVM)
444{
445 LogFlow(("EMR3Relocate\n"));
446 for (unsigned i=0;i<pVM->cCPUs;i++)
447 {
448 PVMCPU pVCpu = &pVM->aCpus[i];
449
450 if (pVCpu->em.s.pStatsR3)
451 pVCpu->em.s.pStatsRC = MMHyperR3ToRC(pVM, pVCpu->em.s.pStatsR3);
452 }
453}
454
455
456/**
457 * Reset notification.
458 *
459 * @param pVM
460 */
461VMMR3DECL(void) EMR3Reset(PVM pVM)
462{
463 LogFlow(("EMR3Reset: \n"));
464 for (unsigned i=0;i<pVM->cCPUs;i++)
465 {
466 PVMCPU pVCpu = &pVM->aCpus[i];
467
468 pVCpu->em.s.fForceRAW = false;
469 }
470}
471
472
473/**
474 * Terminates the EM.
475 *
476 * Termination means cleaning up and freeing all resources,
477 * the VM it self is at this point powered off or suspended.
478 *
479 * @returns VBox status code.
480 * @param pVM The VM to operate on.
481 */
482VMMR3DECL(int) EMR3Term(PVM pVM)
483{
484 AssertMsg(pVM->em.s.offVM, ("bad init order!\n"));
485
486 PDMR3CritSectDelete(&pVM->em.s.CritSectREM);
487 return VINF_SUCCESS;
488}
489
490/**
491 * Terminates the per-VCPU EM.
492 *
493 * Termination means cleaning up and freeing all resources,
494 * the VM it self is at this point powered off or suspended.
495 *
496 * @returns VBox status code.
497 * @param pVM The VM to operate on.
498 */
499VMMR3DECL(int) EMR3TermCPU(PVM pVM)
500{
501 return 0;
502}
503
504/**
505 * Execute state save operation.
506 *
507 * @returns VBox status code.
508 * @param pVM VM Handle.
509 * @param pSSM SSM operation handle.
510 */
511static DECLCALLBACK(int) emR3Save(PVM pVM, PSSMHANDLE pSSM)
512{
513 for (VMCPUID i = 0; i < pVM->cCPUs; i++)
514 {
515 PVMCPU pVCpu = &pVM->aCpus[i];
516
517 int rc = SSMR3PutBool(pSSM, pVCpu->em.s.fForceRAW);
518 AssertRCReturn(rc, rc);
519
520 Assert(pVCpu->em.s.enmState == EMSTATE_SUSPENDED);
521 Assert(pVCpu->em.s.enmPrevState != EMSTATE_SUSPENDED);
522 rc = SSMR3PutU32(pSSM, pVCpu->em.s.enmPrevState);
523 AssertRCReturn(rc, rc);
524 }
525 return VINF_SUCCESS;
526}
527
528
529/**
530 * Execute state load operation.
531 *
532 * @returns VBox status code.
533 * @param pVM VM Handle.
534 * @param pSSM SSM operation handle.
535 * @param u32Version Data layout version.
536 */
537static DECLCALLBACK(int) emR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
538{
539 int rc = VINF_SUCCESS;
540
541 /*
542 * Validate version.
543 */
544 if ( u32Version != EM_SAVED_STATE_VERSION
545 && u32Version != EM_SAVED_STATE_VERSION_PRE_SMP)
546 {
547 AssertMsgFailed(("emR3Load: Invalid version u32Version=%d (current %d)!\n", u32Version, EM_SAVED_STATE_VERSION));
548 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
549 }
550
551 /*
552 * Load the saved state.
553 */
554 for (VMCPUID i = 0; i < pVM->cCPUs; i++)
555 {
556 PVMCPU pVCpu = &pVM->aCpus[i];
557
558 rc = SSMR3GetBool(pSSM, &pVCpu->em.s.fForceRAW);
559 if (RT_FAILURE(rc))
560 pVCpu->em.s.fForceRAW = false;
561
562 if (u32Version > EM_SAVED_STATE_VERSION_PRE_SMP)
563 {
564 AssertCompile(sizeof(pVCpu->em.s.enmPrevState) == sizeof(uint32_t));
565 rc = SSMR3GetU32(pSSM, (uint32_t *)&pVCpu->em.s.enmPrevState);
566 AssertRCReturn(rc, rc);
567 Assert(pVCpu->em.s.enmPrevState != EMSTATE_SUSPENDED);
568
569 pVCpu->em.s.enmState = EMSTATE_SUSPENDED;
570 }
571 Assert(!pVCpu->em.s.pCliStatTree);
572 }
573 return rc;
574}
575
576
577/**
578 * Enables or disables a set of raw-mode execution modes.
579 *
580 * @returns VINF_SUCCESS on success.
581 * @returns VINF_RESCHEDULE if a rescheduling might be required.
582 * @returns VERR_INVALID_PARAMETER on an invalid enmMode value.
583 *
584 * @param pVM The VM to operate on.
585 * @param enmMode The execution mode change.
586 * @thread The emulation thread.
587 */
588VMMR3DECL(int) EMR3RawSetMode(PVM pVM, EMRAWMODE enmMode)
589{
590 switch (enmMode)
591 {
592 case EMRAW_NONE:
593 pVM->fRawR3Enabled = false;
594 pVM->fRawR0Enabled = false;
595 break;
596 case EMRAW_RING3_ENABLE:
597 pVM->fRawR3Enabled = true;
598 break;
599 case EMRAW_RING3_DISABLE:
600 pVM->fRawR3Enabled = false;
601 break;
602 case EMRAW_RING0_ENABLE:
603 pVM->fRawR0Enabled = true;
604 break;
605 case EMRAW_RING0_DISABLE:
606 pVM->fRawR0Enabled = false;
607 break;
608 default:
609 AssertMsgFailed(("Invalid enmMode=%d\n", enmMode));
610 return VERR_INVALID_PARAMETER;
611 }
612 Log(("EMR3SetRawMode: fRawR3Enabled=%RTbool fRawR0Enabled=%RTbool\n",
613 pVM->fRawR3Enabled, pVM->fRawR0Enabled));
614 return pVM->aCpus[0].em.s.enmState == EMSTATE_RAW ? VINF_EM_RESCHEDULE : VINF_SUCCESS;
615}
616
617
618/**
619 * Raise a fatal error.
620 *
621 * Safely terminate the VM with full state report and stuff. This function
622 * will naturally never return.
623 *
624 * @param pVCpu VMCPU handle.
625 * @param rc VBox status code.
626 */
627VMMR3DECL(void) EMR3FatalError(PVMCPU pVCpu, int rc)
628{
629 longjmp(pVCpu->em.s.u.FatalLongJump, rc);
630 AssertReleaseMsgFailed(("longjmp returned!\n"));
631}
632
633
634/**
635 * Gets the EM state name.
636 *
637 * @returns pointer to read only state name,
638 * @param enmState The state.
639 */
640VMMR3DECL(const char *) EMR3GetStateName(EMSTATE enmState)
641{
642 switch (enmState)
643 {
644 case EMSTATE_NONE: return "EMSTATE_NONE";
645 case EMSTATE_RAW: return "EMSTATE_RAW";
646 case EMSTATE_HWACC: return "EMSTATE_HWACC";
647 case EMSTATE_REM: return "EMSTATE_REM";
648 case EMSTATE_PARAV: return "EMSTATE_PARAV";
649 case EMSTATE_HALTED: return "EMSTATE_HALTED";
650 case EMSTATE_WAIT_SIPI: return "EMSTATE_WAIT_SIPI";
651 case EMSTATE_SUSPENDED: return "EMSTATE_SUSPENDED";
652 case EMSTATE_TERMINATING: return "EMSTATE_TERMINATING";
653 case EMSTATE_DEBUG_GUEST_RAW: return "EMSTATE_DEBUG_GUEST_RAW";
654 case EMSTATE_DEBUG_GUEST_REM: return "EMSTATE_DEBUG_GUEST_REM";
655 case EMSTATE_DEBUG_HYPER: return "EMSTATE_DEBUG_HYPER";
656 case EMSTATE_GURU_MEDITATION: return "EMSTATE_GURU_MEDITATION";
657 default: return "Unknown!";
658 }
659}
660
661
662#ifdef VBOX_WITH_STATISTICS
663/**
664 * Just a braindead function to keep track of cli addresses.
665 * @param pVM VM handle.
666 * @param pVMCPU VMCPU handle.
667 * @param GCPtrInstr The EIP of the cli instruction.
668 */
669static void emR3RecordCli(PVM pVM, PVMCPU pVCpu, RTGCPTR GCPtrInstr)
670{
671 PCLISTAT pRec;
672
673 pRec = (PCLISTAT)RTAvlPVGet(&pVCpu->em.s.pCliStatTree, (AVLPVKEY)GCPtrInstr);
674 if (!pRec)
675 {
676 /* New cli instruction; insert into the tree. */
677 pRec = (PCLISTAT)MMR3HeapAllocZ(pVM, MM_TAG_EM, sizeof(*pRec));
678 Assert(pRec);
679 if (!pRec)
680 return;
681 pRec->Core.Key = (AVLPVKEY)GCPtrInstr;
682
683 char szCliStatName[32];
684 RTStrPrintf(szCliStatName, sizeof(szCliStatName), "/EM/Cli/0x%RGv", GCPtrInstr);
685 STAM_REG(pVM, &pRec->Counter, STAMTYPE_COUNTER, szCliStatName, STAMUNIT_OCCURENCES, "Number of times cli was executed.");
686
687 bool fRc = RTAvlPVInsert(&pVCpu->em.s.pCliStatTree, &pRec->Core);
688 Assert(fRc); NOREF(fRc);
689 }
690 STAM_COUNTER_INC(&pRec->Counter);
691 STAM_COUNTER_INC(&pVCpu->em.s.StatTotalClis);
692}
693#endif /* VBOX_WITH_STATISTICS */
694
695
696/**
697 * Debug loop.
698 *
699 * @returns VBox status code for EM.
700 * @param pVM VM handle.
701 * @param pVCpu VMCPU handle.
702 * @param rc Current EM VBox status code..
703 */
704static int emR3Debug(PVM pVM, PVMCPU pVCpu, int rc)
705{
706 for (;;)
707 {
708 Log(("emR3Debug: rc=%Rrc\n", rc));
709 const int rcLast = rc;
710
711 /*
712 * Debug related RC.
713 */
714 switch (rc)
715 {
716 /*
717 * Single step an instruction.
718 */
719 case VINF_EM_DBG_STEP:
720 if ( pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_RAW
721 || pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER
722 || pVCpu->em.s.fForceRAW /* paranoia */)
723 rc = emR3RawStep(pVM, pVCpu);
724 else
725 {
726 Assert(pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_REM);
727 rc = emR3RemStep(pVM, pVCpu);
728 }
729 break;
730
731 /*
732 * Simple events: stepped, breakpoint, stop/assertion.
733 */
734 case VINF_EM_DBG_STEPPED:
735 rc = DBGFR3Event(pVM, DBGFEVENT_STEPPED);
736 break;
737
738 case VINF_EM_DBG_BREAKPOINT:
739 rc = DBGFR3EventBreakpoint(pVM, DBGFEVENT_BREAKPOINT);
740 break;
741
742 case VINF_EM_DBG_STOP:
743 rc = DBGFR3EventSrc(pVM, DBGFEVENT_DEV_STOP, NULL, 0, NULL, NULL);
744 break;
745
746 case VINF_EM_DBG_HYPER_STEPPED:
747 rc = DBGFR3Event(pVM, DBGFEVENT_STEPPED_HYPER);
748 break;
749
750 case VINF_EM_DBG_HYPER_BREAKPOINT:
751 rc = DBGFR3EventBreakpoint(pVM, DBGFEVENT_BREAKPOINT_HYPER);
752 break;
753
754 case VINF_EM_DBG_HYPER_ASSERTION:
755 RTPrintf("\nVINF_EM_DBG_HYPER_ASSERTION:\n%s%s\n", VMMR3GetRZAssertMsg1(pVM), VMMR3GetRZAssertMsg2(pVM));
756 rc = DBGFR3EventAssertion(pVM, DBGFEVENT_ASSERTION_HYPER, VMMR3GetRZAssertMsg1(pVM), VMMR3GetRZAssertMsg2(pVM));
757 break;
758
759 /*
760 * Guru meditation.
761 */
762 case VERR_VMM_RING0_ASSERTION: /** @todo Make a guru meditation event! */
763 rc = DBGFR3EventSrc(pVM, DBGFEVENT_FATAL_ERROR, "VERR_VMM_RING0_ASSERTION", 0, NULL, NULL);
764 break;
765 case VERR_REM_TOO_MANY_TRAPS: /** @todo Make a guru meditation event! */
766 rc = DBGFR3EventSrc(pVM, DBGFEVENT_DEV_STOP, "VERR_REM_TOO_MANY_TRAPS", 0, NULL, NULL);
767 break;
768
769 default: /** @todo don't use default for guru, but make special errors code! */
770 rc = DBGFR3Event(pVM, DBGFEVENT_FATAL_ERROR);
771 break;
772 }
773
774 /*
775 * Process the result.
776 */
777 do
778 {
779 switch (rc)
780 {
781 /*
782 * Continue the debugging loop.
783 */
784 case VINF_EM_DBG_STEP:
785 case VINF_EM_DBG_STOP:
786 case VINF_EM_DBG_STEPPED:
787 case VINF_EM_DBG_BREAKPOINT:
788 case VINF_EM_DBG_HYPER_STEPPED:
789 case VINF_EM_DBG_HYPER_BREAKPOINT:
790 case VINF_EM_DBG_HYPER_ASSERTION:
791 break;
792
793 /*
794 * Resuming execution (in some form) has to be done here if we got
795 * a hypervisor debug event.
796 */
797 case VINF_SUCCESS:
798 case VINF_EM_RESUME:
799 case VINF_EM_SUSPEND:
800 case VINF_EM_RESCHEDULE:
801 case VINF_EM_RESCHEDULE_RAW:
802 case VINF_EM_RESCHEDULE_REM:
803 case VINF_EM_HALT:
804 if (pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER)
805 {
806 rc = emR3RawResumeHyper(pVM, pVCpu);
807 if (rc != VINF_SUCCESS && RT_SUCCESS(rc))
808 continue;
809 }
810 if (rc == VINF_SUCCESS)
811 rc = VINF_EM_RESCHEDULE;
812 return rc;
813
814 /*
815 * The debugger isn't attached.
816 * We'll simply turn the thing off since that's the easiest thing to do.
817 */
818 case VERR_DBGF_NOT_ATTACHED:
819 switch (rcLast)
820 {
821 case VINF_EM_DBG_HYPER_STEPPED:
822 case VINF_EM_DBG_HYPER_BREAKPOINT:
823 case VINF_EM_DBG_HYPER_ASSERTION:
824 case VERR_TRPM_PANIC:
825 case VERR_TRPM_DONT_PANIC:
826 case VERR_VMM_RING0_ASSERTION:
827 return rcLast;
828 }
829 return VINF_EM_OFF;
830
831 /*
832 * Status codes terminating the VM in one or another sense.
833 */
834 case VINF_EM_TERMINATE:
835 case VINF_EM_OFF:
836 case VINF_EM_RESET:
837 case VINF_EM_NO_MEMORY:
838 case VINF_EM_RAW_STALE_SELECTOR:
839 case VINF_EM_RAW_IRET_TRAP:
840 case VERR_TRPM_PANIC:
841 case VERR_TRPM_DONT_PANIC:
842 case VERR_VMM_RING0_ASSERTION:
843 case VERR_INTERNAL_ERROR:
844 case VERR_INTERNAL_ERROR_2:
845 case VERR_INTERNAL_ERROR_3:
846 case VERR_INTERNAL_ERROR_4:
847 case VERR_INTERNAL_ERROR_5:
848 case VERR_IPE_UNEXPECTED_STATUS:
849 case VERR_IPE_UNEXPECTED_INFO_STATUS:
850 case VERR_IPE_UNEXPECTED_ERROR_STATUS:
851 return rc;
852
853 /*
854 * The rest is unexpected, and will keep us here.
855 */
856 default:
857 AssertMsgFailed(("Unxpected rc %Rrc!\n", rc));
858 break;
859 }
860 } while (false);
861 } /* debug for ever */
862}
863
864/**
865 * Locks REM execution to a single VCpu
866 *
867 * @param pVM VM handle.
868 */
869VMMR3DECL(void) EMR3RemLock(PVM pVM)
870{
871 if (!PDMCritSectIsInitialized(&pVM->em.s.CritSectREM))
872 return; /* early init */
873
874 int rc = PDMCritSectEnter(&pVM->em.s.CritSectREM, VERR_SEM_BUSY);
875 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
876}
877
878/**
879 * Unlocks REM execution
880 *
881 * @param pVM VM handle.
882 */
883VMMR3DECL(void) EMR3RemUnlock(PVM pVM)
884{
885 if (!PDMCritSectIsInitialized(&pVM->em.s.CritSectREM))
886 return; /* early init */
887
888 PDMCritSectLeave(&pVM->em.s.CritSectREM);
889}
890
891/**
892 * Check if this VCPU currently owns the REM lock.
893 *
894 * @returns bool owner/not owner
895 * @param pVM The VM to operate on.
896 */
897VMMR3DECL(bool) EMR3RemIsLockOwner(PVM pVM)
898{
899 return PDMCritSectIsOwner(&pVM->em.s.CritSectREM);
900}
901
902/**
903 * Steps recompiled code.
904 *
905 * @returns VBox status code. The most important ones are: VINF_EM_STEP_EVENT,
906 * VINF_EM_RESCHEDULE, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
907 *
908 * @param pVM VM handle.
909 * @param pVCpu VMCPU handle.
910 */
911static int emR3RemStep(PVM pVM, PVMCPU pVCpu)
912{
913 LogFlow(("emR3RemStep: cs:eip=%04x:%08x\n", CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
914
915 EMR3RemLock(pVM);
916
917 /*
918 * Switch to REM, step instruction, switch back.
919 */
920 int rc = REMR3State(pVM, pVCpu);
921 if (RT_SUCCESS(rc))
922 {
923 rc = REMR3Step(pVM, pVCpu);
924 REMR3StateBack(pVM, pVCpu);
925 }
926 EMR3RemUnlock(pVM);
927
928 LogFlow(("emR3RemStep: returns %Rrc cs:eip=%04x:%08x\n", rc, CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
929 return rc;
930}
931
932
933/**
934 * Executes recompiled code.
935 *
936 * This function contains the recompiler version of the inner
937 * execution loop (the outer loop being in EMR3ExecuteVM()).
938 *
939 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE,
940 * VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
941 *
942 * @param pVM VM handle.
943 * @param pVCpu VMCPU handle.
944 * @param pfFFDone Where to store an indicator telling wheter or not
945 * FFs were done before returning.
946 *
947 */
948static int emR3RemExecute(PVM pVM, PVMCPU pVCpu, bool *pfFFDone)
949{
950#ifdef LOG_ENABLED
951 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
952 uint32_t cpl = CPUMGetGuestCPL(pVCpu, CPUMCTX2CORE(pCtx));
953
954 if (pCtx->eflags.Bits.u1VM)
955 Log(("EMV86: %04X:%08X IF=%d\n", pCtx->cs, pCtx->eip, pCtx->eflags.Bits.u1IF));
956 else
957 Log(("EMR%d: %04X:%08X ESP=%08X IF=%d CR0=%x\n", cpl, pCtx->cs, pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, (uint32_t)pCtx->cr0));
958#endif
959 STAM_REL_PROFILE_ADV_START(&pVCpu->em.s.StatREMTotal, a);
960
961#if defined(VBOX_STRICT) && defined(DEBUG_bird)
962 AssertMsg( VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL)
963 || !MMHyperIsInsideArea(pVM, CPUMGetGuestEIP(pVCpu)), /** @todo #1419 - get flat address. */
964 ("cs:eip=%RX16:%RX32\n", CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
965#endif
966
967 /* Big lock, but you are not supposed to own any lock when coming in here. */
968 EMR3RemLock(pVM);
969
970 /*
971 * Spin till we get a forced action which returns anything but VINF_SUCCESS
972 * or the REM suggests raw-mode execution.
973 */
974 *pfFFDone = false;
975 bool fInREMState = false;
976 int rc = VINF_SUCCESS;
977
978 /* Flush the recompiler TLB if the VCPU has changed. */
979 if (pVM->em.s.idLastRemCpu != pVCpu->idCpu)
980 {
981 REMFlushTBs(pVM);
982 /* Also sync the entire state. */
983 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_ALL);
984 }
985 pVM->em.s.idLastRemCpu = pVCpu->idCpu;
986
987 for (;;)
988 {
989 /*
990 * Update REM state if not already in sync.
991 */
992 if (!fInREMState)
993 {
994 STAM_PROFILE_START(&pVCpu->em.s.StatREMSync, b);
995 rc = REMR3State(pVM, pVCpu);
996 STAM_PROFILE_STOP(&pVCpu->em.s.StatREMSync, b);
997 if (RT_FAILURE(rc))
998 break;
999 fInREMState = true;
1000
1001 /*
1002 * We might have missed the raising of VMREQ, TIMER and some other
1003 * imporant FFs while we were busy switching the state. So, check again.
1004 */
1005 if ( VM_FF_ISPENDING(pVM, VM_FF_REQUEST | VM_FF_PDM_QUEUES | VM_FF_DBGF | VM_FF_TERMINATE | VM_FF_RESET)
1006 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TIMER | VMCPU_FF_REQUEST))
1007 {
1008 LogFlow(("emR3RemExecute: Skipping run, because FF is set. %#x\n", pVM->fGlobalForcedActions));
1009 goto l_REMDoForcedActions;
1010 }
1011 }
1012
1013
1014 /*
1015 * Execute REM.
1016 */
1017 STAM_PROFILE_START(&pVCpu->em.s.StatREMExec, c);
1018 rc = REMR3Run(pVM, pVCpu);
1019 STAM_PROFILE_STOP(&pVCpu->em.s.StatREMExec, c);
1020
1021
1022 /*
1023 * Deal with high priority post execution FFs before doing anything else.
1024 */
1025 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK)
1026 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_POST_MASK))
1027 rc = emR3HighPriorityPostForcedActions(pVM, pVCpu, rc);
1028
1029 /*
1030 * Process the returned status code.
1031 * (Try keep this short! Call functions!)
1032 */
1033 if (rc != VINF_SUCCESS)
1034 {
1035 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
1036 break;
1037 if (rc != VINF_REM_INTERRUPED_FF)
1038 {
1039 /*
1040 * Anything which is not known to us means an internal error
1041 * and the termination of the VM!
1042 */
1043 AssertMsg(rc == VERR_REM_TOO_MANY_TRAPS, ("Unknown GC return code: %Rra\n", rc));
1044 break;
1045 }
1046 }
1047
1048
1049 /*
1050 * Check and execute forced actions.
1051 * Sync back the VM state before calling any of these.
1052 */
1053#ifdef VBOX_HIGH_RES_TIMERS_HACK
1054 TMTimerPollVoid(pVM, pVCpu);
1055#endif
1056 AssertCompile((VMCPU_FF_ALL_BUT_RAW_MASK & ~(VMCPU_FF_CSAM_PENDING_ACTION | VMCPU_FF_CSAM_SCAN_PAGE)) & VMCPU_FF_TIMER);
1057 if ( VM_FF_ISPENDING(pVM, VM_FF_ALL_BUT_RAW_MASK)
1058 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_ALL_BUT_RAW_MASK & ~(VMCPU_FF_CSAM_PENDING_ACTION | VMCPU_FF_CSAM_SCAN_PAGE)))
1059 {
1060l_REMDoForcedActions:
1061 if (fInREMState)
1062 {
1063 STAM_PROFILE_START(&pVCpu->em.s.StatREMSync, d);
1064 REMR3StateBack(pVM, pVCpu);
1065 STAM_PROFILE_STOP(&pVCpu->em.s.StatREMSync, d);
1066 fInREMState = false;
1067 }
1068 STAM_REL_PROFILE_ADV_SUSPEND(&pVCpu->em.s.StatREMTotal, a);
1069 rc = emR3ForcedActions(pVM, pVCpu, rc);
1070 STAM_REL_PROFILE_ADV_RESUME(&pVCpu->em.s.StatREMTotal, a);
1071 if ( rc != VINF_SUCCESS
1072 && rc != VINF_EM_RESCHEDULE_REM)
1073 {
1074 *pfFFDone = true;
1075 break;
1076 }
1077 }
1078
1079 } /* The Inner Loop, recompiled execution mode version. */
1080
1081
1082 /*
1083 * Returning. Sync back the VM state if required.
1084 */
1085 if (fInREMState)
1086 {
1087 STAM_PROFILE_START(&pVCpu->em.s.StatREMSync, e);
1088 REMR3StateBack(pVM, pVCpu);
1089 STAM_PROFILE_STOP(&pVCpu->em.s.StatREMSync, e);
1090 }
1091 EMR3RemUnlock(pVM);
1092
1093 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatREMTotal, a);
1094 return rc;
1095}
1096
1097
1098/**
1099 * Resumes executing hypervisor after a debug event.
1100 *
1101 * This is kind of special since our current guest state is
1102 * potentially out of sync.
1103 *
1104 * @returns VBox status code.
1105 * @param pVM The VM handle.
1106 * @param pVCpu The VMCPU handle.
1107 */
1108static int emR3RawResumeHyper(PVM pVM, PVMCPU pVCpu)
1109{
1110 int rc;
1111 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1112 Assert(pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER);
1113 Log(("emR3RawResumeHyper: cs:eip=%RTsel:%RGr efl=%RGr\n", pCtx->cs, pCtx->eip, pCtx->eflags));
1114
1115 /*
1116 * Resume execution.
1117 */
1118 CPUMRawEnter(pVCpu, NULL);
1119 CPUMSetHyperEFlags(pVCpu, CPUMGetHyperEFlags(pVCpu) | X86_EFL_RF);
1120 rc = VMMR3ResumeHyper(pVM, pVCpu);
1121 Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr - returned from GC with rc=%Rrc\n", pCtx->cs, pCtx->eip, pCtx->eflags, rc));
1122 rc = CPUMRawLeave(pVCpu, NULL, rc);
1123 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
1124
1125 /*
1126 * Deal with the return code.
1127 */
1128 rc = emR3HighPriorityPostForcedActions(pVM, pVCpu, rc);
1129 rc = emR3RawHandleRC(pVM, pVCpu, pCtx, rc);
1130 rc = emR3RawUpdateForceFlag(pVM, pVCpu, pCtx, rc);
1131 return rc;
1132}
1133
1134
1135/**
1136 * Steps rawmode.
1137 *
1138 * @returns VBox status code.
1139 * @param pVM The VM handle.
1140 * @param pVCpu The VMCPU handle.
1141 */
1142static int emR3RawStep(PVM pVM, PVMCPU pVCpu)
1143{
1144 Assert( pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER
1145 || pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_RAW
1146 || pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_REM);
1147 int rc;
1148 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1149 bool fGuest = pVCpu->em.s.enmState != EMSTATE_DEBUG_HYPER;
1150#ifndef DEBUG_sandervl
1151 Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr\n", fGuest ? CPUMGetGuestCS(pVCpu) : CPUMGetHyperCS(pVCpu),
1152 fGuest ? CPUMGetGuestEIP(pVCpu) : CPUMGetHyperEIP(pVCpu), fGuest ? CPUMGetGuestEFlags(pVCpu) : CPUMGetHyperEFlags(pVCpu)));
1153#endif
1154 if (fGuest)
1155 {
1156 /*
1157 * Check vital forced actions, but ignore pending interrupts and timers.
1158 */
1159 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
1160 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
1161 {
1162 rc = emR3RawForcedActions(pVM, pVCpu, pCtx);
1163 if (rc != VINF_SUCCESS)
1164 return rc;
1165 }
1166
1167 /*
1168 * Set flags for single stepping.
1169 */
1170 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) | X86_EFL_TF | X86_EFL_RF);
1171 }
1172 else
1173 CPUMSetHyperEFlags(pVCpu, CPUMGetHyperEFlags(pVCpu) | X86_EFL_TF | X86_EFL_RF);
1174
1175 /*
1176 * Single step.
1177 * We do not start time or anything, if anything we should just do a few nanoseconds.
1178 */
1179 CPUMRawEnter(pVCpu, NULL);
1180 do
1181 {
1182 if (pVCpu->em.s.enmState == EMSTATE_DEBUG_HYPER)
1183 rc = VMMR3ResumeHyper(pVM, pVCpu);
1184 else
1185 rc = VMMR3RawRunGC(pVM, pVCpu);
1186#ifndef DEBUG_sandervl
1187 Log(("emR3RawStep: cs:eip=%RTsel:%RGr efl=%RGr - GC rc %Rrc\n", fGuest ? CPUMGetGuestCS(pVCpu) : CPUMGetHyperCS(pVCpu),
1188 fGuest ? CPUMGetGuestEIP(pVCpu) : CPUMGetHyperEIP(pVCpu), fGuest ? CPUMGetGuestEFlags(pVCpu) : CPUMGetHyperEFlags(pVCpu), rc));
1189#endif
1190 } while ( rc == VINF_SUCCESS
1191 || rc == VINF_EM_RAW_INTERRUPT);
1192 rc = CPUMRawLeave(pVCpu, NULL, rc);
1193 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
1194
1195 /*
1196 * Make sure the trap flag is cleared.
1197 * (Too bad if the guest is trying to single step too.)
1198 */
1199 if (fGuest)
1200 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
1201 else
1202 CPUMSetHyperEFlags(pVCpu, CPUMGetHyperEFlags(pVCpu) & ~X86_EFL_TF);
1203
1204 /*
1205 * Deal with the return codes.
1206 */
1207 rc = emR3HighPriorityPostForcedActions(pVM, pVCpu, rc);
1208 rc = emR3RawHandleRC(pVM, pVCpu, pCtx, rc);
1209 rc = emR3RawUpdateForceFlag(pVM, pVCpu, pCtx, rc);
1210 return rc;
1211}
1212
1213
1214#ifdef DEBUG
1215
1216/**
1217 * Steps hardware accelerated mode.
1218 *
1219 * @returns VBox status code.
1220 * @param pVM The VM handle.
1221 * @param pVCpu The VMCPU handle.
1222 */
1223static int emR3HwAccStep(PVM pVM, PVMCPU pVCpu)
1224{
1225 Assert(pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_HWACC);
1226
1227 int rc;
1228 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1229 VMCPU_FF_CLEAR(pVCpu, (VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT | VMCPU_FF_TRPM_SYNC_IDT | VMCPU_FF_SELM_SYNC_TSS));
1230
1231 /*
1232 * Check vital forced actions, but ignore pending interrupts and timers.
1233 */
1234 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
1235 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
1236 {
1237 rc = emR3RawForcedActions(pVM, pVCpu, pCtx);
1238 if (rc != VINF_SUCCESS)
1239 return rc;
1240 }
1241 /*
1242 * Set flags for single stepping.
1243 */
1244 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) | X86_EFL_TF | X86_EFL_RF);
1245
1246 /*
1247 * Single step.
1248 * We do not start time or anything, if anything we should just do a few nanoseconds.
1249 */
1250 do
1251 {
1252 rc = VMMR3HwAccRunGC(pVM, pVCpu);
1253 } while ( rc == VINF_SUCCESS
1254 || rc == VINF_EM_RAW_INTERRUPT);
1255 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
1256
1257 /*
1258 * Make sure the trap flag is cleared.
1259 * (Too bad if the guest is trying to single step too.)
1260 */
1261 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
1262
1263 /*
1264 * Deal with the return codes.
1265 */
1266 rc = emR3HighPriorityPostForcedActions(pVM, pVCpu, rc);
1267 rc = emR3RawHandleRC(pVM, pVCpu, pCtx, rc);
1268 rc = emR3RawUpdateForceFlag(pVM, pVCpu, pCtx, rc);
1269 return rc;
1270}
1271
1272
1273int emR3SingleStepExecRaw(PVM pVM, PVMCPU pVCpu, uint32_t cIterations)
1274{
1275 int rc = VINF_SUCCESS;
1276 EMSTATE enmOldState = pVCpu->em.s.enmState;
1277 pVCpu->em.s.enmState = EMSTATE_DEBUG_GUEST_RAW;
1278
1279 Log(("Single step BEGIN:\n"));
1280 for (uint32_t i = 0; i < cIterations; i++)
1281 {
1282 DBGFR3PrgStep(pVCpu);
1283 DBGFR3DisasInstrCurrentLog(pVCpu, "RSS: ");
1284 rc = emR3RawStep(pVM, pVCpu);
1285 if (rc != VINF_SUCCESS)
1286 break;
1287 }
1288 Log(("Single step END: rc=%Rrc\n", rc));
1289 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
1290 pVCpu->em.s.enmState = enmOldState;
1291 return rc;
1292}
1293
1294
1295static int emR3SingleStepExecHwAcc(PVM pVM, PVMCPU pVCpu, uint32_t cIterations)
1296{
1297 int rc = VINF_SUCCESS;
1298 EMSTATE enmOldState = pVCpu->em.s.enmState;
1299 pVCpu->em.s.enmState = EMSTATE_DEBUG_GUEST_HWACC;
1300
1301 Log(("Single step BEGIN:\n"));
1302 for (uint32_t i = 0; i < cIterations; i++)
1303 {
1304 DBGFR3PrgStep(pVCpu);
1305 DBGFR3DisasInstrCurrentLog(pVCpu, "RSS: ");
1306 rc = emR3HwAccStep(pVM, pVCpu);
1307 if ( rc != VINF_SUCCESS
1308 || !HWACCMR3CanExecuteGuest(pVM, pVCpu->em.s.pCtx))
1309 break;
1310 }
1311 Log(("Single step END: rc=%Rrc\n", rc));
1312 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
1313 pVCpu->em.s.enmState = enmOldState;
1314 return rc == VINF_SUCCESS ? VINF_EM_RESCHEDULE_REM : rc;
1315}
1316
1317
1318static int emR3SingleStepExecRem(PVM pVM, PVMCPU pVCpu, uint32_t cIterations)
1319{
1320 EMSTATE enmOldState = pVCpu->em.s.enmState;
1321
1322 pVCpu->em.s.enmState = EMSTATE_DEBUG_GUEST_REM;
1323
1324 Log(("Single step BEGIN:\n"));
1325 for (uint32_t i = 0; i < cIterations; i++)
1326 {
1327 DBGFR3PrgStep(pVCpu);
1328 DBGFR3DisasInstrCurrentLog(pVCpu, "RSS: ");
1329 emR3RemStep(pVM, pVCpu);
1330 if (emR3Reschedule(pVM, pVCpu, pVCpu->em.s.pCtx) != EMSTATE_REM)
1331 break;
1332 }
1333 Log(("Single step END:\n"));
1334 CPUMSetGuestEFlags(pVCpu, CPUMGetGuestEFlags(pVCpu) & ~X86_EFL_TF);
1335 pVCpu->em.s.enmState = enmOldState;
1336 return VINF_EM_RESCHEDULE;
1337}
1338
1339#endif /* DEBUG */
1340
1341
1342/**
1343 * Executes one (or perhaps a few more) instruction(s).
1344 *
1345 * @returns VBox status code suitable for EM.
1346 *
1347 * @param pVM VM handle.
1348 * @param pVCpu VMCPU handle
1349 * @param rcGC GC return code
1350 * @param pszPrefix Disassembly prefix. If not NULL we'll disassemble the
1351 * instruction and prefix the log output with this text.
1352 */
1353#ifdef LOG_ENABLED
1354static int emR3RawExecuteInstructionWorker(PVM pVM, PVMCPU pVCpu, int rcGC, const char *pszPrefix)
1355#else
1356static int emR3RawExecuteInstructionWorker(PVM pVM, PVMCPU pVCpu, int rcGC)
1357#endif
1358{
1359 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1360 int rc;
1361
1362 /*
1363 *
1364 * The simple solution is to use the recompiler.
1365 * The better solution is to disassemble the current instruction and
1366 * try handle as many as possible without using REM.
1367 *
1368 */
1369
1370#ifdef LOG_ENABLED
1371 /*
1372 * Disassemble the instruction if requested.
1373 */
1374 if (pszPrefix)
1375 {
1376 DBGFR3InfoLog(pVM, "cpumguest", pszPrefix);
1377 DBGFR3DisasInstrCurrentLog(pVCpu, pszPrefix);
1378 }
1379#endif /* LOG_ENABLED */
1380
1381 /*
1382 * PATM is making life more interesting.
1383 * We cannot hand anything to REM which has an EIP inside patch code. So, we'll
1384 * tell PATM there is a trap in this code and have it take the appropriate actions
1385 * to allow us execute the code in REM.
1386 */
1387 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
1388 {
1389 Log(("emR3RawExecuteInstruction: In patch block. eip=%RRv\n", (RTRCPTR)pCtx->eip));
1390
1391 RTGCPTR pNewEip;
1392 rc = PATMR3HandleTrap(pVM, pCtx, pCtx->eip, &pNewEip);
1393 switch (rc)
1394 {
1395 /*
1396 * It's not very useful to emulate a single instruction and then go back to raw
1397 * mode; just execute the whole block until IF is set again.
1398 */
1399 case VINF_SUCCESS:
1400 Log(("emR3RawExecuteInstruction: Executing instruction starting at new address %RGv IF=%d VMIF=%x\n",
1401 pNewEip, pCtx->eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
1402 pCtx->eip = pNewEip;
1403 Assert(pCtx->eip);
1404
1405 if (pCtx->eflags.Bits.u1IF)
1406 {
1407 /*
1408 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1409 */
1410 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1411 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
1412 }
1413 else if (rcGC == VINF_PATM_PENDING_IRQ_AFTER_IRET)
1414 {
1415 /* special case: iret, that sets IF, detected a pending irq/event */
1416 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIRET");
1417 }
1418 return VINF_EM_RESCHEDULE_REM;
1419
1420 /*
1421 * One instruction.
1422 */
1423 case VINF_PATCH_EMULATE_INSTR:
1424 Log(("emR3RawExecuteInstruction: Emulate patched instruction at %RGv IF=%d VMIF=%x\n",
1425 pNewEip, pCtx->eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
1426 pCtx->eip = pNewEip;
1427 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
1428
1429 /*
1430 * The patch was disabled, hand it to the REM.
1431 */
1432 case VERR_PATCH_DISABLED:
1433 Log(("emR3RawExecuteInstruction: Disabled patch -> new eip %RGv IF=%d VMIF=%x\n",
1434 pNewEip, pCtx->eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
1435 pCtx->eip = pNewEip;
1436 if (pCtx->eflags.Bits.u1IF)
1437 {
1438 /*
1439 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1440 */
1441 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1442 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
1443 }
1444 return VINF_EM_RESCHEDULE_REM;
1445
1446 /* Force continued patch exection; usually due to write monitored stack. */
1447 case VINF_PATCH_CONTINUE:
1448 return VINF_SUCCESS;
1449
1450 default:
1451 AssertReleaseMsgFailed(("Unknown return code %Rrc from PATMR3HandleTrap\n", rc));
1452 return VERR_IPE_UNEXPECTED_STATUS;
1453 }
1454 }
1455
1456#if 0
1457 /* Try our own instruction emulator before falling back to the recompiler. */
1458 DISCPUSTATE Cpu;
1459 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->rip, &Cpu, "GEN EMU");
1460 if (RT_SUCCESS(rc))
1461 {
1462 uint32_t size;
1463
1464 switch (Cpu.pCurInstr->opcode)
1465 {
1466 /* @todo we can do more now */
1467 case OP_MOV:
1468 case OP_AND:
1469 case OP_OR:
1470 case OP_XOR:
1471 case OP_POP:
1472 case OP_INC:
1473 case OP_DEC:
1474 case OP_XCHG:
1475 STAM_PROFILE_START(&pVCpu->em.s.StatMiscEmu, a);
1476 rc = EMInterpretInstructionCPU(pVM, &Cpu, CPUMCTX2CORE(pCtx), 0, &size);
1477 if (RT_SUCCESS(rc))
1478 {
1479 pCtx->rip += Cpu.opsize;
1480#ifdef EM_NOTIFY_HWACCM
1481 if (pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_HWACC)
1482 HWACCMR3NotifyEmulated(pVCpu);
1483#endif
1484 STAM_PROFILE_STOP(&pVCpu->em.s.StatMiscEmu, a);
1485 return rc;
1486 }
1487 if (rc != VERR_EM_INTERPRETER)
1488 AssertMsgFailedReturn(("rc=%Rrc\n", rc), rc);
1489 STAM_PROFILE_STOP(&pVCpu->em.s.StatMiscEmu, a);
1490 break;
1491 }
1492 }
1493#endif /* 0 */
1494 STAM_PROFILE_START(&pVCpu->em.s.StatREMEmu, a);
1495 Log(("EMINS: %04x:%RGv RSP=%RGv\n", pCtx->cs, (RTGCPTR)pCtx->rip, (RTGCPTR)pCtx->rsp));
1496 EMR3RemLock(pVM);
1497 /* Flush the recompiler TLB if the VCPU has changed. */
1498 if (pVM->em.s.idLastRemCpu != pVCpu->idCpu)
1499 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_ALL);
1500 pVM->em.s.idLastRemCpu = pVCpu->idCpu;
1501
1502 rc = REMR3EmulateInstruction(pVM, pVCpu);
1503 EMR3RemUnlock(pVM);
1504 STAM_PROFILE_STOP(&pVCpu->em.s.StatREMEmu, a);
1505
1506#ifdef EM_NOTIFY_HWACCM
1507 if (pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_HWACC)
1508 HWACCMR3NotifyEmulated(pVCpu);
1509#endif
1510 return rc;
1511}
1512
1513
1514/**
1515 * Executes one (or perhaps a few more) instruction(s).
1516 * This is just a wrapper for discarding pszPrefix in non-logging builds.
1517 *
1518 * @returns VBox status code suitable for EM.
1519 * @param pVM VM handle.
1520 * @param pVCpu VMCPU handle.
1521 * @param pszPrefix Disassembly prefix. If not NULL we'll disassemble the
1522 * instruction and prefix the log output with this text.
1523 * @param rcGC GC return code
1524 */
1525DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, PVMCPU pVCpu, const char *pszPrefix, int rcGC)
1526{
1527#ifdef LOG_ENABLED
1528 return emR3RawExecuteInstructionWorker(pVM, pVCpu, rcGC, pszPrefix);
1529#else
1530 return emR3RawExecuteInstructionWorker(pVM, pVCpu, rcGC);
1531#endif
1532}
1533
1534/**
1535 * Executes one (or perhaps a few more) IO instruction(s).
1536 *
1537 * @returns VBox status code suitable for EM.
1538 * @param pVM VM handle.
1539 * @param pVCpu VMCPU handle.
1540 */
1541int emR3RawExecuteIOInstruction(PVM pVM, PVMCPU pVCpu)
1542{
1543 int rc;
1544 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1545
1546 STAM_PROFILE_START(&pVCpu->em.s.StatIOEmu, a);
1547
1548 /** @todo probably we should fall back to the recompiler; otherwise we'll go back and forth between HC & GC
1549 * as io instructions tend to come in packages of more than one
1550 */
1551 DISCPUSTATE Cpu;
1552 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->rip, &Cpu, "IO EMU");
1553 if (RT_SUCCESS(rc))
1554 {
1555 rc = VINF_EM_RAW_EMULATE_INSTR;
1556
1557 if (!(Cpu.prefix & (PREFIX_REP | PREFIX_REPNE)))
1558 {
1559 switch (Cpu.pCurInstr->opcode)
1560 {
1561 case OP_IN:
1562 {
1563 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatIn);
1564 rc = IOMInterpretIN(pVM, CPUMCTX2CORE(pCtx), &Cpu);
1565 break;
1566 }
1567
1568 case OP_OUT:
1569 {
1570 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatOut);
1571 rc = IOMInterpretOUT(pVM, CPUMCTX2CORE(pCtx), &Cpu);
1572 break;
1573 }
1574 }
1575 }
1576 else if (Cpu.prefix & PREFIX_REP)
1577 {
1578 switch (Cpu.pCurInstr->opcode)
1579 {
1580 case OP_INSB:
1581 case OP_INSWD:
1582 {
1583 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatIn);
1584 rc = IOMInterpretINS(pVM, CPUMCTX2CORE(pCtx), &Cpu);
1585 break;
1586 }
1587
1588 case OP_OUTSB:
1589 case OP_OUTSWD:
1590 {
1591 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatOut);
1592 rc = IOMInterpretOUTS(pVM, CPUMCTX2CORE(pCtx), &Cpu);
1593 break;
1594 }
1595 }
1596 }
1597
1598 /*
1599 * Handled the I/O return codes.
1600 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
1601 */
1602 if (IOM_SUCCESS(rc))
1603 {
1604 pCtx->rip += Cpu.opsize;
1605 STAM_PROFILE_STOP(&pVCpu->em.s.StatIOEmu, a);
1606 return rc;
1607 }
1608
1609 if (rc == VINF_EM_RAW_GUEST_TRAP)
1610 {
1611 STAM_PROFILE_STOP(&pVCpu->em.s.StatIOEmu, a);
1612 rc = emR3RawGuestTrap(pVM, pVCpu);
1613 return rc;
1614 }
1615 AssertMsg(rc != VINF_TRPM_XCPT_DISPATCHED, ("Handle VINF_TRPM_XCPT_DISPATCHED\n"));
1616
1617 if (RT_FAILURE(rc))
1618 {
1619 STAM_PROFILE_STOP(&pVCpu->em.s.StatIOEmu, a);
1620 return rc;
1621 }
1622 AssertMsg(rc == VINF_EM_RAW_EMULATE_INSTR || rc == VINF_EM_RESCHEDULE_REM, ("rc=%Rrc\n", rc));
1623 }
1624 STAM_PROFILE_STOP(&pVCpu->em.s.StatIOEmu, a);
1625 return emR3RawExecuteInstruction(pVM, pVCpu, "IO: ");
1626}
1627
1628
1629/**
1630 * Handle a guest context trap.
1631 *
1632 * @returns VBox status code suitable for EM.
1633 * @param pVM VM handle.
1634 * @param pVCpu VMCPU handle.
1635 */
1636static int emR3RawGuestTrap(PVM pVM, PVMCPU pVCpu)
1637{
1638 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1639
1640 /*
1641 * Get the trap info.
1642 */
1643 uint8_t u8TrapNo;
1644 TRPMEVENT enmType;
1645 RTGCUINT uErrorCode;
1646 RTGCUINTPTR uCR2;
1647 int rc = TRPMQueryTrapAll(pVCpu, &u8TrapNo, &enmType, &uErrorCode, &uCR2);
1648 if (RT_FAILURE(rc))
1649 {
1650 AssertReleaseMsgFailed(("No trap! (rc=%Rrc)\n", rc));
1651 return rc;
1652 }
1653
1654 /*
1655 * Traps can be directly forwarded in hardware accelerated mode.
1656 */
1657 if (HWACCMIsEnabled(pVM))
1658 {
1659#ifdef LOGGING_ENABLED
1660 DBGFR3InfoLog(pVM, "cpumguest", "Guest trap");
1661 DBGFR3DisasInstrCurrentLog(pVCpu, "Guest trap");
1662#endif
1663 return VINF_EM_RESCHEDULE_HWACC;
1664 }
1665
1666#if 1 /* Experimental: Review, disable if it causes trouble. */
1667 /*
1668 * Handle traps in patch code first.
1669 *
1670 * We catch a few of these cases in RC before returning to R3 (#PF, #GP, #BP)
1671 * but several traps isn't handled specially by TRPM in RC and we end up here
1672 * instead. One example is #DE.
1673 */
1674 uint32_t uCpl = CPUMGetGuestCPL(pVCpu, CPUMCTX2CORE(pCtx));
1675 if ( uCpl == 0
1676 && PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip))
1677 {
1678 LogFlow(("emR3RawGuestTrap: trap %#x in patch code; eip=%08x\n", u8TrapNo, pCtx->eip));
1679 return emR3PatchTrap(pVM, pVCpu, pCtx, rc);
1680 }
1681#endif
1682
1683 /*
1684 * If the guest gate is marked unpatched, then we will check again if we can patch it.
1685 * (This assumes that we've already tried and failed to dispatch the trap in
1686 * RC for the gates that already has been patched. Which is true for most high
1687 * volume traps, because these are handled specially, but not for odd ones like #DE.)
1688 */
1689 if (TRPMR3GetGuestTrapHandler(pVM, u8TrapNo) == TRPM_INVALID_HANDLER)
1690 {
1691 CSAMR3CheckGates(pVM, u8TrapNo, 1);
1692 Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8TrapNo, TRPMR3GetGuestTrapHandler(pVM, u8TrapNo) != TRPM_INVALID_HANDLER));
1693
1694 /* If it was successful, then we could go back to raw mode. */
1695 if (TRPMR3GetGuestTrapHandler(pVM, u8TrapNo) != TRPM_INVALID_HANDLER)
1696 {
1697 /* Must check pending forced actions as our IDT or GDT might be out of sync. */
1698 rc = EMR3CheckRawForcedActions(pVM, pVCpu);
1699 AssertRCReturn(rc, rc);
1700
1701 TRPMERRORCODE enmError = uErrorCode != ~0U
1702 ? TRPM_TRAP_HAS_ERRORCODE
1703 : TRPM_TRAP_NO_ERRORCODE;
1704 rc = TRPMForwardTrap(pVCpu, CPUMCTX2CORE(pCtx), u8TrapNo, uErrorCode, enmError, TRPM_TRAP, -1);
1705 if (rc == VINF_SUCCESS /* Don't use RT_SUCCESS */)
1706 {
1707 TRPMResetTrap(pVCpu);
1708 return VINF_EM_RESCHEDULE_RAW;
1709 }
1710 AssertMsg(rc == VINF_EM_RAW_GUEST_TRAP, ("%Rrc\n", rc));
1711 }
1712 }
1713
1714 /*
1715 * Scan kernel code that traps; we might not get another chance.
1716 */
1717 /** @todo move this up before the dispatching? */
1718 if ( (pCtx->ss & X86_SEL_RPL) <= 1
1719 && !pCtx->eflags.Bits.u1VM)
1720 {
1721 Assert(!PATMIsPatchGCAddr(pVM, pCtx->eip));
1722 CSAMR3CheckCodeEx(pVM, CPUMCTX2CORE(pCtx), pCtx->eip);
1723 }
1724
1725 /*
1726 * Trap specific handling.
1727 */
1728 if (u8TrapNo == 6) /* (#UD) Invalid opcode. */
1729 {
1730 /*
1731 * If MONITOR & MWAIT are supported, then interpret them here.
1732 */
1733 DISCPUSTATE cpu;
1734 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->rip, &cpu, "Guest Trap (#UD): ");
1735 if ( RT_SUCCESS(rc)
1736 && (cpu.pCurInstr->opcode == OP_MONITOR || cpu.pCurInstr->opcode == OP_MWAIT))
1737 {
1738 uint32_t u32Dummy, u32Features, u32ExtFeatures;
1739 CPUMGetGuestCpuId(pVCpu, 1, &u32Dummy, &u32Dummy, &u32ExtFeatures, &u32Features);
1740 if (u32ExtFeatures & X86_CPUID_FEATURE_ECX_MONITOR)
1741 {
1742 rc = TRPMResetTrap(pVCpu);
1743 AssertRC(rc);
1744
1745 uint32_t opsize;
1746 rc = EMInterpretInstructionCPU(pVM, pVCpu, &cpu, CPUMCTX2CORE(pCtx), 0, &opsize);
1747 if (RT_SUCCESS(rc))
1748 {
1749 pCtx->rip += cpu.opsize;
1750#ifdef EM_NOTIFY_HWACCM
1751 if (pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_HWACC)
1752 HWACCMR3NotifyEmulated(pVCpu);
1753#endif
1754 return rc;
1755 }
1756 return emR3RawExecuteInstruction(pVM, pVCpu, "Monitor: ");
1757 }
1758 }
1759 }
1760 else if (u8TrapNo == 13) /* (#GP) Privileged exception */
1761 {
1762 /*
1763 * Handle I/O bitmap?
1764 */
1765 /** @todo We're not supposed to be here with a false guest trap concerning
1766 * I/O access. We can easily handle those in RC. */
1767 DISCPUSTATE cpu;
1768 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->rip, &cpu, "Guest Trap: ");
1769 if ( RT_SUCCESS(rc)
1770 && (cpu.pCurInstr->optype & OPTYPE_PORTIO))
1771 {
1772 /*
1773 * We should really check the TSS for the IO bitmap, but it's not like this
1774 * lazy approach really makes things worse.
1775 */
1776 rc = TRPMResetTrap(pVCpu);
1777 AssertRC(rc);
1778 return emR3RawExecuteInstruction(pVM, pVCpu, "IO Guest Trap: ");
1779 }
1780 }
1781
1782#ifdef LOG_ENABLED
1783 DBGFR3InfoLog(pVM, "cpumguest", "Guest trap");
1784 DBGFR3DisasInstrCurrentLog(pVCpu, "Guest trap");
1785
1786 /* Get guest page information. */
1787 uint64_t fFlags = 0;
1788 RTGCPHYS GCPhys = 0;
1789 int rc2 = PGMGstGetPage(pVCpu, uCR2, &fFlags, &GCPhys);
1790 Log(("emR3RawGuestTrap: cs:eip=%04x:%08x: trap=%02x err=%08x cr2=%08x cr0=%08x%s: Phys=%RGp fFlags=%08llx %s %s %s%s rc2=%d\n",
1791 pCtx->cs, pCtx->eip, u8TrapNo, uErrorCode, uCR2, (uint32_t)pCtx->cr0, (enmType == TRPM_SOFTWARE_INT) ? " software" : "", GCPhys, fFlags,
1792 fFlags & X86_PTE_P ? "P " : "NP", fFlags & X86_PTE_US ? "U" : "S",
1793 fFlags & X86_PTE_RW ? "RW" : "R0", fFlags & X86_PTE_G ? " G" : "", rc2));
1794#endif
1795
1796 /*
1797 * #PG has CR2.
1798 * (Because of stuff like above we must set CR2 in a delayed fashion.)
1799 */
1800 if (u8TrapNo == 14 /* #PG */)
1801 pCtx->cr2 = uCR2;
1802
1803 return VINF_EM_RESCHEDULE_REM;
1804}
1805
1806
1807/**
1808 * Handle a ring switch trap.
1809 * Need to do statistics and to install patches. The result is going to REM.
1810 *
1811 * @returns VBox status code suitable for EM.
1812 * @param pVM VM handle.
1813 * @param pVCpu VMCPU handle.
1814 */
1815int emR3RawRingSwitch(PVM pVM, PVMCPU pVCpu)
1816{
1817 int rc;
1818 DISCPUSTATE Cpu;
1819 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
1820
1821 /*
1822 * sysenter, syscall & callgate
1823 */
1824 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->rip, &Cpu, "RSWITCH: ");
1825 if (RT_SUCCESS(rc))
1826 {
1827 if (Cpu.pCurInstr->opcode == OP_SYSENTER)
1828 {
1829 if (pCtx->SysEnter.cs != 0)
1830 {
1831 rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, DIS_SELREG_CS, CPUMCTX2CORE(pCtx), pCtx->eip),
1832 (SELMGetCpuModeFromSelector(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) == CPUMODE_32BIT) ? PATMFL_CODE32 : 0);
1833 if (RT_SUCCESS(rc))
1834 {
1835 DBGFR3DisasInstrCurrentLog(pVCpu, "Patched sysenter instruction");
1836 return VINF_EM_RESCHEDULE_RAW;
1837 }
1838 }
1839 }
1840
1841#ifdef VBOX_WITH_STATISTICS
1842 switch (Cpu.pCurInstr->opcode)
1843 {
1844 case OP_SYSENTER:
1845 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysEnter);
1846 break;
1847 case OP_SYSEXIT:
1848 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysExit);
1849 break;
1850 case OP_SYSCALL:
1851 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysCall);
1852 break;
1853 case OP_SYSRET:
1854 STAM_COUNTER_INC(&pVCpu->em.s.CTX_SUFF(pStats)->StatSysRet);
1855 break;
1856 }
1857#endif
1858 }
1859 else
1860 AssertRC(rc);
1861
1862 /* go to the REM to emulate a single instruction */
1863 return emR3RawExecuteInstruction(pVM, pVCpu, "RSWITCH: ");
1864}
1865
1866
1867/**
1868 * Handle a trap (\#PF or \#GP) in patch code
1869 *
1870 * @returns VBox status code suitable for EM.
1871 * @param pVM VM handle.
1872 * @param pVCpu VMCPU handle.
1873 * @param pCtx CPU context
1874 * @param gcret GC return code
1875 */
1876static int emR3PatchTrap(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int gcret)
1877{
1878 uint8_t u8TrapNo;
1879 int rc;
1880 TRPMEVENT enmType;
1881 RTGCUINT uErrorCode;
1882 RTGCUINTPTR uCR2;
1883
1884 Assert(PATMIsPatchGCAddr(pVM, pCtx->eip));
1885
1886 if (gcret == VINF_PATM_PATCH_INT3)
1887 {
1888 u8TrapNo = 3;
1889 uCR2 = 0;
1890 uErrorCode = 0;
1891 }
1892 else if (gcret == VINF_PATM_PATCH_TRAP_GP)
1893 {
1894 /* No active trap in this case. Kind of ugly. */
1895 u8TrapNo = X86_XCPT_GP;
1896 uCR2 = 0;
1897 uErrorCode = 0;
1898 }
1899 else
1900 {
1901 rc = TRPMQueryTrapAll(pVCpu, &u8TrapNo, &enmType, &uErrorCode, &uCR2);
1902 if (RT_FAILURE(rc))
1903 {
1904 AssertReleaseMsgFailed(("emR3PatchTrap: no trap! (rc=%Rrc) gcret=%Rrc\n", rc, gcret));
1905 return rc;
1906 }
1907 /* Reset the trap as we'll execute the original instruction again. */
1908 TRPMResetTrap(pVCpu);
1909 }
1910
1911 /*
1912 * Deal with traps inside patch code.
1913 * (This code won't run outside GC.)
1914 */
1915 if (u8TrapNo != 1)
1916 {
1917#ifdef LOG_ENABLED
1918 DBGFR3InfoLog(pVM, "cpumguest", "Trap in patch code");
1919 DBGFR3DisasInstrCurrentLog(pVCpu, "Patch code");
1920
1921 DISCPUSTATE Cpu;
1922 int rc;
1923
1924 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->eip, &Cpu, "Patch code: ");
1925 if ( RT_SUCCESS(rc)
1926 && Cpu.pCurInstr->opcode == OP_IRET)
1927 {
1928 uint32_t eip, selCS, uEFlags;
1929
1930 /* Iret crashes are bad as we have already changed the flags on the stack */
1931 rc = PGMPhysSimpleReadGCPtr(pVCpu, &eip, pCtx->esp, 4);
1932 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selCS, pCtx->esp+4, 4);
1933 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &uEFlags, pCtx->esp+8, 4);
1934 if (rc == VINF_SUCCESS)
1935 {
1936 if ( (uEFlags & X86_EFL_VM)
1937 || (selCS & X86_SEL_RPL) == 3)
1938 {
1939 uint32_t selSS, esp;
1940
1941 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &esp, pCtx->esp + 12, 4);
1942 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selSS, pCtx->esp + 16, 4);
1943
1944 if (uEFlags & X86_EFL_VM)
1945 {
1946 uint32_t selDS, selES, selFS, selGS;
1947 rc = PGMPhysSimpleReadGCPtr(pVCpu, &selES, pCtx->esp + 20, 4);
1948 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selDS, pCtx->esp + 24, 4);
1949 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selFS, pCtx->esp + 28, 4);
1950 rc |= PGMPhysSimpleReadGCPtr(pVCpu, &selGS, pCtx->esp + 32, 4);
1951 if (rc == VINF_SUCCESS)
1952 {
1953 Log(("Patch code: IRET->VM stack frame: return address %04X:%08RX32 eflags=%08x ss:esp=%04X:%08RX32\n", selCS, eip, uEFlags, selSS, esp));
1954 Log(("Patch code: IRET->VM stack frame: DS=%04X ES=%04X FS=%04X GS=%04X\n", selDS, selES, selFS, selGS));
1955 }
1956 }
1957 else
1958 Log(("Patch code: IRET stack frame: return address %04X:%08RX32 eflags=%08x ss:esp=%04X:%08RX32\n", selCS, eip, uEFlags, selSS, esp));
1959 }
1960 else
1961 Log(("Patch code: IRET stack frame: return address %04X:%08RX32 eflags=%08x\n", selCS, eip, uEFlags));
1962 }
1963 }
1964#endif /* LOG_ENABLED */
1965 Log(("emR3PatchTrap: in patch: eip=%08x: trap=%02x err=%08x cr2=%08x cr0=%08x\n",
1966 pCtx->eip, u8TrapNo, uErrorCode, uCR2, (uint32_t)pCtx->cr0));
1967
1968 RTGCPTR pNewEip;
1969 rc = PATMR3HandleTrap(pVM, pCtx, pCtx->eip, &pNewEip);
1970 switch (rc)
1971 {
1972 /*
1973 * Execute the faulting instruction.
1974 */
1975 case VINF_SUCCESS:
1976 {
1977 /** @todo execute a whole block */
1978 Log(("emR3PatchTrap: Executing faulting instruction at new address %RGv\n", pNewEip));
1979 if (!(pVCpu->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
1980 Log(("emR3PatchTrap: Virtual IF flag disabled!!\n"));
1981
1982 pCtx->eip = pNewEip;
1983 AssertRelease(pCtx->eip);
1984
1985 if (pCtx->eflags.Bits.u1IF)
1986 {
1987 /* Windows XP lets irets fault intentionally and then takes action based on the opcode; an
1988 * int3 patch overwrites it and leads to blue screens. Remove the patch in this case.
1989 */
1990 if ( u8TrapNo == X86_XCPT_GP
1991 && PATMIsInt3Patch(pVM, pCtx->eip, NULL, NULL))
1992 {
1993 /** @todo move to PATMR3HandleTrap */
1994 Log(("Possible Windows XP iret fault at %08RX32\n", pCtx->eip));
1995 PATMR3RemovePatch(pVM, pCtx->eip);
1996 }
1997
1998 /** @todo Knoppix 5 regression when returning VINF_SUCCESS here and going back to raw mode. */
1999 /* Note: possibly because a reschedule is required (e.g. iret to V86 code) */
2000
2001 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
2002 /* Interrupts are enabled; just go back to the original instruction.
2003 return VINF_SUCCESS; */
2004 }
2005 return VINF_EM_RESCHEDULE_REM;
2006 }
2007
2008 /*
2009 * One instruction.
2010 */
2011 case VINF_PATCH_EMULATE_INSTR:
2012 Log(("emR3PatchTrap: Emulate patched instruction at %RGv IF=%d VMIF=%x\n",
2013 pNewEip, pCtx->eflags.Bits.u1IF, pVCpu->em.s.pPatmGCState->uVMFlags));
2014 pCtx->eip = pNewEip;
2015 AssertRelease(pCtx->eip);
2016 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHEMUL: ");
2017
2018 /*
2019 * The patch was disabled, hand it to the REM.
2020 */
2021 case VERR_PATCH_DISABLED:
2022 if (!(pVCpu->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
2023 Log(("emR3PatchTrap: Virtual IF flag disabled!!\n"));
2024 pCtx->eip = pNewEip;
2025 AssertRelease(pCtx->eip);
2026
2027 if (pCtx->eflags.Bits.u1IF)
2028 {
2029 /*
2030 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
2031 */
2032 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
2033 return emR3RawExecuteInstruction(pVM, pVCpu, "PATCHIR");
2034 }
2035 return VINF_EM_RESCHEDULE_REM;
2036
2037 /* Force continued patch exection; usually due to write monitored stack. */
2038 case VINF_PATCH_CONTINUE:
2039 return VINF_SUCCESS;
2040
2041 /*
2042 * Anything else is *fatal*.
2043 */
2044 default:
2045 AssertReleaseMsgFailed(("Unknown return code %Rrc from PATMR3HandleTrap!\n", rc));
2046 return VERR_IPE_UNEXPECTED_STATUS;
2047 }
2048 }
2049 return VINF_SUCCESS;
2050}
2051
2052
2053/**
2054 * Handle a privileged instruction.
2055 *
2056 * @returns VBox status code suitable for EM.
2057 * @param pVM VM handle.
2058 * @param pVCpu VMCPU handle;
2059 */
2060int emR3RawPrivileged(PVM pVM, PVMCPU pVCpu)
2061{
2062 STAM_PROFILE_START(&pVCpu->em.s.StatPrivEmu, a);
2063 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
2064
2065 Assert(!pCtx->eflags.Bits.u1VM);
2066
2067 if (PATMIsEnabled(pVM))
2068 {
2069 /*
2070 * Check if in patch code.
2071 */
2072 if (PATMR3IsInsidePatchJump(pVM, pCtx->eip, NULL))
2073 {
2074#ifdef LOG_ENABLED
2075 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
2076#endif
2077 AssertMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08X\n", pCtx->eip));
2078 return VERR_EM_RAW_PATCH_CONFLICT;
2079 }
2080 if ( (pCtx->ss & X86_SEL_RPL) == 0
2081 && !pCtx->eflags.Bits.u1VM
2082 && !PATMIsPatchGCAddr(pVM, pCtx->eip))
2083 {
2084 int rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, DIS_SELREG_CS, CPUMCTX2CORE(pCtx), pCtx->eip),
2085 (SELMGetCpuModeFromSelector(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) == CPUMODE_32BIT) ? PATMFL_CODE32 : 0);
2086 if (RT_SUCCESS(rc))
2087 {
2088#ifdef LOG_ENABLED
2089 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
2090#endif
2091 DBGFR3DisasInstrCurrentLog(pVCpu, "Patched privileged instruction");
2092 return VINF_SUCCESS;
2093 }
2094 }
2095 }
2096
2097#ifdef LOG_ENABLED
2098 if (!PATMIsPatchGCAddr(pVM, pCtx->eip))
2099 {
2100 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
2101 DBGFR3DisasInstrCurrentLog(pVCpu, "Privileged instr: ");
2102 }
2103#endif
2104
2105 /*
2106 * Instruction statistics and logging.
2107 */
2108 DISCPUSTATE Cpu;
2109 int rc;
2110
2111 rc = CPUMR3DisasmInstrCPU(pVM, pVCpu, pCtx, pCtx->rip, &Cpu, "PRIV: ");
2112 if (RT_SUCCESS(rc))
2113 {
2114#ifdef VBOX_WITH_STATISTICS
2115 PEMSTATS pStats = pVCpu->em.s.CTX_SUFF(pStats);
2116 switch (Cpu.pCurInstr->opcode)
2117 {
2118 case OP_INVLPG:
2119 STAM_COUNTER_INC(&pStats->StatInvlpg);
2120 break;
2121 case OP_IRET:
2122 STAM_COUNTER_INC(&pStats->StatIret);
2123 break;
2124 case OP_CLI:
2125 STAM_COUNTER_INC(&pStats->StatCli);
2126 emR3RecordCli(pVM, pVCpu, pCtx->rip);
2127 break;
2128 case OP_STI:
2129 STAM_COUNTER_INC(&pStats->StatSti);
2130 break;
2131 case OP_INSB:
2132 case OP_INSWD:
2133 case OP_IN:
2134 case OP_OUTSB:
2135 case OP_OUTSWD:
2136 case OP_OUT:
2137 AssertMsgFailed(("Unexpected privileged exception due to port IO\n"));
2138 break;
2139
2140 case OP_MOV_CR:
2141 if (Cpu.param1.flags & USE_REG_GEN32)
2142 {
2143 //read
2144 Assert(Cpu.param2.flags & USE_REG_CR);
2145 Assert(Cpu.param2.base.reg_ctrl <= USE_REG_CR4);
2146 STAM_COUNTER_INC(&pStats->StatMovReadCR[Cpu.param2.base.reg_ctrl]);
2147 }
2148 else
2149 {
2150 //write
2151 Assert(Cpu.param1.flags & USE_REG_CR);
2152 Assert(Cpu.param1.base.reg_ctrl <= USE_REG_CR4);
2153 STAM_COUNTER_INC(&pStats->StatMovWriteCR[Cpu.param1.base.reg_ctrl]);
2154 }
2155 break;
2156
2157 case OP_MOV_DR:
2158 STAM_COUNTER_INC(&pStats->StatMovDRx);
2159 break;
2160 case OP_LLDT:
2161 STAM_COUNTER_INC(&pStats->StatMovLldt);
2162 break;
2163 case OP_LIDT:
2164 STAM_COUNTER_INC(&pStats->StatMovLidt);
2165 break;
2166 case OP_LGDT:
2167 STAM_COUNTER_INC(&pStats->StatMovLgdt);
2168 break;
2169 case OP_SYSENTER:
2170 STAM_COUNTER_INC(&pStats->StatSysEnter);
2171 break;
2172 case OP_SYSEXIT:
2173 STAM_COUNTER_INC(&pStats->StatSysExit);
2174 break;
2175 case OP_SYSCALL:
2176 STAM_COUNTER_INC(&pStats->StatSysCall);
2177 break;
2178 case OP_SYSRET:
2179 STAM_COUNTER_INC(&pStats->StatSysRet);
2180 break;
2181 case OP_HLT:
2182 STAM_COUNTER_INC(&pStats->StatHlt);
2183 break;
2184 default:
2185 STAM_COUNTER_INC(&pStats->StatMisc);
2186 Log4(("emR3RawPrivileged: opcode=%d\n", Cpu.pCurInstr->opcode));
2187 break;
2188 }
2189#endif /* VBOX_WITH_STATISTICS */
2190 if ( (pCtx->ss & X86_SEL_RPL) == 0
2191 && !pCtx->eflags.Bits.u1VM
2192 && SELMGetCpuModeFromSelector(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) == CPUMODE_32BIT)
2193 {
2194 uint32_t size;
2195
2196 STAM_PROFILE_START(&pVCpu->em.s.StatPrivEmu, a);
2197 switch (Cpu.pCurInstr->opcode)
2198 {
2199 case OP_CLI:
2200 pCtx->eflags.u32 &= ~X86_EFL_IF;
2201 Assert(Cpu.opsize == 1);
2202 pCtx->rip += Cpu.opsize;
2203 STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
2204 return VINF_EM_RESCHEDULE_REM; /* must go to the recompiler now! */
2205
2206 case OP_STI:
2207 pCtx->eflags.u32 |= X86_EFL_IF;
2208 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip + Cpu.opsize);
2209 Assert(Cpu.opsize == 1);
2210 pCtx->rip += Cpu.opsize;
2211 STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
2212 return VINF_SUCCESS;
2213
2214 case OP_HLT:
2215 if (PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip))
2216 {
2217 PATMTRANSSTATE enmState;
2218 RTGCPTR pOrgInstrGC = PATMR3PatchToGCPtr(pVM, pCtx->eip, &enmState);
2219
2220 if (enmState == PATMTRANS_OVERWRITTEN)
2221 {
2222 rc = PATMR3DetectConflict(pVM, pOrgInstrGC, pOrgInstrGC);
2223 Assert(rc == VERR_PATCH_DISABLED);
2224 /* Conflict detected, patch disabled */
2225 Log(("emR3RawPrivileged: detected conflict -> disabled patch at %08RX32\n", pCtx->eip));
2226
2227 enmState = PATMTRANS_SAFE;
2228 }
2229
2230 /* The translation had better be successful. Otherwise we can't recover. */
2231 AssertReleaseMsg(pOrgInstrGC && enmState != PATMTRANS_OVERWRITTEN, ("Unable to translate instruction address at %08RX32\n", pCtx->eip));
2232 if (enmState != PATMTRANS_OVERWRITTEN)
2233 pCtx->eip = pOrgInstrGC;
2234 }
2235 /* no break; we could just return VINF_EM_HALT here */
2236
2237 case OP_MOV_CR:
2238 case OP_MOV_DR:
2239#ifdef LOG_ENABLED
2240 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2241 {
2242 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
2243 DBGFR3DisasInstrCurrentLog(pVCpu, "Privileged instr: ");
2244 }
2245#endif
2246
2247 rc = EMInterpretInstructionCPU(pVM, pVCpu, &Cpu, CPUMCTX2CORE(pCtx), 0, &size);
2248 if (RT_SUCCESS(rc))
2249 {
2250 pCtx->rip += Cpu.opsize;
2251#ifdef EM_NOTIFY_HWACCM
2252 if (pVCpu->em.s.enmState == EMSTATE_DEBUG_GUEST_HWACC)
2253 HWACCMR3NotifyEmulated(pVCpu);
2254#endif
2255 STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
2256
2257 if ( Cpu.pCurInstr->opcode == OP_MOV_CR
2258 && Cpu.param1.flags == USE_REG_CR /* write */
2259 )
2260 {
2261 /* Deal with CR0 updates inside patch code that force
2262 * us to go to the recompiler.
2263 */
2264 if ( PATMIsPatchGCAddr(pVM, pCtx->rip)
2265 && (pCtx->cr0 & (X86_CR0_WP|X86_CR0_PG|X86_CR0_PE)) != (X86_CR0_WP|X86_CR0_PG|X86_CR0_PE))
2266 {
2267 PATMTRANSSTATE enmState;
2268 RTGCPTR pOrgInstrGC = PATMR3PatchToGCPtr(pVM, pCtx->rip, &enmState);
2269
2270 Log(("Force recompiler switch due to cr0 (%RGp) update rip=%RGv -> %RGv (enmState=%d)\n", pCtx->cr0, pCtx->rip, pOrgInstrGC, enmState));
2271 if (enmState == PATMTRANS_OVERWRITTEN)
2272 {
2273 rc = PATMR3DetectConflict(pVM, pOrgInstrGC, pOrgInstrGC);
2274 Assert(rc == VERR_PATCH_DISABLED);
2275 /* Conflict detected, patch disabled */
2276 Log(("emR3RawPrivileged: detected conflict -> disabled patch at %RGv\n", (RTGCPTR)pCtx->rip));
2277 enmState = PATMTRANS_SAFE;
2278 }
2279 /* The translation had better be successful. Otherwise we can't recover. */
2280 AssertReleaseMsg(pOrgInstrGC && enmState != PATMTRANS_OVERWRITTEN, ("Unable to translate instruction address at %RGv\n", (RTGCPTR)pCtx->rip));
2281 if (enmState != PATMTRANS_OVERWRITTEN)
2282 pCtx->rip = pOrgInstrGC;
2283 }
2284
2285 /* Reschedule is necessary as the execution/paging mode might have changed. */
2286 return VINF_EM_RESCHEDULE;
2287 }
2288 return rc; /* can return VINF_EM_HALT as well. */
2289 }
2290 AssertMsgReturn(rc == VERR_EM_INTERPRETER, ("%Rrc\n", rc), rc);
2291 break; /* fall back to the recompiler */
2292 }
2293 STAM_PROFILE_STOP(&pVCpu->em.s.StatPrivEmu, a);
2294 }
2295 }
2296
2297 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2298 return emR3PatchTrap(pVM, pVCpu, pCtx, VINF_PATM_PATCH_TRAP_GP);
2299
2300 return emR3RawExecuteInstruction(pVM, pVCpu, "PRIV");
2301}
2302
2303
2304/**
2305 * Update the forced rawmode execution modifier.
2306 *
2307 * This function is called when we're returning from the raw-mode loop(s). If we're
2308 * in patch code, it will set a flag forcing execution to be resumed in raw-mode,
2309 * if not in patch code, the flag will be cleared.
2310 *
2311 * We should never interrupt patch code while it's being executed. Cli patches can
2312 * contain big code blocks, but they are always executed with IF=0. Other patches
2313 * replace single instructions and should be atomic.
2314 *
2315 * @returns Updated rc.
2316 *
2317 * @param pVM The VM handle.
2318 * @param pVCpu The VMCPU handle.
2319 * @param pCtx The guest CPU context.
2320 * @param rc The result code.
2321 */
2322DECLINLINE(int) emR3RawUpdateForceFlag(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rc)
2323{
2324 if (PATMIsPatchGCAddr(pVM, pCtx->eip)) /** @todo check cs selector base/type */
2325 {
2326 /* ignore reschedule attempts. */
2327 switch (rc)
2328 {
2329 case VINF_EM_RESCHEDULE:
2330 case VINF_EM_RESCHEDULE_REM:
2331 LogFlow(("emR3RawUpdateForceFlag: patch address -> force raw reschedule\n"));
2332 rc = VINF_SUCCESS;
2333 break;
2334 }
2335 pVCpu->em.s.fForceRAW = true;
2336 }
2337 else
2338 pVCpu->em.s.fForceRAW = false;
2339 return rc;
2340}
2341
2342
2343/**
2344 * Process a subset of the raw-mode return code.
2345 *
2346 * Since we have to share this with raw-mode single stepping, this inline
2347 * function has been created to avoid code duplication.
2348 *
2349 * @returns VINF_SUCCESS if it's ok to continue raw mode.
2350 * @returns VBox status code to return to the EM main loop.
2351 *
2352 * @param pVM The VM handle
2353 * @param pVCpu The VMCPU handle
2354 * @param rc The return code.
2355 * @param pCtx The guest cpu context.
2356 */
2357DECLINLINE(int) emR3RawHandleRC(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rc)
2358{
2359 switch (rc)
2360 {
2361 /*
2362 * Common & simple ones.
2363 */
2364 case VINF_SUCCESS:
2365 break;
2366 case VINF_EM_RESCHEDULE_RAW:
2367 case VINF_EM_RESCHEDULE_HWACC:
2368 case VINF_EM_RAW_INTERRUPT:
2369 case VINF_EM_RAW_TO_R3:
2370 case VINF_EM_RAW_TIMER_PENDING:
2371 case VINF_EM_PENDING_REQUEST:
2372 rc = VINF_SUCCESS;
2373 break;
2374
2375 /*
2376 * Privileged instruction.
2377 */
2378 case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
2379 case VINF_PATM_PATCH_TRAP_GP:
2380 rc = emR3RawPrivileged(pVM, pVCpu);
2381 break;
2382
2383 /*
2384 * Got a trap which needs dispatching.
2385 */
2386 case VINF_EM_RAW_GUEST_TRAP:
2387 if (PATMR3IsInsidePatchJump(pVM, pCtx->eip, NULL))
2388 {
2389 AssertReleaseMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08X\n", CPUMGetGuestEIP(pVCpu)));
2390 rc = VERR_EM_RAW_PATCH_CONFLICT;
2391 break;
2392 }
2393 rc = emR3RawGuestTrap(pVM, pVCpu);
2394 break;
2395
2396 /*
2397 * Trap in patch code.
2398 */
2399 case VINF_PATM_PATCH_TRAP_PF:
2400 case VINF_PATM_PATCH_INT3:
2401 rc = emR3PatchTrap(pVM, pVCpu, pCtx, rc);
2402 break;
2403
2404 case VINF_PATM_DUPLICATE_FUNCTION:
2405 Assert(PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2406 rc = PATMR3DuplicateFunctionRequest(pVM, pCtx);
2407 AssertRC(rc);
2408 rc = VINF_SUCCESS;
2409 break;
2410
2411 case VINF_PATM_CHECK_PATCH_PAGE:
2412 rc = PATMR3HandleMonitoredPage(pVM);
2413 AssertRC(rc);
2414 rc = VINF_SUCCESS;
2415 break;
2416
2417 /*
2418 * Patch manager.
2419 */
2420 case VERR_EM_RAW_PATCH_CONFLICT:
2421 AssertReleaseMsgFailed(("%Rrc handling is not yet implemented\n", rc));
2422 break;
2423
2424#ifdef VBOX_WITH_VMI
2425 /*
2426 * PARAV function.
2427 */
2428 case VINF_EM_RESCHEDULE_PARAV:
2429 rc = PARAVCallFunction(pVM);
2430 break;
2431#endif
2432
2433 /*
2434 * Memory mapped I/O access - attempt to patch the instruction
2435 */
2436 case VINF_PATM_HC_MMIO_PATCH_READ:
2437 rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, DIS_SELREG_CS, CPUMCTX2CORE(pCtx), pCtx->eip),
2438 PATMFL_MMIO_ACCESS | ((SELMGetCpuModeFromSelector(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) == CPUMODE_32BIT) ? PATMFL_CODE32 : 0));
2439 if (RT_FAILURE(rc))
2440 rc = emR3RawExecuteInstruction(pVM, pVCpu, "MMIO");
2441 break;
2442
2443 case VINF_PATM_HC_MMIO_PATCH_WRITE:
2444 AssertFailed(); /* not yet implemented. */
2445 rc = emR3RawExecuteInstruction(pVM, pVCpu, "MMIO");
2446 break;
2447
2448 /*
2449 * Conflict or out of page tables.
2450 *
2451 * VM_FF_PGM_SYNC_CR3 is set by the hypervisor and all we need to
2452 * do here is to execute the pending forced actions.
2453 */
2454 case VINF_PGM_SYNC_CR3:
2455 AssertMsg(VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL),
2456 ("VINF_PGM_SYNC_CR3 and no VMCPU_FF_PGM_SYNC_CR3*!\n"));
2457 rc = VINF_SUCCESS;
2458 break;
2459
2460 /*
2461 * Paging mode change.
2462 */
2463 case VINF_PGM_CHANGE_MODE:
2464 rc = PGMChangeMode(pVCpu, pCtx->cr0, pCtx->cr4, pCtx->msrEFER);
2465 if (rc == VINF_SUCCESS)
2466 rc = VINF_EM_RESCHEDULE;
2467 AssertMsg(RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST), ("%Rrc\n", rc));
2468 break;
2469
2470 /*
2471 * CSAM wants to perform a task in ring-3. It has set an FF action flag.
2472 */
2473 case VINF_CSAM_PENDING_ACTION:
2474 rc = VINF_SUCCESS;
2475 break;
2476
2477 /*
2478 * Invoked Interrupt gate - must directly (!) go to the recompiler.
2479 */
2480 case VINF_EM_RAW_INTERRUPT_PENDING:
2481 case VINF_EM_RAW_RING_SWITCH_INT:
2482 Assert(TRPMHasTrap(pVCpu));
2483 Assert(!PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2484
2485 if (TRPMHasTrap(pVCpu))
2486 {
2487 /* If the guest gate is marked unpatched, then we will check again if we can patch it. */
2488 uint8_t u8Interrupt = TRPMGetTrapNo(pVCpu);
2489 if (TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) == TRPM_INVALID_HANDLER)
2490 {
2491 CSAMR3CheckGates(pVM, u8Interrupt, 1);
2492 Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8Interrupt, TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) != TRPM_INVALID_HANDLER));
2493 /* Note: If it was successful, then we could go back to raw mode, but let's keep things simple for now. */
2494 }
2495 }
2496 rc = VINF_EM_RESCHEDULE_REM;
2497 break;
2498
2499 /*
2500 * Other ring switch types.
2501 */
2502 case VINF_EM_RAW_RING_SWITCH:
2503 rc = emR3RawRingSwitch(pVM, pVCpu);
2504 break;
2505
2506 /*
2507 * REMGCNotifyInvalidatePage() failed because of overflow.
2508 */
2509 case VERR_REM_FLUSHED_PAGES_OVERFLOW:
2510 Assert((pCtx->ss & X86_SEL_RPL) != 1);
2511 EMR3RemLock(pVM);
2512 REMR3ReplayInvalidatedPages(pVM, pVCpu);
2513 EMR3RemUnlock(pVM);
2514 rc = VINF_SUCCESS;
2515 break;
2516
2517 /*
2518 * I/O Port access - emulate the instruction.
2519 */
2520 case VINF_IOM_HC_IOPORT_READ:
2521 case VINF_IOM_HC_IOPORT_WRITE:
2522 rc = emR3RawExecuteIOInstruction(pVM, pVCpu);
2523 break;
2524
2525 /*
2526 * Memory mapped I/O access - emulate the instruction.
2527 */
2528 case VINF_IOM_HC_MMIO_READ:
2529 case VINF_IOM_HC_MMIO_WRITE:
2530 case VINF_IOM_HC_MMIO_READ_WRITE:
2531 rc = emR3RawExecuteInstruction(pVM, pVCpu, "MMIO");
2532 break;
2533
2534 /*
2535 * (MM)IO intensive code block detected; fall back to the recompiler for better performance
2536 */
2537 case VINF_EM_RAW_EMULATE_IO_BLOCK:
2538 rc = HWACCMR3EmulateIoBlock(pVM, pCtx);
2539 break;
2540
2541 /*
2542 * Execute instruction.
2543 */
2544 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
2545 rc = emR3RawExecuteInstruction(pVM, pVCpu, "LDT FAULT: ");
2546 break;
2547 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
2548 rc = emR3RawExecuteInstruction(pVM, pVCpu, "GDT FAULT: ");
2549 break;
2550 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
2551 rc = emR3RawExecuteInstruction(pVM, pVCpu, "IDT FAULT: ");
2552 break;
2553 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
2554 rc = emR3RawExecuteInstruction(pVM, pVCpu, "TSS FAULT: ");
2555 break;
2556 case VINF_EM_RAW_EMULATE_INSTR_PD_FAULT:
2557 rc = emR3RawExecuteInstruction(pVM, pVCpu, "PD FAULT: ");
2558 break;
2559
2560 case VINF_EM_RAW_EMULATE_INSTR_HLT:
2561 /** @todo skip instruction and go directly to the halt state. (see REM for implementation details) */
2562 rc = emR3RawPrivileged(pVM, pVCpu);
2563 break;
2564
2565 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
2566 rc = emR3RawExecuteInstruction(pVM, pVCpu, "EMUL: ", VINF_PATM_PENDING_IRQ_AFTER_IRET);
2567 break;
2568
2569 case VINF_EM_RAW_EMULATE_INSTR:
2570 case VINF_PATCH_EMULATE_INSTR:
2571 rc = emR3RawExecuteInstruction(pVM, pVCpu, "EMUL: ");
2572 break;
2573
2574 /*
2575 * Stale selector and iret traps => REM.
2576 */
2577 case VINF_EM_RAW_STALE_SELECTOR:
2578 case VINF_EM_RAW_IRET_TRAP:
2579 /* We will not go to the recompiler if EIP points to patch code. */
2580 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2581 {
2582 pCtx->eip = PATMR3PatchToGCPtr(pVM, (RTGCPTR)pCtx->eip, 0);
2583 }
2584 LogFlow(("emR3RawHandleRC: %Rrc -> %Rrc\n", rc, VINF_EM_RESCHEDULE_REM));
2585 rc = VINF_EM_RESCHEDULE_REM;
2586 break;
2587
2588 /*
2589 * Up a level.
2590 */
2591 case VINF_EM_TERMINATE:
2592 case VINF_EM_OFF:
2593 case VINF_EM_RESET:
2594 case VINF_EM_SUSPEND:
2595 case VINF_EM_HALT:
2596 case VINF_EM_RESUME:
2597 case VINF_EM_NO_MEMORY:
2598 case VINF_EM_RESCHEDULE:
2599 case VINF_EM_RESCHEDULE_REM:
2600 case VINF_EM_WAIT_SIPI:
2601 break;
2602
2603 /*
2604 * Up a level and invoke the debugger.
2605 */
2606 case VINF_EM_DBG_STEPPED:
2607 case VINF_EM_DBG_BREAKPOINT:
2608 case VINF_EM_DBG_STEP:
2609 case VINF_EM_DBG_HYPER_BREAKPOINT:
2610 case VINF_EM_DBG_HYPER_STEPPED:
2611 case VINF_EM_DBG_HYPER_ASSERTION:
2612 case VINF_EM_DBG_STOP:
2613 break;
2614
2615 /*
2616 * Up a level, dump and debug.
2617 */
2618 case VERR_TRPM_DONT_PANIC:
2619 case VERR_TRPM_PANIC:
2620 case VERR_VMM_RING0_ASSERTION:
2621 break;
2622
2623 /*
2624 * Up a level, after HwAccM have done some release logging.
2625 */
2626 case VERR_VMX_INVALID_VMCS_FIELD:
2627 case VERR_VMX_INVALID_VMCS_PTR:
2628 case VERR_VMX_INVALID_VMXON_PTR:
2629 case VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_CODE:
2630 case VERR_VMX_UNEXPECTED_EXCEPTION:
2631 case VERR_VMX_UNEXPECTED_EXIT_CODE:
2632 case VERR_VMX_INVALID_GUEST_STATE:
2633 case VERR_VMX_UNABLE_TO_START_VM:
2634 case VERR_VMX_UNABLE_TO_RESUME_VM:
2635 HWACCMR3CheckError(pVM, rc);
2636 break;
2637 /*
2638 * Anything which is not known to us means an internal error
2639 * and the termination of the VM!
2640 */
2641 default:
2642 AssertMsgFailed(("Unknown GC return code: %Rra\n", rc));
2643 break;
2644 }
2645 return rc;
2646}
2647
2648
2649/**
2650 * Check for pending raw actions
2651 *
2652 * @returns VBox status code. May return VINF_EM_NO_MEMORY but none of the other
2653 * EM statuses.
2654 * @param pVM The VM to operate on.
2655 * @param pVCpu The VMCPU handle.
2656 */
2657VMMR3DECL(int) EMR3CheckRawForcedActions(PVM pVM, PVMCPU pVCpu)
2658{
2659 return emR3RawForcedActions(pVM, pVCpu, pVCpu->em.s.pCtx);
2660}
2661
2662
2663/**
2664 * Process raw-mode specific forced actions.
2665 *
2666 * This function is called when any FFs in the VM_FF_HIGH_PRIORITY_PRE_RAW_MASK is pending.
2667 *
2668 * @returns VBox status code. May return VINF_EM_NO_MEMORY but none of the other
2669 * EM statuses.
2670 * @param pVM The VM handle.
2671 * @param pVCpu The VMCPU handle.
2672 * @param pCtx The guest CPUM register context.
2673 */
2674static int emR3RawForcedActions(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2675{
2676 /*
2677 * Note that the order is *vitally* important!
2678 * Also note that SELMR3UpdateFromCPUM may trigger VM_FF_SELM_SYNC_TSS.
2679 */
2680
2681
2682 /*
2683 * Sync selector tables.
2684 */
2685 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT))
2686 {
2687 int rc = SELMR3UpdateFromCPUM(pVM, pVCpu);
2688 if (RT_FAILURE(rc))
2689 return rc;
2690 }
2691
2692 /*
2693 * Sync IDT.
2694 *
2695 * The CSAMR3CheckGates call in TRPMR3SyncIDT may call PGMPrefetchPage
2696 * and PGMShwModifyPage, so we're in for trouble if for instance a
2697 * PGMSyncCR3+pgmPoolClearAll is pending.
2698 */
2699 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TRPM_SYNC_IDT))
2700 {
2701 if ( VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3)
2702 && EMIsRawRing0Enabled(pVM)
2703 && CSAMIsEnabled(pVM))
2704 {
2705 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2706 if (RT_FAILURE(rc))
2707 return rc;
2708 }
2709
2710 int rc = TRPMR3SyncIDT(pVM, pVCpu);
2711 if (RT_FAILURE(rc))
2712 return rc;
2713 }
2714
2715 /*
2716 * Sync TSS.
2717 */
2718 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_SELM_SYNC_TSS))
2719 {
2720 int rc = SELMR3SyncTSS(pVM, pVCpu);
2721 if (RT_FAILURE(rc))
2722 return rc;
2723 }
2724
2725 /*
2726 * Sync page directory.
2727 */
2728 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2729 {
2730 Assert(pVCpu->em.s.enmState != EMSTATE_WAIT_SIPI);
2731 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2732 if (RT_FAILURE(rc))
2733 return rc;
2734
2735 Assert(!VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT));
2736
2737 /* Prefetch pages for EIP and ESP. */
2738 /** @todo This is rather expensive. Should investigate if it really helps at all. */
2739 rc = PGMPrefetchPage(pVCpu, SELMToFlat(pVM, DIS_SELREG_CS, CPUMCTX2CORE(pCtx), pCtx->rip));
2740 if (rc == VINF_SUCCESS)
2741 rc = PGMPrefetchPage(pVCpu, SELMToFlat(pVM, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), pCtx->rsp));
2742 if (rc != VINF_SUCCESS)
2743 {
2744 if (rc != VINF_PGM_SYNC_CR3)
2745 {
2746 AssertLogRelMsgReturn(RT_FAILURE(rc), ("%Rrc\n", rc), VERR_IPE_UNEXPECTED_INFO_STATUS);
2747 return rc;
2748 }
2749 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2750 if (RT_FAILURE(rc))
2751 return rc;
2752 }
2753 /** @todo maybe prefetch the supervisor stack page as well */
2754 Assert(!VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT));
2755 }
2756
2757 /*
2758 * Allocate handy pages (just in case the above actions have consumed some pages).
2759 */
2760 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_PGM_NEED_HANDY_PAGES, VM_FF_PGM_NO_MEMORY))
2761 {
2762 int rc = PGMR3PhysAllocateHandyPages(pVM);
2763 if (RT_FAILURE(rc))
2764 return rc;
2765 }
2766
2767 /*
2768 * Check whether we're out of memory now.
2769 *
2770 * This may stem from some of the above actions or operations that has been executed
2771 * since we ran FFs. The allocate handy pages must for instance always be followed by
2772 * this check.
2773 */
2774 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY))
2775 return VINF_EM_NO_MEMORY;
2776
2777 return VINF_SUCCESS;
2778}
2779
2780
2781/**
2782 * Executes raw code.
2783 *
2784 * This function contains the raw-mode version of the inner
2785 * execution loop (the outer loop being in EMR3ExecuteVM()).
2786 *
2787 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE,
2788 * VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
2789 *
2790 * @param pVM VM handle.
2791 * @param pVCpu VMCPU handle.
2792 * @param pfFFDone Where to store an indicator telling whether or not
2793 * FFs were done before returning.
2794 */
2795static int emR3RawExecute(PVM pVM, PVMCPU pVCpu, bool *pfFFDone)
2796{
2797 STAM_REL_PROFILE_ADV_START(&pVCpu->em.s.StatRAWTotal, a);
2798
2799 int rc = VERR_INTERNAL_ERROR;
2800 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
2801 LogFlow(("emR3RawExecute: (cs:eip=%04x:%08x)\n", pCtx->cs, pCtx->eip));
2802 pVCpu->em.s.fForceRAW = false;
2803 *pfFFDone = false;
2804
2805
2806 /*
2807 *
2808 * Spin till we get a forced action or raw mode status code resulting in
2809 * in anything but VINF_SUCCESS or VINF_EM_RESCHEDULE_RAW.
2810 *
2811 */
2812 for (;;)
2813 {
2814 STAM_PROFILE_ADV_START(&pVCpu->em.s.StatRAWEntry, b);
2815
2816 /*
2817 * Check various preconditions.
2818 */
2819#ifdef VBOX_STRICT
2820 Assert(REMR3QueryPendingInterrupt(pVM, pVCpu) == REM_NO_PENDING_IRQ);
2821 Assert(pCtx->eflags.Bits.u1VM || (pCtx->ss & X86_SEL_RPL) == 3 || (pCtx->ss & X86_SEL_RPL) == 0);
2822 AssertMsg( (pCtx->eflags.u32 & X86_EFL_IF)
2823 || PATMShouldUseRawMode(pVM, (RTGCPTR)pCtx->eip),
2824 ("Tried to execute code with IF at EIP=%08x!\n", pCtx->eip));
2825 if ( !VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL)
2826 && PGMMapHasConflicts(pVM))
2827 {
2828 PGMMapCheck(pVM);
2829 AssertMsgFailed(("We should not get conflicts any longer!!!\n"));
2830 return VERR_INTERNAL_ERROR;
2831 }
2832#endif /* VBOX_STRICT */
2833
2834 /*
2835 * Process high priority pre-execution raw-mode FFs.
2836 */
2837 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
2838 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2839 {
2840 rc = emR3RawForcedActions(pVM, pVCpu, pCtx);
2841 if (rc != VINF_SUCCESS)
2842 break;
2843 }
2844
2845 /*
2846 * If we're going to execute ring-0 code, the guest state needs to
2847 * be modified a bit and some of the state components (IF, SS/CS RPL,
2848 * and perhaps EIP) needs to be stored with PATM.
2849 */
2850 rc = CPUMRawEnter(pVCpu, NULL);
2851 if (rc != VINF_SUCCESS)
2852 {
2853 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWEntry, b);
2854 break;
2855 }
2856
2857 /*
2858 * Scan code before executing it. Don't bother with user mode or V86 code
2859 */
2860 if ( (pCtx->ss & X86_SEL_RPL) <= 1
2861 && !pCtx->eflags.Bits.u1VM
2862 && !PATMIsPatchGCAddr(pVM, pCtx->eip))
2863 {
2864 STAM_PROFILE_ADV_SUSPEND(&pVCpu->em.s.StatRAWEntry, b);
2865 CSAMR3CheckCodeEx(pVM, CPUMCTX2CORE(pCtx), pCtx->eip);
2866 STAM_PROFILE_ADV_RESUME(&pVCpu->em.s.StatRAWEntry, b);
2867 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
2868 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2869 {
2870 rc = emR3RawForcedActions(pVM, pVCpu, pCtx);
2871 if (rc != VINF_SUCCESS)
2872 {
2873 rc = CPUMRawLeave(pVCpu, NULL, rc);
2874 break;
2875 }
2876 }
2877 }
2878
2879#ifdef LOG_ENABLED
2880 /*
2881 * Log important stuff before entering GC.
2882 */
2883 PPATMGCSTATE pGCState = PATMR3QueryGCStateHC(pVM);
2884 if (pCtx->eflags.Bits.u1VM)
2885 Log(("RV86: %04X:%08X IF=%d VMFlags=%x\n", pCtx->cs, pCtx->eip, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags));
2886 else if ((pCtx->ss & X86_SEL_RPL) == 1)
2887 {
2888 bool fCSAMScanned = CSAMIsPageScanned(pVM, (RTGCPTR)pCtx->eip);
2889 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));
2890 }
2891 else if ((pCtx->ss & X86_SEL_RPL) == 3)
2892 Log(("RR3: %08X ESP=%08X IF=%d VMFlags=%x\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags));
2893#endif /* LOG_ENABLED */
2894
2895
2896
2897 /*
2898 * Execute the code.
2899 */
2900 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWEntry, b);
2901 STAM_PROFILE_START(&pVCpu->em.s.StatRAWExec, c);
2902 rc = VMMR3RawRunGC(pVM, pVCpu);
2903 STAM_PROFILE_STOP(&pVCpu->em.s.StatRAWExec, c);
2904 STAM_PROFILE_ADV_START(&pVCpu->em.s.StatRAWTail, d);
2905
2906 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)));
2907 LogFlow(("VMMR3RawRunGC returned %Rrc\n", rc));
2908
2909
2910
2911 /*
2912 * Restore the real CPU state and deal with high priority post
2913 * execution FFs before doing anything else.
2914 */
2915 rc = CPUMRawLeave(pVCpu, NULL, rc);
2916 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
2917 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK)
2918 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_POST_MASK))
2919 rc = emR3HighPriorityPostForcedActions(pVM, pVCpu, rc);
2920
2921#ifdef VBOX_STRICT
2922 /*
2923 * Assert TSS consistency & rc vs patch code.
2924 */
2925 if ( !VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_SELM_SYNC_TSS | VMCPU_FF_SELM_SYNC_GDT) /* GDT implies TSS at the moment. */
2926 && EMIsRawRing0Enabled(pVM))
2927 SELMR3CheckTSS(pVM);
2928 switch (rc)
2929 {
2930 case VINF_SUCCESS:
2931 case VINF_EM_RAW_INTERRUPT:
2932 case VINF_PATM_PATCH_TRAP_PF:
2933 case VINF_PATM_PATCH_TRAP_GP:
2934 case VINF_PATM_PATCH_INT3:
2935 case VINF_PATM_CHECK_PATCH_PAGE:
2936 case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
2937 case VINF_EM_RAW_GUEST_TRAP:
2938 case VINF_EM_RESCHEDULE_RAW:
2939 break;
2940
2941 default:
2942 if (PATMIsPatchGCAddr(pVM, pCtx->eip) && !(pCtx->eflags.u32 & X86_EFL_TF))
2943 LogIt(NULL, 0, LOG_GROUP_PATM, ("Patch code interrupted at %RRv for reason %Rrc\n", (RTRCPTR)CPUMGetGuestEIP(pVCpu), rc));
2944 break;
2945 }
2946 /*
2947 * Let's go paranoid!
2948 */
2949 if ( !VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL)
2950 && PGMMapHasConflicts(pVM))
2951 {
2952 PGMMapCheck(pVM);
2953 AssertMsgFailed(("We should not get conflicts any longer!!! rc=%Rrc\n", rc));
2954 return VERR_INTERNAL_ERROR;
2955 }
2956#endif /* VBOX_STRICT */
2957
2958 /*
2959 * Process the returned status code.
2960 */
2961 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
2962 {
2963 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTail, d);
2964 break;
2965 }
2966 rc = emR3RawHandleRC(pVM, pVCpu, pCtx, rc);
2967 if (rc != VINF_SUCCESS)
2968 {
2969 rc = emR3RawUpdateForceFlag(pVM, pVCpu, pCtx, rc);
2970 if (rc != VINF_SUCCESS)
2971 {
2972 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTail, d);
2973 break;
2974 }
2975 }
2976
2977 /*
2978 * Check and execute forced actions.
2979 */
2980#ifdef VBOX_HIGH_RES_TIMERS_HACK
2981 TMTimerPollVoid(pVM, pVCpu);
2982#endif
2983 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTail, d);
2984 if ( VM_FF_ISPENDING(pVM, ~VM_FF_HIGH_PRIORITY_PRE_RAW_MASK | VM_FF_PGM_NO_MEMORY)
2985 || VMCPU_FF_ISPENDING(pVCpu, ~VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2986 {
2987 Assert(pCtx->eflags.Bits.u1VM || (pCtx->ss & X86_SEL_RPL) != 1);
2988
2989 STAM_REL_PROFILE_ADV_SUSPEND(&pVCpu->em.s.StatRAWTotal, a);
2990 rc = emR3ForcedActions(pVM, pVCpu, rc);
2991 STAM_REL_PROFILE_ADV_RESUME(&pVCpu->em.s.StatRAWTotal, a);
2992 if ( rc != VINF_SUCCESS
2993 && rc != VINF_EM_RESCHEDULE_RAW)
2994 {
2995 rc = emR3RawUpdateForceFlag(pVM, pVCpu, pCtx, rc);
2996 if (rc != VINF_SUCCESS)
2997 {
2998 *pfFFDone = true;
2999 break;
3000 }
3001 }
3002 }
3003 }
3004
3005 /*
3006 * Return to outer loop.
3007 */
3008#if defined(LOG_ENABLED) && defined(DEBUG)
3009 RTLogFlush(NULL);
3010#endif
3011 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatRAWTotal, a);
3012 return rc;
3013}
3014
3015
3016/**
3017 * Executes hardware accelerated raw code. (Intel VMX & AMD SVM)
3018 *
3019 * This function contains the raw-mode version of the inner
3020 * execution loop (the outer loop being in EMR3ExecuteVM()).
3021 *
3022 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE, VINF_EM_RESCHEDULE_RAW,
3023 * VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
3024 *
3025 * @param pVM VM handle.
3026 * @param pVCpu VMCPU handle.
3027 * @param pfFFDone Where to store an indicator telling whether or not
3028 * FFs were done before returning.
3029 */
3030static int emR3HwAccExecute(PVM pVM, PVMCPU pVCpu, bool *pfFFDone)
3031{
3032 int rc = VERR_INTERNAL_ERROR;
3033 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
3034
3035 LogFlow(("emR3HwAccExecute%d: (cs:eip=%04x:%RGv)\n", pVCpu->idCpu, pCtx->cs, (RTGCPTR)pCtx->rip));
3036 *pfFFDone = false;
3037
3038 STAM_COUNTER_INC(&pVCpu->em.s.StatHwAccExecuteEntry);
3039
3040#ifdef EM_NOTIFY_HWACCM
3041 HWACCMR3NotifyScheduled(pVCpu);
3042#endif
3043
3044 /*
3045 * Spin till we get a forced action which returns anything but VINF_SUCCESS.
3046 */
3047 for (;;)
3048 {
3049 STAM_PROFILE_ADV_START(&pVCpu->em.s.StatHwAccEntry, a);
3050
3051 /*
3052 * Process high priority pre-execution raw-mode FFs.
3053 */
3054 VMCPU_FF_CLEAR(pVCpu, (VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT | VMCPU_FF_TRPM_SYNC_IDT | VMCPU_FF_SELM_SYNC_TSS)); /* not relevant in HWACCM mode; shouldn't be set really. */
3055 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK)
3056 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_RAW_MASK))
3057 {
3058 rc = emR3RawForcedActions(pVM, pVCpu, pCtx);
3059 if (rc != VINF_SUCCESS)
3060 break;
3061 }
3062
3063#ifdef LOG_ENABLED
3064 /*
3065 * Log important stuff before entering GC.
3066 */
3067 if (TRPMHasTrap(pVCpu))
3068 Log(("CPU%d: Pending hardware interrupt=0x%x cs:rip=%04X:%RGv\n", pVCpu->idCpu, TRPMGetTrapNo(pVCpu), pCtx->cs, (RTGCPTR)pCtx->rip));
3069
3070 uint32_t cpl = CPUMGetGuestCPL(pVCpu, CPUMCTX2CORE(pCtx));
3071
3072 if (pVM->cCPUs == 1)
3073 {
3074 if (pCtx->eflags.Bits.u1VM)
3075 Log(("HWV86: %08X IF=%d\n", pCtx->eip, pCtx->eflags.Bits.u1IF));
3076 else if (CPUMIsGuestIn64BitCodeEx(pCtx))
3077 Log(("HWR%d: %04X:%RGv ESP=%RGv IF=%d IOPL=%d CR0=%x CR4=%x EFER=%x\n", cpl, pCtx->cs, (RTGCPTR)pCtx->rip, pCtx->rsp, pCtx->eflags.Bits.u1IF, pCtx->eflags.Bits.u2IOPL, (uint32_t)pCtx->cr0, (uint32_t)pCtx->cr4, (uint32_t)pCtx->msrEFER));
3078 else
3079 Log(("HWR%d: %04X:%08X ESP=%08X IF=%d IOPL=%d CR0=%x CR4=%x EFER=%x\n", cpl, pCtx->cs, pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pCtx->eflags.Bits.u2IOPL, (uint32_t)pCtx->cr0, (uint32_t)pCtx->cr4, (uint32_t)pCtx->msrEFER));
3080 }
3081 else
3082 {
3083 if (pCtx->eflags.Bits.u1VM)
3084 Log(("HWV86-CPU%d: %08X IF=%d\n", pVCpu->idCpu, pCtx->eip, pCtx->eflags.Bits.u1IF));
3085 else if (CPUMIsGuestIn64BitCodeEx(pCtx))
3086 Log(("HWR%d-CPU%d: %04X:%RGv ESP=%RGv IF=%d IOPL=%d CR0=%x CR4=%x EFER=%x\n", cpl, pVCpu->idCpu, pCtx->cs, (RTGCPTR)pCtx->rip, pCtx->rsp, pCtx->eflags.Bits.u1IF, pCtx->eflags.Bits.u2IOPL, (uint32_t)pCtx->cr0, (uint32_t)pCtx->cr4, (uint32_t)pCtx->msrEFER));
3087 else
3088 Log(("HWR%d-CPU%d: %04X:%08X ESP=%08X IF=%d IOPL=%d CR0=%x CR4=%x EFER=%x\n", cpl, pVCpu->idCpu, pCtx->cs, pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pCtx->eflags.Bits.u2IOPL, (uint32_t)pCtx->cr0, (uint32_t)pCtx->cr4, (uint32_t)pCtx->msrEFER));
3089 }
3090#endif /* LOG_ENABLED */
3091
3092 /*
3093 * Execute the code.
3094 */
3095 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatHwAccEntry, a);
3096 STAM_PROFILE_START(&pVCpu->em.s.StatHwAccExec, x);
3097 rc = VMMR3HwAccRunGC(pVM, pVCpu);
3098 STAM_PROFILE_STOP(&pVCpu->em.s.StatHwAccExec, x);
3099
3100 /*
3101 * Deal with high priority post execution FFs before doing anything else.
3102 */
3103 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_RESUME_GUEST_MASK);
3104 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK)
3105 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_POST_MASK))
3106 rc = emR3HighPriorityPostForcedActions(pVM, pVCpu, rc);
3107
3108 /*
3109 * Process the returned status code.
3110 */
3111 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
3112 break;
3113
3114 rc = emR3RawHandleRC(pVM, pVCpu, pCtx, rc);
3115 if (rc != VINF_SUCCESS)
3116 break;
3117
3118 /*
3119 * Check and execute forced actions.
3120 */
3121#ifdef VBOX_HIGH_RES_TIMERS_HACK
3122 TMTimerPollVoid(pVM, pVCpu);
3123#endif
3124 if ( VM_FF_ISPENDING(pVM, VM_FF_ALL_MASK)
3125 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_ALL_MASK))
3126 {
3127 rc = emR3ForcedActions(pVM, pVCpu, rc);
3128 if ( rc != VINF_SUCCESS
3129 && rc != VINF_EM_RESCHEDULE_HWACC)
3130 {
3131 *pfFFDone = true;
3132 break;
3133 }
3134 }
3135 }
3136
3137 /*
3138 * Return to outer loop.
3139 */
3140#if defined(LOG_ENABLED) && defined(DEBUG)
3141 RTLogFlush(NULL);
3142#endif
3143 return rc;
3144}
3145
3146
3147/**
3148 * Decides whether to execute RAW, HWACC or REM.
3149 *
3150 * @returns new EM state
3151 * @param pVM The VM.
3152 * @param pVCpu The VMCPU handle.
3153 * @param pCtx The CPU context.
3154 */
3155static EMSTATE emR3Reschedule(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3156{
3157 /*
3158 * When forcing raw-mode execution, things are simple.
3159 */
3160 if (pVCpu->em.s.fForceRAW)
3161 return EMSTATE_RAW;
3162
3163 /*
3164 * We stay in the wait for SIPI state unless explicitly told otherwise.
3165 */
3166 if (pVCpu->em.s.enmState == EMSTATE_WAIT_SIPI)
3167 return EMSTATE_WAIT_SIPI;
3168
3169 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
3170 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
3171 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
3172
3173 X86EFLAGS EFlags = pCtx->eflags;
3174 if (HWACCMIsEnabled(pVM))
3175 {
3176 /* Hardware accelerated raw-mode:
3177 *
3178 * Typically only 32-bits protected mode, with paging enabled, code is allowed here.
3179 */
3180 if (HWACCMR3CanExecuteGuest(pVM, pCtx) == true)
3181 return EMSTATE_HWACC;
3182
3183 /* Note: Raw mode and hw accelerated mode are incompatible. The latter turns
3184 * off monitoring features essential for raw mode! */
3185 return EMSTATE_REM;
3186 }
3187
3188 /*
3189 * Standard raw-mode:
3190 *
3191 * Here we only support 16 & 32 bits protected mode ring 3 code that has no IO privileges
3192 * or 32 bits protected mode ring 0 code
3193 *
3194 * The tests are ordered by the likelyhood of being true during normal execution.
3195 */
3196 if (EFlags.u32 & (X86_EFL_TF /* | HF_INHIBIT_IRQ_MASK*/))
3197 {
3198 Log2(("raw mode refused: EFlags=%#x\n", EFlags.u32));
3199 return EMSTATE_REM;
3200 }
3201
3202#ifndef VBOX_RAW_V86
3203 if (EFlags.u32 & X86_EFL_VM) {
3204 Log2(("raw mode refused: VM_MASK\n"));
3205 return EMSTATE_REM;
3206 }
3207#endif
3208
3209 /** @todo check up the X86_CR0_AM flag in respect to raw mode!!! We're probably not emulating it right! */
3210 uint32_t u32CR0 = pCtx->cr0;
3211 if ((u32CR0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
3212 {
3213 //Log2(("raw mode refused: %s%s%s\n", (u32CR0 & X86_CR0_PG) ? "" : " !PG", (u32CR0 & X86_CR0_PE) ? "" : " !PE", (u32CR0 & X86_CR0_AM) ? "" : " !AM"));
3214 return EMSTATE_REM;
3215 }
3216
3217 if (pCtx->cr4 & X86_CR4_PAE)
3218 {
3219 uint32_t u32Dummy, u32Features;
3220
3221 CPUMGetGuestCpuId(pVCpu, 1, &u32Dummy, &u32Dummy, &u32Dummy, &u32Features);
3222 if (!(u32Features & X86_CPUID_FEATURE_EDX_PAE))
3223 return EMSTATE_REM;
3224 }
3225
3226 unsigned uSS = pCtx->ss;
3227 if ( pCtx->eflags.Bits.u1VM
3228 || (uSS & X86_SEL_RPL) == 3)
3229 {
3230 if (!EMIsRawRing3Enabled(pVM))
3231 return EMSTATE_REM;
3232
3233 if (!(EFlags.u32 & X86_EFL_IF))
3234 {
3235 Log2(("raw mode refused: IF (RawR3)\n"));
3236 return EMSTATE_REM;
3237 }
3238
3239 if (!(u32CR0 & X86_CR0_WP) && EMIsRawRing0Enabled(pVM))
3240 {
3241 Log2(("raw mode refused: CR0.WP + RawR0\n"));
3242 return EMSTATE_REM;
3243 }
3244 }
3245 else
3246 {
3247 if (!EMIsRawRing0Enabled(pVM))
3248 return EMSTATE_REM;
3249
3250 /* Only ring 0 supervisor code. */
3251 if ((uSS & X86_SEL_RPL) != 0)
3252 {
3253 Log2(("raw r0 mode refused: CPL %d\n", uSS & X86_SEL_RPL));
3254 return EMSTATE_REM;
3255 }
3256
3257 // Let's start with pure 32 bits ring 0 code first
3258 /** @todo What's pure 32-bit mode? flat? */
3259 if ( !(pCtx->ssHid.Attr.n.u1DefBig)
3260 || !(pCtx->csHid.Attr.n.u1DefBig))
3261 {
3262 Log2(("raw r0 mode refused: SS/CS not 32bit\n"));
3263 return EMSTATE_REM;
3264 }
3265
3266 /* Write protection must be turned on, or else the guest can overwrite our hypervisor code and data. */
3267 if (!(u32CR0 & X86_CR0_WP))
3268 {
3269 Log2(("raw r0 mode refused: CR0.WP=0!\n"));
3270 return EMSTATE_REM;
3271 }
3272
3273 if (PATMShouldUseRawMode(pVM, (RTGCPTR)pCtx->eip))
3274 {
3275 Log2(("raw r0 mode forced: patch code\n"));
3276 return EMSTATE_RAW;
3277 }
3278
3279#if !defined(VBOX_ALLOW_IF0) && !defined(VBOX_RUN_INTERRUPT_GATE_HANDLERS)
3280 if (!(EFlags.u32 & X86_EFL_IF))
3281 {
3282 ////Log2(("R0: IF=0 VIF=%d %08X\n", eip, pVMeflags));
3283 //Log2(("RR0: Interrupts turned off; fall back to emulation\n"));
3284 return EMSTATE_REM;
3285 }
3286#endif
3287
3288 /** @todo still necessary??? */
3289 if (EFlags.Bits.u2IOPL != 0)
3290 {
3291 Log2(("raw r0 mode refused: IOPL %d\n", EFlags.Bits.u2IOPL));
3292 return EMSTATE_REM;
3293 }
3294 }
3295
3296 Assert(PGMPhysIsA20Enabled(pVCpu));
3297 return EMSTATE_RAW;
3298}
3299
3300
3301/**
3302 * Executes all high priority post execution force actions.
3303 *
3304 * @returns rc or a fatal status code.
3305 *
3306 * @param pVM VM handle.
3307 * @param pVCpu VMCPU handle.
3308 * @param rc The current rc.
3309 */
3310static int emR3HighPriorityPostForcedActions(PVM pVM, PVMCPU pVCpu, int rc)
3311{
3312 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PDM_CRITSECT))
3313 PDMCritSectFF(pVCpu);
3314
3315 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_CSAM_PENDING_ACTION))
3316 CSAMR3DoPendingAction(pVM, pVCpu);
3317
3318 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY))
3319 {
3320 if ( rc > VINF_EM_NO_MEMORY
3321 && rc <= VINF_EM_LAST)
3322 rc = VINF_EM_NO_MEMORY;
3323 }
3324
3325 return rc;
3326}
3327
3328
3329/**
3330 * Executes all pending forced actions.
3331 *
3332 * Forced actions can cause execution delays and execution
3333 * rescheduling. The first we deal with using action priority, so
3334 * that for instance pending timers aren't scheduled and ran until
3335 * right before execution. The rescheduling we deal with using
3336 * return codes. The same goes for VM termination, only in that case
3337 * we exit everything.
3338 *
3339 * @returns VBox status code of equal or greater importance/severity than rc.
3340 * The most important ones are: VINF_EM_RESCHEDULE,
3341 * VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
3342 *
3343 * @param pVM VM handle.
3344 * @param pVCpu VMCPU handle.
3345 * @param rc The current rc.
3346 *
3347 */
3348static int emR3ForcedActions(PVM pVM, PVMCPU pVCpu, int rc)
3349{
3350 STAM_REL_PROFILE_START(&pVCpu->em.s.StatForcedActions, a);
3351#ifdef VBOX_STRICT
3352 int rcIrq = VINF_SUCCESS;
3353#endif
3354 int rc2;
3355#define UPDATE_RC() \
3356 do { \
3357 AssertMsg(rc2 <= 0 || (rc2 >= VINF_EM_FIRST && rc2 <= VINF_EM_LAST), ("Invalid FF return code: %Rra\n", rc2)); \
3358 if (rc2 == VINF_SUCCESS || rc < VINF_SUCCESS) \
3359 break; \
3360 if (!rc || rc2 < rc) \
3361 rc = rc2; \
3362 } while (0)
3363
3364 /*
3365 * Post execution chunk first.
3366 */
3367 if ( VM_FF_ISPENDING(pVM, VM_FF_NORMAL_PRIORITY_POST_MASK)
3368 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_NORMAL_PRIORITY_POST_MASK))
3369 {
3370 /*
3371 * Termination request.
3372 */
3373 if (VM_FF_ISPENDING(pVM, VM_FF_TERMINATE))
3374 {
3375 Log2(("emR3ForcedActions: returns VINF_EM_TERMINATE\n"));
3376 STAM_REL_PROFILE_STOP(&pVCpu->em.s.StatForcedActions, a);
3377 return VINF_EM_TERMINATE;
3378 }
3379
3380 /*
3381 * Debugger Facility polling.
3382 */
3383 if (VM_FF_ISPENDING(pVM, VM_FF_DBGF))
3384 {
3385 rc2 = DBGFR3VMMForcedAction(pVM);
3386 UPDATE_RC();
3387 }
3388
3389 /*
3390 * Postponed reset request.
3391 */
3392 if (VM_FF_TESTANDCLEAR(pVM, VM_FF_RESET_BIT))
3393 {
3394 rc2 = VMR3Reset(pVM);
3395 UPDATE_RC();
3396 }
3397
3398 /*
3399 * CSAM page scanning.
3400 */
3401 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)
3402 && VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_CSAM_SCAN_PAGE))
3403 {
3404 PCPUMCTX pCtx = pVCpu->em.s.pCtx;
3405
3406 /** @todo: check for 16 or 32 bits code! (D bit in the code selector) */
3407 Log(("Forced action VMCPU_FF_CSAM_SCAN_PAGE\n"));
3408
3409 CSAMR3CheckCodeEx(pVM, CPUMCTX2CORE(pCtx), pCtx->eip);
3410 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_CSAM_SCAN_PAGE);
3411 }
3412
3413 /*
3414 * Out of memory? Putting this after CSAM as it may in theory cause us to run out of memory.
3415 */
3416 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY))
3417 {
3418 rc2 = PGMR3PhysAllocateHandyPages(pVM);
3419 UPDATE_RC();
3420 if (rc == VINF_EM_NO_MEMORY)
3421 return rc;
3422 }
3423
3424 /* check that we got them all */
3425 AssertCompile(VM_FF_NORMAL_PRIORITY_POST_MASK == (VM_FF_TERMINATE | VM_FF_DBGF | VM_FF_RESET | VM_FF_PGM_NO_MEMORY));
3426 AssertCompile(VMCPU_FF_NORMAL_PRIORITY_POST_MASK == VMCPU_FF_CSAM_SCAN_PAGE);
3427 }
3428
3429 /*
3430 * Normal priority then.
3431 * (Executed in no particular order.)
3432 */
3433 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_NORMAL_PRIORITY_MASK, VM_FF_PGM_NO_MEMORY))
3434 {
3435 /*
3436 * PDM Queues are pending.
3437 */
3438 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_PDM_QUEUES, VM_FF_PGM_NO_MEMORY))
3439 PDMR3QueueFlushAll(pVM);
3440
3441 /*
3442 * PDM DMA transfers are pending.
3443 */
3444 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_PDM_DMA, VM_FF_PGM_NO_MEMORY))
3445 PDMR3DmaRun(pVM);
3446
3447 /*
3448 * Requests from other threads.
3449 */
3450 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_REQUEST, VM_FF_PGM_NO_MEMORY))
3451 {
3452 rc2 = VMR3ReqProcessU(pVM->pUVM, VMCPUID_ANY);
3453 Assert(rc2 != VINF_EM_RESET); /* should be per-VCPU */
3454 if (rc2 == VINF_EM_OFF || rc2 == VINF_EM_TERMINATE)
3455 {
3456 Log2(("emR3ForcedActions: returns %Rrc\n", rc2));
3457 STAM_REL_PROFILE_STOP(&pVCpu->em.s.StatForcedActions, a);
3458 return rc2;
3459 }
3460 UPDATE_RC();
3461 }
3462
3463 /* Replay the handler notification changes. */
3464 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_REM_HANDLER_NOTIFY, VM_FF_PGM_NO_MEMORY))
3465 {
3466 EMR3RemLock(pVM);
3467 REMR3ReplayHandlerNotifications(pVM);
3468 EMR3RemUnlock(pVM);
3469 }
3470
3471 /* check that we got them all */
3472 AssertCompile(VM_FF_NORMAL_PRIORITY_MASK == (VM_FF_REQUEST | VM_FF_PDM_QUEUES | VM_FF_PDM_DMA | VM_FF_REM_HANDLER_NOTIFY));
3473 }
3474
3475 /*
3476 * Normal priority then. (per-VCPU)
3477 * (Executed in no particular order.)
3478 */
3479 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)
3480 && VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_NORMAL_PRIORITY_MASK))
3481 {
3482 /*
3483 * Requests from other threads.
3484 */
3485 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_REQUEST))
3486 {
3487 rc2 = VMR3ReqProcessU(pVM->pUVM, pVCpu->idCpu);
3488 if (rc2 == VINF_EM_OFF || rc2 == VINF_EM_TERMINATE || rc2 == VINF_EM_RESET)
3489 {
3490 Log2(("emR3ForcedActions: returns %Rrc\n", rc2));
3491 STAM_REL_PROFILE_STOP(&pVCpu->em.s.StatForcedActions, a);
3492 return rc2;
3493 }
3494 UPDATE_RC();
3495 }
3496
3497 /* check that we got them all */
3498 Assert(!(VMCPU_FF_NORMAL_PRIORITY_MASK & ~(VMCPU_FF_REQUEST)));
3499 }
3500
3501 /*
3502 * High priority pre execution chunk last.
3503 * (Executed in ascending priority order.)
3504 */
3505 if ( VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_MASK)
3506 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HIGH_PRIORITY_PRE_MASK))
3507 {
3508 /*
3509 * Timers before interrupts.
3510 */
3511 if ( VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TIMER)
3512 && !VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY))
3513 TMR3TimerQueuesDo(pVM);
3514
3515 /*
3516 * The instruction following an emulated STI should *always* be executed!
3517 */
3518 if ( VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
3519 && !VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY))
3520 {
3521 Log(("VM_FF_EMULATED_STI at %RGv successor %RGv\n", (RTGCPTR)CPUMGetGuestRIP(pVCpu), EMGetInhibitInterruptsPC(pVCpu)));
3522 if (CPUMGetGuestEIP(pVCpu) != EMGetInhibitInterruptsPC(pVCpu))
3523 {
3524 /* Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here if the eip is the same as the inhibited instr address.
3525 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
3526 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
3527 * break the guest. Sounds very unlikely, but such timing sensitive problem are not as rare as you might think.
3528 */
3529 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3530 }
3531 if (HWACCMR3IsActive(pVCpu))
3532 rc2 = VINF_EM_RESCHEDULE_HWACC;
3533 else
3534 rc2 = PATMAreInterruptsEnabled(pVM) ? VINF_EM_RESCHEDULE_RAW : VINF_EM_RESCHEDULE_REM;
3535
3536 UPDATE_RC();
3537 }
3538
3539 /*
3540 * Interrupts.
3541 */
3542 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)
3543 && !VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
3544 && (!rc || rc >= VINF_EM_RESCHEDULE_HWACC)
3545 && !TRPMHasTrap(pVCpu) /* an interrupt could already be scheduled for dispatching in the recompiler. */
3546 && PATMAreInterruptsEnabled(pVM)
3547 && !HWACCMR3IsEventPending(pVM))
3548 {
3549 Assert(pVCpu->em.s.enmState != EMSTATE_WAIT_SIPI);
3550 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC))
3551 {
3552 /* Note: it's important to make sure the return code from TRPMR3InjectEvent isn't ignored! */
3553 /** @todo this really isn't nice, should properly handle this */
3554 rc2 = TRPMR3InjectEvent(pVM, pVCpu, TRPM_HARDWARE_INT);
3555#ifdef VBOX_STRICT
3556 rcIrq = rc2;
3557#endif
3558 UPDATE_RC();
3559 }
3560 /** @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. */
3561 else if (REMR3QueryPendingInterrupt(pVM, pVCpu) != REM_NO_PENDING_IRQ)
3562 {
3563 rc2 = VINF_EM_RESCHEDULE_REM;
3564 UPDATE_RC();
3565 }
3566 }
3567
3568 /*
3569 * Allocate handy pages.
3570 */
3571 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_PGM_NEED_HANDY_PAGES, VM_FF_PGM_NO_MEMORY))
3572 {
3573 rc2 = PGMR3PhysAllocateHandyPages(pVM);
3574 UPDATE_RC();
3575 }
3576
3577 /*
3578 * Debugger Facility request.
3579 */
3580 if (VM_FF_IS_PENDING_EXCEPT(pVM, VM_FF_DBGF, VM_FF_PGM_NO_MEMORY))
3581 {
3582 rc2 = DBGFR3VMMForcedAction(pVM);
3583 UPDATE_RC();
3584 }
3585
3586 /*
3587 * Termination request.
3588 */
3589 if (VM_FF_ISPENDING(pVM, VM_FF_TERMINATE))
3590 {
3591 Log2(("emR3ForcedActions: returns VINF_EM_TERMINATE\n"));
3592 STAM_REL_PROFILE_STOP(&pVCpu->em.s.StatForcedActions, a);
3593 return VINF_EM_TERMINATE;
3594 }
3595
3596 /*
3597 * Out of memory? Since most of our fellow high priority actions may cause us
3598 * to run out of memory, we're employing VM_FF_IS_PENDING_EXCEPT and putting this
3599 * at the end rather than the start. Also, VM_FF_TERMINATE has higher priority
3600 * than us since we can terminate without allocating more memory.
3601 */
3602 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY))
3603 {
3604 rc2 = PGMR3PhysAllocateHandyPages(pVM);
3605 UPDATE_RC();
3606 if (rc == VINF_EM_NO_MEMORY)
3607 return rc;
3608 }
3609
3610 /*
3611 * If the virtual sync clock is still stopped, make TM restart it.
3612 */
3613 if (VM_FF_ISPENDING(pVM, VM_FF_TM_VIRTUAL_SYNC))
3614 TMR3VirtualSyncFF(pVM, pVCpu);
3615
3616#ifdef DEBUG
3617 /*
3618 * Debug, pause the VM.
3619 */
3620 if (VM_FF_ISPENDING(pVM, VM_FF_DEBUG_SUSPEND))
3621 {
3622 VM_FF_CLEAR(pVM, VM_FF_DEBUG_SUSPEND);
3623 Log(("emR3ForcedActions: returns VINF_EM_SUSPEND\n"));
3624 return VINF_EM_SUSPEND;
3625 }
3626#endif
3627
3628 /* check that we got them all */
3629 AssertCompile(VM_FF_HIGH_PRIORITY_PRE_MASK == (VM_FF_TM_VIRTUAL_SYNC | VM_FF_DBGF | VM_FF_TERMINATE | VM_FF_DEBUG_SUSPEND | VM_FF_PGM_NEED_HANDY_PAGES | VM_FF_PGM_NO_MEMORY));
3630 AssertCompile(VMCPU_FF_HIGH_PRIORITY_PRE_MASK == (VMCPU_FF_TIMER | VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC | VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL | VMCPU_FF_SELM_SYNC_TSS | VMCPU_FF_TRPM_SYNC_IDT | VMCPU_FF_SELM_SYNC_GDT | VMCPU_FF_SELM_SYNC_LDT | VMCPU_FF_INHIBIT_INTERRUPTS));
3631 }
3632
3633#undef UPDATE_RC
3634 Log2(("emR3ForcedActions: returns %Rrc\n", rc));
3635 STAM_REL_PROFILE_STOP(&pVCpu->em.s.StatForcedActions, a);
3636 Assert(rcIrq == VINF_SUCCESS || rcIrq == rc);
3637 return rc;
3638}
3639
3640/**
3641 * Release the IOM lock if owned by the current VCPU
3642 *
3643 * @param pVM The VM to operate on.
3644 */
3645VMMR3DECL(void) EMR3ReleaseOwnedLocks(PVM pVM)
3646{
3647 while (PDMCritSectIsOwner(&pVM->em.s.CritSectREM))
3648 PDMCritSectLeave(&pVM->em.s.CritSectREM);
3649}
3650
3651
3652/**
3653 * Execute VM.
3654 *
3655 * This function is the main loop of the VM. The emulation thread
3656 * calls this function when the VM has been successfully constructed
3657 * and we're ready for executing the VM.
3658 *
3659 * Returning from this function means that the VM is turned off or
3660 * suspended (state already saved) and deconstruction in next in line.
3661 *
3662 * All interaction from other thread are done using forced actions
3663 * and signaling of the wait object.
3664 *
3665 * @returns VBox status code, informational status codes may indicate failure.
3666 * @param pVM The VM to operate on.
3667 * @param pVCpu The VMCPU to operate on.
3668 */
3669VMMR3DECL(int) EMR3ExecuteVM(PVM pVM, PVMCPU pVCpu)
3670{
3671 LogFlow(("EMR3ExecuteVM: pVM=%p enmVMState=%d enmState=%d (%s) fForceRAW=%d\n", pVM, pVM->enmVMState,
3672 pVCpu->em.s.enmState, EMR3GetStateName(pVCpu->em.s.enmState), pVCpu->em.s.fForceRAW));
3673 VM_ASSERT_EMT(pVM);
3674 AssertMsg( pVCpu->em.s.enmState == EMSTATE_NONE
3675 || pVCpu->em.s.enmState == EMSTATE_WAIT_SIPI
3676 || pVCpu->em.s.enmState == EMSTATE_SUSPENDED,
3677 ("%s\n", EMR3GetStateName(pVCpu->em.s.enmState)));
3678
3679 int rc = setjmp(pVCpu->em.s.u.FatalLongJump);
3680 if (rc == 0)
3681 {
3682 /*
3683 * Start the virtual time.
3684 */
3685 TMR3NotifyResume(pVM, pVCpu);
3686
3687 /*
3688 * The Outer Main Loop.
3689 */
3690 bool fFFDone = false;
3691
3692 /* Reschedule right away to start in the right state. */
3693 rc = VINF_SUCCESS;
3694
3695 /* If resuming after a pause or a state load, restore the previous
3696 state or else we'll start executing code. Else, just reschedule. */
3697 if ( pVCpu->em.s.enmState == EMSTATE_SUSPENDED
3698 && ( pVCpu->em.s.enmPrevState == EMSTATE_WAIT_SIPI
3699 || pVCpu->em.s.enmPrevState == EMSTATE_HALTED))
3700 pVCpu->em.s.enmState = pVCpu->em.s.enmPrevState;
3701 else
3702 pVCpu->em.s.enmState = emR3Reschedule(pVM, pVCpu, pVCpu->em.s.pCtx);
3703
3704 STAM_REL_PROFILE_ADV_START(&pVCpu->em.s.StatTotal, x);
3705 for (;;)
3706 {
3707 /*
3708 * Before we can schedule anything (we're here because
3709 * scheduling is required) we must service any pending
3710 * forced actions to avoid any pending action causing
3711 * immediate rescheduling upon entering an inner loop
3712 *
3713 * Do forced actions.
3714 */
3715 if ( !fFFDone
3716 && rc != VINF_EM_TERMINATE
3717 && rc != VINF_EM_OFF
3718 && ( VM_FF_ISPENDING(pVM, VM_FF_ALL_BUT_RAW_MASK)
3719 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_ALL_BUT_RAW_MASK)))
3720 {
3721 rc = emR3ForcedActions(pVM, pVCpu, rc);
3722 if ( ( rc == VINF_EM_RESCHEDULE_REM
3723 || rc == VINF_EM_RESCHEDULE_HWACC)
3724 && pVCpu->em.s.fForceRAW)
3725 rc = VINF_EM_RESCHEDULE_RAW;
3726 }
3727 else if (fFFDone)
3728 fFFDone = false;
3729
3730 /*
3731 * Now what to do?
3732 */
3733 Log2(("EMR3ExecuteVM: rc=%Rrc\n", rc));
3734 switch (rc)
3735 {
3736 /*
3737 * Keep doing what we're currently doing.
3738 */
3739 case VINF_SUCCESS:
3740 break;
3741
3742 /*
3743 * Reschedule - to raw-mode execution.
3744 */
3745 case VINF_EM_RESCHEDULE_RAW:
3746 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_RAW: %d -> %d (EMSTATE_RAW)\n", pVCpu->em.s.enmState, EMSTATE_RAW));
3747 pVCpu->em.s.enmState = EMSTATE_RAW;
3748 break;
3749
3750 /*
3751 * Reschedule - to hardware accelerated raw-mode execution.
3752 */
3753 case VINF_EM_RESCHEDULE_HWACC:
3754 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_HWACC: %d -> %d (EMSTATE_HWACC)\n", pVCpu->em.s.enmState, EMSTATE_HWACC));
3755 Assert(!pVCpu->em.s.fForceRAW);
3756 pVCpu->em.s.enmState = EMSTATE_HWACC;
3757 break;
3758
3759 /*
3760 * Reschedule - to recompiled execution.
3761 */
3762 case VINF_EM_RESCHEDULE_REM:
3763 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_REM: %d -> %d (EMSTATE_REM)\n", pVCpu->em.s.enmState, EMSTATE_REM));
3764 pVCpu->em.s.enmState = EMSTATE_REM;
3765 break;
3766
3767#ifdef VBOX_WITH_VMI
3768 /*
3769 * Reschedule - parav call.
3770 */
3771 case VINF_EM_RESCHEDULE_PARAV:
3772 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_PARAV: %d -> %d (EMSTATE_PARAV)\n", pVCpu->em.s.enmState, EMSTATE_PARAV));
3773 pVCpu->em.s.enmState = EMSTATE_PARAV;
3774 break;
3775#endif
3776
3777 /*
3778 * Resume.
3779 */
3780 case VINF_EM_RESUME:
3781 Log2(("EMR3ExecuteVM: VINF_EM_RESUME: %d -> VINF_EM_RESCHEDULE\n", pVCpu->em.s.enmState));
3782 /* Don't reschedule in the halted or wait for SIPI case. */
3783 if ( pVCpu->em.s.enmPrevState == EMSTATE_WAIT_SIPI
3784 || pVCpu->em.s.enmPrevState == EMSTATE_HALTED)
3785 break;
3786 /* fall through and get scheduled. */
3787
3788 /*
3789 * Reschedule.
3790 */
3791 case VINF_EM_RESCHEDULE:
3792 {
3793 EMSTATE enmState = emR3Reschedule(pVM, pVCpu, pVCpu->em.s.pCtx);
3794 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE: %d -> %d (%s)\n", pVCpu->em.s.enmState, enmState, EMR3GetStateName(enmState)));
3795 pVCpu->em.s.enmState = enmState;
3796 break;
3797 }
3798
3799 /*
3800 * Halted.
3801 */
3802 case VINF_EM_HALT:
3803 Log2(("EMR3ExecuteVM: VINF_EM_HALT: %d -> %d\n", pVCpu->em.s.enmState, EMSTATE_HALTED));
3804 pVCpu->em.s.enmState = EMSTATE_HALTED;
3805 break;
3806
3807 /*
3808 * Switch to the wait for SIPI state (application processor only)
3809 */
3810 case VINF_EM_WAIT_SIPI:
3811 Assert(pVCpu->idCpu != 0);
3812 Log2(("EMR3ExecuteVM: VINF_EM_WAIT_SIPI: %d -> %d\n", pVCpu->em.s.enmState, EMSTATE_WAIT_SIPI));
3813 pVCpu->em.s.enmState = EMSTATE_WAIT_SIPI;
3814 break;
3815
3816
3817 /*
3818 * Suspend.
3819 */
3820 case VINF_EM_SUSPEND:
3821 Log2(("EMR3ExecuteVM: VINF_EM_SUSPEND: %d -> %d\n", pVCpu->em.s.enmState, EMSTATE_SUSPENDED));
3822 pVCpu->em.s.enmPrevState = pVCpu->em.s.enmState;
3823 pVCpu->em.s.enmState = EMSTATE_SUSPENDED;
3824 break;
3825
3826 /*
3827 * Reset.
3828 * We might end up doing a double reset for now, we'll have to clean up the mess later.
3829 */
3830 case VINF_EM_RESET:
3831 {
3832 if (pVCpu->idCpu == 0)
3833 {
3834 EMSTATE enmState = emR3Reschedule(pVM, pVCpu, pVCpu->em.s.pCtx);
3835 Log2(("EMR3ExecuteVM: VINF_EM_RESET: %d -> %d (%s)\n", pVCpu->em.s.enmState, enmState, EMR3GetStateName(enmState)));
3836 pVCpu->em.s.enmState = enmState;
3837 }
3838 else
3839 {
3840 /* All other VCPUs go into the wait for SIPI state. */
3841 pVCpu->em.s.enmState = EMSTATE_WAIT_SIPI;
3842 }
3843 break;
3844 }
3845
3846 /*
3847 * Power Off.
3848 */
3849 case VINF_EM_OFF:
3850 pVCpu->em.s.enmState = EMSTATE_TERMINATING;
3851 Log2(("EMR3ExecuteVM: returns VINF_EM_OFF (%d -> %d)\n", pVCpu->em.s.enmState, EMSTATE_TERMINATING));
3852 TMR3NotifySuspend(pVM, pVCpu);
3853 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
3854 return rc;
3855
3856 /*
3857 * Terminate the VM.
3858 */
3859 case VINF_EM_TERMINATE:
3860 pVCpu->em.s.enmState = EMSTATE_TERMINATING;
3861 Log(("EMR3ExecuteVM returns VINF_EM_TERMINATE (%d -> %d)\n", pVCpu->em.s.enmState, EMSTATE_TERMINATING));
3862 TMR3NotifySuspend(pVM, pVCpu);
3863 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
3864 return rc;
3865
3866
3867 /*
3868 * Out of memory, suspend the VM and stuff.
3869 */
3870 case VINF_EM_NO_MEMORY:
3871 Log2(("EMR3ExecuteVM: VINF_EM_NO_MEMORY: %d -> %d\n", pVCpu->em.s.enmState, EMSTATE_SUSPENDED));
3872 pVCpu->em.s.enmState = EMSTATE_SUSPENDED;
3873 TMR3NotifySuspend(pVM, pVCpu);
3874 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
3875
3876 rc = VMSetRuntimeError(pVM, VMSETRTERR_FLAGS_SUSPEND, "HostMemoryLow",
3877 N_("Unable to allocate and lock memory. The virtual machine will be paused. Please close applications to free up memory or close the VM"));
3878 if (rc != VINF_EM_SUSPEND)
3879 {
3880 if (RT_SUCCESS_NP(rc))
3881 {
3882 AssertLogRelMsgFailed(("%Rrc\n", rc));
3883 rc = VERR_EM_INTERNAL_ERROR;
3884 }
3885 pVCpu->em.s.enmState = EMSTATE_GURU_MEDITATION;
3886 }
3887 return rc;
3888
3889 /*
3890 * Guest debug events.
3891 */
3892 case VINF_EM_DBG_STEPPED:
3893 AssertMsgFailed(("VINF_EM_DBG_STEPPED cannot be here!"));
3894 case VINF_EM_DBG_STOP:
3895 case VINF_EM_DBG_BREAKPOINT:
3896 case VINF_EM_DBG_STEP:
3897 if (pVCpu->em.s.enmState == EMSTATE_RAW)
3898 {
3899 Log2(("EMR3ExecuteVM: %Rrc: %d -> %d\n", rc, pVCpu->em.s.enmState, EMSTATE_DEBUG_GUEST_RAW));
3900 pVCpu->em.s.enmState = EMSTATE_DEBUG_GUEST_RAW;
3901 }
3902 else
3903 {
3904 Log2(("EMR3ExecuteVM: %Rrc: %d -> %d\n", rc, pVCpu->em.s.enmState, EMSTATE_DEBUG_GUEST_REM));
3905 pVCpu->em.s.enmState = EMSTATE_DEBUG_GUEST_REM;
3906 }
3907 break;
3908
3909 /*
3910 * Hypervisor debug events.
3911 */
3912 case VINF_EM_DBG_HYPER_STEPPED:
3913 case VINF_EM_DBG_HYPER_BREAKPOINT:
3914 case VINF_EM_DBG_HYPER_ASSERTION:
3915 Log2(("EMR3ExecuteVM: %Rrc: %d -> %d\n", rc, pVCpu->em.s.enmState, EMSTATE_DEBUG_HYPER));
3916 pVCpu->em.s.enmState = EMSTATE_DEBUG_HYPER;
3917 break;
3918
3919 /*
3920 * Guru mediations.
3921 */
3922 case VERR_VMM_RING0_ASSERTION:
3923 Log(("EMR3ExecuteVM: %Rrc: %d -> %d (EMSTATE_GURU_MEDITATION)\n", rc, pVCpu->em.s.enmState, EMSTATE_GURU_MEDITATION));
3924 pVCpu->em.s.enmState = EMSTATE_GURU_MEDITATION;
3925 break;
3926
3927 /*
3928 * Any error code showing up here other than the ones we
3929 * know and process above are considered to be FATAL.
3930 *
3931 * Unknown warnings and informational status codes are also
3932 * included in this.
3933 */
3934 default:
3935 if (RT_SUCCESS_NP(rc))
3936 {
3937 AssertMsgFailed(("Unexpected warning or informational status code %Rra!\n", rc));
3938 rc = VERR_EM_INTERNAL_ERROR;
3939 }
3940 pVCpu->em.s.enmState = EMSTATE_GURU_MEDITATION;
3941 Log(("EMR3ExecuteVM returns %d\n", rc));
3942 break;
3943 }
3944
3945 STAM_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x); /* (skip this in release) */
3946 STAM_PROFILE_ADV_START(&pVCpu->em.s.StatTotal, x);
3947
3948 /*
3949 * Act on the state.
3950 */
3951 switch (pVCpu->em.s.enmState)
3952 {
3953 /*
3954 * Execute raw.
3955 */
3956 case EMSTATE_RAW:
3957 rc = emR3RawExecute(pVM, pVCpu, &fFFDone);
3958 break;
3959
3960 /*
3961 * Execute hardware accelerated raw.
3962 */
3963 case EMSTATE_HWACC:
3964 rc = emR3HwAccExecute(pVM, pVCpu, &fFFDone);
3965 break;
3966
3967 /*
3968 * Execute recompiled.
3969 */
3970 case EMSTATE_REM:
3971 rc = emR3RemExecute(pVM, pVCpu, &fFFDone);
3972 Log2(("EMR3ExecuteVM: emR3RemExecute -> %Rrc\n", rc));
3973 break;
3974
3975#ifdef VBOX_WITH_VMI
3976 /*
3977 * Execute PARAV function.
3978 */
3979 case EMSTATE_PARAV:
3980 rc = PARAVCallFunction(pVM);
3981 pVCpu->em.s.enmState = EMSTATE_REM;
3982 break;
3983#endif
3984
3985 /*
3986 * Application processor execution halted until SIPI.
3987 */
3988 case EMSTATE_WAIT_SIPI:
3989 /* no break */
3990 /*
3991 * hlt - execution halted until interrupt.
3992 */
3993 case EMSTATE_HALTED:
3994 {
3995 STAM_REL_PROFILE_START(&pVCpu->em.s.StatHalted, y);
3996 rc = VMR3WaitHalted(pVM, pVCpu, !(CPUMGetGuestEFlags(pVCpu) & X86_EFL_IF));
3997 STAM_REL_PROFILE_STOP(&pVCpu->em.s.StatHalted, y);
3998 break;
3999 }
4000
4001 /*
4002 * Suspended - return to VM.cpp.
4003 */
4004 case EMSTATE_SUSPENDED:
4005 TMR3NotifySuspend(pVM, pVCpu);
4006 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
4007 return VINF_EM_SUSPEND;
4008
4009 /*
4010 * Debugging in the guest.
4011 */
4012 case EMSTATE_DEBUG_GUEST_REM:
4013 case EMSTATE_DEBUG_GUEST_RAW:
4014 TMR3NotifySuspend(pVM, pVCpu);
4015 rc = emR3Debug(pVM, pVCpu, rc);
4016 TMR3NotifyResume(pVM, pVCpu);
4017 Log2(("EMR3ExecuteVM: enmr3Debug -> %Rrc (state %d)\n", rc, pVCpu->em.s.enmState));
4018 break;
4019
4020 /*
4021 * Debugging in the hypervisor.
4022 */
4023 case EMSTATE_DEBUG_HYPER:
4024 {
4025 TMR3NotifySuspend(pVM, pVCpu);
4026 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
4027
4028 rc = emR3Debug(pVM, pVCpu, rc);
4029 Log2(("EMR3ExecuteVM: enmr3Debug -> %Rrc (state %d)\n", rc, pVCpu->em.s.enmState));
4030 if (rc != VINF_SUCCESS)
4031 {
4032 /* switch to guru meditation mode */
4033 pVCpu->em.s.enmState = EMSTATE_GURU_MEDITATION;
4034 VMMR3FatalDump(pVM, pVCpu, rc);
4035 return rc;
4036 }
4037
4038 STAM_REL_PROFILE_ADV_START(&pVCpu->em.s.StatTotal, x);
4039 TMR3NotifyResume(pVM, pVCpu);
4040 break;
4041 }
4042
4043 /*
4044 * Guru meditation takes place in the debugger.
4045 */
4046 case EMSTATE_GURU_MEDITATION:
4047 {
4048 TMR3NotifySuspend(pVM, pVCpu);
4049 VMMR3FatalDump(pVM, pVCpu, rc);
4050 emR3Debug(pVM, pVCpu, rc);
4051 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
4052 return rc;
4053 }
4054
4055 /*
4056 * The states we don't expect here.
4057 */
4058 case EMSTATE_NONE:
4059 case EMSTATE_TERMINATING:
4060 default:
4061 AssertMsgFailed(("EMR3ExecuteVM: Invalid state %d!\n", pVCpu->em.s.enmState));
4062 pVCpu->em.s.enmState = EMSTATE_GURU_MEDITATION;
4063 TMR3NotifySuspend(pVM, pVCpu);
4064 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
4065 return VERR_EM_INTERNAL_ERROR;
4066 }
4067 } /* The Outer Main Loop */
4068 }
4069 else
4070 {
4071 /*
4072 * Fatal error.
4073 */
4074 LogFlow(("EMR3ExecuteVM: returns %Rrc (longjmp / fatal error)\n", rc));
4075 TMR3NotifySuspend(pVM, pVCpu);
4076 VMMR3FatalDump(pVM, pVCpu, rc);
4077 emR3Debug(pVM, pVCpu, rc);
4078 STAM_REL_PROFILE_ADV_STOP(&pVCpu->em.s.StatTotal, x);
4079 /** @todo change the VM state! */
4080 return rc;
4081 }
4082
4083 /* (won't ever get here). */
4084 AssertFailed();
4085}
4086
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