VirtualBox

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

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

Put back RF flag

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 151.1 KB
Line 
1/* $Id: EM.cpp 2177 2007-04-18 13:46:52Z 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/**
968 * Steps hardware accelerated mode.
969 *
970 * @returns VBox status code.
971 * @param pVM The VM handle.
972 */
973static int emR3HwAccStep(PVM pVM)
974{
975 Assert(pVM->em.s.enmState == EMSTATE_DEBUG_GUEST_HWACC);
976
977 int rc;
978 PCPUMCTX pCtx = pVM->em.s.pCtx;
979 VM_FF_CLEAR(pVM, (VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT | VM_FF_TRPM_SYNC_IDT | VM_FF_SELM_SYNC_TSS));
980
981 /*
982 * Check vital forced actions, but ignore pending interrupts and timers.
983 */
984 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
985 {
986 rc = emR3RawForcedActions(pVM, pCtx);
987 if (VBOX_FAILURE(rc))
988 return rc;
989 }
990
991 /*
992 * Set flags for single stepping.
993 */
994 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) | X86_EFL_TF | X86_EFL_RF);
995
996 /*
997 * Single step.
998 * We do not start time or anything, if anything we should just do a few nanoseconds.
999 */
1000 do
1001 {
1002 rc = VMMR3HwAccRunGC(pVM);
1003 } while ( rc == VINF_SUCCESS
1004 || rc == VINF_EM_RAW_INTERRUPT);
1005 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
1006
1007 /*
1008 * Make sure the trap flag is cleared.
1009 * (Too bad if the guest is trying to single step too.)
1010 */
1011 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) & ~X86_EFL_TF);
1012
1013 /*
1014 * Deal with the return codes.
1015 */
1016 rc = emR3HighPriorityPostForcedActions(pVM, rc);
1017 rc = emR3RawHandleRC(pVM, pCtx, rc);
1018 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
1019 return rc;
1020}
1021
1022#ifdef DEBUG_sandervl
1023void emR3SingleStepExecRaw(PVM pVM, uint32_t cIterations)
1024{
1025 EMSTATE enmOldState = pVM->em.s.enmState;
1026 PCPUMCTX pCtx = pVM->em.s.pCtx;
1027
1028 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_RAW;
1029
1030 Log(("Single step BEGIN:\n"));
1031 for(uint32_t i=0;i<cIterations;i++)
1032 {
1033 DBGFR3PrgStep(pVM);
1034 DBGFR3DisasInstrCurrentLog(pVM, "RSS: ");
1035 emR3RawStep(pVM);
1036 }
1037 Log(("Single step END:\n"));
1038 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) & ~X86_EFL_TF);
1039 pVM->em.s.enmState = enmOldState;
1040}
1041
1042void emR3SingleStepExecHwAcc(PVM pVM, uint32_t cIterations)
1043{
1044 EMSTATE enmOldState = pVM->em.s.enmState;
1045 PCPUMCTX pCtx = pVM->em.s.pCtx;
1046
1047 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_HWACC;
1048
1049 Log(("Single step BEGIN:\n"));
1050 for(uint32_t i=0;i<cIterations;i++)
1051 {
1052 DBGFR3PrgStep(pVM);
1053 DBGFR3DisasInstrCurrentLog(pVM, "RSS: ");
1054 emR3HwAccStep(pVM);
1055 }
1056 Log(("Single step END:\n"));
1057 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) & ~X86_EFL_TF);
1058 pVM->em.s.enmState = enmOldState;
1059}
1060
1061void emR3SingleStepExecRem(PVM pVM, uint32_t cIterations)
1062{
1063 EMSTATE enmOldState = pVM->em.s.enmState;
1064 PCPUMCTX pCtx = pVM->em.s.pCtx;
1065
1066 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_REM;
1067
1068 Log(("Single step BEGIN:\n"));
1069 for(uint32_t i=0;i<cIterations;i++)
1070 {
1071 DBGFR3PrgStep(pVM);
1072 DBGFR3DisasInstrCurrentLog(pVM, "RSS: ");
1073 emR3RemStep(pVM);
1074 }
1075 Log(("Single step END:\n"));
1076 CPUMSetGuestEFlags(pVM, CPUMGetGuestEFlags(pVM) & ~X86_EFL_TF);
1077 pVM->em.s.enmState = enmOldState;
1078}
1079#endif
1080
1081/**
1082 * Executes one (or perhaps a few more) instruction(s).
1083 *
1084 * @returns VBox status code suitable for EM.
1085 *
1086 * @param pVM VM handle.
1087 * @param rcGC GC return code
1088 * @param pszPrefix Disassembly prefix. If not NULL we'll disassemble the
1089 * instruction and prefix the log output with this text.
1090 */
1091#ifdef LOG_ENABLED
1092static int emR3RawExecuteInstructionWorker(PVM pVM, int rcGC, const char *pszPrefix)
1093#else
1094static int emR3RawExecuteInstructionWorker(PVM pVM, int rcGC)
1095#endif
1096{
1097 PCPUMCTX pCtx = pVM->em.s.pCtx;
1098 int rc;
1099
1100 /*
1101 *
1102 * The simple solution is to use the recompiler.
1103 * The better solution is to disassemble the current instruction and
1104 * try handle as many as possible without using REM.
1105 *
1106 */
1107
1108#ifdef LOG_ENABLED
1109 /*
1110 * Disassemble the instruction if requested.
1111 */
1112 if (pszPrefix)
1113 {
1114 DBGFR3InfoLog(pVM, "cpumguest", pszPrefix);
1115 DBGFR3DisasInstrCurrentLog(pVM, pszPrefix);
1116 }
1117#endif /* LOG_ENABLED */
1118
1119 /*
1120 * PATM is making life more interesting.
1121 * We cannot hand anything to REM which has an EIP inside patch code. So, we'll
1122 * tell PATM there is a trap in this code and have it take the appropriate actions
1123 * to allow us execute the code in REM.
1124 */
1125 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
1126 {
1127 Log(("emR3RawExecuteInstruction: In patch block. eip=%VGv\n", pCtx->eip));
1128
1129 RTGCPTR pNewEip;
1130 rc = PATMR3HandleTrap(pVM, pCtx, pCtx->eip, &pNewEip);
1131 switch (rc)
1132 {
1133 /*
1134 * It's not very useful to emulate a single instruction and then go back to raw
1135 * mode; just execute the whole block until IF is set again.
1136 */
1137 case VINF_SUCCESS:
1138 Log(("emR3RawExecuteInstruction: Executing instruction starting at new address %VGv IF=%d VMIF=%x\n",
1139 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1140 pCtx->eip = pNewEip;
1141 Assert(pCtx->eip);
1142
1143 if (pCtx->eflags.Bits.u1IF)
1144 {
1145 /*
1146 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1147 */
1148 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1149 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1150 }
1151 else if (rcGC == VINF_PATM_PENDING_IRQ_AFTER_IRET)
1152 {
1153 /* special case: iret, that sets IF, detected a pending irq/event */
1154 return emR3RawExecuteInstruction(pVM, "PATCHIRET");
1155 }
1156 return VINF_EM_RESCHEDULE_REM;
1157
1158 /*
1159 * One instruction.
1160 */
1161 case VINF_PATCH_EMULATE_INSTR:
1162 Log(("emR3RawExecuteInstruction: Emulate patched instruction at %VGv IF=%d VMIF=%x\n",
1163 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1164 pCtx->eip = pNewEip;
1165 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1166
1167 /*
1168 * The patch was disabled, hand it to the REM.
1169 */
1170 case VERR_PATCH_DISABLED:
1171 Log(("emR3RawExecuteInstruction: Disabled patch -> new eip %VGv IF=%d VMIF=%x\n",
1172 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1173 pCtx->eip = pNewEip;
1174 if (pCtx->eflags.Bits.u1IF)
1175 {
1176 /*
1177 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1178 */
1179 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1180 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1181 }
1182 return VINF_EM_RESCHEDULE_REM;
1183
1184 /* Force continued patch exection; usually due to write monitored stack. */
1185 case VINF_PATCH_CONTINUE:
1186 return VINF_SUCCESS;
1187
1188 default:
1189 AssertReleaseMsgFailed(("Unknown return code %Vrc from PATMR3HandleTrap\n", rc));
1190 return VERR_INTERNAL_ERROR;
1191 }
1192 }
1193
1194#if 0 /// @todo Sander, this breaks the linux image (panics). So, I'm disabling it for now. (OP_MOV triggers it btw.)
1195 DISCPUSTATE Cpu;
1196 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "GEN EMU");
1197 if (VBOX_SUCCESS(rc))
1198 {
1199 uint32_t size;
1200
1201 switch (Cpu.pCurInstr->opcode)
1202 {
1203 case OP_MOV:
1204 case OP_AND:
1205 case OP_OR:
1206 case OP_XOR:
1207 case OP_POP:
1208 case OP_INC:
1209 case OP_DEC:
1210 case OP_XCHG:
1211 STAM_PROFILE_START(&pVM->em.s.StatMiscEmu, a);
1212 rc = EMInterpretInstructionCPU(pVM, &Cpu, CPUMCTX2CORE(pCtx), 0, &size);
1213 if (VBOX_SUCCESS(rc))
1214 {
1215 pCtx->eip += Cpu.opsize;
1216 STAM_PROFILE_STOP(&pVM->em.s.StatMiscEmu, a);
1217 return rc;
1218 }
1219 if (rc != VERR_EM_INTERPRETER)
1220 AssertMsgFailedReturn(("rc=%Vrc\n", rc), rc);
1221 STAM_PROFILE_STOP(&pVM->em.s.StatMiscEmu, a);
1222 break;
1223 }
1224 }
1225#endif
1226 STAM_PROFILE_START(&pVM->em.s.StatREMEmu, a);
1227 rc = REMR3EmulateInstruction(pVM);
1228 STAM_PROFILE_STOP(&pVM->em.s.StatREMEmu, a);
1229
1230 return rc;
1231}
1232
1233
1234/**
1235 * Executes one (or perhaps a few more) instruction(s).
1236 * This is just a wrapper for discarding pszPrefix in non-logging builds.
1237 *
1238 * @returns VBox status code suitable for EM.
1239 * @param pVM VM handle.
1240 * @param pszPrefix Disassembly prefix. If not NULL we'll disassemble the
1241 * instruction and prefix the log output with this text.
1242 * @param rcGC GC return code
1243 */
1244DECLINLINE(int) emR3RawExecuteInstruction(PVM pVM, const char *pszPrefix, int rcGC)
1245{
1246#ifdef LOG_ENABLED
1247 return emR3RawExecuteInstructionWorker(pVM, rcGC, pszPrefix);
1248#else
1249 return emR3RawExecuteInstructionWorker(pVM, rcGC);
1250#endif
1251}
1252
1253/**
1254 * Executes one (or perhaps a few more) IO instruction(s).
1255 *
1256 * @returns VBox status code suitable for EM.
1257 * @param pVM VM handle.
1258 */
1259int emR3RawExecuteIOInstruction(PVM pVM)
1260{
1261 int rc;
1262 PCPUMCTX pCtx = pVM->em.s.pCtx;
1263
1264 STAM_PROFILE_START(&pVM->em.s.StatIOEmu, a);
1265
1266 /** @todo probably we should fall back to the recompiler; otherwise we'll go back and forth between HC & GC
1267 * as io instructions tend to come in packages of more than one
1268 */
1269 DISCPUSTATE Cpu;
1270 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "IO EMU");
1271 if (VBOX_SUCCESS(rc))
1272 {
1273#ifdef VBOX_WITH_STATISTICS
1274 switch (Cpu.pCurInstr->opcode)
1275 {
1276 case OP_INSB:
1277 case OP_INSWD:
1278 case OP_IN:
1279 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatIn);
1280 break;
1281
1282 case OP_OUTSB:
1283 case OP_OUTSWD:
1284 case OP_OUT:
1285 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatOut);
1286 break;
1287 }
1288#endif
1289
1290 if (!(Cpu.prefix & (PREFIX_REP | PREFIX_REPNE)))
1291 {
1292 OP_PARAMVAL ParmVal;
1293 int rc;
1294 switch (Cpu.pCurInstr->opcode)
1295 {
1296 case OP_IN:
1297 {
1298 rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), &Cpu, &Cpu.param2, &ParmVal, PARAM_SOURCE);
1299 if ( VBOX_FAILURE(rc)
1300 || ParmVal.type != PARMTYPE_IMMEDIATE)
1301 break;
1302
1303 if (!(Cpu.param1.flags & (USE_REG_GEN8 | USE_REG_GEN16 | USE_REG_GEN32)))
1304 break;
1305
1306 /* Make sure port access is allowed */
1307 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), ParmVal.val.val16, Cpu.param1.size);
1308 if (rc != VINF_SUCCESS)
1309 {
1310 if (rc == VINF_EM_RAW_GUEST_TRAP)
1311 rc = emR3RawGuestTrap(pVM);
1312
1313 return rc;
1314 }
1315
1316 uint32_t u32Value = 0;
1317 switch (Cpu.param1.size)
1318 {
1319 case 1:
1320 Assert(Cpu.param1.base.reg_gen8 == USE_REG_AL);
1321 rc = IOMIOPortRead(pVM, ParmVal.val.val16, &u32Value, sizeof(uint8_t));
1322 if (VBOX_SUCCESS(rc))
1323 {
1324 pCtx->eax = (pCtx->eax & ~0xFF) | (uint8_t)u32Value;
1325 Log(("EMU: in8 %x, %x\n", ParmVal.val.val16, pCtx->eax & 0xFF));
1326 pCtx->eip += Cpu.opsize;
1327 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1328 return rc;
1329 }
1330 AssertRC(rc);
1331 break;
1332
1333 case 2:
1334 Assert(Cpu.param1.base.reg_gen16 == USE_REG_AX);
1335 rc = IOMIOPortRead(pVM, ParmVal.val.val16, &u32Value, sizeof(uint16_t));
1336 if (VBOX_SUCCESS(rc))
1337 {
1338 pCtx->eax = (pCtx->eax & ~0xFFFF) | (uint16_t)u32Value;
1339 Log(("EMU: in16 %x, %x\n", ParmVal.val.val16, pCtx->eax & 0xFFFF));
1340 pCtx->eip += Cpu.opsize;
1341 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1342 return rc;
1343 }
1344 AssertRC(rc);
1345 break;
1346
1347 case 4:
1348 Assert(Cpu.param1.base.reg_gen32 == USE_REG_EAX);
1349 rc = IOMIOPortRead(pVM, ParmVal.val.val16, &u32Value, sizeof(uint32_t));
1350 if (VBOX_SUCCESS(rc))
1351 {
1352 pCtx->eax = u32Value;
1353 Log(("EMU: in32 %x, %x\n", ParmVal.val.val16, pCtx->eax));
1354 pCtx->eip += Cpu.opsize;
1355 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1356 return rc;
1357 }
1358 AssertRC(rc);
1359 break;
1360
1361 default:
1362 AssertMsgFailed(("Unexpected port size %d\n", ParmVal.size));
1363 break;
1364 }
1365 break;
1366 }
1367
1368 case OP_OUT:
1369 {
1370 // it really is the destination, but we're interested in the destination value. hence we specify PARAM_SOURCE (bit of a hack)
1371 rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), &Cpu, &Cpu.param1, &ParmVal, PARAM_SOURCE);
1372 if ( VBOX_FAILURE(rc)
1373 || ParmVal.type != PARMTYPE_IMMEDIATE)
1374 break;
1375 OP_PARAMVAL ParmVal2;
1376 rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), &Cpu, &Cpu.param2, &ParmVal2, PARAM_SOURCE);
1377 if ( VBOX_FAILURE(rc)
1378 || ParmVal2.type != PARMTYPE_IMMEDIATE)
1379 break;
1380
1381 /* Make sure port access is allowed */
1382 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), ParmVal.val.val16, Cpu.param1.size);
1383 if (rc != VINF_SUCCESS)
1384 {
1385 if (rc == VINF_EM_RAW_GUEST_TRAP)
1386 rc = emR3RawGuestTrap(pVM);
1387
1388 return rc;
1389 }
1390
1391 AssertMsg(Cpu.param2.size == ParmVal2.size, ("size %d vs %d\n", Cpu.param2.size, ParmVal2.size));
1392 switch (ParmVal2.size)
1393 {
1394 case 1:
1395 Log(("EMU: out8 %x, %x\n", ParmVal.val.val16, ParmVal2.val.val8));
1396 rc = IOMIOPortWrite(pVM, ParmVal.val.val16, ParmVal2.val.val8, sizeof(ParmVal2.val.val8));
1397 if (VBOX_SUCCESS(rc))
1398 {
1399 pCtx->eip += Cpu.opsize;
1400 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1401 return rc;
1402 }
1403 AssertRC(rc);
1404 break;
1405
1406 case 2:
1407 Log(("EMU: out16 %x, %x\n", ParmVal.val.val16, ParmVal2.val.val16));
1408 rc = IOMIOPortWrite(pVM, ParmVal.val.val16, ParmVal2.val.val16, sizeof(ParmVal2.val.val16));
1409 if (VBOX_SUCCESS(rc))
1410 {
1411 pCtx->eip += Cpu.opsize;
1412 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1413 return rc;
1414 }
1415 AssertRC(rc);
1416 break;
1417
1418 case 4:
1419 Log(("EMU: out32 %x, %x\n", ParmVal.val.val16, ParmVal2.val.val32));
1420 rc = IOMIOPortWrite(pVM, ParmVal.val.val16, ParmVal2.val.val32, sizeof(ParmVal2.val.val32));
1421 if (VBOX_SUCCESS(rc))
1422 {
1423 pCtx->eip += Cpu.opsize;
1424 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1425 return rc;
1426 }
1427 AssertRC(rc);
1428 break;
1429
1430 default:
1431 AssertMsgFailed(("Unexpected port size %d\n", ParmVal2.size));
1432 break;
1433 }
1434 break;
1435 }
1436
1437 default:
1438 break;
1439 }
1440 }//if(!(Cpu.prefix & (PREFIX_REP|PREFIX_REPNE))
1441 else if (Cpu.prefix & PREFIX_REP)
1442 {
1443 switch (Cpu.pCurInstr->opcode)
1444 {
1445 case OP_INSB:
1446 case OP_INSWD:
1447 {
1448 /*
1449 * Do not optimize the destination address decrement case (not worth the effort)
1450 * and likewise for 16 bit address size (would need to use and update only cx/di).
1451 */
1452 if (pCtx->eflags.Bits.u1DF || Cpu.addrmode != CPUMODE_32BIT)
1453 break;
1454 /*
1455 * Get port number and transfer count directly from the registers (no need to bother the
1456 * disassembler). And get the I/O register size from the opcode / prefix.
1457 */
1458 uint32_t uPort = pCtx->edx & 0xffff;
1459 RTGCUINTREG cTransfers = pCtx->ecx;
1460 unsigned cbUnit;
1461 if (Cpu.pCurInstr->opcode == OP_INSB)
1462 cbUnit = 1;
1463 else
1464 cbUnit = Cpu.opmode == CPUMODE_32BIT ? 4 : 2;
1465
1466 RTGCPTR GCPtrDst = pCtx->edi;
1467 uint32_t cpl = (pCtx->eflags.Bits.u1VM) ? 3 : (pCtx->ss & X86_SEL_RPL);
1468
1469 /* Access verification first; we can't recover from traps inside this instruction, as the port read cannot be repeated. */
1470 rc = PGMVerifyAccess(pVM, GCPtrDst, cTransfers * cbUnit,
1471 X86_PTE_RW | ((cpl == 3) ? X86_PTE_US : 0));
1472 if (rc != VINF_SUCCESS)
1473 {
1474 Log(("EMU: rep ins%d will generate a trap -> fallback, rc=%d\n", cbUnit * 8, rc));
1475 break;
1476 }
1477
1478 Log(("EMU: rep ins%d port %#x count %d\n", cbUnit * 8, uPort, cTransfers));
1479
1480 /* Make sure port access is allowed */
1481 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), uPort, cbUnit);
1482 if (rc != VINF_SUCCESS)
1483 {
1484 if (rc == VINF_EM_RAW_GUEST_TRAP)
1485 rc = emR3RawGuestTrap(pVM);
1486
1487 return rc;
1488 }
1489
1490 /*
1491 * If the device supports string transfers, ask it to do as
1492 * much as it wants. The rest is done with single-word transfers.
1493 */
1494 rc = IOMIOPortReadString(pVM, uPort, &GCPtrDst, &cTransfers, cbUnit);
1495 AssertRC(rc); Assert(cTransfers <= pCtx->ecx);
1496
1497 while (cTransfers && rc == VINF_SUCCESS)
1498 {
1499 uint32_t u32Value;
1500 rc = IOMIOPortRead(pVM, uPort, &u32Value, cbUnit);
1501 AssertRC(rc);
1502 int rc2 = PGMPhysWriteGCPtrDirty(pVM, GCPtrDst, &u32Value, cbUnit);
1503 AssertRC(rc2);
1504 GCPtrDst += cbUnit;
1505 cTransfers--;
1506 }
1507 pCtx->edi += (pCtx->ecx - cTransfers) * cbUnit;
1508 pCtx->ecx = cTransfers;
1509 if (!cTransfers && VBOX_SUCCESS(rc))
1510 pCtx->eip += Cpu.opsize;
1511 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1512 return rc;
1513 }
1514 case OP_OUTSB:
1515 case OP_OUTSWD:
1516 {
1517 /*
1518 * Do not optimize the source address decrement case (not worth the effort)
1519 * and likewise for 16 bit address size (would need to use and update only cx/si).
1520 */
1521 if (pCtx->eflags.Bits.u1DF || Cpu.addrmode != CPUMODE_32BIT)
1522 break;
1523 /*
1524 * Get port number and transfer count directly from the registers (no need to bother the
1525 * disassembler). And get the I/O register size from the opcode / prefix.
1526 */
1527 uint32_t uPort = pCtx->edx & 0xffff;
1528 RTGCUINTREG cTransfers = pCtx->ecx;
1529 unsigned cbUnit;
1530 if (Cpu.pCurInstr->opcode == OP_OUTSB)
1531 cbUnit = 1;
1532 else
1533 cbUnit = Cpu.opmode == CPUMODE_32BIT ? 4 : 2;
1534
1535 RTGCPTR GCPtrSrc = pCtx->esi;
1536 uint32_t cpl = (pCtx->eflags.Bits.u1VM) ? 3 : (pCtx->ss & X86_SEL_RPL);
1537
1538 /* Access verification first; we currently can't recover properly from traps inside this instruction */
1539 rc = PGMVerifyAccess(pVM, GCPtrSrc, cTransfers * cbUnit, ((cpl == 3) ? X86_PTE_US : 0));
1540 if (rc != VINF_SUCCESS)
1541 {
1542 Log(("EMU: rep outs%d will generate a trap -> fallback, rc=%d\n", cbUnit * 8, rc));
1543 break;
1544 }
1545
1546 Log(("EMU: rep outs%d port %#x count %d\n", cbUnit * 8, uPort, cTransfers));
1547
1548 /* Make sure port access is allowed */
1549 rc = IOMInterpretCheckPortIOAccess(pVM, CPUMCTX2CORE(pCtx), uPort, cbUnit);
1550 if (rc != VINF_SUCCESS)
1551 {
1552 if (rc == VINF_EM_RAW_GUEST_TRAP)
1553 rc = emR3RawGuestTrap(pVM);
1554
1555 return rc;
1556 }
1557
1558 /*
1559 * If the device supports string transfers, ask it to do as
1560 * much as it wants. The rest is done with single-word transfers.
1561 */
1562 rc = IOMIOPortWriteString(pVM, uPort, &GCPtrSrc, &cTransfers, cbUnit);
1563 AssertRC(rc); Assert(cTransfers <= pCtx->ecx);
1564
1565 while (cTransfers && rc == VINF_SUCCESS)
1566 {
1567 uint32_t u32Value;
1568 rc = PGMPhysReadGCPtr(pVM, &u32Value, GCPtrSrc, cbUnit);
1569 Assert(rc == VINF_SUCCESS);
1570 rc = IOMIOPortWrite(pVM, uPort, u32Value, cbUnit);
1571 AssertRC(rc);
1572 GCPtrSrc += cbUnit;
1573 cTransfers--;
1574 }
1575 pCtx->esi += (pCtx->ecx - cTransfers) * cbUnit;
1576 pCtx->ecx = cTransfers;
1577 if (!cTransfers && VBOX_SUCCESS(rc))
1578 pCtx->eip += Cpu.opsize;
1579 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1580 return rc;
1581 }
1582 }
1583 }//if(Cpu.prefix & PREFIX_REP)
1584 }
1585
1586 STAM_PROFILE_STOP(&pVM->em.s.StatIOEmu, a);
1587 return emR3RawExecuteInstruction(pVM, "IO: ");
1588}
1589
1590
1591/**
1592 * Handle a guest context trap.
1593 *
1594 * @returns VBox status code suitable for EM.
1595 * @param pVM VM handle.
1596 */
1597static int emR3RawGuestTrap(PVM pVM)
1598{
1599 PCPUMCTX pCtx = pVM->em.s.pCtx;
1600
1601 /*
1602 * Get the trap info.
1603 */
1604 uint8_t u8TrapNo;
1605 TRPMEVENT enmType;;
1606 RTGCUINT uErrorCode;
1607 RTGCUINTPTR uCR2;
1608 int rc = TRPMQueryTrapAll(pVM, &u8TrapNo, &enmType, &uErrorCode, &uCR2);
1609 if (VBOX_FAILURE(rc))
1610 {
1611 AssertReleaseMsgFailed(("No trap! (rc=%Vrc)\n", rc));
1612 return rc;
1613 }
1614
1615 /* Traps can be directly forwarded in hardware accelerated mode. */
1616 if (HWACCMR3IsActive(pVM))
1617 {
1618#ifdef LOGGING_ENABLED
1619 DBGFR3InfoLog(pVM, "cpumguest", "Guest trap");
1620 DBGFR3DisasInstrCurrentLog(pVM, "Guest trap");
1621#endif
1622 return VINF_EM_RESCHEDULE_HWACC;
1623 }
1624
1625 /** Scan kernel code that traps; we might not get another chance. */
1626 if ( (pCtx->ss & X86_SEL_RPL) <= 1
1627 && !pCtx->eflags.Bits.u1VM)
1628 {
1629 Assert(!PATMIsPatchGCAddr(pVM, pCtx->eip));
1630 CSAMR3CheckCodeEx(pVM, pCtx->cs, &pCtx->csHid, pCtx->eip);
1631 }
1632
1633 if (u8TrapNo == 6) /* (#UD) Invalid opcode. */
1634 {
1635 DISCPUSTATE cpu;
1636
1637 /* If MONITOR & MWAIT are supported, then interpret them here. */
1638 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &cpu, "Guest Trap (#UD): ");
1639 if ( VBOX_SUCCESS(rc)
1640 && (cpu.pCurInstr->opcode == OP_MONITOR || cpu.pCurInstr->opcode == OP_MWAIT))
1641 {
1642 uint32_t u32Dummy, u32Features, u32ExtFeatures, size;
1643
1644 CPUMGetGuestCpuId(pVM, 1, &u32Dummy, &u32Dummy, &u32ExtFeatures, &u32Features);
1645
1646 if (u32ExtFeatures & X86_CPUID_FEATURE_ECX_MONITOR)
1647 {
1648 rc = TRPMResetTrap(pVM);
1649 AssertRC(rc);
1650
1651 rc = EMInterpretInstructionCPU(pVM, &cpu, CPUMCTX2CORE(pCtx), 0, &size);
1652 if (VBOX_SUCCESS(rc))
1653 {
1654 pCtx->eip += cpu.opsize;
1655 return rc;
1656 }
1657 return emR3RawExecuteInstruction(pVM, "Monitor: ");
1658 }
1659 }
1660 }
1661 else if (u8TrapNo == 13) /* (#GP) Privileged exception */
1662 {
1663 DISCPUSTATE cpu;
1664
1665 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &cpu, "Guest Trap: ");
1666 if (VBOX_SUCCESS(rc) && (cpu.pCurInstr->optype & OPTYPE_PORTIO))
1667 {
1668 /*
1669 * We should really check the TSS for the IO bitmap, but it's not like this
1670 * lazy approach really makes things worse.
1671 */
1672 rc = TRPMResetTrap(pVM);
1673 AssertRC(rc);
1674 return emR3RawExecuteInstruction(pVM, "IO Guest Trap: ");
1675 }
1676 }
1677
1678#ifdef LOG_ENABLED
1679 DBGFR3InfoLog(pVM, "cpumguest", "Guest trap");
1680 DBGFR3DisasInstrCurrentLog(pVM, "Guest trap");
1681
1682 /* Get guest page information. */
1683 uint64_t fFlags = 0;
1684 RTGCPHYS GCPhys = 0;
1685 int rc2 = PGMGstGetPage(pVM, uCR2, &fFlags, &GCPhys);
1686 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",
1687 pCtx->cs, pCtx->eip, u8TrapNo, uErrorCode, uCR2, pCtx->cr0, (enmType == TRPM_SOFTWARE_INT) ? " software" : "", GCPhys, fFlags,
1688 fFlags & X86_PTE_P ? "P " : "NP", fFlags & X86_PTE_US ? "U" : "S",
1689 fFlags & X86_PTE_RW ? "RW" : "R0", fFlags & X86_PTE_G ? " G" : "", rc2));
1690#endif
1691
1692 /*
1693 * #PG has CR2.
1694 * (Because of stuff like above we must set CR2 in a delayed fashion.)
1695 */
1696 if (u8TrapNo == 14 /* #PG */)
1697 pCtx->cr2 = uCR2;
1698
1699 return VINF_EM_RESCHEDULE_REM;
1700}
1701
1702
1703/**
1704 * Handle a ring switch trap.
1705 * Need to do statistics and to install patches. The result is going to REM.
1706 *
1707 * @returns VBox status code suitable for EM.
1708 * @param pVM VM handle.
1709 */
1710int emR3RawRingSwitch(PVM pVM)
1711{
1712 int rc;
1713 DISCPUSTATE Cpu;
1714 PCPUMCTX pCtx = pVM->em.s.pCtx;
1715
1716 /*
1717 * sysenter, syscall & callgate
1718 */
1719 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "RSWITCH: ");
1720 if (VBOX_SUCCESS(rc))
1721 {
1722 if (Cpu.pCurInstr->opcode == OP_SYSENTER)
1723 {
1724 if (pCtx->SysEnter.cs != 0)
1725 {
1726 rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid, pCtx->eip),
1727 SELMIsSelector32Bit(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) ? PATMFL_CODE32 : 0);
1728 if (VBOX_SUCCESS(rc))
1729 {
1730 DBGFR3DisasInstrCurrentLog(pVM, "Patched sysenter instruction");
1731 return VINF_EM_RESCHEDULE_RAW;
1732 }
1733 }
1734 }
1735
1736#ifdef VBOX_WITH_STATISTICS
1737 switch (Cpu.pCurInstr->opcode)
1738 {
1739 case OP_SYSENTER:
1740 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysEnter);
1741 break;
1742 case OP_SYSEXIT:
1743 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysExit);
1744 break;
1745 case OP_SYSCALL:
1746 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysCall);
1747 break;
1748 case OP_SYSRET:
1749 STAM_COUNTER_INC(&pVM->em.s.CTXSUFF(pStats)->StatSysRet);
1750 break;
1751 }
1752#endif
1753 }
1754 else
1755 AssertRC(rc);
1756
1757 /* go to the REM to emulate a single instruction */
1758 return emR3RawExecuteInstruction(pVM, "RSWITCH: ");
1759}
1760
1761/**
1762 * Handle a trap (#PF or #GP) in patch code
1763 *
1764 * @returns VBox status code suitable for EM.
1765 * @param pVM VM handle.
1766 * @param pCtx CPU context
1767 * @param gcret GC return code
1768 */
1769int emR3PatchTrap(PVM pVM, PCPUMCTX pCtx, int gcret)
1770{
1771 uint8_t u8TrapNo;
1772 int rc;
1773 TRPMEVENT enmType;
1774 RTGCUINT uErrorCode;
1775 RTGCUINTPTR uCR2;
1776
1777 Assert(PATMIsPatchGCAddr(pVM, pCtx->eip));
1778
1779 if (gcret == VINF_PATM_PATCH_INT3)
1780 {
1781 u8TrapNo = 3;
1782 uCR2 = 0;
1783 uErrorCode = 0;
1784 }
1785 else
1786 if (gcret == VINF_PATM_PATCH_TRAP_GP)
1787 {
1788 /* No active trap in this case. Kind of ugly. */
1789 u8TrapNo = X86_XCPT_GP;
1790 uCR2 = 0;
1791 uErrorCode = 0;
1792 }
1793 else
1794 {
1795 rc = TRPMQueryTrapAll(pVM, &u8TrapNo, &enmType, &uErrorCode, &uCR2);
1796 if (VBOX_FAILURE(rc))
1797 {
1798 AssertReleaseMsgFailed(("emR3PatchTrap: no trap! (rc=%Vrc) gcret=%Vrc\n", rc, gcret));
1799 return rc;
1800 }
1801 /* Reset the trap as we'll execute the original instruction again. */
1802 TRPMResetTrap(pVM);
1803 }
1804
1805 /*
1806 * Deal with traps inside patch code.
1807 * (This code won't run outside GC.)
1808 */
1809 if (u8TrapNo != 1)
1810 {
1811#ifdef LOG_ENABLED
1812 DBGFR3InfoLog(pVM, "cpumguest", "Trap in patch code");
1813 DBGFR3DisasInstrCurrentLog(pVM, "Patch code");
1814
1815 DISCPUSTATE Cpu;
1816 int rc;
1817
1818 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "Patch code: ");
1819 if ( VBOX_SUCCESS(rc)
1820 && Cpu.pCurInstr->opcode == OP_IRET)
1821 {
1822 uint32_t eip, selCS, uEFlags;
1823
1824 /* Iret crashes are bad as we have already changed the flags on the stack */
1825 rc = PGMPhysReadGCPtr(pVM, &eip, pCtx->esp, 4);
1826 rc |= PGMPhysReadGCPtr(pVM, &selCS, pCtx->esp+4, 4);
1827 rc |= PGMPhysReadGCPtr(pVM, &uEFlags, pCtx->esp+8, 4);
1828 if (rc == VINF_SUCCESS)
1829 {
1830 if ( (uEFlags & X86_EFL_VM)
1831 || (selCS & X86_SEL_RPL) == 3)
1832 {
1833 uint32_t selSS, esp;
1834
1835 rc |= PGMPhysReadGCPtr(pVM, &esp, pCtx->esp + 12, 4);
1836 rc |= PGMPhysReadGCPtr(pVM, &selSS, pCtx->esp + 16, 4);
1837
1838 if (uEFlags & X86_EFL_VM)
1839 {
1840 uint32_t selDS, selES, selFS, selGS;
1841 rc = PGMPhysReadGCPtr(pVM, &selES, pCtx->esp + 20, 4);
1842 rc |= PGMPhysReadGCPtr(pVM, &selDS, pCtx->esp + 24, 4);
1843 rc |= PGMPhysReadGCPtr(pVM, &selFS, pCtx->esp + 28, 4);
1844 rc |= PGMPhysReadGCPtr(pVM, &selGS, pCtx->esp + 32, 4);
1845 if (rc == VINF_SUCCESS)
1846 {
1847 Log(("Patch code: IRET->VM stack frame: return address %04X:%VGv eflags=%08x ss:esp=%04X:%VGv\n", selCS, eip, uEFlags, selSS, esp));
1848 Log(("Patch code: IRET->VM stack frame: DS=%04X ES=%04X FS=%04X GS=%04X\n", selDS, selES, selFS, selGS));
1849 }
1850 }
1851 else
1852 Log(("Patch code: IRET stack frame: return address %04X:%VGv eflags=%08x ss:esp=%04X:%VGv\n", selCS, eip, uEFlags, selSS, esp));
1853 }
1854 else
1855 Log(("Patch code: IRET stack frame: return address %04X:%VGv eflags=%08x\n", selCS, eip, uEFlags));
1856 }
1857 }
1858#endif
1859 Log(("emR3PatchTrap: in patch: eip=%08x: trap=%02x err=%08x cr2=%08x cr0=%08x\n",
1860 pCtx->eip, u8TrapNo, uErrorCode, uCR2, pCtx->cr0));
1861
1862 RTGCPTR pNewEip;
1863 rc = PATMR3HandleTrap(pVM, pCtx, pCtx->eip, &pNewEip);
1864 switch (rc)
1865 {
1866 /*
1867 * Execute the faulting instruction.
1868 */
1869 case VINF_SUCCESS:
1870 {
1871 /** @todo execute a whole block */
1872 Log(("emR3PatchTrap: Executing faulting instruction at new address %VGv\n", pNewEip));
1873 if (!(pVM->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
1874 Log(("emR3PatchTrap: Virtual IF flag disabled!!\n"));
1875
1876 pCtx->eip = pNewEip;
1877 AssertRelease(pCtx->eip);
1878
1879 if (pCtx->eflags.Bits.u1IF)
1880 {
1881 /* Windows XP lets irets fault intentionally and then takes action based on the opcode; an
1882 * int3 patch overwrites it and leads to blue screens. Remove the patch in this case.
1883 */
1884 if ( u8TrapNo == X86_XCPT_GP
1885 && PATMIsInt3Patch(pVM, pCtx->eip, NULL, NULL))
1886 {
1887 /** @todo move to PATMR3HandleTrap */
1888 Log(("Possible Windows XP iret fault at %VGv\n", pCtx->eip));
1889 PATMR3RemovePatch(pVM, pCtx->eip);
1890 }
1891
1892 /** @todo Knoppix 5 regression when returning VINF_SUCCESS here and going back to raw mode. */
1893 /** @note possibly because a reschedule is required (e.g. iret to V86 code) */
1894
1895 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1896 /* Interrupts are enabled; just go back to the original instruction.
1897 return VINF_SUCCESS; */
1898 }
1899 return VINF_EM_RESCHEDULE_REM;
1900 }
1901
1902 /*
1903 * One instruction.
1904 */
1905 case VINF_PATCH_EMULATE_INSTR:
1906 Log(("emR3PatchTrap: Emulate patched instruction at %VGv IF=%d VMIF=%x\n",
1907 pNewEip, pCtx->eflags.Bits.u1IF, pVM->em.s.pPatmGCState->uVMFlags));
1908 pCtx->eip = pNewEip;
1909 AssertRelease(pCtx->eip);
1910 return emR3RawExecuteInstruction(pVM, "PATCHEMUL: ");
1911
1912 /*
1913 * The patch was disabled, hand it to the REM.
1914 */
1915 case VERR_PATCH_DISABLED:
1916 if (!(pVM->em.s.pPatmGCState->uVMFlags & X86_EFL_IF))
1917 Log(("emR3PatchTrap: Virtual IF flag disabled!!\n"));
1918 pCtx->eip = pNewEip;
1919 AssertRelease(pCtx->eip);
1920
1921 if (pCtx->eflags.Bits.u1IF)
1922 {
1923 /*
1924 * The last instruction in the patch block needs to be executed!! (sti/sysexit for example)
1925 */
1926 Log(("PATCH: IF=1 -> emulate last instruction as it can't be interrupted!!\n"));
1927 return emR3RawExecuteInstruction(pVM, "PATCHIR");
1928 }
1929 return VINF_EM_RESCHEDULE_REM;
1930
1931 /* Force continued patch exection; usually due to write monitored stack. */
1932 case VINF_PATCH_CONTINUE:
1933 return VINF_SUCCESS;
1934
1935 /*
1936 * Anything else is *fatal*.
1937 */
1938 default:
1939 AssertReleaseMsgFailed(("Unknown return code %Vrc from PATMR3HandleTrap!\n", rc));
1940 return VERR_INTERNAL_ERROR;
1941 }
1942 }
1943 return VINF_SUCCESS;
1944}
1945
1946
1947/**
1948 * Handle a privileged instruction.
1949 *
1950 * @returns VBox status code suitable for EM.
1951 * @param pVM VM handle.
1952 */
1953int emR3RawPrivileged(PVM pVM)
1954{
1955 STAM_PROFILE_START(&pVM->em.s.StatPrivEmu, a);
1956 PCPUMCTX pCtx = pVM->em.s.pCtx;
1957
1958 Assert(!pCtx->eflags.Bits.u1VM);
1959
1960 if (PATMIsEnabled(pVM))
1961 {
1962 /*
1963 * Check if in patch code.
1964 */
1965 if (PATMR3IsInsidePatchJump(pVM, pCtx->eip, NULL))
1966 {
1967#ifdef LOG_ENABLED
1968 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
1969#endif
1970 AssertMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08X\n", pCtx->eip));
1971 return VERR_EM_RAW_PATCH_CONFLICT;
1972 }
1973 if ( (pCtx->ss & X86_SEL_RPL) == 0
1974 && !pCtx->eflags.Bits.u1VM
1975 && !PATMIsPatchGCAddr(pVM, pCtx->eip))
1976 {
1977 int rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid, pCtx->eip),
1978 SELMIsSelector32Bit(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) ? PATMFL_CODE32 : 0);
1979 if (VBOX_SUCCESS(rc))
1980 {
1981#ifdef LOG_ENABLED
1982 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
1983#endif
1984 DBGFR3DisasInstrCurrentLog(pVM, "Patched privileged instruction");
1985 return VINF_SUCCESS;
1986 }
1987 }
1988 }
1989
1990#ifdef LOG_ENABLED
1991 if (!PATMIsPatchGCAddr(pVM, pCtx->eip))
1992 {
1993 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
1994 DBGFR3DisasInstrCurrentLog(pVM, "Privileged instr: ");
1995 }
1996#endif
1997
1998 /*
1999 * Instruction statistics and logging.
2000 */
2001 DISCPUSTATE Cpu;
2002 int rc;
2003
2004 rc = CPUMR3DisasmInstrCPU(pVM, pCtx, pCtx->eip, &Cpu, "PRIV: ");
2005 if (VBOX_SUCCESS(rc))
2006 {
2007#ifdef VBOX_WITH_STATISTICS
2008 PEMSTATS pStats = pVM->em.s.CTXSUFF(pStats);
2009 switch (Cpu.pCurInstr->opcode)
2010 {
2011 case OP_INVLPG:
2012 STAM_COUNTER_INC(&pStats->StatInvlpg);
2013 break;
2014 case OP_IRET:
2015 STAM_COUNTER_INC(&pStats->StatIret);
2016 break;
2017 case OP_CLI:
2018 STAM_COUNTER_INC(&pStats->StatCli);
2019 emR3RecordCli(pVM, pCtx->eip);
2020 break;
2021 case OP_STI:
2022 STAM_COUNTER_INC(&pStats->StatSti);
2023 break;
2024 case OP_INSB:
2025 case OP_INSWD:
2026 case OP_IN:
2027 case OP_OUTSB:
2028 case OP_OUTSWD:
2029 case OP_OUT:
2030 AssertMsgFailed(("Unexpected privileged exception due to port IO\n"));
2031 break;
2032
2033 case OP_MOV_CR:
2034 if (Cpu.param1.flags & USE_REG_GEN32)
2035 {
2036 //read
2037 Assert(Cpu.param2.flags & USE_REG_CR);
2038 Assert(Cpu.param2.base.reg_ctrl <= USE_REG_CR4);
2039 STAM_COUNTER_INC(&pStats->StatMovReadCR[Cpu.param2.base.reg_ctrl]);
2040 }
2041 else
2042 {
2043 //write
2044 Assert(Cpu.param1.flags & USE_REG_CR);
2045 Assert(Cpu.param1.base.reg_ctrl <= USE_REG_CR4);
2046 STAM_COUNTER_INC(&pStats->StatMovWriteCR[Cpu.param1.base.reg_ctrl]);
2047 }
2048 break;
2049
2050 case OP_MOV_DR:
2051 STAM_COUNTER_INC(&pStats->StatMovDRx);
2052 break;
2053 case OP_LLDT:
2054 STAM_COUNTER_INC(&pStats->StatMovLldt);
2055 break;
2056 case OP_LIDT:
2057 STAM_COUNTER_INC(&pStats->StatMovLidt);
2058 break;
2059 case OP_LGDT:
2060 STAM_COUNTER_INC(&pStats->StatMovLgdt);
2061 break;
2062 case OP_SYSENTER:
2063 STAM_COUNTER_INC(&pStats->StatSysEnter);
2064 break;
2065 case OP_SYSEXIT:
2066 STAM_COUNTER_INC(&pStats->StatSysExit);
2067 break;
2068 case OP_SYSCALL:
2069 STAM_COUNTER_INC(&pStats->StatSysCall);
2070 break;
2071 case OP_SYSRET:
2072 STAM_COUNTER_INC(&pStats->StatSysRet);
2073 break;
2074 case OP_HLT:
2075 STAM_COUNTER_INC(&pStats->StatHlt);
2076 break;
2077 default:
2078 STAM_COUNTER_INC(&pStats->StatMisc);
2079 Log4(("emR3RawPrivileged: opcode=%d\n", Cpu.pCurInstr->opcode));
2080 break;
2081 }
2082#endif
2083 if ( (pCtx->ss & X86_SEL_RPL) == 0
2084 && !pCtx->eflags.Bits.u1VM
2085 && SELMIsSelector32Bit(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid))
2086 {
2087 uint32_t size;
2088
2089 STAM_PROFILE_START(&pVM->em.s.StatPrivEmu, a);
2090 switch (Cpu.pCurInstr->opcode)
2091 {
2092 case OP_CLI:
2093 pCtx->eflags.u32 &= ~X86_EFL_IF;
2094 Assert(Cpu.opsize == 1);
2095 pCtx->eip += Cpu.opsize;
2096 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
2097 return VINF_EM_RESCHEDULE_REM; /* must go to the recompiler now! */
2098
2099 case OP_STI:
2100 pCtx->eflags.u32 |= X86_EFL_IF;
2101 EMSetInhibitInterruptsPC(pVM, pCtx->eip + Cpu.opsize);
2102 Assert(Cpu.opsize == 1);
2103 pCtx->eip += Cpu.opsize;
2104 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
2105 return VINF_SUCCESS;
2106
2107 case OP_HLT:
2108 if (PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip))
2109 {
2110 PATMTRANSSTATE enmState;
2111 RTGCPTR pOrgInstrGC = PATMR3PatchToGCPtr(pVM, pCtx->eip, &enmState);
2112
2113 if (enmState == PATMTRANS_OVERWRITTEN)
2114 {
2115 rc = PATMR3DetectConflict(pVM, pOrgInstrGC, pOrgInstrGC);
2116 Assert(rc == VERR_PATCH_DISABLED);
2117 /* Conflict detected, patch disabled */
2118 Log(("emR3RawPrivileged: detected conflict -> disabled patch at %VGv\n", pCtx->eip));
2119
2120 enmState = PATMTRANS_SAFE;
2121 }
2122
2123 /* The translation had better be successful. Otherwise we can't recover. */
2124 AssertReleaseMsg(pOrgInstrGC && enmState != PATMTRANS_OVERWRITTEN, ("Unable to translate instruction address at %VGv\n", pCtx->eip));
2125 if (enmState != PATMTRANS_OVERWRITTEN)
2126 pCtx->eip = pOrgInstrGC;
2127 }
2128 /* no break; we could just return VINF_EM_HALT here */
2129
2130 case OP_MOV_CR:
2131 case OP_MOV_DR:
2132#ifdef LOG_ENABLED
2133 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2134 {
2135 DBGFR3InfoLog(pVM, "cpumguest", "PRIV");
2136 DBGFR3DisasInstrCurrentLog(pVM, "Privileged instr: ");
2137 }
2138#endif
2139
2140 rc = EMInterpretInstructionCPU(pVM, &Cpu, CPUMCTX2CORE(pCtx), 0, &size);
2141 if (VBOX_SUCCESS(rc))
2142 {
2143 pCtx->eip += Cpu.opsize;
2144 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
2145
2146 if ( Cpu.pCurInstr->opcode == OP_MOV_CR
2147 && Cpu.param1.flags == USE_REG_CR /* write */
2148 )
2149 {
2150 /* Reschedule is necessary as the execution/paging mode might have changed. */
2151 return VINF_EM_RESCHEDULE;
2152 }
2153 return rc; /* can return VINF_EM_HALT as well. */
2154 }
2155 AssertMsgReturn(rc == VERR_EM_INTERPRETER, ("%Vrc\n", rc), rc);
2156 break; /* fall back to the recompiler */
2157 }
2158 STAM_PROFILE_STOP(&pVM->em.s.StatPrivEmu, a);
2159 }
2160 }
2161
2162 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2163 return emR3PatchTrap(pVM, pCtx, VINF_PATM_PATCH_TRAP_GP);
2164
2165 return emR3RawExecuteInstruction(pVM, "PRIV");
2166}
2167
2168
2169/**
2170 * Update the forced rawmode execution modifier.
2171 *
2172 * This function is called when we're returning from the raw-mode loop(s). If we're
2173 * in patch code, it will set a flag forcing execution to be resumed in raw-mode,
2174 * if not in patch code, the flag will be cleared.
2175 *
2176 * We should never interrupt patch code while it's being executed. Cli patches can
2177 * contain big code blocks, but they are always executed with IF=0. Other patches
2178 * replace single instructions and should be atomic.
2179 *
2180 * @returns Updated rc.
2181 *
2182 * @param pVM The VM handle.
2183 * @param pCtx The guest CPU context.
2184 * @param rc The result code.
2185 */
2186DECLINLINE(int) emR3RawUpdateForceFlag(PVM pVM, PCPUMCTX pCtx, int rc)
2187{
2188 if (PATMIsPatchGCAddr(pVM, pCtx->eip)) /** @todo check cs selector base/type */
2189 {
2190 /* ignore reschedule attempts. */
2191 switch (rc)
2192 {
2193 case VINF_EM_RESCHEDULE:
2194 case VINF_EM_RESCHEDULE_REM:
2195 rc = VINF_SUCCESS;
2196 break;
2197 }
2198 pVM->em.s.fForceRAW = true;
2199 }
2200 else
2201 pVM->em.s.fForceRAW = false;
2202 return rc;
2203}
2204
2205
2206/**
2207 * Process a subset of the raw-mode return code.
2208 *
2209 * Since we have to share this with raw-mode single stepping, this inline
2210 * function has been created to avoid code duplication.
2211 *
2212 * @returns VINF_SUCCESS if it's ok to continue raw mode.
2213 * @returns VBox status code to return to the EM main loop.
2214 *
2215 * @param pVM The VM handle
2216 * @param rc The return code.
2217 * @param pCtx The guest cpu context.
2218 */
2219DECLINLINE(int) emR3RawHandleRC(PVM pVM, PCPUMCTX pCtx, int rc)
2220{
2221 switch (rc)
2222 {
2223 /*
2224 * Common & simple ones.
2225 */
2226 case VINF_SUCCESS:
2227 break;
2228 case VINF_EM_RESCHEDULE_RAW:
2229 case VINF_EM_RESCHEDULE_HWACC:
2230 case VINF_EM_RAW_INTERRUPT:
2231 case VINF_EM_RAW_TO_R3:
2232 case VINF_EM_RAW_TIMER_PENDING:
2233 case VINF_EM_PENDING_REQUEST:
2234 rc = VINF_SUCCESS;
2235 break;
2236
2237 /*
2238 * Privileged instruction.
2239 */
2240 case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
2241 case VINF_PATM_PATCH_TRAP_GP:
2242 rc = emR3RawPrivileged(pVM);
2243 break;
2244
2245 /*
2246 * Got a trap which needs dispatching.
2247 */
2248 case VINF_EM_RAW_GUEST_TRAP:
2249 if (PATMR3IsInsidePatchJump(pVM, pCtx->eip, NULL))
2250 {
2251 AssertReleaseMsgFailed(("FATAL ERROR: executing random instruction inside generated patch jump %08X\n", CPUMGetGuestEIP(pVM)));
2252 rc = VERR_EM_RAW_PATCH_CONFLICT;
2253 break;
2254 }
2255
2256 Assert(TRPMHasTrap(pVM));
2257 Assert(!PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2258
2259 if (TRPMHasTrap(pVM))
2260 {
2261 uint8_t u8Interrupt;
2262 uint32_t uErrorCode;
2263 TRPMERRORCODE enmError = TRPM_TRAP_NO_ERRORCODE;
2264
2265 rc = TRPMQueryTrapAll(pVM, &u8Interrupt, NULL, &uErrorCode, NULL);
2266 AssertRC(rc);
2267
2268 if (uErrorCode != ~0U)
2269 enmError = TRPM_TRAP_HAS_ERRORCODE;
2270
2271 /* If the guest gate is marked unpatched, then we will check again if we can patch it. */
2272 if (TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) == TRPM_INVALID_HANDLER)
2273 {
2274 CSAMR3CheckGates(pVM, u8Interrupt, 1);
2275 Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8Interrupt, TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) != TRPM_INVALID_HANDLER));
2276
2277 /** If it was successful, then we could go back to raw mode. */
2278 if (TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) != TRPM_INVALID_HANDLER)
2279 {
2280 rc = TRPMForwardTrap(pVM, CPUMCTX2CORE(pCtx), u8Interrupt, uErrorCode, enmError, TRPM_TRAP);
2281 if (rc == VINF_SUCCESS /* Don't use VBOX_SUCCESS */)
2282 {
2283 TRPMResetTrap(pVM);
2284 return VINF_EM_RESCHEDULE_RAW;
2285 }
2286 }
2287 }
2288 }
2289 rc = emR3RawGuestTrap(pVM);
2290 break;
2291
2292 /*
2293 * Trap in patch code.
2294 */
2295 case VINF_PATM_PATCH_TRAP_PF:
2296 case VINF_PATM_PATCH_INT3:
2297 rc = emR3PatchTrap(pVM, pCtx, rc);
2298 break;
2299
2300 case VINF_PATM_DUPLICATE_FUNCTION:
2301 Assert(PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2302 rc = PATMR3DuplicateFunctionRequest(pVM, pCtx);
2303 AssertRC(rc);
2304 rc = VINF_SUCCESS;
2305 break;
2306
2307 case VINF_PATM_CHECK_PATCH_PAGE:
2308 rc = PATMR3HandleMonitoredPage(pVM);
2309 AssertRC(rc);
2310 rc = VINF_SUCCESS;
2311 break;
2312
2313 /*
2314 * Patch manager.
2315 */
2316 case VERR_EM_RAW_PATCH_CONFLICT:
2317 AssertReleaseMsgFailed(("%Vrc handling is not yet implemented\n", rc));
2318 break;
2319
2320 /*
2321 * Memory mapped I/O access - attempt to patch the instruction
2322 */
2323 case VINF_PATM_HC_MMIO_PATCH_READ:
2324 rc = PATMR3InstallPatch(pVM, SELMToFlat(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid, pCtx->eip),
2325 PATMFL_MMIO_ACCESS | (SELMIsSelector32Bit(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid) ? PATMFL_CODE32 : 0));
2326 if (VBOX_FAILURE(rc))
2327 rc = emR3RawExecuteInstruction(pVM, "MMIO");
2328 break;
2329
2330 case VINF_PATM_HC_MMIO_PATCH_WRITE:
2331 AssertFailed(); /* not yet implemented. */
2332 rc = emR3RawExecuteInstruction(pVM, "MMIO");
2333 break;
2334
2335 /*
2336 * Conflict or out of page tables.
2337 *
2338 * VM_FF_PGM_SYNC_CR3 is set by the hypervisor and all we need to
2339 * do here is to execute the pending forced actions.
2340 */
2341 case VINF_PGM_SYNC_CR3:
2342 AssertMsg(VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL),
2343 ("VINF_PGM_SYNC_CR3 and no VM_FF_PGM_SYNC_CR3*!\n"));
2344 rc = VINF_SUCCESS;
2345 break;
2346
2347 /*
2348 * Paging mode change.
2349 */
2350 case VINF_PGM_CHANGE_MODE:
2351 rc = PGMChangeMode(pVM, pCtx->cr0, pCtx->cr4, 0);
2352 if (VBOX_SUCCESS(rc))
2353 rc = VINF_EM_RESCHEDULE;
2354 break;
2355
2356 /*
2357 * CSAM wants to perform a task in ring-3. It has set an FF action flag.
2358 */
2359 case VINF_CSAM_PENDING_ACTION:
2360 rc = VINF_SUCCESS;
2361 break;
2362
2363 /*
2364 * Invoked Interrupt gate - must directly (!) go to the recompiler.
2365 */
2366 case VINF_EM_RAW_INTERRUPT_PENDING:
2367 case VINF_EM_RAW_RING_SWITCH_INT:
2368 {
2369 uint8_t u8Interrupt;
2370
2371 Assert(TRPMHasTrap(pVM));
2372 Assert(!PATMIsPatchGCAddr(pVM, (RTGCPTR)pCtx->eip));
2373
2374 if (TRPMHasTrap(pVM))
2375 {
2376 u8Interrupt = TRPMGetTrapNo(pVM);
2377
2378 /* If the guest gate is marked unpatched, then we will check again if we can patch it. */
2379 if (TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) == TRPM_INVALID_HANDLER)
2380 {
2381 CSAMR3CheckGates(pVM, u8Interrupt, 1);
2382 Log(("emR3RawHandleRC: recheck gate %x -> valid=%d\n", u8Interrupt, TRPMR3GetGuestTrapHandler(pVM, u8Interrupt) != TRPM_INVALID_HANDLER));
2383 /** @note If it was successful, then we could go back to raw mode, but let's keep things simple for now. */
2384 }
2385 }
2386 rc = VINF_EM_RESCHEDULE_REM;
2387 break;
2388 }
2389
2390 /*
2391 * Other ring switch types.
2392 */
2393 case VINF_EM_RAW_RING_SWITCH:
2394 rc = emR3RawRingSwitch(pVM);
2395 break;
2396
2397 /*
2398 * REMGCNotifyInvalidatePage() failed because of overflow.
2399 */
2400 case VERR_REM_FLUSHED_PAGES_OVERFLOW:
2401 Assert((pCtx->ss & X86_SEL_RPL) != 1);
2402 REMR3ReplayInvalidatedPages(pVM);
2403 break;
2404
2405 /*
2406 * I/O Port access - emulate the instruction.
2407 */
2408 case VINF_IOM_HC_IOPORT_READ:
2409 case VINF_IOM_HC_IOPORT_WRITE:
2410 case VINF_IOM_HC_IOPORT_READWRITE:
2411 rc = emR3RawExecuteIOInstruction(pVM);
2412 break;
2413
2414 /*
2415 * Memory mapped I/O access - emulate the instruction.
2416 */
2417 case VINF_IOM_HC_MMIO_READ:
2418 case VINF_IOM_HC_MMIO_WRITE:
2419 case VINF_IOM_HC_MMIO_READ_WRITE:
2420 rc = emR3RawExecuteInstruction(pVM, "MMIO");
2421 break;
2422
2423 /*
2424 * Execute instruction.
2425 */
2426 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
2427 rc = emR3RawExecuteInstruction(pVM, "LDT FAULT: ");
2428 break;
2429 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
2430 rc = emR3RawExecuteInstruction(pVM, "GDT FAULT: ");
2431 break;
2432 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
2433 rc = emR3RawExecuteInstruction(pVM, "IDT FAULT: ");
2434 break;
2435 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
2436 rc = emR3RawExecuteInstruction(pVM, "TSS FAULT: ");
2437 break;
2438 case VINF_EM_RAW_EMULATE_INSTR_PD_FAULT:
2439 rc = emR3RawExecuteInstruction(pVM, "PD FAULT: ");
2440 break;
2441
2442 case VINF_EM_RAW_EMULATE_INSTR_HLT:
2443 /** @todo skip instruction and go directly to the halt state. (see REM for implementation details) */
2444 rc = emR3RawPrivileged(pVM);
2445 break;
2446
2447 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
2448 rc = emR3RawExecuteInstruction(pVM, "EMUL: ", VINF_PATM_PENDING_IRQ_AFTER_IRET);
2449 break;
2450
2451 case VINF_EM_RAW_EMULATE_INSTR:
2452 case VINF_PATCH_EMULATE_INSTR:
2453 rc = emR3RawExecuteInstruction(pVM, "EMUL: ");
2454 break;
2455
2456 /*
2457 * Stale selector and iret traps => REM.
2458 */
2459 case VINF_EM_RAW_STALE_SELECTOR:
2460 case VINF_EM_RAW_IRET_TRAP:
2461 /* We will not go to the recompiler if EIP points to patch code. */
2462 if (PATMIsPatchGCAddr(pVM, pCtx->eip))
2463 {
2464 pCtx->eip = PATMR3PatchToGCPtr(pVM, (RTGCPTR)pCtx->eip, 0);
2465 }
2466 LogFlow(("emR3RawHandleRC: %Vrc -> %Vrc\n", rc, VINF_EM_RESCHEDULE_REM));
2467 rc = VINF_EM_RESCHEDULE_REM;
2468 break;
2469
2470 /*
2471 * Up a level.
2472 */
2473 case VINF_EM_TERMINATE:
2474 case VINF_EM_OFF:
2475 case VINF_EM_RESET:
2476 case VINF_EM_SUSPEND:
2477 case VINF_EM_HALT:
2478 case VINF_EM_RESUME:
2479 case VINF_EM_RESCHEDULE:
2480 case VINF_EM_RESCHEDULE_REM:
2481 break;
2482
2483 /*
2484 * Up a level and invoke the debugger.
2485 */
2486 case VINF_EM_DBG_STEPPED:
2487 case VINF_EM_DBG_BREAKPOINT:
2488 case VINF_EM_DBG_STEP:
2489 case VINF_EM_DBG_HYPER_ASSERTION:
2490 case VINF_EM_DBG_HYPER_BREAKPOINT:
2491 case VINF_EM_DBG_HYPER_STEPPED:
2492 case VINF_EM_DBG_STOP:
2493 break;
2494
2495 /*
2496 * Up a level, dump and debug.
2497 */
2498 case VERR_TRPM_DONT_PANIC:
2499 case VERR_TRPM_PANIC:
2500 break;
2501
2502 /*
2503 * Anything which is not known to us means an internal error
2504 * and the termination of the VM!
2505 */
2506 default:
2507 AssertMsgFailed(("Unknown GC return code: %Vra\n", rc));
2508 break;
2509 }
2510 return rc;
2511}
2512
2513/**
2514 * Check for pending raw actions
2515 *
2516 * @returns VBox status code.
2517 * @param pVM The VM to operate on.
2518 */
2519EMR3DECL(int) EMR3CheckRawForcedActions(PVM pVM)
2520{
2521 return emR3RawForcedActions(pVM, pVM->em.s.pCtx);
2522}
2523
2524
2525/**
2526 * Process raw-mode specific forced actions.
2527 *
2528 * This function is called when any FFs in the VM_FF_HIGH_PRIORITY_PRE_RAW_MASK is pending.
2529 *
2530 * @returns VBox status code.
2531 * Only the normal success/failure stuff, no VINF_EM_*.
2532 * @param pVM The VM handle.
2533 * @param pCtx The guest CPUM register context.
2534 */
2535static int emR3RawForcedActions(PVM pVM, PCPUMCTX pCtx)
2536{
2537 /*
2538 * Note that the order is *vitally* important!
2539 * Also note that SELMR3UpdateFromCPUM may trigger VM_FF_SELM_SYNC_TSS.
2540 */
2541
2542
2543 /*
2544 * Sync selector tables.
2545 */
2546 if (VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT))
2547 {
2548 int rc = SELMR3UpdateFromCPUM(pVM);
2549 if (VBOX_FAILURE(rc))
2550 return rc;
2551 }
2552
2553 /*
2554 * Sync IDT.
2555 */
2556 if (VM_FF_ISSET(pVM, VM_FF_TRPM_SYNC_IDT))
2557 {
2558 int rc = TRPMR3SyncIDT(pVM);
2559 if (VBOX_FAILURE(rc))
2560 return rc;
2561 }
2562
2563 /*
2564 * Sync TSS.
2565 */
2566 if (VM_FF_ISSET(pVM, VM_FF_SELM_SYNC_TSS))
2567 {
2568 int rc = SELMR3SyncTSS(pVM);
2569 if (VBOX_FAILURE(rc))
2570 return rc;
2571 }
2572
2573 /*
2574 * Sync page directory.
2575 */
2576 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL))
2577 {
2578 int rc = PGMSyncCR3(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4, VM_FF_ISSET(pVM, VM_FF_PGM_SYNC_CR3));
2579 if (VBOX_FAILURE(rc))
2580 return rc;
2581
2582 Assert(!VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT));
2583
2584 /* Prefetch pages for EIP and ESP */
2585 /** @todo This is rather expensive. Should investigate if it really helps at all. */
2586 rc = PGMPrefetchPage(pVM, SELMToFlat(pVM, pCtx->eflags, pCtx->cs, &pCtx->csHid, pCtx->eip));
2587 if (rc == VINF_SUCCESS)
2588 rc = PGMPrefetchPage(pVM, SELMToFlat(pVM, pCtx->eflags, pCtx->ss, &pCtx->ssHid, pCtx->esp));
2589 if (rc != VINF_SUCCESS)
2590 {
2591 if (rc != VINF_PGM_SYNC_CR3)
2592 return rc;
2593 rc = PGMSyncCR3(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4, VM_FF_ISSET(pVM, VM_FF_PGM_SYNC_CR3));
2594 if (VBOX_FAILURE(rc))
2595 return rc;
2596 }
2597 /** @todo maybe prefetch the supervisor stack page as well */
2598 }
2599
2600 return VINF_SUCCESS;
2601}
2602
2603
2604/**
2605 * Executes raw code.
2606 *
2607 * This function contains the raw-mode version of the inner
2608 * execution loop (the outer loop being in EMR3ExecuteVM()).
2609 *
2610 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE,
2611 * VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
2612 *
2613 * @param pVM VM handle.
2614 * @param pfFFDone Where to store an indicator telling whether or not
2615 * FFs were done before returning.
2616 */
2617static int emR3RawExecute(PVM pVM, bool *pfFFDone)
2618{
2619 STAM_PROFILE_ADV_START(&pVM->em.s.StatRAWTotal, a);
2620
2621 int rc = VERR_INTERNAL_ERROR;
2622 PCPUMCTX pCtx = pVM->em.s.pCtx;
2623 LogFlow(("emR3RawExecute: (cs:eip=%04x:%08x)\n", pCtx->cs, pCtx->eip));
2624 pVM->em.s.fForceRAW = false;
2625 *pfFFDone = false;
2626
2627
2628 /*
2629 *
2630 * Spin till we get a forced action or raw mode status code resulting in
2631 * in anything but VINF_SUCCESS or VINF_EM_RESCHEDULE_RAW.
2632 *
2633 */
2634 for (;;)
2635 {
2636 STAM_PROFILE_ADV_START(&pVM->em.s.StatRAWEntry, b);
2637
2638 /*
2639 * Check various preconditions.
2640 */
2641#ifdef VBOX_STRICT
2642 Assert(REMR3QueryPendingInterrupt(pVM) == REM_NO_PENDING_IRQ);
2643 Assert(!(pCtx->cr4 & X86_CR4_PAE));
2644 Assert(pCtx->eflags.Bits.u1VM || (pCtx->ss & X86_SEL_RPL) == 3 || (pCtx->ss & X86_SEL_RPL) == 0);
2645 AssertMsg( (pCtx->eflags.u32 & X86_EFL_IF)
2646 || PATMShouldUseRawMode(pVM, (RTGCPTR)pCtx->eip),
2647 ("Tried to execute code with IF at EIP=%08x!\n", pCtx->eip));
2648 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL)
2649 && PGMR3MapHasConflicts(pVM, pCtx->cr3, pVM->fRawR0Enabled))
2650 {
2651 AssertMsgFailed(("We should not get conflicts any longer!!!\n"));
2652 return VERR_INTERNAL_ERROR;
2653 }
2654#endif /* VBOX_STRICT */
2655
2656 /*
2657 * Process high priority pre-execution raw-mode FFs.
2658 */
2659 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2660 {
2661 rc = emR3RawForcedActions(pVM, pCtx);
2662 if (VBOX_FAILURE(rc))
2663 break;
2664 }
2665
2666 /*
2667 * If we're going to execute ring-0 code, the guest state needs to
2668 * be modified a bit and some of the state components (IF, SS/CS RPL,
2669 * and perhaps EIP) needs to be stored with PATM.
2670 */
2671 rc = CPUMRawEnter(pVM, NULL);
2672 if (rc != VINF_SUCCESS)
2673 {
2674 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWEntry, b);
2675 break;
2676 }
2677
2678 /*
2679 * Scan code before executing it. Don't bother with user mode or V86 code
2680 */
2681 if ( (pCtx->ss & X86_SEL_RPL) <= 1
2682 && !pCtx->eflags.Bits.u1VM
2683 && !PATMIsPatchGCAddr(pVM, pCtx->eip))
2684 {
2685 STAM_PROFILE_ADV_SUSPEND(&pVM->em.s.StatRAWEntry, b);
2686 CSAMR3CheckCodeEx(pVM, pCtx->cs, &pCtx->csHid, pCtx->eip);
2687 STAM_PROFILE_ADV_RESUME(&pVM->em.s.StatRAWEntry, b);
2688 }
2689
2690#ifdef LOG_ENABLED
2691 /*
2692 * Log important stuff before entering GC.
2693 */
2694 PPATMGCSTATE pGCState = PATMR3QueryGCStateHC(pVM);
2695 if (pCtx->eflags.Bits.u1VM)
2696 Log(("RV86: %04X:%08X IF=%d VMFlags=%x\n", pCtx->cs, pCtx->eip, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags));
2697 else if ((pCtx->ss & X86_SEL_RPL) == 1)
2698 {
2699 bool fCSAMScanned = CSAMIsPageScanned(pVM, (RTGCPTR)pCtx->eip);
2700 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));
2701 }
2702 else if ((pCtx->ss & X86_SEL_RPL) == 3)
2703 Log(("RR3: %08X ESP=%08X IF=%d VMFlags=%x\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, pGCState->uVMFlags));
2704#endif /* LOG_ENABLED */
2705
2706
2707
2708 /*
2709 * Execute the code.
2710 */
2711 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWEntry, b);
2712 STAM_PROFILE_START(&pVM->em.s.StatRAWExec, c);
2713 VMMR3Unlock(pVM);
2714 rc = VMMR3RawRunGC(pVM);
2715 VMMR3Lock(pVM);
2716 STAM_PROFILE_STOP(&pVM->em.s.StatRAWExec, c);
2717 STAM_PROFILE_ADV_START(&pVM->em.s.StatRAWTail, d);
2718
2719 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)));
2720 LogFlow(("VMMR3RawRunGC returned %Vrc\n", rc));
2721
2722 /*
2723 * Restore the real CPU state and deal with high priority post
2724 * execution FFs before doing anything else.
2725 */
2726 rc = CPUMRawLeave(pVM, NULL, rc);
2727 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
2728 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK))
2729 rc = emR3HighPriorityPostForcedActions(pVM, rc);
2730
2731#ifdef PGM_CACHE_VERY_STRICT
2732 /*
2733 * Page manager cache checks.
2734 */
2735 if ( rc == VINF_EM_RAW_INTERRUPT
2736 || rc == VINF_EM_RAW_GUEST_TRAP
2737 || rc == VINF_IOM_HC_IOPORT_READ
2738 || rc == VINF_IOM_HC_IOPORT_WRITE
2739 || rc == VINF_IOM_HC_IOPORT_READWRITE
2740 //|| rc == VINF_PATM_PATCH_INT3
2741 )
2742 pgmCacheCheckPD(pVM, pCtx->cr0, pCtx->cr3, pCtx->cr4);
2743#endif
2744
2745#ifdef VBOX_STRICT
2746 /*
2747 * Assert TSS consistency & rc vs patch code.
2748 */
2749 if ( !VM_FF_ISPENDING(pVM, VM_FF_SELM_SYNC_TSS | VM_FF_SELM_SYNC_GDT) /* GDT implies TSS at the moment. */
2750 && EMIsRawRing0Enabled(pVM))
2751 SELMR3CheckTSS(pVM);
2752 switch (rc)
2753 {
2754 case VINF_SUCCESS:
2755 case VINF_EM_RAW_INTERRUPT:
2756 case VINF_PATM_PATCH_TRAP_PF:
2757 case VINF_PATM_PATCH_TRAP_GP:
2758 case VINF_PATM_PATCH_INT3:
2759 case VINF_PATM_CHECK_PATCH_PAGE:
2760 case VINF_EM_RAW_EXCEPTION_PRIVILEGED:
2761 case VINF_EM_RAW_GUEST_TRAP:
2762 case VINF_EM_RESCHEDULE_RAW:
2763 break;
2764
2765 default:
2766 if (PATMIsPatchGCAddr(pVM, pCtx->eip) && !(pCtx->eflags.u32 & X86_EFL_TF))
2767 LogIt(NULL, 0, LOG_GROUP_PATM, ("Patch code interrupted at %VGv for reason %Vrc\n", CPUMGetGuestEIP(pVM), rc));
2768 break;
2769 }
2770 /*
2771 * Let's go paranoid!
2772 */
2773 if ( !VM_FF_ISPENDING(pVM, VM_FF_PGM_SYNC_CR3 | VM_FF_PGM_SYNC_CR3_NON_GLOBAL)
2774 && PGMR3MapHasConflicts(pVM, pCtx->cr3, pVM->fRawR0Enabled))
2775 {
2776 AssertMsgFailed(("We should not get conflicts any longer!!!\n"));
2777 return VERR_INTERNAL_ERROR;
2778 }
2779#endif /* VBOX_STRICT */
2780
2781 /*
2782 * Process the returned status code.
2783 */
2784 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
2785 {
2786 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTail, d);
2787 break;
2788 }
2789 rc = emR3RawHandleRC(pVM, pCtx, rc);
2790 if (rc != VINF_SUCCESS)
2791 {
2792 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
2793 if (rc != VINF_SUCCESS)
2794 {
2795 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTail, d);
2796 break;
2797 }
2798 }
2799
2800 /*
2801 * Check and execute forced actions.
2802 */
2803#ifdef VBOX_HIGH_RES_TIMERS_HACK
2804 TMTimerPoll(pVM);
2805#endif
2806 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTail, d);
2807 if (VM_FF_ISPENDING(pVM, ~VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2808 {
2809 Assert(pCtx->eflags.Bits.u1VM || (pCtx->ss & X86_SEL_RPL) != 1);
2810
2811 STAM_PROFILE_ADV_SUSPEND(&pVM->em.s.StatRAWTotal, a);
2812 rc = emR3ForcedActions(pVM, rc);
2813 STAM_PROFILE_ADV_RESUME(&pVM->em.s.StatRAWTotal, a);
2814 if ( rc != VINF_SUCCESS
2815 && rc != VINF_EM_RESCHEDULE_RAW)
2816 {
2817 rc = emR3RawUpdateForceFlag(pVM, pCtx, rc);
2818 if (rc != VINF_SUCCESS)
2819 {
2820 *pfFFDone = true;
2821 break;
2822 }
2823 }
2824 }
2825 }
2826
2827 /*
2828 * Return to outer loop.
2829 */
2830#if defined(LOG_ENABLED) && defined(DEBUG)
2831 RTLogFlush(NULL);
2832#endif
2833 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatRAWTotal, a);
2834 return rc;
2835}
2836
2837
2838/**
2839 * Executes hardware accelerated raw code. (Intel VMX & AMD SVM)
2840 *
2841 * This function contains the raw-mode version of the inner
2842 * execution loop (the outer loop being in EMR3ExecuteVM()).
2843 *
2844 * @returns VBox status code. The most important ones are: VINF_EM_RESCHEDULE, VINF_EM_RESCHEDULE_RAW,
2845 * VINF_EM_RESCHEDULE_REM, VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
2846 *
2847 * @param pVM VM handle.
2848 * @param pfFFDone Where to store an indicator telling whether or not
2849 * FFs were done before returning.
2850 */
2851static int emR3HwAccExecute(PVM pVM, bool *pfFFDone)
2852{
2853 int rc = VERR_INTERNAL_ERROR;
2854 PCPUMCTX pCtx = pVM->em.s.pCtx;
2855
2856 LogFlow(("emR3HwAccExecute: (cs:eip=%04x:%08x)\n", pCtx->cs, pCtx->eip));
2857 *pfFFDone = false;
2858
2859 STAM_COUNTER_INC(&pVM->em.s.StatHwAccExecuteEntry);
2860
2861 /*
2862 * Spin till we get a forced action which returns anything but VINF_SUCCESS.
2863 */
2864 for (;;)
2865 {
2866 STAM_PROFILE_ADV_START(&pVM->em.s.StatHwAccEntry, a);
2867
2868 /*
2869 * Check various preconditions.
2870 */
2871 VM_FF_CLEAR(pVM, (VM_FF_SELM_SYNC_GDT | VM_FF_SELM_SYNC_LDT | VM_FF_TRPM_SYNC_IDT | VM_FF_SELM_SYNC_TSS));
2872
2873 /*
2874 * Process high priority pre-execution raw-mode FFs.
2875 */
2876 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_RAW_MASK))
2877 {
2878 rc = emR3RawForcedActions(pVM, pCtx);
2879 if (VBOX_FAILURE(rc))
2880 break;
2881 }
2882
2883#ifdef LOG_ENABLED
2884 uint8_t u8Vector;
2885
2886 rc = TRPMQueryTrapAll(pVM, &u8Vector, 0, 0, 0);
2887 if (rc == VINF_SUCCESS)
2888 {
2889 Log(("Pending hardware interrupt %d\n", u8Vector));
2890 }
2891 /*
2892 * Log important stuff before entering GC.
2893 */
2894 if (pCtx->eflags.Bits.u1VM)
2895 Log(("HWV86: %08X IF=%d\n", pCtx->eip, pCtx->eflags.Bits.u1IF));
2896 else if ((pCtx->ss & X86_SEL_RPL) == 0)
2897 Log(("HWR0: %08X ESP=%08X IF=%d CPL=%d\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF, (pCtx->ss & X86_SEL_RPL)));
2898 else if ((pCtx->ss & X86_SEL_RPL) == 3)
2899 Log(("HWR3: %08X ESP=%08X IF=%d\n", pCtx->eip, pCtx->esp, pCtx->eflags.Bits.u1IF));
2900#endif
2901
2902
2903 /*
2904 * Execute the code.
2905 */
2906 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatHwAccEntry, a);
2907 STAM_PROFILE_START(&pVM->em.s.StatHwAccExec, x);
2908 VMMR3Unlock(pVM);
2909 rc = VMMR3HwAccRunGC(pVM);
2910 VMMR3Lock(pVM);
2911 STAM_PROFILE_STOP(&pVM->em.s.StatHwAccExec, x);
2912
2913 /*
2914 * Deal with high priority post execution FFs before doing anything else.
2915 */
2916 VM_FF_CLEAR(pVM, VM_FF_RESUME_GUEST_MASK);
2917 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_POST_MASK))
2918 rc = emR3HighPriorityPostForcedActions(pVM, rc);
2919
2920 /*
2921 * Process the returned status code.
2922 */
2923 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
2924 break;
2925
2926 rc = emR3RawHandleRC(pVM, pCtx, rc);
2927 if (rc != VINF_SUCCESS)
2928 break;
2929
2930 /*
2931 * Check and execute forced actions.
2932 */
2933#ifdef VBOX_HIGH_RES_TIMERS_HACK
2934 TMTimerPoll(pVM);
2935#endif
2936 if (VM_FF_ISPENDING(pVM, VM_FF_ALL_MASK))
2937 {
2938 rc = emR3ForcedActions(pVM, rc);
2939 if ( rc != VINF_SUCCESS
2940 && rc != VINF_EM_RESCHEDULE_HWACC)
2941 {
2942 *pfFFDone = true;
2943 break;
2944 }
2945 }
2946 }
2947 /*
2948 * Return to outer loop.
2949 */
2950#if defined(LOG_ENABLED) && defined(DEBUG)
2951 RTLogFlush(NULL);
2952#endif
2953 return rc;
2954}
2955
2956
2957/**
2958 * Decides whether to execute RAW, HWACC or REM.
2959 *
2960 * @returns new EM state
2961 * @param pVM The VM.
2962 * @param pCtx The CPU context.
2963 */
2964inline EMSTATE emR3Reschedule(PVM pVM, PCPUMCTX pCtx)
2965{
2966 /*
2967 * When forcing raw-mode execution, things are simple.
2968 */
2969 if (pVM->em.s.fForceRAW)
2970 return EMSTATE_RAW;
2971
2972 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
2973 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
2974 /* !!! THIS MUST BE IN SYNC WITH remR3CanExecuteRaw !!! */
2975
2976 X86EFLAGS EFlags = pCtx->eflags;
2977 if (HWACCMIsEnabled(pVM))
2978 {
2979 /* Hardware accelerated raw-mode:
2980 *
2981 * Typically only 32-bits protected mode, with paging enabled, code is allowed here.
2982 */
2983 if (HWACCMR3CanExecuteGuest(pVM, pCtx) == true)
2984 return EMSTATE_HWACC;
2985
2986 /** @note Raw mode and hw accelerated mode are incompatible. The latter turns off monitoring features essential for raw mode! */
2987 return EMSTATE_REM;
2988 }
2989
2990 /* Standard raw-mode:
2991 *
2992 * Here we only support 16 & 32 bits protected mode ring 3 code that has no IO privileges
2993 * or 32 bits protected mode ring 0 code
2994 *
2995 * The tests are ordered by the likelyhood of being true during normal execution.
2996 */
2997 if (EFlags.u32 & (X86_EFL_TF /* | HF_INHIBIT_IRQ_MASK*/))
2998 {
2999 Log2(("raw mode refused: EFlags=%#x\n", EFlags.u32));
3000 return EMSTATE_REM;
3001 }
3002
3003#ifndef VBOX_RAW_V86
3004 if (EFlags.u32 & X86_EFL_VM) {
3005 Log2(("raw mode refused: VM_MASK\n"));
3006 return EMSTATE_REM;
3007 }
3008#endif
3009
3010 /** @todo check up the X86_CR0_AM flag in respect to raw mode!!! We're probably not emulating it right! */
3011 uint32_t u32CR0 = pCtx->cr0;
3012 if ((u32CR0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
3013 {
3014 //Log2(("raw mode refused: %s%s%s\n", (u32CR0 & X86_CR0_PG) ? "" : " !PG", (u32CR0 & X86_CR0_PE) ? "" : " !PE", (u32CR0 & X86_CR0_AM) ? "" : " !AM"));
3015 return EMSTATE_REM;
3016 }
3017
3018 if (pCtx->cr4 & X86_CR4_PAE)
3019 {
3020 //Log2(("raw mode refused: PAE\n"));
3021 return EMSTATE_REM;
3022 }
3023
3024 unsigned uSS = pCtx->ss;
3025 if ( pCtx->eflags.Bits.u1VM
3026 || (uSS & X86_SEL_RPL) == 3)
3027 {
3028 if (!EMIsRawRing3Enabled(pVM))
3029 return EMSTATE_REM;
3030
3031 if (!(EFlags.u32 & X86_EFL_IF))
3032 {
3033 Log2(("raw mode refused: IF (RawR3)\n"));
3034 return EMSTATE_REM;
3035 }
3036
3037 if (!(u32CR0 & X86_CR0_WP) && EMIsRawRing0Enabled(pVM))
3038 {
3039 Log2(("raw mode refused: CR0.WP + RawR0\n"));
3040 return EMSTATE_REM;
3041 }
3042 }
3043 else
3044 {
3045 if (!EMIsRawRing0Enabled(pVM))
3046 return EMSTATE_REM;
3047
3048 /* Only ring 0 supervisor code. */
3049 if ((uSS & X86_SEL_RPL) != 0)
3050 {
3051 Log2(("raw r0 mode refused: CPL %d\n", uSS & X86_SEL_RPL));
3052 return EMSTATE_REM;
3053 }
3054
3055 // Let's start with pure 32 bits ring 0 code first
3056 /** @todo What's pure 32-bit mode? flat? */
3057 if ( !(pCtx->ssHid.Attr.n.u1DefBig)
3058 || !(pCtx->csHid.Attr.n.u1DefBig))
3059 {
3060 Log2(("raw r0 mode refused: SS/CS not 32bit\n"));
3061 return EMSTATE_REM;
3062 }
3063
3064 /* Write protection muts be turned on, or else the guest can overwrite our hypervisor code and data. */
3065 if (!(u32CR0 & X86_CR0_WP))
3066 {
3067 Log2(("raw r0 mode refused: CR0.WP=0!\n"));
3068 return EMSTATE_REM;
3069 }
3070
3071 if (PATMShouldUseRawMode(pVM, (RTGCPTR)pCtx->eip))
3072 {
3073 Log2(("raw r0 mode forced: patch code\n"));
3074 return EMSTATE_RAW;
3075 }
3076
3077#if !defined(VBOX_ALLOW_IF0) && !defined(VBOX_RUN_INTERRUPT_GATE_HANDLERS)
3078 if (!(EFlags.u32 & X86_EFL_IF))
3079 {
3080 ////Log2(("R0: IF=0 VIF=%d %08X\n", eip, pVMeflags));
3081 //Log2(("RR0: Interrupts turned off; fall back to emulation\n"));
3082 return EMSTATE_REM;
3083 }
3084#endif
3085
3086 /** @todo still necessary??? */
3087 if (EFlags.Bits.u2IOPL != 0)
3088 {
3089 Log2(("raw r0 mode refused: IOPL %d\n", EFlags.Bits.u2IOPL));
3090 return EMSTATE_REM;
3091 }
3092 }
3093
3094 Assert(PGMPhysIsA20Enabled(pVM));
3095 return EMSTATE_RAW;
3096}
3097
3098
3099/**
3100 * Executes all high priority post execution force actions.
3101 *
3102 * @returns rc or a fatal status code.
3103 *
3104 * @param pVM VM handle.
3105 * @param rc The current rc.
3106 */
3107static int emR3HighPriorityPostForcedActions(PVM pVM, int rc)
3108{
3109 if (VM_FF_ISSET(pVM, VM_FF_PDM_CRITSECT))
3110 PDMR3CritSectFF(pVM);
3111
3112 if (VM_FF_ISSET(pVM, VM_FF_CSAM_PENDING_ACTION))
3113 CSAMR3DoPendingAction(pVM);
3114
3115 return rc;
3116}
3117
3118
3119/**
3120 * Executes all pending forced actions.
3121 *
3122 * Forced actions can cause execution delays and execution
3123 * rescheduling. The first we deal with using action priority, so
3124 * that for instance pending timers aren't scheduled and ran until
3125 * right before execution. The rescheduling we deal with using
3126 * return codes. The same goes for VM termination, only in that case
3127 * we exit everything.
3128 *
3129 * @returns VBox status code of equal or greater importance/severity than rc.
3130 * The most important ones are: VINF_EM_RESCHEDULE,
3131 * VINF_EM_SUSPEND, VINF_EM_RESET and VINF_EM_TERMINATE.
3132 *
3133 * @param pVM VM handle.
3134 * @param rc The current rc.
3135 *
3136 */
3137static int emR3ForcedActions(PVM pVM, int rc)
3138{
3139#ifdef VBOX_STRICT
3140 int rcIrq = VINF_SUCCESS;
3141#endif
3142 STAM_PROFILE_START(&pVM->em.s.StatForcedActions, a);
3143
3144#define UPDATE_RC() \
3145 do { \
3146 AssertMsg(rc2 <= 0 || (rc2 >= VINF_EM_FIRST && rc2 <= VINF_EM_LAST), ("Invalid FF return code: %Vra\n", rc2)); \
3147 if (rc2 == VINF_SUCCESS || rc < VINF_SUCCESS) \
3148 break; \
3149 if (!rc || rc2 < rc) \
3150 rc = rc2; \
3151 } while (0)
3152
3153 int rc2;
3154
3155 /*
3156 * Post execution chunk first.
3157 */
3158 if (VM_FF_ISPENDING(pVM, VM_FF_NORMAL_PRIORITY_POST_MASK))
3159 {
3160 /*
3161 * Termination request.
3162 */
3163 if (VM_FF_ISSET(pVM, VM_FF_TERMINATE))
3164 {
3165 Log2(("emR3ForcedActions: returns VINF_EM_TERMINATE\n"));
3166 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3167 return VINF_EM_TERMINATE;
3168 }
3169
3170 /*
3171 * Debugger Facility polling.
3172 */
3173 if (VM_FF_ISSET(pVM, VM_FF_DBGF))
3174 {
3175 rc2 = DBGFR3VMMForcedAction(pVM);
3176 UPDATE_RC();
3177 }
3178
3179 /*
3180 * Postponed reset request.
3181 */
3182 if (VM_FF_ISSET(pVM, VM_FF_RESET))
3183 {
3184 rc2 = VMR3Reset(pVM);
3185 UPDATE_RC();
3186 VM_FF_CLEAR(pVM, VM_FF_RESET);
3187 }
3188
3189 /*
3190 * CSAM page scanning.
3191 */
3192 if (VM_FF_ISSET(pVM, VM_FF_CSAM_SCAN_PAGE))
3193 {
3194 PCPUMCTX pCtx = pVM->em.s.pCtx;
3195
3196 /** @todo: check for 16 or 32 bits code! (D bit in the code selector) */
3197 Log(("Forced action VM_FF_CSAM_SCAN_PAGE\n"));
3198
3199 CSAMR3CheckCodeEx(pVM, pCtx->cs, &pCtx->csHid, pCtx->eip);
3200 VM_FF_CLEAR(pVM, VM_FF_CSAM_SCAN_PAGE);
3201 }
3202
3203 /* check that we got them all */
3204 Assert(!(VM_FF_NORMAL_PRIORITY_POST_MASK & ~(VM_FF_TERMINATE | VM_FF_DBGF | VM_FF_RESET | VM_FF_CSAM_SCAN_PAGE)));
3205 }
3206
3207 /*
3208 * Normal priority then.
3209 * (Executed in no particular order.)
3210 */
3211 if (VM_FF_ISPENDING(pVM, VM_FF_NORMAL_PRIORITY_MASK))
3212 {
3213 /*
3214 * PDM Queues are pending.
3215 */
3216 if (VM_FF_ISSET(pVM, VM_FF_PDM_QUEUES))
3217 PDMR3QueueFlushAll(pVM);
3218
3219 /*
3220 * PDM DMA transfers are pending.
3221 */
3222 if (VM_FF_ISSET(pVM, VM_FF_PDM_DMA))
3223 PDMR3DmaRun(pVM);
3224
3225 /*
3226 * Requests from other threads.
3227 */
3228 if (VM_FF_ISSET(pVM, VM_FF_REQUEST))
3229 {
3230 rc2 = VMR3ReqProcess(pVM);
3231 if (rc2 == VINF_EM_OFF || rc2 == VINF_EM_TERMINATE)
3232 {
3233 Log2(("emR3ForcedActions: returns %Vrc\n", rc2));
3234 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3235 return rc2;
3236 }
3237 UPDATE_RC();
3238 }
3239
3240 /* check that we got them all */
3241 Assert(!(VM_FF_NORMAL_PRIORITY_MASK & ~(VM_FF_REQUEST | VM_FF_PDM_QUEUES | VM_FF_PDM_DMA)));
3242 }
3243
3244 /*
3245 * Execute polling function ever so often.
3246 * THIS IS A HACK, IT WILL BE *REPLACED* BY PROPER ASYNC NETWORKING SOON!
3247 */
3248 static unsigned cLast = 0;
3249 if (!((++cLast) % 4))
3250 PDMR3Poll(pVM);
3251
3252 /*
3253 * High priority pre execution chunk last.
3254 * (Executed in ascending priority order.)
3255 */
3256 if (VM_FF_ISPENDING(pVM, VM_FF_HIGH_PRIORITY_PRE_MASK))
3257 {
3258 /*
3259 * Timers before interrupts.
3260 */
3261 if (VM_FF_ISSET(pVM, VM_FF_TIMER))
3262 TMR3TimerQueuesDo(pVM);
3263
3264 /*
3265 * The instruction following an emulated STI should *always* be executed!
3266 */
3267 if (VM_FF_ISSET(pVM, VM_FF_INHIBIT_INTERRUPTS))
3268 {
3269 Log(("VM_FF_EMULATED_STI at %VGv successor %VGv\n", CPUMGetGuestEIP(pVM), EMGetInhibitInterruptsPC(pVM)));
3270 if (CPUMGetGuestEIP(pVM) != EMGetInhibitInterruptsPC(pVM))
3271 {
3272 /** @note we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here if the eip is the same as the inhibited instr address.
3273 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
3274 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
3275 * break the guest. Sounds very unlikely, but such timing sensitive problem are not as rare as you might think.
3276 */
3277 VM_FF_CLEAR(pVM, VM_FF_INHIBIT_INTERRUPTS);
3278 }
3279 if (HWACCMR3IsActive(pVM))
3280 rc2 = VINF_EM_RESCHEDULE_HWACC;
3281 else
3282 rc2 = PATMAreInterruptsEnabled(pVM) ? VINF_EM_RESCHEDULE_RAW : VINF_EM_RESCHEDULE_REM;
3283
3284 UPDATE_RC();
3285 }
3286
3287 /*
3288 * Interrupts.
3289 */
3290 if ( !VM_FF_ISSET(pVM, VM_FF_INHIBIT_INTERRUPTS)
3291 && (!rc || rc >= VINF_EM_RESCHEDULE_RAW)
3292 && !TRPMHasTrap(pVM) /* an interrupt could already be scheduled for dispatching in the recompiler. */
3293 && PATMAreInterruptsEnabled(pVM)
3294 && !HWACCMR3IsEventPending(pVM))
3295 {
3296 if (VM_FF_ISPENDING(pVM, VM_FF_INTERRUPT_APIC | VM_FF_INTERRUPT_PIC))
3297 {
3298 /** @note it's important to make sure the return code from TRPMR3InjectEvent isn't ignored! */
3299 /** @todo this really isn't nice, should properly handle this */
3300 rc2 = TRPMR3InjectEvent(pVM, TRPM_HARDWARE_INT);
3301#ifdef VBOX_STRICT
3302 rcIrq = rc2;
3303#endif
3304 UPDATE_RC();
3305 }
3306 /** @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. */
3307 else if (REMR3QueryPendingInterrupt(pVM) != REM_NO_PENDING_IRQ)
3308 {
3309 rc2 = VINF_EM_RESCHEDULE_REM;
3310 UPDATE_RC();
3311 }
3312 }
3313
3314 /*
3315 * Debugger Facility request.
3316 */
3317 if (VM_FF_ISSET(pVM, VM_FF_DBGF))
3318 {
3319 rc2 = DBGFR3VMMForcedAction(pVM);
3320 UPDATE_RC();
3321 }
3322
3323 /*
3324 * Termination request.
3325 */
3326 if (VM_FF_ISSET(pVM, VM_FF_TERMINATE))
3327 {
3328 Log2(("emR3ForcedActions: returns VINF_EM_TERMINATE\n"));
3329 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3330 return VINF_EM_TERMINATE;
3331 }
3332
3333#ifdef DEBUG
3334 /*
3335 * Debug, pause the VM.
3336 */
3337 if (VM_FF_ISSET(pVM, VM_FF_DEBUG_SUSPEND))
3338 {
3339 VM_FF_CLEAR(pVM, VM_FF_DEBUG_SUSPEND);
3340 Log(("emR3ForcedActions: returns VINF_EM_SUSPEND\n"));
3341 return VINF_EM_SUSPEND;
3342 }
3343
3344#endif
3345 /* check that we got them all */
3346 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)));
3347 }
3348
3349#undef UPDATE_RC
3350 Log2(("emR3ForcedActions: returns %Vrc\n", rc));
3351 STAM_PROFILE_STOP(&pVM->em.s.StatForcedActions, a);
3352 Assert(rcIrq == VINF_SUCCESS || rcIrq == rc);
3353 return rc;
3354}
3355
3356
3357/**
3358 * Execute VM.
3359 *
3360 * This function is the main loop of the VM. The emulation thread
3361 * calls this function when the VM has been successfully constructed
3362 * and we're ready for executing the VM.
3363 *
3364 * Returning from this function means that the VM is turned off or
3365 * suspended (state already saved) and deconstruction in next in line.
3366 *
3367 * All interaction from other thread are done using forced actions
3368 * and signaling of the wait object.
3369 *
3370 * @returns VBox status code.
3371 * @param pVM The VM to operate on.
3372 */
3373EMR3DECL(int) EMR3ExecuteVM(PVM pVM)
3374{
3375 LogFlow(("EMR3ExecuteVM: pVM=%p enmVMState=%d enmState=%d (%s) fForceRAW=%d\n", pVM, pVM->enmVMState,
3376 pVM->em.s.enmState, EMR3GetStateName(pVM->em.s.enmState), pVM->em.s.fForceRAW));
3377 VM_ASSERT_EMT(pVM);
3378 Assert(pVM->em.s.enmState == EMSTATE_NONE || pVM->em.s.enmState == EMSTATE_SUSPENDED);
3379
3380 VMMR3Lock(pVM);
3381
3382 int rc = setjmp(pVM->em.s.u.FatalLongJump);
3383 if (rc == 0)
3384 {
3385 /*
3386 * Start the virtual time.
3387 */
3388 rc = TMVirtualResume(pVM);
3389 Assert(rc == VINF_SUCCESS);
3390 rc = TMCpuTickResume(pVM);
3391 Assert(rc == VINF_SUCCESS);
3392
3393 /*
3394 * The Outer Main Loop.
3395 */
3396 bool fFFDone = false;
3397 rc = VINF_EM_RESCHEDULE;
3398 pVM->em.s.enmState = EMSTATE_REM;
3399 STAM_PROFILE_ADV_START(&pVM->em.s.StatTotal, x);
3400 for (;;)
3401 {
3402 /*
3403 * Before we can schedule anything (we're here because
3404 * scheduling is required) we must service any pending
3405 * forced actions to avoid any pending action causing
3406 * immidate rescheduling upon entering an inner loop
3407 *
3408 * Do forced actions.
3409 */
3410 if ( !fFFDone
3411 && rc != VINF_EM_TERMINATE
3412 && rc != VINF_EM_OFF
3413 && VM_FF_ISPENDING(pVM, VM_FF_ALL_BUT_RAW_MASK))
3414 {
3415 rc = emR3ForcedActions(pVM, rc);
3416 if ( ( rc == VINF_EM_RESCHEDULE_REM
3417 || rc == VINF_EM_RESCHEDULE_HWACC)
3418 && pVM->em.s.fForceRAW)
3419 rc = VINF_EM_RESCHEDULE_RAW;
3420 }
3421 else if (fFFDone)
3422 fFFDone = false;
3423
3424 /*
3425 * Now what to do?
3426 */
3427 Log2(("EMR3ExecuteVM: rc=%Vrc\n", rc));
3428 switch (rc)
3429 {
3430 /*
3431 * Keep doing what we're currently doing.
3432 */
3433 case VINF_SUCCESS:
3434 break;
3435
3436 /*
3437 * Reschedule - to raw-mode execution.
3438 */
3439 case VINF_EM_RESCHEDULE_RAW:
3440 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_RAW: %d -> %d (EMSTATE_RAW)\n", pVM->em.s.enmState, EMSTATE_RAW));
3441 pVM->em.s.enmState = EMSTATE_RAW;
3442 break;
3443
3444 /*
3445 * Reschedule - to hardware accelerated raw-mode execution.
3446 */
3447 case VINF_EM_RESCHEDULE_HWACC:
3448 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_HWACC: %d -> %d (EMSTATE_HWACC)\n", pVM->em.s.enmState, EMSTATE_HWACC));
3449 Assert(!pVM->em.s.fForceRAW);
3450 pVM->em.s.enmState = EMSTATE_HWACC;
3451 break;
3452
3453 /*
3454 * Reschedule - to recompiled execution.
3455 */
3456 case VINF_EM_RESCHEDULE_REM:
3457 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE_REM: %d -> %d (EMSTATE_REM)\n", pVM->em.s.enmState, EMSTATE_REM));
3458 pVM->em.s.enmState = EMSTATE_REM;
3459 break;
3460
3461 /*
3462 * Resume.
3463 */
3464 case VINF_EM_RESUME:
3465 Log2(("EMR3ExecuteVM: VINF_EM_RESUME: %d -> VINF_EM_RESCHEDULE\n", pVM->em.s.enmState));
3466 /* fall through and get scheduled. */
3467
3468 /*
3469 * Reschedule.
3470 */
3471 case VINF_EM_RESCHEDULE:
3472 {
3473 EMSTATE enmState = emR3Reschedule(pVM, pVM->em.s.pCtx);
3474 Log2(("EMR3ExecuteVM: VINF_EM_RESCHEDULE: %d -> %d (%s)\n", pVM->em.s.enmState, enmState, EMR3GetStateName(enmState)));
3475 pVM->em.s.enmState = enmState;
3476 break;
3477 }
3478
3479 /*
3480 * Halted.
3481 */
3482 case VINF_EM_HALT:
3483 Log2(("EMR3ExecuteVM: VINF_EM_HALT: %d -> %d\n", pVM->em.s.enmState, EMSTATE_HALTED));
3484 pVM->em.s.enmState = EMSTATE_HALTED;
3485 break;
3486
3487 /*
3488 * Suspend.
3489 */
3490 case VINF_EM_SUSPEND:
3491 Log2(("EMR3ExecuteVM: VINF_EM_SUSPEND: %d -> %d\n", pVM->em.s.enmState, EMSTATE_SUSPENDED));
3492 pVM->em.s.enmState = EMSTATE_SUSPENDED;
3493 break;
3494
3495 /*
3496 * Reset.
3497 * We might end up doing a double reset for now, we'll have to clean up the mess later.
3498 */
3499 case VINF_EM_RESET:
3500 Log2(("EMR3ExecuteVM: VINF_EM_RESET: %d -> %d\n", pVM->em.s.enmState, EMSTATE_REM));
3501 pVM->em.s.enmState = EMSTATE_REM;
3502 break;
3503
3504 /*
3505 * Power Off.
3506 */
3507 case VINF_EM_OFF:
3508 pVM->em.s.enmState = EMSTATE_TERMINATING;
3509 Log2(("EMR3ExecuteVM: returns VINF_EM_OFF (%d -> %d)\n", pVM->em.s.enmState, EMSTATE_TERMINATING));
3510 TMVirtualPause(pVM);
3511 TMCpuTickPause(pVM);
3512 VMMR3Unlock(pVM);
3513 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3514 return rc;
3515
3516 /*
3517 * Terminate the VM.
3518 */
3519 case VINF_EM_TERMINATE:
3520 pVM->em.s.enmState = EMSTATE_TERMINATING;
3521 Log(("EMR3ExecuteVM returns VINF_EM_TERMINATE (%d -> %d)\n", pVM->em.s.enmState, EMSTATE_TERMINATING));
3522 TMVirtualPause(pVM);
3523 TMCpuTickPause(pVM);
3524 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3525 return rc;
3526
3527 /*
3528 * Guest debug events.
3529 */
3530 case VINF_EM_DBG_STEPPED:
3531 AssertMsgFailed(("VINF_EM_DBG_STEPPED cannot be here!"));
3532 case VINF_EM_DBG_STOP:
3533 case VINF_EM_DBG_BREAKPOINT:
3534 case VINF_EM_DBG_STEP:
3535 if (pVM->em.s.enmState == EMSTATE_RAW)
3536 {
3537 Log2(("EMR3ExecuteVM: %Vrc: %d -> %d\n", rc, pVM->em.s.enmState, EMSTATE_DEBUG_GUEST_RAW));
3538 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_RAW;
3539 }
3540 else
3541 {
3542 Log2(("EMR3ExecuteVM: %Vrc: %d -> %d\n", rc, pVM->em.s.enmState, EMSTATE_DEBUG_GUEST_REM));
3543 pVM->em.s.enmState = EMSTATE_DEBUG_GUEST_REM;
3544 }
3545 break;
3546
3547 /*
3548 * Hypervisor debug events.
3549 */
3550 case VINF_EM_DBG_HYPER_STEPPED:
3551 case VINF_EM_DBG_HYPER_BREAKPOINT:
3552 case VINF_EM_DBG_HYPER_ASSERTION:
3553 Log2(("EMR3ExecuteVM: %Vrc: %d -> %d\n", rc, pVM->em.s.enmState, EMSTATE_DEBUG_HYPER));
3554 pVM->em.s.enmState = EMSTATE_DEBUG_HYPER;
3555 break;
3556
3557 /*
3558 * Any error code showing up here other than the ones we
3559 * know and process above are considered to be FATAL.
3560 *
3561 * Unknown warnings and informational status codes are also
3562 * included in this.
3563 */
3564 default:
3565 if (VBOX_SUCCESS(rc))
3566 {
3567 AssertMsgFailed(("Unexpected warning or informational status code %Vra!\n", rc));
3568 rc = VERR_EM_INTERNAL_ERROR;
3569 }
3570 pVM->em.s.enmState = EMSTATE_GURU_MEDITATION;
3571 Log(("EMR3ExecuteVM returns %d\n", rc));
3572 break;
3573 }
3574
3575
3576 /*
3577 * Any waiters can now be woken up
3578 */
3579 VMMR3Unlock(pVM);
3580 VMMR3Lock(pVM);
3581
3582 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3583 STAM_PROFILE_ADV_START(&pVM->em.s.StatTotal, x);
3584
3585 /*
3586 * Act on the state.
3587 */
3588 switch (pVM->em.s.enmState)
3589 {
3590 /*
3591 * Execute raw.
3592 */
3593 case EMSTATE_RAW:
3594 rc = emR3RawExecute(pVM, &fFFDone);
3595 break;
3596
3597 /*
3598 * Execute hardware accelerated raw.
3599 */
3600 case EMSTATE_HWACC:
3601 rc = emR3HwAccExecute(pVM, &fFFDone);
3602 break;
3603
3604 /*
3605 * Execute recompiled.
3606 */
3607 case EMSTATE_REM:
3608 rc = emR3RemExecute(pVM, &fFFDone);
3609 Log2(("EMR3ExecuteVM: emR3RemExecute -> %Vrc\n", rc));
3610 break;
3611
3612 /*
3613 * hlt - execution halted until interrupt.
3614 */
3615 case EMSTATE_HALTED:
3616 {
3617 STAM_PROFILE_START(&pVM->em.s.StatHalted, y);
3618 rc = VMR3WaitHalted(pVM, !(CPUMGetGuestEFlags(pVM) & X86_EFL_IF));
3619 STAM_PROFILE_STOP(&pVM->em.s.StatHalted, y);
3620 break;
3621 }
3622
3623 /*
3624 * Suspended - return to VM.cpp.
3625 */
3626 case EMSTATE_SUSPENDED:
3627 TMVirtualPause(pVM);
3628 TMCpuTickPause(pVM);
3629 VMMR3Unlock(pVM);
3630 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3631 return VINF_EM_SUSPEND;
3632
3633 /*
3634 * Debugging in the guest.
3635 */
3636 case EMSTATE_DEBUG_GUEST_REM:
3637 case EMSTATE_DEBUG_GUEST_RAW:
3638 TMVirtualPause(pVM);
3639 TMCpuTickPause(pVM);
3640 rc = emR3Debug(pVM, rc);
3641 TMVirtualResume(pVM);
3642 TMCpuTickResume(pVM);
3643 Log2(("EMR3ExecuteVM: enmr3Debug -> %Vrc (state %d)\n", rc, pVM->em.s.enmState));
3644 break;
3645
3646 /*
3647 * Debugging in the hypervisor.
3648 */
3649 case EMSTATE_DEBUG_HYPER:
3650 {
3651 TMVirtualPause(pVM);
3652 TMCpuTickPause(pVM);
3653 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3654
3655 rc = emR3Debug(pVM, rc);
3656 Log2(("EMR3ExecuteVM: enmr3Debug -> %Vrc (state %d)\n", rc, pVM->em.s.enmState));
3657 if (rc != VINF_SUCCESS)
3658 {
3659 /* switch to guru meditation mode */
3660 pVM->em.s.enmState = EMSTATE_GURU_MEDITATION;
3661 VMMR3FatalDump(pVM, rc);
3662 return rc;
3663 }
3664
3665 STAM_PROFILE_ADV_START(&pVM->em.s.StatTotal, x);
3666 TMVirtualResume(pVM);
3667 TMCpuTickResume(pVM);
3668 break;
3669 }
3670
3671 /*
3672 * Guru meditation takes place in the debugger.
3673 */
3674 case EMSTATE_GURU_MEDITATION:
3675 {
3676 /** @todo this ain't entirely safe. make a better return code check and specify this in DBGF/emR3Debug. */
3677 TMVirtualPause(pVM);
3678 TMCpuTickPause(pVM);
3679 VMMR3FatalDump(pVM, rc);
3680 int rc2 = emR3Debug(pVM, rc);
3681 if (rc2 == VERR_DBGF_NOT_ATTACHED)
3682 {
3683 VMMR3Unlock(pVM);
3684 /** @todo change the VM state! */
3685 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3686 return rc;
3687 }
3688 TMVirtualResume(pVM);
3689 TMCpuTickResume(pVM);
3690 rc = rc2;
3691 /** @todo we're not doing the right thing in emR3Debug and will cause code to be executed on disconnect and stuff.. */
3692 Log2(("EMR3ExecuteVM: enmr3Debug -> %Vrc (state %d)\n", rc, pVM->em.s.enmState));
3693 break;
3694 }
3695
3696 /*
3697 * The states we don't expect here.
3698 */
3699 case EMSTATE_NONE:
3700 case EMSTATE_TERMINATING:
3701 default:
3702 AssertMsgFailed(("EMR3ExecuteVM: Invalid state %d!\n", pVM->em.s.enmState));
3703 pVM->em.s.enmState = EMSTATE_GURU_MEDITATION;
3704 TMVirtualPause(pVM);
3705 TMCpuTickPause(pVM);
3706 VMMR3Unlock(pVM);
3707 STAM_PROFILE_ADV_STOP(&pVM->em.s.StatTotal, x);
3708 return VERR_EM_INTERNAL_ERROR;
3709 }
3710 } /* The Outer Main Loop */
3711 }
3712 else
3713 {
3714 /*
3715 * Fatal error.
3716 */
3717 LogFlow(("EMR3ExecuteVM: returns %Vrc (longjmp / fatal error)\n", rc));
3718 TMVirtualPause(pVM);
3719 TMCpuTickPause(pVM);
3720 VMMR3FatalDump(pVM, rc);
3721 emR3Debug(pVM, rc);
3722 VMMR3Unlock(pVM);
3723 /** @todo change the VM state! */
3724 return rc;
3725 }
3726
3727 /* (won't ever get here). */
3728 AssertFailed();
3729}
3730
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