VirtualBox

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

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

rcGC

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