VirtualBox

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

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

log fix

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