VirtualBox

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

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

backed out accidental commit

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