VirtualBox

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

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

EM: build fix.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 199.2 KB
Line 
1/* $Id: HWVMXR0.cpp 40451 2012-03-13 16:13:54Z 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 as we need to report them to the guest in a different way. */
1312 if ( CPUMIsGuestFPUStateActive(pVCpu) == true
1313 && !(pCtx->cr0 & X86_CR0_NE)
1314 && !pVCpu->hwaccm.s.fFPUOldStyleOverride)
1315 {
1316 u32TrapMask |= RT_BIT(X86_XCPT_MF);
1317 pVCpu->hwaccm.s.fFPUOldStyleOverride = true;
1318 }
1319
1320#ifdef VBOX_STRICT
1321 Assert(u32TrapMask & RT_BIT(X86_XCPT_GP));
1322#endif
1323
1324 /* Intercept all exceptions in real mode as none of them can be injected directly (#GP otherwise). */
1325 if ( CPUMIsGuestInRealModeEx(pCtx)
1326 && pVM->hwaccm.s.vmx.pRealModeTSS)
1327 u32TrapMask |= HWACCM_VMX_TRAP_MASK_REALMODE;
1328
1329 int rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXCEPTION_BITMAP, u32TrapMask);
1330 AssertRC(rc);
1331}
1332
1333/**
1334 * Loads a minimal guest state
1335 *
1336 * NOTE: Don't do anything here that can cause a jump back to ring 3!!!!!
1337 *
1338 * @param pVM The VM to operate on.
1339 * @param pVCpu The VMCPU to operate on.
1340 * @param pCtx Guest context
1341 */
1342VMMR0DECL(void) VMXR0LoadMinimalGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1343{
1344 int rc;
1345 X86EFLAGS eflags;
1346
1347 Assert(!(pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_ALL_GUEST));
1348
1349 /* EIP, ESP and EFLAGS */
1350 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_RIP, pCtx->rip);
1351 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_RSP, pCtx->rsp);
1352 AssertRC(rc);
1353
1354 /* Bits 22-31, 15, 5 & 3 must be zero. Bit 1 must be 1. */
1355 eflags = pCtx->eflags;
1356 eflags.u32 &= VMX_EFLAGS_RESERVED_0;
1357 eflags.u32 |= VMX_EFLAGS_RESERVED_1;
1358
1359 /* Real mode emulation using v86 mode. */
1360 if ( CPUMIsGuestInRealModeEx(pCtx)
1361 && pVM->hwaccm.s.vmx.pRealModeTSS)
1362 {
1363 pVCpu->hwaccm.s.vmx.RealMode.eflags = eflags;
1364
1365 eflags.Bits.u1VM = 1;
1366 eflags.Bits.u2IOPL = 0; /* must always be 0 or else certain instructions won't cause faults. */
1367 }
1368 rc = VMXWriteVMCS(VMX_VMCS_GUEST_RFLAGS, eflags.u32);
1369 AssertRC(rc);
1370}
1371
1372/**
1373 * Loads the guest state
1374 *
1375 * NOTE: Don't do anything here that can cause a jump back to ring 3!!!!!
1376 *
1377 * @returns VBox status code.
1378 * @param pVM The VM to operate on.
1379 * @param pVCpu The VMCPU to operate on.
1380 * @param pCtx Guest context
1381 */
1382VMMR0DECL(int) VMXR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1383{
1384 int rc = VINF_SUCCESS;
1385 RTGCUINTPTR val;
1386
1387 /* VMX_VMCS_CTRL_ENTRY_CONTROLS
1388 * Set required bits to one and zero according to the MSR capabilities.
1389 */
1390 val = pVM->hwaccm.s.vmx.msr.vmx_entry.n.disallowed0;
1391 /* 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) */
1392 val |= VMX_VMCS_CTRL_ENTRY_CONTROLS_LOAD_DEBUG;
1393 /* 64 bits guest mode? */
1394 if (CPUMIsGuestInLongModeEx(pCtx))
1395 val |= VMX_VMCS_CTRL_ENTRY_CONTROLS_IA64_MODE;
1396 /* else Must be zero when AMD64 is not available. */
1397
1398 /* Mask away the bits that the CPU doesn't support */
1399 val &= pVM->hwaccm.s.vmx.msr.vmx_entry.n.allowed1;
1400 rc = VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_CONTROLS, val);
1401 AssertRC(rc);
1402
1403 /* VMX_VMCS_CTRL_EXIT_CONTROLS
1404 * Set required bits to one and zero according to the MSR capabilities.
1405 */
1406 val = pVM->hwaccm.s.vmx.msr.vmx_exit.n.disallowed0;
1407
1408 /* Save debug controls (dr7 & IA32_DEBUGCTL_MSR) (forced to 1 on the 'first' VT-x capable CPUs; this actually includes the newest Nehalem CPUs) */
1409 val |= VMX_VMCS_CTRL_EXIT_CONTROLS_SAVE_DEBUG;
1410
1411#if HC_ARCH_BITS == 64 || defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1412 if (VMX_IS_64BIT_HOST_MODE())
1413 val |= VMX_VMCS_CTRL_EXIT_CONTROLS_HOST_AMD64;
1414 /* else: Must be zero when AMD64 is not available. */
1415#elif HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1416 if (CPUMIsGuestInLongModeEx(pCtx))
1417 val |= VMX_VMCS_CTRL_EXIT_CONTROLS_HOST_AMD64; /* our switcher goes to long mode */
1418 else
1419 Assert(!(val & VMX_VMCS_CTRL_EXIT_CONTROLS_HOST_AMD64));
1420#endif
1421 val &= pVM->hwaccm.s.vmx.msr.vmx_exit.n.allowed1;
1422 /* Don't acknowledge external interrupts on VM-exit. */
1423 rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXIT_CONTROLS, val);
1424 AssertRC(rc);
1425
1426 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1427 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_SEGMENT_REGS)
1428 {
1429 if (pVM->hwaccm.s.vmx.pRealModeTSS)
1430 {
1431 PGMMODE enmGuestMode = PGMGetGuestMode(pVCpu);
1432 if (pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode != enmGuestMode)
1433 {
1434 /* Correct weird requirements for switching to protected mode. */
1435 if ( pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode == PGMMODE_REAL
1436 && enmGuestMode >= PGMMODE_PROTECTED)
1437 {
1438#ifdef VBOX_WITH_REM
1439 /* Flush the recompiler code cache as it's not unlikely
1440 * the guest will rewrite code it will later execute in real
1441 * mode (OpenBSD 4.0 is one such example)
1442 */
1443 REMFlushTBs(pVM);
1444#endif
1445
1446 /* DPL of all hidden selector registers must match the current CPL (0). */
1447 pCtx->csHid.Attr.n.u2Dpl = 0;
1448 pCtx->csHid.Attr.n.u4Type = X86_SEL_TYPE_CODE | X86_SEL_TYPE_RW_ACC;
1449
1450 pCtx->dsHid.Attr.n.u2Dpl = 0;
1451 pCtx->esHid.Attr.n.u2Dpl = 0;
1452 pCtx->fsHid.Attr.n.u2Dpl = 0;
1453 pCtx->gsHid.Attr.n.u2Dpl = 0;
1454 pCtx->ssHid.Attr.n.u2Dpl = 0;
1455 }
1456 pVCpu->hwaccm.s.vmx.enmLastSeenGuestMode = enmGuestMode;
1457 }
1458 else
1459 /* VT-x will fail with a guest invalid state otherwise... (CPU state after a reset) */
1460 if ( CPUMIsGuestInRealModeEx(pCtx)
1461 && pCtx->csHid.u64Base == 0xffff0000)
1462 {
1463 pCtx->csHid.u64Base = 0xf0000;
1464 pCtx->cs = 0xf000;
1465 }
1466 }
1467
1468 VMX_WRITE_SELREG(ES, es);
1469 AssertRC(rc);
1470
1471 VMX_WRITE_SELREG(CS, cs);
1472 AssertRC(rc);
1473
1474 VMX_WRITE_SELREG(SS, ss);
1475 AssertRC(rc);
1476
1477 VMX_WRITE_SELREG(DS, ds);
1478 AssertRC(rc);
1479
1480 VMX_WRITE_SELREG(FS, fs);
1481 AssertRC(rc);
1482
1483 VMX_WRITE_SELREG(GS, gs);
1484 AssertRC(rc);
1485 }
1486
1487 /* Guest CPU context: LDTR. */
1488 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_LDTR)
1489 {
1490 if (pCtx->ldtr == 0)
1491 {
1492 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_LDTR, 0);
1493 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_LIMIT, 0);
1494 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_LDTR_BASE, 0);
1495 /* Note: vmlaunch will fail with 0 or just 0x02. No idea why. */
1496 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, 0x82 /* present, LDT */);
1497 }
1498 else
1499 {
1500 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_LDTR, pCtx->ldtr);
1501 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_LIMIT, pCtx->ldtrHid.u32Limit);
1502 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_LDTR_BASE, pCtx->ldtrHid.u64Base);
1503 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, pCtx->ldtrHid.Attr.u);
1504 }
1505 AssertRC(rc);
1506 }
1507 /* Guest CPU context: TR. */
1508 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_TR)
1509 {
1510 /* Real mode emulation using v86 mode with CR4.VME (interrupt redirection using the int bitmap in the TSS) */
1511 if ( CPUMIsGuestInRealModeEx(pCtx)
1512 && pVM->hwaccm.s.vmx.pRealModeTSS)
1513 {
1514 RTGCPHYS GCPhys;
1515
1516 /* We convert it here every time as pci regions could be reconfigured. */
1517 rc = PDMVMMDevHeapR3ToGCPhys(pVM, pVM->hwaccm.s.vmx.pRealModeTSS, &GCPhys);
1518 AssertRC(rc);
1519
1520 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_TR, 0);
1521 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_TR_LIMIT, HWACCM_VTX_TSS_SIZE);
1522 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_TR_BASE, GCPhys /* phys = virt in this mode */);
1523
1524 X86DESCATTR attr;
1525
1526 attr.u = 0;
1527 attr.n.u1Present = 1;
1528 attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
1529 val = attr.u;
1530 }
1531 else
1532 {
1533 rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_TR, pCtx->tr);
1534 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_TR_LIMIT, pCtx->trHid.u32Limit);
1535 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_TR_BASE, pCtx->trHid.u64Base);
1536
1537 val = pCtx->trHid.Attr.u;
1538
1539 /* The TSS selector must be busy (REM bugs? see defect #XXXX). */
1540 if (!(val & X86_SEL_TYPE_SYS_TSS_BUSY_MASK))
1541 {
1542 if (val & 0xf)
1543 val |= X86_SEL_TYPE_SYS_TSS_BUSY_MASK;
1544 else
1545 /* Default if no TR selector has been set (otherwise vmlaunch will fail!) */
1546 val = (val & ~0xF) | X86_SEL_TYPE_SYS_386_TSS_BUSY;
1547 }
1548 AssertMsg((val & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY || (val & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("%#x\n", val));
1549 }
1550 rc |= VMXWriteVMCS(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, val);
1551 AssertRC(rc);
1552 }
1553 /* Guest CPU context: GDTR. */
1554 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_GDTR)
1555 {
1556 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_GDTR_LIMIT, pCtx->gdtr.cbGdt);
1557 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_GDTR_BASE, pCtx->gdtr.pGdt);
1558 AssertRC(rc);
1559 }
1560 /* Guest CPU context: IDTR. */
1561 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_IDTR)
1562 {
1563 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_IDTR_LIMIT, pCtx->idtr.cbIdt);
1564 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_IDTR_BASE, pCtx->idtr.pIdt);
1565 AssertRC(rc);
1566 }
1567
1568 /*
1569 * Sysenter MSRs
1570 */
1571 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_MSR)
1572 {
1573 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_SYSENTER_CS, pCtx->SysEnter.cs);
1574 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_SYSENTER_EIP, pCtx->SysEnter.eip);
1575 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_SYSENTER_ESP, pCtx->SysEnter.esp);
1576 AssertRC(rc);
1577 }
1578
1579 /* Control registers */
1580 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR0)
1581 {
1582 val = pCtx->cr0;
1583 rc = VMXWriteVMCS(VMX_VMCS_CTRL_CR0_READ_SHADOW, val);
1584 Log2(("Guest CR0-shadow %08x\n", val));
1585 if (CPUMIsGuestFPUStateActive(pVCpu) == false)
1586 {
1587 /* Always use #NM exceptions to load the FPU/XMM state on demand. */
1588 val |= X86_CR0_TS | X86_CR0_ET | X86_CR0_NE | X86_CR0_MP;
1589 }
1590 else
1591 {
1592 /** @todo check if we support the old style mess correctly. */
1593 if (!(val & X86_CR0_NE))
1594 Log(("Forcing X86_CR0_NE!!!\n"));
1595
1596 val |= X86_CR0_NE; /* always turn on the native mechanism to report FPU errors (old style uses interrupts) */
1597 }
1598 /* Note: protected mode & paging are always enabled; we use them for emulating real and protected mode without paging too. */
1599 if (!pVM->hwaccm.s.vmx.fUnrestrictedGuest)
1600 val |= X86_CR0_PE | X86_CR0_PG;
1601
1602 if (pVM->hwaccm.s.fNestedPaging)
1603 {
1604 if (CPUMIsGuestInPagedProtectedModeEx(pCtx))
1605 {
1606 /* Disable cr3 read/write monitoring as we don't need it for EPT. */
1607 pVCpu->hwaccm.s.vmx.proc_ctls &= ~( VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
1608 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT);
1609 }
1610 else
1611 {
1612 /* Reenable cr3 read/write monitoring as our identity mapped page table is active. */
1613 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
1614 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT;
1615 }
1616 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1617 AssertRC(rc);
1618 }
1619 else
1620 {
1621 /* Note: We must also set this as we rely on protecting various pages for which supervisor writes must be caught. */
1622 val |= X86_CR0_WP;
1623 }
1624
1625 /* Always enable caching. */
1626 val &= ~(X86_CR0_CD|X86_CR0_NW);
1627
1628 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_CR0, val);
1629 Log2(("Guest CR0 %08x\n", val));
1630 /* CR0 flags owned by the host; if the guests attempts to change them, then
1631 * the VM will exit.
1632 */
1633 val = X86_CR0_PE /* Must monitor this bit (assumptions are made for real mode emulation) */
1634 | X86_CR0_WP /* Must monitor this bit (it must always be enabled). */
1635 | X86_CR0_PG /* Must monitor this bit (assumptions are made for real mode & protected mode without paging emulation) */
1636 | X86_CR0_CD /* Bit not restored during VM-exit! */
1637 | X86_CR0_NW /* Bit not restored during VM-exit! */
1638 | X86_CR0_NE;
1639
1640 /* When the guest's FPU state is active, then we no longer care about
1641 * the FPU related bits.
1642 */
1643 if (CPUMIsGuestFPUStateActive(pVCpu) == false)
1644 val |= X86_CR0_TS | X86_CR0_ET | X86_CR0_MP;
1645
1646 pVCpu->hwaccm.s.vmx.cr0_mask = val;
1647
1648 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_CR0_MASK, val);
1649 Log2(("Guest CR0-mask %08x\n", val));
1650 AssertRC(rc);
1651 }
1652 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR4)
1653 {
1654 /* CR4 */
1655 rc = VMXWriteVMCS(VMX_VMCS_CTRL_CR4_READ_SHADOW, pCtx->cr4);
1656 Log2(("Guest CR4-shadow %08x\n", pCtx->cr4));
1657 /* Set the required bits in cr4 too (currently X86_CR4_VMXE). */
1658 val = pCtx->cr4 | (uint32_t)pVM->hwaccm.s.vmx.msr.vmx_cr4_fixed0;
1659
1660 if (!pVM->hwaccm.s.fNestedPaging)
1661 {
1662 switch(pVCpu->hwaccm.s.enmShadowMode)
1663 {
1664 case PGMMODE_REAL: /* Real mode -> emulated using v86 mode */
1665 case PGMMODE_PROTECTED: /* Protected mode, no paging -> emulated using identity mapping. */
1666 case PGMMODE_32_BIT: /* 32-bit paging. */
1667 val &= ~X86_CR4_PAE;
1668 break;
1669
1670 case PGMMODE_PAE: /* PAE paging. */
1671 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1672 /** Must use PAE paging as we could use physical memory > 4 GB */
1673 val |= X86_CR4_PAE;
1674 break;
1675
1676 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1677 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1678#ifdef VBOX_ENABLE_64_BITS_GUESTS
1679 break;
1680#else
1681 AssertFailed();
1682 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1683#endif
1684 default: /* shut up gcc */
1685 AssertFailed();
1686 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1687 }
1688 }
1689 else
1690 if ( !CPUMIsGuestInPagedProtectedModeEx(pCtx)
1691 && !pVM->hwaccm.s.vmx.fUnrestrictedGuest)
1692 {
1693 /* We use 4 MB pages in our identity mapping page table for real and protected mode without paging. */
1694 val |= X86_CR4_PSE;
1695 /* Our identity mapping is a 32 bits page directory. */
1696 val &= ~X86_CR4_PAE;
1697 }
1698
1699 /* Turn off VME if we're in emulated real mode. */
1700 if ( CPUMIsGuestInRealModeEx(pCtx)
1701 && pVM->hwaccm.s.vmx.pRealModeTSS)
1702 val &= ~X86_CR4_VME;
1703
1704 rc |= VMXWriteVMCS64(VMX_VMCS64_GUEST_CR4, val);
1705 Log2(("Guest CR4 %08x\n", val));
1706 /* CR4 flags owned by the host; if the guests attempts to change them, then
1707 * the VM will exit.
1708 */
1709 val = 0
1710 | X86_CR4_VME
1711 | X86_CR4_PAE
1712 | X86_CR4_PGE
1713 | X86_CR4_PSE
1714 | X86_CR4_VMXE;
1715 pVCpu->hwaccm.s.vmx.cr4_mask = val;
1716
1717 rc |= VMXWriteVMCS(VMX_VMCS_CTRL_CR4_MASK, val);
1718 Log2(("Guest CR4-mask %08x\n", val));
1719 AssertRC(rc);
1720 }
1721
1722 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR3)
1723 {
1724 if (pVM->hwaccm.s.fNestedPaging)
1725 {
1726 Assert(PGMGetHyperCR3(pVCpu));
1727 pVCpu->hwaccm.s.vmx.GCPhysEPTP = PGMGetHyperCR3(pVCpu);
1728
1729 Assert(!(pVCpu->hwaccm.s.vmx.GCPhysEPTP & 0xfff));
1730 /** @todo Check the IA32_VMX_EPT_VPID_CAP MSR for other supported memory types. */
1731 pVCpu->hwaccm.s.vmx.GCPhysEPTP |= VMX_EPT_MEMTYPE_WB
1732 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
1733
1734 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_EPTP_FULL, pVCpu->hwaccm.s.vmx.GCPhysEPTP);
1735 AssertRC(rc);
1736
1737 if ( !CPUMIsGuestInPagedProtectedModeEx(pCtx)
1738 && !pVM->hwaccm.s.vmx.fUnrestrictedGuest)
1739 {
1740 RTGCPHYS GCPhys;
1741
1742 /* We convert it here every time as pci regions could be reconfigured. */
1743 rc = PDMVMMDevHeapR3ToGCPhys(pVM, pVM->hwaccm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
1744 AssertMsgRC(rc, ("pNonPagingModeEPTPageTable = %RGv\n", pVM->hwaccm.s.vmx.pNonPagingModeEPTPageTable));
1745
1746 /* We use our identity mapping page table here as we need to map guest virtual to guest physical addresses; EPT will
1747 * take care of the translation to host physical addresses.
1748 */
1749 val = GCPhys;
1750 }
1751 else
1752 {
1753 /* Save the real guest CR3 in VMX_VMCS_GUEST_CR3 */
1754 val = pCtx->cr3;
1755 rc = hmR0VmxLoadPaePdpes(pVCpu, pCtx);
1756 AssertRCReturn(rc, rc);
1757 }
1758 }
1759 else
1760 {
1761 val = PGMGetHyperCR3(pVCpu);
1762 Assert(val || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
1763 }
1764
1765 /* Save our shadow CR3 register. */
1766 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_CR3, val);
1767 AssertRC(rc);
1768 }
1769
1770 /* Debug registers. */
1771 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_DEBUG)
1772 {
1773 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* set all reserved bits to 1. */
1774 pCtx->dr[6] &= ~RT_BIT(12); /* must be zero. */
1775
1776 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
1777 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
1778 pCtx->dr[7] |= 0x400; /* must be one */
1779
1780 /* Resync DR7 */
1781 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, pCtx->dr[7]);
1782 AssertRC(rc);
1783
1784#ifdef DEBUG
1785 /* Sync the hypervisor debug state now if any breakpoint is armed. */
1786 if ( CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK|X86_DR7_GD)
1787 && !CPUMIsHyperDebugStateActive(pVCpu)
1788 && !DBGFIsStepping(pVCpu))
1789 {
1790 /* Save the host and load the hypervisor debug state. */
1791 rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1792 AssertRC(rc);
1793
1794 /* DRx intercepts remain enabled. */
1795
1796 /* Override dr7 with the hypervisor value. */
1797 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, CPUMGetHyperDR7(pVCpu));
1798 AssertRC(rc);
1799 }
1800 else
1801#endif
1802 /* Sync the debug state now if any breakpoint is armed. */
1803 if ( (pCtx->dr[7] & (X86_DR7_ENABLED_MASK|X86_DR7_GD))
1804 && !CPUMIsGuestDebugStateActive(pVCpu)
1805 && !DBGFIsStepping(pVCpu))
1806 {
1807 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxArmed);
1808
1809 /* Disable drx move intercepts. */
1810 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT;
1811 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1812 AssertRC(rc);
1813
1814 /* Save the host and load the guest debug state. */
1815 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1816 AssertRC(rc);
1817 }
1818
1819 /* IA32_DEBUGCTL MSR. */
1820 rc = VMXWriteVMCS64(VMX_VMCS_GUEST_DEBUGCTL_FULL, 0);
1821 AssertRC(rc);
1822
1823 /** @todo do we really ever need this? */
1824 rc |= VMXWriteVMCS(VMX_VMCS_GUEST_DEBUG_EXCEPTIONS, 0);
1825 AssertRC(rc);
1826 }
1827
1828 /* 64 bits guest mode? */
1829 if (CPUMIsGuestInLongModeEx(pCtx))
1830 {
1831#if !defined(VBOX_ENABLE_64_BITS_GUESTS)
1832 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1833#elif HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1834 pVCpu->hwaccm.s.vmx.pfnStartVM = VMXR0SwitcherStartVM64;
1835#else
1836# ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1837 if (!pVM->hwaccm.s.fAllow64BitGuests)
1838 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1839# endif
1840 pVCpu->hwaccm.s.vmx.pfnStartVM = VMXR0StartVM64;
1841#endif
1842 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_MSR)
1843 {
1844 /* Update these as wrmsr might have changed them. */
1845 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_FS_BASE, pCtx->fsHid.u64Base);
1846 AssertRC(rc);
1847 rc = VMXWriteVMCS64(VMX_VMCS64_GUEST_GS_BASE, pCtx->gsHid.u64Base);
1848 AssertRC(rc);
1849 }
1850 }
1851 else
1852 {
1853 pVCpu->hwaccm.s.vmx.pfnStartVM = VMXR0StartVM32;
1854 }
1855
1856 hmR0VmxUpdateExceptionBitmap(pVM, pVCpu, pCtx);
1857
1858#ifdef VBOX_WITH_AUTO_MSR_LOAD_RESTORE
1859 /* Store all guest MSRs in the VM-Entry load area, so they will be loaded during the world switch. */
1860 PVMXMSR pMsr = (PVMXMSR)pVCpu->hwaccm.s.vmx.pGuestMSR;
1861 unsigned idxMsr = 0;
1862
1863 uint32_t ulEdx;
1864 uint32_t ulTemp;
1865 CPUMGetGuestCpuId(pVCpu, 0x80000001, &ulTemp, &ulTemp, &ulTemp, &ulEdx);
1866 /* EFER MSR present? */
1867 if (ulEdx & (X86_CPUID_AMD_FEATURE_EDX_NX|X86_CPUID_AMD_FEATURE_EDX_LONG_MODE))
1868 {
1869 pMsr->u32IndexMSR = MSR_K6_EFER;
1870 pMsr->u32Reserved = 0;
1871 pMsr->u64Value = pCtx->msrEFER;
1872 /* VT-x will complain if only MSR_K6_EFER_LME is set. */
1873 if (!CPUMIsGuestInLongModeEx(pCtx))
1874 pMsr->u64Value &= ~(MSR_K6_EFER_LMA|MSR_K6_EFER_LME);
1875 pMsr++; idxMsr++;
1876
1877 if (ulEdx & X86_CPUID_AMD_FEATURE_EDX_LONG_MODE)
1878 {
1879 pMsr->u32IndexMSR = MSR_K8_LSTAR;
1880 pMsr->u32Reserved = 0;
1881 pMsr->u64Value = pCtx->msrLSTAR; /* 64 bits mode syscall rip */
1882 pMsr++; idxMsr++;
1883 pMsr->u32IndexMSR = MSR_K6_STAR;
1884 pMsr->u32Reserved = 0;
1885 pMsr->u64Value = pCtx->msrSTAR; /* legacy syscall eip, cs & ss */
1886 pMsr++; idxMsr++;
1887 pMsr->u32IndexMSR = MSR_K8_SF_MASK;
1888 pMsr->u32Reserved = 0;
1889 pMsr->u64Value = pCtx->msrSFMASK; /* syscall flag mask */
1890 pMsr++; idxMsr++;
1891 pMsr->u32IndexMSR = MSR_K8_KERNEL_GS_BASE;
1892 pMsr->u32Reserved = 0;
1893 pMsr->u64Value = pCtx->msrKERNELGSBASE; /* swapgs exchange value */
1894 pMsr++; idxMsr++;
1895 }
1896 }
1897 pVCpu->hwaccm.s.vmx.cCachedMSRs = idxMsr;
1898
1899 rc = VMXWriteVMCS(VMX_VMCS_CTRL_ENTRY_MSR_LOAD_COUNT, idxMsr);
1900 AssertRC(rc);
1901
1902 rc = VMXWriteVMCS(VMX_VMCS_CTRL_EXIT_MSR_STORE_COUNT, idxMsr);
1903 AssertRC(rc);
1904#endif /* VBOX_WITH_AUTO_MSR_LOAD_RESTORE */
1905
1906 bool fOffsettedTsc;
1907 if (pVM->hwaccm.s.vmx.fUsePreemptTimer)
1908 {
1909 uint64_t cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVCpu, &fOffsettedTsc, &pVCpu->hwaccm.s.vmx.u64TSCOffset);
1910
1911 /* Make sure the returned values have sane upper and lower boundaries. */
1912 uint64_t u64CpuHz = SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage);
1913
1914 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64 of a second */
1915 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 2048); /* 1/2048th of a second */
1916
1917 cTicksToDeadline >>= pVM->hwaccm.s.vmx.cPreemptTimerShift;
1918 uint32_t cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
1919 rc = VMXWriteVMCS(VMX_VMCS32_GUEST_PREEMPTION_TIMER_VALUE, cPreemptionTickCount);
1920 AssertRC(rc);
1921 }
1922 else
1923 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVCpu, &pVCpu->hwaccm.s.vmx.u64TSCOffset);
1924 if (fOffsettedTsc)
1925 {
1926 uint64_t u64CurTSC = ASMReadTSC();
1927 if (u64CurTSC + pVCpu->hwaccm.s.vmx.u64TSCOffset >= TMCpuTickGetLastSeen(pVCpu))
1928 {
1929 /* Note: VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT takes precedence over TSC_OFFSET */
1930 rc = VMXWriteVMCS64(VMX_VMCS_CTRL_TSC_OFFSET_FULL, pVCpu->hwaccm.s.vmx.u64TSCOffset);
1931 AssertRC(rc);
1932
1933 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT;
1934 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1935 AssertRC(rc);
1936 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCOffset);
1937 }
1938 else
1939 {
1940 /* Fall back to rdtsc emulation as we would otherwise pass decreasing tsc values to the guest. */
1941 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)));
1942 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT;
1943 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1944 AssertRC(rc);
1945 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCInterceptOverFlow);
1946 }
1947 }
1948 else
1949 {
1950 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT;
1951 rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
1952 AssertRC(rc);
1953 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCIntercept);
1954 }
1955
1956 /* Done with the major changes */
1957 pVCpu->hwaccm.s.fContextUseFlags &= ~HWACCM_CHANGED_ALL_GUEST;
1958
1959 /* Minimal guest state update (esp, eip, eflags mostly) */
1960 VMXR0LoadMinimalGuestState(pVM, pVCpu, pCtx);
1961 return rc;
1962}
1963
1964/**
1965 * Syncs back the guest state
1966 *
1967 * @returns VBox status code.
1968 * @param pVM The VM to operate on.
1969 * @param pVCpu The VMCPU to operate on.
1970 * @param pCtx Guest context
1971 */
1972DECLINLINE(int) VMXR0SaveGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1973{
1974 RTGCUINTREG val, valShadow;
1975 RTGCUINTPTR uInterruptState;
1976 int rc;
1977
1978 /* Let's first sync back eip, esp, and eflags. */
1979 rc = VMXReadCachedVMCS(VMX_VMCS64_GUEST_RIP, &val);
1980 AssertRC(rc);
1981 pCtx->rip = val;
1982 rc = VMXReadCachedVMCS(VMX_VMCS64_GUEST_RSP, &val);
1983 AssertRC(rc);
1984 pCtx->rsp = val;
1985 rc = VMXReadCachedVMCS(VMX_VMCS_GUEST_RFLAGS, &val);
1986 AssertRC(rc);
1987 pCtx->eflags.u32 = val;
1988
1989 /* Take care of instruction fusing (sti, mov ss) */
1990 rc |= VMXReadCachedVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &val);
1991 uInterruptState = val;
1992 if (uInterruptState != 0)
1993 {
1994 Assert(uInterruptState <= 2); /* only sti & mov ss */
1995 Log(("uInterruptState %x eip=%RGv\n", (uint32_t)uInterruptState, pCtx->rip));
1996 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip);
1997 }
1998 else
1999 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2000
2001 /* Control registers. */
2002 VMXReadCachedVMCS(VMX_VMCS_CTRL_CR0_READ_SHADOW, &valShadow);
2003 VMXReadCachedVMCS(VMX_VMCS64_GUEST_CR0, &val);
2004 val = (valShadow & pVCpu->hwaccm.s.vmx.cr0_mask) | (val & ~pVCpu->hwaccm.s.vmx.cr0_mask);
2005 CPUMSetGuestCR0(pVCpu, val);
2006
2007 VMXReadCachedVMCS(VMX_VMCS_CTRL_CR4_READ_SHADOW, &valShadow);
2008 VMXReadCachedVMCS(VMX_VMCS64_GUEST_CR4, &val);
2009 val = (valShadow & pVCpu->hwaccm.s.vmx.cr4_mask) | (val & ~pVCpu->hwaccm.s.vmx.cr4_mask);
2010 CPUMSetGuestCR4(pVCpu, val);
2011
2012 /* Note: no reason to sync back the CRx registers. They can't be changed by the guest. */
2013 /* Note: only in the nested paging case can CR3 & CR4 be changed by the guest. */
2014 if ( pVM->hwaccm.s.fNestedPaging
2015 && CPUMIsGuestInPagedProtectedModeEx(pCtx)) /** @todo check if we will always catch mode switches and such... */
2016 {
2017 PVMCSCACHE pCache = &pVCpu->hwaccm.s.vmx.VMCSCache;
2018
2019 /* Can be updated behind our back in the nested paging case. */
2020 CPUMSetGuestCR2(pVCpu, pCache->cr2);
2021
2022 VMXReadCachedVMCS(VMX_VMCS64_GUEST_CR3, &val);
2023
2024 if (val != pCtx->cr3)
2025 {
2026 CPUMSetGuestCR3(pVCpu, val);
2027 PGMUpdateCR3(pVCpu, val);
2028 }
2029 rc = hmR0VmxSavePaePdpes(pVCpu, pCtx);
2030 AssertRCReturn(rc, rc);
2031 }
2032
2033 /* Sync back DR7 here. */
2034 VMXReadCachedVMCS(VMX_VMCS64_GUEST_DR7, &val);
2035 pCtx->dr[7] = val;
2036
2037 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
2038 VMX_READ_SELREG(ES, es);
2039 VMX_READ_SELREG(SS, ss);
2040 VMX_READ_SELREG(CS, cs);
2041 VMX_READ_SELREG(DS, ds);
2042 VMX_READ_SELREG(FS, fs);
2043 VMX_READ_SELREG(GS, gs);
2044
2045 /*
2046 * System MSRs
2047 */
2048 VMXReadCachedVMCS(VMX_VMCS32_GUEST_SYSENTER_CS, &val);
2049 pCtx->SysEnter.cs = val;
2050 VMXReadCachedVMCS(VMX_VMCS64_GUEST_SYSENTER_EIP, &val);
2051 pCtx->SysEnter.eip = val;
2052 VMXReadCachedVMCS(VMX_VMCS64_GUEST_SYSENTER_ESP, &val);
2053 pCtx->SysEnter.esp = val;
2054
2055 /* Misc. registers; must sync everything otherwise we can get out of sync when jumping to ring 3. */
2056 VMX_READ_SELREG(LDTR, ldtr);
2057
2058 VMXReadCachedVMCS(VMX_VMCS32_GUEST_GDTR_LIMIT, &val);
2059 pCtx->gdtr.cbGdt = val;
2060 VMXReadCachedVMCS(VMX_VMCS64_GUEST_GDTR_BASE, &val);
2061 pCtx->gdtr.pGdt = val;
2062
2063 VMXReadCachedVMCS(VMX_VMCS32_GUEST_IDTR_LIMIT, &val);
2064 pCtx->idtr.cbIdt = val;
2065 VMXReadCachedVMCS(VMX_VMCS64_GUEST_IDTR_BASE, &val);
2066 pCtx->idtr.pIdt = val;
2067
2068 /* Real mode emulation using v86 mode. */
2069 if ( CPUMIsGuestInRealModeEx(pCtx)
2070 && pVM->hwaccm.s.vmx.pRealModeTSS)
2071 {
2072 /* Hide our emulation flags */
2073 pCtx->eflags.Bits.u1VM = 0;
2074
2075 /* Restore original IOPL setting as we always use 0. */
2076 pCtx->eflags.Bits.u2IOPL = pVCpu->hwaccm.s.vmx.RealMode.eflags.Bits.u2IOPL;
2077
2078 /* Force a TR resync every time in case we switch modes. */
2079 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_TR;
2080 }
2081 else
2082 {
2083 /* In real mode we have a fake TSS, so only sync it back when it's supposed to be valid. */
2084 VMX_READ_SELREG(TR, tr);
2085 }
2086
2087#ifdef VBOX_WITH_AUTO_MSR_LOAD_RESTORE
2088 /* Save the possibly changed MSRs that we automatically restore and save during a world switch. */
2089 for (unsigned i = 0; i < pVCpu->hwaccm.s.vmx.cCachedMSRs; i++)
2090 {
2091 PVMXMSR pMsr = (PVMXMSR)pVCpu->hwaccm.s.vmx.pGuestMSR;
2092 pMsr += i;
2093
2094 switch (pMsr->u32IndexMSR)
2095 {
2096 case MSR_K8_LSTAR:
2097 pCtx->msrLSTAR = pMsr->u64Value;
2098 break;
2099 case MSR_K6_STAR:
2100 pCtx->msrSTAR = pMsr->u64Value;
2101 break;
2102 case MSR_K8_SF_MASK:
2103 pCtx->msrSFMASK = pMsr->u64Value;
2104 break;
2105 case MSR_K8_KERNEL_GS_BASE:
2106 pCtx->msrKERNELGSBASE = pMsr->u64Value;
2107 break;
2108 case MSR_K6_EFER:
2109 /* EFER can't be changed without causing a VM-exit. */
2110// Assert(pCtx->msrEFER == pMsr->u64Value);
2111 break;
2112 default:
2113 AssertFailed();
2114 return VERR_HM_UNEXPECTED_LD_ST_MSR;
2115 }
2116 }
2117#endif /* VBOX_WITH_AUTO_MSR_LOAD_RESTORE */
2118 return VINF_SUCCESS;
2119}
2120
2121/**
2122 * Dummy placeholder
2123 *
2124 * @param pVM The VM to operate on.
2125 * @param pVCpu The VMCPU to operate on.
2126 */
2127static DECLCALLBACK(void) hmR0VmxSetupTLBDummy(PVM pVM, PVMCPU pVCpu)
2128{
2129 NOREF(pVM);
2130 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2131 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
2132 pVCpu->hwaccm.s.TlbShootdown.cPages = 0;
2133 return;
2134}
2135
2136/**
2137 * Setup the tagged TLB for EPT
2138 *
2139 * @returns VBox status code.
2140 * @param pVM The VM to operate on.
2141 * @param pVCpu The VMCPU to operate on.
2142 */
2143static DECLCALLBACK(void) hmR0VmxSetupTLBEPT(PVM pVM, PVMCPU pVCpu)
2144{
2145 PHMGLOBLCPUINFO pCpu;
2146
2147 Assert(pVM->hwaccm.s.fNestedPaging);
2148 Assert(!pVM->hwaccm.s.vmx.fVPID);
2149
2150 /* Deal with tagged TLBs if VPID or EPT is supported. */
2151 pCpu = HWACCMR0GetCurrentCpu();
2152 /* Force a TLB flush for the first world switch if the current cpu differs from the one we ran on last. */
2153 /* Note that this can happen both for start and resume due to long jumps back to ring 3. */
2154 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
2155 /* if the tlb flush count has changed, another VM has flushed the TLB of this cpu, so we can't use our current ASID anymore. */
2156 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
2157 {
2158 /* Force a TLB flush on VM entry. */
2159 pVCpu->hwaccm.s.fForceTLBFlush = true;
2160 }
2161 /* Disabled because this has triggered every time I have suspended my
2162 * laptop with a VM running for the past three months or more. */
2163 // else
2164 // Assert(!pCpu->fFlushTLB);
2165
2166 /* Check for tlb shootdown flushes. */
2167 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2168 pVCpu->hwaccm.s.fForceTLBFlush = true;
2169
2170 pVCpu->hwaccm.s.idLastCpu = pCpu->idCpu;
2171 pCpu->fFlushTLB = false;
2172
2173 if (pVCpu->hwaccm.s.fForceTLBFlush)
2174 {
2175 hmR0VmxFlushEPT(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushContext, 0);
2176 }
2177 else
2178 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
2179 {
2180 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
2181 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTlbShootdown);
2182
2183 for (unsigned i=0;i<pVCpu->hwaccm.s.TlbShootdown.cPages;i++)
2184 {
2185 /* aTlbShootdownPages contains physical addresses in this case. */
2186 hmR0VmxFlushEPT(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushPage, pVCpu->hwaccm.s.TlbShootdown.aPages[i]);
2187 }
2188 }
2189 pVCpu->hwaccm.s.TlbShootdown.cPages= 0;
2190 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
2191
2192#ifdef VBOX_WITH_STATISTICS
2193 if (pVCpu->hwaccm.s.fForceTLBFlush)
2194 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBWorldSwitch);
2195 else
2196 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatNoFlushTLBWorldSwitch);
2197#endif
2198}
2199
2200#ifdef HWACCM_VTX_WITH_VPID
2201/**
2202 * Setup the tagged TLB for VPID
2203 *
2204 * @returns VBox status code.
2205 * @param pVM The VM to operate on.
2206 * @param pVCpu The VMCPU to operate on.
2207 */
2208static DECLCALLBACK(void) hmR0VmxSetupTLBVPID(PVM pVM, PVMCPU pVCpu)
2209{
2210 PHMGLOBLCPUINFO pCpu;
2211
2212 Assert(pVM->hwaccm.s.vmx.fVPID);
2213 Assert(!pVM->hwaccm.s.fNestedPaging);
2214
2215 /* Deal with tagged TLBs if VPID or EPT is supported. */
2216 pCpu = HWACCMR0GetCurrentCpu();
2217 /* Force a TLB flush for the first world switch if the current cpu differs from the one we ran on last. */
2218 /* Note that this can happen both for start and resume due to long jumps back to ring 3. */
2219 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
2220 /* 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. */
2221 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
2222 {
2223 /* Force a TLB flush on VM entry. */
2224 pVCpu->hwaccm.s.fForceTLBFlush = true;
2225 }
2226 else
2227 Assert(!pCpu->fFlushTLB);
2228
2229 pVCpu->hwaccm.s.idLastCpu = pCpu->idCpu;
2230
2231 /* Check for tlb shootdown flushes. */
2232 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2233 pVCpu->hwaccm.s.fForceTLBFlush = true;
2234
2235 /* 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). */
2236 if (pVCpu->hwaccm.s.fForceTLBFlush)
2237 {
2238 if ( ++pCpu->uCurrentASID >= pVM->hwaccm.s.uMaxASID
2239 || pCpu->fFlushTLB)
2240 {
2241 pCpu->fFlushTLB = false;
2242 pCpu->uCurrentASID = 1; /* start at 1; host uses 0 */
2243 pCpu->cTLBFlushes++;
2244 hmR0VmxFlushVPID(pVM, pVCpu, VMX_FLUSH_ALL_CONTEXTS, 0);
2245 }
2246 else
2247 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushASID);
2248
2249 pVCpu->hwaccm.s.fForceTLBFlush = false;
2250 pVCpu->hwaccm.s.cTLBFlushes = pCpu->cTLBFlushes;
2251 pVCpu->hwaccm.s.uCurrentASID = pCpu->uCurrentASID;
2252 }
2253 else
2254 {
2255 Assert(!pCpu->fFlushTLB);
2256 Assert(pVCpu->hwaccm.s.uCurrentASID && pCpu->uCurrentASID);
2257
2258 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
2259 {
2260 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
2261 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTlbShootdown);
2262 for (unsigned i = 0; i < pVCpu->hwaccm.s.TlbShootdown.cPages; i++)
2263 hmR0VmxFlushVPID(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushPage, pVCpu->hwaccm.s.TlbShootdown.aPages[i]);
2264 }
2265 }
2266 pVCpu->hwaccm.s.TlbShootdown.cPages = 0;
2267 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
2268
2269 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));
2270 AssertMsg(pCpu->uCurrentASID >= 1 && pCpu->uCurrentASID < pVM->hwaccm.s.uMaxASID, ("cpu%d uCurrentASID = %x\n", pCpu->idCpu, pCpu->uCurrentASID));
2271 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));
2272
2273 int rc = VMXWriteVMCS(VMX_VMCS16_GUEST_FIELD_VPID, pVCpu->hwaccm.s.uCurrentASID);
2274 AssertRC(rc);
2275
2276 if (pVCpu->hwaccm.s.fForceTLBFlush)
2277 hmR0VmxFlushVPID(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushContext, 0);
2278
2279# ifdef VBOX_WITH_STATISTICS
2280 if (pVCpu->hwaccm.s.fForceTLBFlush)
2281 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBWorldSwitch);
2282 else
2283 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatNoFlushTLBWorldSwitch);
2284# endif
2285}
2286#endif /* HWACCM_VTX_WITH_VPID */
2287
2288/**
2289 * Runs guest code in a VT-x VM.
2290 *
2291 * @returns VBox status code.
2292 * @param pVM The VM to operate on.
2293 * @param pVCpu The VMCPU to operate on.
2294 * @param pCtx Guest context
2295 */
2296VMMR0DECL(int) VMXR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2297{
2298 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatEntry, x);
2299 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hwaccm.s.StatExit1);
2300 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hwaccm.s.StatExit2);
2301
2302 VBOXSTRICTRC rc = VINF_SUCCESS;
2303 int rc2;
2304 RTGCUINTREG val;
2305 RTGCUINTREG exitReason = (RTGCUINTREG)VMX_EXIT_INVALID;
2306 RTGCUINTREG instrError, cbInstr;
2307 RTGCUINTPTR exitQualification = 0;
2308 RTGCUINTPTR intInfo = 0; /* shut up buggy gcc 4 */
2309 RTGCUINTPTR errCode, instrInfo;
2310 bool fSetupTPRCaching = false;
2311 uint64_t u64OldLSTAR = 0;
2312 uint8_t u8LastTPR = 0;
2313 RTCCUINTREG uOldEFlags = ~(RTCCUINTREG)0;
2314 unsigned cResume = 0;
2315#ifdef VBOX_STRICT
2316 RTCPUID idCpuCheck;
2317 bool fWasInLongMode = false;
2318#endif
2319#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
2320 uint64_t u64LastTime = RTTimeMilliTS();
2321#endif
2322
2323 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));
2324
2325 /* Check if we need to use TPR shadowing. */
2326 if ( CPUMIsGuestInLongModeEx(pCtx)
2327 || ( ((pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC) || pVM->hwaccm.s.fTRPPatchingAllowed)
2328 && pVM->hwaccm.s.fHasIoApic)
2329 )
2330 {
2331 fSetupTPRCaching = true;
2332 }
2333
2334 Log2(("\nE"));
2335
2336#ifdef VBOX_STRICT
2337 {
2338 RTCCUINTREG val2;
2339
2340 rc2 = VMXReadVMCS(VMX_VMCS_CTRL_PIN_EXEC_CONTROLS, &val2);
2341 AssertRC(rc2);
2342 Log2(("VMX_VMCS_CTRL_PIN_EXEC_CONTROLS = %08x\n", val2));
2343
2344 /* allowed zero */
2345 if ((val2 & pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.disallowed0)
2346 Log(("Invalid VMX_VMCS_CTRL_PIN_EXEC_CONTROLS: zero\n"));
2347
2348 /* allowed one */
2349 if ((val2 & ~pVM->hwaccm.s.vmx.msr.vmx_pin_ctls.n.allowed1) != 0)
2350 Log(("Invalid VMX_VMCS_CTRL_PIN_EXEC_CONTROLS: one\n"));
2351
2352 rc2 = VMXReadVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, &val2);
2353 AssertRC(rc2);
2354 Log2(("VMX_VMCS_CTRL_PROC_EXEC_CONTROLS = %08x\n", val2));
2355
2356 /* Must be set according to the MSR, but can be cleared in case of EPT. */
2357 if (pVM->hwaccm.s.fNestedPaging)
2358 val2 |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_INVLPG_EXIT
2359 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_LOAD_EXIT
2360 | VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_CR3_STORE_EXIT;
2361
2362 /* allowed zero */
2363 if ((val2 & pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.disallowed0)
2364 Log(("Invalid VMX_VMCS_CTRL_PROC_EXEC_CONTROLS: zero\n"));
2365
2366 /* allowed one */
2367 if ((val2 & ~pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1) != 0)
2368 Log(("Invalid VMX_VMCS_CTRL_PROC_EXEC_CONTROLS: one\n"));
2369
2370 rc2 = VMXReadVMCS(VMX_VMCS_CTRL_ENTRY_CONTROLS, &val2);
2371 AssertRC(rc2);
2372 Log2(("VMX_VMCS_CTRL_ENTRY_CONTROLS = %08x\n", val2));
2373
2374 /* allowed zero */
2375 if ((val2 & pVM->hwaccm.s.vmx.msr.vmx_entry.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_entry.n.disallowed0)
2376 Log(("Invalid VMX_VMCS_CTRL_ENTRY_CONTROLS: zero\n"));
2377
2378 /* allowed one */
2379 if ((val2 & ~pVM->hwaccm.s.vmx.msr.vmx_entry.n.allowed1) != 0)
2380 Log(("Invalid VMX_VMCS_CTRL_ENTRY_CONTROLS: one\n"));
2381
2382 rc2 = VMXReadVMCS(VMX_VMCS_CTRL_EXIT_CONTROLS, &val2);
2383 AssertRC(rc2);
2384 Log2(("VMX_VMCS_CTRL_EXIT_CONTROLS = %08x\n", val2));
2385
2386 /* allowed zero */
2387 if ((val2 & pVM->hwaccm.s.vmx.msr.vmx_exit.n.disallowed0) != pVM->hwaccm.s.vmx.msr.vmx_exit.n.disallowed0)
2388 Log(("Invalid VMX_VMCS_CTRL_EXIT_CONTROLS: zero\n"));
2389
2390 /* allowed one */
2391 if ((val2 & ~pVM->hwaccm.s.vmx.msr.vmx_exit.n.allowed1) != 0)
2392 Log(("Invalid VMX_VMCS_CTRL_EXIT_CONTROLS: one\n"));
2393 }
2394 fWasInLongMode = CPUMIsGuestInLongModeEx(pCtx);
2395#endif /* VBOX_STRICT */
2396
2397#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2398 pVCpu->hwaccm.s.vmx.VMCSCache.u64TimeEntry = RTTimeNanoTS();
2399#endif
2400
2401 /* We can jump to this point to resume execution after determining that a VM-exit is innocent.
2402 */
2403ResumeExecution:
2404 if (!STAM_REL_PROFILE_ADV_IS_RUNNING(&pVCpu->hwaccm.s.StatEntry))
2405 STAM_REL_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatExit2, &pVCpu->hwaccm.s.StatEntry, x);
2406 AssertMsg(pVCpu->hwaccm.s.idEnteredCpu == RTMpCpuId(),
2407 ("Expected %d, I'm %d; cResume=%d exitReason=%RGv exitQualification=%RGv\n",
2408 (int)pVCpu->hwaccm.s.idEnteredCpu, (int)RTMpCpuId(), cResume, exitReason, exitQualification));
2409 Assert(!HWACCMR0SuspendPending());
2410 /* Not allowed to switch modes without reloading the host state (32->64 switcher)!! */
2411 Assert(fWasInLongMode == CPUMIsGuestInLongModeEx(pCtx));
2412
2413 /* Safety precaution; looping for too long here can have a very bad effect on the host */
2414 if (RT_UNLIKELY(++cResume > pVM->hwaccm.s.cMaxResumeLoops))
2415 {
2416 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMaxResume);
2417 rc = VINF_EM_RAW_INTERRUPT;
2418 goto end;
2419 }
2420
2421 /* Check for irq inhibition due to instruction fusing (sti, mov ss). */
2422 if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2423 {
2424 Log(("VM_FF_INHIBIT_INTERRUPTS at %RGv successor %RGv\n", (RTGCPTR)pCtx->rip, EMGetInhibitInterruptsPC(pVCpu)));
2425 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2426 {
2427 /* Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here.
2428 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
2429 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
2430 * break the guest. Sounds very unlikely, but such timing sensitive problems are not as rare as you might think.
2431 */
2432 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2433 /* Irq inhibition is no longer active; clear the corresponding VMX state. */
2434 rc2 = VMXWriteVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, 0);
2435 AssertRC(rc2);
2436 }
2437 }
2438 else
2439 {
2440 /* Irq inhibition is no longer active; clear the corresponding VMX state. */
2441 rc2 = VMXWriteVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, 0);
2442 AssertRC(rc2);
2443 }
2444
2445#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
2446 if (RT_UNLIKELY((cResume & 0xf) == 0))
2447 {
2448 uint64_t u64CurTime = RTTimeMilliTS();
2449
2450 if (RT_UNLIKELY(u64CurTime > u64LastTime))
2451 {
2452 u64LastTime = u64CurTime;
2453 TMTimerPollVoid(pVM, pVCpu);
2454 }
2455 }
2456#endif
2457
2458 /* Check for pending actions that force us to go back to ring 3. */
2459 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK | VM_FF_REQUEST | VM_FF_PGM_POOL_FLUSH_PENDING | VM_FF_PDM_DMA)
2460 || 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))
2461 {
2462 /* Check if a sync operation is pending. */
2463 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2464 {
2465 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2466 if (rc != VINF_SUCCESS)
2467 {
2468 AssertRC(VBOXSTRICTRC_VAL(rc));
2469 Log(("Pending pool sync is forcing us back to ring 3; rc=%d\n", VBOXSTRICTRC_VAL(rc)));
2470 goto end;
2471 }
2472 }
2473
2474#ifdef DEBUG
2475 /* Intercept X86_XCPT_DB if stepping is enabled */
2476 if (!DBGFIsStepping(pVCpu))
2477#endif
2478 {
2479 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK)
2480 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HWACCM_TO_R3_MASK))
2481 {
2482 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatSwitchToR3);
2483 rc = RT_UNLIKELY(VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2484 goto end;
2485 }
2486 }
2487
2488 /* Pending request packets might contain actions that need immediate attention, such as pending hardware interrupts. */
2489 if ( VM_FF_ISPENDING(pVM, VM_FF_REQUEST)
2490 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_REQUEST))
2491 {
2492 rc = VINF_EM_PENDING_REQUEST;
2493 goto end;
2494 }
2495
2496 /* Check if a pgm pool flush is in progress. */
2497 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2498 {
2499 rc = VINF_PGM_POOL_FLUSH_PENDING;
2500 goto end;
2501 }
2502
2503 /* Check if DMA work is pending (2nd+ run). */
2504 if (VM_FF_ISPENDING(pVM, VM_FF_PDM_DMA) && cResume > 1)
2505 {
2506 rc = VINF_EM_RAW_TO_R3;
2507 goto end;
2508 }
2509 }
2510
2511#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2512 /*
2513 * Exit to ring-3 preemption/work is pending.
2514 *
2515 * Interrupts are disabled before the call to make sure we don't miss any interrupt
2516 * that would flag preemption (IPI, timer tick, ++). (Would've been nice to do this
2517 * further down, but hmR0VmxCheckPendingInterrupt makes that impossible.)
2518 *
2519 * Note! Interrupts must be disabled done *before* we check for TLB flushes; TLB
2520 * shootdowns rely on this.
2521 */
2522 uOldEFlags = ASMIntDisableFlags();
2523 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2524 {
2525 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPreemptPending);
2526 rc = VINF_EM_RAW_INTERRUPT;
2527 goto end;
2528 }
2529 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2530#endif
2531
2532 /* When external interrupts are pending, we should exit the VM when IF is set. */
2533 /* Note! *After* VM_FF_INHIBIT_INTERRUPTS check!!! */
2534 rc = hmR0VmxCheckPendingInterrupt(pVM, pVCpu, pCtx);
2535 if (RT_FAILURE(rc))
2536 goto end;
2537
2538 /** @todo check timers?? */
2539
2540 /* TPR caching using CR8 is only available in 64 bits mode */
2541 /* Note the 32 bits exception for AMD (X86_CPUID_AMD_FEATURE_ECX_CR8L), but that appears missing in Intel CPUs */
2542 /* Note: we can't do this in LoadGuestState as PDMApicGetTPR can jump back to ring 3 (lock)!!!!! (no longer true) */
2543 /**
2544 * @todo query and update the TPR only when it could have been changed (mmio access & wrmsr (x2apic))
2545 */
2546 if (fSetupTPRCaching)
2547 {
2548 /* TPR caching in CR8 */
2549 bool fPending;
2550
2551 rc2 = PDMApicGetTPR(pVCpu, &u8LastTPR, &fPending);
2552 AssertRC(rc2);
2553 /* The TPR can be found at offset 0x80 in the APIC mmio page. */
2554 pVCpu->hwaccm.s.vmx.pbVAPIC[0x80] = u8LastTPR;
2555
2556 /* Two options here:
2557 * - external interrupt pending, but masked by the TPR value.
2558 * -> a CR8 update that lower the current TPR value should cause an exit
2559 * - no pending interrupts
2560 * -> We don't need to be explicitely notified. There are enough world switches for detecting pending interrupts.
2561 */
2562 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. */
2563 AssertRC(VBOXSTRICTRC_VAL(rc));
2564
2565 if (pVM->hwaccm.s.fTPRPatchingActive)
2566 {
2567 Assert(!CPUMIsGuestInLongModeEx(pCtx));
2568 /* Our patch code uses LSTAR for TPR caching. */
2569 pCtx->msrLSTAR = u8LastTPR;
2570
2571 if (fPending)
2572 {
2573 /* A TPR change could activate a pending interrupt, so catch lstar writes. */
2574 hmR0VmxSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, false);
2575 }
2576 else
2577 {
2578 /* No interrupts are pending, so we don't need to be explicitely notified.
2579 * There are enough world switches for detecting pending interrupts.
2580 */
2581 hmR0VmxSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
2582 }
2583 }
2584 }
2585
2586#if defined(HWACCM_VTX_WITH_EPT) && defined(LOG_ENABLED)
2587 if ( pVM->hwaccm.s.fNestedPaging
2588# ifdef HWACCM_VTX_WITH_VPID
2589 || pVM->hwaccm.s.vmx.fVPID
2590# endif /* HWACCM_VTX_WITH_VPID */
2591 )
2592 {
2593 PHMGLOBLCPUINFO pCpu;
2594
2595 pCpu = HWACCMR0GetCurrentCpu();
2596 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
2597 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
2598 {
2599 if (pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu)
2600 LogFlow(("Force TLB flush due to rescheduling to a different cpu (%d vs %d)\n", pVCpu->hwaccm.s.idLastCpu, pCpu->idCpu));
2601 else
2602 LogFlow(("Force TLB flush due to changed TLB flush count (%x vs %x)\n", pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
2603 }
2604 if (pCpu->fFlushTLB)
2605 LogFlow(("Force TLB flush: first time cpu %d is used -> flush\n", pCpu->idCpu));
2606 else
2607 if (pVCpu->hwaccm.s.fForceTLBFlush)
2608 LogFlow(("Manual TLB flush\n"));
2609 }
2610#endif
2611#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
2612 PGMRZDynMapFlushAutoSet(pVCpu);
2613#endif
2614
2615 /*
2616 * NOTE: DO NOT DO ANYTHING AFTER THIS POINT THAT MIGHT JUMP BACK TO RING 3!
2617 * (until the actual world switch)
2618 */
2619#ifdef VBOX_STRICT
2620 idCpuCheck = RTMpCpuId();
2621#endif
2622#ifdef LOG_ENABLED
2623 VMMR0LogFlushDisable(pVCpu);
2624#endif
2625 /* Save the host state first. */
2626 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_HOST_CONTEXT)
2627 {
2628 rc = VMXR0SaveHostState(pVM, pVCpu);
2629 if (RT_UNLIKELY(rc != VINF_SUCCESS))
2630 {
2631 VMMR0LogFlushEnable(pVCpu);
2632 goto end;
2633 }
2634 }
2635
2636 /* Load the guest state */
2637 if (!pVCpu->hwaccm.s.fContextUseFlags)
2638 {
2639 VMXR0LoadMinimalGuestState(pVM, pVCpu, pCtx);
2640 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatLoadMinimal);
2641 }
2642 else
2643 {
2644 rc = VMXR0LoadGuestState(pVM, pVCpu, pCtx);
2645 if (RT_UNLIKELY(rc != VINF_SUCCESS))
2646 {
2647 VMMR0LogFlushEnable(pVCpu);
2648 goto end;
2649 }
2650 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatLoadFull);
2651 }
2652
2653#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2654 /* Disable interrupts to make sure a poke will interrupt execution.
2655 * This must be done *before* we check for TLB flushes; TLB shootdowns rely on this.
2656 */
2657 uOldEFlags = ASMIntDisableFlags();
2658 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2659#endif
2660
2661 /* Non-register state Guest Context */
2662 /** @todo change me according to cpu state */
2663 rc2 = VMXWriteVMCS(VMX_VMCS32_GUEST_ACTIVITY_STATE, VMX_CMS_GUEST_ACTIVITY_ACTIVE);
2664 AssertRC(rc2);
2665
2666 /* Set TLB flush state as checked until we return from the world switch. */
2667 ASMAtomicWriteBool(&pVCpu->hwaccm.s.fCheckedTLBFlush, true);
2668 /* Deal with tagged TLB setup and invalidation. */
2669 pVM->hwaccm.s.vmx.pfnSetupTaggedTLB(pVM, pVCpu);
2670
2671 /* Manual save and restore:
2672 * - General purpose registers except RIP, RSP
2673 *
2674 * Trashed:
2675 * - CR2 (we don't care)
2676 * - LDTR (reset to 0)
2677 * - DRx (presumably not changed at all)
2678 * - DR7 (reset to 0x400)
2679 * - EFLAGS (reset to RT_BIT(1); not relevant)
2680 *
2681 */
2682
2683 /* All done! Let's start VM execution. */
2684 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatEntry, &pVCpu->hwaccm.s.StatInGC, x);
2685 Assert(idCpuCheck == RTMpCpuId());
2686
2687#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2688 pVCpu->hwaccm.s.vmx.VMCSCache.cResume = cResume;
2689 pVCpu->hwaccm.s.vmx.VMCSCache.u64TimeSwitch = RTTimeNanoTS();
2690#endif
2691
2692 /* Save the current TPR value in the LSTAR msr so our patches can access it. */
2693 if (pVM->hwaccm.s.fTPRPatchingActive)
2694 {
2695 Assert(pVM->hwaccm.s.fTPRPatchingActive);
2696 u64OldLSTAR = ASMRdMsr(MSR_K8_LSTAR);
2697 ASMWrMsr(MSR_K8_LSTAR, u8LastTPR);
2698 }
2699
2700 TMNotifyStartOfExecution(pVCpu);
2701#ifdef VBOX_WITH_KERNEL_USING_XMM
2702 rc = hwaccmR0VMXStartVMWrapXMM(pVCpu->hwaccm.s.fResumeVM, pCtx, &pVCpu->hwaccm.s.vmx.VMCSCache, pVM, pVCpu, pVCpu->hwaccm.s.vmx.pfnStartVM);
2703#else
2704 rc = pVCpu->hwaccm.s.vmx.pfnStartVM(pVCpu->hwaccm.s.fResumeVM, pCtx, &pVCpu->hwaccm.s.vmx.VMCSCache, pVM, pVCpu);
2705#endif
2706 ASMAtomicWriteBool(&pVCpu->hwaccm.s.fCheckedTLBFlush, false);
2707 ASMAtomicIncU32(&pVCpu->hwaccm.s.cWorldSwitchExits);
2708 /* Possibly the last TSC value seen by the guest (too high) (only when we're in tsc offset mode). */
2709 if (!(pVCpu->hwaccm.s.vmx.proc_ctls & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_RDTSC_EXIT))
2710 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVCpu->hwaccm.s.vmx.u64TSCOffset - 0x400 /* guestimate of world switch overhead in clock ticks */);
2711
2712 TMNotifyEndOfExecution(pVCpu);
2713 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
2714 Assert(!(ASMGetFlags() & X86_EFL_IF));
2715
2716 /* Restore the host LSTAR msr if the guest could have changed it. */
2717 if (pVM->hwaccm.s.fTPRPatchingActive)
2718 {
2719 Assert(pVM->hwaccm.s.fTPRPatchingActive);
2720 pVCpu->hwaccm.s.vmx.pbVAPIC[0x80] = pCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
2721 ASMWrMsr(MSR_K8_LSTAR, u64OldLSTAR);
2722 }
2723
2724 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatInGC, &pVCpu->hwaccm.s.StatExit1, x);
2725 ASMSetFlags(uOldEFlags);
2726#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2727 uOldEFlags = ~(RTCCUINTREG)0;
2728#endif
2729
2730 AssertMsg(!pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries, ("pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries=%d\n", pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries));
2731
2732 /* In case we execute a goto ResumeExecution later on. */
2733 pVCpu->hwaccm.s.fResumeVM = true;
2734 pVCpu->hwaccm.s.fForceTLBFlush = false;
2735
2736 /*
2737 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2738 * 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
2739 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2740 */
2741
2742 if (RT_UNLIKELY(rc != VINF_SUCCESS))
2743 {
2744 hmR0VmxReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
2745 VMMR0LogFlushEnable(pVCpu);
2746 goto end;
2747 }
2748
2749 /* Success. Query the guest state and figure out what has happened. */
2750
2751 /* Investigate why there was a VM-exit. */
2752 rc2 = VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_REASON, &exitReason);
2753 STAM_COUNTER_INC(&pVCpu->hwaccm.s.paStatExitReasonR0[exitReason & MASK_EXITREASON_STAT]);
2754
2755 exitReason &= 0xffff; /* bit 0-15 contain the exit code. */
2756 rc2 |= VMXReadCachedVMCS(VMX_VMCS32_RO_VM_INSTR_ERROR, &instrError);
2757 rc2 |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &cbInstr);
2758 rc2 |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &intInfo);
2759 /* might not be valid; depends on VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID. */
2760 rc2 |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERRCODE, &errCode);
2761 rc2 |= VMXReadCachedVMCS(VMX_VMCS32_RO_EXIT_INSTR_INFO, &instrInfo);
2762 rc2 |= VMXReadCachedVMCS(VMX_VMCS_RO_EXIT_QUALIFICATION, &exitQualification);
2763 AssertRC(rc2);
2764
2765 /* Sync back the guest state */
2766 rc2 = VMXR0SaveGuestState(pVM, pVCpu, pCtx);
2767 AssertRC(rc2);
2768
2769 /* Note! NOW IT'S SAFE FOR LOGGING! */
2770 VMMR0LogFlushEnable(pVCpu);
2771 Log2(("Raw exit reason %08x\n", exitReason));
2772
2773 /* Check if an injected event was interrupted prematurely. */
2774 rc2 = VMXReadCachedVMCS(VMX_VMCS32_RO_IDT_INFO, &val);
2775 AssertRC(rc2);
2776 pVCpu->hwaccm.s.Event.intInfo = VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(val);
2777 if ( VMX_EXIT_INTERRUPTION_INFO_VALID(pVCpu->hwaccm.s.Event.intInfo)
2778 /* Ignore 'int xx' as they'll be restarted anyway. */
2779 && VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hwaccm.s.Event.intInfo) != VMX_EXIT_INTERRUPTION_INFO_TYPE_SW
2780 /* Ignore software exceptions (such as int3) as they'll reoccur when we restart the instruction anyway. */
2781 && VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hwaccm.s.Event.intInfo) != VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT)
2782 {
2783 Assert(!pVCpu->hwaccm.s.Event.fPending);
2784 pVCpu->hwaccm.s.Event.fPending = true;
2785 /* Error code present? */
2786 if (VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(pVCpu->hwaccm.s.Event.intInfo))
2787 {
2788 rc2 = VMXReadCachedVMCS(VMX_VMCS32_RO_IDT_ERRCODE, &val);
2789 AssertRC(rc2);
2790 pVCpu->hwaccm.s.Event.errCode = val;
2791 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));
2792 }
2793 else
2794 {
2795 Log(("Pending inject %RX64 at %RGv exit=%08x intInfo=%08x exitQualification=%RGv\n", pVCpu->hwaccm.s.Event.intInfo, (RTGCPTR)pCtx->rip, exitReason, intInfo, exitQualification));
2796 pVCpu->hwaccm.s.Event.errCode = 0;
2797 }
2798 }
2799#ifdef VBOX_STRICT
2800 else
2801 if ( VMX_EXIT_INTERRUPTION_INFO_VALID(pVCpu->hwaccm.s.Event.intInfo)
2802 /* Ignore software exceptions (such as int3) as they're reoccur when we restart the instruction anyway. */
2803 && VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hwaccm.s.Event.intInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT)
2804 {
2805 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));
2806 }
2807
2808 if (exitReason == VMX_EXIT_ERR_INVALID_GUEST_STATE)
2809 HWACCMDumpRegs(pVM, pVCpu, pCtx);
2810#endif
2811
2812 Log2(("E%d: New EIP=%x:%RGv\n", (uint32_t)exitReason, pCtx->cs, (RTGCPTR)pCtx->rip));
2813 Log2(("Exit reason %d, exitQualification %RGv\n", (uint32_t)exitReason, exitQualification));
2814 Log2(("instrInfo=%d instrError=%d instr length=%d\n", (uint32_t)instrInfo, (uint32_t)instrError, (uint32_t)cbInstr));
2815 Log2(("Interruption error code %d\n", (uint32_t)errCode));
2816 Log2(("IntInfo = %08x\n", (uint32_t)intInfo));
2817
2818 /* Sync back the TPR if it was changed. */
2819 if ( fSetupTPRCaching
2820 && u8LastTPR != pVCpu->hwaccm.s.vmx.pbVAPIC[0x80])
2821 {
2822 rc2 = PDMApicSetTPR(pVCpu, pVCpu->hwaccm.s.vmx.pbVAPIC[0x80]);
2823 AssertRC(rc2);
2824 }
2825
2826#ifdef DBGFTRACE_ENABLED /** @todo DTrace later. */
2827 RTTraceBufAddMsgF(pVM->CTX_SUFF(hTraceBuf), "vmexit %08x %016RX64 at %04:%08RX64 %RX64",
2828 exitReason, (uint64_t)exitQualification, pCtx->cs, pCtx->rip, (uint64_t)intInfo);
2829#endif
2830 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatExit1, &pVCpu->hwaccm.s.StatExit2, x);
2831
2832 /* Some cases don't need a complete resync of the guest CPU state; handle them here. */
2833 Assert(rc == VINF_SUCCESS); /* might consider VERR_IPE_UNINITIALIZED_STATUS here later... */
2834 switch (exitReason)
2835 {
2836 case VMX_EXIT_EXCEPTION: /* 0 Exception or non-maskable interrupt (NMI). */
2837 case VMX_EXIT_EXTERNAL_IRQ: /* 1 External interrupt. */
2838 {
2839 uint32_t vector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(intInfo);
2840
2841 if (!VMX_EXIT_INTERRUPTION_INFO_VALID(intInfo))
2842 {
2843 Assert(exitReason == VMX_EXIT_EXTERNAL_IRQ);
2844#if 0 //def VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2845 if ( RTThreadPreemptIsPendingTrusty()
2846 && !RTThreadPreemptIsPending(NIL_RTTHREAD))
2847 goto ResumeExecution;
2848#endif
2849 /* External interrupt; leave to allow it to be dispatched again. */
2850 rc = VINF_EM_RAW_INTERRUPT;
2851 break;
2852 }
2853 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2854 switch (VMX_EXIT_INTERRUPTION_INFO_TYPE(intInfo))
2855 {
2856 case VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI: /* Non-maskable interrupt. */
2857 /* External interrupt; leave to allow it to be dispatched again. */
2858 rc = VINF_EM_RAW_INTERRUPT;
2859 break;
2860
2861 case VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT: /* External hardware interrupt. */
2862 AssertFailed(); /* can't come here; fails the first check. */
2863 break;
2864
2865 case VMX_EXIT_INTERRUPTION_INFO_TYPE_DBEXCPT: /* Unknown why we get this type for #DB */
2866 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SWEXCPT: /* Software exception. (#BP or #OF) */
2867 Assert(vector == 1 || vector == 3 || vector == 4);
2868 /* no break */
2869 case VMX_EXIT_INTERRUPTION_INFO_TYPE_HWEXCPT: /* Hardware exception. */
2870 Log2(("Hardware/software interrupt %d\n", vector));
2871 switch (vector)
2872 {
2873 case X86_XCPT_NM:
2874 {
2875 Log(("#NM fault at %RGv error code %x\n", (RTGCPTR)pCtx->rip, errCode));
2876
2877 /** @todo don't intercept #NM exceptions anymore when we've activated the guest FPU state. */
2878 /* If we sync the FPU/XMM state on-demand, then we can continue execution as if nothing has happened. */
2879 rc = CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
2880 if (rc == VINF_SUCCESS)
2881 {
2882 Assert(CPUMIsGuestFPUStateActive(pVCpu));
2883
2884 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowNM);
2885
2886 /* Continue execution. */
2887 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
2888
2889 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2890 goto ResumeExecution;
2891 }
2892
2893 Log(("Forward #NM fault to the guest\n"));
2894 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNM);
2895 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, 0);
2896 AssertRC(rc2);
2897 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2898 goto ResumeExecution;
2899 }
2900
2901 case X86_XCPT_PF: /* Page fault */
2902 {
2903#ifdef DEBUG
2904 if (pVM->hwaccm.s.fNestedPaging)
2905 { /* A genuine pagefault.
2906 * Forward the trap to the guest by injecting the exception and resuming execution.
2907 */
2908 Log(("Guest page fault at %RGv cr2=%RGv error code %RGv rsp=%RGv\n", (RTGCPTR)pCtx->rip, exitQualification, errCode, (RTGCPTR)pCtx->rsp));
2909
2910 Assert(CPUMIsGuestInPagedProtectedModeEx(pCtx));
2911
2912 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
2913
2914 /* Now we must update CR2. */
2915 pCtx->cr2 = exitQualification;
2916 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
2917 AssertRC(rc2);
2918
2919 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2920 goto ResumeExecution;
2921 }
2922#endif
2923 Assert(!pVM->hwaccm.s.fNestedPaging);
2924
2925#ifdef VBOX_HWACCM_WITH_GUEST_PATCHING
2926 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
2927 if ( pVM->hwaccm.s.fTRPPatchingAllowed
2928 && pVM->hwaccm.s.pGuestPatchMem
2929 && (exitQualification & 0xfff) == 0x080
2930 && !(errCode & X86_TRAP_PF_P) /* not present */
2931 && CPUMGetGuestCPL(pVCpu, CPUMCTX2CORE(pCtx)) == 0
2932 && !CPUMIsGuestInLongModeEx(pCtx)
2933 && pVM->hwaccm.s.cPatches < RT_ELEMENTS(pVM->hwaccm.s.aPatches))
2934 {
2935 RTGCPHYS GCPhysApicBase, GCPhys;
2936 PDMApicGetBase(pVM, &GCPhysApicBase); /* @todo cache this */
2937 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2938
2939 rc = PGMGstGetPage(pVCpu, (RTGCPTR)exitQualification, NULL, &GCPhys);
2940 if ( rc == VINF_SUCCESS
2941 && GCPhys == GCPhysApicBase)
2942 {
2943 /* Only attempt to patch the instruction once. */
2944 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2945 if (!pPatch)
2946 {
2947 rc = VINF_EM_HWACCM_PATCH_TPR_INSTR;
2948 break;
2949 }
2950 }
2951 }
2952#endif
2953
2954 Log2(("Page fault at %RGv error code %x\n", exitQualification, errCode));
2955 /* Exit qualification contains the linear address of the page fault. */
2956 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
2957 TRPMSetErrorCode(pVCpu, errCode);
2958 TRPMSetFaultAddress(pVCpu, exitQualification);
2959
2960 /* Shortcut for APIC TPR reads and writes. */
2961 if ( (exitQualification & 0xfff) == 0x080
2962 && !(errCode & X86_TRAP_PF_P) /* not present */
2963 && fSetupTPRCaching
2964 && (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC))
2965 {
2966 RTGCPHYS GCPhysApicBase, GCPhys;
2967 PDMApicGetBase(pVM, &GCPhysApicBase); /* @todo cache this */
2968 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2969
2970 rc = PGMGstGetPage(pVCpu, (RTGCPTR)exitQualification, NULL, &GCPhys);
2971 if ( rc == VINF_SUCCESS
2972 && GCPhys == GCPhysApicBase)
2973 {
2974 Log(("Enable VT-x virtual APIC access filtering\n"));
2975 rc2 = IOMMMIOMapMMIOHCPage(pVM, GCPhysApicBase, pVM->hwaccm.s.vmx.pAPICPhys, X86_PTE_RW | X86_PTE_P);
2976 AssertRC(rc2);
2977 }
2978 }
2979
2980 /* Forward it to our trap handler first, in case our shadow pages are out of sync. */
2981 rc = PGMTrap0eHandler(pVCpu, errCode, CPUMCTX2CORE(pCtx), (RTGCPTR)exitQualification);
2982 Log2(("PGMTrap0eHandler %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
2983
2984 if (rc == VINF_SUCCESS)
2985 { /* We've successfully synced our shadow pages, so let's just continue execution. */
2986 Log2(("Shadow page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, exitQualification ,errCode));
2987 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowPF);
2988
2989 TRPMResetTrap(pVCpu);
2990 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
2991 goto ResumeExecution;
2992 }
2993 else
2994 if (rc == VINF_EM_RAW_GUEST_TRAP)
2995 { /* A genuine pagefault.
2996 * Forward the trap to the guest by injecting the exception and resuming execution.
2997 */
2998 Log2(("Forward page fault to the guest\n"));
2999
3000 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
3001 /* The error code might have been changed. */
3002 errCode = TRPMGetErrorCode(pVCpu);
3003
3004 TRPMResetTrap(pVCpu);
3005
3006 /* Now we must update CR2. */
3007 pCtx->cr2 = exitQualification;
3008 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3009 AssertRC(rc2);
3010
3011 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3012 goto ResumeExecution;
3013 }
3014#ifdef VBOX_STRICT
3015 if (rc != VINF_EM_RAW_EMULATE_INSTR && rc != VINF_EM_RAW_EMULATE_IO_BLOCK)
3016 Log2(("PGMTrap0eHandler failed with %d\n", VBOXSTRICTRC_VAL(rc)));
3017#endif
3018 /* Need to go back to the recompiler to emulate the instruction. */
3019 TRPMResetTrap(pVCpu);
3020 break;
3021 }
3022
3023 case X86_XCPT_MF: /* Floating point exception. */
3024 {
3025 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestMF);
3026 if (!(pCtx->cr0 & X86_CR0_NE))
3027 {
3028 /* old style FPU error reporting needs some extra work. */
3029 /** @todo don't fall back to the recompiler, but do it manually. */
3030 rc = VINF_EM_RAW_EMULATE_INSTR;
3031 break;
3032 }
3033 Log(("Trap %x at %04X:%RGv\n", vector, pCtx->cs, (RTGCPTR)pCtx->rip));
3034 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3035 AssertRC(rc2);
3036
3037 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3038 goto ResumeExecution;
3039 }
3040
3041 case X86_XCPT_DB: /* Debug exception. */
3042 {
3043 uint64_t uDR6;
3044
3045 /* DR6, DR7.GD and IA32_DEBUGCTL.LBR are not updated yet.
3046 *
3047 * Exit qualification bits:
3048 * 3:0 B0-B3 which breakpoint condition was met
3049 * 12:4 Reserved (0)
3050 * 13 BD - debug register access detected
3051 * 14 BS - single step execution or branch taken
3052 * 63:15 Reserved (0)
3053 */
3054 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDB);
3055
3056 /* Note that we don't support guest and host-initiated debugging at the same time. */
3057
3058 uDR6 = X86_DR6_INIT_VAL;
3059 uDR6 |= (exitQualification & (X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3|X86_DR6_BD|X86_DR6_BS));
3060 rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), uDR6);
3061 if (rc == VINF_EM_RAW_GUEST_TRAP)
3062 {
3063 /* Update DR6 here. */
3064 pCtx->dr[6] = uDR6;
3065
3066 /* Resync DR6 if the debug state is active. */
3067 if (CPUMIsGuestDebugStateActive(pVCpu))
3068 ASMSetDR6(pCtx->dr[6]);
3069
3070 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
3071 pCtx->dr[7] &= ~X86_DR7_GD;
3072
3073 /* Paranoia. */
3074 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
3075 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
3076 pCtx->dr[7] |= 0x400; /* must be one */
3077
3078 /* Resync DR7 */
3079 rc2 = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, pCtx->dr[7]);
3080 AssertRC(rc2);
3081
3082 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]));
3083 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3084 AssertRC(rc2);
3085
3086 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3087 goto ResumeExecution;
3088 }
3089 /* Return to ring 3 to deal with the debug exit code. */
3090 Log(("Debugger hardware BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs, pCtx->rip, VBOXSTRICTRC_VAL(rc)));
3091 break;
3092 }
3093
3094 case X86_XCPT_BP: /* Breakpoint. */
3095 {
3096 rc = DBGFRZTrap03Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3097 if (rc == VINF_EM_RAW_GUEST_TRAP)
3098 {
3099 Log(("Guest #BP at %04x:%RGv\n", pCtx->cs, pCtx->rip));
3100 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3101 AssertRC(rc2);
3102 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3103 goto ResumeExecution;
3104 }
3105 if (rc == VINF_SUCCESS)
3106 {
3107 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3108 goto ResumeExecution;
3109 }
3110 Log(("Debugger BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs, pCtx->rip, VBOXSTRICTRC_VAL(rc)));
3111 break;
3112 }
3113
3114 case X86_XCPT_GP: /* General protection failure exception.*/
3115 {
3116 uint32_t cbOp;
3117 PDISCPUSTATE pDis = &pVCpu->hwaccm.s.DisState;
3118
3119 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestGP);
3120#ifdef VBOX_STRICT
3121 if ( !CPUMIsGuestInRealModeEx(pCtx)
3122 || !pVM->hwaccm.s.vmx.pRealModeTSS)
3123 {
3124 Log(("Trap %x at %04X:%RGv errorCode=%RGv\n", vector, pCtx->cs, (RTGCPTR)pCtx->rip, errCode));
3125 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3126 AssertRC(rc2);
3127 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3128 goto ResumeExecution;
3129 }
3130#endif
3131 Assert(CPUMIsGuestInRealModeEx(pCtx));
3132
3133 LogFlow(("Real mode X86_XCPT_GP instruction emulation at %x:%RGv\n", pCtx->cs, (RTGCPTR)pCtx->rip));
3134
3135 rc2 = EMInterpretDisasOne(pVM, pVCpu, CPUMCTX2CORE(pCtx), pDis, &cbOp);
3136 if (RT_SUCCESS(rc2))
3137 {
3138 bool fUpdateRIP = true;
3139
3140 rc = VINF_SUCCESS;
3141 Assert(cbOp == pDis->opsize);
3142 switch (pDis->pCurInstr->opcode)
3143 {
3144 case OP_CLI:
3145 pCtx->eflags.Bits.u1IF = 0;
3146 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCli);
3147 break;
3148
3149 case OP_STI:
3150 pCtx->eflags.Bits.u1IF = 1;
3151 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip + pDis->opsize);
3152 Assert(VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
3153 rc2 = VMXWriteVMCS(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
3154 AssertRC(rc2);
3155 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitSti);
3156 break;
3157
3158 case OP_HLT:
3159 fUpdateRIP = false;
3160 rc = VINF_EM_HALT;
3161 pCtx->rip += pDis->opsize;
3162 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitHlt);
3163 break;
3164
3165 case OP_POPF:
3166 {
3167 RTGCPTR GCPtrStack;
3168 uint32_t cbParm;
3169 uint32_t uMask;
3170 X86EFLAGS eflags;
3171
3172 if (pDis->prefix & PREFIX_OPSIZE)
3173 {
3174 cbParm = 4;
3175 uMask = 0xffffffff;
3176 }
3177 else
3178 {
3179 cbParm = 2;
3180 uMask = 0xffff;
3181 }
3182
3183 rc2 = SELMToFlatEx(pVCpu, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), pCtx->esp & uMask, 0, &GCPtrStack);
3184 if (RT_FAILURE(rc2))
3185 {
3186 rc = VERR_EM_INTERPRETER;
3187 break;
3188 }
3189 eflags.u = 0;
3190 rc2 = PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &eflags.u, cbParm);
3191 if (RT_FAILURE(rc2))
3192 {
3193 rc = VERR_EM_INTERPRETER;
3194 break;
3195 }
3196 LogFlow(("POPF %x -> %RGv mask=%x\n", eflags.u, pCtx->rsp, uMask));
3197 pCtx->eflags.u = (pCtx->eflags.u & ~(X86_EFL_POPF_BITS & uMask)) | (eflags.u & X86_EFL_POPF_BITS & uMask);
3198 /* RF cleared when popped in real mode; see pushf description in AMD manual. */
3199 pCtx->eflags.Bits.u1RF = 0;
3200 pCtx->esp += cbParm;
3201 pCtx->esp &= uMask;
3202
3203 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPopf);
3204 break;
3205 }
3206
3207 case OP_PUSHF:
3208 {
3209 RTGCPTR GCPtrStack;
3210 uint32_t cbParm;
3211 uint32_t uMask;
3212 X86EFLAGS eflags;
3213
3214 if (pDis->prefix & PREFIX_OPSIZE)
3215 {
3216 cbParm = 4;
3217 uMask = 0xffffffff;
3218 }
3219 else
3220 {
3221 cbParm = 2;
3222 uMask = 0xffff;
3223 }
3224
3225 rc2 = SELMToFlatEx(pVCpu, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), (pCtx->esp - cbParm) & uMask, 0, &GCPtrStack);
3226 if (RT_FAILURE(rc2))
3227 {
3228 rc = VERR_EM_INTERPRETER;
3229 break;
3230 }
3231 eflags = pCtx->eflags;
3232 /* RF & VM cleared when pushed in real mode; see pushf description in AMD manual. */
3233 eflags.Bits.u1RF = 0;
3234 eflags.Bits.u1VM = 0;
3235
3236 rc2 = PGMPhysWrite(pVM, (RTGCPHYS)GCPtrStack, &eflags.u, cbParm);
3237 if (RT_FAILURE(rc2))
3238 {
3239 rc = VERR_EM_INTERPRETER;
3240 break;
3241 }
3242 LogFlow(("PUSHF %x -> %RGv\n", eflags.u, GCPtrStack));
3243 pCtx->esp -= cbParm;
3244 pCtx->esp &= uMask;
3245 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPushf);
3246 break;
3247 }
3248
3249 case OP_IRET:
3250 {
3251 RTGCPTR GCPtrStack;
3252 uint32_t uMask = 0xffff;
3253 uint16_t aIretFrame[3];
3254
3255 if (pDis->prefix & (PREFIX_OPSIZE | PREFIX_ADDRSIZE))
3256 {
3257 rc = VERR_EM_INTERPRETER;
3258 break;
3259 }
3260
3261 rc2 = SELMToFlatEx(pVCpu, DIS_SELREG_SS, CPUMCTX2CORE(pCtx), pCtx->esp & uMask, 0, &GCPtrStack);
3262 if (RT_FAILURE(rc2))
3263 {
3264 rc = VERR_EM_INTERPRETER;
3265 break;
3266 }
3267 rc2 = PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &aIretFrame[0], sizeof(aIretFrame));
3268 if (RT_FAILURE(rc2))
3269 {
3270 rc = VERR_EM_INTERPRETER;
3271 break;
3272 }
3273 pCtx->ip = aIretFrame[0];
3274 pCtx->cs = aIretFrame[1];
3275 pCtx->csHid.u64Base = pCtx->cs << 4;
3276 pCtx->eflags.u = (pCtx->eflags.u & ~(X86_EFL_POPF_BITS & uMask)) | (aIretFrame[2] & X86_EFL_POPF_BITS & uMask);
3277 pCtx->sp += sizeof(aIretFrame);
3278
3279 LogFlow(("iret to %04x:%x\n", pCtx->cs, pCtx->ip));
3280 fUpdateRIP = false;
3281 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIret);
3282 break;
3283 }
3284
3285 case OP_INT:
3286 {
3287 uint32_t intInfo2;
3288
3289 LogFlow(("Realmode: INT %x\n", pDis->param1.parval & 0xff));
3290 intInfo2 = pDis->param1.parval & 0xff;
3291 intInfo2 |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3292 intInfo2 |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3293
3294 rc = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, intInfo2, cbOp, 0);
3295 AssertRC(VBOXSTRICTRC_VAL(rc));
3296 fUpdateRIP = false;
3297 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInt);
3298 break;
3299 }
3300
3301 case OP_INTO:
3302 {
3303 if (pCtx->eflags.Bits.u1OF)
3304 {
3305 uint32_t intInfo2;
3306
3307 LogFlow(("Realmode: INTO\n"));
3308 intInfo2 = X86_XCPT_OF;
3309 intInfo2 |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3310 intInfo2 |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3311
3312 rc = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, intInfo2, cbOp, 0);
3313 AssertRC(VBOXSTRICTRC_VAL(rc));
3314 fUpdateRIP = false;
3315 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInt);
3316 }
3317 break;
3318 }
3319
3320 case OP_INT3:
3321 {
3322 uint32_t intInfo2;
3323
3324 LogFlow(("Realmode: INT 3\n"));
3325 intInfo2 = 3;
3326 intInfo2 |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3327 intInfo2 |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3328
3329 rc = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, intInfo2, cbOp, 0);
3330 AssertRC(VBOXSTRICTRC_VAL(rc));
3331 fUpdateRIP = false;
3332 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInt);
3333 break;
3334 }
3335
3336 default:
3337 rc = EMInterpretInstructionDisasState(pVCpu, pDis, CPUMCTX2CORE(pCtx), 0, EMCODETYPE_SUPERVISOR);
3338 fUpdateRIP = false;
3339 break;
3340 }
3341
3342 if (rc == VINF_SUCCESS)
3343 {
3344 if (fUpdateRIP)
3345 pCtx->rip += cbOp; /* Move on to the next instruction. */
3346
3347 /* lidt, lgdt can end up here. In the future crx changes as well. Just reload the whole context to be done with it. */
3348 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_ALL;
3349
3350 /* Only resume if successful. */
3351 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3352 goto ResumeExecution;
3353 }
3354 }
3355 else
3356 rc = VERR_EM_INTERPRETER;
3357
3358 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_EM_HALT, ("Unexpected rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
3359 break;
3360 }
3361
3362#ifdef VBOX_STRICT
3363 case X86_XCPT_XF: /* SIMD exception. */
3364 case X86_XCPT_DE: /* Divide error. */
3365 case X86_XCPT_UD: /* Unknown opcode exception. */
3366 case X86_XCPT_SS: /* Stack segment exception. */
3367 case X86_XCPT_NP: /* Segment not present exception. */
3368 {
3369 switch(vector)
3370 {
3371 case X86_XCPT_DE:
3372 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDE);
3373 break;
3374 case X86_XCPT_UD:
3375 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestUD);
3376 break;
3377 case X86_XCPT_SS:
3378 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestSS);
3379 break;
3380 case X86_XCPT_NP:
3381 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNP);
3382 break;
3383 }
3384
3385 Log(("Trap %x at %04X:%RGv\n", vector, pCtx->cs, (RTGCPTR)pCtx->rip));
3386 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3387 AssertRC(rc2);
3388
3389 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3390 goto ResumeExecution;
3391 }
3392#endif
3393 default:
3394 if ( CPUMIsGuestInRealModeEx(pCtx)
3395 && pVM->hwaccm.s.vmx.pRealModeTSS)
3396 {
3397 Log(("Real Mode Trap %x at %04x:%04X error code %x\n", vector, pCtx->cs, pCtx->eip, errCode));
3398 rc = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), cbInstr, errCode);
3399 AssertRC(VBOXSTRICTRC_VAL(rc)); /* Strict RC check below. */
3400
3401 /* Go back to ring 3 in case of a triple fault. */
3402 if ( vector == X86_XCPT_DF
3403 && rc == VINF_EM_RESET)
3404 break;
3405
3406 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3407 goto ResumeExecution;
3408 }
3409 AssertMsgFailed(("Unexpected vm-exit caused by exception %x\n", vector));
3410 rc = VERR_VMX_UNEXPECTED_EXCEPTION;
3411 break;
3412 } /* switch (vector) */
3413
3414 break;
3415
3416 default:
3417 rc = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_CODE;
3418 AssertMsgFailed(("Unexpected interruption code %x\n", intInfo));
3419 break;
3420 }
3421
3422 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub3, y3);
3423 break;
3424 }
3425
3426 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. */
3427 {
3428 RTGCPHYS GCPhys;
3429
3430 Assert(pVM->hwaccm.s.fNestedPaging);
3431
3432 rc2 = VMXReadVMCS64(VMX_VMCS_EXIT_PHYS_ADDR_FULL, &GCPhys);
3433 AssertRC(rc2);
3434 Assert(((exitQualification >> 7) & 3) != 2);
3435
3436 /* Determine the kind of violation. */
3437 errCode = 0;
3438 if (exitQualification & VMX_EXIT_QUALIFICATION_EPT_INSTR_FETCH)
3439 errCode |= X86_TRAP_PF_ID;
3440
3441 if (exitQualification & VMX_EXIT_QUALIFICATION_EPT_DATA_WRITE)
3442 errCode |= X86_TRAP_PF_RW;
3443
3444 /* If the page is present, then it's a page level protection fault. */
3445 if (exitQualification & VMX_EXIT_QUALIFICATION_EPT_ENTRY_PRESENT)
3446 {
3447 errCode |= X86_TRAP_PF_P;
3448 }
3449 else
3450 {
3451 /* Shortcut for APIC TPR reads and writes. */
3452 if ( (GCPhys & 0xfff) == 0x080
3453 && GCPhys > 0x1000000 /* to skip VGA frame buffer accesses */
3454 && fSetupTPRCaching
3455 && (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC))
3456 {
3457 RTGCPHYS GCPhysApicBase;
3458 PDMApicGetBase(pVM, &GCPhysApicBase); /* @todo cache this */
3459 GCPhysApicBase &= PAGE_BASE_GC_MASK;
3460 if (GCPhys == GCPhysApicBase + 0x80)
3461 {
3462 Log(("Enable VT-x virtual APIC access filtering\n"));
3463 rc2 = IOMMMIOMapMMIOHCPage(pVM, GCPhysApicBase, pVM->hwaccm.s.vmx.pAPICPhys, X86_PTE_RW | X86_PTE_P);
3464 AssertRC(rc2);
3465 }
3466 }
3467 }
3468 Log(("EPT Page fault %x at %RGp error code %x\n", (uint32_t)exitQualification, GCPhys, errCode));
3469
3470 /* GCPhys contains the guest physical address of the page fault. */
3471 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
3472 TRPMSetErrorCode(pVCpu, errCode);
3473 TRPMSetFaultAddress(pVCpu, GCPhys);
3474
3475 /* Handle the pagefault trap for the nested shadow table. */
3476 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, errCode, CPUMCTX2CORE(pCtx), GCPhys);
3477 Log2(("PGMR0Trap0eHandlerNestedPaging %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
3478 if (rc == VINF_SUCCESS)
3479 { /* We've successfully synced our shadow pages, so let's just continue execution. */
3480 Log2(("Shadow page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, exitQualification , errCode));
3481 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitReasonNPF);
3482
3483 TRPMResetTrap(pVCpu);
3484 goto ResumeExecution;
3485 }
3486
3487#ifdef VBOX_STRICT
3488 if (rc != VINF_EM_RAW_EMULATE_INSTR)
3489 LogFlow(("PGMTrap0eHandlerNestedPaging failed with %d\n", VBOXSTRICTRC_VAL(rc)));
3490#endif
3491 /* Need to go back to the recompiler to emulate the instruction. */
3492 TRPMResetTrap(pVCpu);
3493 break;
3494 }
3495
3496 case VMX_EXIT_EPT_MISCONFIG:
3497 {
3498 RTGCPHYS GCPhys;
3499
3500 Assert(pVM->hwaccm.s.fNestedPaging);
3501
3502 rc2 = VMXReadVMCS64(VMX_VMCS_EXIT_PHYS_ADDR_FULL, &GCPhys);
3503 AssertRC(rc2);
3504 Log(("VMX_EXIT_EPT_MISCONFIG for %RGp\n", GCPhys));
3505
3506 /* Shortcut for APIC TPR reads and writes. */
3507 if ( (GCPhys & 0xfff) == 0x080
3508 && GCPhys > 0x1000000 /* to skip VGA frame buffer accesses */
3509 && fSetupTPRCaching
3510 && (pVM->hwaccm.s.vmx.msr.vmx_proc_ctls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC))
3511 {
3512 RTGCPHYS GCPhysApicBase;
3513 PDMApicGetBase(pVM, &GCPhysApicBase); /* @todo cache this */
3514 GCPhysApicBase &= PAGE_BASE_GC_MASK;
3515 if (GCPhys == GCPhysApicBase + 0x80)
3516 {
3517 Log(("Enable VT-x virtual APIC access filtering\n"));
3518 rc2 = IOMMMIOMapMMIOHCPage(pVM, GCPhysApicBase, pVM->hwaccm.s.vmx.pAPICPhys, X86_PTE_RW | X86_PTE_P);
3519 AssertRC(rc2);
3520 }
3521 }
3522
3523 rc = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pCtx), GCPhys, UINT32_MAX);
3524 if (rc == VINF_SUCCESS)
3525 {
3526 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhys, (RTGCPTR)pCtx->rip));
3527 goto ResumeExecution;
3528 }
3529
3530 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> %Rrc\n", GCPhys, (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
3531 break;
3532 }
3533
3534 case VMX_EXIT_IRQ_WINDOW: /* 7 Interrupt window. */
3535 /* Clear VM-exit on IF=1 change. */
3536 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));
3537 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_IRQ_WINDOW_EXIT;
3538 rc2 = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
3539 AssertRC(rc2);
3540 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIrqWindow);
3541 goto ResumeExecution; /* we check for pending guest interrupts there */
3542
3543 case VMX_EXIT_WBINVD: /* 54 Guest software attempted to execute WBINVD. (conditional) */
3544 case VMX_EXIT_INVD: /* 13 Guest software attempted to execute INVD. (unconditional) */
3545 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvd);
3546 /* Skip instruction and continue directly. */
3547 pCtx->rip += cbInstr;
3548 /* Continue execution.*/
3549 goto ResumeExecution;
3550
3551 case VMX_EXIT_CPUID: /* 10 Guest software attempted to execute CPUID. */
3552 {
3553 Log2(("VMX: Cpuid %x\n", pCtx->eax));
3554 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCpuid);
3555 rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3556 if (rc == VINF_SUCCESS)
3557 {
3558 /* Update EIP and continue execution. */
3559 Assert(cbInstr == 2);
3560 pCtx->rip += cbInstr;
3561 goto ResumeExecution;
3562 }
3563 AssertMsgFailed(("EMU: cpuid failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
3564 rc = VINF_EM_RAW_EMULATE_INSTR;
3565 break;
3566 }
3567
3568 case VMX_EXIT_RDPMC: /* 15 Guest software attempted to execute RDPMC. */
3569 {
3570 Log2(("VMX: Rdpmc %x\n", pCtx->ecx));
3571 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdpmc);
3572 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3573 if (rc == VINF_SUCCESS)
3574 {
3575 /* Update EIP and continue execution. */
3576 Assert(cbInstr == 2);
3577 pCtx->rip += cbInstr;
3578 goto ResumeExecution;
3579 }
3580 rc = VINF_EM_RAW_EMULATE_INSTR;
3581 break;
3582 }
3583
3584 case VMX_EXIT_RDTSC: /* 16 Guest software attempted to execute RDTSC. */
3585 {
3586 Log2(("VMX: Rdtsc\n"));
3587 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdtsc);
3588 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3589 if (rc == VINF_SUCCESS)
3590 {
3591 /* Update EIP and continue execution. */
3592 Assert(cbInstr == 2);
3593 pCtx->rip += cbInstr;
3594 goto ResumeExecution;
3595 }
3596 rc = VINF_EM_RAW_EMULATE_INSTR;
3597 break;
3598 }
3599
3600 case VMX_EXIT_INVPG: /* 14 Guest software attempted to execute INVPG. */
3601 {
3602 Log2(("VMX: invlpg\n"));
3603 Assert(!pVM->hwaccm.s.fNestedPaging);
3604
3605 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvpg);
3606 rc = EMInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx), exitQualification);
3607 if (rc == VINF_SUCCESS)
3608 {
3609 /* Update EIP and continue execution. */
3610 pCtx->rip += cbInstr;
3611 goto ResumeExecution;
3612 }
3613 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: invlpg %RGv failed with %Rrc\n", exitQualification, VBOXSTRICTRC_VAL(rc)));
3614 break;
3615 }
3616
3617 case VMX_EXIT_MONITOR: /* 39 Guest software attempted to execute MONITOR. */
3618 {
3619 Log2(("VMX: monitor\n"));
3620
3621 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMonitor);
3622 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3623 if (rc == VINF_SUCCESS)
3624 {
3625 /* Update EIP and continue execution. */
3626 pCtx->rip += cbInstr;
3627 goto ResumeExecution;
3628 }
3629 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: monitor failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
3630 break;
3631 }
3632
3633 case VMX_EXIT_WRMSR: /* 32 WRMSR. Guest software attempted to execute WRMSR. */
3634 /* When an interrupt is pending, we'll let MSR_K8_LSTAR writes fault in our TPR patch code. */
3635 if ( pVM->hwaccm.s.fTPRPatchingActive
3636 && pCtx->ecx == MSR_K8_LSTAR)
3637 {
3638 Assert(!CPUMIsGuestInLongModeEx(pCtx));
3639 if ((pCtx->eax & 0xff) != u8LastTPR)
3640 {
3641 Log(("VMX: Faulting MSR_K8_LSTAR write with new TPR value %x\n", pCtx->eax & 0xff));
3642
3643 /* Our patch code uses LSTAR for TPR caching. */
3644 rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
3645 AssertRC(rc2);
3646 }
3647
3648 /* Skip the instruction and continue. */
3649 pCtx->rip += cbInstr; /* wrmsr = [0F 30] */
3650
3651 /* Only resume if successful. */
3652 goto ResumeExecution;
3653 }
3654 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_MSR;
3655 /* no break */
3656 case VMX_EXIT_RDMSR: /* 31 RDMSR. Guest software attempted to execute RDMSR. */
3657 {
3658 STAM_COUNTER_INC((exitReason == VMX_EXIT_RDMSR) ? &pVCpu->hwaccm.s.StatExitRdmsr : &pVCpu->hwaccm.s.StatExitWrmsr);
3659
3660 /* 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. */
3661 Log2(("VMX: %s\n", (exitReason == VMX_EXIT_RDMSR) ? "rdmsr" : "wrmsr"));
3662 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
3663 if (rc == VINF_SUCCESS)
3664 {
3665 /* EIP has been updated already. */
3666
3667 /* Only resume if successful. */
3668 goto ResumeExecution;
3669 }
3670 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: %s failed with %Rrc\n", (exitReason == VMX_EXIT_RDMSR) ? "rdmsr" : "wrmsr", VBOXSTRICTRC_VAL(rc)));
3671 break;
3672 }
3673
3674 case VMX_EXIT_CRX_MOVE: /* 28 Control-register accesses. */
3675 {
3676 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2Sub2, y2);
3677
3678 switch (VMX_EXIT_QUALIFICATION_CRX_ACCESS(exitQualification))
3679 {
3680 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_WRITE:
3681 Log2(("VMX: %RGv mov cr%d, x\n", (RTGCPTR)pCtx->rip, VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification)));
3682 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxWrite[VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification)]);
3683 rc = EMInterpretCRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3684 VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification),
3685 VMX_EXIT_QUALIFICATION_CRX_GENREG(exitQualification));
3686
3687 switch (VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification))
3688 {
3689 case 0:
3690 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0 | HWACCM_CHANGED_GUEST_CR3;
3691 break;
3692 case 2:
3693 break;
3694 case 3:
3695 Assert(!pVM->hwaccm.s.fNestedPaging || !CPUMIsGuestInPagedProtectedModeEx(pCtx));
3696 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR3;
3697 break;
3698 case 4:
3699 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR4;
3700 break;
3701 case 8:
3702 /* CR8 contains the APIC TPR */
3703 Assert(!(pVM->hwaccm.s.vmx.msr.vmx_proc_ctls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_USE_TPR_SHADOW));
3704 break;
3705
3706 default:
3707 AssertFailed();
3708 break;
3709 }
3710 break;
3711
3712 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_READ:
3713 Log2(("VMX: mov x, crx\n"));
3714 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxRead[VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification)]);
3715
3716 Assert(!pVM->hwaccm.s.fNestedPaging || !CPUMIsGuestInPagedProtectedModeEx(pCtx) || VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification) != USE_REG_CR3);
3717
3718 /* CR8 reads only cause an exit when the TPR shadow feature isn't present. */
3719 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));
3720
3721 rc = EMInterpretCRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3722 VMX_EXIT_QUALIFICATION_CRX_GENREG(exitQualification),
3723 VMX_EXIT_QUALIFICATION_CRX_REGISTER(exitQualification));
3724 break;
3725
3726 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_CLTS:
3727 Log2(("VMX: clts\n"));
3728 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCLTS);
3729 rc = EMInterpretCLTS(pVM, pVCpu);
3730 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
3731 break;
3732
3733 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_LMSW:
3734 Log2(("VMX: lmsw %x\n", VMX_EXIT_QUALIFICATION_CRX_LMSW_DATA(exitQualification)));
3735 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitLMSW);
3736 rc = EMInterpretLMSW(pVM, pVCpu, CPUMCTX2CORE(pCtx), VMX_EXIT_QUALIFICATION_CRX_LMSW_DATA(exitQualification));
3737 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
3738 break;
3739 }
3740
3741 /* Update EIP if no error occurred. */
3742 if (RT_SUCCESS(rc))
3743 pCtx->rip += cbInstr;
3744
3745 if (rc == VINF_SUCCESS)
3746 {
3747 /* Only resume if successful. */
3748 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub2, y2);
3749 goto ResumeExecution;
3750 }
3751 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3752 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub2, y2);
3753 break;
3754 }
3755
3756 case VMX_EXIT_DRX_MOVE: /* 29 Debug-register accesses. */
3757 {
3758 if ( !DBGFIsStepping(pVCpu)
3759 && !CPUMIsHyperDebugStateActive(pVCpu))
3760 {
3761 /* Disable drx move intercepts. */
3762 pVCpu->hwaccm.s.vmx.proc_ctls &= ~VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT;
3763 rc2 = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
3764 AssertRC(rc2);
3765
3766 /* Save the host and load the guest debug state. */
3767 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
3768 AssertRC(rc2);
3769
3770#ifdef LOG_ENABLED
3771 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
3772 Log(("VMX_EXIT_DRX_MOVE: write DR%d genreg %d\n", VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification), VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification)));
3773 else
3774 Log(("VMX_EXIT_DRX_MOVE: read DR%d\n", VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification)));
3775#endif
3776
3777#ifdef VBOX_WITH_STATISTICS
3778 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxContextSwitch);
3779 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
3780 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxWrite);
3781 else
3782 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxRead);
3783#endif
3784
3785 goto ResumeExecution;
3786 }
3787
3788 /** @todo clear VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT after the first time and restore drx registers afterwards */
3789 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
3790 {
3791 Log2(("VMX: mov drx%d, genreg%d\n", VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification), VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification)));
3792 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxWrite);
3793 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3794 VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification),
3795 VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification));
3796 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
3797 Log2(("DR7=%08x\n", pCtx->dr[7]));
3798 }
3799 else
3800 {
3801 Log2(("VMX: mov x, drx\n"));
3802 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxRead);
3803 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
3804 VMX_EXIT_QUALIFICATION_DRX_GENREG(exitQualification),
3805 VMX_EXIT_QUALIFICATION_DRX_REGISTER(exitQualification));
3806 }
3807 /* Update EIP if no error occurred. */
3808 if (RT_SUCCESS(rc))
3809 pCtx->rip += cbInstr;
3810
3811 if (rc == VINF_SUCCESS)
3812 {
3813 /* Only resume if successful. */
3814 goto ResumeExecution;
3815 }
3816 Assert(rc == VERR_EM_INTERPRETER);
3817 break;
3818 }
3819
3820 /* Note: We'll get a #GP if the IO instruction isn't allowed (IOPL or TSS bitmap); no need to double check. */
3821 case VMX_EXIT_PORT_IO: /* 30 I/O instruction. */
3822 {
3823 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3824 uint32_t uIOWidth = VMX_EXIT_QUALIFICATION_IO_WIDTH(exitQualification);
3825 uint32_t uPort;
3826 bool fIOWrite = (VMX_EXIT_QUALIFICATION_IO_DIRECTION(exitQualification) == VMX_EXIT_QUALIFICATION_IO_DIRECTION_OUT);
3827
3828 /** @todo necessary to make the distinction? */
3829 if (VMX_EXIT_QUALIFICATION_IO_ENCODING(exitQualification) == VMX_EXIT_QUALIFICATION_IO_ENCODING_DX)
3830 {
3831 uPort = pCtx->edx & 0xffff;
3832 }
3833 else
3834 uPort = VMX_EXIT_QUALIFICATION_IO_PORT(exitQualification); /* Immediate encoding. */
3835
3836 /* paranoia */
3837 if (RT_UNLIKELY(uIOWidth == 2 || uIOWidth >= 4))
3838 {
3839 rc = fIOWrite ? VINF_IOM_R3_IOPORT_WRITE : VINF_IOM_R3_IOPORT_READ;
3840 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3841 break;
3842 }
3843
3844 uint32_t cbSize = g_aIOSize[uIOWidth];
3845
3846 if (VMX_EXIT_QUALIFICATION_IO_STRING(exitQualification))
3847 {
3848 /* ins/outs */
3849 PDISCPUSTATE pDis = &pVCpu->hwaccm.s.DisState;
3850
3851 /* Disassemble manually to deal with segment prefixes. */
3852 /** @todo VMX_VMCS_EXIT_GUEST_LINEAR_ADDR contains the flat pointer operand of the instruction. */
3853 /** @todo VMX_VMCS32_RO_EXIT_INSTR_INFO also contains segment prefix info. */
3854 rc2 = EMInterpretDisasOne(pVM, pVCpu, CPUMCTX2CORE(pCtx), pDis, NULL);
3855 if (RT_SUCCESS(rc))
3856 {
3857 if (fIOWrite)
3858 {
3859 Log2(("IOMInterpretOUTSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, uPort, cbSize));
3860 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringWrite);
3861 rc = IOMInterpretOUTSEx(pVM, CPUMCTX2CORE(pCtx), uPort, pDis->prefix, pDis->addrmode, cbSize);
3862 }
3863 else
3864 {
3865 Log2(("IOMInterpretINSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, uPort, cbSize));
3866 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringRead);
3867 rc = IOMInterpretINSEx(pVM, CPUMCTX2CORE(pCtx), uPort, pDis->prefix, pDis->addrmode, cbSize);
3868 }
3869 }
3870 else
3871 rc = VINF_EM_RAW_EMULATE_INSTR;
3872 }
3873 else
3874 {
3875 /* normal in/out */
3876 uint32_t uAndVal = g_aIOOpAnd[uIOWidth];
3877
3878 Assert(!VMX_EXIT_QUALIFICATION_IO_REP(exitQualification));
3879
3880 if (fIOWrite)
3881 {
3882 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOWrite);
3883 rc = IOMIOPortWrite(pVM, uPort, pCtx->eax & uAndVal, cbSize);
3884 if (rc == VINF_IOM_R3_IOPORT_WRITE)
3885 HWACCMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pCtx->rip + cbInstr, uPort, uAndVal, cbSize);
3886 }
3887 else
3888 {
3889 uint32_t u32Val = 0;
3890
3891 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIORead);
3892 rc = IOMIOPortRead(pVM, uPort, &u32Val, cbSize);
3893 if (IOM_SUCCESS(rc))
3894 {
3895 /* Write back to the EAX register. */
3896 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
3897 }
3898 else
3899 if (rc == VINF_IOM_R3_IOPORT_READ)
3900 HWACCMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pCtx->rip + cbInstr, uPort, uAndVal, cbSize);
3901 }
3902 }
3903 /*
3904 * Handled the I/O return codes.
3905 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
3906 */
3907 if (IOM_SUCCESS(rc))
3908 {
3909 /* Update EIP and continue execution. */
3910 pCtx->rip += cbInstr;
3911 if (RT_LIKELY(rc == VINF_SUCCESS))
3912 {
3913 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
3914 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
3915 {
3916 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxIOCheck);
3917 for (unsigned i=0;i<4;i++)
3918 {
3919 unsigned uBPLen = g_aIOSize[X86_DR7_GET_LEN(pCtx->dr[7], i)];
3920
3921 if ( (uPort >= pCtx->dr[i] && uPort < pCtx->dr[i] + uBPLen)
3922 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
3923 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
3924 {
3925 uint64_t uDR6;
3926
3927 Assert(CPUMIsGuestDebugStateActive(pVCpu));
3928
3929 uDR6 = ASMGetDR6();
3930
3931 /* Clear all breakpoint status flags and set the one we just hit. */
3932 uDR6 &= ~(X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3);
3933 uDR6 |= (uint64_t)RT_BIT(i);
3934
3935 /* Note: AMD64 Architecture Programmer's Manual 13.1:
3936 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared by software after
3937 * the contents have been read.
3938 */
3939 ASMSetDR6(uDR6);
3940
3941 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
3942 pCtx->dr[7] &= ~X86_DR7_GD;
3943
3944 /* Paranoia. */
3945 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
3946 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
3947 pCtx->dr[7] |= 0x400; /* must be one */
3948
3949 /* Resync DR7 */
3950 rc2 = VMXWriteVMCS64(VMX_VMCS64_GUEST_DR7, pCtx->dr[7]);
3951 AssertRC(rc2);
3952
3953 /* Construct inject info. */
3954 intInfo = X86_XCPT_DB;
3955 intInfo |= (1 << VMX_EXIT_INTERRUPTION_INFO_VALID_SHIFT);
3956 intInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HWEXCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
3957
3958 Log(("Inject IO debug trap at %RGv\n", (RTGCPTR)pCtx->rip));
3959 rc2 = hmR0VmxInjectEvent(pVM, pVCpu, pCtx, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(intInfo), 0, 0);
3960 AssertRC(rc2);
3961
3962 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3963 goto ResumeExecution;
3964 }
3965 }
3966 }
3967 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3968 goto ResumeExecution;
3969 }
3970 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3971 break;
3972 }
3973
3974#ifdef VBOX_STRICT
3975 if (rc == VINF_IOM_R3_IOPORT_READ)
3976 Assert(!fIOWrite);
3977 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
3978 Assert(fIOWrite);
3979 else
3980 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)));
3981#endif
3982 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2Sub1, y1);
3983 break;
3984 }
3985
3986 case VMX_EXIT_TPR: /* 43 TPR below threshold. Guest software executed MOV to CR8. */
3987 LogFlow(("VMX_EXIT_TPR\n"));
3988 /* RIP is already set to the next instruction and the TPR has been synced back. Just resume. */
3989 goto ResumeExecution;
3990
3991 case VMX_EXIT_APIC_ACCESS: /* 44 APIC access. Guest software attempted to access memory at a physical address on the APIC-access page. */
3992 {
3993 LogFlow(("VMX_EXIT_APIC_ACCESS\n"));
3994 unsigned uAccessType = VMX_EXIT_QUALIFICATION_APIC_ACCESS_TYPE(exitQualification);
3995
3996 switch(uAccessType)
3997 {
3998 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
3999 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
4000 {
4001 RTGCPHYS GCPhys;
4002 PDMApicGetBase(pVM, &GCPhys);
4003 GCPhys &= PAGE_BASE_GC_MASK;
4004 GCPhys += VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(exitQualification);
4005
4006 LogFlow(("Apic access at %RGp\n", GCPhys));
4007 rc = IOMMMIOPhysHandler(pVM, (uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ) ? 0 : X86_TRAP_PF_RW, CPUMCTX2CORE(pCtx), GCPhys);
4008 if (rc == VINF_SUCCESS)
4009 goto ResumeExecution; /* rip already updated */
4010 break;
4011 }
4012
4013 default:
4014 rc = VINF_EM_RAW_EMULATE_INSTR;
4015 break;
4016 }
4017 break;
4018 }
4019
4020 case VMX_EXIT_PREEMPTION_TIMER: /* 52 VMX-preemption timer expired. The preemption timer counted down to zero. */
4021 if (!TMTimerPollBool(pVM, pVCpu))
4022 goto ResumeExecution;
4023 rc = VINF_EM_RAW_TIMER_PENDING;
4024 break;
4025
4026 default:
4027 /* The rest is handled after syncing the entire CPU state. */
4028 break;
4029 }
4030
4031 /* Note: the guest state isn't entirely synced back at this stage. */
4032
4033 /* Investigate why there was a VM-exit. (part 2) */
4034 switch (exitReason)
4035 {
4036 case VMX_EXIT_EXCEPTION: /* 0 Exception or non-maskable interrupt (NMI). */
4037 case VMX_EXIT_EXTERNAL_IRQ: /* 1 External interrupt. */
4038 case VMX_EXIT_EPT_VIOLATION:
4039 case VMX_EXIT_EPT_MISCONFIG: /* 49 EPT misconfig is used by the PGM/MMIO optimizations. */
4040 case VMX_EXIT_PREEMPTION_TIMER: /* 52 VMX-preemption timer expired. The preemption timer counted down to zero. */
4041 /* Already handled above. */
4042 break;
4043
4044 case VMX_EXIT_TRIPLE_FAULT: /* 2 Triple fault. */
4045 rc = VINF_EM_RESET; /* Triple fault equals a reset. */
4046 break;
4047
4048 case VMX_EXIT_INIT_SIGNAL: /* 3 INIT signal. */
4049 case VMX_EXIT_SIPI: /* 4 Start-up IPI (SIPI). */
4050 rc = VINF_EM_RAW_INTERRUPT;
4051 AssertFailed(); /* Can't happen. Yet. */
4052 break;
4053
4054 case VMX_EXIT_IO_SMI_IRQ: /* 5 I/O system-management interrupt (SMI). */
4055 case VMX_EXIT_SMI_IRQ: /* 6 Other SMI. */
4056 rc = VINF_EM_RAW_INTERRUPT;
4057 AssertFailed(); /* Can't happen afaik. */
4058 break;
4059
4060 case VMX_EXIT_TASK_SWITCH: /* 9 Task switch: too complicated to emulate, so fall back to the recompiler */
4061 Log(("VMX_EXIT_TASK_SWITCH: exit=%RX64\n", exitQualification));
4062 if ( (VMX_EXIT_QUALIFICATION_TASK_SWITCH_TYPE(exitQualification) == VMX_EXIT_QUALIFICATION_TASK_SWITCH_TYPE_IDT)
4063 && pVCpu->hwaccm.s.Event.fPending)
4064 {
4065 /* Caused by an injected interrupt. */
4066 pVCpu->hwaccm.s.Event.fPending = false;
4067
4068 Log(("VMX_EXIT_TASK_SWITCH: reassert trap %d\n", VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVCpu->hwaccm.s.Event.intInfo)));
4069 Assert(!VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(pVCpu->hwaccm.s.Event.intInfo));
4070 rc2 = TRPMAssertTrap(pVCpu, VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVCpu->hwaccm.s.Event.intInfo), TRPM_HARDWARE_INT);
4071 AssertRC(rc2);
4072 }
4073 /* else Exceptions and software interrupts can just be restarted. */
4074 rc = VERR_EM_INTERPRETER;
4075 break;
4076
4077 case VMX_EXIT_HLT: /* 12 Guest software attempted to execute HLT. */
4078 /* Check if external interrupts are pending; if so, don't switch back. */
4079 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitHlt);
4080 pCtx->rip++; /* skip hlt */
4081 if (EMShouldContinueAfterHalt(pVCpu, pCtx))
4082 goto ResumeExecution;
4083
4084 rc = VINF_EM_HALT;
4085 break;
4086
4087 case VMX_EXIT_MWAIT: /* 36 Guest software executed MWAIT. */
4088 Log2(("VMX: mwait\n"));
4089 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMwait);
4090 rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4091 if ( rc == VINF_EM_HALT
4092 || rc == VINF_SUCCESS)
4093 {
4094 /* Update EIP and continue execution. */
4095 pCtx->rip += cbInstr;
4096
4097 /* Check if external interrupts are pending; if so, don't switch back. */
4098 if ( rc == VINF_SUCCESS
4099 || ( rc == VINF_EM_HALT
4100 && EMShouldContinueAfterHalt(pVCpu, pCtx))
4101 )
4102 goto ResumeExecution;
4103 }
4104 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_EM_HALT, ("EMU: mwait failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
4105 break;
4106
4107 case VMX_EXIT_RSM: /* 17 Guest software attempted to execute RSM in SMM. */
4108 AssertFailed(); /* can't happen. */
4109 rc = VERR_EM_INTERPRETER;
4110 break;
4111
4112 case VMX_EXIT_VMCALL: /* 18 Guest software executed VMCALL. */
4113 case VMX_EXIT_VMCLEAR: /* 19 Guest software executed VMCLEAR. */
4114 case VMX_EXIT_VMLAUNCH: /* 20 Guest software executed VMLAUNCH. */
4115 case VMX_EXIT_VMPTRLD: /* 21 Guest software executed VMPTRLD. */
4116 case VMX_EXIT_VMPTRST: /* 22 Guest software executed VMPTRST. */
4117 case VMX_EXIT_VMREAD: /* 23 Guest software executed VMREAD. */
4118 case VMX_EXIT_VMRESUME: /* 24 Guest software executed VMRESUME. */
4119 case VMX_EXIT_VMWRITE: /* 25 Guest software executed VMWRITE. */
4120 case VMX_EXIT_VMXOFF: /* 26 Guest software executed VMXOFF. */
4121 case VMX_EXIT_VMXON: /* 27 Guest software executed VMXON. */
4122 /** @todo inject #UD immediately */
4123 rc = VERR_EM_INTERPRETER;
4124 break;
4125
4126 case VMX_EXIT_CPUID: /* 10 Guest software attempted to execute CPUID. */
4127 case VMX_EXIT_RDTSC: /* 16 Guest software attempted to execute RDTSC. */
4128 case VMX_EXIT_INVPG: /* 14 Guest software attempted to execute INVPG. */
4129 case VMX_EXIT_CRX_MOVE: /* 28 Control-register accesses. */
4130 case VMX_EXIT_DRX_MOVE: /* 29 Debug-register accesses. */
4131 case VMX_EXIT_PORT_IO: /* 30 I/O instruction. */
4132 case VMX_EXIT_RDPMC: /* 15 Guest software attempted to execute RDPMC. */
4133 /* already handled above */
4134 AssertMsg( rc == VINF_PGM_CHANGE_MODE
4135 || rc == VINF_EM_RAW_INTERRUPT
4136 || rc == VERR_EM_INTERPRETER
4137 || rc == VINF_EM_RAW_EMULATE_INSTR
4138 || rc == VINF_PGM_SYNC_CR3
4139 || rc == VINF_IOM_R3_IOPORT_READ
4140 || rc == VINF_IOM_R3_IOPORT_WRITE
4141 || rc == VINF_EM_RAW_GUEST_TRAP
4142 || rc == VINF_TRPM_XCPT_DISPATCHED
4143 || rc == VINF_EM_RESCHEDULE_REM,
4144 ("rc = %d\n", VBOXSTRICTRC_VAL(rc)));
4145 break;
4146
4147 case VMX_EXIT_TPR: /* 43 TPR below threshold. Guest software executed MOV to CR8. */
4148 case VMX_EXIT_APIC_ACCESS: /* 44 APIC access. Guest software attempted to access memory at a physical address on the APIC-access page. */
4149 case VMX_EXIT_RDMSR: /* 31 RDMSR. Guest software attempted to execute RDMSR. */
4150 case VMX_EXIT_WRMSR: /* 32 WRMSR. Guest software attempted to execute WRMSR. */
4151 case VMX_EXIT_PAUSE: /* 40 Guest software attempted to execute PAUSE. */
4152 case VMX_EXIT_MONITOR: /* 39 Guest software attempted to execute MONITOR. */
4153 /* Note: If we decide to emulate them here, then we must sync the MSRs that could have been changed (sysenter, fs/gs base)!!! */
4154 rc = VERR_EM_INTERPRETER;
4155 break;
4156
4157 case VMX_EXIT_IRQ_WINDOW: /* 7 Interrupt window. */
4158 Assert(rc == VINF_EM_RAW_INTERRUPT);
4159 break;
4160
4161 case VMX_EXIT_ERR_INVALID_GUEST_STATE: /* 33 VM-entry failure due to invalid guest state. */
4162 {
4163#ifdef VBOX_STRICT
4164 RTCCUINTREG val2 = 0;
4165
4166 Log(("VMX_EXIT_ERR_INVALID_GUEST_STATE\n"));
4167
4168 VMXReadVMCS(VMX_VMCS64_GUEST_RIP, &val2);
4169 Log(("Old eip %RGv new %RGv\n", (RTGCPTR)pCtx->rip, (RTGCPTR)val2));
4170
4171 VMXReadVMCS(VMX_VMCS64_GUEST_CR0, &val2);
4172 Log(("VMX_VMCS_GUEST_CR0 %RX64\n", (uint64_t)val2));
4173
4174 VMXReadVMCS(VMX_VMCS64_GUEST_CR3, &val2);
4175 Log(("VMX_VMCS_GUEST_CR3 %RX64\n", (uint64_t)val2));
4176
4177 VMXReadVMCS(VMX_VMCS64_GUEST_CR4, &val2);
4178 Log(("VMX_VMCS_GUEST_CR4 %RX64\n", (uint64_t)val2));
4179
4180 VMXReadVMCS(VMX_VMCS_GUEST_RFLAGS, &val2);
4181 Log(("VMX_VMCS_GUEST_RFLAGS %08x\n", val2));
4182
4183 VMX_LOG_SELREG(CS, "CS", val2);
4184 VMX_LOG_SELREG(DS, "DS", val2);
4185 VMX_LOG_SELREG(ES, "ES", val2);
4186 VMX_LOG_SELREG(FS, "FS", val2);
4187 VMX_LOG_SELREG(GS, "GS", val2);
4188 VMX_LOG_SELREG(SS, "SS", val2);
4189 VMX_LOG_SELREG(TR, "TR", val2);
4190 VMX_LOG_SELREG(LDTR, "LDTR", val2);
4191
4192 VMXReadVMCS(VMX_VMCS64_GUEST_GDTR_BASE, &val2);
4193 Log(("VMX_VMCS_GUEST_GDTR_BASE %RX64\n", (uint64_t)val2));
4194 VMXReadVMCS(VMX_VMCS64_GUEST_IDTR_BASE, &val2);
4195 Log(("VMX_VMCS_GUEST_IDTR_BASE %RX64\n", (uint64_t)val2));
4196#endif /* VBOX_STRICT */
4197 rc = VERR_VMX_INVALID_GUEST_STATE;
4198 break;
4199 }
4200
4201 case VMX_EXIT_ERR_MSR_LOAD: /* 34 VM-entry failure due to MSR loading. */
4202 case VMX_EXIT_ERR_MACHINE_CHECK: /* 41 VM-entry failure due to machine-check. */
4203 default:
4204 rc = VERR_VMX_UNEXPECTED_EXIT_CODE;
4205 AssertMsgFailed(("Unexpected exit code %d\n", exitReason)); /* Can't happen. */
4206 break;
4207
4208 }
4209end:
4210
4211 /* We now going back to ring-3, so clear the action flag. */
4212 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
4213
4214 /* Signal changes for the recompiler. */
4215 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR | CPUM_CHANGED_LDTR | CPUM_CHANGED_GDTR | CPUM_CHANGED_IDTR | CPUM_CHANGED_TR | CPUM_CHANGED_HIDDEN_SEL_REGS);
4216
4217 /* If we executed vmlaunch/vmresume and an external irq was pending, then we don't have to do a full sync the next time. */
4218 if ( exitReason == VMX_EXIT_EXTERNAL_IRQ
4219 && !VMX_EXIT_INTERRUPTION_INFO_VALID(intInfo))
4220 {
4221 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatPendingHostIrq);
4222 /* On the next entry we'll only sync the host context. */
4223 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_HOST_CONTEXT;
4224 }
4225 else
4226 {
4227 /* On the next entry we'll sync everything. */
4228 /** @todo we can do better than this */
4229 /* Not in the VINF_PGM_CHANGE_MODE though! */
4230 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_ALL;
4231 }
4232
4233 /* translate into a less severe return code */
4234 if (rc == VERR_EM_INTERPRETER)
4235 rc = VINF_EM_RAW_EMULATE_INSTR;
4236 else
4237 /* Try to extract more information about what might have gone wrong here. */
4238 if (rc == VERR_VMX_INVALID_VMCS_PTR)
4239 {
4240 VMXGetActivateVMCS(&pVCpu->hwaccm.s.vmx.lasterror.u64VMCSPhys);
4241 pVCpu->hwaccm.s.vmx.lasterror.ulVMCSRevision = *(uint32_t *)pVCpu->hwaccm.s.vmx.pvVMCS;
4242 pVCpu->hwaccm.s.vmx.lasterror.idEnteredCpu = pVCpu->hwaccm.s.idEnteredCpu;
4243 pVCpu->hwaccm.s.vmx.lasterror.idCurrentCpu = RTMpCpuId();
4244 }
4245
4246 /* Just set the correct state here instead of trying to catch every goto above. */
4247 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC);
4248
4249#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
4250 /* Restore interrupts if we exitted after disabling them. */
4251 if (uOldEFlags != ~(RTCCUINTREG)0)
4252 ASMSetFlags(uOldEFlags);
4253#endif
4254
4255 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2, x);
4256 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit1, x);
4257 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatEntry, x);
4258 Log2(("X"));
4259 return VBOXSTRICTRC_TODO(rc);
4260}
4261
4262
4263/**
4264 * Enters the VT-x session
4265 *
4266 * @returns VBox status code.
4267 * @param pVM The VM to operate on.
4268 * @param pVCpu The VMCPU to operate on.
4269 * @param pCpu CPU info struct
4270 */
4271VMMR0DECL(int) VMXR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
4272{
4273 Assert(pVM->hwaccm.s.vmx.fSupported);
4274 NOREF(pCpu);
4275
4276 unsigned cr4 = ASMGetCR4();
4277 if (!(cr4 & X86_CR4_VMXE))
4278 {
4279 AssertMsgFailed(("X86_CR4_VMXE should be set!\n"));
4280 return VERR_VMX_X86_CR4_VMXE_CLEARED;
4281 }
4282
4283 /* Activate the VM Control Structure. */
4284 int rc = VMXActivateVMCS(pVCpu->hwaccm.s.vmx.HCPhysVMCS);
4285 if (RT_FAILURE(rc))
4286 return rc;
4287
4288 pVCpu->hwaccm.s.fResumeVM = false;
4289 return VINF_SUCCESS;
4290}
4291
4292
4293/**
4294 * Leaves the VT-x session
4295 *
4296 * @returns VBox status code.
4297 * @param pVM The VM to operate on.
4298 * @param pVCpu The VMCPU to operate on.
4299 * @param pCtx CPU context
4300 */
4301VMMR0DECL(int) VMXR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4302{
4303 Assert(pVM->hwaccm.s.vmx.fSupported);
4304
4305#ifdef DEBUG
4306 if (CPUMIsHyperDebugStateActive(pVCpu))
4307 {
4308 CPUMR0LoadHostDebugState(pVM, pVCpu);
4309 Assert(pVCpu->hwaccm.s.vmx.proc_ctls & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT);
4310 }
4311 else
4312#endif
4313 /* Save the guest debug state if necessary. */
4314 if (CPUMIsGuestDebugStateActive(pVCpu))
4315 {
4316 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, true /* save DR6 */);
4317
4318 /* Enable drx move intercepts again. */
4319 pVCpu->hwaccm.s.vmx.proc_ctls |= VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT;
4320 int rc = VMXWriteVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, pVCpu->hwaccm.s.vmx.proc_ctls);
4321 AssertRC(rc);
4322
4323 /* Resync the debug registers the next time. */
4324 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
4325 }
4326 else
4327 Assert(pVCpu->hwaccm.s.vmx.proc_ctls & VMX_VMCS_CTRL_PROC_EXEC_CONTROLS_MOV_DR_EXIT);
4328
4329 /* Clear VM Control Structure. Marking it inactive, clearing implementation specific data and writing back VMCS data to memory. */
4330 int rc = VMXClearVMCS(pVCpu->hwaccm.s.vmx.HCPhysVMCS);
4331 AssertRC(rc);
4332
4333 return VINF_SUCCESS;
4334}
4335
4336/**
4337 * Flush the TLB (EPT)
4338 *
4339 * @returns VBox status code.
4340 * @param pVM The VM to operate on.
4341 * @param pVCpu The VM CPU to operate on.
4342 * @param enmFlush Type of flush
4343 * @param GCPhys Physical address of the page to flush
4344 */
4345static void hmR0VmxFlushEPT(PVM pVM, PVMCPU pVCpu, VMX_FLUSH enmFlush, RTGCPHYS GCPhys)
4346{
4347 uint64_t descriptor[2];
4348
4349 LogFlow(("hmR0VmxFlushEPT %d %RGv\n", enmFlush, GCPhys));
4350 Assert(pVM->hwaccm.s.fNestedPaging);
4351 descriptor[0] = pVCpu->hwaccm.s.vmx.GCPhysEPTP;
4352 descriptor[1] = GCPhys;
4353 int rc = VMXR0InvEPT(enmFlush, &descriptor[0]);
4354 AssertRC(rc);
4355}
4356
4357#ifdef HWACCM_VTX_WITH_VPID
4358/**
4359 * Flush the TLB (EPT)
4360 *
4361 * @returns VBox status code.
4362 * @param pVM The VM to operate on.
4363 * @param pVCpu The VM CPU to operate on.
4364 * @param enmFlush Type of flush
4365 * @param GCPtr Virtual address of the page to flush
4366 */
4367static void hmR0VmxFlushVPID(PVM pVM, PVMCPU pVCpu, VMX_FLUSH enmFlush, RTGCPTR GCPtr)
4368{
4369#if HC_ARCH_BITS == 32
4370 /* If we get a flush in 64 bits guest mode, then force a full TLB flush. Invvpid probably takes only 32 bits addresses. (@todo) */
4371 if ( CPUMIsGuestInLongMode(pVCpu)
4372 && !VMX_IS_64BIT_HOST_MODE())
4373 {
4374 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
4375 }
4376 else
4377#endif
4378 {
4379 uint64_t descriptor[2];
4380
4381 Assert(pVM->hwaccm.s.vmx.fVPID);
4382 descriptor[0] = pVCpu->hwaccm.s.uCurrentASID;
4383 descriptor[1] = GCPtr;
4384 int rc = VMXR0InvVPID(enmFlush, &descriptor[0]); NOREF(rc);
4385 AssertMsg(rc == VINF_SUCCESS, ("VMXR0InvVPID %x %x %RGv failed with %d\n", enmFlush, pVCpu->hwaccm.s.uCurrentASID, GCPtr, rc));
4386 }
4387}
4388#endif /* HWACCM_VTX_WITH_VPID */
4389
4390/**
4391 * Invalidates a guest page
4392 *
4393 * @returns VBox status code.
4394 * @param pVM The VM to operate on.
4395 * @param pVCpu The VM CPU to operate on.
4396 * @param GCVirt Page to invalidate
4397 */
4398VMMR0DECL(int) VMXR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
4399{
4400 bool fFlushPending = VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
4401
4402 Log2(("VMXR0InvalidatePage %RGv\n", GCVirt));
4403
4404 /* Only relevant if we want to use VPID.
4405 * In the nested paging case we still see such calls, but
4406 * can safely ignore them. (e.g. after cr3 updates)
4407 */
4408#ifdef HWACCM_VTX_WITH_VPID
4409 /* Skip it if a TLB flush is already pending. */
4410 if ( !fFlushPending
4411 && pVM->hwaccm.s.vmx.fVPID)
4412 hmR0VmxFlushVPID(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushPage, GCVirt);
4413#endif /* HWACCM_VTX_WITH_VPID */
4414
4415 return VINF_SUCCESS;
4416}
4417
4418/**
4419 * Invalidates a guest page by physical address
4420 *
4421 * NOTE: Assumes the current instruction references this physical page though a virtual address!!
4422 *
4423 * @returns VBox status code.
4424 * @param pVM The VM to operate on.
4425 * @param pVCpu The VM CPU to operate on.
4426 * @param GCPhys Page to invalidate
4427 */
4428VMMR0DECL(int) VMXR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
4429{
4430 bool fFlushPending = VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
4431
4432 Assert(pVM->hwaccm.s.fNestedPaging);
4433
4434 LogFlow(("VMXR0InvalidatePhysPage %RGp\n", GCPhys));
4435
4436 /* Skip it if a TLB flush is already pending. */
4437 if (!fFlushPending)
4438 hmR0VmxFlushEPT(pVM, pVCpu, pVM->hwaccm.s.vmx.enmFlushPage, GCPhys);
4439
4440 return VINF_SUCCESS;
4441}
4442
4443/**
4444 * Report world switch error and dump some useful debug info
4445 *
4446 * @param pVM The VM to operate on.
4447 * @param pVCpu The VMCPU to operate on.
4448 * @param rc Return code
4449 * @param pCtx Current CPU context (not updated)
4450 */
4451static void hmR0VmxReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, VBOXSTRICTRC rc, PCPUMCTX pCtx)
4452{
4453 NOREF(pVM);
4454
4455 switch (VBOXSTRICTRC_VAL(rc))
4456 {
4457 case VERR_VMX_INVALID_VMXON_PTR:
4458 AssertFailed();
4459 break;
4460
4461 case VERR_VMX_UNABLE_TO_START_VM:
4462 case VERR_VMX_UNABLE_TO_RESUME_VM:
4463 {
4464 int rc2;
4465 RTCCUINTREG exitReason, instrError;
4466
4467 rc2 = VMXReadVMCS(VMX_VMCS32_RO_EXIT_REASON, &exitReason);
4468 rc2 |= VMXReadVMCS(VMX_VMCS32_RO_VM_INSTR_ERROR, &instrError);
4469 AssertRC(rc2);
4470 if (rc2 == VINF_SUCCESS)
4471 {
4472 Log(("Unable to start/resume VM for reason: %x. Instruction error %x\n", (uint32_t)exitReason, (uint32_t)instrError));
4473 Log(("Current stack %08x\n", &rc2));
4474
4475 pVCpu->hwaccm.s.vmx.lasterror.ulInstrError = instrError;
4476 pVCpu->hwaccm.s.vmx.lasterror.ulExitReason = exitReason;
4477
4478#ifdef VBOX_STRICT
4479 RTGDTR gdtr;
4480 PCX86DESCHC pDesc;
4481 RTCCUINTREG val;
4482
4483 ASMGetGDTR(&gdtr);
4484
4485 VMXReadVMCS(VMX_VMCS64_GUEST_RIP, &val);
4486 Log(("Old eip %RGv new %RGv\n", (RTGCPTR)pCtx->rip, (RTGCPTR)val));
4487 VMXReadVMCS(VMX_VMCS_CTRL_PIN_EXEC_CONTROLS, &val);
4488 Log(("VMX_VMCS_CTRL_PIN_EXEC_CONTROLS %08x\n", val));
4489 VMXReadVMCS(VMX_VMCS_CTRL_PROC_EXEC_CONTROLS, &val);
4490 Log(("VMX_VMCS_CTRL_PROC_EXEC_CONTROLS %08x\n", val));
4491 VMXReadVMCS(VMX_VMCS_CTRL_ENTRY_CONTROLS, &val);
4492 Log(("VMX_VMCS_CTRL_ENTRY_CONTROLS %08x\n", val));
4493 VMXReadVMCS(VMX_VMCS_CTRL_EXIT_CONTROLS, &val);
4494 Log(("VMX_VMCS_CTRL_EXIT_CONTROLS %08x\n", val));
4495
4496 VMXReadVMCS(VMX_VMCS_HOST_CR0, &val);
4497 Log(("VMX_VMCS_HOST_CR0 %08x\n", val));
4498
4499 VMXReadVMCS(VMX_VMCS_HOST_CR3, &val);
4500 Log(("VMX_VMCS_HOST_CR3 %08x\n", val));
4501
4502 VMXReadVMCS(VMX_VMCS_HOST_CR4, &val);
4503 Log(("VMX_VMCS_HOST_CR4 %08x\n", val));
4504
4505 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_CS, &val);
4506 Log(("VMX_VMCS_HOST_FIELD_CS %08x\n", val));
4507
4508 VMXReadVMCS(VMX_VMCS_GUEST_RFLAGS, &val);
4509 Log(("VMX_VMCS_GUEST_RFLAGS %08x\n", val));
4510
4511 if (val < gdtr.cbGdt)
4512 {
4513 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4514 HWACCMR0DumpDescriptor(pDesc, val, "CS: ");
4515 }
4516
4517 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_DS, &val);
4518 Log(("VMX_VMCS_HOST_FIELD_DS %08x\n", val));
4519 if (val < gdtr.cbGdt)
4520 {
4521 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4522 HWACCMR0DumpDescriptor(pDesc, val, "DS: ");
4523 }
4524
4525 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_ES, &val);
4526 Log(("VMX_VMCS_HOST_FIELD_ES %08x\n", val));
4527 if (val < gdtr.cbGdt)
4528 {
4529 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4530 HWACCMR0DumpDescriptor(pDesc, val, "ES: ");
4531 }
4532
4533 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_FS, &val);
4534 Log(("VMX_VMCS16_HOST_FIELD_FS %08x\n", val));
4535 if (val < gdtr.cbGdt)
4536 {
4537 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4538 HWACCMR0DumpDescriptor(pDesc, val, "FS: ");
4539 }
4540
4541 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_GS, &val);
4542 Log(("VMX_VMCS16_HOST_FIELD_GS %08x\n", val));
4543 if (val < gdtr.cbGdt)
4544 {
4545 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4546 HWACCMR0DumpDescriptor(pDesc, val, "GS: ");
4547 }
4548
4549 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_SS, &val);
4550 Log(("VMX_VMCS16_HOST_FIELD_SS %08x\n", val));
4551 if (val < gdtr.cbGdt)
4552 {
4553 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4554 HWACCMR0DumpDescriptor(pDesc, val, "SS: ");
4555 }
4556
4557 VMXReadVMCS(VMX_VMCS16_HOST_FIELD_TR, &val);
4558 Log(("VMX_VMCS16_HOST_FIELD_TR %08x\n", val));
4559 if (val < gdtr.cbGdt)
4560 {
4561 pDesc = (PCX86DESCHC)(gdtr.pGdt + (val & X86_SEL_MASK));
4562 HWACCMR0DumpDescriptor(pDesc, val, "TR: ");
4563 }
4564
4565 VMXReadVMCS(VMX_VMCS_HOST_TR_BASE, &val);
4566 Log(("VMX_VMCS_HOST_TR_BASE %RHv\n", val));
4567
4568 VMXReadVMCS(VMX_VMCS_HOST_GDTR_BASE, &val);
4569 Log(("VMX_VMCS_HOST_GDTR_BASE %RHv\n", val));
4570 VMXReadVMCS(VMX_VMCS_HOST_IDTR_BASE, &val);
4571 Log(("VMX_VMCS_HOST_IDTR_BASE %RHv\n", val));
4572
4573 VMXReadVMCS(VMX_VMCS32_HOST_SYSENTER_CS, &val);
4574 Log(("VMX_VMCS_HOST_SYSENTER_CS %08x\n", val));
4575
4576 VMXReadVMCS(VMX_VMCS_HOST_SYSENTER_EIP, &val);
4577 Log(("VMX_VMCS_HOST_SYSENTER_EIP %RHv\n", val));
4578
4579 VMXReadVMCS(VMX_VMCS_HOST_SYSENTER_ESP, &val);
4580 Log(("VMX_VMCS_HOST_SYSENTER_ESP %RHv\n", val));
4581
4582 VMXReadVMCS(VMX_VMCS_HOST_RSP, &val);
4583 Log(("VMX_VMCS_HOST_RSP %RHv\n", val));
4584 VMXReadVMCS(VMX_VMCS_HOST_RIP, &val);
4585 Log(("VMX_VMCS_HOST_RIP %RHv\n", val));
4586
4587# if HC_ARCH_BITS == 64 || defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
4588 if (VMX_IS_64BIT_HOST_MODE())
4589 {
4590 Log(("MSR_K6_EFER = %RX64\n", ASMRdMsr(MSR_K6_EFER)));
4591 Log(("MSR_K6_STAR = %RX64\n", ASMRdMsr(MSR_K6_STAR)));
4592 Log(("MSR_K8_LSTAR = %RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
4593 Log(("MSR_K8_CSTAR = %RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
4594 Log(("MSR_K8_SF_MASK = %RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
4595 }
4596# endif
4597#endif /* VBOX_STRICT */
4598 }
4599 break;
4600 }
4601
4602 default:
4603 /* impossible */
4604 AssertMsgFailed(("%Rrc (%#x)\n", VBOXSTRICTRC_VAL(rc), VBOXSTRICTRC_VAL(rc)));
4605 break;
4606 }
4607}
4608
4609#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
4610
4611/**
4612 * Prepares for and executes VMLAUNCH (64 bits guest mode)
4613 *
4614 * @returns VBox status code
4615 * @param fResume vmlauch/vmresume
4616 * @param pCtx Guest context
4617 * @param pCache VMCS cache
4618 * @param pVM The VM to operate on.
4619 * @param pVCpu The VMCPU to operate on.
4620 */
4621DECLASM(int) VMXR0SwitcherStartVM64(RTHCUINT fResume, PCPUMCTX pCtx, PVMCSCACHE pCache, PVM pVM, PVMCPU pVCpu)
4622{
4623 uint32_t aParam[6];
4624 PHMGLOBLCPUINFO pCpu;
4625 RTHCPHYS HCPhysCpuPage;
4626 int rc;
4627
4628 pCpu = HWACCMR0GetCurrentCpu();
4629 HCPhysCpuPage = RTR0MemObjGetPagePhysAddr(pCpu->hMemObj, 0);
4630
4631#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4632 pCache->uPos = 1;
4633 pCache->interPD = PGMGetInterPaeCR3(pVM);
4634 pCache->pSwitcher = (uint64_t)pVM->hwaccm.s.pfnHost32ToGuest64R0;
4635#endif
4636
4637#ifdef DEBUG
4638 pCache->TestIn.HCPhysCpuPage= 0;
4639 pCache->TestIn.HCPhysVMCS = 0;
4640 pCache->TestIn.pCache = 0;
4641 pCache->TestOut.HCPhysVMCS = 0;
4642 pCache->TestOut.pCache = 0;
4643 pCache->TestOut.pCtx = 0;
4644 pCache->TestOut.eflags = 0;
4645#endif
4646
4647 aParam[0] = (uint32_t)(HCPhysCpuPage); /* Param 1: VMXON physical address - Lo. */
4648 aParam[1] = (uint32_t)(HCPhysCpuPage >> 32); /* Param 1: VMXON physical address - Hi. */
4649 aParam[2] = (uint32_t)(pVCpu->hwaccm.s.vmx.HCPhysVMCS); /* Param 2: VMCS physical address - Lo. */
4650 aParam[3] = (uint32_t)(pVCpu->hwaccm.s.vmx.HCPhysVMCS >> 32); /* Param 2: VMCS physical address - Hi. */
4651 aParam[4] = VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hwaccm.s.vmx.VMCSCache);
4652 aParam[5] = 0;
4653
4654#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4655 pCtx->dr[4] = pVM->hwaccm.s.vmx.pScratchPhys + 16 + 8;
4656 *(uint32_t *)(pVM->hwaccm.s.vmx.pScratch + 16 + 8) = 1;
4657#endif
4658 rc = VMXR0Execute64BitsHandler(pVM, pVCpu, pCtx, pVM->hwaccm.s.pfnVMXGCStartVM64, 6, &aParam[0]);
4659
4660#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4661 Assert(*(uint32_t *)(pVM->hwaccm.s.vmx.pScratch + 16 + 8) == 5);
4662 Assert(pCtx->dr[4] == 10);
4663 *(uint32_t *)(pVM->hwaccm.s.vmx.pScratch + 16 + 8) = 0xff;
4664#endif
4665
4666#ifdef DEBUG
4667 AssertMsg(pCache->TestIn.HCPhysCpuPage== HCPhysCpuPage, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysCpuPage, HCPhysCpuPage));
4668 AssertMsg(pCache->TestIn.HCPhysVMCS == pVCpu->hwaccm.s.vmx.HCPhysVMCS, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysVMCS, pVCpu->hwaccm.s.vmx.HCPhysVMCS));
4669 AssertMsg(pCache->TestIn.HCPhysVMCS == pCache->TestOut.HCPhysVMCS, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysVMCS, pCache->TestOut.HCPhysVMCS));
4670 AssertMsg(pCache->TestIn.pCache == pCache->TestOut.pCache, ("%RGv vs %RGv\n", pCache->TestIn.pCache, pCache->TestOut.pCache));
4671 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)));
4672 AssertMsg(pCache->TestIn.pCtx == pCache->TestOut.pCtx, ("%RGv vs %RGv\n", pCache->TestIn.pCtx, pCache->TestOut.pCtx));
4673 Assert(!(pCache->TestOut.eflags & X86_EFL_IF));
4674#endif
4675 return rc;
4676}
4677
4678# ifdef VBOX_STRICT
4679
4680static bool hmR0VmxIsValidReadField(uint32_t idxField)
4681{
4682 switch(idxField)
4683 {
4684 case VMX_VMCS64_GUEST_RIP:
4685 case VMX_VMCS64_GUEST_RSP:
4686 case VMX_VMCS_GUEST_RFLAGS:
4687 case VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE:
4688 case VMX_VMCS_CTRL_CR0_READ_SHADOW:
4689 case VMX_VMCS64_GUEST_CR0:
4690 case VMX_VMCS_CTRL_CR4_READ_SHADOW:
4691 case VMX_VMCS64_GUEST_CR4:
4692 case VMX_VMCS64_GUEST_DR7:
4693 case VMX_VMCS32_GUEST_SYSENTER_CS:
4694 case VMX_VMCS64_GUEST_SYSENTER_EIP:
4695 case VMX_VMCS64_GUEST_SYSENTER_ESP:
4696 case VMX_VMCS32_GUEST_GDTR_LIMIT:
4697 case VMX_VMCS64_GUEST_GDTR_BASE:
4698 case VMX_VMCS32_GUEST_IDTR_LIMIT:
4699 case VMX_VMCS64_GUEST_IDTR_BASE:
4700 case VMX_VMCS16_GUEST_FIELD_CS:
4701 case VMX_VMCS32_GUEST_CS_LIMIT:
4702 case VMX_VMCS64_GUEST_CS_BASE:
4703 case VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS:
4704 case VMX_VMCS16_GUEST_FIELD_DS:
4705 case VMX_VMCS32_GUEST_DS_LIMIT:
4706 case VMX_VMCS64_GUEST_DS_BASE:
4707 case VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS:
4708 case VMX_VMCS16_GUEST_FIELD_ES:
4709 case VMX_VMCS32_GUEST_ES_LIMIT:
4710 case VMX_VMCS64_GUEST_ES_BASE:
4711 case VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS:
4712 case VMX_VMCS16_GUEST_FIELD_FS:
4713 case VMX_VMCS32_GUEST_FS_LIMIT:
4714 case VMX_VMCS64_GUEST_FS_BASE:
4715 case VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS:
4716 case VMX_VMCS16_GUEST_FIELD_GS:
4717 case VMX_VMCS32_GUEST_GS_LIMIT:
4718 case VMX_VMCS64_GUEST_GS_BASE:
4719 case VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS:
4720 case VMX_VMCS16_GUEST_FIELD_SS:
4721 case VMX_VMCS32_GUEST_SS_LIMIT:
4722 case VMX_VMCS64_GUEST_SS_BASE:
4723 case VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS:
4724 case VMX_VMCS16_GUEST_FIELD_LDTR:
4725 case VMX_VMCS32_GUEST_LDTR_LIMIT:
4726 case VMX_VMCS64_GUEST_LDTR_BASE:
4727 case VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS:
4728 case VMX_VMCS16_GUEST_FIELD_TR:
4729 case VMX_VMCS32_GUEST_TR_LIMIT:
4730 case VMX_VMCS64_GUEST_TR_BASE:
4731 case VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS:
4732 case VMX_VMCS32_RO_EXIT_REASON:
4733 case VMX_VMCS32_RO_VM_INSTR_ERROR:
4734 case VMX_VMCS32_RO_EXIT_INSTR_LENGTH:
4735 case VMX_VMCS32_RO_EXIT_INTERRUPTION_ERRCODE:
4736 case VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO:
4737 case VMX_VMCS32_RO_EXIT_INSTR_INFO:
4738 case VMX_VMCS_RO_EXIT_QUALIFICATION:
4739 case VMX_VMCS32_RO_IDT_INFO:
4740 case VMX_VMCS32_RO_IDT_ERRCODE:
4741 case VMX_VMCS64_GUEST_CR3:
4742 case VMX_VMCS_EXIT_PHYS_ADDR_FULL:
4743 return true;
4744 }
4745 return false;
4746}
4747
4748static bool hmR0VmxIsValidWriteField(uint32_t idxField)
4749{
4750 switch(idxField)
4751 {
4752 case VMX_VMCS64_GUEST_LDTR_BASE:
4753 case VMX_VMCS64_GUEST_TR_BASE:
4754 case VMX_VMCS64_GUEST_GDTR_BASE:
4755 case VMX_VMCS64_GUEST_IDTR_BASE:
4756 case VMX_VMCS64_GUEST_SYSENTER_EIP:
4757 case VMX_VMCS64_GUEST_SYSENTER_ESP:
4758 case VMX_VMCS64_GUEST_CR0:
4759 case VMX_VMCS64_GUEST_CR4:
4760 case VMX_VMCS64_GUEST_CR3:
4761 case VMX_VMCS64_GUEST_DR7:
4762 case VMX_VMCS64_GUEST_RIP:
4763 case VMX_VMCS64_GUEST_RSP:
4764 case VMX_VMCS64_GUEST_CS_BASE:
4765 case VMX_VMCS64_GUEST_DS_BASE:
4766 case VMX_VMCS64_GUEST_ES_BASE:
4767 case VMX_VMCS64_GUEST_FS_BASE:
4768 case VMX_VMCS64_GUEST_GS_BASE:
4769 case VMX_VMCS64_GUEST_SS_BASE:
4770 return true;
4771 }
4772 return false;
4773}
4774
4775# endif /* VBOX_STRICT */
4776
4777/**
4778 * Executes the specified handler in 64 mode
4779 *
4780 * @returns VBox status code.
4781 * @param pVM The VM to operate on.
4782 * @param pVCpu The VMCPU to operate on.
4783 * @param pCtx Guest context
4784 * @param pfnHandler RC handler
4785 * @param cbParam Number of parameters
4786 * @param paParam Array of 32 bits parameters
4787 */
4788VMMR0DECL(int) VMXR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, RTRCPTR pfnHandler, uint32_t cbParam, uint32_t *paParam)
4789{
4790 int rc, rc2;
4791 PHMGLOBLCPUINFO pCpu;
4792 RTHCPHYS HCPhysCpuPage;
4793 RTHCUINTREG uOldEFlags;
4794
4795 AssertReturn(pVM->hwaccm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
4796 Assert(pfnHandler);
4797 Assert(pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries <= RT_ELEMENTS(pVCpu->hwaccm.s.vmx.VMCSCache.Write.aField));
4798 Assert(pVCpu->hwaccm.s.vmx.VMCSCache.Read.cValidEntries <= RT_ELEMENTS(pVCpu->hwaccm.s.vmx.VMCSCache.Read.aField));
4799
4800#ifdef VBOX_STRICT
4801 for (unsigned i=0;i<pVCpu->hwaccm.s.vmx.VMCSCache.Write.cValidEntries;i++)
4802 Assert(hmR0VmxIsValidWriteField(pVCpu->hwaccm.s.vmx.VMCSCache.Write.aField[i]));
4803
4804 for (unsigned i=0;i<pVCpu->hwaccm.s.vmx.VMCSCache.Read.cValidEntries;i++)
4805 Assert(hmR0VmxIsValidReadField(pVCpu->hwaccm.s.vmx.VMCSCache.Read.aField[i]));
4806#endif
4807
4808 /* Disable interrupts. */
4809 uOldEFlags = ASMIntDisableFlags();
4810
4811 pCpu = HWACCMR0GetCurrentCpu();
4812 HCPhysCpuPage = RTR0MemObjGetPagePhysAddr(pCpu->hMemObj, 0);
4813
4814 /* Clear VM Control Structure. Marking it inactive, clearing implementation specific data and writing back VMCS data to memory. */
4815 VMXClearVMCS(pVCpu->hwaccm.s.vmx.HCPhysVMCS);
4816
4817 /* Leave VMX Root Mode. */
4818 VMXDisable();
4819
4820 ASMSetCR4(ASMGetCR4() & ~X86_CR4_VMXE);
4821
4822 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
4823 CPUMSetHyperEIP(pVCpu, pfnHandler);
4824 for (int i=(int)cbParam-1;i>=0;i--)
4825 CPUMPushHyper(pVCpu, paParam[i]);
4826
4827 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
4828 /* Call switcher. */
4829 rc = pVM->hwaccm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
4830 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
4831
4832 /* Make sure the VMX instructions don't cause #UD faults. */
4833 ASMSetCR4(ASMGetCR4() | X86_CR4_VMXE);
4834
4835 /* Enter VMX Root Mode */
4836 rc2 = VMXEnable(HCPhysCpuPage);
4837 if (RT_FAILURE(rc2))
4838 {
4839 ASMSetCR4(ASMGetCR4() & ~X86_CR4_VMXE);
4840 ASMSetFlags(uOldEFlags);
4841 return VERR_VMX_VMXON_FAILED;
4842 }
4843
4844 rc2 = VMXActivateVMCS(pVCpu->hwaccm.s.vmx.HCPhysVMCS);
4845 AssertRC(rc2);
4846 Assert(!(ASMGetFlags() & X86_EFL_IF));
4847 ASMSetFlags(uOldEFlags);
4848 return rc;
4849}
4850
4851#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL) */
4852
4853
4854#if HC_ARCH_BITS == 32 && !defined(VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0)
4855/**
4856 * Executes VMWRITE
4857 *
4858 * @returns VBox status code
4859 * @param pVCpu The VMCPU to operate on.
4860 * @param idxField VMCS index
4861 * @param u64Val 16, 32 or 64 bits value
4862 */
4863VMMR0DECL(int) VMXWriteVMCS64Ex(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
4864{
4865 int rc;
4866
4867 switch (idxField)
4868 {
4869 case VMX_VMCS_CTRL_TSC_OFFSET_FULL:
4870 case VMX_VMCS_CTRL_IO_BITMAP_A_FULL:
4871 case VMX_VMCS_CTRL_IO_BITMAP_B_FULL:
4872 case VMX_VMCS_CTRL_MSR_BITMAP_FULL:
4873 case VMX_VMCS_CTRL_VMEXIT_MSR_STORE_FULL:
4874 case VMX_VMCS_CTRL_VMEXIT_MSR_LOAD_FULL:
4875 case VMX_VMCS_CTRL_VMENTRY_MSR_LOAD_FULL:
4876 case VMX_VMCS_CTRL_VAPIC_PAGEADDR_FULL:
4877 case VMX_VMCS_CTRL_APIC_ACCESSADDR_FULL:
4878 case VMX_VMCS_GUEST_LINK_PTR_FULL:
4879 case VMX_VMCS_GUEST_PDPTR0_FULL:
4880 case VMX_VMCS_GUEST_PDPTR1_FULL:
4881 case VMX_VMCS_GUEST_PDPTR2_FULL:
4882 case VMX_VMCS_GUEST_PDPTR3_FULL:
4883 case VMX_VMCS_GUEST_DEBUGCTL_FULL:
4884 case VMX_VMCS_GUEST_EFER_FULL:
4885 case VMX_VMCS_CTRL_EPTP_FULL:
4886 /* These fields consist of two parts, which are both writable in 32 bits mode. */
4887 rc = VMXWriteVMCS32(idxField, u64Val);
4888 rc |= VMXWriteVMCS32(idxField + 1, (uint32_t)(u64Val >> 32ULL));
4889 AssertRC(rc);
4890 return rc;
4891
4892 case VMX_VMCS64_GUEST_LDTR_BASE:
4893 case VMX_VMCS64_GUEST_TR_BASE:
4894 case VMX_VMCS64_GUEST_GDTR_BASE:
4895 case VMX_VMCS64_GUEST_IDTR_BASE:
4896 case VMX_VMCS64_GUEST_SYSENTER_EIP:
4897 case VMX_VMCS64_GUEST_SYSENTER_ESP:
4898 case VMX_VMCS64_GUEST_CR0:
4899 case VMX_VMCS64_GUEST_CR4:
4900 case VMX_VMCS64_GUEST_CR3:
4901 case VMX_VMCS64_GUEST_DR7:
4902 case VMX_VMCS64_GUEST_RIP:
4903 case VMX_VMCS64_GUEST_RSP:
4904 case VMX_VMCS64_GUEST_CS_BASE:
4905 case VMX_VMCS64_GUEST_DS_BASE:
4906 case VMX_VMCS64_GUEST_ES_BASE:
4907 case VMX_VMCS64_GUEST_FS_BASE:
4908 case VMX_VMCS64_GUEST_GS_BASE:
4909 case VMX_VMCS64_GUEST_SS_BASE:
4910 /* Queue a 64 bits value as we can't set it in 32 bits host mode. */
4911 if (u64Val >> 32ULL)
4912 rc = VMXWriteCachedVMCSEx(pVCpu, idxField, u64Val);
4913 else
4914 rc = VMXWriteVMCS32(idxField, (uint32_t)u64Val);
4915
4916 return rc;
4917
4918 default:
4919 AssertMsgFailed(("Unexpected field %x\n", idxField));
4920 return VERR_INVALID_PARAMETER;
4921 }
4922}
4923
4924/**
4925 * Cache VMCS writes for performance reasons (Darwin) and for running 64 bits guests on 32 bits hosts.
4926 *
4927 * @param pVCpu The VMCPU to operate on.
4928 * @param idxField VMCS field
4929 * @param u64Val Value
4930 */
4931VMMR0DECL(int) VMXWriteCachedVMCSEx(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
4932{
4933 PVMCSCACHE pCache = &pVCpu->hwaccm.s.vmx.VMCSCache;
4934
4935 AssertMsgReturn(pCache->Write.cValidEntries < VMCSCACHE_MAX_ENTRY - 1, ("entries=%x\n", pCache->Write.cValidEntries), VERR_ACCESS_DENIED);
4936
4937 /* Make sure there are no duplicates. */
4938 for (unsigned i=0;i<pCache->Write.cValidEntries;i++)
4939 {
4940 if (pCache->Write.aField[i] == idxField)
4941 {
4942 pCache->Write.aFieldVal[i] = u64Val;
4943 return VINF_SUCCESS;
4944 }
4945 }
4946
4947 pCache->Write.aField[pCache->Write.cValidEntries] = idxField;
4948 pCache->Write.aFieldVal[pCache->Write.cValidEntries] = u64Val;
4949 pCache->Write.cValidEntries++;
4950 return VINF_SUCCESS;
4951}
4952
4953#endif /* HC_ARCH_BITS == 32 && !VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0 */
4954
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette