VirtualBox

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

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

More stats

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