VirtualBox

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

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

Statistics for BTR.

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