VirtualBox

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

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

Back to manual msr save and restore.

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