VirtualBox

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

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

Removed wrong assertion.

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