VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HWVMXR0.cpp@ 22049

Last change on this file since 22049 was 22049, checked in by vboxsync, 15 years ago

Make sure we only load those MSRs that are supported by the guest

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 186.0 KB
Line 
1/* $Id: HWVMXR0.cpp 22049 2009-08-07 08:14:01Z vboxsync $ */
2/** @file
3 * HWACCM VMX - Host Context Ring 0.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
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 (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26#define LOG_GROUP LOG_GROUP_HWACCM
27#include <VBox/hwaccm.h>
28#include "HWACCMInternal.h"
29#include <VBox/vm.h>
30#include <VBox/x86.h>
31#include <VBox/pgm.h>
32#include <VBox/pdm.h>
33#include <VBox/err.h>
34#include <VBox/log.h>
35#include <VBox/selm.h>
36#include <VBox/iom.h>
37#include <VBox/rem.h>
38#include <iprt/asm.h>
39#include <iprt/assert.h>
40#include <iprt/param.h>
41#include <iprt/string.h>
42#include <iprt/time.h>
43#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
44# include <iprt/thread.h>
45#endif
46#include "HWVMXR0.h"
47
48/*******************************************************************************
49* Defined Constants And Macros *
50*******************************************************************************/
51#if defined(RT_ARCH_AMD64)
52# define VMX_IS_64BIT_HOST_MODE() (true)
53#elif defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
54# define VMX_IS_64BIT_HOST_MODE() (g_fVMXIs64bitHost != 0)
55#else
56# define VMX_IS_64BIT_HOST_MODE() (false)
57#endif
58
59/*******************************************************************************
60* Global Variables *
61*******************************************************************************/
62/* IO operation lookup arrays. */
63static uint32_t const g_aIOSize[4] = {1, 2, 0, 4};
64static uint32_t const g_aIOOpAnd[4] = {0xff, 0xffff, 0, 0xffffffff};
65
66#ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
67/** See HWACCMR0A.asm. */
68extern "C" uint32_t g_fVMXIs64bitHost;
69#endif
70
71/*******************************************************************************
72* Local Functions *
73*******************************************************************************/
74static void VMXR0ReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rc, PCPUMCTX pCtx);
75static void vmxR0SetupTLBEPT(PVM pVM, PVMCPU pVCpu);
76static void vmxR0SetupTLBVPID(PVM pVM, PVMCPU pVCpu);
77static void vmxR0SetupTLBDummy(PVM pVM, PVMCPU pVCpu);
78static void vmxR0FlushEPT(PVM pVM, PVMCPU pVCpu, VMX_FLUSH enmFlush, RTGCPHYS GCPhys);
79static void vmxR0FlushVPID(PVM pVM, PVMCPU pVCpu, VMX_FLUSH enmFlush, RTGCPTR GCPtr);
80static void vmxR0UpdateExceptionBitmap(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
81#ifdef VBOX_STRICT
82static bool vmxR0IsValidReadField(uint32_t idxField);
83static bool vmxR0IsValidWriteField(uint32_t idxField);
84#endif
85static void vmxR0SetMSRPermission(PVMCPU pVCpu, unsigned ulMSR, bool fRead, bool fWrite);
86
87static void VMXR0CheckError(PVM pVM, PVMCPU pVCpu, int rc)
88{
89 if (rc == VERR_VMX_GENERIC)
90 {
91 RTCCUINTREG instrError;
92
93 VMXReadVMCS(VMX_VMCS32_RO_VM_INSTR_ERROR, &instrError);
94 pVCpu->hwaccm.s.vmx.lasterror.ulInstrError = instrError;
95 }
96 pVM->hwaccm.s.lLastError = rc;
97}
98
99/**
100 * Sets up and activates VT-x on the current CPU
101 *
102 * @returns VBox status code.
103 * @param pCpu CPU info struct
104 * @param pVM The VM to operate on. (can be NULL after a resume!!)
105 * @param pvPageCpu Pointer to the global cpu page
106 * @param pPageCpuPhys Physical address of the global cpu page
107 */
108VMMR0DECL(int) VMXR0EnableCpu(PHWACCM_CPUINFO pCpu, PVM pVM, void *pvPageCpu, RTHCPHYS pPageCpuPhys)
109{
110 AssertReturn(pPageCpuPhys, VERR_INVALID_PARAMETER);
111 AssertReturn(pvPageCpu, VERR_INVALID_PARAMETER);
112
113#if defined(LOG_ENABLED) && !defined(DEBUG_bird)
114 SUPR0Printf("VMXR0EnableCpu cpu %d page (%x) %x\n", pCpu->idCpu, pvPageCpu, (uint32_t)pPageCpuPhys);
115#endif
116 if (pVM)
117 {
118 /* Set revision dword at the beginning of the VMXON structure. */
119 *(uint32_t *)pvPageCpu = MSR_IA32_VMX_BASIC_INFO_VMCS_ID(pVM->hwaccm.s.vmx.msr.vmx_basic_info);
120 }
121
122 /** @todo we should unmap the two pages from the virtual address space in order to prevent accidental corruption.
123 * (which can have very bad consequences!!!)
124 */
125
126 /* Make sure the VMX instructions don't cause #UD faults. */
127 ASMSetCR4(ASMGetCR4() | X86_CR4_VMXE);
128
129 /* Enter VMX Root Mode */
130 int rc = VMXEnable(pPageCpuPhys);
131 if (RT_FAILURE(rc))
132 {
133 if (pVM)
134 VMXR0CheckError(pVM, &pVM->aCpus[0], rc);
135 ASMSetCR4(ASMGetCR4() & ~X86_CR4_VMXE);
136 return VERR_VMX_VMXON_FAILED;
137 }
138 return VINF_SUCCESS;
139}
140
141/**
142 * Deactivates VT-x on the current CPU
143 *
144 * @returns VBox status code.
145 * @param pCpu CPU info struct
146 * @param pvPageCpu Pointer to the global cpu page
147 * @param pPageCpuPhys Physical address of the global cpu page
148 */
149VMMR0DECL(int) VMXR0DisableCpu(PHWACCM_CPUINFO pCpu, void *pvPageCpu, RTHCPHYS pPageCpuPhys)
150{
151 AssertReturn(pPageCpuPhys, VERR_INVALID_PARAMETER);
152 AssertReturn(pvPageCpu, VERR_INVALID_PARAMETER);
153
154 /* Leave VMX Root Mode. */
155 VMXDisable();
156
157 /* And clear the X86_CR4_VMXE bit */
158 ASMSetCR4(ASMGetCR4() & ~X86_CR4_VMXE);
159
160#if defined(LOG_ENABLED) && !defined(DEBUG_bird)
161 SUPR0Printf("VMXR0DisableCpu cpu %d\n", pCpu->idCpu);
162#endif
163 return VINF_SUCCESS;
164}
165
166/**
167 * Does Ring-0 per VM VT-x init.
168 *
169 * @returns VBox status code.
170 * @param pVM The VM to operate on.
171 */
172VMMR0DECL(int) VMXR0InitVM(PVM pVM)
173{
174 int rc;
175
176#ifdef LOG_ENABLED
177 SUPR0Printf("VMXR0InitVM %x\n", pVM);
178#endif
179
180 pVM->hwaccm.s.vmx.pMemObjAPIC = NIL_RTR0MEMOBJ;
181
182 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW)
183 {
184 /* Allocate one page for the APIC physical page (serves for filtering accesses). */
185 rc = RTR0MemObjAllocCont(&pVM->hwaccm.s.vmx.pMemObjAPIC, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
186 AssertRC(rc);
187 if (RT_FAILURE(rc))
188 return rc;
189
190 pVM->hwaccm.s.vmx.pAPIC = (uint8_t *)RTR0MemObjAddress(pVM->hwaccm.s.vmx.pMemObjAPIC);
191 pVM->hwaccm.s.vmx.pAPICPhys = RTR0MemObjGetPagePhysAddr(pVM->hwaccm.s.vmx.pMemObjAPIC, 0);
192 ASMMemZero32(pVM->hwaccm.s.vmx.pAPIC, PAGE_SIZE);
193 }
194 else
195 {
196 pVM->hwaccm.s.vmx.pMemObjAPIC = 0;
197 pVM->hwaccm.s.vmx.pAPIC = 0;
198 pVM->hwaccm.s.vmx.pAPICPhys = 0;
199 }
200
201#ifdef VBOX_WITH_CRASHDUMP_MAGIC
202 {
203 rc = RTR0MemObjAllocCont(&pVM->hwaccm.s.vmx.pMemObjScratch, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
204 AssertRC(rc);
205 if (RT_FAILURE(rc))
206 return rc;
207
208 pVM->hwaccm.s.vmx.pScratch = (uint8_t *)RTR0MemObjAddress(pVM->hwaccm.s.vmx.pMemObjScratch);
209 pVM->hwaccm.s.vmx.pScratchPhys = RTR0MemObjGetPagePhysAddr(pVM->hwaccm.s.vmx.pMemObjScratch, 0);
210
211 ASMMemZero32(pVM->hwaccm.s.vmx.pScratch, PAGE_SIZE);
212 strcpy((char *)pVM->hwaccm.s.vmx.pScratch, "SCRATCH Magic");
213 *(uint64_t *)(pVM->hwaccm.s.vmx.pScratch + 16) = UINT64_C(0xDEADBEEFDEADBEEF);
214 }
215#endif
216
217 /* Allocate VMCBs for all guest CPUs. */
218 for (unsigned i=0;i<pVM->cCPUs;i++)
219 {
220 PVMCPU pVCpu = &pVM->aCpus[i];
221
222 pVCpu->hwaccm.s.vmx.pMemObjVMCS = NIL_RTR0MEMOBJ;
223
224 /* Allocate one page for the VM control structure (VMCS). */
225 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.vmx.pMemObjVMCS, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
226 AssertRC(rc);
227 if (RT_FAILURE(rc))
228 return rc;
229
230 pVCpu->hwaccm.s.vmx.pVMCS = RTR0MemObjAddress(pVCpu->hwaccm.s.vmx.pMemObjVMCS);
231 pVCpu->hwaccm.s.vmx.pVMCSPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.vmx.pMemObjVMCS, 0);
232 ASMMemZero32(pVCpu->hwaccm.s.vmx.pVMCS, PAGE_SIZE);
233
234 pVCpu->hwaccm.s.vmx.cr0_mask = 0;
235 pVCpu->hwaccm.s.vmx.cr4_mask = 0;
236
237 /* Allocate one page for the virtual APIC page for TPR caching. */
238 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.vmx.pMemObjVAPIC, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
239 AssertRC(rc);
240 if (RT_FAILURE(rc))
241 return rc;
242
243 pVCpu->hwaccm.s.vmx.pVAPIC = (uint8_t *)RTR0MemObjAddress(pVCpu->hwaccm.s.vmx.pMemObjVAPIC);
244 pVCpu->hwaccm.s.vmx.pVAPICPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.vmx.pMemObjVAPIC, 0);
245 ASMMemZero32(pVCpu->hwaccm.s.vmx.pVAPIC, PAGE_SIZE);
246
247 /* Allocate the MSR bitmap if this feature is supported. */
248 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_MSR_BITMAPS)
249 {
250 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.vmx.pMemObjMSRBitmap, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
251 AssertRC(rc);
252 if (RT_FAILURE(rc))
253 return rc;
254
255 pVCpu->hwaccm.s.vmx.pMSRBitmap = (uint8_t *)RTR0MemObjAddress(pVCpu->hwaccm.s.vmx.pMemObjMSRBitmap);
256 pVCpu->hwaccm.s.vmx.pMSRBitmapPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.vmx.pMemObjMSRBitmap, 0);
257 memset(pVCpu->hwaccm.s.vmx.pMSRBitmap, 0xff, PAGE_SIZE);
258 }
259
260 /* Allocate one page for the guest MSR load area (for preloading guest MSRs during the world switch). */
261 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.vmx.pMemObjGuestMSR, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
262 AssertRC(rc);
263 if (RT_FAILURE(rc))
264 return rc;
265
266 pVCpu->hwaccm.s.vmx.pGuestMSR = (uint8_t *)RTR0MemObjAddress(pVCpu->hwaccm.s.vmx.pMemObjGuestMSR);
267 pVCpu->hwaccm.s.vmx.pGuestMSRPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.vmx.pMemObjGuestMSR, 0);
268 memset(pVCpu->hwaccm.s.vmx.pGuestMSR, 0, PAGE_SIZE);
269
270 /* Allocate one page for the host MSR load area (for restoring host MSRs after the world switch back). */
271 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.vmx.pMemObjHostMSR, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
272 AssertRC(rc);
273 if (RT_FAILURE(rc))
274 return rc;
275
276 pVCpu->hwaccm.s.vmx.pHostMSR = (uint8_t *)RTR0MemObjAddress(pVCpu->hwaccm.s.vmx.pMemObjHostMSR);
277 pVCpu->hwaccm.s.vmx.pHostMSRPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.vmx.pMemObjHostMSR, 0);
278 memset(pVCpu->hwaccm.s.vmx.pHostMSR, 0, PAGE_SIZE);
279
280 /* Current guest paging mode. */
281 pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode = PGMMODE_REAL;
282
283#ifdef LOG_ENABLED
284 SUPR0Printf("VMXR0InitVM %x VMCS=%x (%x)\n", pVM, pVCpu->hwaccm.s.vmx.pVMCS, (uint32_t)pVCpu->hwaccm.s.vmx.pVMCSPhys);
285#endif
286 }
287
288 return VINF_SUCCESS;
289}
290
291/**
292 * Does Ring-0 per VM VT-x termination.
293 *
294 * @returns VBox status code.
295 * @param pVM The VM to operate on.
296 */
297VMMR0DECL(int) VMXR0TermVM(PVM pVM)
298{
299 for (unsigned i=0;i<pVM->cCPUs;i++)
300 {
301 PVMCPU pVCpu = &pVM->aCpus[i];
302
303 if (pVCpu->hwaccm.s.vmx.pMemObjVMCS != NIL_RTR0MEMOBJ)
304 {
305 RTR0MemObjFree(pVCpu->hwaccm.s.vmx.pMemObjVMCS, false);
306 pVCpu->hwaccm.s.vmx.pMemObjVMCS = NIL_RTR0MEMOBJ;
307 pVCpu->hwaccm.s.vmx.pVMCS = 0;
308 pVCpu->hwaccm.s.vmx.pVMCSPhys = 0;
309 }
310 if (pVCpu->hwaccm.s.vmx.pMemObjVAPIC != NIL_RTR0MEMOBJ)
311 {
312 RTR0MemObjFree(pVCpu->hwaccm.s.vmx.pMemObjVAPIC, false);
313 pVCpu->hwaccm.s.vmx.pMemObjVAPIC = NIL_RTR0MEMOBJ;
314 pVCpu->hwaccm.s.vmx.pVAPIC = 0;
315 pVCpu->hwaccm.s.vmx.pVAPICPhys = 0;
316 }
317 if (pVCpu->hwaccm.s.vmx.pMemObjMSRBitmap != NIL_RTR0MEMOBJ)
318 {
319 RTR0MemObjFree(pVCpu->hwaccm.s.vmx.pMemObjMSRBitmap, false);
320 pVCpu->hwaccm.s.vmx.pMemObjMSRBitmap = NIL_RTR0MEMOBJ;
321 pVCpu->hwaccm.s.vmx.pMSRBitmap = 0;
322 pVCpu->hwaccm.s.vmx.pMSRBitmapPhys = 0;
323 }
324 if (pVCpu->hwaccm.s.vmx.pMemObjHostMSR != NIL_RTR0MEMOBJ)
325 {
326 RTR0MemObjFree(pVCpu->hwaccm.s.vmx.pMemObjHostMSR, false);
327 pVCpu->hwaccm.s.vmx.pMemObjHostMSR = NIL_RTR0MEMOBJ;
328 pVCpu->hwaccm.s.vmx.pHostMSR = 0;
329 pVCpu->hwaccm.s.vmx.pHostMSRPhys = 0;
330 }
331 if (pVCpu->hwaccm.s.vmx.pMemObjGuestMSR != NIL_RTR0MEMOBJ)
332 {
333 RTR0MemObjFree(pVCpu->hwaccm.s.vmx.pMemObjGuestMSR, false);
334 pVCpu->hwaccm.s.vmx.pMemObjGuestMSR = NIL_RTR0MEMOBJ;
335 pVCpu->hwaccm.s.vmx.pGuestMSR = 0;
336 pVCpu->hwaccm.s.vmx.pGuestMSRPhys = 0;
337 }
338 }
339 if (pVM->hwaccm.s.vmx.pMemObjAPIC != NIL_RTR0MEMOBJ)
340 {
341 RTR0MemObjFree(pVM->hwaccm.s.vmx.pMemObjAPIC, false);
342 pVM->hwaccm.s.vmx.pMemObjAPIC = NIL_RTR0MEMOBJ;
343 pVM->hwaccm.s.vmx.pAPIC = 0;
344 pVM->hwaccm.s.vmx.pAPICPhys = 0;
345 }
346#ifdef VBOX_WITH_CRASHDUMP_MAGIC
347 if (pVM->hwaccm.s.vmx.pMemObjScratch != NIL_RTR0MEMOBJ)
348 {
349 ASMMemZero32(pVM->hwaccm.s.vmx.pScratch, PAGE_SIZE);
350 RTR0MemObjFree(pVM->hwaccm.s.vmx.pMemObjScratch, false);
351 pVM->hwaccm.s.vmx.pMemObjScratch = NIL_RTR0MEMOBJ;
352 pVM->hwaccm.s.vmx.pScratch = 0;
353 pVM->hwaccm.s.vmx.pScratchPhys = 0;
354 }
355#endif
356 return VINF_SUCCESS;
357}
358
359/**
360 * Sets up VT-x for the specified VM
361 *
362 * @returns VBox status code.
363 * @param pVM The VM to operate on.
364 */
365VMMR0DECL(int) VMXR0SetupVM(PVM pVM)
366{
367 int rc = VINF_SUCCESS;
368 uint32_t val;
369
370 AssertReturn(pVM, VERR_INVALID_PARAMETER);
371
372 for (unsigned i=0;i<pVM->cCPUs;i++)
373 {
374 PVMCPU pVCpu = &pVM->aCpus[i];
375
376 Assert(pVCpu->hwaccm.s.vmx.pVMCS);
377
378 /* Set revision dword at the beginning of the VMCS structure. */
379 *(uint32_t *)pVCpu->hwaccm.s.vmx.pVMCS = MSR_IA32_VMX_BASIC_INFO_VMCS_ID(pVM->hwaccm.s.vmx.msr.vmx_basic_info);
380
381 /* Clear VM Control Structure. */
382 Log(("pVMCSPhys = %RHp\n", pVCpu->hwaccm.s.vmx.pVMCSPhys));
383 rc = VMXClearVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
384 if (RT_FAILURE(rc))
385 goto vmx_end;
386
387 /* Activate the VM Control Structure. */
388 rc = VMXActivateVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
389 if (RT_FAILURE(rc))
390 goto vmx_end;
391
392 /* VMX_VMCS_CTRL_PIN_EXEC_CONTROLS
393 * Set required bits to one and zero according to the MSR capabilities.
394 */
395 val = pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.disallowed0;
396 /* External and non-maskable interrupts cause VM-exits. */
397 val = val | VMX_VMCS_CTRL_PIN_EXEC_CONTROLS_EXT_INT_EXIT | VMX_VMCS_CTRL_PIN_EXEC_CONTROLS_NMI_EXIT;
398 val &= pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.allowed1;
399
400 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PIN_EXEC_CONTROLS, val);
401 AssertRC(rc);
402
403 /* VMX_VMCS_CTRL_PROC_EXEC_CONTROLS
404 * Set required bits to one and zero according to the MSR capabilities.
405 */
406 val = pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.disallowed0;
407 /* Program which event cause VM-exits and which features we want to use. */
408 val = val | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_HLT_EXIT
409 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_TSC_OFFSET
410 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT
411 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_UNCOND_IO_EXIT
412 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDPMC_EXIT
413 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MWAIT_EXIT; /* don't execute mwait or else we'll idle inside the guest (host thinks the cpu load is high) */
414
415 /* Without nested paging we should intercept invlpg and cr3 mov instructions. */
416 if (!pVM->hwaccm.s.fNestedPaging)
417 val |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_INVLPG_EXIT
418 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
419 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT;
420
421 /* Note: VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MWAIT_EXIT might cause a vmlaunch failure with an invalid control fields error. (combined with some other exit reasons) */
422 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW)
423 {
424 /* CR8 reads from the APIC shadow page; writes cause an exit is they lower the TPR below the threshold */
425 val |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW;
426 Assert(pVM->hwaccm.s.vmx.pAPIC);
427 }
428 else
429 /* Exit on CR8 reads & writes in case the TPR shadow feature isn't present. */
430 val |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR8_STORE_EXIT | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR8_LOAD_EXIT;
431
432 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_MSR_BITMAPS)
433 {
434 Assert(pVCpu->hwaccm.s.vmx.pMSRBitmapPhys);
435 val |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_MSR_BITMAPS;
436 }
437
438 /* We will use the secondary control if it's present. */
439 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL;
440
441 /* Mask away the bits that the CPU doesn't support */
442 /** @todo make sure they don't conflict with the above requirements. */
443 val &= pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1;
444 pVCpu->hwaccm.s.vmx.proc_ctls = val;
445
446 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, val);
447 AssertRC(rc);
448
449 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
450 {
451 /* VMX_VMCS_CTRL_PROC_EXEC_CONTROLS2
452 * Set required bits to one and zero according to the MSR capabilities.
453 */
454 val = pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.disallowed0;
455 val |= VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT;
456
457#ifdef HWACCM_VTX_WITH_EPT
458 if (pVM->hwaccm.s.fNestedPaging)
459 val |= VMX_VMCS_CTRL_PROC_EXEC2_EPT;
460#endif /* HWACCM_VTX_WITH_EPT */
461#ifdef HWACCM_VTX_WITH_VPID
462 else
463 if (pVM->hwaccm.s.vmx.fVPID)
464 val |= VMX_VMCS_CTRL_PROC_EXEC2_VPID;
465#endif /* HWACCM_VTX_WITH_VPID */
466
467 if (pVM->hwaccm.s.fHasIoApic)
468 val |= VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC;
469
470 /* Mask away the bits that the CPU doesn't support */
471 /** @todo make sure they don't conflict with the above requirements. */
472 val &= pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1;
473 pVCpu->hwaccm.s.vmx.proc_ctls2 = val;
474 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS2, val);
475 AssertRC(rc);
476 }
477
478 /* VMX_VMCS_CTRL_CR3_TARGET_COUNT
479 * Set required bits to one and zero according to the MSR capabilities.
480 */
481 rc = VMXWriteVMCS(VMX_VMCS_CTRL_CR3_TARGET_COUNT, 0);
482 AssertRC(rc);
483
484 /* Forward all exception except #NM & #PF to the guest.
485 * We always need to check pagefaults since our shadow page table can be out of sync.
486 * And we always lazily sync the FPU & XMM state.
487 */
488
489 /** @todo Possible optimization:
490 * Keep the FPU and XMM state current in the EM thread. That way there's no need to
491 * lazily sync anything, but the downside is that we can't use the FPU stack or XMM
492 * registers ourselves of course.
493 *
494 * Note: only possible if the current state is actually ours (X86_CR0_TS flag)
495 */
496
497 /* Don't filter page faults; all of them should cause a switch. */
498 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PAGEFAULT_ERROR_MASK, 0);
499 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_PAGEFAULT_ERROR_MATCH, 0);
500 AssertRC(rc);
501
502 /* Init TSC offset to zero. */
503 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_TSC_OFFSET_FULL, 0);
504 AssertRC(rc);
505
506 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_IO_BITMAP_A_FULL, 0);
507 AssertRC(rc);
508
509 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_IO_BITMAP_B_FULL, 0);
510 AssertRC(rc);
511
512 /* Set the MSR bitmap address. */
513 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_MSR_BITMAPS)
514 {
515 Assert(pVCpu->hwaccm.s.vmx.pMSRBitmapPhys);
516
517 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_MSR_BITMAP_FULL, pVCpu->hwaccm.s.vmx.pMSRBitmapPhys);
518 AssertRC(rc);
519
520 /* Allow the guest to directly modify these MSRs; they are restored and saved automatically. */
521 vmxR0SetMSRPermission(pVCpu, MSR_IA32_SYSENTER_CS, true, true);
522 vmxR0SetMSRPermission(pVCpu, MSR_IA32_SYSENTER_ESP, true, true);
523 vmxR0SetMSRPermission(pVCpu, MSR_IA32_SYSENTER_EIP, true, true);
524 }
525
526 /* Set the guest & host MSR load/store physical addresses. */
527 Assert(pVCpu->hwaccm.s.vmx.pGuestMSRPhys);
528 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_VMENTRY_MSR_LOAD_FULL, pVCpu->hwaccm.s.vmx.pGuestMSRPhys);
529 AssertRC(rc);
530 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_VMEXIT_MSR_STORE_FULL, pVCpu->hwaccm.s.vmx.pGuestMSRPhys);
531 AssertRC(rc);
532
533 Assert(pVCpu->hwaccm.s.vmx.pHostMSRPhys);
534 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_VMEXIT_MSR_LOAD_FULL, pVCpu->hwaccm.s.vmx.pHostMSRPhys);
535 AssertRC(rc);
536
537 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW)
538 {
539 Assert(pVM->hwaccm.s.vmx.pMemObjAPIC);
540 /* Optional */
541 rc = VMXWriteVMCS(VMX_VMCS_CTRL_TPR_THRESHOLD, 0);
542 rc |= VMXWriteVMCS64(VMX_VMCS_CTRL_VAPIC_PAGEADDR_FULL, pVCpu->hwaccm.s.vmx.pVAPICPhys);
543
544 if (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
545 rc |= VMXWriteVMCS64(VMX_VMCS_CTRL_APIC_ACCESSADDR_FULL, pVM->hwaccm.s.vmx.pAPICPhys);
546
547 AssertRC(rc);
548 }
549
550 /* Set link pointer to -1. Not currently used. */
551 rc = VMXWriteVMCS64(VMX_VMCS_GUEST_LINK_PTR_FULL, 0xFFFFFFFFFFFFFFFFULL);
552 AssertRC(rc);
553
554 /* Clear VM Control Structure. Marking it inactive, clearing implementation specific data and writing back VMCS data to memory. */
555 rc = VMXClearVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
556 AssertRC(rc);
557
558 /* Configure the VMCS read cache. */
559 PVMCSCACHE pCache = &pVCpu->hwaccm.s.vmx.VMCSCache;
560
561 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_RIP);
562 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_RSP);
563 VMXSetupCachedReadVMCS(pCache, VMX_VMCS_GUEST_RFLAGS);
564 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE);
565 VMXSetupCachedReadVMCS(pCache, VMX_VMCS_CTRL_CR0_READ_SHADOW);
566 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_CR0);
567 VMXSetupCachedReadVMCS(pCache, VMX_VMCS_CTRL_CR4_READ_SHADOW);
568 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_CR4);
569 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_DR7);
570 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_GUEST_SYSENTER_CS);
571 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_SYSENTER_EIP);
572 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_SYSENTER_ESP);
573 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_GUEST_GDTR_LIMIT);
574 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_GDTR_BASE);
575 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_GUEST_IDTR_LIMIT);
576 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_IDTR_BASE);
577
578 VMX_SETUP_SELREG(ES, pCache);
579 VMX_SETUP_SELREG(SS, pCache);
580 VMX_SETUP_SELREG(CS, pCache);
581 VMX_SETUP_SELREG(DS, pCache);
582 VMX_SETUP_SELREG(FS, pCache);
583 VMX_SETUP_SELREG(GS, pCache);
584 VMX_SETUP_SELREG(LDTR, pCache);
585 VMX_SETUP_SELREG(TR, pCache);
586
587 /* Status code VMCS reads. */
588 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_EXIT_REASON);
589 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_VM_INSTR_ERROR);
590 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_EXIT_INSTR_LENGTH);
591 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_EXIT_INTERRUPTION_ERRCODE);
592 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO);
593 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_EXIT_INSTR_INFO);
594 VMXSetupCachedReadVMCS(pCache, VMX_VMCS_RO_EXIT_QUALIFICATION);
595 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_IDT_INFO);
596 VMXSetupCachedReadVMCS(pCache, VMX_VMCS32_RO_IDT_ERRCODE);
597
598 if (pVM->hwaccm.s.fNestedPaging)
599 {
600 VMXSetupCachedReadVMCS(pCache, VMX_VMCS64_GUEST_CR3);
601 VMXSetupCachedReadVMCS(pCache, VMX_VMCS_EXIT_PHYS_ADDR_FULL);
602 pCache->Read.cValidEntries = VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX;
603 }
604 else
605 pCache->Read.cValidEntries = VMX_VMCS_MAX_CACHE_IDX;
606 } /* for each VMCPU */
607
608 /* Choose the right TLB setup function. */
609 if (pVM->hwaccm.s.fNestedPaging)
610 {
611 pVM->hwaccm.s.vmx.pfnSetupTaggedTLB = vmxR0SetupTLBEPT;
612
613 /* Default values for flushing. */
614 pVM->hwaccm.s.vmx.enmFlushPage = VMX_FLUSH_ALL_CONTEXTS;
615 pVM->hwaccm.s.vmx.enmFlushContext = VMX_FLUSH_ALL_CONTEXTS;
616
617 /* If the capabilities specify we can do more, then make use of it. */
618 if (pVM->hwaccm.s.vmx.msr.vmx_eptcaps & MSR_IA32_VMX_EPT_CAPS_INVEPT_CAPS_INDIV)
619 pVM->hwaccm.s.vmx.enmFlushPage = VMX_FLUSH_PAGE;
620 else
621 if (pVM->hwaccm.s.vmx.msr.vmx_eptcaps & MSR_IA32_VMX_EPT_CAPS_INVEPT_CAPS_CONTEXT)
622 pVM->hwaccm.s.vmx.enmFlushPage = VMX_FLUSH_SINGLE_CONTEXT;
623
624 if (pVM->hwaccm.s.vmx.msr.vmx_eptcaps & MSR_IA32_VMX_EPT_CAPS_INVEPT_CAPS_CONTEXT)
625 pVM->hwaccm.s.vmx.enmFlushContext = VMX_FLUSH_SINGLE_CONTEXT;
626 }
627#ifdef HWACCM_VTX_WITH_VPID
628 else
629 if (pVM->hwaccm.s.vmx.fVPID)
630 {
631 pVM->hwaccm.s.vmx.pfnSetupTaggedTLB = vmxR0SetupTLBVPID;
632
633 /* Default values for flushing. */
634 pVM->hwaccm.s.vmx.enmFlushPage = VMX_FLUSH_ALL_CONTEXTS;
635 pVM->hwaccm.s.vmx.enmFlushContext = VMX_FLUSH_ALL_CONTEXTS;
636
637 /* If the capabilities specify we can do more, then make use of it. */
638 if (pVM->hwaccm.s.vmx.msr.vmx_eptcaps & MSR_IA32_VMX_EPT_CAPS_INVVPID_CAPS_INDIV)
639 pVM->hwaccm.s.vmx.enmFlushPage = VMX_FLUSH_PAGE;
640 else
641 if (pVM->hwaccm.s.vmx.msr.vmx_eptcaps & MSR_IA32_VMX_EPT_CAPS_INVVPID_CAPS_CONTEXT)
642 pVM->hwaccm.s.vmx.enmFlushPage = VMX_FLUSH_SINGLE_CONTEXT;
643
644 if (pVM->hwaccm.s.vmx.msr.vmx_eptcaps & MSR_IA32_VMX_EPT_CAPS_INVVPID_CAPS_CONTEXT)
645 pVM->hwaccm.s.vmx.enmFlushContext = VMX_FLUSH_SINGLE_CONTEXT;
646 }
647#endif /* HWACCM_VTX_WITH_VPID */
648 else
649 pVM->hwaccm.s.vmx.pfnSetupTaggedTLB = vmxR0SetupTLBDummy;
650
651vmx_end:
652 VMXR0CheckError(pVM, &pVM->aCpus[0], rc);
653 return rc;
654}
655
656/**
657 * Sets the permission bits for the specified MSR
658 *
659 * @param pVCpu The VMCPU to operate on.
660 * @param ulMSR MSR value
661 * @param fRead Reading allowed/disallowed
662 * @param fWrite Writing allowed/disallowed
663 */
664static void vmxR0SetMSRPermission(PVMCPU pVCpu, unsigned ulMSR, bool fRead, bool fWrite)
665{
666 unsigned ulBit;
667 uint8_t *pMSRBitmap = (uint8_t *)pVCpu->hwaccm.s.vmx.pMSRBitmap;
668
669 /* Layout:
670 * 0x000 - 0x3ff - Low MSR read bits
671 * 0x400 - 0x7ff - High MSR read bits
672 * 0x800 - 0xbff - Low MSR write bits
673 * 0xc00 - 0xfff - High MSR write bits
674 */
675 if (ulMSR <= 0x00001FFF)
676 {
677 /* Pentium-compatible MSRs */
678 ulBit = ulMSR;
679 }
680 else
681 if ( ulMSR >= 0xC0000000
682 && ulMSR <= 0xC0001FFF)
683 {
684 /* AMD Sixth Generation x86 Processor MSRs */
685 ulBit = (ulMSR - 0xC0000000);
686 pMSRBitmap += 0x400;
687 }
688 else
689 {
690 AssertFailed();
691 return;
692 }
693
694 Assert(ulBit <= 0x1fff);
695 if (fRead)
696 ASMBitClear(pMSRBitmap, ulBit);
697 else
698 ASMBitSet(pMSRBitmap, ulBit);
699
700 if (fWrite)
701 ASMBitClear(pMSRBitmap + 0x800, ulBit);
702 else
703 ASMBitSet(pMSRBitmap + 0x800, ulBit);
704}
705
706
707/**
708 * Injects an event (trap or external interrupt)
709 *
710 * @returns VBox status code.
711 * @param pVM The VM to operate on.
712 * @param pVCpu The VMCPU to operate on.
713 * @param pCtx CPU Context
714 * @param intInfo VMX interrupt info
715 * @param cbInstr Opcode length of faulting instruction
716 * @param errCode Error code (optional)
717 */
718static int VMXR0InjectEvent(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t intInfo, uint32_t cbInstr, uint32_t errCode)
719{
720 int rc;
721 uint32_t iGate = VMX_EXIT_INTERRUPTION_INFO_VECTOR(intInfo);
722
723#ifdef VBOX_WITH_STATISTICS
724 STAM_COUNTER_INC(&pVCpu->hwaccm.s.paStatInjectedIrqsR0[iGate & MASK_INJECT_IRQ_STAT]);
725#endif
726
727#ifdef VBOX_STRICT
728 if (iGate == 0xE)
729 LogFlow(("VMXR0InjectEvent: Injecting interrupt %d at %RGv error code=%08x CR2=%RGv intInfo=%08x\n", iGate, (RTGCPTR)pCtx->rip, errCode, pCtx->cr2, intInfo));
730 else
731 if (iGate < 0x20)
732 LogFlow(("VMXR0InjectEvent: Injecting interrupt %d at %RGv error code=%08x\n", iGate, (RTGCPTR)pCtx->rip, errCode));
733 else
734 {
735 LogFlow(("INJ-EI: %x at %RGv\n", iGate, (RTGCPTR)pCtx->rip));
736 Assert(VMX_EXIT_INTERRUPTION_INFO_TYPE(intInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW || !VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
737 Assert(VMX_EXIT_INTERRUPTION_INFO_TYPE(intInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW || pCtx->eflags.u32 & X86_EFL_IF);
738 }
739#endif
740
741#ifdef HWACCM_VMX_EMULATE_REALMODE
742 if (CPUMIsGuestInRealModeEx(pCtx))
743 {
744 RTGCPHYS GCPhysHandler;
745 uint16_t offset, ip;
746 RTSEL sel;
747
748 /* Injecting events doesn't work right with real mode emulation.
749 * (#GP if we try to inject external hardware interrupts)
750 * Inject the interrupt or trap directly instead.
751 *
752 * ASSUMES no access handlers for the bits we read or write below (should be safe).
753 */
754 Log(("Manual interrupt/trap '%x' inject (real mode)\n", iGate));
755
756 /* Check if the interrupt handler is present. */
757 if (iGate * 4 + 3 > pCtx->idtr.cbIdt)
758 {
759 Log(("IDT cbIdt violation\n"));
760 if (iGate != X86_XCPT_DF)
761 {
762 RTGCUINTPTR intInfo;
763
764 intInfo = (iGate == X86_XCPT_GP) ? (uint32_t)X86_XCPT_DF : iGate;
765 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
766 intInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
767 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HWEXCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
768
769 return VMXR0InjectEvent(pVM, pVCpu, pCtx, intInfo, 0, 0 /* no error code according to the Intel docs */);
770 }
771 Log(("Triple fault -> reset the VM!\n"));
772 return VINF_EM_RESET;
773 }
774 if ( VMX_EXIT_INTERRUPTION_INFO_TYPE(intInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW
775 || iGate == 3 /* Both #BP and #OF point to the instruction after. */
776 || iGate == 4)
777 {
778 ip = pCtx->ip + cbInstr;
779 }
780 else
781 ip = pCtx->ip;
782
783 /* Read the selector:offset pair of the interrupt handler. */
784 GCPhysHandler = (RTGCPHYS)pCtx->idtr.pIdt + iGate * 4;
785 rc = PGMPhysSimpleReadGCPhys(pVM, &offset, GCPhysHandler, sizeof(offset)); AssertRC(rc);
786 rc = PGMPhysSimpleReadGCPhys(pVM, &sel, GCPhysHandler + 2, sizeof(sel)); AssertRC(rc);
787
788 LogFlow(("IDT handler %04X:%04X\n", sel, offset));
789
790 /* Construct the stack frame. */
791 /** @todo should check stack limit. */
792 pCtx->sp -= 2;
793 LogFlow(("ss:sp %04X:%04X eflags=%x\n", pCtx->ss, pCtx->sp, pCtx->eflags.u));
794 rc = PGMPhysSimpleWriteGCPhys(pVM, pCtx->ssHid.u64Base + pCtx->sp, &pCtx->eflags, sizeof(uint16_t)); AssertRC(rc);
795 pCtx->sp -= 2;
796 LogFlow(("ss:sp %04X:%04X cs=%x\n", pCtx->ss, pCtx->sp, pCtx->cs));
797 rc = PGMPhysSimpleWriteGCPhys(pVM, pCtx->ssHid.u64Base + pCtx->sp, &pCtx->cs, sizeof(uint16_t)); AssertRC(rc);
798 pCtx->sp -= 2;
799 LogFlow(("ss:sp %04X:%04X ip=%x\n", pCtx->ss, pCtx->sp, ip));
800 rc = PGMPhysSimpleWriteGCPhys(pVM, pCtx->ssHid.u64Base + pCtx->sp, &ip, sizeof(ip)); AssertRC(rc);
801
802 /* Update the CPU state for executing the handler. */
803 pCtx->rip = offset;
804 pCtx->cs = sel;
805 pCtx->csHid.u64Base = sel << 4;
806 pCtx->eflags.u &= ~(X86_EFL_IF|X86_EFL_TF|X86_EFL_RF|X86_EFL_AC);
807
808 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_SEGMENT_REGS;
809 return VINF_SUCCESS;
810 }
811#endif /* HWACCM_VMX_EMULATE_REALMODE */
812
813 /* Set event injection state. */
814 rc = VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_IRQ_INFO, intInfo | (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT));
815
816 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
817 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_EXCEPTION_ERRCODE, errCode);
818
819 AssertRC(rc);
820 return rc;
821}
822
823
824/**
825 * Checks for pending guest interrupts and injects them
826 *
827 * @returns VBox status code.
828 * @param pVM The VM to operate on.
829 * @param pVCpu The VMCPU to operate on.
830 * @param pCtx CPU Context
831 */
832static int VMXR0CheckPendingInterrupt(PVM pVM, PVMCPU pVCpu, CPUMCTX *pCtx)
833{
834 int rc;
835
836 /* Dispatch any pending interrupts. (injected before, but a VM exit occurred prematurely) */
837 if (pVCpu->hwaccm.s.Event.fPending)
838 {
839 Log(("CPU%d: Reinjecting event %RX64 %08x at %RGv cr2=%RX64\n", pVCpu->idCpu, pVCpu->hwaccm.s.Event.intInfo, pVCpu->hwaccm.s.Event.errCode, (RTGCPTR)pCtx->rip, pCtx->cr2));
840 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatIntReinject);
841 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, pVCpu->hwaccm.s.Event.intInfo, 0, pVCpu->hwaccm.s.Event.errCode);
842 AssertRC(rc);
843
844 pVCpu->hwaccm.s.Event.fPending = false;
845 return VINF_SUCCESS;
846 }
847
848 /* If an active trap is already pending, then we must forward it first! */
849 if (!TRPMHasTrap(pVCpu))
850 {
851 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI))
852 {
853 RTGCUINTPTR intInfo;
854
855 Log(("CPU%d: injecting #NMI\n", pVCpu->idCpu));
856
857 intInfo = X86_XCPT_NMI;
858 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
859 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
860
861 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, intInfo, 0, 0);
862 AssertRC(rc);
863
864 return VINF_SUCCESS;
865 }
866
867 /* @todo SMI interrupts. */
868
869 /* When external interrupts are pending, we should exit the VM when IF is set. */
870 if (VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)))
871 {
872 if (!(pCtx->eflags.u32 & X86_EFL_IF))
873 {
874 if (!(pVCpu->hwaccm.s.vmx.proc_ctls & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_IRQ_WINDOW_EXIT))
875 {
876 LogFlow(("Enable irq window exit!\n"));
877 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_IRQ_WINDOW_EXIT;
878 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
879 AssertRC(rc);
880 }
881 /* else nothing to do but wait */
882 }
883 else
884 if (!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
885 {
886 uint8_t u8Interrupt;
887
888 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
889 Log(("CPU%d: Dispatch interrupt: u8Interrupt=%x (%d) rc=%Rrc cs:rip=%04X:%RGv\n", pVCpu->idCpu, u8Interrupt, u8Interrupt, rc, pCtx->cs, (RTGCPTR)pCtx->rip));
890 if (RT_SUCCESS(rc))
891 {
892 rc = TRPMAssertTrap(pVCpu, u8Interrupt, TRPM_HARDWARE_INT);
893 AssertRC(rc);
894 }
895 else
896 {
897 /* Can only happen in rare cases where a pending interrupt is cleared behind our back */
898 Assert(!VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)));
899 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatSwitchGuestIrq);
900 /* Just continue */
901 }
902 }
903 else
904 Log(("Pending interrupt blocked at %RGv by VM_FF_INHIBIT_INTERRUPTS!!\n", (RTGCPTR)pCtx->rip));
905 }
906 }
907
908#ifdef VBOX_STRICT
909 if (TRPMHasTrap(pVCpu))
910 {
911 uint8_t u8Vector;
912 rc = TRPMQueryTrapAll(pVCpu, &u8Vector, 0, 0, 0);
913 AssertRC(rc);
914 }
915#endif
916
917 if ( (pCtx->eflags.u32 & X86_EFL_IF)
918 && (!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
919 && TRPMHasTrap(pVCpu)
920 )
921 {
922 uint8_t u8Vector;
923 int rc;
924 TRPMEVENT enmType;
925 RTGCUINTPTR intInfo;
926 RTGCUINT errCode;
927
928 /* If a new event is pending, then dispatch it now. */
929 rc = TRPMQueryTrapAll(pVCpu, &u8Vector, &enmType, &errCode, 0);
930 AssertRC(rc);
931 Assert(pCtx->eflags.Bits.u1IF == 1 || enmType == TRPM_TRAP);
932 Assert(enmType != TRPM_SOFTWARE_INT);
933
934 /* Clear the pending trap. */
935 rc = TRPMResetTrap(pVCpu);
936 AssertRC(rc);
937
938 intInfo = u8Vector;
939 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
940
941 if (enmType == TRPM_TRAP)
942 {
943 switch (u8Vector) {
944 case 8:
945 case 10:
946 case 11:
947 case 12:
948 case 13:
949 case 14:
950 case 17:
951 /* Valid error codes. */
952 intInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
953 break;
954 default:
955 break;
956 }
957 if (u8Vector == X86_XCPT_BP || u8Vector == X86_XCPT_OF)
958 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
959 else
960 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HWEXCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
961 }
962 else
963 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
964
965 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatIntInject);
966 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, intInfo, 0, errCode);
967 AssertRC(rc);
968 } /* if (interrupts can be dispatched) */
969
970 return VINF_SUCCESS;
971}
972
973/**
974 * Save the host state
975 *
976 * @returns VBox status code.
977 * @param pVM The VM to operate on.
978 * @param pVCpu The VMCPU to operate on.
979 */
980VMMR0DECL(int) VMXR0SaveHostState(PVM pVM, PVMCPU pVCpu)
981{
982 int rc = VINF_SUCCESS;
983
984 /*
985 * Host CPU Context
986 */
987 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_HOST_CONTEXT)
988 {
989 RTIDTR idtr;
990 RTGDTR gdtr;
991 RTSEL SelTR;
992 PX86DESCHC pDesc;
993 uintptr_t trBase;
994 RTSEL cs;
995 RTSEL ss;
996 uint64_t cr3;
997
998 /* Control registers */
999 rc = VMXWriteVMCS(VMX_VMCS_HOST_CR0, ASMGetCR0());
1000#ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1001 if (VMX_IS_64BIT_HOST_MODE())
1002 {
1003 cr3 = hwaccmR0Get64bitCR3();
1004 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_CR3, cr3);
1005 }
1006 else
1007#endif
1008 {
1009 cr3 = ASMGetCR3();
1010 rc |= VMXWriteVMCS(VMX_VMCS_HOST_CR3, cr3);
1011 }
1012 rc |= VMXWriteVMCS(VMX_VMCS_HOST_CR4, ASMGetCR4());
1013 AssertRC(rc);
1014 Log2(("VMX_VMCS_HOST_CR0 %08x\n", ASMGetCR0()));
1015 Log2(("VMX_VMCS_HOST_CR3 %08RX64\n", cr3));
1016 Log2(("VMX_VMCS_HOST_CR4 %08x\n", ASMGetCR4()));
1017
1018 /* Selector registers. */
1019#ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1020 if (VMX_IS_64BIT_HOST_MODE())
1021 {
1022 cs = (RTSEL)(uintptr_t)&SUPR0Abs64bitKernelCS;
1023 ss = (RTSEL)(uintptr_t)&SUPR0Abs64bitKernelSS;
1024 }
1025 else
1026 {
1027 /* sysenter loads LDT cs & ss, VMX doesn't like this. Load the GDT ones (safe). */
1028 cs = (RTSEL)(uintptr_t)&SUPR0AbsKernelCS;
1029 ss = (RTSEL)(uintptr_t)&SUPR0AbsKernelSS;
1030 }
1031#else
1032 cs = ASMGetCS();
1033 ss = ASMGetSS();
1034#endif
1035 Assert(!(cs & X86_SEL_LDT)); Assert((cs & X86_SEL_RPL) == 0);
1036 Assert(!(ss & X86_SEL_LDT)); Assert((ss & X86_SEL_RPL) == 0);
1037 rc = VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_CS, cs);
1038 /* Note: VMX is (again) very picky about the RPL of the selectors here; we'll restore them manually. */
1039 rc |= VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_DS, 0);
1040 rc |= VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_ES, 0);
1041#if HC_ARCH_BITS == 32
1042 if (!VMX_IS_64BIT_HOST_MODE())
1043 {
1044 rc |= VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_FS, 0);
1045 rc |= VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_GS, 0);
1046 }
1047#endif
1048 rc |= VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_SS, ss);
1049 SelTR = ASMGetTR();
1050 rc |= VMXWriteVMCS(VMX_VMCS16_HOST_FIELD_TR, SelTR);
1051 AssertRC(rc);
1052 Log2(("VMX_VMCS_HOST_FIELD_CS %08x (%08x)\n", cs, ASMGetSS()));
1053 Log2(("VMX_VMCS_HOST_FIELD_DS 00000000 (%08x)\n", ASMGetDS()));
1054 Log2(("VMX_VMCS_HOST_FIELD_ES 00000000 (%08x)\n", ASMGetES()));
1055 Log2(("VMX_VMCS_HOST_FIELD_FS 00000000 (%08x)\n", ASMGetFS()));
1056 Log2(("VMX_VMCS_HOST_FIELD_GS 00000000 (%08x)\n", ASMGetGS()));
1057 Log2(("VMX_VMCS_HOST_FIELD_SS %08x (%08x)\n", ss, ASMGetSS()));
1058 Log2(("VMX_VMCS_HOST_FIELD_TR %08x\n", ASMGetTR()));
1059
1060 /* GDTR & IDTR */
1061#ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1062 if (VMX_IS_64BIT_HOST_MODE())
1063 {
1064 X86XDTR64 gdtr64, idtr64;
1065 hwaccmR0Get64bitGDTRandIDTR(&gdtr64, &idtr64);
1066 rc = VMXWriteVMCS64(VMX_VMCS_HOST_GDTR_BASE, gdtr64.uAddr);
1067 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_IDTR_BASE, gdtr64.uAddr);
1068 AssertRC(rc);
1069 Log2(("VMX_VMCS_HOST_GDTR_BASE %RX64\n", gdtr64.uAddr));
1070 Log2(("VMX_VMCS_HOST_IDTR_BASE %RX64\n", idtr64.uAddr));
1071 gdtr.cbGdt = gdtr64.cb;
1072 gdtr.pGdt = (uintptr_t)gdtr64.uAddr;
1073 }
1074 else
1075#endif
1076 {
1077 ASMGetGDTR(&gdtr);
1078 rc = VMXWriteVMCS(VMX_VMCS_HOST_GDTR_BASE, gdtr.pGdt);
1079 ASMGetIDTR(&idtr);
1080 rc |= VMXWriteVMCS(VMX_VMCS_HOST_IDTR_BASE, idtr.pIdt);
1081 AssertRC(rc);
1082 Log2(("VMX_VMCS_HOST_GDTR_BASE %RHv\n", gdtr.pGdt));
1083 Log2(("VMX_VMCS_HOST_IDTR_BASE %RHv\n", idtr.pIdt));
1084 }
1085
1086 /* Save the base address of the TR selector. */
1087 if (SelTR > gdtr.cbGdt)
1088 {
1089 AssertMsgFailed(("Invalid TR selector %x. GDTR.cbGdt=%x\n", SelTR, gdtr.cbGdt));
1090 return VERR_VMX_INVALID_HOST_STATE;
1091 }
1092
1093#ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1094 if (VMX_IS_64BIT_HOST_MODE())
1095 {
1096 pDesc = &((PX86DESCHC)gdtr.pGdt)[SelTR >> X86_SEL_SHIFT_HC]; /// ????
1097 uint64_t trBase64 = X86DESC64_BASE(*(PX86DESC64)pDesc);
1098 rc = VMXWriteVMCS64(VMX_VMCS_HOST_TR_BASE, trBase64);
1099 Log2(("VMX_VMCS_HOST_TR_BASE %RX64\n", trBase64));
1100 AssertRC(rc);
1101 }
1102 else
1103#endif
1104 {
1105 pDesc = &((PX86DESCHC)gdtr.pGdt)[SelTR >> X86_SEL_SHIFT_HC];
1106#if HC_ARCH_BITS == 64
1107 trBase = X86DESC64_BASE(*pDesc);
1108#else
1109 trBase = X86DESC_BASE(*pDesc);
1110#endif
1111 rc = VMXWriteVMCS(VMX_VMCS_HOST_TR_BASE, trBase);
1112 AssertRC(rc);
1113 Log2(("VMX_VMCS_HOST_TR_BASE %RHv\n", trBase));
1114 }
1115
1116 /* FS and GS base. */
1117#if HC_ARCH_BITS == 64 || defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1118 if (VMX_IS_64BIT_HOST_MODE())
1119 {
1120 Log2(("MSR_K8_FS_BASE = %RX64\n", ASMRdMsr(MSR_K8_FS_BASE)));
1121 Log2(("MSR_K8_GS_BASE = %RX64\n", ASMRdMsr(MSR_K8_GS_BASE)));
1122 rc = VMXWriteVMCS64(VMX_VMCS_HOST_FS_BASE, ASMRdMsr(MSR_K8_FS_BASE));
1123 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_GS_BASE, ASMRdMsr(MSR_K8_GS_BASE));
1124 }
1125#endif
1126 AssertRC(rc);
1127
1128 /* Sysenter MSRs. */
1129 /** @todo expensive!! */
1130 rc = VMXWriteVMCS(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS));
1131 Log2(("VMX_VMCS_HOST_SYSENTER_CS %08x\n", ASMRdMsr_Low(MSR_IA32_SYSENTER_CS)));
1132#ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1133 if (VMX_IS_64BIT_HOST_MODE())
1134 {
1135 Log2(("VMX_VMCS_HOST_SYSENTER_EIP %RX64\n", ASMRdMsr(MSR_IA32_SYSENTER_EIP)));
1136 Log2(("VMX_VMCS_HOST_SYSENTER_ESP %RX64\n", ASMRdMsr(MSR_IA32_SYSENTER_ESP)));
1137 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP));
1138 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP));
1139 }
1140 else
1141 {
1142 rc |= VMXWriteVMCS(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr_Low(MSR_IA32_SYSENTER_ESP));
1143 rc |= VMXWriteVMCS(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr_Low(MSR_IA32_SYSENTER_EIP));
1144 Log2(("VMX_VMCS_HOST_SYSENTER_EIP %RX32\n", ASMRdMsr_Low(MSR_IA32_SYSENTER_EIP)));
1145 Log2(("VMX_VMCS_HOST_SYSENTER_ESP %RX32\n", ASMRdMsr_Low(MSR_IA32_SYSENTER_ESP)));
1146 }
1147#elif HC_ARCH_BITS == 32
1148 rc |= VMXWriteVMCS(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr_Low(MSR_IA32_SYSENTER_ESP));
1149 rc |= VMXWriteVMCS(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr_Low(MSR_IA32_SYSENTER_EIP));
1150 Log2(("VMX_VMCS_HOST_SYSENTER_EIP %RX32\n", ASMRdMsr_Low(MSR_IA32_SYSENTER_EIP)));
1151 Log2(("VMX_VMCS_HOST_SYSENTER_ESP %RX32\n", ASMRdMsr_Low(MSR_IA32_SYSENTER_ESP)));
1152#else
1153 Log2(("VMX_VMCS_HOST_SYSENTER_EIP %RX64\n", ASMRdMsr(MSR_IA32_SYSENTER_EIP)));
1154 Log2(("VMX_VMCS_HOST_SYSENTER_ESP %RX64\n", ASMRdMsr(MSR_IA32_SYSENTER_ESP)));
1155 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP));
1156 rc |= VMXWriteVMCS64(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP));
1157#endif
1158 AssertRC(rc);
1159
1160 /* Store all host MSRs in the VM-Exit load area, so they will be reloaded after the world switch back to the host. */
1161 PVMXMSR pMsr = (PVMXMSR)pVCpu->hwaccm.s.vmx.pHostMSR;
1162 unsigned idxMsr = 0;
1163
1164 /* EFER MSR present? */
1165 if (ASMCpuId_EDX(0x80000001) & (X86_CPUID_AMD_FEATURE_EDX_NX|X86_CPUID_AMD_FEATURE_EDX_LONG_MODE))
1166 {
1167 if (ASMCpuId_EDX(0x80000001) & X86_CPUID_AMD_FEATURE_EDX_SEP)
1168 {
1169 pMsr->u32IndexMSR = MSR_K6_STAR;
1170 pMsr->u32Reserved = 0;
1171 pMsr->u64Value = ASMRdMsr(MSR_K6_STAR); /* legacy syscall eip, cs & ss */
1172 pMsr++; idxMsr++;
1173 }
1174
1175 pMsr->u32IndexMSR = MSR_K6_EFER;
1176 pMsr->u32Reserved = 0;
1177#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1178 if (CPUMIsGuestInLongMode(pVCpu))
1179 {
1180 /* Must match the efer value in our 64 bits switcher. */
1181 pMsr->u64Value = ASMRdMsr(MSR_K6_EFER) | MSR_K6_EFER_LME | MSR_K6_EFER_SCE | MSR_K6_EFER_NXE;
1182 }
1183 else
1184#endif
1185 pMsr->u64Value = ASMRdMsr(MSR_K6_EFER);
1186 pMsr++; idxMsr++;
1187 }
1188
1189#if HC_ARCH_BITS == 64 || defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1190 if (VMX_IS_64BIT_HOST_MODE())
1191 {
1192 pMsr->u32IndexMSR = MSR_K8_LSTAR;
1193 pMsr->u32Reserved = 0;
1194 pMsr->u64Value = ASMRdMsr(MSR_K8_LSTAR); /* 64 bits mode syscall rip */
1195 pMsr++; idxMsr++;
1196 pMsr->u32IndexMSR = MSR_K8_SF_MASK;
1197 pMsr->u32Reserved = 0;
1198 pMsr->u64Value = ASMRdMsr(MSR_K8_SF_MASK); /* syscall flag mask */
1199 pMsr++; idxMsr++;
1200 pMsr->u32IndexMSR = MSR_K8_KERNEL_GS_BASE;
1201 pMsr->u32Reserved = 0;
1202 pMsr->u64Value = ASMRdMsr(MSR_K8_KERNEL_GS_BASE); /* swapgs exchange value */
1203 pMsr++; idxMsr++;
1204 }
1205#endif
1206 rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXIT_MSR_LOAD_COUNT, idxMsr);
1207 AssertRC(rc);
1208
1209 pVCpu->hwaccm.s.fContextUseFlags &= ~HWACCM_CHANGED_HOST_CONTEXT;
1210 }
1211 return rc;
1212}
1213
1214/**
1215 * Prefetch the 4 PDPT pointers (PAE and nested paging only)
1216 *
1217 * @param pVM The VM to operate on.
1218 * @param pVCpu The VMCPU to operate on.
1219 * @param pCtx Guest context
1220 */
1221static void vmxR0PrefetchPAEPdptrs(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1222{
1223 if (CPUMIsGuestInPAEModeEx(pCtx))
1224 {
1225 X86PDPE Pdpe;
1226
1227 for (unsigned i=0;i<4;i++)
1228 {
1229 Pdpe = PGMGstGetPaePDPtr(pVCpu, i);
1230 int rc = VMXWriteVMCS64(VMX_VMCS_GUEST_PDPTR0_FULL + i*2, Pdpe.u);
1231 AssertRC(rc);
1232 }
1233 }
1234}
1235
1236/**
1237 * Update the exception bitmap according to the current CPU state
1238 *
1239 * @param pVM The VM to operate on.
1240 * @param pVCpu The VMCPU to operate on.
1241 * @param pCtx Guest context
1242 */
1243static void vmxR0UpdateExceptionBitmap(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1244{
1245 uint32_t u32TrapMask;
1246 Assert(pCtx);
1247
1248 u32TrapMask = HWACCM_VMX_TRAP_MASK;
1249#ifndef DEBUG
1250 if (pVM->hwaccm.s.fNestedPaging)
1251 u32TrapMask &= ~RT_BIT(X86_XCPT_PF); /* no longer need to intercept #PF. */
1252#endif
1253
1254 /* Also catch floating point exceptions as we need to report them to the guest in a different way. */
1255 if ( CPUMIsGuestFPUStateActive(pVCpu) == true
1256 && !(pCtx->cr0 & X86_CR0_NE)
1257 && !pVCpu->hwaccm.s.fFPUOldStyleOverride)
1258 {
1259 u32TrapMask |= RT_BIT(X86_XCPT_MF);
1260 pVCpu->hwaccm.s.fFPUOldStyleOverride = true;
1261 }
1262
1263#ifdef DEBUG /* till after branching, enable it by default then. */
1264 /* Intercept X86_XCPT_DB if stepping is enabled */
1265 if ( DBGFIsStepping(pVCpu)
1266 || CPUMIsHyperDebugStateActive(pVCpu))
1267 u32TrapMask |= RT_BIT(X86_XCPT_DB);
1268 /** @todo Don't trap it unless the debugger has armed breakpoints. */
1269 u32TrapMask |= RT_BIT(X86_XCPT_BP);
1270#endif
1271
1272#ifdef VBOX_STRICT
1273 Assert(u32TrapMask & RT_BIT(X86_XCPT_GP));
1274#endif
1275
1276# ifdef HWACCM_VMX_EMULATE_REALMODE
1277 /* Intercept all exceptions in real mode as none of them can be injected directly (#GP otherwise). */
1278 if (CPUMIsGuestInRealModeEx(pCtx) && pVM->hwaccm.s.vmx.pRealModeTSS)
1279 u32TrapMask |= HWACCM_VMX_TRAP_MASK_REALMODE;
1280# endif /* HWACCM_VMX_EMULATE_REALMODE */
1281
1282 int rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXCEPTION_BITMAP, u32TrapMask);
1283 AssertRC(rc);
1284}
1285
1286/**
1287 * Loads the guest state
1288 *
1289 * NOTE: Don't do anything here that can cause a jump back to ring 3!!!!!
1290 *
1291 * @returns VBox status code.
1292 * @param pVM The VM to operate on.
1293 * @param pVCpu The VMCPU to operate on.
1294 * @param pCtx Guest context
1295 */
1296VMMR0DECL(int) VMXR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1297{
1298 int rc = VINF_SUCCESS;
1299 RTGCUINTPTR val;
1300 X86EFLAGS eflags;
1301
1302 /* VMX_VMCS_CTRL_ENTRY_CONTROLS
1303 * Set required bits to one and zero according to the MSR capabilities.
1304 */
1305 val = pVM->hwaccm.s.vmx.msr.vmx_entry.n.disallowed0;
1306 /* Load guest debug controls (dr7 & IA32_DEBUGCTL_MSR) (forced to 1 on the 'first' VT-x capable CPUs; this actually includes the newest Nehalem CPUs) */
1307 val |= VMX_VMCS_CTRL_ENTRY_CONTROLS_LOAD_DEBUG;
1308 /* 64 bits guest mode? */
1309 if (CPUMIsGuestInLongModeEx(pCtx))
1310 val |= VMX_VMCS_CTRL_ENTRY_CONTROLS_IA64_MODE;
1311 /* else Must be zero when AMD64 is not available. */
1312
1313 /* Mask away the bits that the CPU doesn't support */
1314 val &= pVM->hwaccm.s.vmx.msr.vmx_entry.n.allowed1;
1315 rc = VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_CONTROLS, val);
1316 AssertRC(rc);
1317
1318 /* VMX_VMCS_CTRL_EXIT_CONTROLS
1319 * Set required bits to one and zero according to the MSR capabilities.
1320 */
1321 val = pVM->hwaccm.s.vmx.msr.vmx_exit.n.disallowed0;
1322
1323 /* Save debug controls (dr7 & IA32_DEBUGCTL_MSR) (forced to 1 on the 'first' VT-x capable CPUs; this actually includes the newest Nehalem CPUs) */
1324 val |= VMX_VMCS_CTRL_EXIT_CONTROLS_SAVE_DEBUG;
1325
1326#if HC_ARCH_BITS == 64 || defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1327 if (VMX_IS_64BIT_HOST_MODE())
1328 val |= VMX_VMCS_CTRL_EXIT_CONTROLS_HOST_AMD64;
1329 /* else: Must be zero when AMD64 is not available. */
1330#elif HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1331 if (CPUMIsGuestInLongModeEx(pCtx))
1332 val |= VMX_VMCS_CTRL_EXIT_CONTROLS_HOST_AMD64; /* our switcher goes to long mode */
1333 else
1334 Assert(!(val & VMX_VMCS_CTRL_EXIT_CONTROLS_HOST_AMD64));
1335#endif
1336 val &= pVM->hwaccm.s.vmx.msr.vmx_exit.n.allowed1;
1337 /* Don't acknowledge external interrupts on VM-exit. */
1338 rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXIT_CONTROLS, val);
1339 AssertRC(rc);
1340
1341 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1342 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_SEGMENT_REGS)
1343 {
1344#ifdef HWACCM_VMX_EMULATE_REALMODE
1345 if (pVM->hwaccm.s.vmx.pRealModeTSS)
1346 {
1347 PGMMODE enmGuestMode = PGMGetGuestMode(pVCpu);
1348 if (pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode != enmGuestMode)
1349 {
1350 /* Correct weird requirements for switching to protected mode. */
1351 if ( pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode == PGMMODE_REAL
1352 && enmGuestMode >= PGMMODE_PROTECTED)
1353 {
1354 /* Flush the recompiler code cache as it's not unlikely
1355 * the guest will rewrite code it will later execute in real
1356 * mode (OpenBSD 4.0 is one such example)
1357 */
1358 REMFlushTBs(pVM);
1359
1360 /* DPL of all hidden selector registers must match the current CPL (0). */
1361 pCtx->csHid.Attr.n.u2Dpl = 0;
1362 pCtx->csHid.Attr.n.u4Type = X86_SEL_TYPE_CODE | X86_SEL_TYPE_RW_ACC;
1363
1364 pCtx->dsHid.Attr.n.u2Dpl = 0;
1365 pCtx->esHid.Attr.n.u2Dpl = 0;
1366 pCtx->fsHid.Attr.n.u2Dpl = 0;
1367 pCtx->gsHid.Attr.n.u2Dpl = 0;
1368 pCtx->ssHid.Attr.n.u2Dpl = 0;
1369
1370 /* The limit must correspond to the 32 bits setting. */
1371 if (!pCtx->csHid.Attr.n.u1DefBig)
1372 pCtx->csHid.u32Limit &= 0xffff;
1373 if (!pCtx->dsHid.Attr.n.u1DefBig)
1374 pCtx->dsHid.u32Limit &= 0xffff;
1375 if (!pCtx->esHid.Attr.n.u1DefBig)
1376 pCtx->esHid.u32Limit &= 0xffff;
1377 if (!pCtx->fsHid.Attr.n.u1DefBig)
1378 pCtx->fsHid.u32Limit &= 0xffff;
1379 if (!pCtx->gsHid.Attr.n.u1DefBig)
1380 pCtx->gsHid.u32Limit &= 0xffff;
1381 if (!pCtx->ssHid.Attr.n.u1DefBig)
1382 pCtx->ssHid.u32Limit &= 0xffff;
1383 }
1384 else
1385 /* Switching from protected mode to real mode. */
1386 if ( pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode >= PGMMODE_PROTECTED
1387 && enmGuestMode == PGMMODE_REAL)
1388 {
1389 /* The limit must also be set to 0xffff. */
1390 pCtx->csHid.u32Limit = 0xffff;
1391 pCtx->dsHid.u32Limit = 0xffff;
1392 pCtx->esHid.u32Limit = 0xffff;
1393 pCtx->fsHid.u32Limit = 0xffff;
1394 pCtx->gsHid.u32Limit = 0xffff;
1395 pCtx->ssHid.u32Limit = 0xffff;
1396
1397 Assert(pCtx->csHid.u64Base <= 0xfffff);
1398 Assert(pCtx->dsHid.u64Base <= 0xfffff);
1399 Assert(pCtx->esHid.u64Base <= 0xfffff);
1400 Assert(pCtx->fsHid.u64Base <= 0xfffff);
1401 Assert(pCtx->gsHid.u64Base <= 0xfffff);
1402 }
1403 pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode = enmGuestMode;
1404 }
1405 else
1406 /* VT-x will fail with a guest invalid state otherwise... (CPU state after a reset) */
1407 if ( CPUMIsGuestInRealModeEx(pCtx)
1408 && pCtx->csHid.u64Base == 0xffff0000)
1409 {
1410 pCtx->csHid.u64Base = 0xf0000;
1411 pCtx->cs = 0xf000;
1412 }
1413 }
1414#endif /* HWACCM_VMX_EMULATE_REALMODE */
1415
1416 VMX_WRITE_SELREG(ES, es);
1417 AssertRC(rc);
1418
1419 VMX_WRITE_SELREG(CS, cs);
1420 AssertRC(rc);
1421
1422 VMX_WRITE_SELREG(SS, ss);
1423 AssertRC(rc);
1424
1425 VMX_WRITE_SELREG(DS, ds);
1426 AssertRC(rc);
1427
1428 /* The base values in the hidden fs & gs registers are not in sync with the msrs; they are cut to 32 bits. */
1429 VMX_WRITE_SELREG(FS, fs);
1430 AssertRC(rc);
1431
1432 VMX_WRITE_SELREG(GS, gs);
1433 AssertRC(rc);
1434 }
1435
1436 /* Guest CPU context: LDTR. */
1437 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_LDTR)
1438 {
1439 if (pCtx->ldtr == 0)
1440 {
1441 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_LDTR, 0);
1442 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_LIMIT, 0);
1443 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_LDTR_BASE, 0);
1444 /* Note: vmlaunch will fail with 0 or just 0x02. No idea why. */
1445 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, 0x82 /* present, LDT */);
1446 }
1447 else
1448 {
1449 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_LDTR, pCtx->ldtr);
1450 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_LIMIT, pCtx->ldtrHid.u32Limit);
1451 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_LDTR_BASE, pCtx->ldtrHid.u64Base);
1452 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, pCtx->ldtrHid.Attr.u);
1453 }
1454 AssertRC(rc);
1455 }
1456 /* Guest CPU context: TR. */
1457 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_TR)
1458 {
1459#ifdef HWACCM_VMX_EMULATE_REALMODE
1460 /* Real mode emulation using v86 mode with CR4.VME (interrupt redirection using the int bitmap in the TSS) */
1461 if (CPUMIsGuestInRealModeEx(pCtx))
1462 {
1463 RTGCPHYS GCPhys;
1464
1465 /* We convert it here every time as pci regions could be reconfigured. */
1466 rc = PDMVMMDevHeapR3ToGCPhys(pVM, pVM->hwaccm.s.vmx.pRealModeTSS, &GCPhys);
1467 AssertRC(rc);
1468
1469 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_TR, 0);
1470 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_TR_LIMIT, HWACCM_VTX_TSS_SIZE);
1471 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_TR_BASE, GCPhys /* phys = virt in this mode */);
1472
1473 X86DESCATTR attr;
1474
1475 attr.u = 0;
1476 attr.n.u1Present = 1;
1477 attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
1478 val = attr.u;
1479 }
1480 else
1481#endif /* HWACCM_VMX_EMULATE_REALMODE */
1482 {
1483 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_TR, pCtx->tr);
1484 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_TR_LIMIT, pCtx->trHid.u32Limit);
1485 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_TR_BASE, pCtx->trHid.u64Base);
1486
1487 val = pCtx->trHid.Attr.u;
1488
1489 /* The TSS selector must be busy. */
1490 if ((val & 0xF) == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
1491 val = (val & ~0xF) | X86_SEL_TYPE_SYS_286_TSS_BUSY;
1492 else
1493 /* Default even if no TR selector has been set (otherwise vmlaunch will fail!) */
1494 val = (val & ~0xF) | X86_SEL_TYPE_SYS_386_TSS_BUSY;
1495
1496 }
1497 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, val);
1498 AssertRC(rc);
1499 }
1500 /* Guest CPU context: GDTR. */
1501 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_GDTR)
1502 {
1503 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_GDTR_LIMIT, pCtx->gdtr.cbGdt);
1504 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_GDTR_BASE, pCtx->gdtr.pGdt);
1505 AssertRC(rc);
1506 }
1507 /* Guest CPU context: IDTR. */
1508 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_IDTR)
1509 {
1510 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_IDTR_LIMIT, pCtx->idtr.cbIdt);
1511 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_IDTR_BASE, pCtx->idtr.pIdt);
1512 AssertRC(rc);
1513 }
1514
1515 /*
1516 * Sysenter MSRs (unconditional)
1517 */
1518 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_SYSENTER_CS, pCtx->SysEnter.cs);
1519 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_SYSENTER_EIP, pCtx->SysEnter.eip);
1520 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_SYSENTER_ESP, pCtx->SysEnter.esp);
1521 AssertRC(rc);
1522
1523 /* Control registers */
1524 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR0)
1525 {
1526 val = pCtx->cr0;
1527 rc = VMXWriteVMCS(VMX_VMCS_CTRL_CR0_READ_SHADOW, val);
1528 Log2(("Guest CR0-shadow %08x\n", val));
1529 if (CPUMIsGuestFPUStateActive(pVCpu) == false)
1530 {
1531 /* Always use #NM exceptions to load the FPU/XMM state on demand. */
1532 val |= X86_CR0_TS | X86_CR0_ET | X86_CR0_NE | X86_CR0_MP;
1533 }
1534 else
1535 {
1536 /** @todo check if we support the old style mess correctly. */
1537 if (!(val & X86_CR0_NE))
1538 Log(("Forcing X86_CR0_NE!!!\n"));
1539
1540 val |= X86_CR0_NE; /* always turn on the native mechanism to report FPU errors (old style uses interrupts) */
1541 }
1542 /* Note: protected mode & paging are always enabled; we use them for emulating real and protected mode without paging too. */
1543 val |= X86_CR0_PE | X86_CR0_PG;
1544 if (pVM->hwaccm.s.fNestedPaging)
1545 {
1546 if (CPUMIsGuestInPagedProtectedModeEx(pCtx))
1547 {
1548 /* Disable cr3 read/write monitoring as we don't need it for EPT. */
1549 pVCpu->hwaccm.s.vmx.proc_ctls &= ~( VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
1550 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT);
1551 }
1552 else
1553 {
1554 /* Reenable cr3 read/write monitoring as our identity mapped page table is active. */
1555 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
1556 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT;
1557 }
1558 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1559 AssertRC(rc);
1560 }
1561 else
1562 {
1563 /* Note: We must also set this as we rely on protecting various pages for which supervisor writes must be caught. */
1564 val |= X86_CR0_WP;
1565 }
1566
1567 /* Always enable caching. */
1568 val &= ~(X86_CR0_CD|X86_CR0_NW);
1569
1570 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_CR0, val);
1571 Log2(("Guest CR0 %08x\n", val));
1572 /* CR0 flags owned by the host; if the guests attempts to change them, then
1573 * the VM will exit.
1574 */
1575 val = X86_CR0_PE /* Must monitor this bit (assumptions are made for real mode emulation) */
1576 | X86_CR0_WP /* Must monitor this bit (it must always be enabled). */
1577 | X86_CR0_PG /* Must monitor this bit (assumptions are made for real mode & protected mode without paging emulation) */
1578 | X86_CR0_TS
1579 | X86_CR0_ET /* Bit not restored during VM-exit! */
1580 | X86_CR0_CD /* Bit not restored during VM-exit! */
1581 | X86_CR0_NW /* Bit not restored during VM-exit! */
1582 | X86_CR0_NE
1583 | X86_CR0_MP;
1584 pVCpu->hwaccm.s.vmx.cr0_mask = val;
1585
1586 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_CR0_MASK, val);
1587 Log2(("Guest CR0-mask %08x\n", val));
1588 AssertRC(rc);
1589 }
1590 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR4)
1591 {
1592 /* CR4 */
1593 rc = VMXWriteVMCS(VMX_VMCS_CTRL_CR4_READ_SHADOW, pCtx->cr4);
1594 Log2(("Guest CR4-shadow %08x\n", pCtx->cr4));
1595 /* Set the required bits in cr4 too (currently X86_CR4_VMXE). */
1596 val = pCtx->cr4 | (uint32_t)pVM->hwaccm.s.vmx.msr.vmx_cr4_fixed0;
1597
1598 if (!pVM->hwaccm.s.fNestedPaging)
1599 {
1600 switch(pVCpu->hwaccm.s.enmShadowMode)
1601 {
1602 case PGMMODE_REAL: /* Real mode -> emulated using v86 mode */
1603 case PGMMODE_PROTECTED: /* Protected mode, no paging -> emulated using identity mapping. */
1604 case PGMMODE_32_BIT: /* 32-bit paging. */
1605 val &= ~X86_CR4_PAE;
1606 break;
1607
1608 case PGMMODE_PAE: /* PAE paging. */
1609 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1610 /** @todo use normal 32 bits paging */
1611 val |= X86_CR4_PAE;
1612 break;
1613
1614 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1615 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1616#ifdef VBOX_ENABLE_64_BITS_GUESTS
1617 break;
1618#else
1619 AssertFailed();
1620 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1621#endif
1622 default: /* shut up gcc */
1623 AssertFailed();
1624 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1625 }
1626 }
1627 else
1628 if (!CPUMIsGuestInPagedProtectedModeEx(pCtx))
1629 {
1630 /* We use 4 MB pages in our identity mapping page table for real and protected mode without paging. */
1631 val |= X86_CR4_PSE;
1632 /* Our identity mapping is a 32 bits page directory. */
1633 val &= ~X86_CR4_PAE;
1634 }
1635
1636 /* Turn off VME if we're in emulated real mode. */
1637 if (CPUMIsGuestInRealModeEx(pCtx))
1638 val &= ~X86_CR4_VME;
1639
1640 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_CR4, val);
1641 Log2(("Guest CR4 %08x\n", val));
1642 /* CR4 flags owned by the host; if the guests attempts to change them, then
1643 * the VM will exit.
1644 */
1645 val = 0
1646 | X86_CR4_VME
1647 | X86_CR4_PAE
1648 | X86_CR4_PGE
1649 | X86_CR4_PSE
1650 | X86_CR4_VMXE;
1651 pVCpu->hwaccm.s.vmx.cr4_mask = val;
1652
1653 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_CR4_MASK, val);
1654 Log2(("Guest CR4-mask %08x\n", val));
1655 AssertRC(rc);
1656 }
1657
1658 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR3)
1659 {
1660 if (pVM->hwaccm.s.fNestedPaging)
1661 {
1662 Assert(PGMGetHyperCR3(pVCpu));
1663 pVCpu->hwaccm.s.vmx.GCPhysEPTP = PGMGetHyperCR3(pVCpu);
1664
1665 Assert(!(pVCpu->hwaccm.s.vmx.GCPhysEPTP & 0xfff));
1666 /** @todo Check the IA32_VMX_EPT_VPID_CAP MSR for other supported memory types. */
1667 pVCpu->hwaccm.s.vmx.GCPhysEPTP |= VMX_EPT_MEMTYPE_WB
1668 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
1669
1670 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_EPTP_FULL, pVCpu->hwaccm.s.vmx.GCPhysEPTP);
1671 AssertRC(rc);
1672
1673 if (!CPUMIsGuestInPagedProtectedModeEx(pCtx))
1674 {
1675 RTGCPHYS GCPhys;
1676
1677 /* We convert it here every time as pci regions could be reconfigured. */
1678 rc = PDMVMMDevHeapR3ToGCPhys(pVM, pVM->hwaccm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
1679 AssertRC(rc);
1680
1681 /* We use our identity mapping page table here as we need to map guest virtual to guest physical addresses; EPT will
1682 * take care of the translation to host physical addresses.
1683 */
1684 val = GCPhys;
1685 }
1686 else
1687 {
1688 /* Save the real guest CR3 in VMX_VMCS_GUEST_CR3 */
1689 val = pCtx->cr3;
1690 /* Prefetch the four PDPT entries in PAE mode. */
1691 vmxR0PrefetchPAEPdptrs(pVM, pVCpu, pCtx);
1692 }
1693 }
1694 else
1695 {
1696 val = PGMGetHyperCR3(pVCpu);
1697 Assert(val || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
1698 }
1699
1700 /* Save our shadow CR3 register. */
1701 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_CR3, val);
1702 AssertRC(rc);
1703 }
1704
1705 /* Debug registers. */
1706 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_DEBUG)
1707 {
1708 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* set all reserved bits to 1. */
1709 pCtx->dr[6] &= ~RT_BIT(12); /* must be zero. */
1710
1711 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
1712 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
1713 pCtx->dr[7] |= 0x400; /* must be one */
1714
1715 /* Resync DR7 */
1716 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, pCtx->dr[7]);
1717 AssertRC(rc);
1718
1719#ifdef DEBUG
1720 /* Sync the hypervisor debug state now if any breakpoint is armed. */
1721 if ( CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK|X86_DR7_GD)
1722 && !CPUMIsHyperDebugStateActive(pVCpu)
1723 && !DBGFIsStepping(pVCpu))
1724 {
1725 /* Save the host and load the hypervisor debug state. */
1726 rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1727 AssertRC(rc);
1728
1729 /* DRx intercepts remain enabled. */
1730
1731 /* Override dr7 with the hypervisor value. */
1732 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, CPUMGetHyperDR7(pVCpu));
1733 AssertRC(rc);
1734 }
1735 else
1736#endif
1737 /* Sync the debug state now if any breakpoint is armed. */
1738 if ( (pCtx->dr[7] & (X86_DR7_ENABLED_MASK|X86_DR7_GD))
1739 && !CPUMIsGuestDebugStateActive(pVCpu)
1740 && !DBGFIsStepping(pVCpu))
1741 {
1742 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxArmed);
1743
1744 /* Disable drx move intercepts. */
1745 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT;
1746 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1747 AssertRC(rc);
1748
1749 /* Save the host and load the guest debug state. */
1750 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1751 AssertRC(rc);
1752 }
1753
1754 /* IA32_DEBUGCTL MSR. */
1755 rc = VMXWriteVMCS64(VMX_VMCS_GUEST_DEBUGCTL_FULL, 0);
1756 AssertRC(rc);
1757
1758 /** @todo do we really ever need this? */
1759 rc |= VMXWriteVMCS(VMX_VMCS_GUEST_DEBUG_EXCEPTIONS, 0);
1760 AssertRC(rc);
1761 }
1762
1763 /* EIP, ESP and EFLAGS */
1764 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_RIP, pCtx->rip);
1765 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_RSP, pCtx->rsp);
1766 AssertRC(rc);
1767
1768 /* Bits 22-31, 15, 5 & 3 must be zero. Bit 1 must be 1. */
1769 eflags = pCtx->eflags;
1770 eflags.u32 &= VMX_EFLAGS_RESERVED_0;
1771 eflags.u32 |= VMX_EFLAGS_RESERVED_1;
1772
1773#ifdef HWACCM_VMX_EMULATE_REALMODE
1774 /* Real mode emulation using v86 mode. */
1775 if (CPUMIsGuestInRealModeEx(pCtx))
1776 {
1777 pVCpu->hwaccm.s.vmx.RealMode.eflags = eflags;
1778
1779 eflags.Bits.u1VM = 1;
1780 eflags.Bits.u2IOPL = 0; /* must always be 0 or else certain instructions won't cause faults. */
1781 }
1782#endif /* HWACCM_VMX_EMULATE_REALMODE */
1783 rc = VMXWriteVMCS(VMX_VMCS_GUEST_RFLAGS, eflags.u32);
1784 AssertRC(rc);
1785
1786 /* TSC offset. */
1787 uint64_t u64TSCOffset;
1788
1789 if (TMCpuTickCanUseRealTSC(pVCpu, &u64TSCOffset))
1790 {
1791 /* Note: VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT takes precedence over TSC_OFFSET */
1792 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_TSC_OFFSET_FULL, u64TSCOffset);
1793 AssertRC(rc);
1794
1795 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT;
1796 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1797 AssertRC(rc);
1798 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCOffset);
1799 }
1800 else
1801 {
1802 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT;
1803 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1804 AssertRC(rc);
1805 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCIntercept);
1806 }
1807
1808 /* 64 bits guest mode? */
1809 if (CPUMIsGuestInLongModeEx(pCtx))
1810 {
1811#if !defined(VBOX_ENABLE_64_BITS_GUESTS)
1812 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1813#elif HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1814 pVCpu->hwaccm.s.vmx.pfnStartVM = VMXR0SwitcherStartVM64;
1815#else
1816# ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1817 if (!pVM->hwaccm.s.fAllow64BitGuests)
1818 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1819# endif
1820 pVCpu->hwaccm.s.vmx.pfnStartVM = VMXR0StartVM64;
1821#endif
1822 /* Unconditionally update these as wrmsr might have changed them. */
1823 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_FS_BASE, pCtx->fsHid.u64Base);
1824 AssertRC(rc);
1825 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_GS_BASE, pCtx->gsHid.u64Base);
1826 AssertRC(rc);
1827 }
1828 else
1829 {
1830 pVCpu->hwaccm.s.vmx.pfnStartVM = VMXR0StartVM32;
1831 }
1832
1833 vmxR0UpdateExceptionBitmap(pVM, pVCpu, pCtx);
1834
1835 /* Store all guest MSRs in the VM-Entry load area, so they will be loaded during the world switch. */
1836 PVMXMSR pMsr = (PVMXMSR)pVCpu->hwaccm.s.vmx.pGuestMSR;
1837 unsigned idxMsr = 0;
1838
1839 uint32_t ulEdx;
1840 uint32_t ulTemp;
1841 CPUMGetGuestCpuId(pVCpu, 0x80000001, &ulTemp, &ulTemp, &ulTemp, &ulEdx);
1842 /* EFER MSR present? */
1843 if (ulEdx & (X86_CPUID_AMD_FEATURE_EDX_NX|X86_CPUID_AMD_FEATURE_EDX_LONG_MODE))
1844 {
1845 pMsr->u32IndexMSR = MSR_K6_EFER;
1846 pMsr->u32Reserved = 0;
1847 pMsr->u64Value = pCtx->msrEFER;
1848 /* VT-x will complain if only MSR_K6_EFER_LME is set. */
1849 if (!CPUMIsGuestInLongModeEx(pCtx))
1850 pMsr->u64Value &= ~(MSR_K6_EFER_LMA|MSR_K6_EFER_LME);
1851 pMsr++; idxMsr++;
1852
1853 if (ulEdx & X86_CPUID_AMD_FEATURE_EDX_LONG_MODE)
1854 {
1855 pMsr->u32IndexMSR = MSR_K8_LSTAR;
1856 pMsr->u32Reserved = 0;
1857 pMsr->u64Value = pCtx->msrLSTAR; /* 64 bits mode syscall rip */
1858 pMsr++; idxMsr++;
1859 pMsr->u32IndexMSR = MSR_K6_STAR;
1860 pMsr->u32Reserved = 0;
1861 pMsr->u64Value = pCtx->msrSTAR; /* legacy syscall eip, cs & ss */
1862 pMsr++; idxMsr++;
1863 pMsr->u32IndexMSR = MSR_K8_SF_MASK;
1864 pMsr->u32Reserved = 0;
1865 pMsr->u64Value = pCtx->msrSFMASK; /* syscall flag mask */
1866 pMsr++; idxMsr++;
1867 pMsr->u32IndexMSR = MSR_K8_KERNEL_GS_BASE;
1868 pMsr->u32Reserved = 0;
1869 pMsr->u64Value = pCtx->msrKERNELGSBASE; /* swapgs exchange value */
1870 pMsr++; idxMsr++;
1871 }
1872 }
1873
1874 if ( (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_MSR_BITMAPS)
1875 && (ulEdx & X86_CPUID_AMD_FEATURE_EDX_LONG_MODE))
1876 {
1877 /* Allow the guest to directly modify these MSRs; they are restored and saved automatically. */
1878 vmxR0SetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
1879 vmxR0SetMSRPermission(pVCpu, MSR_K6_STAR, true, true);
1880 vmxR0SetMSRPermission(pVCpu, MSR_K8_SF_MASK, true, true);
1881 vmxR0SetMSRPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, true, true);
1882 vmxR0SetMSRPermission(pVCpu, MSR_K8_GS_BASE, true, true);
1883 vmxR0SetMSRPermission(pVCpu, MSR_K8_FS_BASE, true, true);
1884 }
1885
1886 rc = VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_MSR_LOAD_COUNT, idxMsr);
1887 AssertRC(rc);
1888
1889 rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXIT_MSR_STORE_COUNT, idxMsr);
1890 AssertRC(rc);
1891
1892 /* Done. */
1893 pVCpu->hwaccm.s.fContextUseFlags &= ~HWACCM_CHANGED_ALL_GUEST;
1894
1895 return rc;
1896}
1897
1898/**
1899 * Syncs back the guest state
1900 *
1901 * @returns VBox status code.
1902 * @param pVM The VM to operate on.
1903 * @param pVCpu The VMCPU to operate on.
1904 * @param pCtx Guest context
1905 */
1906DECLINLINE(int) VMXR0SaveGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1907{
1908 RTGCUINTREG val, valShadow;
1909 RTGCUINTPTR uInterruptState;
1910 int rc;
1911
1912 /* Let's first sync back eip, esp, and eflags. */
1913 rc = VMXReadCachedVMCS(VMX_VMCS64_GUEST_RIP, &val);
1914 AssertRC(rc);
1915 pCtx->rip = val;
1916 rc = VMXReadCachedVMCS(VMX_VMCS64_GUEST_RSP, &val);
1917 AssertRC(rc);
1918 pCtx->rsp = val;
1919 rc = VMXReadCachedVMCS(VMX_VMCS_GUEST_RFLAGS, &val);
1920 AssertRC(rc);
1921 pCtx->eflags.u32 = val;
1922
1923 /* Take care of instruction fusing (sti, mov ss) */
1924 rc |= VMXReadCachedVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &val);
1925 uInterruptState = val;
1926 if (uInterruptState != 0)
1927 {
1928 Assert(uInterruptState <= 2); /* only sti & mov ss */
1929 Log(("uInterruptState %x eip=%RGv\n", (uint32_t)uInterruptState, pCtx->rip));
1930 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip);
1931 }
1932 else
1933 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1934
1935 /* Control registers. */
1936 VMXReadCachedVMCS(VMX_VMCS_CTRL_CR0_READ_SHADOW, &valShadow);
1937 VMXReadCachedVMCS(VMX_VMCS64_GUEST_CR0, &val);
1938 val = (valShadow & pVCpu->hwaccm.s.vmx.cr0_mask) | (val & ~pVCpu->hwaccm.s.vmx.cr0_mask);
1939 CPUMSetGuestCR0(pVCpu, val);
1940
1941 VMXReadCachedVMCS(VMX_VMCS_CTRL_CR4_READ_SHADOW, &valShadow);
1942 VMXReadCachedVMCS(VMX_VMCS64_GUEST_CR4, &val);
1943 val = (valShadow & pVCpu->hwaccm.s.vmx.cr4_mask) | (val & ~pVCpu->hwaccm.s.vmx.cr4_mask);
1944 CPUMSetGuestCR4(pVCpu, val);
1945
1946 /* Note: no reason to sync back the CRx registers. They can't be changed by the guest. */
1947 /* Note: only in the nested paging case can CR3 & CR4 be changed by the guest. */
1948 if ( pVM->hwaccm.s.fNestedPaging
1949 && CPUMIsGuestInPagedProtectedModeEx(pCtx))
1950 {
1951 PVMCSCACHE pCache = &pVCpu->hwaccm.s.vmx.VMCSCache;
1952
1953 /* Can be updated behind our back in the nested paging case. */
1954 CPUMSetGuestCR2(pVCpu, pCache->cr2);
1955
1956 VMXReadCachedVMCS(VMX_VMCS64_GUEST_CR3, &val);
1957
1958 if (val != pCtx->cr3)
1959 {
1960 CPUMSetGuestCR3(pVCpu, val);
1961 PGMUpdateCR3(pVCpu, val);
1962 }
1963 /* Prefetch the four PDPT entries in PAE mode. */
1964 vmxR0PrefetchPAEPdptrs(pVM, pVCpu, pCtx);
1965 }
1966
1967 /* Sync back DR7 here. */
1968 VMXReadCachedVMCS(VMX_VMCS64_GUEST_DR7, &val);
1969 pCtx->dr[7] = val;
1970
1971 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1972 VMX_READ_SELREG(ES, es);
1973 VMX_READ_SELREG(SS, ss);
1974 VMX_READ_SELREG(CS, cs);
1975 VMX_READ_SELREG(DS, ds);
1976 VMX_READ_SELREG(FS, fs);
1977 VMX_READ_SELREG(GS, gs);
1978
1979 /*
1980 * System MSRs
1981 */
1982 VMXReadCachedVMCS(VMX_VMCS32_GUEST_SYSENTER_CS, &val);
1983 pCtx->SysEnter.cs = val;
1984 VMXReadCachedVMCS(VMX_VMCS64_GUEST_SYSENTER_EIP, &val);
1985 pCtx->SysEnter.eip = val;
1986 VMXReadCachedVMCS(VMX_VMCS64_GUEST_SYSENTER_ESP, &val);
1987 pCtx->SysEnter.esp = val;
1988
1989 /* Misc. registers; must sync everything otherwise we can get out of sync when jumping to ring 3. */
1990 VMX_READ_SELREG(LDTR, ldtr);
1991
1992 VMXReadCachedVMCS(VMX_VMCS32_GUEST_GDTR_LIMIT, &val);
1993 pCtx->gdtr.cbGdt = val;
1994 VMXReadCachedVMCS(VMX_VMCS64_GUEST_GDTR_BASE, &val);
1995 pCtx->gdtr.pGdt = val;
1996
1997 VMXReadCachedVMCS(VMX_VMCS32_GUEST_IDTR_LIMIT, &val);
1998 pCtx->idtr.cbIdt = val;
1999 VMXReadCachedVMCS(VMX_VMCS64_GUEST_IDTR_BASE, &val);
2000 pCtx->idtr.pIdt = val;
2001
2002#ifdef HWACCM_VMX_EMULATE_REALMODE
2003 /* Real mode emulation using v86 mode. */
2004 if (CPUMIsGuestInRealModeEx(pCtx))
2005 {
2006 /* Hide our emulation flags */
2007 pCtx->eflags.Bits.u1VM = 0;
2008
2009 /* Restore original IOPL setting as we always use 0. */
2010 pCtx->eflags.Bits.u2IOPL = pVCpu->hwaccm.s.vmx.RealMode.eflags.Bits.u2IOPL;
2011
2012 /* Force a TR resync every time in case we switch modes. */
2013 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_TR;
2014 }
2015 else
2016#endif /* HWACCM_VMX_EMULATE_REALMODE */
2017 {
2018 /* In real mode we have a fake TSS, so only sync it back when it's supposed to be valid. */
2019 VMX_READ_SELREG(TR, tr);
2020 }
2021
2022 uint32_t maxMsr = 0;
2023 rc = VMXReadVMCS32(VMX_VMCS_CTRL_EXIT_MSR_STORE_COUNT, &maxMsr);
2024 AssertRC(rc);
2025
2026 /* Save the possibly changed MSRs that we automatically restore and save during a world switch. */
2027 for (unsigned i = 0; i < maxMsr; i++)
2028 {
2029 PVMXMSR pMsr = (PVMXMSR)pVCpu->hwaccm.s.vmx.pGuestMSR;
2030 pMsr += i;
2031
2032 switch (pMsr->u32IndexMSR)
2033 {
2034 case MSR_K8_LSTAR:
2035 pCtx->msrLSTAR = pMsr->u64Value;
2036 break;
2037 case MSR_K6_STAR:
2038 pCtx->msrSTAR = pMsr->u64Value;
2039 break;
2040 case MSR_K8_SF_MASK:
2041 pCtx->msrSFMASK = pMsr->u64Value;
2042 break;
2043 case MSR_K8_KERNEL_GS_BASE:
2044 pCtx->msrKERNELGSBASE = pMsr->u64Value;
2045 break;
2046 case MSR_K6_EFER:
2047 /* EFER can't be changed without causing a VM-exit. */
2048// Assert(pCtx->msrEFER == pMsr->u64Value);
2049 break;
2050 default:
2051 AssertFailed();
2052 return VERR_INTERNAL_ERROR;
2053 }
2054 }
2055 return VINF_SUCCESS;
2056}
2057
2058/**
2059 * Dummy placeholder
2060 *
2061 * @param pVM The VM to operate on.
2062 * @param pVCpu The VMCPU to operate on.
2063 */
2064static void vmxR0SetupTLBDummy(PVM pVM, PVMCPU pVCpu)
2065{
2066 NOREF(pVM);
2067 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2068 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
2069 pVCpu->hwaccm.s.TlbShootdown.cPages = 0;
2070 return;
2071}
2072
2073/**
2074 * Setup the tagged TLB for EPT
2075 *
2076 * @returns VBox status code.
2077 * @param pVM The VM to operate on.
2078 * @param pVCpu The VMCPU to operate on.
2079 */
2080static void vmxR0SetupTLBEPT(PVM pVM, PVMCPU pVCpu)
2081{
2082 PHWACCM_CPUINFO pCpu;
2083
2084 Assert(pVM->hwaccm.s.fNestedPaging);
2085 Assert(!pVM->hwaccm.s.vmx.fVPID);
2086
2087 /* Deal with tagged TLBs if VPID or EPT is supported. */
2088 pCpu = HWACCMR0GetCurrentCpu();
2089 /* Force a TLB flush for the first world switch if the current cpu differs from the one we ran on last. */
2090 /* Note that this can happen both for start and resume due to long jumps back to ring 3. */
2091 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
2092 /* if the tlb flush count has changed, another VM has flushed the TLB of this cpu, so we can't use our current ASID anymore. */
2093 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
2094 {
2095 /* Force a TLB flush on VM entry. */
2096 pVCpu->hwaccm.s.fForceTLBFlush = true;
2097 }
2098 else
2099 Assert(!pCpu->fFlushTLB);
2100
2101 /* Check for tlb shootdown flushes. */
2102 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2103 pVCpu->hwaccm.s.fForceTLBFlush = true;
2104
2105 pVCpu->hwaccm.s.idLastCpu = pCpu->idCpu;
2106 pCpu->fFlushTLB = false;
2107
2108 if (pVCpu->hwaccm.s.fForceTLBFlush)
2109 {
2110 vmxR0FlushEPT(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushContext, 0);
2111 }
2112 else
2113 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
2114 {
2115 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
2116 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTlbShootdown);
2117
2118 for (unsigned i=0;i<pVCpu->hwaccm.s.TlbShootdown.cPages;i++)
2119 {
2120 /* aTlbShootdownPages contains physical addresses in this case. */
2121 vmxR0FlushEPT(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushContext, pVCpu->hwaccm.s.TlbShootdown.aPages[i]);
2122 }
2123 }
2124 pVCpu->hwaccm.s.TlbShootdown.cPages= 0;
2125 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
2126
2127#ifdef VBOX_WITH_STATISTICS
2128 if (pVCpu->hwaccm.s.fForceTLBFlush)
2129 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBWorldSwitch);
2130 else
2131 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatNoFlushTLBWorldSwitch);
2132#endif
2133}
2134
2135#ifdef HWACCM_VTX_WITH_VPID
2136/**
2137 * Setup the tagged TLB for VPID
2138 *
2139 * @returns VBox status code.
2140 * @param pVM The VM to operate on.
2141 * @param pVCpu The VMCPU to operate on.
2142 */
2143static void vmxR0SetupTLBVPID(PVM pVM, PVMCPU pVCpu)
2144{
2145 PHWACCM_CPUINFO pCpu;
2146
2147 Assert(pVM->hwaccm.s.vmx.fVPID);
2148 Assert(!pVM->hwaccm.s.fNestedPaging);
2149
2150 /* Deal with tagged TLBs if VPID or EPT is supported. */
2151 pCpu = HWACCMR0GetCurrentCpu();
2152 /* Force a TLB flush for the first world switch if the current cpu differs from the one we ran on last. */
2153 /* Note that this can happen both for start and resume due to long jumps back to ring 3. */
2154 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
2155 /* if the tlb flush count has changed, another VM has flushed the TLB of this cpu, so we can't use our current ASID anymore. */
2156 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
2157 {
2158 /* Force a TLB flush on VM entry. */
2159 pVCpu->hwaccm.s.fForceTLBFlush = true;
2160 }
2161 else
2162 Assert(!pCpu->fFlushTLB);
2163
2164 pVCpu->hwaccm.s.idLastCpu = pCpu->idCpu;
2165
2166 /* Check for tlb shootdown flushes. */
2167 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2168 pVCpu->hwaccm.s.fForceTLBFlush = true;
2169
2170 /* Make sure we flush the TLB when required. Switch ASID to achieve the same thing, but without actually flushing the whole TLB (which is expensive). */
2171 if (pVCpu->hwaccm.s.fForceTLBFlush)
2172 {
2173 if ( ++pCpu->uCurrentASID >= pVM->hwaccm.s.uMaxASID
2174 || pCpu->fFlushTLB)
2175 {
2176 pCpu->fFlushTLB = false;
2177 pCpu->uCurrentASID = 1; /* start at 1; host uses 0 */
2178 pCpu->cTLBFlushes++;
2179 }
2180 else
2181 {
2182 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushASID);
2183 pVCpu->hwaccm.s.fForceTLBFlush = false;
2184 }
2185
2186 pVCpu->hwaccm.s.cTLBFlushes = pCpu->cTLBFlushes;
2187 pVCpu->hwaccm.s.uCurrentASID = pCpu->uCurrentASID;
2188 }
2189 else
2190 {
2191 Assert(!pCpu->fFlushTLB);
2192 Assert(pVCpu->hwaccm.s.uCurrentASID && pCpu->uCurrentASID);
2193
2194 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
2195 {
2196 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
2197 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTlbShootdown);
2198 for (unsigned i=0;i<pVCpu->hwaccm.s.TlbShootdown.cPages;i++)
2199 vmxR0FlushVPID(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushContext, pVCpu->hwaccm.s.TlbShootdown.aPages[i]);
2200 }
2201 }
2202 pVCpu->hwaccm.s.TlbShootdown.cPages = 0;
2203 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
2204
2205 AssertMsg(pVCpu->hwaccm.s.cTLBFlushes == pCpu->cTLBFlushes, ("Flush count mismatch for cpu %d (%x vs %x)\n", pCpu->idCpu, pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
2206 AssertMsg(pCpu->uCurrentASID >= 1 && pCpu->uCurrentASID < pVM->hwaccm.s.uMaxASID, ("cpu%d uCurrentASID = %x\n", pCpu->idCpu, pCpu->uCurrentASID));
2207 AssertMsg(pVCpu->hwaccm.s.uCurrentASID >= 1 && pVCpu->hwaccm.s.uCurrentASID < pVM->hwaccm.s.uMaxASID, ("cpu%d VM uCurrentASID = %x\n", pCpu->idCpu, pVCpu->hwaccm.s.uCurrentASID));
2208
2209 int rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_VPID, pVCpu->hwaccm.s.uCurrentASID);
2210 AssertRC(rc);
2211
2212 if (pVCpu->hwaccm.s.fForceTLBFlush)
2213 vmxR0FlushVPID(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushContext, 0);
2214
2215#ifdef VBOX_WITH_STATISTICS
2216 if (pVCpu->hwaccm.s.fForceTLBFlush)
2217 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBWorldSwitch);
2218 else
2219 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatNoFlushTLBWorldSwitch);
2220#endif
2221}
2222#endif /* HWACCM_VTX_WITH_VPID */
2223
2224/**
2225 * Runs guest code in a VT-x VM.
2226 *
2227 * @returns VBox status code.
2228 * @param pVM The VM to operate on.
2229 * @param pVCpu The VMCPU to operate on.
2230 * @param pCtx Guest context
2231 */
2232VMMR0DECL(int) VMXR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2233{
2234 int rc = VINF_SUCCESS;
2235 RTGCUINTREG val;
2236 RTGCUINTREG exitReason = VMX_EXIT_INVALID;
2237 RTGCUINTREG instrError, cbInstr;
2238 RTGCUINTPTR exitQualification = 0;
2239 RTGCUINTPTR intInfo = 0; /* shut up buggy gcc 4 */
2240 RTGCUINTPTR errCode, instrInfo;
2241 bool fSetupTPRCaching = false;
2242 uint8_t u8LastTPR = 0;
2243 PHWACCM_CPUINFO pCpu = 0;
2244 RTCCUINTREG uOldEFlags = ~(RTCCUINTREG)0;
2245 unsigned cResume = 0;
2246#ifdef VBOX_STRICT
2247 RTCPUID idCpuCheck;
2248 bool fWasInLongMode = false;
2249#endif
2250#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
2251 uint64_t u64LastTime = RTTimeMilliTS();
2252#endif
2253#ifdef VBOX_WITH_STATISTICS
2254 bool fStatEntryStarted = true;
2255 bool fStatExit2Started = false;
2256#endif
2257
2258 Assert(!(pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC) || (pVCpu->hwaccm.s.vmx.pVAPIC && pVM->hwaccm.s.vmx.pAPIC));
2259
2260 /* Check if we need to use TPR shadowing. */
2261 if ( CPUMIsGuestInLongModeEx(pCtx)
2262 || ( (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
2263 && pVM->hwaccm.s.fHasIoApic)
2264 )
2265 {
2266 fSetupTPRCaching = true;
2267 }
2268
2269 Log2(("\nE"));
2270
2271 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatEntry, x);
2272
2273#ifdef VBOX_STRICT
2274 {
2275 RTCCUINTREG val;
2276
2277 rc = VMXReadVMCS(VMX_VMCS_CTRL_PIN_EXEC_CONTROLS, &val);
2278 AssertRC(rc);
2279 Log2(("VMX_VMCS_CTRL_PIN_EXEC_CONTROLS = %08x\n", val));
2280
2281 /* allowed zero */
2282 if ((val & pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.disallowed0)
2283 Log(("Invalid VMX_VMCS_CTRL_PIN_EXEC_CONTROLS: zero\n"));
2284
2285 /* allowed one */
2286 if ((val & ~pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.allowed1) != 0)
2287 Log(("Invalid VMX_VMCS_CTRL_PIN_EXEC_CONTROLS: one\n"));
2288
2289 rc = VMXReadVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, &val);
2290 AssertRC(rc);
2291 Log2(("VMX_VMCS_CTRL_PROC_EXEC_CONTROLS = %08x\n", val));
2292
2293 /* Must be set according to the MSR, but can be cleared in case of EPT. */
2294 if (pVM->hwaccm.s.fNestedPaging)
2295 val |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_INVLPG_EXIT
2296 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
2297 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT;
2298
2299 /* allowed zero */
2300 if ((val & pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.disallowed0)
2301 Log(("Invalid VMX_VMCS_CTRL_PROC_EXEC_CONTROLS: zero\n"));
2302
2303 /* allowed one */
2304 if ((val & ~pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1) != 0)
2305 Log(("Invalid VMX_VMCS_CTRL_PROC_EXEC_CONTROLS: one\n"));
2306
2307 rc = VMXReadVMCS(VMX_VMCS_CTRL_ENTRY_CONTROLS, &val);
2308 AssertRC(rc);
2309 Log2(("VMX_VMCS_CTRL_ENTRY_CONTROLS = %08x\n", val));
2310
2311 /* allowed zero */
2312 if ((val & pVM->hwaccm.s.vmx.msr.vmx_entry.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_entry.n.disallowed0)
2313 Log(("Invalid VMX_VMCS_CTRL_ENTRY_CONTROLS: zero\n"));
2314
2315 /* allowed one */
2316 if ((val & ~pVM->hwaccm.s.vmx.msr.vmx_entry.n.allowed1) != 0)
2317 Log(("Invalid VMX_VMCS_CTRL_ENTRY_CONTROLS: one\n"));
2318
2319 rc = VMXReadVMCS(VMX_VMCS_CTRL_EXIT_CONTROLS, &val);
2320 AssertRC(rc);
2321 Log2(("VMX_VMCS_CTRL_EXIT_CONTROLS = %08x\n", val));
2322
2323 /* allowed zero */
2324 if ((val & pVM->hwaccm.s.vmx.msr.vmx_exit.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_exit.n.disallowed0)
2325 Log(("Invalid VMX_VMCS_CTRL_EXIT_CONTROLS: zero\n"));
2326
2327 /* allowed one */
2328 if ((val & ~pVM->hwaccm.s.vmx.msr.vmx_exit.n.allowed1) != 0)
2329 Log(("Invalid VMX_VMCS_CTRL_EXIT_CONTROLS: one\n"));
2330 }
2331 fWasInLongMode = CPUMIsGuestInLongMode(pVCpu);
2332#endif
2333
2334#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2335 pVCpu->hwaccm.s.vmx.VMCSCache.u64TimeEntry = RTTimeNanoTS();
2336#endif
2337
2338 /* We can jump to this point to resume execution after determining that a VM-exit is innocent.
2339 */
2340ResumeExecution:
2341 STAM_STATS({
2342 if (fStatExit2Started) { STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2, y); fStatExit2Started = false; }
2343 if (!fStatEntryStarted) { STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatEntry, x); fStatEntryStarted = true; }
2344 });
2345 AssertMsg(pVCpu->hwaccm.s.idEnteredCpu == RTMpCpuId(),
2346 ("Expected %d, I'm %d; cResume=%d exitReason=%RGv exitQualification=%RGv\n",
2347 (int)pVCpu->hwaccm.s.idEnteredCpu, (int)RTMpCpuId(), cResume, exitReason, exitQualification));
2348 Assert(!HWACCMR0SuspendPending());
2349 /* Not allowed to switch modes without reloading the host state (32->64 switcher)!! */
2350 Assert(fWasInLongMode == CPUMIsGuestInLongMode(pVCpu));
2351
2352 /* Safety precaution; looping for too long here can have a very bad effect on the host */
2353 if (RT_UNLIKELY(++cResume > pVM->hwaccm.s.cMaxResumeLoops))
2354 {
2355 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMaxResume);
2356 rc = VINF_EM_RAW_INTERRUPT;
2357 goto end;
2358 }
2359
2360 /* Check for irq inhibition due to instruction fusing (sti, mov ss). */
2361 if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2362 {
2363 Log(("VM_FF_INHIBIT_INTERRUPTS at %RGv successor %RGv\n", (RTGCPTR)pCtx->rip, EMGetInhibitInterruptsPC(pVCpu)));
2364 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2365 {
2366 /* Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here.
2367 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
2368 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
2369 * break the guest. Sounds very unlikely, but such timing sensitive problems are not as rare as you might think.
2370 */
2371 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2372 /* Irq inhibition is no longer active; clear the corresponding VMX state. */
2373 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, 0);
2374 AssertRC(rc);
2375 }
2376 }
2377 else
2378 {
2379 /* Irq inhibition is no longer active; clear the corresponding VMX state. */
2380 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, 0);
2381 AssertRC(rc);
2382 }
2383
2384#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
2385 if (RT_UNLIKELY(cResume & 0xf) == 0)
2386 {
2387 uint64_t u64CurTime = RTTimeMilliTS();
2388
2389 if (RT_UNLIKELY(u64CurTime > u64LastTime))
2390 {
2391 u64LastTime = u64CurTime;
2392 TMTimerPollVoid(pVM, pVCpu);
2393 }
2394 }
2395#endif
2396
2397 /* Check for pending actions that force us to go back to ring 3. */
2398#ifdef DEBUG
2399 /* Intercept X86_XCPT_DB if stepping is enabled */
2400 if (!DBGFIsStepping(pVCpu))
2401#endif
2402 {
2403 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK)
2404 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HWACCM_TO_R3_MASK))
2405 {
2406 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2407 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatSwitchToR3);
2408 rc = RT_UNLIKELY(VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2409 goto end;
2410 }
2411 }
2412
2413 /* Pending request packets might contain actions that need immediate attention, such as pending hardware interrupts. */
2414 if ( VM_FF_ISPENDING(pVM, VM_FF_REQUEST)
2415 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_REQUEST))
2416 {
2417 rc = VINF_EM_PENDING_REQUEST;
2418 goto end;
2419 }
2420
2421#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2422 /*
2423 * Exit to ring-3 preemption/work is pending.
2424 *
2425 * Interrupts are disabled before the call to make sure we don't miss any interrupt
2426 * that would flag preemption (IPI, timer tick, ++). (Would've been nice to do this
2427 * further down, but VMXR0CheckPendingInterrupt makes that impossible.)
2428 *
2429 * Note! Interrupts must be disabled done *before* we check for TLB flushes; TLB
2430 * shootdowns rely on this.
2431 */
2432 uOldEFlags = ASMIntDisableFlags();
2433 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2434 {
2435 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPreemptPending);
2436 rc = VINF_EM_RAW_INTERRUPT;
2437 goto end;
2438 }
2439 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2440#endif
2441
2442 /* When external interrupts are pending, we should exit the VM when IF is set. */
2443 /* Note! *After* VM_FF_INHIBIT_INTERRUPTS check!!! */
2444 rc = VMXR0CheckPendingInterrupt(pVM, pVCpu, pCtx);
2445 if (RT_FAILURE(rc))
2446 goto end;
2447
2448 /** @todo check timers?? */
2449
2450 /* TPR caching using CR8 is only available in 64 bits mode */
2451 /* Note the 32 bits exception for AMD (X86_CPUID_AMD_FEATURE_ECX_CR8L), but that appears missing in Intel CPUs */
2452 /* Note: we can't do this in LoadGuestState as PDMApicGetTPR can jump back to ring 3 (lock)!!!!! (no longer true) */
2453 /**
2454 * @todo query and update the TPR only when it could have been changed (mmio access & wrmsr (x2apic))
2455 */
2456 if (fSetupTPRCaching)
2457 {
2458 /* TPR caching in CR8 */
2459 bool fPending;
2460
2461 int rc = PDMApicGetTPR(pVCpu, &u8LastTPR, &fPending);
2462 AssertRC(rc);
2463 /* The TPR can be found at offset 0x80 in the APIC mmio page. */
2464 pVCpu->hwaccm.s.vmx.pVAPIC[0x80] = u8LastTPR;
2465
2466 /* Two options here:
2467 * - external interrupt pending, but masked by the TPR value.
2468 * -> a CR8 update that lower the current TPR value should cause an exit
2469 * - no pending interrupts
2470 * -> We don't need to be explicitely notified. There are enough world switches for detecting pending interrupts.
2471 */
2472 rc = VMXWriteVMCS(VMX_VMCS_CTRL_TPR_THRESHOLD, (fPending) ? (u8LastTPR >> 4) : 0); /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
2473 AssertRC(rc);
2474 }
2475
2476#if defined(HWACCM_VTX_WITH_EPT) && defined(LOG_ENABLED)
2477 if ( pVM->hwaccm.s.fNestedPaging
2478# ifdef HWACCM_VTX_WITH_VPID
2479 || pVM->hwaccm.s.vmx.fVPID
2480# endif /* HWACCM_VTX_WITH_VPID */
2481 )
2482 {
2483 pCpu = HWACCMR0GetCurrentCpu();
2484 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
2485 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
2486 {
2487 if (pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu)
2488 Log(("Force TLB flush due to rescheduling to a different cpu (%d vs %d)\n", pVCpu->hwaccm.s.idLastCpu, pCpu->idCpu));
2489 else
2490 Log(("Force TLB flush due to changed TLB flush count (%x vs %x)\n", pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
2491 }
2492 if (pCpu->fFlushTLB)
2493 Log(("Force TLB flush: first time cpu %d is used -> flush\n", pCpu->idCpu));
2494 else
2495 if (pVCpu->hwaccm.s.fForceTLBFlush)
2496 LogFlow(("Manual TLB flush\n"));
2497 }
2498#endif
2499#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
2500 PGMDynMapFlushAutoSet(pVCpu);
2501#endif
2502
2503 /*
2504 * NOTE: DO NOT DO ANYTHING AFTER THIS POINT THAT MIGHT JUMP BACK TO RING 3!
2505 * (until the actual world switch)
2506 */
2507#ifdef VBOX_STRICT
2508 idCpuCheck = RTMpCpuId();
2509#endif
2510#ifdef LOG_ENABLED
2511 VMMR0LogFlushDisable(pVCpu);
2512#endif
2513 /* Save the host state first. */
2514 rc = VMXR0SaveHostState(pVM, pVCpu);
2515 if (RT_UNLIKELY(rc != VINF_SUCCESS))
2516 {
2517 VMMR0LogFlushEnable(pVCpu);
2518 goto end;
2519 }
2520 /* Load the guest state */
2521 rc = VMXR0LoadGuestState(pVM, pVCpu, pCtx);
2522 if (RT_UNLIKELY(rc != VINF_SUCCESS))
2523 {
2524 VMMR0LogFlushEnable(pVCpu);
2525 goto end;
2526 }
2527
2528#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2529 /* Disable interrupts to make sure a poke will interrupt execution.
2530 * This must be done *before* we check for TLB flushes; TLB shootdowns rely on this.
2531 */
2532 uOldEFlags = ASMIntDisableFlags();
2533 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2534#endif
2535
2536 /* Deal with tagged TLB setup and invalidation. */
2537 pVM->hwaccm.s.vmx.pfnSetupTaggedTLB(pVM, pVCpu);
2538
2539 /* Non-register state Guest Context */
2540 /** @todo change me according to cpu state */
2541 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_ACTIVITY_STATE, VMX_CMS_GUEST_ACTIVITY_ACTIVE);
2542 AssertRC(rc);
2543
2544 STAM_STATS({ STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatEntry, x); fStatEntryStarted = false; });
2545
2546 /* Manual save and restore:
2547 * - General purpose registers except RIP, RSP
2548 *
2549 * Trashed:
2550 * - CR2 (we don't care)
2551 * - LDTR (reset to 0)
2552 * - DRx (presumably not changed at all)
2553 * - DR7 (reset to 0x400)
2554 * - EFLAGS (reset to RT_BIT(1); not relevant)
2555 *
2556 */
2557
2558
2559 /* All done! Let's start VM execution. */
2560 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatInGC, z);
2561 Assert(idCpuCheck == RTMpCpuId());
2562
2563#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2564 pVCpu->hwaccm.s.vmx.VMCSCache.cResume = cResume;
2565 pVCpu->hwaccm.s.vmx.VMCSCache.u64TimeSwitch = RTTimeNanoTS();
2566#endif
2567
2568 TMNotifyStartOfExecution(pVCpu);
2569#ifdef VBOX_WITH_KERNEL_USING_XMM
2570 rc = hwaccmR0VMXStartVMWrapXMM(pVCpu->hwaccm.s.fResumeVM, pCtx, &pVCpu->hwaccm.s.vmx.VMCSCache, pVM, pVCpu, pVCpu->hwaccm.s.vmx.pfnStartVM);
2571#else
2572 rc = pVCpu->hwaccm.s.vmx.pfnStartVM(pVCpu->hwaccm.s.fResumeVM, pCtx, &pVCpu->hwaccm.s.vmx.VMCSCache, pVM, pVCpu);
2573#endif
2574 TMNotifyEndOfExecution(pVCpu);
2575 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
2576 Assert(!(ASMGetFlags() & X86_EFL_IF));
2577 ASMSetFlags(uOldEFlags);
2578#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2579 uOldEFlags = ~(RTCCUINTREG)0;
2580#endif
2581
2582 AssertMsg(!pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries, ("pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries=%d\n", pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries));
2583
2584 /* In case we execute a goto ResumeExecution later on. */
2585 pVCpu->hwaccm.s.fResumeVM = true;
2586 pVCpu->hwaccm.s.fForceTLBFlush = false;
2587
2588 /*
2589 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2590 * IMPORTANT: WE CAN'T DO ANY LOGGING OR OPERATIONS THAT CAN DO A LONGJMP BACK TO RING 3 *BEFORE* WE'VE SYNCED BACK (MOST OF) THE GUEST STATE
2591 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2592 */
2593 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatInGC, z);
2594 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit1, v);
2595
2596 if (RT_UNLIKELY(rc != VINF_SUCCESS))
2597 {
2598 VMXR0ReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
2599 VMMR0LogFlushEnable(pVCpu);
2600 goto end;
2601 }
2602
2603 /* Success. Query the guest state and figure out what has happened. */
2604
2605 /* Investigate why there was a VM-exit. */
2606 rc = VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_REASON, &exitReason);
2607 STAM_COUNTER_INC(&pVCpu->hwaccm.s.paStatExitReasonR0[exitReason & MASK_EXITREASON_STAT]);
2608
2609 exitReason &= 0xffff; /* bit 0-15 contain the exit code. */
2610 rc |= VMXReadCachedVMCS(VMX_VMCS32_RO_VM_INSTR_ERROR, &instrError);
2611 rc |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &cbInstr);
2612 rc |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &intInfo);
2613 /* might not be valid; depends on VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID. */
2614 rc |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERRCODE, &errCode);
2615 rc |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INSTR_INFO, &instrInfo);
2616 rc |= VMXReadCachedVMCS(VMX_VMCS_RO_EXIT_QUALIFICATION, &exitQualification);
2617 AssertRC(rc);
2618
2619 /* Sync back the guest state */
2620 rc = VMXR0SaveGuestState(pVM, pVCpu, pCtx);
2621 AssertRC(rc);
2622
2623 /* Note! NOW IT'S SAFE FOR LOGGING! */
2624 VMMR0LogFlushEnable(pVCpu);
2625 Log2(("Raw exit reason %08x\n", exitReason));
2626
2627 /* Check if an injected event was interrupted prematurely. */
2628 rc = VMXReadCachedVMCS(VMX_VMCS32_RO_IDT_INFO, &val);
2629 AssertRC(rc);
2630 pVCpu->hwaccm.s.Event.intInfo = VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(val);
2631 if ( VMX_EXIT_INTERRUPTION_INFO_VALID(pVCpu->hwaccm.s.Event.intInfo)
2632 /* Ignore 'int xx' as they'll be restarted anyway. */
2633 && VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hwaccm.s.Event.intInfo) != VMX_EXIT_INTERRUPTION_INFO_TYPE_SW
2634 /* Ignore software exceptions (such as int3) as they'll reoccur when we restart the instruction anyway. */
2635 && VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hwaccm.s.Event.intInfo) != VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT)
2636 {
2637 Assert(!pVCpu->hwaccm.s.Event.fPending);
2638 pVCpu->hwaccm.s.Event.fPending = true;
2639 /* Error code present? */
2640 if (VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(pVCpu->hwaccm.s.Event.intInfo))
2641 {
2642 rc = VMXReadCachedVMCS(VMX_VMCS32_RO_IDT_ERRCODE, &val);
2643 AssertRC(rc);
2644 pVCpu->hwaccm.s.Event.errCode = val;
2645 Log(("Pending inject %RX64 at %RGv exit=%08x intInfo=%08x exitQualification=%RGv pending error=%RX64\n", pVCpu->hwaccm.s.Event.intInfo, (RTGCPTR)pCtx->rip, exitReason, intInfo, exitQualification, val));
2646 }
2647 else
2648 {
2649 Log(("Pending inject %RX64 at %RGv exit=%08x intInfo=%08x exitQualification=%RGv\n", pVCpu->hwaccm.s.Event.intInfo, (RTGCPTR)pCtx->rip, exitReason, intInfo, exitQualification));
2650 pVCpu->hwaccm.s.Event.errCode = 0;
2651 }
2652 }
2653#ifdef VBOX_STRICT
2654 else
2655 if ( VMX_EXIT_INTERRUPTION_INFO_VALID(pVCpu->hwaccm.s.Event.intInfo)
2656 /* Ignore software exceptions (such as int3) as they're reoccur when we restart the instruction anyway. */
2657 && VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hwaccm.s.Event.intInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT)
2658 {
2659 Log(("Ignore pending inject %RX64 at %RGv exit=%08x intInfo=%08x exitQualification=%RGv\n", pVCpu->hwaccm.s.Event.intInfo, (RTGCPTR)pCtx->rip, exitReason, intInfo, exitQualification));
2660 }
2661
2662 if (exitReason == VMX_EXIT_ERR_INVALID_GUEST_STATE)
2663 HWACCMDumpRegs(pVM, pVCpu, pCtx);
2664#endif
2665
2666 Log2(("E%d: New EIP=%RGv\n", exitReason, (RTGCPTR)pCtx->rip));
2667 Log2(("Exit reason %d, exitQualification %RGv\n", (uint32_t)exitReason, exitQualification));
2668 Log2(("instrInfo=%d instrError=%d instr length=%d\n", (uint32_t)instrInfo, (uint32_t)instrError, (uint32_t)cbInstr));
2669 Log2(("Interruption error code %d\n", (uint32_t)errCode));
2670 Log2(("IntInfo = %08x\n", (uint32_t)intInfo));
2671
2672 /* Sync back the TPR if it was changed. */
2673 if ( fSetupTPRCaching
2674 && u8LastTPR != pVCpu->hwaccm.s.vmx.pVAPIC[0x80])
2675 {
2676 rc = PDMApicSetTPR(pVCpu, pVCpu->hwaccm.s.vmx.pVAPIC[0x80]);
2677 AssertRC(rc);
2678 }
2679
2680 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit1, v);
2681 STAM_STATS({ STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2, y); fStatExit2Started = true; });
2682
2683 /* Some cases don't need a complete resync of the guest CPU state; handle them here. */
2684 switch (exitReason)
2685 {
2686 case VMX_EXIT_EXCEPTION: /* 0 Exception or non-maskable interrupt (NMI). */
2687 case VMX_EXIT_EXTERNAL_IRQ: /* 1 External interrupt. */
2688 {
2689 uint32_t vector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(intInfo);
2690
2691 if (!VMX_EXIT_INTERRUPTION_INFO_VALID(intInfo))
2692 {
2693 Assert(exitReason == VMX_EXIT_EXTERNAL_IRQ);
2694 /* External interrupt; leave to allow it to be dispatched again. */
2695 rc = VINF_EM_RAW_INTERRUPT;
2696 break;
2697 }
2698 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2699 switch (VMX_EXIT_INTERRUPTION_INFO_TYPE(intInfo))
2700 {
2701 case VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI: /* Non-maskable interrupt. */
2702 /* External interrupt; leave to allow it to be dispatched again. */
2703 rc = VINF_EM_RAW_INTERRUPT;
2704 break;
2705
2706 case VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT: /* External hardware interrupt. */
2707 AssertFailed(); /* can't come here; fails the first check. */
2708 break;
2709
2710 case VMX_EXIT_INTERRUPTION_INFO_TYPE_DBEXCPT: /* Unknown why we get this type for #DB */
2711 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT: /* Software exception. (#BP or #OF) */
2712 Assert(vector == 1 || vector == 3 || vector == 4);
2713 /* no break */
2714 case VMX_EXIT_INTERRUPTION_INFO_TYPE_HWEXCPT: /* Hardware exception. */
2715 Log2(("Hardware/software interrupt %d\n", vector));
2716 switch (vector)
2717 {
2718 case X86_XCPT_NM:
2719 {
2720 Log(("#NM fault at %RGv error code %x\n", (RTGCPTR)pCtx->rip, errCode));
2721
2722 /** @todo don't intercept #NM exceptions anymore when we've activated the guest FPU state. */
2723 /* If we sync the FPU/XMM state on-demand, then we can continue execution as if nothing has happened. */
2724 rc = CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
2725 if (rc == VINF_SUCCESS)
2726 {
2727 Assert(CPUMIsGuestFPUStateActive(pVCpu));
2728
2729 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowNM);
2730
2731 /* Continue execution. */
2732 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
2733
2734 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2735 goto ResumeExecution;
2736 }
2737
2738 Log(("Forward #NM fault to the guest\n"));
2739 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNM);
2740 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, 0);
2741 AssertRC(rc);
2742 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2743 goto ResumeExecution;
2744 }
2745
2746 case X86_XCPT_PF: /* Page fault */
2747 {
2748#ifdef DEBUG
2749 if (pVM->hwaccm.s.fNestedPaging)
2750 { /* A genuine pagefault.
2751 * Forward the trap to the guest by injecting the exception and resuming execution.
2752 */
2753 Log(("Guest page fault at %RGv cr2=%RGv error code %x rsp=%RGv\n", (RTGCPTR)pCtx->rip, exitQualification, errCode, (RTGCPTR)pCtx->rsp));
2754
2755 Assert(CPUMIsGuestInPagedProtectedModeEx(pCtx));
2756
2757 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
2758
2759 /* Now we must update CR2. */
2760 pCtx->cr2 = exitQualification;
2761 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2762 AssertRC(rc);
2763
2764 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2765 goto ResumeExecution;
2766 }
2767#endif
2768 Assert(!pVM->hwaccm.s.fNestedPaging);
2769
2770 Log2(("Page fault at %RGv error code %x\n", exitQualification, errCode));
2771 /* Exit qualification contains the linear address of the page fault. */
2772 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
2773 TRPMSetErrorCode(pVCpu, errCode);
2774 TRPMSetFaultAddress(pVCpu, exitQualification);
2775
2776 /* Shortcut for APIC TPR reads and writes. */
2777 if ( (exitQualification & 0xfff) == 0x080
2778 && !(errCode & X86_TRAP_PF_P) /* not present */
2779 && fSetupTPRCaching
2780 && (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC))
2781 {
2782 RTGCPHYS GCPhysApicBase, GCPhys;
2783 PDMApicGetBase(pVM, &GCPhysApicBase); /* @todo cache this */
2784 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2785
2786 rc = PGMGstGetPage(pVCpu, (RTGCPTR)exitQualification, NULL, &GCPhys);
2787 if ( rc == VINF_SUCCESS
2788 && GCPhys == GCPhysApicBase)
2789 {
2790 Log(("Enable VT-x virtual APIC access filtering\n"));
2791 rc = IOMMMIOMapMMIOHCPage(pVM, GCPhysApicBase, pVM->hwaccm.s.vmx.pAPICPhys, X86_PTE_RW | X86_PTE_P);
2792 AssertRC(rc);
2793 }
2794 }
2795
2796 /* Forward it to our trap handler first, in case our shadow pages are out of sync. */
2797 rc = PGMTrap0eHandler(pVCpu, errCode, CPUMCTX2CORE(pCtx), (RTGCPTR)exitQualification);
2798 Log2(("PGMTrap0eHandler %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, rc));
2799 if (rc == VINF_SUCCESS)
2800 { /* We've successfully synced our shadow pages, so let's just continue execution. */
2801 Log2(("Shadow page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, exitQualification ,errCode));
2802 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowPF);
2803
2804 TRPMResetTrap(pVCpu);
2805
2806 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2807 goto ResumeExecution;
2808 }
2809 else
2810 if (rc == VINF_EM_RAW_GUEST_TRAP)
2811 { /* A genuine pagefault.
2812 * Forward the trap to the guest by injecting the exception and resuming execution.
2813 */
2814 Log2(("Forward page fault to the guest\n"));
2815
2816 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
2817 /* The error code might have been changed. */
2818 errCode = TRPMGetErrorCode(pVCpu);
2819
2820 TRPMResetTrap(pVCpu);
2821
2822 /* Now we must update CR2. */
2823 pCtx->cr2 = exitQualification;
2824 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2825 AssertRC(rc);
2826
2827 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2828 goto ResumeExecution;
2829 }
2830#ifdef VBOX_STRICT
2831 if (rc != VINF_EM_RAW_EMULATE_INSTR && rc != VINF_EM_RAW_EMULATE_IO_BLOCK)
2832 Log2(("PGMTrap0eHandler failed with %d\n", rc));
2833#endif
2834 /* Need to go back to the recompiler to emulate the instruction. */
2835 TRPMResetTrap(pVCpu);
2836 break;
2837 }
2838
2839 case X86_XCPT_MF: /* Floating point exception. */
2840 {
2841 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestMF);
2842 if (!(pCtx->cr0 & X86_CR0_NE))
2843 {
2844 /* old style FPU error reporting needs some extra work. */
2845 /** @todo don't fall back to the recompiler, but do it manually. */
2846 rc = VINF_EM_RAW_EMULATE_INSTR;
2847 break;
2848 }
2849 Log(("Trap %x at %04X:%RGv\n", vector, pCtx->cs, (RTGCPTR)pCtx->rip));
2850 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2851 AssertRC(rc);
2852
2853 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2854 goto ResumeExecution;
2855 }
2856
2857 case X86_XCPT_DB: /* Debug exception. */
2858 {
2859 uint64_t uDR6;
2860
2861 /* DR6, DR7.GD and IA32_DEBUGCTL.LBR are not updated yet.
2862 *
2863 * Exit qualification bits:
2864 * 3:0 B0-B3 which breakpoint condition was met
2865 * 12:4 Reserved (0)
2866 * 13 BD - debug register access detected
2867 * 14 BS - single step execution or branch taken
2868 * 63:15 Reserved (0)
2869 */
2870 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDB);
2871
2872 /* Note that we don't support guest and host-initiated debugging at the same time. */
2873 Assert(DBGFIsStepping(pVCpu) || CPUMIsGuestInRealModeEx(pCtx) || CPUMIsHyperDebugStateActive(pVCpu));
2874
2875 uDR6 = X86_DR6_INIT_VAL;
2876 uDR6 |= (exitQualification & (X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3|X86_DR6_BD|X86_DR6_BS));
2877 rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), uDR6);
2878 if (rc == VINF_EM_RAW_GUEST_TRAP)
2879 {
2880 /** @todo this isn't working, but we'll never get here normally. */
2881
2882 /* Update DR6 here. */
2883 pCtx->dr[6] = uDR6;
2884
2885 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
2886 pCtx->dr[7] &= ~X86_DR7_GD;
2887
2888 /* Paranoia. */
2889 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
2890 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
2891 pCtx->dr[7] |= 0x400; /* must be one */
2892
2893 /* Resync DR7 */
2894 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, pCtx->dr[7]);
2895 AssertRC(rc);
2896
2897 Log(("Trap %x (debug) at %RGv exit qualification %RX64\n", vector, (RTGCPTR)pCtx->rip, exitQualification));
2898 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2899 AssertRC(rc);
2900
2901 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2902 goto ResumeExecution;
2903 }
2904 /* Return to ring 3 to deal with the debug exit code. */
2905 Log(("Debugger hardware BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs, pCtx->rip, rc));
2906 break;
2907 }
2908
2909 case X86_XCPT_BP: /* Breakpoint. */
2910 {
2911 rc = DBGFRZTrap03Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2912 if (rc == VINF_EM_RAW_GUEST_TRAP)
2913 {
2914 Log(("Guest #BP at %04x:%RGv\n", pCtx->cs, pCtx->rip));
2915 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2916 AssertRC(rc);
2917 goto ResumeExecution;
2918 }
2919 if (rc == VINF_SUCCESS)
2920 goto ResumeExecution;
2921 Log(("Debugger BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs, pCtx->rip, rc));
2922 break;
2923 }
2924
2925 case X86_XCPT_GP: /* General protection failure exception.*/
2926 {
2927 uint32_t cbOp;
2928 uint32_t cbSize;
2929 PDISCPUSTATE pDis = &pVCpu->hwaccm.s.DisState;
2930
2931 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestGP);
2932#ifdef VBOX_STRICT
2933 if (!CPUMIsGuestInRealModeEx(pCtx))
2934 {
2935 Log(("Trap %x at %04X:%RGv errorCode=%x\n", vector, pCtx->cs, (RTGCPTR)pCtx->rip, errCode));
2936 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2937 AssertRC(rc);
2938 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2939 goto ResumeExecution;
2940 }
2941#endif
2942 Assert(CPUMIsGuestInRealModeEx(pCtx));
2943
2944 LogFlow(("Real mode X86_XCPT_GP instruction emulation at %RGv\n", (RTGCPTR)pCtx->rip));
2945
2946 rc = EMInterpretDisasOne(pVM, pVCpu, CPUMCTX2CORE(pCtx), pDis, &cbOp);
2947 if (RT_SUCCESS(rc))
2948 {
2949 bool fUpdateRIP = true;
2950
2951 Assert(cbOp == pDis->opsize);
2952 switch (pDis->pCurInstr->opcode)
2953 {
2954 case OP_CLI:
2955 pCtx->eflags.Bits.u1IF = 0;
2956 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCli);
2957 break;
2958
2959 case OP_STI:
2960 pCtx->eflags.Bits.u1IF = 1;
2961 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip + pDis->opsize);
2962 Assert(VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
2963 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
2964 AssertRC(rc);
2965 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitSti);
2966 break;
2967
2968 case OP_HLT:
2969 fUpdateRIP = false;
2970 rc = VINF_EM_HALT;
2971 pCtx->rip += pDis->opsize;
2972 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitHlt);
2973 break;
2974
2975 case OP_POPF:
2976 {
2977 RTGCPTR GCPtrStack;
2978 uint32_t cbParm;
2979 uint32_t uMask;
2980 X86EFLAGS eflags;
2981
2982 if (pDis->prefix & PREFIX_OPSIZE)
2983 {
2984 cbParm = 4;
2985 uMask = 0xffffffff;
2986 }
2987 else
2988 {
2989 cbParm = 2;
2990 uMask = 0xffff;
2991 }
2992
2993 rc = SELMToFlatEx(pVM, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), pCtx->esp & uMask, 0, &GCPtrStack);
2994 if (RT_FAILURE(rc))
2995 {
2996 rc = VERR_EM_INTERPRETER;
2997 break;
2998 }
2999 eflags.u = 0;
3000 rc = PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &eflags.u, cbParm);
3001 if (RT_FAILURE(rc))
3002 {
3003 rc = VERR_EM_INTERPRETER;
3004 break;
3005 }
3006 LogFlow(("POPF %x -> %RGv mask=%x\n", eflags.u, pCtx->rsp, uMask));
3007 pCtx->eflags.u = (pCtx->eflags.u & ~(X86_EFL_POPF_BITS & uMask)) | (eflags.u & X86_EFL_POPF_BITS & uMask);
3008 /* RF cleared when popped in real mode; see pushf description in AMD manual. */
3009 pCtx->eflags.Bits.u1RF = 0;
3010 pCtx->esp += cbParm;
3011 pCtx->esp &= uMask;
3012
3013 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPopf);
3014 break;
3015 }
3016
3017 case OP_PUSHF:
3018 {
3019 RTGCPTR GCPtrStack;
3020 uint32_t cbParm;
3021 uint32_t uMask;
3022 X86EFLAGS eflags;
3023
3024 if (pDis->prefix & PREFIX_OPSIZE)
3025 {
3026 cbParm = 4;
3027 uMask = 0xffffffff;
3028 }
3029 else
3030 {
3031 cbParm = 2;
3032 uMask = 0xffff;
3033 }
3034
3035 rc = SELMToFlatEx(pVM, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), (pCtx->esp - cbParm) & uMask, 0, &GCPtrStack);
3036 if (RT_FAILURE(rc))
3037 {
3038 rc = VERR_EM_INTERPRETER;
3039 break;
3040 }
3041 eflags = pCtx->eflags;
3042 /* RF & VM cleared when pushed in real mode; see pushf description in AMD manual. */
3043 eflags.Bits.u1RF = 0;
3044 eflags.Bits.u1VM = 0;
3045
3046 rc = PGMPhysWrite(pVM, (RTGCPHYS)GCPtrStack, &eflags.u, cbParm);
3047 if (RT_FAILURE(rc))
3048 {
3049 rc = VERR_EM_INTERPRETER;
3050 break;
3051 }
3052 LogFlow(("PUSHF %x -> %RGv\n", eflags.u, GCPtrStack));
3053 pCtx->esp -= cbParm;
3054 pCtx->esp &= uMask;
3055 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPushf);
3056 break;
3057 }
3058
3059 case OP_IRET:
3060 {
3061 RTGCPTR GCPtrStack;
3062 uint32_t uMask = 0xffff;
3063 uint16_t aIretFrame[3];
3064
3065 if (pDis->prefix & (PREFIX_OPSIZE | PREFIX_ADDRSIZE))
3066 {
3067 rc = VERR_EM_INTERPRETER;
3068 break;
3069 }
3070
3071 rc = SELMToFlatEx(pVM, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), pCtx->esp & uMask, 0, &GCPtrStack);
3072 if (RT_FAILURE(rc))
3073 {
3074 rc = VERR_EM_INTERPRETER;
3075 break;
3076 }
3077 rc = PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &aIretFrame[0], sizeof(aIretFrame));
3078 if (RT_FAILURE(rc))
3079 {
3080 rc = VERR_EM_INTERPRETER;
3081 break;
3082 }
3083 pCtx->ip = aIretFrame[0];
3084 pCtx->cs = aIretFrame[1];
3085 pCtx->csHid.u64Base = pCtx->cs << 4;
3086 pCtx->eflags.u = (pCtx->eflags.u & ~(X86_EFL_POPF_BITS & uMask)) | (aIretFrame[2] & X86_EFL_POPF_BITS & uMask);
3087 pCtx->sp += sizeof(aIretFrame);
3088
3089 LogFlow(("iret to %04x:%x\n", pCtx->cs, pCtx->ip));
3090 fUpdateRIP = false;
3091 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIret);
3092 break;
3093 }
3094
3095 case OP_INT:
3096 {
3097 RTGCUINTPTR intInfo;
3098
3099 LogFlow(("Realmode: INT %x\n", pDis->param1.parval & 0xff));
3100 intInfo = pDis->param1.parval & 0xff;
3101 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3102 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3103
3104 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, intInfo, cbOp, 0);
3105 AssertRC(rc);
3106 fUpdateRIP = false;
3107 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInt);
3108 break;
3109 }
3110
3111 case OP_INTO:
3112 {
3113 if (pCtx->eflags.Bits.u1OF)
3114 {
3115 RTGCUINTPTR intInfo;
3116
3117 LogFlow(("Realmode: INTO\n"));
3118 intInfo = X86_XCPT_OF;
3119 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3120 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3121
3122 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, intInfo, cbOp, 0);
3123 AssertRC(rc);
3124 fUpdateRIP = false;
3125 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInt);
3126 }
3127 break;
3128 }
3129
3130 case OP_INT3:
3131 {
3132 RTGCUINTPTR intInfo;
3133
3134 LogFlow(("Realmode: INT 3\n"));
3135 intInfo = 3;
3136 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3137 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3138
3139 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, intInfo, cbOp, 0);
3140 AssertRC(rc);
3141 fUpdateRIP = false;
3142 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInt);
3143 break;
3144 }
3145
3146 default:
3147 rc = EMInterpretInstructionCPU(pVM, pVCpu, pDis, CPUMCTX2CORE(pCtx), 0, &cbSize);
3148 break;
3149 }
3150
3151 if (rc == VINF_SUCCESS)
3152 {
3153 if (fUpdateRIP)
3154 pCtx->rip += cbOp; /* Move on to the next instruction. */
3155
3156 /* lidt, lgdt can end up here. In the future crx changes as well. Just reload the whole context to be done with it. */
3157 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_ALL;
3158
3159 /* Only resume if successful. */
3160 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3161 goto ResumeExecution;
3162 }
3163 }
3164 else
3165 rc = VERR_EM_INTERPRETER;
3166
3167 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_EM_HALT, ("Unexpected rc=%Rrc\n", rc));
3168 break;
3169 }
3170
3171#ifdef VBOX_STRICT
3172 case X86_XCPT_DE: /* Divide error. */
3173 case X86_XCPT_UD: /* Unknown opcode exception. */
3174 case X86_XCPT_SS: /* Stack segment exception. */
3175 case X86_XCPT_NP: /* Segment not present exception. */
3176 {
3177 switch(vector)
3178 {
3179 case X86_XCPT_DE:
3180 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDE);
3181 break;
3182 case X86_XCPT_UD:
3183 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestUD);
3184 break;
3185 case X86_XCPT_SS:
3186 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestSS);
3187 break;
3188 case X86_XCPT_NP:
3189 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNP);
3190 break;
3191 }
3192
3193 Log(("Trap %x at %04X:%RGv\n", vector, pCtx->cs, (RTGCPTR)pCtx->rip));
3194 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3195 AssertRC(rc);
3196
3197 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3198 goto ResumeExecution;
3199 }
3200#endif
3201 default:
3202#ifdef HWACCM_VMX_EMULATE_REALMODE
3203 if (CPUMIsGuestInRealModeEx(pCtx))
3204 {
3205 Log(("Real Mode Trap %x at %04x:%04X error code %x\n", vector, pCtx->cs, pCtx->eip, errCode));
3206 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3207 AssertRC(rc);
3208
3209 /* Go back to ring 3 in case of a triple fault. */
3210 if ( vector == X86_XCPT_DF
3211 && rc == VINF_EM_RESET)
3212 break;
3213
3214 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3215 goto ResumeExecution;
3216 }
3217#endif
3218 AssertMsgFailed(("Unexpected vm-exit caused by exception %x\n", vector));
3219 rc = VERR_VMX_UNEXPECTED_EXCEPTION;
3220 break;
3221 } /* switch (vector) */
3222
3223 break;
3224
3225 default:
3226 rc = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_CODE;
3227 AssertMsgFailed(("Unexpected interuption code %x\n", intInfo));
3228 break;
3229 }
3230
3231 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3232 break;
3233 }
3234
3235 case VMX_EXIT_EPT_VIOLATION: /* 48 EPT violation. An attempt to access memory with a guest-physical address was disallowed by the configuration of the EPT paging structures. */
3236 {
3237 RTGCPHYS GCPhys;
3238
3239 Assert(pVM->hwaccm.s.fNestedPaging);
3240
3241 rc = VMXReadVMCS64(VMX_VMCS_EXIT_PHYS_ADDR_FULL, &GCPhys);
3242 AssertRC(rc);
3243 Assert(((exitQualification >> 7) & 3) != 2);
3244
3245 /* Determine the kind of violation. */
3246 errCode = 0;
3247 if (exitQualification & VMX_EXIT_QUALIFICATION_EPT_INSTR_FETCH)
3248 errCode |= X86_TRAP_PF_ID;
3249
3250 if (exitQualification & VMX_EXIT_QUALIFICATION_EPT_DATA_WRITE)
3251 errCode |= X86_TRAP_PF_RW;
3252
3253 /* If the page is present, then it's a page level protection fault. */
3254 if (exitQualification & VMX_EXIT_QUALIFICATION_EPT_ENTRY_PRESENT)
3255 {
3256 errCode |= X86_TRAP_PF_P;
3257 }
3258 else {
3259 /* Shortcut for APIC TPR reads and writes. */
3260 if ( (GCPhys & 0xfff) == 0x080
3261 && GCPhys > 0x1000000 /* to skip VGA frame buffer accesses */
3262 && fSetupTPRCaching
3263 && (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC))
3264 {
3265 RTGCPHYS GCPhysApicBase;
3266 PDMApicGetBase(pVM, &GCPhysApicBase); /* @todo cache this */
3267 GCPhysApicBase &= PAGE_BASE_GC_MASK;
3268 if (GCPhys == GCPhysApicBase + 0x80)
3269 {
3270 Log(("Enable VT-x virtual APIC access filtering\n"));
3271 rc = IOMMMIOMapMMIOHCPage(pVM, GCPhysApicBase, pVM->hwaccm.s.vmx.pAPICPhys, X86_PTE_RW | X86_PTE_P);
3272 AssertRC(rc);
3273 }
3274 }
3275 }
3276 Log(("EPT Page fault %x at %RGp error code %x\n", (uint32_t)exitQualification, GCPhys, errCode));
3277
3278 /* GCPhys contains the guest physical address of the page fault. */
3279 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
3280 TRPMSetErrorCode(pVCpu, errCode);
3281 TRPMSetFaultAddress(pVCpu, GCPhys);
3282
3283 /* Handle the pagefault trap for the nested shadow table. */
3284 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, errCode, CPUMCTX2CORE(pCtx), GCPhys);
3285 Log2(("PGMR0Trap0eHandlerNestedPaging %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, rc));
3286 if (rc == VINF_SUCCESS)
3287 { /* We've successfully synced our shadow pages, so let's just continue execution. */
3288 Log2(("Shadow page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, exitQualification , errCode));
3289 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitReasonNPF);
3290
3291 TRPMResetTrap(pVCpu);
3292
3293 goto ResumeExecution;
3294 }
3295
3296#ifdef VBOX_STRICT
3297 if (rc != VINF_EM_RAW_EMULATE_INSTR)
3298 LogFlow(("PGMTrap0eHandlerNestedPaging failed with %d\n", rc));
3299#endif
3300 /* Need to go back to the recompiler to emulate the instruction. */
3301 TRPMResetTrap(pVCpu);
3302 break;
3303 }
3304
3305 case VMX_EXIT_EPT_MISCONFIG:
3306 {
3307 RTGCPHYS GCPhys;
3308
3309 Assert(pVM->hwaccm.s.fNestedPaging);
3310
3311 rc = VMXReadVMCS64(VMX_VMCS_EXIT_PHYS_ADDR_FULL, &GCPhys);
3312 AssertRC(rc);
3313
3314 Log(("VMX_EXIT_EPT_MISCONFIG for %VGp\n", GCPhys));
3315 break;
3316 }
3317
3318 case VMX_EXIT_IRQ_WINDOW: /* 7 Interrupt window. */
3319 /* Clear VM-exit on IF=1 change. */
3320 LogFlow(("VMX_EXIT_IRQ_WINDOW %RGv pending=%d IF=%d\n", (RTGCPTR)pCtx->rip, VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)), pCtx->eflags.Bits.u1IF));
3321 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_IRQ_WINDOW_EXIT;
3322 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
3323 AssertRC(rc);
3324 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIrqWindow);
3325 goto ResumeExecution; /* we check for pending guest interrupts there */
3326
3327 case VMX_EXIT_WBINVD: /* 54 Guest software attempted to execute WBINVD. (conditional) */
3328 case VMX_EXIT_INVD: /* 13 Guest software attempted to execute INVD. (unconditional) */
3329 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvd);
3330 /* Skip instruction and continue directly. */
3331 pCtx->rip += cbInstr;
3332 /* Continue execution.*/
3333 goto ResumeExecution;
3334
3335 case VMX_EXIT_CPUID: /* 10 Guest software attempted to execute CPUID. */
3336 {
3337 Log2(("VMX: Cpuid %x\n", pCtx->eax));
3338 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCpuid);
3339 rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3340 if (rc == VINF_SUCCESS)
3341 {
3342 /* Update EIP and continue execution. */
3343 Assert(cbInstr == 2);
3344 pCtx->rip += cbInstr;
3345 goto ResumeExecution;
3346 }
3347 AssertMsgFailed(("EMU: cpuid failed with %Rrc\n", rc));
3348 rc = VINF_EM_RAW_EMULATE_INSTR;
3349 break;
3350 }
3351
3352 case VMX_EXIT_RDPMC: /* 15 Guest software attempted to execute RDPMC. */
3353 {
3354 Log2(("VMX: Rdpmc %x\n", pCtx->ecx));
3355 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdpmc);
3356 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3357 if (rc == VINF_SUCCESS)
3358 {
3359 /* Update EIP and continue execution. */
3360 Assert(cbInstr == 2);
3361 pCtx->rip += cbInstr;
3362 goto ResumeExecution;
3363 }
3364 rc = VINF_EM_RAW_EMULATE_INSTR;
3365 break;
3366 }
3367
3368 case VMX_EXIT_RDTSC: /* 16 Guest software attempted to execute RDTSC. */
3369 {
3370 Log2(("VMX: Rdtsc\n"));
3371 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdtsc);
3372 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3373 if (rc == VINF_SUCCESS)
3374 {
3375 /* Update EIP and continue execution. */
3376 Assert(cbInstr == 2);
3377 pCtx->rip += cbInstr;
3378 goto ResumeExecution;
3379 }
3380 rc = VINF_EM_RAW_EMULATE_INSTR;
3381 break;
3382 }
3383
3384 case VMX_EXIT_INVPG: /* 14 Guest software attempted to execute INVPG. */
3385 {
3386 Log2(("VMX: invlpg\n"));
3387 Assert(!pVM->hwaccm.s.fNestedPaging);
3388
3389 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvpg);
3390 rc = EMInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx), exitQualification);
3391 if (rc == VINF_SUCCESS)
3392 {
3393 /* Update EIP and continue execution. */
3394 pCtx->rip += cbInstr;
3395 goto ResumeExecution;
3396 }
3397 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: invlpg %RGv failed with %Rrc\n", exitQualification, rc));
3398 break;
3399 }
3400
3401 case VMX_EXIT_RDMSR: /* 31 RDMSR. Guest software attempted to execute RDMSR. */
3402 case VMX_EXIT_WRMSR: /* 32 WRMSR. Guest software attempted to execute WRMSR. */
3403 {
3404 uint32_t cbSize;
3405
3406 STAM_COUNTER_INC((exitReason == VMX_EXIT_RDMSR) ? &pVCpu->hwaccm.s.StatExitRdmsr : &pVCpu->hwaccm.s.StatExitWrmsr);
3407
3408 /* Note: the intel manual claims there's a REX version of RDMSR that's slightly different, so we play safe by completely disassembling the instruction. */
3409 Log2(("VMX: %s\n", (exitReason == VMX_EXIT_RDMSR) ? "rdmsr" : "wrmsr"));
3410 rc = EMInterpretInstruction(pVM, pVCpu, CPUMCTX2CORE(pCtx), 0, &cbSize);
3411 if (rc == VINF_SUCCESS)
3412 {
3413 /* EIP has been updated already. */
3414
3415 /* Only resume if successful. */
3416 goto ResumeExecution;
3417 }
3418 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: %s failed with %Rrc\n", (exitReason == VMX_EXIT_RDMSR) ? "rdmsr" : "wrmsr", rc));
3419 break;
3420 }
3421
3422 case VMX_EXIT_CRX_MOVE: /* 28 Control-register accesses. */
3423 {
3424 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2Sub2, y2);
3425
3426 switch (VMX_EXIT_QUALIFICATION_CRX_ACCESS(exitQualification))
3427 {
3428 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_WRITE:
3429 Log2(("VMX: %RGv mov cr%d, x\n", (RTGCPTR)pCtx->rip, VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification)));
3430 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxWrite[VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification)]);
3431 rc = EMInterpretCRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3432 VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification),
3433 VMX_EXIT_QUALIFICATION_CRX_GENREG(exitQualification));
3434
3435 switch (VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification))
3436 {
3437 case 0:
3438 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0 | HWACCM_CHANGED_GUEST_CR3;
3439 break;
3440 case 2:
3441 break;
3442 case 3:
3443 Assert(!pVM->hwaccm.s.fNestedPaging || !CPUMIsGuestInPagedProtectedModeEx(pCtx));
3444 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR3;
3445 break;
3446 case 4:
3447 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR4;
3448 break;
3449 case 8:
3450 /* CR8 contains the APIC TPR */
3451 Assert(!(pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW));
3452 break;
3453
3454 default:
3455 AssertFailed();
3456 break;
3457 }
3458 /* Check if a sync operation is pending. */
3459 if ( rc == VINF_SUCCESS /* don't bother if we are going to ring 3 anyway */
3460 && VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
3461 {
3462 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
3463 AssertRC(rc);
3464 }
3465 break;
3466
3467 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_READ:
3468 Log2(("VMX: mov x, crx\n"));
3469 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxRead[VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification)]);
3470
3471 Assert(!pVM->hwaccm.s.fNestedPaging || !CPUMIsGuestInPagedProtectedModeEx(pCtx) || VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification) != USE_REG_CR3);
3472
3473 /* CR8 reads only cause an exit when the TPR shadow feature isn't present. */
3474 Assert(VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification) != 8 || !(pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW));
3475
3476 rc = EMInterpretCRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3477 VMX_EXIT_QUALIFICATION_CRX_GENREG(exitQualification),
3478 VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification));
3479 break;
3480
3481 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_CLTS:
3482 Log2(("VMX: clts\n"));
3483 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCLTS);
3484 rc = EMInterpretCLTS(pVM, pVCpu);
3485 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
3486 break;
3487
3488 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_LMSW:
3489 Log2(("VMX: lmsw %x\n", VMX_EXIT_QUALIFICATION_CRX_LMSW_DATA(exitQualification)));
3490 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitLMSW);
3491 rc = EMInterpretLMSW(pVM, pVCpu, CPUMCTX2CORE(pCtx), VMX_EXIT_QUALIFICATION_CRX_LMSW_DATA(exitQualification));
3492 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
3493 break;
3494 }
3495
3496 /* Update EIP if no error occurred. */
3497 if (RT_SUCCESS(rc))
3498 pCtx->rip += cbInstr;
3499
3500 if (rc == VINF_SUCCESS)
3501 {
3502 /* Only resume if successful. */
3503 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub2, y2);
3504 goto ResumeExecution;
3505 }
3506 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3507 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub2, y2);
3508 break;
3509 }
3510
3511 case VMX_EXIT_DRX_MOVE: /* 29 Debug-register accesses. */
3512 {
3513 if ( !DBGFIsStepping(pVCpu)
3514 && !CPUMIsHyperDebugStateActive(pVCpu))
3515 {
3516 /* Disable drx move intercepts. */
3517 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT;
3518 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
3519 AssertRC(rc);
3520
3521 /* Save the host and load the guest debug state. */
3522 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
3523 AssertRC(rc);
3524
3525#ifdef VBOX_WITH_STATISTICS
3526 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxContextSwitch);
3527 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
3528 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxWrite);
3529 else
3530 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxRead);
3531#endif
3532
3533 goto ResumeExecution;
3534 }
3535
3536 /** @todo clear VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT after the first time and restore drx registers afterwards */
3537 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
3538 {
3539 Log2(("VMX: mov drx%d, genreg%d\n", VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification), VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification)));
3540 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxWrite);
3541 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3542 VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification),
3543 VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification));
3544 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
3545 Log2(("DR7=%08x\n", pCtx->dr[7]));
3546 }
3547 else
3548 {
3549 Log2(("VMX: mov x, drx\n"));
3550 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxRead);
3551 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3552 VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification),
3553 VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification));
3554 }
3555 /* Update EIP if no error occurred. */
3556 if (RT_SUCCESS(rc))
3557 pCtx->rip += cbInstr;
3558
3559 if (rc == VINF_SUCCESS)
3560 {
3561 /* Only resume if successful. */
3562 goto ResumeExecution;
3563 }
3564 Assert(rc == VERR_EM_INTERPRETER);
3565 break;
3566 }
3567
3568 /* Note: We'll get a #GP if the IO instruction isn't allowed (IOPL or TSS bitmap); no need to double check. */
3569 case VMX_EXIT_PORT_IO: /* 30 I/O instruction. */
3570 {
3571 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3572 uint32_t uIOWidth = VMX_EXIT_QUALIFICATION_IO_WIDTH(exitQualification);
3573 uint32_t uPort;
3574 bool fIOWrite = (VMX_EXIT_QUALIFICATION_IO_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_IO_DIRECTION_OUT);
3575
3576 /** @todo necessary to make the distinction? */
3577 if (VMX_EXIT_QUALIFICATION_IO_ENCODING(exitQualification) == VMX_EXIT_QUALIFICATION_IO_ENCODING_DX)
3578 {
3579 uPort = pCtx->edx & 0xffff;
3580 }
3581 else
3582 uPort = VMX_EXIT_QUALIFICATION_IO_PORT(exitQualification); /* Immediate encoding. */
3583
3584 /* paranoia */
3585 if (RT_UNLIKELY(uIOWidth == 2 || uIOWidth >= 4))
3586 {
3587 rc = fIOWrite ? VINF_IOM_HC_IOPORT_WRITE : VINF_IOM_HC_IOPORT_READ;
3588 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3589 break;
3590 }
3591
3592 uint32_t cbSize = g_aIOSize[uIOWidth];
3593
3594 if (VMX_EXIT_QUALIFICATION_IO_STRING(exitQualification))
3595 {
3596 /* ins/outs */
3597 PDISCPUSTATE pDis = &pVCpu->hwaccm.s.DisState;
3598
3599 /* Disassemble manually to deal with segment prefixes. */
3600 /** @todo VMX_VMCS_EXIT_GUEST_LINEAR_ADDR contains the flat pointer operand of the instruction. */
3601 /** @todo VMX_VMCS32_RO_EXIT_INSTR_INFO also contains segment prefix info. */
3602 rc = EMInterpretDisasOne(pVM, pVCpu, CPUMCTX2CORE(pCtx), pDis, NULL);
3603 if (rc == VINF_SUCCESS)
3604 {
3605 if (fIOWrite)
3606 {
3607 Log2(("IOMInterpretOUTSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, uPort, cbSize));
3608 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringWrite);
3609 rc = IOMInterpretOUTSEx(pVM, CPUMCTX2CORE(pCtx), uPort, pDis->prefix, cbSize);
3610 }
3611 else
3612 {
3613 Log2(("IOMInterpretINSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, uPort, cbSize));
3614 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringRead);
3615 rc = IOMInterpretINSEx(pVM, CPUMCTX2CORE(pCtx), uPort, pDis->prefix, cbSize);
3616 }
3617 }
3618 else
3619 rc = VINF_EM_RAW_EMULATE_INSTR;
3620 }
3621 else
3622 {
3623 /* normal in/out */
3624 uint32_t uAndVal = g_aIOOpAnd[uIOWidth];
3625
3626 Assert(!VMX_EXIT_QUALIFICATION_IO_REP(exitQualification));
3627
3628 if (fIOWrite)
3629 {
3630 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOWrite);
3631 rc = IOMIOPortWrite(pVM, uPort, pCtx->eax & uAndVal, cbSize);
3632 if (rc == VINF_IOM_HC_IOPORT_WRITE)
3633 HWACCMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pCtx->rip + cbInstr, uPort, uAndVal, cbSize);
3634 }
3635 else
3636 {
3637 uint32_t u32Val = 0;
3638
3639 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIORead);
3640 rc = IOMIOPortRead(pVM, uPort, &u32Val, cbSize);
3641 if (IOM_SUCCESS(rc))
3642 {
3643 /* Write back to the EAX register. */
3644 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
3645 }
3646 else
3647 if (rc == VINF_IOM_HC_IOPORT_READ)
3648 HWACCMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pCtx->rip + cbInstr, uPort, uAndVal, cbSize);
3649 }
3650 }
3651 /*
3652 * Handled the I/O return codes.
3653 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
3654 */
3655 if (IOM_SUCCESS(rc))
3656 {
3657 /* Update EIP and continue execution. */
3658 pCtx->rip += cbInstr;
3659 if (RT_LIKELY(rc == VINF_SUCCESS))
3660 {
3661 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
3662 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
3663 {
3664 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxIOCheck);
3665 for (unsigned i=0;i<4;i++)
3666 {
3667 unsigned uBPLen = g_aIOSize[X86_DR7_GET_LEN(pCtx->dr[7], i)];
3668
3669 if ( (uPort >= pCtx->dr[i] && uPort < pCtx->dr[i] + uBPLen)
3670 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
3671 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
3672 {
3673 uint64_t uDR6;
3674
3675 Assert(CPUMIsGuestDebugStateActive(pVCpu));
3676
3677 uDR6 = ASMGetDR6();
3678
3679 /* Clear all breakpoint status flags and set the one we just hit. */
3680 uDR6 &= ~(X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3);
3681 uDR6 |= (uint64_t)RT_BIT(i);
3682
3683 /* Note: AMD64 Architecture Programmer's Manual 13.1:
3684 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared by software after
3685 * the contents have been read.
3686 */
3687 ASMSetDR6(uDR6);
3688
3689 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
3690 pCtx->dr[7] &= ~X86_DR7_GD;
3691
3692 /* Paranoia. */
3693 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
3694 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
3695 pCtx->dr[7] |= 0x400; /* must be one */
3696
3697 /* Resync DR7 */
3698 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, pCtx->dr[7]);
3699 AssertRC(rc);
3700
3701 /* Construct inject info. */
3702 intInfo = X86_XCPT_DB;
3703 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3704 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HWEXCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3705
3706 Log(("Inject IO debug trap at %RGv\n", (RTGCPTR)pCtx->rip));
3707 rc = VMXR0InjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), 0, 0);
3708 AssertRC(rc);
3709
3710 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3711 goto ResumeExecution;
3712 }
3713 }
3714 }
3715
3716 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3717 goto ResumeExecution;
3718 }
3719 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3720 break;
3721 }
3722
3723#ifdef VBOX_STRICT
3724 if (rc == VINF_IOM_HC_IOPORT_READ)
3725 Assert(!fIOWrite);
3726 else if (rc == VINF_IOM_HC_IOPORT_WRITE)
3727 Assert(fIOWrite);
3728 else
3729 AssertMsg(RT_FAILURE(rc) || rc == VINF_EM_RAW_EMULATE_INSTR || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", rc));
3730#endif
3731 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3732 break;
3733 }
3734
3735 case VMX_EXIT_TPR: /* 43 TPR below threshold. Guest software executed MOV to CR8. */
3736 LogFlow(("VMX_EXIT_TPR\n"));
3737 /* RIP is already set to the next instruction and the TPR has been synced back. Just resume. */
3738 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3739 goto ResumeExecution;
3740
3741 case VMX_EXIT_APIC_ACCESS: /* 44 APIC access. Guest software attempted to access memory at a physical address on the APIC-access page. */
3742 {
3743 LogFlow(("VMX_EXIT_APIC_ACCESS\n"));
3744 unsigned uAccessType = VMX_EXIT_QUALIFICATION_APIC_ACCESS_TYPE(exitQualification);
3745
3746 switch(uAccessType)
3747 {
3748 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
3749 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
3750 {
3751 RTGCPHYS GCPhys;
3752 PDMApicGetBase(pVM, &GCPhys);
3753 GCPhys &= PAGE_BASE_GC_MASK;
3754 GCPhys += VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(exitQualification);
3755
3756 LogFlow(("Apic access at %RGp\n", GCPhys));
3757 rc = IOMMMIOPhysHandler(pVM, (uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ) ? 0 : X86_TRAP_PF_RW, CPUMCTX2CORE(pCtx), GCPhys);
3758 if (rc == VINF_SUCCESS)
3759 {
3760 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3761 goto ResumeExecution; /* rip already updated */
3762 }
3763 break;
3764 }
3765
3766 default:
3767 rc = VINF_EM_RAW_EMULATE_INSTR;
3768 break;
3769 }
3770 break;
3771 }
3772
3773 case VMX_EXIT_PREEMPTION_TIMER: /* 52 VMX-preemption timer expired. The preemption timer counted down to zero. */
3774 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3775 goto ResumeExecution;
3776
3777 default:
3778 /* The rest is handled after syncing the entire CPU state. */
3779 break;
3780 }
3781
3782 /* Note: the guest state isn't entirely synced back at this stage. */
3783
3784 /* Investigate why there was a VM-exit. (part 2) */
3785 switch (exitReason)
3786 {
3787 case VMX_EXIT_EXCEPTION: /* 0 Exception or non-maskable interrupt (NMI). */
3788 case VMX_EXIT_EXTERNAL_IRQ: /* 1 External interrupt. */
3789 case VMX_EXIT_EPT_VIOLATION:
3790 case VMX_EXIT_PREEMPTION_TIMER: /* 52 VMX-preemption timer expired. The preemption timer counted down to zero. */
3791 /* Already handled above. */
3792 break;
3793
3794 case VMX_EXIT_TRIPLE_FAULT: /* 2 Triple fault. */
3795 rc = VINF_EM_RESET; /* Triple fault equals a reset. */
3796 break;
3797
3798 case VMX_EXIT_INIT_SIGNAL: /* 3 INIT signal. */
3799 case VMX_EXIT_SIPI: /* 4 Start-up IPI (SIPI). */
3800 rc = VINF_EM_RAW_INTERRUPT;
3801 AssertFailed(); /* Can't happen. Yet. */
3802 break;
3803
3804 case VMX_EXIT_IO_SMI_IRQ: /* 5 I/O system-management interrupt (SMI). */
3805 case VMX_EXIT_SMI_IRQ: /* 6 Other SMI. */
3806 rc = VINF_EM_RAW_INTERRUPT;
3807 AssertFailed(); /* Can't happen afaik. */
3808 break;
3809
3810 case VMX_EXIT_TASK_SWITCH: /* 9 Task switch. */
3811 rc = VERR_EM_INTERPRETER;
3812 break;
3813
3814 case VMX_EXIT_HLT: /* 12 Guest software attempted to execute HLT. */
3815 /** Check if external interrupts are pending; if so, don't switch back. */
3816 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitHlt);
3817 pCtx->rip++; /* skip hlt */
3818 if ( pCtx->eflags.Bits.u1IF
3819 && VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)))
3820 goto ResumeExecution;
3821
3822 rc = VINF_EM_HALT;
3823 break;
3824
3825 case VMX_EXIT_MWAIT: /* 36 Guest software executed MWAIT. */
3826 Log2(("VMX: mwait\n"));
3827 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMwait);
3828 rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3829 if ( rc == VINF_EM_HALT
3830 || rc == VINF_SUCCESS)
3831 {
3832 /* Update EIP and continue execution. */
3833 pCtx->rip += cbInstr;
3834
3835 /** Check if external interrupts are pending; if so, don't switch back. */
3836 if ( rc == VINF_SUCCESS
3837 || ( rc == VINF_EM_HALT
3838 && pCtx->eflags.Bits.u1IF
3839 && VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)))
3840 )
3841 goto ResumeExecution;
3842 }
3843 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_EM_HALT, ("EMU: mwait failed with %Rrc\n", rc));
3844 break;
3845
3846 case VMX_EXIT_RSM: /* 17 Guest software attempted to execute RSM in SMM. */
3847 AssertFailed(); /* can't happen. */
3848 rc = VERR_EM_INTERPRETER;
3849 break;
3850
3851 case VMX_EXIT_VMCALL: /* 18 Guest software executed VMCALL. */
3852 case VMX_EXIT_VMCLEAR: /* 19 Guest software executed VMCLEAR. */
3853 case VMX_EXIT_VMLAUNCH: /* 20 Guest software executed VMLAUNCH. */
3854 case VMX_EXIT_VMPTRLD: /* 21 Guest software executed VMPTRLD. */
3855 case VMX_EXIT_VMPTRST: /* 22 Guest software executed VMPTRST. */
3856 case VMX_EXIT_VMREAD: /* 23 Guest software executed VMREAD. */
3857 case VMX_EXIT_VMRESUME: /* 24 Guest software executed VMRESUME. */
3858 case VMX_EXIT_VMWRITE: /* 25 Guest software executed VMWRITE. */
3859 case VMX_EXIT_VMXOFF: /* 26 Guest software executed VMXOFF. */
3860 case VMX_EXIT_VMXON: /* 27 Guest software executed VMXON. */
3861 /** @todo inject #UD immediately */
3862 rc = VERR_EM_INTERPRETER;
3863 break;
3864
3865 case VMX_EXIT_CPUID: /* 10 Guest software attempted to execute CPUID. */
3866 case VMX_EXIT_RDTSC: /* 16 Guest software attempted to execute RDTSC. */
3867 case VMX_EXIT_INVPG: /* 14 Guest software attempted to execute INVPG. */
3868 case VMX_EXIT_CRX_MOVE: /* 28 Control-register accesses. */
3869 case VMX_EXIT_DRX_MOVE: /* 29 Debug-register accesses. */
3870 case VMX_EXIT_PORT_IO: /* 30 I/O instruction. */
3871 case VMX_EXIT_RDPMC: /* 15 Guest software attempted to execute RDPMC. */
3872 /* already handled above */
3873 AssertMsg( rc == VINF_PGM_CHANGE_MODE
3874 || rc == VINF_EM_RAW_INTERRUPT
3875 || rc == VERR_EM_INTERPRETER
3876 || rc == VINF_EM_RAW_EMULATE_INSTR
3877 || rc == VINF_PGM_SYNC_CR3
3878 || rc == VINF_IOM_HC_IOPORT_READ
3879 || rc == VINF_IOM_HC_IOPORT_WRITE
3880 || rc == VINF_EM_RAW_GUEST_TRAP
3881 || rc == VINF_TRPM_XCPT_DISPATCHED
3882 || rc == VINF_EM_RESCHEDULE_REM,
3883 ("rc = %d\n", rc));
3884 break;
3885
3886 case VMX_EXIT_TPR: /* 43 TPR below threshold. Guest software executed MOV to CR8. */
3887 case VMX_EXIT_APIC_ACCESS: /* 44 APIC access. Guest software attempted to access memory at a physical address on the APIC-access page. */
3888 case VMX_EXIT_RDMSR: /* 31 RDMSR. Guest software attempted to execute RDMSR. */
3889 case VMX_EXIT_WRMSR: /* 32 WRMSR. Guest software attempted to execute WRMSR. */
3890 case VMX_EXIT_MONITOR: /* 39 Guest software attempted to execute MONITOR. */
3891 case VMX_EXIT_PAUSE: /* 40 Guest software attempted to execute PAUSE. */
3892 /* Note: If we decide to emulate them here, then we must sync the MSRs that could have been changed (sysenter, fs/gs base)!!! */
3893 rc = VERR_EM_INTERPRETER;
3894 break;
3895
3896 case VMX_EXIT_IRQ_WINDOW: /* 7 Interrupt window. */
3897 Assert(rc == VINF_EM_RAW_INTERRUPT);
3898 break;
3899
3900 case VMX_EXIT_ERR_INVALID_GUEST_STATE: /* 33 VM-entry failure due to invalid guest state. */
3901 {
3902#ifdef VBOX_STRICT
3903 RTCCUINTREG val = 0;
3904
3905 Log(("VMX_EXIT_ERR_INVALID_GUEST_STATE\n"));
3906
3907 VMXReadVMCS(VMX_VMCS64_GUEST_RIP, &val);
3908 Log(("Old eip %RGv new %RGv\n", (RTGCPTR)pCtx->rip, (RTGCPTR)val));
3909
3910 VMXReadVMCS(VMX_VMCS64_GUEST_CR0, &val);
3911 Log(("VMX_VMCS_GUEST_CR0 %RX64\n", (uint64_t)val));
3912
3913 VMXReadVMCS(VMX_VMCS64_GUEST_CR3, &val);
3914 Log(("VMX_VMCS_GUEST_CR3 %RX64\n", (uint64_t)val));
3915
3916 VMXReadVMCS(VMX_VMCS64_GUEST_CR4, &val);
3917 Log(("VMX_VMCS_GUEST_CR4 %RX64\n", (uint64_t)val));
3918
3919 VMXReadVMCS(VMX_VMCS_GUEST_RFLAGS, &val);
3920 Log(("VMX_VMCS_GUEST_RFLAGS %08x\n", val));
3921
3922 VMX_LOG_SELREG(CS, "CS");
3923 VMX_LOG_SELREG(DS, "DS");
3924 VMX_LOG_SELREG(ES, "ES");
3925 VMX_LOG_SELREG(FS, "FS");
3926 VMX_LOG_SELREG(GS, "GS");
3927 VMX_LOG_SELREG(SS, "SS");
3928 VMX_LOG_SELREG(TR, "TR");
3929 VMX_LOG_SELREG(LDTR, "LDTR");
3930
3931 VMXReadVMCS(VMX_VMCS64_GUEST_GDTR_BASE, &val);
3932 Log(("VMX_VMCS_GUEST_GDTR_BASE %RX64\n", (uint64_t)val));
3933 VMXReadVMCS(VMX_VMCS64_GUEST_IDTR_BASE, &val);
3934 Log(("VMX_VMCS_GUEST_IDTR_BASE %RX64\n", (uint64_t)val));
3935#endif /* VBOX_STRICT */
3936 rc = VERR_VMX_INVALID_GUEST_STATE;
3937 break;
3938 }
3939
3940 case VMX_EXIT_ERR_MSR_LOAD: /* 34 VM-entry failure due to MSR loading. */
3941 case VMX_EXIT_ERR_MACHINE_CHECK: /* 41 VM-entry failure due to machine-check. */
3942 default:
3943 rc = VERR_VMX_UNEXPECTED_EXIT_CODE;
3944 AssertMsgFailed(("Unexpected exit code %d\n", exitReason)); /* Can't happen. */
3945 break;
3946
3947 }
3948end:
3949
3950 /* Signal changes for the recompiler. */
3951 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR | CPUM_CHANGED_LDTR | CPUM_CHANGED_GDTR | CPUM_CHANGED_IDTR | CPUM_CHANGED_TR | CPUM_CHANGED_HIDDEN_SEL_REGS);
3952
3953 /* If we executed vmlaunch/vmresume and an external irq was pending, then we don't have to do a full sync the next time. */
3954 if ( exitReason == VMX_EXIT_EXTERNAL_IRQ
3955 && !VMX_EXIT_INTERRUPTION_INFO_VALID(intInfo))
3956 {
3957 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatPendingHostIrq);
3958 /* On the next entry we'll only sync the host context. */
3959 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_HOST_CONTEXT;
3960 }
3961 else
3962 {
3963 /* On the next entry we'll sync everything. */
3964 /** @todo we can do better than this */
3965 /* Not in the VINF_PGM_CHANGE_MODE though! */
3966 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_ALL;
3967 }
3968
3969 /* translate into a less severe return code */
3970 if (rc == VERR_EM_INTERPRETER)
3971 rc = VINF_EM_RAW_EMULATE_INSTR;
3972 else
3973 /* Try to extract more information about what might have gone wrong here. */
3974 if (rc == VERR_VMX_INVALID_VMCS_PTR)
3975 {
3976 VMXGetActivateVMCS(&pVCpu->hwaccm.s.vmx.lasterror.u64VMCSPhys);
3977 pVCpu->hwaccm.s.vmx.lasterror.ulVMCSRevision = *(uint32_t *)pVCpu->hwaccm.s.vmx.pVMCS;
3978 pVCpu->hwaccm.s.vmx.lasterror.idEnteredCpu = pVCpu->hwaccm.s.idEnteredCpu;
3979 pVCpu->hwaccm.s.vmx.lasterror.idCurrentCpu = RTMpCpuId();
3980 }
3981
3982 /* Just set the correct state here instead of trying to catch every goto above. */
3983 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC);
3984
3985#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
3986 /* Restore interrupts if we exitted after disabling them. */
3987 if (uOldEFlags != ~(RTCCUINTREG)0)
3988 ASMSetFlags(uOldEFlags);
3989#endif
3990
3991 STAM_STATS({
3992 if (fStatExit2Started) STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2, y);
3993 else if (fStatEntryStarted) STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatEntry, x);
3994 });
3995 Log2(("X"));
3996 return rc;
3997}
3998
3999
4000/**
4001 * Enters the VT-x session
4002 *
4003 * @returns VBox status code.
4004 * @param pVM The VM to operate on.
4005 * @param pVCpu The VMCPU to operate on.
4006 * @param pCpu CPU info struct
4007 */
4008VMMR0DECL(int) VMXR0Enter(PVM pVM, PVMCPU pVCpu, PHWACCM_CPUINFO pCpu)
4009{
4010 Assert(pVM->hwaccm.s.vmx.fSupported);
4011
4012 unsigned cr4 = ASMGetCR4();
4013 if (!(cr4 & X86_CR4_VMXE))
4014 {
4015 AssertMsgFailed(("X86_CR4_VMXE should be set!\n"));
4016 return VERR_VMX_X86_CR4_VMXE_CLEARED;
4017 }
4018
4019 /* Activate the VM Control Structure. */
4020 int rc = VMXActivateVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
4021 if (RT_FAILURE(rc))
4022 return rc;
4023
4024 pVCpu->hwaccm.s.fResumeVM = false;
4025 return VINF_SUCCESS;
4026}
4027
4028
4029/**
4030 * Leaves the VT-x session
4031 *
4032 * @returns VBox status code.
4033 * @param pVM The VM to operate on.
4034 * @param pVCpu The VMCPU to operate on.
4035 * @param pCtx CPU context
4036 */
4037VMMR0DECL(int) VMXR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4038{
4039 Assert(pVM->hwaccm.s.vmx.fSupported);
4040
4041#ifdef DEBUG
4042 if (CPUMIsHyperDebugStateActive(pVCpu))
4043 {
4044 CPUMR0LoadHostDebugState(pVM, pVCpu);
4045 }
4046 else
4047#endif
4048 /* Save the guest debug state if necessary. */
4049 if (CPUMIsGuestDebugStateActive(pVCpu))
4050 {
4051 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, true /* save DR6 */);
4052
4053 /* Enable drx move intercepts again. */
4054 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT;
4055 int rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
4056 AssertRC(rc);
4057
4058 /* Resync the debug registers the next time. */
4059 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
4060 }
4061 else
4062 Assert(pVCpu->hwaccm.s.vmx.proc_ctls & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT);
4063
4064 /* Clear VM Control Structure. Marking it inactive, clearing implementation specific data and writing back VMCS data to memory. */
4065 int rc = VMXClearVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
4066 AssertRC(rc);
4067
4068 return VINF_SUCCESS;
4069}
4070
4071/**
4072 * Flush the TLB (EPT)
4073 *
4074 * @returns VBox status code.
4075 * @param pVM The VM to operate on.
4076 * @param pVCpu The VM CPU to operate on.
4077 * @param enmFlush Type of flush
4078 * @param GCPhys Physical address of the page to flush
4079 */
4080static void vmxR0FlushEPT(PVM pVM, PVMCPU pVCpu, VMX_FLUSH enmFlush, RTGCPHYS GCPhys)
4081{
4082 uint64_t descriptor[2];
4083
4084 LogFlow(("vmxR0FlushEPT %d %RGv\n", enmFlush, GCPhys));
4085 Assert(pVM->hwaccm.s.fNestedPaging);
4086 descriptor[0] = pVCpu->hwaccm.s.vmx.GCPhysEPTP;
4087 descriptor[1] = GCPhys;
4088 int rc = VMXR0InvEPT(enmFlush, &descriptor[0]);
4089 AssertRC(rc);
4090}
4091
4092#ifdef HWACCM_VTX_WITH_VPID
4093/**
4094 * Flush the TLB (EPT)
4095 *
4096 * @returns VBox status code.
4097 * @param pVM The VM to operate on.
4098 * @param pVCpu The VM CPU to operate on.
4099 * @param enmFlush Type of flush
4100 * @param GCPtr Virtual address of the page to flush
4101 */
4102static void vmxR0FlushVPID(PVM pVM, PVMCPU pVCpu, VMX_FLUSH enmFlush, RTGCPTR GCPtr)
4103{
4104#if HC_ARCH_BITS == 32
4105 /* If we get a flush in 64 bits guest mode, then force a full TLB flush. Invvpid probably takes only 32 bits addresses. (@todo) */
4106 if ( CPUMIsGuestInLongMode(pVCpu)
4107 && !VMX_IS_64BIT_HOST_MODE())
4108 {
4109 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
4110 }
4111 else
4112#endif
4113 {
4114 uint64_t descriptor[2];
4115
4116 Assert(pVM->hwaccm.s.vmx.fVPID);
4117 descriptor[0] = pVCpu->hwaccm.s.uCurrentASID;
4118 descriptor[1] = GCPtr;
4119 int rc = VMXR0InvVPID(enmFlush, &descriptor[0]);
4120 AssertRC(rc);
4121 }
4122}
4123#endif /* HWACCM_VTX_WITH_VPID */
4124
4125/**
4126 * Invalidates a guest page
4127 *
4128 * @returns VBox status code.
4129 * @param pVM The VM to operate on.
4130 * @param pVCpu The VM CPU to operate on.
4131 * @param GCVirt Page to invalidate
4132 */
4133VMMR0DECL(int) VMXR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
4134{
4135 bool fFlushPending = VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
4136
4137 Log2(("VMXR0InvalidatePage %RGv\n", GCVirt));
4138
4139 /* Only relevant if we want to use VPID.
4140 * In the nested paging case we still see such calls, but
4141 * can safely ignore them. (e.g. after cr3 updates)
4142 */
4143#ifdef HWACCM_VTX_WITH_VPID
4144 /* Skip it if a TLB flush is already pending. */
4145 if ( !fFlushPending
4146 && pVM->hwaccm.s.vmx.fVPID)
4147 vmxR0FlushVPID(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushPage, GCVirt);
4148#endif /* HWACCM_VTX_WITH_VPID */
4149
4150 return VINF_SUCCESS;
4151}
4152
4153/**
4154 * Invalidates a guest page by physical address
4155 *
4156 * NOTE: Assumes the current instruction references this physical page though a virtual address!!
4157 *
4158 * @returns VBox status code.
4159 * @param pVM The VM to operate on.
4160 * @param pVCpu The VM CPU to operate on.
4161 * @param GCPhys Page to invalidate
4162 */
4163VMMR0DECL(int) VMXR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
4164{
4165 bool fFlushPending = VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
4166
4167 Assert(pVM->hwaccm.s.fNestedPaging);
4168
4169 LogFlow(("VMXR0InvalidatePhysPage %RGp\n", GCPhys));
4170
4171 /* Skip it if a TLB flush is already pending. */
4172 if (!fFlushPending)
4173 vmxR0FlushEPT(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushPage, GCPhys);
4174
4175 return VINF_SUCCESS;
4176}
4177
4178/**
4179 * Report world switch error and dump some useful debug info
4180 *
4181 * @param pVM The VM to operate on.
4182 * @param pVCpu The VMCPU to operate on.
4183 * @param rc Return code
4184 * @param pCtx Current CPU context (not updated)
4185 */
4186static void VMXR0ReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rc, PCPUMCTX pCtx)
4187{
4188 switch (rc)
4189 {
4190 case VERR_VMX_INVALID_VMXON_PTR:
4191 AssertFailed();
4192 break;
4193
4194 case VERR_VMX_UNABLE_TO_START_VM:
4195 case VERR_VMX_UNABLE_TO_RESUME_VM:
4196 {
4197 int rc;
4198 RTCCUINTREG exitReason, instrError;
4199
4200 rc = VMXReadVMCS(VMX_VMCS32_RO_EXIT_REASON, &exitReason);
4201 rc |= VMXReadVMCS(VMX_VMCS32_RO_VM_INSTR_ERROR, &instrError);
4202 AssertRC(rc);
4203 if (rc == VINF_SUCCESS)
4204 {
4205 Log(("Unable to start/resume VM for reason: %x. Instruction error %x\n", (uint32_t)exitReason, (uint32_t)instrError));
4206 Log(("Current stack %08x\n", &rc));
4207
4208 pVCpu->hwaccm.s.vmx.lasterror.ulInstrError = instrError;
4209 pVCpu->hwaccm.s.vmx.lasterror.ulExitReason = exitReason;
4210
4211#ifdef VBOX_STRICT
4212 RTGDTR gdtr;
4213 PX86DESCHC pDesc;
4214 RTCCUINTREG val;
4215
4216 ASMGetGDTR(&gdtr);
4217
4218 VMXReadVMCS(VMX_VMCS64_GUEST_RIP, &val);
4219 Log(("Old eip %RGv new %RGv\n", (RTGCPTR)pCtx->rip, (RTGCPTR)val));
4220 VMXReadVMCS(VMX_VMCS_CTRL_PIN_EXEC_CONTROLS, &val);
4221 Log(("VMX_VMCS_CTRL_PIN_EXEC_CONTROLS %08x\n", val));
4222 VMXReadVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, &val);
4223 Log(("VMX_VMCS_CTRL_PROC_EXEC_CONTROLS %08x\n", val));
4224 VMXReadVMCS(VMX_VMCS_CTRL_ENTRY_CONTROLS, &val);
4225 Log(("VMX_VMCS_CTRL_ENTRY_CONTROLS %08x\n", val));
4226 VMXReadVMCS(VMX_VMCS_CTRL_EXIT_CONTROLS, &val);
4227 Log(("VMX_VMCS_CTRL_EXIT_CONTROLS %08x\n", val));
4228
4229 VMXReadVMCS(VMX_VMCS_HOST_CR0, &val);
4230 Log(("VMX_VMCS_HOST_CR0 %08x\n", val));
4231
4232 VMXReadVMCS(VMX_VMCS_HOST_CR3, &val);
4233 Log(("VMX_VMCS_HOST_CR3 %08x\n", val));
4234
4235 VMXReadVMCS(VMX_VMCS_HOST_CR4, &val);
4236 Log(("VMX_VMCS_HOST_CR4 %08x\n", val));
4237
4238 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_CS, &val);
4239 Log(("VMX_VMCS_HOST_FIELD_CS %08x\n", val));
4240
4241 VMXReadVMCS(VMX_VMCS_GUEST_RFLAGS, &val);
4242 Log(("VMX_VMCS_GUEST_RFLAGS %08x\n", val));
4243
4244 if (val < gdtr.cbGdt)
4245 {
4246 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4247 HWACCMR0DumpDescriptor(pDesc, val, "CS: ");
4248 }
4249
4250 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_DS, &val);
4251 Log(("VMX_VMCS_HOST_FIELD_DS %08x\n", val));
4252 if (val < gdtr.cbGdt)
4253 {
4254 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4255 HWACCMR0DumpDescriptor(pDesc, val, "DS: ");
4256 }
4257
4258 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_ES, &val);
4259 Log(("VMX_VMCS_HOST_FIELD_ES %08x\n", val));
4260 if (val < gdtr.cbGdt)
4261 {
4262 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4263 HWACCMR0DumpDescriptor(pDesc, val, "ES: ");
4264 }
4265
4266 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_FS, &val);
4267 Log(("VMX_VMCS16_HOST_FIELD_FS %08x\n", val));
4268 if (val < gdtr.cbGdt)
4269 {
4270 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4271 HWACCMR0DumpDescriptor(pDesc, val, "FS: ");
4272 }
4273
4274 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_GS, &val);
4275 Log(("VMX_VMCS16_HOST_FIELD_GS %08x\n", val));
4276 if (val < gdtr.cbGdt)
4277 {
4278 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4279 HWACCMR0DumpDescriptor(pDesc, val, "GS: ");
4280 }
4281
4282 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_SS, &val);
4283 Log(("VMX_VMCS16_HOST_FIELD_SS %08x\n", val));
4284 if (val < gdtr.cbGdt)
4285 {
4286 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4287 HWACCMR0DumpDescriptor(pDesc, val, "SS: ");
4288 }
4289
4290 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_TR, &val);
4291 Log(("VMX_VMCS16_HOST_FIELD_TR %08x\n", val));
4292 if (val < gdtr.cbGdt)
4293 {
4294 pDesc = &((PX86DESCHC)gdtr.pGdt)[val >> X86_SEL_SHIFT_HC];
4295 HWACCMR0DumpDescriptor(pDesc, val, "TR: ");
4296 }
4297
4298 VMXReadVMCS(VMX_VMCS_HOST_TR_BASE, &val);
4299 Log(("VMX_VMCS_HOST_TR_BASE %RHv\n", val));
4300
4301 VMXReadVMCS(VMX_VMCS_HOST_GDTR_BASE, &val);
4302 Log(("VMX_VMCS_HOST_GDTR_BASE %RHv\n", val));
4303 VMXReadVMCS(VMX_VMCS_HOST_IDTR_BASE, &val);
4304 Log(("VMX_VMCS_HOST_IDTR_BASE %RHv\n", val));
4305
4306 VMXReadVMCS(VMX_VMCS32_HOST_SYSENTER_CS, &val);
4307 Log(("VMX_VMCS_HOST_SYSENTER_CS %08x\n", val));
4308
4309 VMXReadVMCS(VMX_VMCS_HOST_SYSENTER_EIP, &val);
4310 Log(("VMX_VMCS_HOST_SYSENTER_EIP %RHv\n", val));
4311
4312 VMXReadVMCS(VMX_VMCS_HOST_SYSENTER_ESP, &val);
4313 Log(("VMX_VMCS_HOST_SYSENTER_ESP %RHv\n", val));
4314
4315 VMXReadVMCS(VMX_VMCS_HOST_RSP, &val);
4316 Log(("VMX_VMCS_HOST_RSP %RHv\n", val));
4317 VMXReadVMCS(VMX_VMCS_HOST_RIP, &val);
4318 Log(("VMX_VMCS_HOST_RIP %RHv\n", val));
4319
4320# if HC_ARCH_BITS == 64 || defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
4321 if (VMX_IS_64BIT_HOST_MODE())
4322 {
4323 Log(("MSR_K6_EFER = %RX64\n", ASMRdMsr(MSR_K6_EFER)));
4324 Log(("MSR_K6_STAR = %RX64\n", ASMRdMsr(MSR_K6_STAR)));
4325 Log(("MSR_K8_LSTAR = %RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
4326 Log(("MSR_K8_CSTAR = %RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
4327 Log(("MSR_K8_SF_MASK = %RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
4328 }
4329# endif
4330#endif /* VBOX_STRICT */
4331 }
4332 break;
4333 }
4334
4335 default:
4336 /* impossible */
4337 AssertMsgFailed(("%Rrc (%#x)\n", rc, rc));
4338 break;
4339 }
4340}
4341
4342#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
4343/**
4344 * Prepares for and executes VMLAUNCH (64 bits guest mode)
4345 *
4346 * @returns VBox status code
4347 * @param fResume vmlauch/vmresume
4348 * @param pCtx Guest context
4349 * @param pCache VMCS cache
4350 * @param pVM The VM to operate on.
4351 * @param pVCpu The VMCPU to operate on.
4352 */
4353DECLASM(int) VMXR0SwitcherStartVM64(RTHCUINT fResume, PCPUMCTX pCtx, PVMCSCACHE pCache, PVM pVM, PVMCPU pVCpu)
4354{
4355 uint32_t aParam[6];
4356 PHWACCM_CPUINFO pCpu;
4357 RTHCPHYS pPageCpuPhys;
4358 int rc;
4359
4360 pCpu = HWACCMR0GetCurrentCpu();
4361 pPageCpuPhys = RTR0MemObjGetPagePhysAddr(pCpu->pMemObj, 0);
4362
4363#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4364 pCache->uPos = 1;
4365 pCache->interPD = PGMGetInterPaeCR3(pVM);
4366 pCache->pSwitcher = (uint64_t)pVM->hwaccm.s.pfnHost32ToGuest64R0;
4367#endif
4368
4369#ifdef DEBUG
4370 pCache->TestIn.pPageCpuPhys = 0;
4371 pCache->TestIn.pVMCSPhys = 0;
4372 pCache->TestIn.pCache = 0;
4373 pCache->TestOut.pVMCSPhys = 0;
4374 pCache->TestOut.pCache = 0;
4375 pCache->TestOut.pCtx = 0;
4376 pCache->TestOut.eflags = 0;
4377#endif
4378
4379 aParam[0] = (uint32_t)(pPageCpuPhys); /* Param 1: VMXON physical address - Lo. */
4380 aParam[1] = (uint32_t)(pPageCpuPhys >> 32); /* Param 1: VMXON physical address - Hi. */
4381 aParam[2] = (uint32_t)(pVCpu->hwaccm.s.vmx.pVMCSPhys); /* Param 2: VMCS physical address - Lo. */
4382 aParam[3] = (uint32_t)(pVCpu->hwaccm.s.vmx.pVMCSPhys >> 32); /* Param 2: VMCS physical address - Hi. */
4383 aParam[4] = VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hwaccm.s.vmx.VMCSCache);
4384 aParam[5] = 0;
4385
4386#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4387 pCtx->dr[4] = pVM->hwaccm.s.vmx.pScratchPhys + 16 + 8;
4388 *(uint32_t *)(pVM->hwaccm.s.vmx.pScratch + 16 + 8) = 1;
4389#endif
4390 rc = VMXR0Execute64BitsHandler(pVM, pVCpu, pCtx, pVM->hwaccm.s.pfnVMXGCStartVM64, 6, &aParam[0]);
4391
4392#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4393 Assert(*(uint32_t *)(pVM->hwaccm.s.vmx.pScratch + 16 + 8) == 5);
4394 Assert(pCtx->dr[4] == 10);
4395 *(uint32_t *)(pVM->hwaccm.s.vmx.pScratch + 16 + 8) = 0xff;
4396#endif
4397
4398#ifdef DEBUG
4399 AssertMsg(pCache->TestIn.pPageCpuPhys == pPageCpuPhys, ("%RHp vs %RHp\n", pCache->TestIn.pPageCpuPhys, pPageCpuPhys));
4400 AssertMsg(pCache->TestIn.pVMCSPhys == pVCpu->hwaccm.s.vmx.pVMCSPhys, ("%RHp vs %RHp\n", pCache->TestIn.pVMCSPhys, pVCpu->hwaccm.s.vmx.pVMCSPhys));
4401 AssertMsg(pCache->TestIn.pVMCSPhys == pCache->TestOut.pVMCSPhys, ("%RHp vs %RHp\n", pCache->TestIn.pVMCSPhys, pCache->TestOut.pVMCSPhys));
4402 AssertMsg(pCache->TestIn.pCache == pCache->TestOut.pCache, ("%RGv vs %RGv\n", pCache->TestIn.pCache, pCache->TestOut.pCache));
4403 AssertMsg(pCache->TestIn.pCache == VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hwaccm.s.vmx.VMCSCache), ("%RGv vs %RGv\n", pCache->TestIn.pCache, VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hwaccm.s.vmx.VMCSCache)));
4404 AssertMsg(pCache->TestIn.pCtx == pCache->TestOut.pCtx, ("%RGv vs %RGv\n", pCache->TestIn.pCtx, pCache->TestOut.pCtx));
4405 Assert(!(pCache->TestOut.eflags & X86_EFL_IF));
4406#endif
4407 return rc;
4408}
4409
4410/**
4411 * Executes the specified handler in 64 mode
4412 *
4413 * @returns VBox status code.
4414 * @param pVM The VM to operate on.
4415 * @param pVCpu The VMCPU to operate on.
4416 * @param pCtx Guest context
4417 * @param pfnHandler RC handler
4418 * @param cbParam Number of parameters
4419 * @param paParam Array of 32 bits parameters
4420 */
4421VMMR0DECL(int) VMXR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, RTRCPTR pfnHandler, uint32_t cbParam, uint32_t *paParam)
4422{
4423 int rc, rc2;
4424 PHWACCM_CPUINFO pCpu;
4425 RTHCPHYS pPageCpuPhys;
4426
4427 /* @todo This code is not guest SMP safe (hyper stack and switchers) */
4428 AssertReturn(pVM->cCPUs == 1, VERR_TOO_MANY_CPUS);
4429 AssertReturn(pVM->hwaccm.s.pfnHost32ToGuest64R0, VERR_INTERNAL_ERROR);
4430 Assert(pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries <= RT_ELEMENTS(pVCpu->hwaccm.s.vmx.VMCSCache.Write.aField));
4431 Assert(pVCpu->hwaccm.s.vmx.VMCSCache.Read.cValidEntries <= RT_ELEMENTS(pVCpu->hwaccm.s.vmx.VMCSCache.Read.aField));
4432
4433#ifdef VBOX_STRICT
4434 for (unsigned i=0;i<pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries;i++)
4435 Assert(vmxR0IsValidWriteField(pVCpu->hwaccm.s.vmx.VMCSCache.Write.aField[i]));
4436
4437 for (unsigned i=0;i<pVCpu->hwaccm.s.vmx.VMCSCache.Read.cValidEntries;i++)
4438 Assert(vmxR0IsValidReadField(pVCpu->hwaccm.s.vmx.VMCSCache.Read.aField[i]));
4439#endif
4440
4441 pCpu = HWACCMR0GetCurrentCpu();
4442 pPageCpuPhys = RTR0MemObjGetPagePhysAddr(pCpu->pMemObj, 0);
4443
4444 /* Clear VM Control Structure. Marking it inactive, clearing implementation specific data and writing back VMCS data to memory. */
4445 VMXClearVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
4446
4447 /* Leave VMX Root Mode. */
4448 VMXDisable();
4449
4450 ASMSetCR4(ASMGetCR4() & ~X86_CR4_VMXE);
4451
4452 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVM));
4453 CPUMSetHyperEIP(pVCpu, pfnHandler);
4454 for (int i=(int)cbParam-1;i>=0;i--)
4455 CPUMPushHyper(pVCpu, paParam[i]);
4456
4457 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
4458 /* Call switcher. */
4459 rc = pVM->hwaccm.s.pfnHost32ToGuest64R0(pVM);
4460 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
4461
4462 /* Make sure the VMX instructions don't cause #UD faults. */
4463 ASMSetCR4(ASMGetCR4() | X86_CR4_VMXE);
4464
4465 /* Enter VMX Root Mode */
4466 rc2 = VMXEnable(pPageCpuPhys);
4467 if (RT_FAILURE(rc2))
4468 {
4469 if (pVM)
4470 VMXR0CheckError(pVM, pVCpu, rc2);
4471 ASMSetCR4(ASMGetCR4() & ~X86_CR4_VMXE);
4472 return VERR_VMX_VMXON_FAILED;
4473 }
4474
4475 rc2 = VMXActivateVMCS(pVCpu->hwaccm.s.vmx.pVMCSPhys);
4476 AssertRCReturn(rc2, rc2);
4477 Assert(!(ASMGetFlags() & X86_EFL_IF));
4478 return rc;
4479}
4480
4481#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL) */
4482
4483
4484#if HC_ARCH_BITS == 32 && !defined(VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0)
4485/**
4486 * Executes VMWRITE
4487 *
4488 * @returns VBox status code
4489 * @param pVCpu The VMCPU to operate on.
4490 * @param idxField VMCS index
4491 * @param u64Val 16, 32 or 64 bits value
4492 */
4493VMMR0DECL(int) VMXWriteVMCS64Ex(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
4494{
4495 int rc;
4496
4497 switch (idxField)
4498 {
4499 case VMX_VMCS_CTRL_TSC_OFFSET_FULL:
4500 case VMX_VMCS_CTRL_IO_BITMAP_A_FULL:
4501 case VMX_VMCS_CTRL_IO_BITMAP_B_FULL:
4502 case VMX_VMCS_CTRL_MSR_BITMAP_FULL:
4503 case VMX_VMCS_CTRL_VMEXIT_MSR_STORE_FULL:
4504 case VMX_VMCS_CTRL_VMEXIT_MSR_LOAD_FULL:
4505 case VMX_VMCS_CTRL_VMENTRY_MSR_LOAD_FULL:
4506 case VMX_VMCS_CTRL_VAPIC_PAGEADDR_FULL:
4507 case VMX_VMCS_CTRL_APIC_ACCESSADDR_FULL:
4508 case VMX_VMCS_GUEST_LINK_PTR_FULL:
4509 case VMX_VMCS_GUEST_PDPTR0_FULL:
4510 case VMX_VMCS_GUEST_PDPTR1_FULL:
4511 case VMX_VMCS_GUEST_PDPTR2_FULL:
4512 case VMX_VMCS_GUEST_PDPTR3_FULL:
4513 case VMX_VMCS_GUEST_DEBUGCTL_FULL:
4514 case VMX_VMCS_GUEST_EFER_FULL:
4515 case VMX_VMCS_CTRL_EPTP_FULL:
4516 /* These fields consist of two parts, which are both writable in 32 bits mode. */
4517 rc = VMXWriteVMCS32(idxField, u64Val);
4518 rc |= VMXWriteVMCS32(idxField + 1, (uint32_t)(u64Val >> 32ULL));
4519 AssertRC(rc);
4520 return rc;
4521
4522 case VMX_VMCS64_GUEST_LDTR_BASE:
4523 case VMX_VMCS64_GUEST_TR_BASE:
4524 case VMX_VMCS64_GUEST_GDTR_BASE:
4525 case VMX_VMCS64_GUEST_IDTR_BASE:
4526 case VMX_VMCS64_GUEST_SYSENTER_EIP:
4527 case VMX_VMCS64_GUEST_SYSENTER_ESP:
4528 case VMX_VMCS64_GUEST_CR0:
4529 case VMX_VMCS64_GUEST_CR4:
4530 case VMX_VMCS64_GUEST_CR3:
4531 case VMX_VMCS64_GUEST_DR7:
4532 case VMX_VMCS64_GUEST_RIP:
4533 case VMX_VMCS64_GUEST_RSP:
4534 case VMX_VMCS64_GUEST_CS_BASE:
4535 case VMX_VMCS64_GUEST_DS_BASE:
4536 case VMX_VMCS64_GUEST_ES_BASE:
4537 case VMX_VMCS64_GUEST_FS_BASE:
4538 case VMX_VMCS64_GUEST_GS_BASE:
4539 case VMX_VMCS64_GUEST_SS_BASE:
4540 /* Queue a 64 bits value as we can't set it in 32 bits host mode. */
4541 if (u64Val >> 32ULL)
4542 rc = VMXWriteCachedVMCSEx(pVCpu, idxField, u64Val);
4543 else
4544 rc = VMXWriteVMCS32(idxField, (uint32_t)u64Val);
4545
4546 return rc;
4547
4548 default:
4549 AssertMsgFailed(("Unexpected field %x\n", idxField));
4550 return VERR_INVALID_PARAMETER;
4551 }
4552}
4553
4554/**
4555 * Cache VMCS writes for performance reasons (Darwin) and for running 64 bits guests on 32 bits hosts.
4556 *
4557 * @param pVCpu The VMCPU to operate on.
4558 * @param idxField VMCS field
4559 * @param u64Val Value
4560 */
4561VMMR0DECL(int) VMXWriteCachedVMCSEx(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
4562{
4563 PVMCSCACHE pCache = &pVCpu->hwaccm.s.vmx.VMCSCache;
4564
4565 AssertMsgReturn(pCache->Write.cValidEntries < VMCSCACHE_MAX_ENTRY - 1, ("entries=%x\n", pCache->Write.cValidEntries), VERR_ACCESS_DENIED);
4566
4567 /* Make sure there are no duplicates. */
4568 for (unsigned i=0;i<pCache->Write.cValidEntries;i++)
4569 {
4570 if (pCache->Write.aField[i] == idxField)
4571 {
4572 pCache->Write.aFieldVal[i] = u64Val;
4573 return VINF_SUCCESS;
4574 }
4575 }
4576
4577 pCache->Write.aField[pCache->Write.cValidEntries] = idxField;
4578 pCache->Write.aFieldVal[pCache->Write.cValidEntries] = u64Val;
4579 pCache->Write.cValidEntries++;
4580 return VINF_SUCCESS;
4581}
4582
4583#endif /* HC_ARCH_BITS == 32 && !VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0 */
4584
4585#ifdef VBOX_STRICT
4586static bool vmxR0IsValidReadField(uint32_t idxField)
4587{
4588 switch(idxField)
4589 {
4590 case VMX_VMCS64_GUEST_RIP:
4591 case VMX_VMCS64_GUEST_RSP:
4592 case VMX_VMCS_GUEST_RFLAGS:
4593 case VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE:
4594 case VMX_VMCS_CTRL_CR0_READ_SHADOW:
4595 case VMX_VMCS64_GUEST_CR0:
4596 case VMX_VMCS_CTRL_CR4_READ_SHADOW:
4597 case VMX_VMCS64_GUEST_CR4:
4598 case VMX_VMCS64_GUEST_DR7:
4599 case VMX_VMCS32_GUEST_SYSENTER_CS:
4600 case VMX_VMCS64_GUEST_SYSENTER_EIP:
4601 case VMX_VMCS64_GUEST_SYSENTER_ESP:
4602 case VMX_VMCS32_GUEST_GDTR_LIMIT:
4603 case VMX_VMCS64_GUEST_GDTR_BASE:
4604 case VMX_VMCS32_GUEST_IDTR_LIMIT:
4605 case VMX_VMCS64_GUEST_IDTR_BASE:
4606 case VMX_VMCS16_GUEST_FIELD_CS:
4607 case VMX_VMCS32_GUEST_CS_LIMIT:
4608 case VMX_VMCS64_GUEST_CS_BASE:
4609 case VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS:
4610 case VMX_VMCS16_GUEST_FIELD_DS:
4611 case VMX_VMCS32_GUEST_DS_LIMIT:
4612 case VMX_VMCS64_GUEST_DS_BASE:
4613 case VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS:
4614 case VMX_VMCS16_GUEST_FIELD_ES:
4615 case VMX_VMCS32_GUEST_ES_LIMIT:
4616 case VMX_VMCS64_GUEST_ES_BASE:
4617 case VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS:
4618 case VMX_VMCS16_GUEST_FIELD_FS:
4619 case VMX_VMCS32_GUEST_FS_LIMIT:
4620 case VMX_VMCS64_GUEST_FS_BASE:
4621 case VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS:
4622 case VMX_VMCS16_GUEST_FIELD_GS:
4623 case VMX_VMCS32_GUEST_GS_LIMIT:
4624 case VMX_VMCS64_GUEST_GS_BASE:
4625 case VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS:
4626 case VMX_VMCS16_GUEST_FIELD_SS:
4627 case VMX_VMCS32_GUEST_SS_LIMIT:
4628 case VMX_VMCS64_GUEST_SS_BASE:
4629 case VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS:
4630 case VMX_VMCS16_GUEST_FIELD_LDTR:
4631 case VMX_VMCS32_GUEST_LDTR_LIMIT:
4632 case VMX_VMCS64_GUEST_LDTR_BASE:
4633 case VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS:
4634 case VMX_VMCS16_GUEST_FIELD_TR:
4635 case VMX_VMCS32_GUEST_TR_LIMIT:
4636 case VMX_VMCS64_GUEST_TR_BASE:
4637 case VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS:
4638 case VMX_VMCS32_RO_EXIT_REASON:
4639 case VMX_VMCS32_RO_VM_INSTR_ERROR:
4640 case VMX_VMCS32_RO_EXIT_INSTR_LENGTH:
4641 case VMX_VMCS32_RO_EXIT_INTERRUPTION_ERRCODE:
4642 case VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO:
4643 case VMX_VMCS32_RO_EXIT_INSTR_INFO:
4644 case VMX_VMCS_RO_EXIT_QUALIFICATION:
4645 case VMX_VMCS32_RO_IDT_INFO:
4646 case VMX_VMCS32_RO_IDT_ERRCODE:
4647 case VMX_VMCS64_GUEST_CR3:
4648 case VMX_VMCS_EXIT_PHYS_ADDR_FULL:
4649 return true;
4650 }
4651 return false;
4652}
4653
4654static bool vmxR0IsValidWriteField(uint32_t idxField)
4655{
4656 switch(idxField)
4657 {
4658 case VMX_VMCS64_GUEST_LDTR_BASE:
4659 case VMX_VMCS64_GUEST_TR_BASE:
4660 case VMX_VMCS64_GUEST_GDTR_BASE:
4661 case VMX_VMCS64_GUEST_IDTR_BASE:
4662 case VMX_VMCS64_GUEST_SYSENTER_EIP:
4663 case VMX_VMCS64_GUEST_SYSENTER_ESP:
4664 case VMX_VMCS64_GUEST_CR0:
4665 case VMX_VMCS64_GUEST_CR4:
4666 case VMX_VMCS64_GUEST_CR3:
4667 case VMX_VMCS64_GUEST_DR7:
4668 case VMX_VMCS64_GUEST_RIP:
4669 case VMX_VMCS64_GUEST_RSP:
4670 case VMX_VMCS64_GUEST_CS_BASE:
4671 case VMX_VMCS64_GUEST_DS_BASE:
4672 case VMX_VMCS64_GUEST_ES_BASE:
4673 case VMX_VMCS64_GUEST_FS_BASE:
4674 case VMX_VMCS64_GUEST_GS_BASE:
4675 case VMX_VMCS64_GUEST_SS_BASE:
4676 return true;
4677 }
4678 return false;
4679}
4680
4681#endif
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