VirtualBox

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

Last change on this file since 18617 was 18617, checked in by vboxsync, 16 years ago

PGM,EM: Handle out of memory situations more gracefully - part 1. New debugger commands: .pgmerror and .pgmerroroff.

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

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