VirtualBox

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

Last change on this file since 40551 was 40551, checked in by vboxsync, 13 years ago

VT-x: Properly determine #MF interception state.

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