VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HWSVMR0.cpp@ 46297

Last change on this file since 46297 was 46297, checked in by vboxsync, 11 years ago

VMM: Started HMSVMR0 work. Unify the AMD-V erratum 170 verification code between R0 and R3. General HM tidying.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 123.5 KB
Line 
1/* $Id: HWSVMR0.cpp 46297 2013-05-28 14:38:48Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2006-2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_HM
22#include <VBox/vmm/hm.h>
23#include <VBox/vmm/pgm.h>
24#include <VBox/vmm/selm.h>
25#include <VBox/vmm/iom.h>
26#include <VBox/vmm/dbgf.h>
27#include <VBox/vmm/dbgftrace.h>
28#include <VBox/vmm/tm.h>
29#include <VBox/vmm/pdmapi.h>
30#include "HMInternal.h"
31#include <VBox/vmm/vm.h>
32#include <VBox/vmm/hm_svm.h>
33#include <VBox/err.h>
34#include <VBox/log.h>
35#include <VBox/dis.h>
36#include <VBox/disopcode.h>
37#include <iprt/param.h>
38#include <iprt/assert.h>
39#include <iprt/asm.h>
40#include <iprt/asm-amd64-x86.h>
41#include <iprt/cpuset.h>
42#include <iprt/mp.h>
43#include <iprt/time.h>
44#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
45# include <iprt/thread.h>
46#endif
47#include <iprt/x86.h>
48#include "HWSVMR0.h"
49
50#include "dtrace/VBoxVMM.h"
51
52
53/*******************************************************************************
54* Internal Functions *
55*******************************************************************************/
56static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame);
57static int hmR0SvmEmulateTprVMMCall(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
58static void hmR0SvmSetMSRPermission(PVMCPU pVCpu, unsigned ulMSR, bool fRead, bool fWrite);
59
60/*******************************************************************************
61* Defined Constants And Macros *
62*******************************************************************************/
63/** Convert hidden selector attribute word between VMX and SVM formats. */
64#define SVM_HIDSEGATTR_VMX2SVM(a) (a & 0xFF) | ((a & 0xF000) >> 4)
65#define SVM_HIDSEGATTR_SVM2VMX(a) (a & 0xFF) | ((a & 0x0F00) << 4)
66
67#define SVM_WRITE_SELREG(REG, reg) \
68 do \
69 { \
70 Assert(pCtx->reg.fFlags & CPUMSELREG_FLAGS_VALID); \
71 Assert(pCtx->reg.ValidSel == pCtx->reg.Sel); \
72 pvVMCB->guest.REG.u16Sel = pCtx->reg.Sel; \
73 pvVMCB->guest.REG.u32Limit = pCtx->reg.u32Limit; \
74 pvVMCB->guest.REG.u64Base = pCtx->reg.u64Base; \
75 pvVMCB->guest.REG.u16Attr = SVM_HIDSEGATTR_VMX2SVM(pCtx->reg.Attr.u); \
76 } while (0)
77
78#define SVM_READ_SELREG(REG, reg) \
79 do \
80 { \
81 pCtx->reg.Sel = pvVMCB->guest.REG.u16Sel; \
82 pCtx->reg.ValidSel = pvVMCB->guest.REG.u16Sel; \
83 pCtx->reg.fFlags = CPUMSELREG_FLAGS_VALID; \
84 pCtx->reg.u32Limit = pvVMCB->guest.REG.u32Limit; \
85 pCtx->reg.u64Base = pvVMCB->guest.REG.u64Base; \
86 pCtx->reg.Attr.u = SVM_HIDSEGATTR_SVM2VMX(pvVMCB->guest.REG.u16Attr); \
87 } while (0)
88
89/*******************************************************************************
90* Global Variables *
91*******************************************************************************/
92/* IO operation lookup arrays. */
93static uint32_t const g_aIOSize[8] = {0, 1, 2, 0, 4, 0, 0, 0};
94static uint32_t const g_aIOOpAnd[8] = {0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0};
95
96
97/**
98 * Sets up and activates AMD-V on the current CPU.
99 *
100 * @returns VBox status code.
101 * @param pCpu Pointer to the CPU info struct.
102 * @param pVM Pointer to the VM (can be NULL after a resume!).
103 * @param pvCpuPage Pointer to the global CPU page.
104 * @param HCPhysCpuPage Physical address of the global CPU page.
105 */
106VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBLCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost)
107{
108 AssertReturn(!fEnabledByHost, VERR_INVALID_PARAMETER);
109 AssertReturn(HCPhysCpuPage != 0 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
110 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
111
112 /*
113 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per cpu/core.
114 */
115 uint64_t fEfer = ASMRdMsr(MSR_K6_EFER);
116 if (fEfer & MSR_K6_EFER_SVME)
117 {
118 /*
119 * If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V.
120 */
121 if ( pVM
122 && pVM->hm.s.svm.fIgnoreInUseError)
123 {
124 pCpu->fIgnoreAMDVInUseError = true;
125 }
126
127 if (!pCpu->fIgnoreAMDVInUseError)
128 return VERR_SVM_IN_USE;
129 }
130
131 /* Turn on AMD-V in the EFER MSR. */
132 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
133
134 /* Write the physical page address where the CPU will store the host state while executing the VM. */
135 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
136
137 /*
138 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all non-zero ASIDs
139 * when enabling SVM. AMD doesn't have an SVM instruction to flush all ASIDs (flushing is done
140 * upon VMRUN). Therefore, just set the fFlushAsidBeforeUse flag which instructs hmR0SvmSetupTLB()
141 * to flush the TLB with before using a new ASID.
142 */
143 pCpu->fFlushAsidBeforeUse = true;
144
145 /*
146 * Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}.
147 */
148 ++pCpu->cTlbFlushes;
149
150 return VINF_SUCCESS;
151}
152
153
154/**
155 * Deactivates AMD-V on the current CPU.
156 *
157 * @returns VBox status code.
158 * @param pCpu Pointer to the CPU info struct.
159 * @param pvCpuPage Pointer to the global CPU page.
160 * @param HCPhysCpuPage Physical address of the global CPU page.
161 */
162VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBLCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
163{
164 AssertReturn(HCPhysCpuPage != 0 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
165 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
166 NOREF(pCpu);
167
168 /* Turn off AMD-V in the EFER MSR. */
169 uint64_t fEfer = ASMRdMsr(MSR_K6_EFER);
170 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
171
172 /* Invalidate host state physical address. */
173 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
174
175 return VINF_SUCCESS;
176}
177
178
179/**
180 * Does global AMD-V initialization (called during module initialization).
181 *
182 * @returns VBox status code.
183 */
184VMMR0DECL(int) SVMR0GlobalInit(void)
185{
186 return VINF_SUCCESS;
187}
188
189
190/**
191 * Does global VT-x termination (called during module termination).
192 */
193VMMR0DECL(void) SVMR0GlobalTerm(void)
194{
195}
196
197
198/**
199 * Does Ring-0 per VM AMD-V init.
200 *
201 * @returns VBox status code.
202 * @param pVM Pointer to the VM.
203 */
204VMMR0DECL(int) SVMR0InitVM(PVM pVM)
205{
206 int rc;
207
208 pVM->hm.s.svm.hMemObjIOBitmap = NIL_RTR0MEMOBJ;
209
210 /* Allocate 12 KB for the IO bitmap (doesn't seem to be a way to convince SVM not to use it) */
211 rc = RTR0MemObjAllocCont(&pVM->hm.s.svm.hMemObjIOBitmap, 3 << PAGE_SHIFT, false /* fExecutable */);
212 if (RT_FAILURE(rc))
213 return rc;
214
215 pVM->hm.s.svm.pvIOBitmap = RTR0MemObjAddress(pVM->hm.s.svm.hMemObjIOBitmap);
216 pVM->hm.s.svm.HCPhysIOBitmap = RTR0MemObjGetPagePhysAddr(pVM->hm.s.svm.hMemObjIOBitmap, 0);
217 /* Set all bits to intercept all IO accesses. */
218 ASMMemFill32(pVM->hm.s.svm.pvIOBitmap, 3 << PAGE_SHIFT, 0xffffffff);
219
220 /* Check for an AMD CPU erratum which requires us to flush the TLB before every world-switch. */
221 uint32_t u32Family;
222 uint32_t u32Model;
223 uint32_t u32Stepping;
224 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
225 {
226 Log(("SVMR0InitVM: AMD cpu with erratum 170 family %x model %x stepping %x\n", u32Family, u32Model, u32Stepping));
227 pVM->hm.s.svm.fAlwaysFlushTLB = true;
228 }
229
230 /* Allocate VMCBs for all guest CPUs. */
231 for (VMCPUID i = 0; i < pVM->cCpus; i++)
232 {
233 PVMCPU pVCpu = &pVM->aCpus[i];
234
235 pVCpu->hm.s.svm.hMemObjVMCBHost = NIL_RTR0MEMOBJ;
236 pVCpu->hm.s.svm.hMemObjVMCB = NIL_RTR0MEMOBJ;
237 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
238
239 /* Allocate one page for the host context */
240 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVMCBHost, 1 << PAGE_SHIFT, false /* fExecutable */);
241 if (RT_FAILURE(rc))
242 return rc;
243
244 pVCpu->hm.s.svm.pvVMCBHost = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVMCBHost);
245 pVCpu->hm.s.svm.HCPhysVMCBHost = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVMCBHost, 0);
246 Assert(pVCpu->hm.s.svm.HCPhysVMCBHost < _4G);
247 ASMMemZeroPage(pVCpu->hm.s.svm.pvVMCBHost);
248
249 /* Allocate one page for the VM control block (VMCB). */
250 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVMCB, 1 << PAGE_SHIFT, false /* fExecutable */);
251 if (RT_FAILURE(rc))
252 return rc;
253
254 pVCpu->hm.s.svm.pvVMCB = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVMCB);
255 pVCpu->hm.s.svm.HCPhysVMCB = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVMCB, 0);
256 Assert(pVCpu->hm.s.svm.HCPhysVMCB < _4G);
257 ASMMemZeroPage(pVCpu->hm.s.svm.pvVMCB);
258
259 /* Allocate 8 KB for the MSR bitmap (doesn't seem to be a way to convince SVM not to use it) */
260 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjMsrBitmap, 2 << PAGE_SHIFT, false /* fExecutable */);
261 if (RT_FAILURE(rc))
262 return rc;
263
264 pVCpu->hm.s.svm.pvMsrBitmap = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjMsrBitmap);
265 pVCpu->hm.s.svm.HCPhysMsrBitmap = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjMsrBitmap, 0);
266 /* Set all bits to intercept all MSR accesses. */
267 ASMMemFill32(pVCpu->hm.s.svm.pvMsrBitmap, 2 << PAGE_SHIFT, 0xffffffff);
268 }
269
270 return VINF_SUCCESS;
271}
272
273
274/**
275 * Does Ring-0 per VM AMD-V termination.
276 *
277 * @returns VBox status code.
278 * @param pVM Pointer to the VM.
279 */
280VMMR0DECL(int) SVMR0TermVM(PVM pVM)
281{
282 for (VMCPUID i = 0; i < pVM->cCpus; i++)
283 {
284 PVMCPU pVCpu = &pVM->aCpus[i];
285
286 if (pVCpu->hm.s.svm.hMemObjVMCBHost != NIL_RTR0MEMOBJ)
287 {
288 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVMCBHost, false);
289 pVCpu->hm.s.svm.pvVMCBHost = 0;
290 pVCpu->hm.s.svm.HCPhysVMCBHost = 0;
291 pVCpu->hm.s.svm.hMemObjVMCBHost = NIL_RTR0MEMOBJ;
292 }
293
294 if (pVCpu->hm.s.svm.hMemObjVMCB != NIL_RTR0MEMOBJ)
295 {
296 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVMCB, false);
297 pVCpu->hm.s.svm.pvVMCB = 0;
298 pVCpu->hm.s.svm.HCPhysVMCB = 0;
299 pVCpu->hm.s.svm.hMemObjVMCB = NIL_RTR0MEMOBJ;
300 }
301 if (pVCpu->hm.s.svm.hMemObjMsrBitmap != NIL_RTR0MEMOBJ)
302 {
303 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjMsrBitmap, false);
304 pVCpu->hm.s.svm.pvMsrBitmap = 0;
305 pVCpu->hm.s.svm.HCPhysMsrBitmap = 0;
306 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
307 }
308 }
309 if (pVM->hm.s.svm.hMemObjIOBitmap != NIL_RTR0MEMOBJ)
310 {
311 RTR0MemObjFree(pVM->hm.s.svm.hMemObjIOBitmap, false);
312 pVM->hm.s.svm.pvIOBitmap = 0;
313 pVM->hm.s.svm.HCPhysIOBitmap = 0;
314 pVM->hm.s.svm.hMemObjIOBitmap = NIL_RTR0MEMOBJ;
315 }
316 return VINF_SUCCESS;
317}
318
319
320/**
321 * Sets up AMD-V for the specified VM.
322 *
323 * @returns VBox status code.
324 * @param pVM Pointer to the VM.
325 */
326VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
327{
328 int rc = VINF_SUCCESS;
329
330 AssertReturn(pVM, VERR_INVALID_PARAMETER);
331 Assert(pVM->hm.s.svm.fSupported);
332
333 for (VMCPUID i = 0; i < pVM->cCpus; i++)
334 {
335 PVMCPU pVCpu = &pVM->aCpus[i];
336 SVM_VMCB *pvVMCB = (SVM_VMCB *)pVM->aCpus[i].hm.s.svm.pvVMCB;
337
338 AssertMsgReturn(pvVMCB, ("Invalid pvVMCB\n"), VERR_SVM_INVALID_PVMCB);
339
340 /*
341 * Program the control fields. Most of them never have to be changed again.
342 * CR0/4 reads must be intercepted, our shadow values are not necessarily the same as the guest's.
343 * Note: CR0 & CR4 can be safely read when guest and shadow copies are identical.
344 */
345 pvVMCB->ctrl.u16InterceptRdCRx = RT_BIT(0) | RT_BIT(4);
346
347 /* CR0/4 writes must be intercepted for obvious reasons. */
348 pvVMCB->ctrl.u16InterceptWrCRx = RT_BIT(0) | RT_BIT(4);
349
350 /* Intercept all DRx reads and writes by default. Changed later on. */
351 pvVMCB->ctrl.u16InterceptRdDRx = 0xFFFF;
352 pvVMCB->ctrl.u16InterceptWrDRx = 0xFFFF;
353
354 /* Intercept traps; only #NM is always intercepted. */
355 pvVMCB->ctrl.u32InterceptException = RT_BIT(X86_XCPT_NM);
356#ifdef VBOX_ALWAYS_TRAP_PF
357 pvVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
358#endif
359#ifdef VBOX_STRICT
360 pvVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_BP)
361 | RT_BIT(X86_XCPT_DB)
362 | RT_BIT(X86_XCPT_DE)
363 | RT_BIT(X86_XCPT_UD)
364 | RT_BIT(X86_XCPT_NP)
365 | RT_BIT(X86_XCPT_SS)
366 | RT_BIT(X86_XCPT_GP)
367 | RT_BIT(X86_XCPT_MF)
368 ;
369#endif
370
371 /* Set up instruction and miscellaneous intercepts. */
372 pvVMCB->ctrl.u32InterceptCtrl1 = SVM_CTRL1_INTERCEPT_INTR
373 | SVM_CTRL1_INTERCEPT_VINTR
374 | SVM_CTRL1_INTERCEPT_NMI
375 | SVM_CTRL1_INTERCEPT_SMI
376 | SVM_CTRL1_INTERCEPT_INIT
377 | SVM_CTRL1_INTERCEPT_RDPMC
378 | SVM_CTRL1_INTERCEPT_CPUID
379 | SVM_CTRL1_INTERCEPT_RSM
380 | SVM_CTRL1_INTERCEPT_HLT
381 | SVM_CTRL1_INTERCEPT_INOUT_BITMAP
382 | SVM_CTRL1_INTERCEPT_MSR_SHADOW
383 | SVM_CTRL1_INTERCEPT_INVLPGA /* AMD only */
384 | SVM_CTRL1_INTERCEPT_SHUTDOWN /* fatal */
385 | SVM_CTRL1_INTERCEPT_FERR_FREEZE; /* Legacy FPU FERR handling. */
386 ;
387 pvVMCB->ctrl.u32InterceptCtrl2 = SVM_CTRL2_INTERCEPT_VMRUN /* required */
388 | SVM_CTRL2_INTERCEPT_VMMCALL
389 | SVM_CTRL2_INTERCEPT_VMLOAD
390 | SVM_CTRL2_INTERCEPT_VMSAVE
391 | SVM_CTRL2_INTERCEPT_STGI
392 | SVM_CTRL2_INTERCEPT_CLGI
393 | SVM_CTRL2_INTERCEPT_SKINIT
394 | SVM_CTRL2_INTERCEPT_WBINVD
395 | SVM_CTRL2_INTERCEPT_MONITOR
396 | SVM_CTRL2_INTERCEPT_MWAIT_UNCOND; /* don't execute mwait or else we'll idle inside the
397 guest (host thinks the cpu load is high) */
398
399 Log(("pvVMCB->ctrl.u32InterceptException = %x\n", pvVMCB->ctrl.u32InterceptException));
400 Log(("pvVMCB->ctrl.u32InterceptCtrl1 = %x\n", pvVMCB->ctrl.u32InterceptCtrl1));
401 Log(("pvVMCB->ctrl.u32InterceptCtrl2 = %x\n", pvVMCB->ctrl.u32InterceptCtrl2));
402
403 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
404 pvVMCB->ctrl.IntCtrl.n.u1VIrqMasking = 1;
405
406 /* Ignore the priority in the TPR; just deliver it when we tell it to. */
407 pvVMCB->ctrl.IntCtrl.n.u1IgnoreTPR = 1;
408
409 /* Set IO and MSR bitmap addresses. */
410 pvVMCB->ctrl.u64IOPMPhysAddr = pVM->hm.s.svm.HCPhysIOBitmap;
411 pvVMCB->ctrl.u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
412
413 /* No LBR virtualization. */
414 pvVMCB->ctrl.u64LBRVirt = 0;
415
416 /* The ASID must start at 1; the host uses 0. */
417 pvVMCB->ctrl.TLBCtrl.n.u32ASID = 1;
418
419 /*
420 * Setup the PAT MSR (nested paging only)
421 * The default value should be 0x0007040600070406ULL, but we want to treat all guest memory as WB,
422 * so choose type 6 for all PAT slots.
423 */
424 pvVMCB->guest.u64GPAT = 0x0006060606060606ULL;
425
426 /* If nested paging is not in use, additional intercepts have to be set up. */
427 if (!pVM->hm.s.fNestedPaging)
428 {
429 /* CR3 reads/writes must be intercepted; our shadow values are different from guest's. */
430 pvVMCB->ctrl.u16InterceptRdCRx |= RT_BIT(3);
431 pvVMCB->ctrl.u16InterceptWrCRx |= RT_BIT(3);
432
433 /*
434 * We must also intercept:
435 * - INVLPG (must go through shadow paging)
436 * - task switches (may change CR3/EFLAGS/LDT)
437 */
438 pvVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_INVLPG
439 | SVM_CTRL1_INTERCEPT_TASK_SWITCH;
440
441 /* Page faults must be intercepted to implement shadow paging. */
442 pvVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
443 }
444
445 /*
446 * The following MSRs are saved automatically by vmload/vmsave, so we allow the guest
447 * to modify them directly.
448 */
449 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
450 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_CSTAR, true, true);
451 hmR0SvmSetMSRPermission(pVCpu, MSR_K6_STAR, true, true);
452 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_SF_MASK, true, true);
453 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_FS_BASE, true, true);
454 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_GS_BASE, true, true);
455 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, true, true);
456 hmR0SvmSetMSRPermission(pVCpu, MSR_IA32_SYSENTER_CS, true, true);
457 hmR0SvmSetMSRPermission(pVCpu, MSR_IA32_SYSENTER_ESP, true, true);
458 hmR0SvmSetMSRPermission(pVCpu, MSR_IA32_SYSENTER_EIP, true, true);
459 }
460
461 return rc;
462}
463
464
465/**
466 * Sets the permission bits for the specified MSR.
467 *
468 * @param pVCpu Pointer to the VMCPU.
469 * @param ulMSR MSR value.
470 * @param fRead Whether reading is allowed.
471 * @param fWrite Whether writing is allowed.
472 */
473static void hmR0SvmSetMSRPermission(PVMCPU pVCpu, unsigned ulMSR, bool fRead, bool fWrite)
474{
475 unsigned ulBit;
476 uint8_t *pvMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
477
478 if (ulMSR <= 0x00001FFF)
479 {
480 /* Pentium-compatible MSRs */
481 ulBit = ulMSR * 2;
482 }
483 else if ( ulMSR >= 0xC0000000
484 && ulMSR <= 0xC0001FFF)
485 {
486 /* AMD Sixth Generation x86 Processor MSRs and SYSCALL */
487 ulBit = (ulMSR - 0xC0000000) * 2;
488 pvMsrBitmap += 0x800;
489 }
490 else if ( ulMSR >= 0xC0010000
491 && ulMSR <= 0xC0011FFF)
492 {
493 /* AMD Seventh and Eighth Generation Processor MSRs */
494 ulBit = (ulMSR - 0xC0001000) * 2;
495 pvMsrBitmap += 0x1000;
496 }
497 else
498 {
499 AssertFailed();
500 return;
501 }
502 Assert(ulBit < 16 * 1024 - 1);
503 if (fRead)
504 ASMBitClear(pvMsrBitmap, ulBit);
505 else
506 ASMBitSet(pvMsrBitmap, ulBit);
507
508 if (fWrite)
509 ASMBitClear(pvMsrBitmap, ulBit + 1);
510 else
511 ASMBitSet(pvMsrBitmap, ulBit + 1);
512}
513
514/**
515 * Posts a pending event (trap or external interrupt). An injected event should only
516 * be written to the VMCB immediately before VMRUN, otherwise we might have stale events
517 * injected across VM resets and suchlike. See @bugref{6220}.
518 *
519 * @param pVCpu Pointer to the VMCPU.
520 * @param pCtx Pointer to the guest CPU context.
521 * @param pIntInfo Pointer to the SVM interrupt info.
522 */
523DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, SVM_EVENT *pEvent)
524{
525#ifdef VBOX_STRICT
526 Log(("SVM: Set pending event: intInfo=%016llx\n", pEvent->au64[0]));
527#endif
528
529 /* If there's an event pending already, we're in trouble... */
530 Assert(!pVCpu->hm.s.Event.fPending);
531
532 /* Set pending event state. */
533 pVCpu->hm.s.Event.u64IntrInfo = pEvent->au64[0];
534 pVCpu->hm.s.Event.fPending = true;
535}
536
537/**
538 * Injects an event (trap or external interrupt).
539 *
540 * @param pVCpu Pointer to the VMCPU.
541 * @param pvVMCB Pointer to the VMCB.
542 * @param pCtx Pointer to the guest CPU context.
543 * @param pIntInfo Pointer to the SVM interrupt info.
544 */
545DECLINLINE(void) hmR0SvmInjectEvent(PVMCPU pVCpu, SVM_VMCB *pvVMCB, CPUMCTX *pCtx, SVM_EVENT *pEvent)
546{
547#ifdef VBOX_WITH_STATISTICS
548 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
549#endif
550
551#ifdef VBOX_STRICT
552 if (pEvent->n.u8Vector == 0xE)
553 {
554 Log(("SVM: Inject int %d at %RGv error code=%02x CR2=%RGv intInfo=%08x\n", pEvent->n.u8Vector,
555 (RTGCPTR)pCtx->rip, pEvent->n.u32ErrorCode, (RTGCPTR)pCtx->cr2, pEvent->au64[0]));
556 }
557 else if (pEvent->n.u8Vector < 0x20)
558 Log(("SVM: Inject int %d at %RGv error code=%08x\n", pEvent->n.u8Vector, (RTGCPTR)pCtx->rip, pEvent->n.u32ErrorCode));
559 else
560 {
561 Log(("INJ-EI: %x at %RGv\n", pEvent->n.u8Vector, (RTGCPTR)pCtx->rip));
562 Assert(!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
563 Assert(pCtx->eflags.u32 & X86_EFL_IF);
564 }
565#endif
566
567 /* Set event injection state. */
568 pvVMCB->ctrl.EventInject.au64[0] = pEvent->au64[0];
569}
570
571
572/**
573 * Checks for pending guest interrupts and injects them.
574 *
575 * @returns VBox status code.
576 * @param pVM Pointer to the VM.
577 * @param pVCpu Pointer to the VMCPU.
578 * @param pvVMCB Pointer to the VMCB.
579 * @param pCtx Pointer to the guest CPU Context.
580 */
581static int hmR0SvmCheckPendingInterrupt(PVM pVM, PVMCPU pVCpu, SVM_VMCB *pvVMCB, CPUMCTX *pCtx)
582{
583 int rc;
584 NOREF(pVM);
585
586 /*
587 * Dispatch any pending interrupts (injected before, but a VM-exit occurred prematurely).
588 */
589 if (pVCpu->hm.s.Event.fPending)
590 {
591 SVM_EVENT Event;
592
593 Log(("Reinjecting event %08x %08x at %RGv\n", pVCpu->hm.s.Event.u64IntrInfo, pVCpu->hm.s.Event.u32ErrCode,
594 (RTGCPTR)pCtx->rip));
595 STAM_COUNTER_INC(&pVCpu->hm.s.StatIntReinject);
596 Event.au64[0] = pVCpu->hm.s.Event.u64IntrInfo;
597 hmR0SvmInjectEvent(pVCpu, pvVMCB, pCtx, &Event);
598
599 pVCpu->hm.s.Event.fPending = false;
600 return VINF_SUCCESS;
601 }
602
603 /*
604 * If an active trap is already pending, we must forward it first!
605 */
606 if (!TRPMHasTrap(pVCpu))
607 {
608 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI))
609 {
610 SVM_EVENT Event;
611
612 Log(("CPU%d: injecting #NMI\n", pVCpu->idCpu));
613 Event.n.u8Vector = X86_XCPT_NMI;
614 Event.n.u1Valid = 1;
615 Event.n.u32ErrorCode = 0;
616 Event.n.u3Type = SVM_EVENT_NMI;
617
618 hmR0SvmInjectEvent(pVCpu, pvVMCB, pCtx, &Event);
619 return VINF_SUCCESS;
620 }
621
622 /** @todo SMI interrupts. */
623
624 /*
625 * When external interrupts are pending, we should exit the VM when IF is set.
626 */
627 if (VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)))
628 {
629 if ( !(pCtx->eflags.u32 & X86_EFL_IF)
630 || VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
631 {
632 if (!pvVMCB->ctrl.IntCtrl.n.u1VIrqValid)
633 {
634 if (!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
635 LogFlow(("Enable irq window exit!\n"));
636 else
637 {
638 Log(("Pending interrupt blocked at %RGv by VM_FF_INHIBIT_INTERRUPTS -> irq window exit\n",
639 (RTGCPTR)pCtx->rip));
640 }
641
642 /** @todo Use virtual interrupt method to inject a pending IRQ; dispatched as
643 * soon as guest.IF is set. */
644 pvVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
645 pvVMCB->ctrl.IntCtrl.n.u1VIrqValid = 1;
646 pvVMCB->ctrl.IntCtrl.n.u8VIrqVector = 0; /* don't care */
647 }
648 }
649 else
650 {
651 uint8_t u8Interrupt;
652
653 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
654 Log(("Dispatch interrupt: u8Interrupt=%x (%d) rc=%Rrc\n", u8Interrupt, u8Interrupt, rc));
655 if (RT_SUCCESS(rc))
656 {
657 rc = TRPMAssertTrap(pVCpu, u8Interrupt, TRPM_HARDWARE_INT);
658 AssertRC(rc);
659 }
660 else
661 {
662 /* Can only happen in rare cases where a pending interrupt is cleared behind our back */
663 Assert(!VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)));
664 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
665 /* Just continue */
666 }
667 }
668 }
669 }
670
671#ifdef VBOX_STRICT
672 if (TRPMHasTrap(pVCpu))
673 {
674 uint8_t u8Vector;
675 rc = TRPMQueryTrapAll(pVCpu, &u8Vector, 0, NULL, NULL, NULL);
676 AssertRC(rc);
677 }
678#endif
679
680 if ( (pCtx->eflags.u32 & X86_EFL_IF)
681 && (!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
682 && TRPMHasTrap(pVCpu)
683 )
684 {
685 uint8_t u8Vector;
686 TRPMEVENT enmType;
687 SVM_EVENT Event;
688 RTGCUINT u32ErrorCode;
689
690 Event.au64[0] = 0;
691
692 /* If a new event is pending, then dispatch it now. */
693 rc = TRPMQueryTrapAll(pVCpu, &u8Vector, &enmType, &u32ErrorCode, NULL, NULL);
694 AssertRC(rc);
695 Assert(pCtx->eflags.Bits.u1IF == 1 || enmType == TRPM_TRAP);
696 Assert(enmType != TRPM_SOFTWARE_INT);
697
698 /* Clear the pending trap. */
699 rc = TRPMResetTrap(pVCpu);
700 AssertRC(rc);
701
702 Event.n.u8Vector = u8Vector;
703 Event.n.u1Valid = 1;
704 Event.n.u32ErrorCode = u32ErrorCode;
705
706 if (enmType == TRPM_TRAP)
707 {
708 switch (u8Vector)
709 {
710 case X86_XCPT_DF:
711 case X86_XCPT_TS:
712 case X86_XCPT_NP:
713 case X86_XCPT_SS:
714 case X86_XCPT_GP:
715 case X86_XCPT_PF:
716 case X86_XCPT_AC:
717 /* Valid error codes. */
718 Event.n.u1ErrorCodeValid = 1;
719 break;
720 default:
721 break;
722 }
723 if (u8Vector == X86_XCPT_NMI)
724 Event.n.u3Type = SVM_EVENT_NMI;
725 else
726 Event.n.u3Type = SVM_EVENT_EXCEPTION;
727 }
728 else
729 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
730
731 STAM_COUNTER_INC(&pVCpu->hm.s.StatIntInject);
732 hmR0SvmInjectEvent(pVCpu, pvVMCB, pCtx, &Event);
733 } /* if (interrupts can be dispatched) */
734
735 return VINF_SUCCESS;
736}
737
738
739/**
740 * Save the host state.
741 *
742 * @returns VBox status code.
743 * @param pVM Pointer to the VM.
744 * @param pVCpu Pointer to the VMCPU.
745 */
746VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
747{
748 NOREF(pVM);
749 NOREF(pVCpu);
750 /* Nothing to do here. */
751 return VINF_SUCCESS;
752}
753
754
755/**
756 * Loads the guest state.
757 *
758 * NOTE: Don't do anything here that can cause a jump back to ring-3!!!
759 *
760 * @returns VBox status code.
761 * @param pVM Pointer to the VM.
762 * @param pVCpu Pointer to the VMCPU.
763 * @param pCtx Pointer to the guest CPU context.
764 */
765VMMR0DECL(int) SVMR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
766{
767 RTGCUINTPTR val;
768 SVM_VMCB *pvVMCB;
769
770 if (pVM == NULL)
771 return VERR_INVALID_PARAMETER;
772
773 /* Setup AMD SVM. */
774 Assert(pVM->hm.s.svm.fSupported);
775
776 pvVMCB = (SVM_VMCB *)pVCpu->hm.s.svm.pvVMCB;
777 AssertMsgReturn(pvVMCB, ("Invalid pvVMCB\n"), VERR_SVM_INVALID_PVMCB);
778
779 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
780 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_SEGMENT_REGS)
781 {
782 SVM_WRITE_SELREG(CS, cs);
783 SVM_WRITE_SELREG(SS, ss);
784 SVM_WRITE_SELREG(DS, ds);
785 SVM_WRITE_SELREG(ES, es);
786 SVM_WRITE_SELREG(FS, fs);
787 SVM_WRITE_SELREG(GS, gs);
788 }
789
790 /* Guest CPU context: LDTR. */
791 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_LDTR)
792 {
793 SVM_WRITE_SELREG(LDTR, ldtr);
794 }
795
796 /* Guest CPU context: TR. */
797 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_TR)
798 {
799 SVM_WRITE_SELREG(TR, tr);
800 }
801
802 /* Guest CPU context: GDTR. */
803 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_GDTR)
804 {
805 pvVMCB->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
806 pvVMCB->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
807 }
808
809 /* Guest CPU context: IDTR. */
810 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_IDTR)
811 {
812 pvVMCB->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
813 pvVMCB->guest.IDTR.u64Base = pCtx->idtr.pIdt;
814 }
815
816 /*
817 * Sysenter MSRs (unconditional)
818 */
819 pvVMCB->guest.u64SysEnterCS = pCtx->SysEnter.cs;
820 pvVMCB->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
821 pvVMCB->guest.u64SysEnterESP = pCtx->SysEnter.esp;
822
823 /* Control registers */
824 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR0)
825 {
826 val = pCtx->cr0;
827 if (!CPUMIsGuestFPUStateActive(pVCpu))
828 {
829 /* Always use #NM exceptions to load the FPU/XMM state on demand. */
830 val |= X86_CR0_TS | X86_CR0_ET | X86_CR0_NE | X86_CR0_MP;
831 }
832 else
833 {
834 /** @todo check if we support the old style mess correctly. */
835 if (!(val & X86_CR0_NE))
836 {
837 Log(("Forcing X86_CR0_NE!!!\n"));
838
839 /* Also catch floating point exceptions as we need to report them to the guest in a different way. */
840 if (!pVCpu->hm.s.fFPUOldStyleOverride)
841 {
842 pvVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_MF);
843 pVCpu->hm.s.fFPUOldStyleOverride = true;
844 }
845 }
846 val |= X86_CR0_NE; /* always turn on the native mechanism to report FPU errors (old style uses interrupts) */
847 }
848 /* Always enable caching. */
849 val &= ~(X86_CR0_CD|X86_CR0_NW);
850
851 /*
852 * Note: WP is not relevant in nested paging mode as we catch accesses on the (guest) physical level.
853 * Note: In nested paging mode, the guest is allowed to run with paging disabled; the guest-physical to host-physical
854 * translation will remain active.
855 */
856 if (!pVM->hm.s.fNestedPaging)
857 {
858 val |= X86_CR0_PG; /* Paging is always enabled; even when the guest is running in real mode or PE without paging. */
859 val |= X86_CR0_WP; /* Must set this as we rely on protecting various pages and supervisor writes must be caught. */
860 }
861 pvVMCB->guest.u64CR0 = val;
862 }
863 /* CR2 as well */
864 pvVMCB->guest.u64CR2 = pCtx->cr2;
865
866 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR3)
867 {
868 /* Save our shadow CR3 register. */
869 if (pVM->hm.s.fNestedPaging)
870 {
871 PGMMODE enmShwPagingMode;
872
873#if HC_ARCH_BITS == 32
874 if (CPUMIsGuestInLongModeEx(pCtx))
875 enmShwPagingMode = PGMMODE_AMD64_NX;
876 else
877#endif
878 enmShwPagingMode = PGMGetHostMode(pVM);
879
880 pvVMCB->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
881 Assert(pvVMCB->ctrl.u64NestedPagingCR3);
882 pvVMCB->guest.u64CR3 = pCtx->cr3;
883 }
884 else
885 {
886 pvVMCB->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
887 Assert(pvVMCB->guest.u64CR3 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
888 }
889 }
890
891 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR4)
892 {
893 val = pCtx->cr4;
894 if (!pVM->hm.s.fNestedPaging)
895 {
896 switch (pVCpu->hm.s.enmShadowMode)
897 {
898 case PGMMODE_REAL:
899 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
900 AssertFailed();
901 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
902
903 case PGMMODE_32_BIT: /* 32-bit paging. */
904 val &= ~X86_CR4_PAE;
905 break;
906
907 case PGMMODE_PAE: /* PAE paging. */
908 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
909 /** Must use PAE paging as we could use physical memory > 4 GB */
910 val |= X86_CR4_PAE;
911 break;
912
913 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
914 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
915#ifdef VBOX_ENABLE_64_BITS_GUESTS
916 break;
917#else
918 AssertFailed();
919 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
920#endif
921
922 default: /* shut up gcc */
923 AssertFailed();
924 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
925 }
926 }
927 pvVMCB->guest.u64CR4 = val;
928 }
929
930 /* Debug registers. */
931 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_DEBUG)
932 {
933 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* set all reserved bits to 1. */
934 pCtx->dr[6] &= ~RT_BIT(12); /* must be zero. */
935
936 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
937 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
938 pCtx->dr[7] |= 0x400; /* must be one */
939
940 pvVMCB->guest.u64DR7 = pCtx->dr[7];
941 pvVMCB->guest.u64DR6 = pCtx->dr[6];
942
943#ifdef DEBUG
944 /* Sync the hypervisor debug state now if any breakpoint is armed. */
945 if ( CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK|X86_DR7_GD)
946 && !CPUMIsHyperDebugStateActive(pVCpu)
947 && !DBGFIsStepping(pVCpu))
948 {
949 /* Save the host and load the hypervisor debug state. */
950 int rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
951 AssertRC(rc);
952
953 /* DRx intercepts remain enabled. */
954
955 /* Override dr6 & dr7 with the hypervisor values. */
956 pvVMCB->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
957 pvVMCB->guest.u64DR6 = CPUMGetHyperDR6(pVCpu);
958 }
959 else
960#endif
961 /* Sync the debug state now if any breakpoint is armed. */
962 if ( (pCtx->dr[7] & (X86_DR7_ENABLED_MASK|X86_DR7_GD))
963 && !CPUMIsGuestDebugStateActive(pVCpu)
964 && !DBGFIsStepping(pVCpu))
965 {
966 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
967
968 /* Disable drx move intercepts. */
969 pvVMCB->ctrl.u16InterceptRdDRx = 0;
970 pvVMCB->ctrl.u16InterceptWrDRx = 0;
971
972 /* Save the host and load the guest debug state. */
973 int rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
974 AssertRC(rc);
975 }
976 }
977
978 /* EIP, ESP and EFLAGS */
979 pvVMCB->guest.u64RIP = pCtx->rip;
980 pvVMCB->guest.u64RSP = pCtx->rsp;
981 pvVMCB->guest.u64RFlags = pCtx->eflags.u32;
982
983 /* Set CPL */
984 pvVMCB->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
985
986 /* RAX/EAX too, as VMRUN uses RAX as an implicit parameter. */
987 pvVMCB->guest.u64RAX = pCtx->rax;
988
989 /* vmrun will fail without MSR_K6_EFER_SVME. */
990 pvVMCB->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
991
992 /* 64 bits guest mode? */
993 if (CPUMIsGuestInLongModeEx(pCtx))
994 {
995#if !defined(VBOX_ENABLE_64_BITS_GUESTS)
996 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
997#elif HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
998 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
999#else
1000# ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
1001 if (!pVM->hm.s.fAllow64BitGuests)
1002 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1003# endif
1004 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1005#endif
1006 /* Unconditionally update these as wrmsr might have changed them. (HM_CHANGED_GUEST_SEGMENT_REGS will not be set) */
1007 pvVMCB->guest.FS.u64Base = pCtx->fs.u64Base;
1008 pvVMCB->guest.GS.u64Base = pCtx->gs.u64Base;
1009 }
1010 else
1011 {
1012 /* Filter out the MSR_K6_LME bit or else AMD-V expects amd64 shadow paging. */
1013 pvVMCB->guest.u64EFER &= ~MSR_K6_EFER_LME;
1014
1015 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1016 }
1017
1018 /* TSC offset. */
1019 if (TMCpuTickCanUseRealTSC(pVCpu, &pvVMCB->ctrl.u64TSCOffset))
1020 {
1021 uint64_t u64CurTSC = ASMReadTSC();
1022 if (u64CurTSC + pvVMCB->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
1023 {
1024 pvVMCB->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
1025 pvVMCB->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
1026 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
1027 }
1028 else
1029 {
1030 /* Fall back to rdtsc emulation as we would otherwise pass decreasing tsc values to the guest. */
1031 LogFlow(("TSC %RX64 offset %RX64 time=%RX64 last=%RX64 (diff=%RX64, virt_tsc=%RX64)\n", u64CurTSC,
1032 pvVMCB->ctrl.u64TSCOffset, u64CurTSC + pvVMCB->ctrl.u64TSCOffset, TMCpuTickGetLastSeen(pVCpu),
1033 TMCpuTickGetLastSeen(pVCpu) - u64CurTSC - pvVMCB->ctrl.u64TSCOffset, TMCpuTickGet(pVCpu)));
1034 pvVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1035 pvVMCB->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1036 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
1037 }
1038 }
1039 else
1040 {
1041 pvVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1042 pvVMCB->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1043 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
1044 }
1045
1046 /* Sync the various MSRs for 64-bit mode. */
1047 pvVMCB->guest.u64STAR = pCtx->msrSTAR; /* legacy syscall eip, cs & ss */
1048 pvVMCB->guest.u64LSTAR = pCtx->msrLSTAR; /* 64-bit mode syscall rip */
1049 pvVMCB->guest.u64CSTAR = pCtx->msrCSTAR; /* compatibility mode syscall rip */
1050 pvVMCB->guest.u64SFMASK = pCtx->msrSFMASK; /* syscall flag mask */
1051 pvVMCB->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE; /* SWAPGS exchange value */
1052
1053#ifdef DEBUG
1054 /* Intercept X86_XCPT_DB if stepping is enabled */
1055 if ( DBGFIsStepping(pVCpu)
1056 || CPUMIsHyperDebugStateActive(pVCpu))
1057 pvVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_DB);
1058 else
1059 pvVMCB->ctrl.u32InterceptException &= ~RT_BIT(X86_XCPT_DB);
1060#endif
1061
1062 /* Done. */
1063 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_ALL_GUEST;
1064
1065 return VINF_SUCCESS;
1066}
1067
1068
1069/**
1070 * Setup TLB for ASID.
1071 *
1072 * @param pVM Pointer to the VM.
1073 * @param pVCpu Pointer to the VMCPU.
1074 */
1075static void hmR0SvmSetupTLB(PVM pVM, PVMCPU pVCpu)
1076{
1077 PHMGLOBLCPUINFO pCpu;
1078
1079 AssertPtr(pVM);
1080 AssertPtr(pVCpu);
1081
1082 SVM_VMCB *pvVMCB = (SVM_VMCB *)pVCpu->hm.s.svm.pvVMCB;
1083 pCpu = HMR0GetCurrentCpu();
1084
1085 /*
1086 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
1087 * This can happen both for start & resume due to long jumps back to ring-3.
1088 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
1089 * so we cannot reuse the ASIDs without flushing.
1090 */
1091 bool fNewAsid = false;
1092 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
1093 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
1094 {
1095 pVCpu->hm.s.fForceTLBFlush = true;
1096 fNewAsid = true;
1097 }
1098
1099 /*
1100 * Set TLB flush state as checked until we return from the world switch.
1101 */
1102 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
1103
1104 /*
1105 * Check for TLB shootdown flushes.
1106 */
1107 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
1108 pVCpu->hm.s.fForceTLBFlush = true;
1109
1110 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
1111 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
1112
1113 if (RT_UNLIKELY(pVM->hm.s.svm.fAlwaysFlushTLB))
1114 {
1115 /*
1116 * This is the AMD erratum 170. We need to flush the entire TLB for each world switch. Sad.
1117 */
1118 pCpu->uCurrentAsid = 1;
1119 pVCpu->hm.s.uCurrentAsid = 1;
1120 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1121 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1122 }
1123 else if (pVCpu->hm.s.fForceTLBFlush)
1124 {
1125 if (fNewAsid)
1126 {
1127 ++pCpu->uCurrentAsid;
1128 bool fHitASIDLimit = false;
1129 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
1130 {
1131 pCpu->uCurrentAsid = 1; /* start at 1; host uses 0 */
1132 pCpu->cTlbFlushes++;
1133 fHitASIDLimit = true;
1134
1135 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1136 {
1137 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1138 pCpu->fFlushAsidBeforeUse = true;
1139 }
1140 else
1141 {
1142 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1143 pCpu->fFlushAsidBeforeUse = false;
1144 }
1145 }
1146
1147 if ( !fHitASIDLimit
1148 && pCpu->fFlushAsidBeforeUse)
1149 {
1150 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1151 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1152 else
1153 {
1154 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1155 pCpu->fFlushAsidBeforeUse = false;
1156 }
1157 }
1158
1159 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
1160 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1161 }
1162 else
1163 {
1164 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1165 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1166 else
1167 pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1168 }
1169
1170 pVCpu->hm.s.fForceTLBFlush = false;
1171 }
1172 else
1173 {
1174 /** @todo We never set VMCPU_FF_TLB_SHOOTDOWN anywhere so this path should
1175 * not be executed. See hmQueueInvlPage() where it is commented
1176 * out. Support individual entry flushing someday. */
1177 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
1178 {
1179 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
1180 STAM_COUNTER_INC(&pVCpu->hm.s.StatTlbShootdown);
1181 for (uint32_t i = 0; i < pVCpu->hm.s.TlbShootdown.cPages; i++)
1182 SVMR0InvlpgA(pVCpu->hm.s.TlbShootdown.aPages[i], pvVMCB->ctrl.TLBCtrl.n.u32ASID);
1183 }
1184 }
1185
1186 pVCpu->hm.s.TlbShootdown.cPages = 0;
1187 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
1188
1189 /* Update VMCB with the ASID. */
1190 pvVMCB->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
1191
1192 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
1193 ("Flush count mismatch for cpu %d (%x vs %x)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
1194 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
1195 ("cpu%d uCurrentAsid = %x\n", pCpu->idCpu, pCpu->uCurrentAsid));
1196 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
1197 ("cpu%d VM uCurrentAsid = %x\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
1198
1199#ifdef VBOX_WITH_STATISTICS
1200 if (pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
1201 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
1202 else if ( pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
1203 || pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
1204 {
1205 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
1206 }
1207 else
1208 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
1209#endif
1210}
1211
1212
1213/**
1214 * Runs guest code in an AMD-V VM.
1215 *
1216 * @returns VBox status code.
1217 * @param pVM Pointer to the VM.
1218 * @param pVCpu Pointer to the VMCPU.
1219 * @param pCtx Pointer to the guest CPU context.
1220 */
1221VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1222{
1223 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
1224 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
1225 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
1226
1227 VBOXSTRICTRC rc = VINF_SUCCESS;
1228 int rc2;
1229 uint64_t exitCode = (uint64_t)SVM_EXIT_INVALID;
1230 SVM_VMCB *pvVMCB = NULL;
1231 bool fSyncTPR = false;
1232 unsigned cResume = 0;
1233 uint8_t u8LastTPR = 0; /* Initialized for potentially stupid compilers. */
1234 uint32_t u32HostExtFeatures = 0;
1235 PHMGLOBLCPUINFO pCpu = 0;
1236 RTCCUINTREG uOldEFlags = ~(RTCCUINTREG)0;
1237#ifdef VBOX_STRICT
1238 RTCPUID idCpuCheck;
1239#endif
1240#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1241 uint64_t u64LastTime = RTTimeMilliTS();
1242#endif
1243
1244 pvVMCB = (SVM_VMCB *)pVCpu->hm.s.svm.pvVMCB;
1245 AssertMsgReturn(pvVMCB, ("Invalid pvVMCB\n"), VERR_SVM_INVALID_PVMCB);
1246
1247 /*
1248 * We can jump to this point to resume execution after determining that a VM-exit is innocent.
1249 */
1250ResumeExecution:
1251 if (!STAM_PROFILE_ADV_IS_RUNNING(&pVCpu->hm.s.StatEntry))
1252 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit2, &pVCpu->hm.s.StatEntry, x);
1253 Assert(!HMR0SuspendPending());
1254
1255 /*
1256 * Safety precaution; looping for too long here can have a very bad effect on the host.
1257 */
1258 if (RT_UNLIKELY(++cResume > pVM->hm.s.cMaxResumeLoops))
1259 {
1260 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
1261 rc = VINF_EM_RAW_INTERRUPT;
1262 goto end;
1263 }
1264
1265 /*
1266 * Check for IRQ inhibition due to instruction fusing (sti, mov ss).
1267 */
1268 if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1269 {
1270 Log(("VM_FF_INHIBIT_INTERRUPTS at %RGv successor %RGv\n", (RTGCPTR)pCtx->rip, EMGetInhibitInterruptsPC(pVCpu)));
1271 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
1272 {
1273 /*
1274 * Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here.
1275 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
1276 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
1277 * break the guest. Sounds very unlikely, but such timing sensitive problems are not as rare as you might think.
1278 */
1279 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1280 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1281 pvVMCB->ctrl.u64IntShadow = 0;
1282 }
1283 }
1284 else
1285 {
1286 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1287 pvVMCB->ctrl.u64IntShadow = 0;
1288 }
1289
1290#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1291 if (RT_UNLIKELY((cResume & 0xf) == 0))
1292 {
1293 uint64_t u64CurTime = RTTimeMilliTS();
1294
1295 if (RT_UNLIKELY(u64CurTime > u64LastTime))
1296 {
1297 u64LastTime = u64CurTime;
1298 TMTimerPollVoid(pVM, pVCpu);
1299 }
1300 }
1301#endif
1302
1303 /*
1304 * Check for pending actions that force us to go back to ring-3.
1305 */
1306 if ( VM_FF_ISPENDING(pVM, VM_FF_HM_TO_R3_MASK | VM_FF_REQUEST | VM_FF_PGM_POOL_FLUSH_PENDING | VM_FF_PDM_DMA)
1307 || VMCPU_FF_ISPENDING(pVCpu,
1308 VMCPU_FF_HM_TO_R3_MASK
1309 | VMCPU_FF_PGM_SYNC_CR3
1310 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
1311 | VMCPU_FF_REQUEST))
1312 {
1313 /* Check if a sync operation is pending. */
1314 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
1315 {
1316 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
1317 AssertRC(VBOXSTRICTRC_VAL(rc));
1318 if (rc != VINF_SUCCESS)
1319 {
1320 Log(("Pending pool sync is forcing us back to ring 3; rc=%d\n", VBOXSTRICTRC_VAL(rc)));
1321 goto end;
1322 }
1323 }
1324
1325#ifdef DEBUG
1326 /* Intercept X86_XCPT_DB if stepping is enabled */
1327 if (!DBGFIsStepping(pVCpu))
1328#endif
1329 {
1330 if ( VM_FF_ISPENDING(pVM, VM_FF_HM_TO_R3_MASK)
1331 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
1332 {
1333 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
1334 rc = RT_UNLIKELY(VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
1335 goto end;
1336 }
1337 }
1338
1339 /* Pending request packets might contain actions that need immediate attention, such as pending hardware interrupts. */
1340 if ( VM_FF_ISPENDING(pVM, VM_FF_REQUEST)
1341 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_REQUEST))
1342 {
1343 rc = VINF_EM_PENDING_REQUEST;
1344 goto end;
1345 }
1346
1347 /* Check if a pgm pool flush is in progress. */
1348 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
1349 {
1350 rc = VINF_PGM_POOL_FLUSH_PENDING;
1351 goto end;
1352 }
1353
1354 /* Check if DMA work is pending (2nd+ run). */
1355 if (VM_FF_ISPENDING(pVM, VM_FF_PDM_DMA) && cResume > 1)
1356 {
1357 rc = VINF_EM_RAW_TO_R3;
1358 goto end;
1359 }
1360 }
1361
1362#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1363 /*
1364 * Exit to ring-3 preemption/work is pending.
1365 *
1366 * Interrupts are disabled before the call to make sure we don't miss any interrupt
1367 * that would flag preemption (IPI, timer tick, ++). (Would've been nice to do this
1368 * further down, but hmR0SvmCheckPendingInterrupt makes that impossible.)
1369 *
1370 * Note! Interrupts must be disabled done *before* we check for TLB flushes; TLB
1371 * shootdowns rely on this.
1372 */
1373 uOldEFlags = ASMIntDisableFlags();
1374 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
1375 {
1376 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
1377 rc = VINF_EM_RAW_INTERRUPT;
1378 goto end;
1379 }
1380 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1381#endif
1382
1383 /*
1384 * When external interrupts are pending, we should exit the VM when IF is set.
1385 * Note: *After* VM_FF_INHIBIT_INTERRUPTS check!!
1386 */
1387 rc = hmR0SvmCheckPendingInterrupt(pVM, pVCpu, pvVMCB, pCtx);
1388 if (RT_FAILURE(rc))
1389 goto end;
1390
1391 /*
1392 * TPR caching using CR8 is only available in 64-bit mode or with 32-bit guests when X86_CPUID_AMD_FEATURE_ECX_CR8L is
1393 * supported.
1394 * Note: we can't do this in LoddGuestState as PDMApicGetTPR can jump back to ring 3 (lock)! (no longer true)
1395 */
1396 /** @todo query and update the TPR only when it could have been changed (mmio access)
1397 */
1398 if (pVM->hm.s.fHasIoApic)
1399 {
1400 /* TPR caching in CR8 */
1401 bool fPending;
1402 rc2 = PDMApicGetTPR(pVCpu, &u8LastTPR, &fPending, NULL /* pu8PendingIrq */);
1403 AssertRC(rc2);
1404
1405 if (pVM->hm.s.fTPRPatchingActive)
1406 {
1407 /* Our patch code uses LSTAR for TPR caching. */
1408 pCtx->msrLSTAR = u8LastTPR;
1409
1410 if (fPending)
1411 {
1412 /* A TPR change could activate a pending interrupt, so catch lstar writes. */
1413 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, false);
1414 }
1415 else
1416 {
1417 /*
1418 * No interrupts are pending, so we don't need to be explicitely notified.
1419 * There are enough world switches for detecting pending interrupts.
1420 */
1421 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
1422 }
1423 }
1424 else
1425 {
1426 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1427 pvVMCB->ctrl.IntCtrl.n.u8VTPR = (u8LastTPR >> 4);
1428
1429 if (fPending)
1430 {
1431 /* A TPR change could activate a pending interrupt, so catch cr8 writes. */
1432 pvVMCB->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1433 }
1434 else
1435 {
1436 /*
1437 * No interrupts are pending, so we don't need to be explicitly notified.
1438 * There are enough world switches for detecting pending interrupts.
1439 */
1440 pvVMCB->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1441 }
1442 }
1443 fSyncTPR = !fPending;
1444 }
1445
1446 /* All done! Let's start VM execution. */
1447
1448 /* Enable nested paging if necessary (disabled each time after #VMEXIT). */
1449 pvVMCB->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
1450
1451#ifdef LOG_ENABLED
1452 pCpu = HMR0GetCurrentCpu();
1453 if (pVCpu->hm.s.idLastCpu != pCpu->idCpu)
1454 LogFlow(("Force TLB flush due to rescheduling to a different cpu (%d vs %d)\n", pVCpu->hm.s.idLastCpu, pCpu->idCpu));
1455 else if (pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
1456 LogFlow(("Force TLB flush due to changed TLB flush count (%x vs %x)\n", pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
1457 else if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH))
1458 LogFlow(("Manual TLB flush\n"));
1459#endif
1460
1461 /*
1462 * NOTE: DO NOT DO ANYTHING AFTER THIS POINT THAT MIGHT JUMP BACK TO RING 3!
1463 * (until the actual world switch)
1464 */
1465#ifdef VBOX_STRICT
1466 idCpuCheck = RTMpCpuId();
1467#endif
1468 VMMR0LogFlushDisable(pVCpu);
1469
1470 /*
1471 * Load the guest state; *must* be here as it sets up the shadow CR0 for lazy FPU syncing!
1472 */
1473 rc = SVMR0LoadGuestState(pVM, pVCpu, pCtx);
1474 if (RT_UNLIKELY(rc != VINF_SUCCESS))
1475 {
1476 VMMR0LogFlushEnable(pVCpu);
1477 goto end;
1478 }
1479
1480#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1481 /*
1482 * Disable interrupts to make sure a poke will interrupt execution.
1483 * This must be done *before* we check for TLB flushes; TLB shootdowns rely on this.
1484 */
1485 uOldEFlags = ASMIntDisableFlags();
1486 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1487#endif
1488 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
1489
1490 /* Setup TLB control and ASID in the VMCB. */
1491 hmR0SvmSetupTLB(pVM, pVCpu);
1492
1493 /* In case we execute a goto ResumeExecution later on. */
1494 pVCpu->hm.s.fResumeVM = true;
1495 pVCpu->hm.s.fForceTLBFlush = pVM->hm.s.svm.fAlwaysFlushTLB;
1496
1497 Assert(sizeof(pVCpu->hm.s.svm.HCPhysVMCB) == 8);
1498 Assert(pvVMCB->ctrl.IntCtrl.n.u1VIrqMasking);
1499 Assert(pvVMCB->ctrl.u64IOPMPhysAddr == pVM->hm.s.svm.HCPhysIOBitmap);
1500 Assert(pvVMCB->ctrl.u64MSRPMPhysAddr == pVCpu->hm.s.svm.HCPhysMsrBitmap);
1501 Assert(pvVMCB->ctrl.u64LBRVirt == 0);
1502
1503#ifdef VBOX_STRICT
1504 Assert(idCpuCheck == RTMpCpuId());
1505#endif
1506 TMNotifyStartOfExecution(pVCpu);
1507
1508 /*
1509 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
1510 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
1511 */
1512 u32HostExtFeatures = pVM->hm.s.cpuid.u32AMDFeatureEDX;
1513 if ( (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1514 && !(pvVMCB->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
1515 {
1516 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
1517 uint64_t u64GuestTscAux = 0;
1518 rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
1519 AssertRC(rc2);
1520 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
1521 }
1522
1523#ifdef VBOX_WITH_KERNEL_USING_XMM
1524 HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVMCBHost, pVCpu->hm.s.svm.HCPhysVMCB, pCtx, pVM, pVCpu,
1525 pVCpu->hm.s.svm.pfnVMRun);
1526#else
1527 pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVMCBHost, pVCpu->hm.s.svm.HCPhysVMCB, pCtx, pVM, pVCpu);
1528#endif
1529
1530 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false);
1531 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits);
1532 /* Possibly the last TSC value seen by the guest (too high) (only when we're in TSC offset mode). */
1533 if (!(pvVMCB->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
1534 {
1535 /* Restore host's TSC_AUX. */
1536 if (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1537 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
1538
1539 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() +
1540 pvVMCB->ctrl.u64TSCOffset - 0x400 /* guestimate of world switch overhead in clock ticks */);
1541 }
1542
1543 TMNotifyEndOfExecution(pVCpu);
1544 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
1545 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
1546 ASMSetFlags(uOldEFlags);
1547#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1548 uOldEFlags = ~(RTCCUINTREG)0;
1549#endif
1550
1551 /*
1552 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1553 * 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
1554 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1555 */
1556
1557 /* Reason for the VM exit */
1558 exitCode = pvVMCB->ctrl.u64ExitCode;
1559
1560 if (RT_UNLIKELY(exitCode == (uint64_t)SVM_EXIT_INVALID)) /* Invalid guest state. */
1561 {
1562 HMDumpRegs(pVM, pVCpu, pCtx);
1563#ifdef DEBUG
1564 Log(("ctrl.u16InterceptRdCRx %x\n", pvVMCB->ctrl.u16InterceptRdCRx));
1565 Log(("ctrl.u16InterceptWrCRx %x\n", pvVMCB->ctrl.u16InterceptWrCRx));
1566 Log(("ctrl.u16InterceptRdDRx %x\n", pvVMCB->ctrl.u16InterceptRdDRx));
1567 Log(("ctrl.u16InterceptWrDRx %x\n", pvVMCB->ctrl.u16InterceptWrDRx));
1568 Log(("ctrl.u32InterceptException %x\n", pvVMCB->ctrl.u32InterceptException));
1569 Log(("ctrl.u32InterceptCtrl1 %x\n", pvVMCB->ctrl.u32InterceptCtrl1));
1570 Log(("ctrl.u32InterceptCtrl2 %x\n", pvVMCB->ctrl.u32InterceptCtrl2));
1571 Log(("ctrl.u64IOPMPhysAddr %RX64\n", pvVMCB->ctrl.u64IOPMPhysAddr));
1572 Log(("ctrl.u64MSRPMPhysAddr %RX64\n", pvVMCB->ctrl.u64MSRPMPhysAddr));
1573 Log(("ctrl.u64TSCOffset %RX64\n", pvVMCB->ctrl.u64TSCOffset));
1574
1575 Log(("ctrl.TLBCtrl.u32ASID %x\n", pvVMCB->ctrl.TLBCtrl.n.u32ASID));
1576 Log(("ctrl.TLBCtrl.u8TLBFlush %x\n", pvVMCB->ctrl.TLBCtrl.n.u8TLBFlush));
1577 Log(("ctrl.TLBCtrl.u24Reserved %x\n", pvVMCB->ctrl.TLBCtrl.n.u24Reserved));
1578
1579 Log(("ctrl.IntCtrl.u8VTPR %x\n", pvVMCB->ctrl.IntCtrl.n.u8VTPR));
1580 Log(("ctrl.IntCtrl.u1VIrqValid %x\n", pvVMCB->ctrl.IntCtrl.n.u1VIrqValid));
1581 Log(("ctrl.IntCtrl.u7Reserved %x\n", pvVMCB->ctrl.IntCtrl.n.u7Reserved));
1582 Log(("ctrl.IntCtrl.u4VIrqPriority %x\n", pvVMCB->ctrl.IntCtrl.n.u4VIrqPriority));
1583 Log(("ctrl.IntCtrl.u1IgnoreTPR %x\n", pvVMCB->ctrl.IntCtrl.n.u1IgnoreTPR));
1584 Log(("ctrl.IntCtrl.u3Reserved %x\n", pvVMCB->ctrl.IntCtrl.n.u3Reserved));
1585 Log(("ctrl.IntCtrl.u1VIrqMasking %x\n", pvVMCB->ctrl.IntCtrl.n.u1VIrqMasking));
1586 Log(("ctrl.IntCtrl.u7Reserved2 %x\n", pvVMCB->ctrl.IntCtrl.n.u7Reserved2));
1587 Log(("ctrl.IntCtrl.u8VIrqVector %x\n", pvVMCB->ctrl.IntCtrl.n.u8VIrqVector));
1588 Log(("ctrl.IntCtrl.u24Reserved %x\n", pvVMCB->ctrl.IntCtrl.n.u24Reserved));
1589
1590 Log(("ctrl.u64IntShadow %RX64\n", pvVMCB->ctrl.u64IntShadow));
1591 Log(("ctrl.u64ExitCode %RX64\n", pvVMCB->ctrl.u64ExitCode));
1592 Log(("ctrl.u64ExitInfo1 %RX64\n", pvVMCB->ctrl.u64ExitInfo1));
1593 Log(("ctrl.u64ExitInfo2 %RX64\n", pvVMCB->ctrl.u64ExitInfo2));
1594 Log(("ctrl.ExitIntInfo.u8Vector %x\n", pvVMCB->ctrl.ExitIntInfo.n.u8Vector));
1595 Log(("ctrl.ExitIntInfo.u3Type %x\n", pvVMCB->ctrl.ExitIntInfo.n.u3Type));
1596 Log(("ctrl.ExitIntInfo.u1ErrorCodeValid %x\n", pvVMCB->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
1597 Log(("ctrl.ExitIntInfo.u19Reserved %x\n", pvVMCB->ctrl.ExitIntInfo.n.u19Reserved));
1598 Log(("ctrl.ExitIntInfo.u1Valid %x\n", pvVMCB->ctrl.ExitIntInfo.n.u1Valid));
1599 Log(("ctrl.ExitIntInfo.u32ErrorCode %x\n", pvVMCB->ctrl.ExitIntInfo.n.u32ErrorCode));
1600 Log(("ctrl.NestedPaging %RX64\n", pvVMCB->ctrl.NestedPaging.au64));
1601 Log(("ctrl.EventInject.u8Vector %x\n", pvVMCB->ctrl.EventInject.n.u8Vector));
1602 Log(("ctrl.EventInject.u3Type %x\n", pvVMCB->ctrl.EventInject.n.u3Type));
1603 Log(("ctrl.EventInject.u1ErrorCodeValid %x\n", pvVMCB->ctrl.EventInject.n.u1ErrorCodeValid));
1604 Log(("ctrl.EventInject.u19Reserved %x\n", pvVMCB->ctrl.EventInject.n.u19Reserved));
1605 Log(("ctrl.EventInject.u1Valid %x\n", pvVMCB->ctrl.EventInject.n.u1Valid));
1606 Log(("ctrl.EventInject.u32ErrorCode %x\n", pvVMCB->ctrl.EventInject.n.u32ErrorCode));
1607
1608 Log(("ctrl.u64NestedPagingCR3 %RX64\n", pvVMCB->ctrl.u64NestedPagingCR3));
1609 Log(("ctrl.u64LBRVirt %RX64\n", pvVMCB->ctrl.u64LBRVirt));
1610
1611 Log(("guest.CS.u16Sel %04X\n", pvVMCB->guest.CS.u16Sel));
1612 Log(("guest.CS.u16Attr %04X\n", pvVMCB->guest.CS.u16Attr));
1613 Log(("guest.CS.u32Limit %X\n", pvVMCB->guest.CS.u32Limit));
1614 Log(("guest.CS.u64Base %RX64\n", pvVMCB->guest.CS.u64Base));
1615 Log(("guest.DS.u16Sel %04X\n", pvVMCB->guest.DS.u16Sel));
1616 Log(("guest.DS.u16Attr %04X\n", pvVMCB->guest.DS.u16Attr));
1617 Log(("guest.DS.u32Limit %X\n", pvVMCB->guest.DS.u32Limit));
1618 Log(("guest.DS.u64Base %RX64\n", pvVMCB->guest.DS.u64Base));
1619 Log(("guest.ES.u16Sel %04X\n", pvVMCB->guest.ES.u16Sel));
1620 Log(("guest.ES.u16Attr %04X\n", pvVMCB->guest.ES.u16Attr));
1621 Log(("guest.ES.u32Limit %X\n", pvVMCB->guest.ES.u32Limit));
1622 Log(("guest.ES.u64Base %RX64\n", pvVMCB->guest.ES.u64Base));
1623 Log(("guest.FS.u16Sel %04X\n", pvVMCB->guest.FS.u16Sel));
1624 Log(("guest.FS.u16Attr %04X\n", pvVMCB->guest.FS.u16Attr));
1625 Log(("guest.FS.u32Limit %X\n", pvVMCB->guest.FS.u32Limit));
1626 Log(("guest.FS.u64Base %RX64\n", pvVMCB->guest.FS.u64Base));
1627 Log(("guest.GS.u16Sel %04X\n", pvVMCB->guest.GS.u16Sel));
1628 Log(("guest.GS.u16Attr %04X\n", pvVMCB->guest.GS.u16Attr));
1629 Log(("guest.GS.u32Limit %X\n", pvVMCB->guest.GS.u32Limit));
1630 Log(("guest.GS.u64Base %RX64\n", pvVMCB->guest.GS.u64Base));
1631
1632 Log(("guest.GDTR.u32Limit %X\n", pvVMCB->guest.GDTR.u32Limit));
1633 Log(("guest.GDTR.u64Base %RX64\n", pvVMCB->guest.GDTR.u64Base));
1634
1635 Log(("guest.LDTR.u16Sel %04X\n", pvVMCB->guest.LDTR.u16Sel));
1636 Log(("guest.LDTR.u16Attr %04X\n", pvVMCB->guest.LDTR.u16Attr));
1637 Log(("guest.LDTR.u32Limit %X\n", pvVMCB->guest.LDTR.u32Limit));
1638 Log(("guest.LDTR.u64Base %RX64\n", pvVMCB->guest.LDTR.u64Base));
1639
1640 Log(("guest.IDTR.u32Limit %X\n", pvVMCB->guest.IDTR.u32Limit));
1641 Log(("guest.IDTR.u64Base %RX64\n", pvVMCB->guest.IDTR.u64Base));
1642
1643 Log(("guest.TR.u16Sel %04X\n", pvVMCB->guest.TR.u16Sel));
1644 Log(("guest.TR.u16Attr %04X\n", pvVMCB->guest.TR.u16Attr));
1645 Log(("guest.TR.u32Limit %X\n", pvVMCB->guest.TR.u32Limit));
1646 Log(("guest.TR.u64Base %RX64\n", pvVMCB->guest.TR.u64Base));
1647
1648 Log(("guest.u8CPL %X\n", pvVMCB->guest.u8CPL));
1649 Log(("guest.u64CR0 %RX64\n", pvVMCB->guest.u64CR0));
1650 Log(("guest.u64CR2 %RX64\n", pvVMCB->guest.u64CR2));
1651 Log(("guest.u64CR3 %RX64\n", pvVMCB->guest.u64CR3));
1652 Log(("guest.u64CR4 %RX64\n", pvVMCB->guest.u64CR4));
1653 Log(("guest.u64DR6 %RX64\n", pvVMCB->guest.u64DR6));
1654 Log(("guest.u64DR7 %RX64\n", pvVMCB->guest.u64DR7));
1655
1656 Log(("guest.u64RIP %RX64\n", pvVMCB->guest.u64RIP));
1657 Log(("guest.u64RSP %RX64\n", pvVMCB->guest.u64RSP));
1658 Log(("guest.u64RAX %RX64\n", pvVMCB->guest.u64RAX));
1659 Log(("guest.u64RFlags %RX64\n", pvVMCB->guest.u64RFlags));
1660
1661 Log(("guest.u64SysEnterCS %RX64\n", pvVMCB->guest.u64SysEnterCS));
1662 Log(("guest.u64SysEnterEIP %RX64\n", pvVMCB->guest.u64SysEnterEIP));
1663 Log(("guest.u64SysEnterESP %RX64\n", pvVMCB->guest.u64SysEnterESP));
1664
1665 Log(("guest.u64EFER %RX64\n", pvVMCB->guest.u64EFER));
1666 Log(("guest.u64STAR %RX64\n", pvVMCB->guest.u64STAR));
1667 Log(("guest.u64LSTAR %RX64\n", pvVMCB->guest.u64LSTAR));
1668 Log(("guest.u64CSTAR %RX64\n", pvVMCB->guest.u64CSTAR));
1669 Log(("guest.u64SFMASK %RX64\n", pvVMCB->guest.u64SFMASK));
1670 Log(("guest.u64KernelGSBase %RX64\n", pvVMCB->guest.u64KernelGSBase));
1671 Log(("guest.u64GPAT %RX64\n", pvVMCB->guest.u64GPAT));
1672 Log(("guest.u64DBGCTL %RX64\n", pvVMCB->guest.u64DBGCTL));
1673 Log(("guest.u64BR_FROM %RX64\n", pvVMCB->guest.u64BR_FROM));
1674 Log(("guest.u64BR_TO %RX64\n", pvVMCB->guest.u64BR_TO));
1675 Log(("guest.u64LASTEXCPFROM %RX64\n", pvVMCB->guest.u64LASTEXCPFROM));
1676 Log(("guest.u64LASTEXCPTO %RX64\n", pvVMCB->guest.u64LASTEXCPTO));
1677#endif
1678 rc = VERR_SVM_UNABLE_TO_START_VM;
1679 VMMR0LogFlushEnable(pVCpu);
1680 goto end;
1681 }
1682
1683 /* Let's first sync back EIP, ESP, and EFLAGS. */
1684 pCtx->rip = pvVMCB->guest.u64RIP;
1685 pCtx->rsp = pvVMCB->guest.u64RSP;
1686 pCtx->eflags.u32 = pvVMCB->guest.u64RFlags;
1687 /* eax is saved/restore across the vmrun instruction */
1688 pCtx->rax = pvVMCB->guest.u64RAX;
1689
1690 /*
1691 * Save all the MSRs that can be changed by the guest without causing a world switch.
1692 * FS & GS base are saved with SVM_READ_SELREG.
1693 */
1694 pCtx->msrSTAR = pvVMCB->guest.u64STAR; /* legacy syscall eip, cs & ss */
1695 pCtx->msrLSTAR = pvVMCB->guest.u64LSTAR; /* 64-bit mode syscall rip */
1696 pCtx->msrCSTAR = pvVMCB->guest.u64CSTAR; /* compatibility mode syscall rip */
1697 pCtx->msrSFMASK = pvVMCB->guest.u64SFMASK; /* syscall flag mask */
1698 pCtx->msrKERNELGSBASE = pvVMCB->guest.u64KernelGSBase; /* swapgs exchange value */
1699 pCtx->SysEnter.cs = pvVMCB->guest.u64SysEnterCS;
1700 pCtx->SysEnter.eip = pvVMCB->guest.u64SysEnterEIP;
1701 pCtx->SysEnter.esp = pvVMCB->guest.u64SysEnterESP;
1702
1703 /* Can be updated behind our back in the nested paging case. */
1704 pCtx->cr2 = pvVMCB->guest.u64CR2;
1705
1706 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1707 SVM_READ_SELREG(SS, ss);
1708 SVM_READ_SELREG(CS, cs);
1709 SVM_READ_SELREG(DS, ds);
1710 SVM_READ_SELREG(ES, es);
1711 SVM_READ_SELREG(FS, fs);
1712 SVM_READ_SELREG(GS, gs);
1713
1714 /*
1715 * Correct the hidden CS granularity flag. Haven't seen it being wrong in any other
1716 * register (yet).
1717 */
1718 if ( !pCtx->cs.Attr.n.u1Granularity
1719 && pCtx->cs.Attr.n.u1Present
1720 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
1721 {
1722 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
1723 pCtx->cs.Attr.n.u1Granularity = 1;
1724 }
1725#define SVM_ASSERT_SEL_GRANULARITY(reg) \
1726 AssertMsg( !pCtx->reg.Attr.n.u1Present \
1727 || ( pCtx->reg.Attr.n.u1Granularity \
1728 ? (pCtx->reg.u32Limit & 0xfff) == 0xfff \
1729 : pCtx->reg.u32Limit <= 0xfffff), \
1730 ("%#x %#x %#llx\n", pCtx->reg.u32Limit, pCtx->reg.Attr.u, pCtx->reg.u64Base))
1731 SVM_ASSERT_SEL_GRANULARITY(ss);
1732 SVM_ASSERT_SEL_GRANULARITY(cs);
1733 SVM_ASSERT_SEL_GRANULARITY(ds);
1734 SVM_ASSERT_SEL_GRANULARITY(es);
1735 SVM_ASSERT_SEL_GRANULARITY(fs);
1736 SVM_ASSERT_SEL_GRANULARITY(gs);
1737#undef SVM_ASSERT_SEL_GRANULARITY
1738
1739 /*
1740 * Correct the hidden SS DPL field. It can be wrong on certain CPUs
1741 * sometimes (seen it on AMD Fusion CPUs with 64-bit guests). The CPU
1742 * always uses the CPL field in the VMCB instead of the DPL in the hidden
1743 * SS (chapter AMD spec. 15.5.1 Basic operation).
1744 */
1745 Assert(!(pvVMCB->guest.u8CPL & ~0x3));
1746 pCtx->ss.Attr.n.u2Dpl = pvVMCB->guest.u8CPL & 0x3;
1747
1748 /*
1749 * Remaining guest CPU context: TR, IDTR, GDTR, LDTR;
1750 * must sync everything otherwise we can get out of sync when jumping back to ring-3.
1751 */
1752 SVM_READ_SELREG(LDTR, ldtr);
1753 SVM_READ_SELREG(TR, tr);
1754
1755 pCtx->gdtr.cbGdt = pvVMCB->guest.GDTR.u32Limit;
1756 pCtx->gdtr.pGdt = pvVMCB->guest.GDTR.u64Base;
1757
1758 pCtx->idtr.cbIdt = pvVMCB->guest.IDTR.u32Limit;
1759 pCtx->idtr.pIdt = pvVMCB->guest.IDTR.u64Base;
1760
1761 /*
1762 * No reason to sync back the CRx and DRx registers as they cannot be changed by the guest
1763 * unless in the nested paging case where CR3 can be changed by the guest.
1764 */
1765 if ( pVM->hm.s.fNestedPaging
1766 && pCtx->cr3 != pvVMCB->guest.u64CR3)
1767 {
1768 CPUMSetGuestCR3(pVCpu, pvVMCB->guest.u64CR3);
1769 PGMUpdateCR3(pVCpu, pvVMCB->guest.u64CR3);
1770 }
1771
1772 /* Note! NOW IT'S SAFE FOR LOGGING! */
1773 VMMR0LogFlushEnable(pVCpu);
1774
1775 /* Take care of instruction fusing (sti, mov ss) (see AMD spec. 15.20.5 Interrupt Shadows) */
1776 if (pvVMCB->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1777 {
1778 Log(("uInterruptState %x rip=%RGv\n", pvVMCB->ctrl.u64IntShadow, (RTGCPTR)pCtx->rip));
1779 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip);
1780 }
1781 else
1782 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1783
1784 Log2(("exitCode = %x\n", exitCode));
1785
1786 /* Sync back DR6 as it could have been changed by hitting breakpoints. */
1787 pCtx->dr[6] = pvVMCB->guest.u64DR6;
1788 /* DR7.GD can be cleared by debug exceptions, so sync it back as well. */
1789 pCtx->dr[7] = pvVMCB->guest.u64DR7;
1790
1791 /* Check if an injected event was interrupted prematurely. */
1792 pVCpu->hm.s.Event.u64IntrInfo = pvVMCB->ctrl.ExitIntInfo.au64[0];
1793 if ( pvVMCB->ctrl.ExitIntInfo.n.u1Valid
1794 /* we don't care about 'int xx' as the instruction will be restarted. */
1795 && pvVMCB->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
1796 {
1797 Log(("Pending inject %RX64 at %RGv exit=%08x\n", pVCpu->hm.s.Event.u64IntrInfo, (RTGCPTR)pCtx->rip, exitCode));
1798
1799#ifdef LOG_ENABLED
1800 SVM_EVENT Event;
1801 Event.au64[0] = pVCpu->hm.s.Event.u64IntrInfo;
1802
1803 if ( exitCode == SVM_EXIT_EXCEPTION_E
1804 && Event.n.u8Vector == 0xE)
1805 {
1806 Log(("Double fault!\n"));
1807 }
1808#endif
1809
1810 pVCpu->hm.s.Event.fPending = true;
1811 /* Error code present? (redundant) */
1812 if (pvVMCB->ctrl.ExitIntInfo.n.u1ErrorCodeValid)
1813 pVCpu->hm.s.Event.u32ErrCode = pvVMCB->ctrl.ExitIntInfo.n.u32ErrorCode;
1814 else
1815 pVCpu->hm.s.Event.u32ErrCode = 0;
1816 }
1817#ifdef VBOX_WITH_STATISTICS
1818 if (exitCode == SVM_EXIT_NPF)
1819 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
1820 else
1821 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[exitCode & MASK_EXITREASON_STAT]);
1822#endif
1823
1824 /* Sync back the TPR if it was changed. */
1825 if (fSyncTPR)
1826 {
1827 if (pVM->hm.s.fTPRPatchingActive)
1828 {
1829 if ((pCtx->msrLSTAR & 0xff) != u8LastTPR)
1830 {
1831 /* Our patch code uses LSTAR for TPR caching. */
1832 rc2 = PDMApicSetTPR(pVCpu, pCtx->msrLSTAR & 0xff);
1833 AssertRC(rc2);
1834 }
1835 }
1836 else
1837 {
1838 if ((uint8_t)(u8LastTPR >> 4) != pvVMCB->ctrl.IntCtrl.n.u8VTPR)
1839 {
1840 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1841 rc2 = PDMApicSetTPR(pVCpu, pvVMCB->ctrl.IntCtrl.n.u8VTPR << 4);
1842 AssertRC(rc2);
1843 }
1844 }
1845 }
1846
1847#ifdef DBGFTRACE_ENABLED /** @todo DTrace */
1848 RTTraceBufAddMsgF(pVM->CTX_SUFF(hTraceBuf), "vmexit %08x at %04:%08RX64 %RX64 %RX64 %RX64",
1849 exitCode, pCtx->cs.Sel, pCtx->rip,
1850 pvVMCB->ctrl.u64ExitInfo1, pvVMCB->ctrl.u64ExitInfo2, pvVMCB->ctrl.ExitIntInfo.au64[0]);
1851#endif
1852#if ARCH_BITS == 64 /* for the time being */
1853 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, exitCode, pvVMCB->ctrl.u64ExitInfo1, pvVMCB->ctrl.u64ExitInfo2,
1854 pvVMCB->ctrl.ExitIntInfo.au64[0], UINT64_MAX);
1855#endif
1856 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
1857
1858 /* Deal with the reason of the VM-exit. */
1859 switch (exitCode)
1860 {
1861 case SVM_EXIT_EXCEPTION_0: case SVM_EXIT_EXCEPTION_1: case SVM_EXIT_EXCEPTION_2: case SVM_EXIT_EXCEPTION_3:
1862 case SVM_EXIT_EXCEPTION_4: case SVM_EXIT_EXCEPTION_5: case SVM_EXIT_EXCEPTION_6: case SVM_EXIT_EXCEPTION_7:
1863 case SVM_EXIT_EXCEPTION_8: case SVM_EXIT_EXCEPTION_9: case SVM_EXIT_EXCEPTION_A: case SVM_EXIT_EXCEPTION_B:
1864 case SVM_EXIT_EXCEPTION_C: case SVM_EXIT_EXCEPTION_D: case SVM_EXIT_EXCEPTION_E: case SVM_EXIT_EXCEPTION_F:
1865 case SVM_EXIT_EXCEPTION_10: case SVM_EXIT_EXCEPTION_11: case SVM_EXIT_EXCEPTION_12: case SVM_EXIT_EXCEPTION_13:
1866 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16: case SVM_EXIT_EXCEPTION_17:
1867 case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19: case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B:
1868 case SVM_EXIT_EXCEPTION_1C: case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
1869 {
1870 /* Pending trap. */
1871 SVM_EVENT Event;
1872 uint32_t vector = exitCode - SVM_EXIT_EXCEPTION_0;
1873
1874 Log2(("Hardware/software interrupt %d\n", vector));
1875 switch (vector)
1876 {
1877 case X86_XCPT_DB:
1878 {
1879 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
1880
1881 /* Note that we don't support guest and host-initiated debugging at the same time. */
1882 Assert(DBGFIsStepping(pVCpu) || CPUMIsHyperDebugStateActive(pVCpu));
1883
1884 rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pCtx->dr[6]);
1885 if (rc == VINF_EM_RAW_GUEST_TRAP)
1886 {
1887 Log(("Trap %x (debug) at %016RX64\n", vector, pCtx->rip));
1888
1889 /* Reinject the exception. */
1890 Event.au64[0] = 0;
1891 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
1892 Event.n.u1Valid = 1;
1893 Event.n.u8Vector = X86_XCPT_DB;
1894
1895 hmR0SvmSetPendingEvent(pVCpu, &Event);
1896 goto ResumeExecution;
1897 }
1898 /* Return to ring 3 to deal with the debug exit code. */
1899 Log(("Debugger hardware BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs.Sel, pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1900 break;
1901 }
1902
1903 case X86_XCPT_NM:
1904 {
1905 Log(("#NM fault at %RGv\n", (RTGCPTR)pCtx->rip));
1906
1907 /** @todo don't intercept #NM exceptions anymore when we've activated the guest FPU state. */
1908 /* If we sync the FPU/XMM state on-demand, then we can continue execution as if nothing has happened. */
1909 rc = CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
1910 if (rc == VINF_SUCCESS)
1911 {
1912 Assert(CPUMIsGuestFPUStateActive(pVCpu));
1913 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
1914
1915 /* Continue execution. */
1916 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
1917
1918 goto ResumeExecution;
1919 }
1920
1921 Log(("Forward #NM fault to the guest\n"));
1922 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
1923
1924 Event.au64[0] = 0;
1925 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1926 Event.n.u1Valid = 1;
1927 Event.n.u8Vector = X86_XCPT_NM;
1928
1929 hmR0SvmSetPendingEvent(pVCpu, &Event);
1930 goto ResumeExecution;
1931 }
1932
1933 case X86_XCPT_PF: /* Page fault */
1934 {
1935 uint32_t errCode = pvVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
1936 RTGCUINTPTR uFaultAddress = pvVMCB->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
1937
1938#ifdef VBOX_ALWAYS_TRAP_PF
1939 if (pVM->hm.s.fNestedPaging)
1940 {
1941 /*
1942 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
1943 */
1944 Log(("Guest page fault at %04X:%RGv cr2=%RGv error code %x rsp=%RGv\n", pCtx->cs, (RTGCPTR)pCtx->rip,
1945 uFaultAddress, errCode, (RTGCPTR)pCtx->rsp));
1946 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
1947
1948 /* Now we must update CR2. */
1949 pCtx->cr2 = uFaultAddress;
1950
1951 Event.au64[0] = 0;
1952 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1953 Event.n.u1Valid = 1;
1954 Event.n.u8Vector = X86_XCPT_PF;
1955 Event.n.u1ErrorCodeValid = 1;
1956 Event.n.u32ErrorCode = errCode;
1957
1958 hmR0SvmSetPendingEvent(pVCpu, &Event);
1959 goto ResumeExecution;
1960 }
1961#endif
1962 Assert(!pVM->hm.s.fNestedPaging);
1963
1964#ifdef VBOX_HM_WITH_GUEST_PATCHING
1965 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
1966 if ( pVM->hm.s.fTRPPatchingAllowed
1967 && (uFaultAddress & 0xfff) == 0x080
1968 && !(errCode & X86_TRAP_PF_P) /* not present */
1969 && CPUMGetGuestCPL(pVCpu) == 0
1970 && !CPUMIsGuestInLongModeEx(pCtx)
1971 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
1972 {
1973 RTGCPHYS GCPhysApicBase, GCPhys;
1974 GCPhysApicBase = pCtx->msrApicBase;
1975 GCPhysApicBase &= PAGE_BASE_GC_MASK;
1976
1977 rc = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL, &GCPhys);
1978 if ( rc == VINF_SUCCESS
1979 && GCPhys == GCPhysApicBase)
1980 {
1981 /* Only attempt to patch the instruction once. */
1982 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
1983 if (!pPatch)
1984 {
1985 rc = VINF_EM_HM_PATCH_TPR_INSTR;
1986 break;
1987 }
1988 }
1989 }
1990#endif
1991
1992 Log2(("Page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
1993 /* Exit qualification contains the linear address of the page fault. */
1994 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
1995 TRPMSetErrorCode(pVCpu, errCode);
1996 TRPMSetFaultAddress(pVCpu, uFaultAddress);
1997
1998 /* Forward it to our trap handler first, in case our shadow pages are out of sync. */
1999 rc = PGMTrap0eHandler(pVCpu, errCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
2000 Log2(("PGMTrap0eHandler %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
2001 if (rc == VINF_SUCCESS)
2002 {
2003 /* We've successfully synced our shadow pages, so let's just continue execution. */
2004 Log2(("Shadow page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
2005 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
2006
2007 TRPMResetTrap(pVCpu);
2008 goto ResumeExecution;
2009 }
2010 else if (rc == VINF_EM_RAW_GUEST_TRAP)
2011 {
2012 /*
2013 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
2014 */
2015 Log2(("Forward page fault to the guest\n"));
2016 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
2017 /* The error code might have been changed. */
2018 errCode = TRPMGetErrorCode(pVCpu);
2019
2020 TRPMResetTrap(pVCpu);
2021
2022 /* Now we must update CR2. */
2023 pCtx->cr2 = uFaultAddress;
2024
2025 Event.au64[0] = 0;
2026 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2027 Event.n.u1Valid = 1;
2028 Event.n.u8Vector = X86_XCPT_PF;
2029 Event.n.u1ErrorCodeValid = 1;
2030 Event.n.u32ErrorCode = errCode;
2031
2032 hmR0SvmSetPendingEvent(pVCpu, &Event);
2033 goto ResumeExecution;
2034 }
2035#ifdef VBOX_STRICT
2036 if (rc != VINF_EM_RAW_EMULATE_INSTR && rc != VINF_EM_RAW_EMULATE_IO_BLOCK)
2037 LogFlow(("PGMTrap0eHandler failed with %d\n", VBOXSTRICTRC_VAL(rc)));
2038#endif
2039 /* Need to go back to the recompiler to emulate the instruction. */
2040 TRPMResetTrap(pVCpu);
2041 break;
2042 }
2043
2044 case X86_XCPT_MF: /* Floating point exception. */
2045 {
2046 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
2047 if (!(pCtx->cr0 & X86_CR0_NE))
2048 {
2049 /* old style FPU error reporting needs some extra work. */
2050 /** @todo don't fall back to the recompiler, but do it manually. */
2051 rc = VINF_EM_RAW_EMULATE_INSTR;
2052 break;
2053 }
2054 Log(("Trap %x at %RGv\n", vector, (RTGCPTR)pCtx->rip));
2055
2056 Event.au64[0] = 0;
2057 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2058 Event.n.u1Valid = 1;
2059 Event.n.u8Vector = X86_XCPT_MF;
2060
2061 hmR0SvmSetPendingEvent(pVCpu, &Event);
2062 goto ResumeExecution;
2063 }
2064
2065#ifdef VBOX_STRICT
2066 case X86_XCPT_BP: /* Breakpoint. */
2067 case X86_XCPT_GP: /* General protection failure exception.*/
2068 case X86_XCPT_UD: /* Unknown opcode exception. */
2069 case X86_XCPT_DE: /* Divide error. */
2070 case X86_XCPT_SS: /* Stack segment exception. */
2071 case X86_XCPT_NP: /* Segment not present exception. */
2072 {
2073 Event.au64[0] = 0;
2074 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2075 Event.n.u1Valid = 1;
2076 Event.n.u8Vector = vector;
2077
2078 switch (vector)
2079 {
2080 case X86_XCPT_GP:
2081 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
2082 Event.n.u1ErrorCodeValid = 1;
2083 Event.n.u32ErrorCode = pvVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2084 break;
2085 case X86_XCPT_BP:
2086 /** Saves the wrong EIP on the stack (pointing to the int3 instead of the next instruction. */
2087 break;
2088 case X86_XCPT_DE:
2089 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
2090 break;
2091 case X86_XCPT_UD:
2092 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
2093 break;
2094 case X86_XCPT_SS:
2095 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
2096 Event.n.u1ErrorCodeValid = 1;
2097 Event.n.u32ErrorCode = pvVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2098 break;
2099 case X86_XCPT_NP:
2100 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
2101 Event.n.u1ErrorCodeValid = 1;
2102 Event.n.u32ErrorCode = pvVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2103 break;
2104 }
2105 Log(("Trap %x at %04x:%RGv esi=%x\n", vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip, pCtx->esi));
2106 hmR0SvmSetPendingEvent(pVCpu, &Event);
2107 goto ResumeExecution;
2108 }
2109#endif
2110 default:
2111 AssertMsgFailed(("Unexpected vm-exit caused by exception %x\n", vector));
2112 rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
2113 break;
2114
2115 } /* switch (vector) */
2116 break;
2117 }
2118
2119 case SVM_EXIT_NPF:
2120 {
2121 /* EXITINFO1 contains fault errorcode; EXITINFO2 contains the guest physical address causing the fault. */
2122 uint32_t errCode = pvVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2123 RTGCPHYS GCPhysFault = pvVMCB->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
2124 PGMMODE enmShwPagingMode;
2125
2126 Assert(pVM->hm.s.fNestedPaging);
2127 LogFlow(("Nested page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2128
2129#ifdef VBOX_HM_WITH_GUEST_PATCHING
2130 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
2131 if ( pVM->hm.s.fTRPPatchingAllowed
2132 && (GCPhysFault & PAGE_OFFSET_MASK) == 0x080
2133 && ( !(errCode & X86_TRAP_PF_P) /* not present */
2134 || (errCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD) /* mmio optimization */)
2135 && CPUMGetGuestCPL(pVCpu) == 0
2136 && !CPUMIsGuestInLongModeEx(pCtx)
2137 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
2138 {
2139 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
2140 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2141
2142 if (GCPhysFault == GCPhysApicBase + 0x80)
2143 {
2144 /* Only attempt to patch the instruction once. */
2145 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2146 if (!pPatch)
2147 {
2148 rc = VINF_EM_HM_PATCH_TPR_INSTR;
2149 break;
2150 }
2151 }
2152 }
2153#endif
2154
2155 /* Handle the pagefault trap for the nested shadow table. */
2156#if HC_ARCH_BITS == 32 /** @todo shadow this in a variable. */
2157 if (CPUMIsGuestInLongModeEx(pCtx))
2158 enmShwPagingMode = PGMMODE_AMD64_NX;
2159 else
2160#endif
2161 enmShwPagingMode = PGMGetHostMode(pVM);
2162
2163 /* MMIO optimization */
2164 Assert((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
2165 if ((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
2166 {
2167 rc = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmShwPagingMode, CPUMCTX2CORE(pCtx), GCPhysFault, errCode);
2168
2169 /*
2170 * If we succeed, resume execution.
2171 * Or, if fail in interpreting the instruction because we couldn't get the guest physical address
2172 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
2173 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
2174 * weird case. See @bugref{6043}.
2175 */
2176 if ( rc == VINF_SUCCESS
2177 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2178 || rc == VERR_PAGE_NOT_PRESENT)
2179 {
2180 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2181 goto ResumeExecution;
2182 }
2183 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2184 break;
2185 }
2186
2187 /* Exit qualification contains the linear address of the page fault. */
2188 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
2189 TRPMSetErrorCode(pVCpu, errCode);
2190 TRPMSetFaultAddress(pVCpu, GCPhysFault);
2191
2192 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmShwPagingMode, errCode, CPUMCTX2CORE(pCtx), GCPhysFault);
2193 Log2(("PGMR0Trap0eHandlerNestedPaging %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
2194
2195 /*
2196 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
2197 */
2198 if ( rc == VINF_SUCCESS
2199 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2200 || rc == VERR_PAGE_NOT_PRESENT)
2201 {
2202 /* We've successfully synced our shadow pages, so let's just continue execution. */
2203 Log2(("Shadow page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2204 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
2205
2206 TRPMResetTrap(pVCpu);
2207 goto ResumeExecution;
2208 }
2209
2210#ifdef VBOX_STRICT
2211 if (rc != VINF_EM_RAW_EMULATE_INSTR)
2212 LogFlow(("PGMTrap0eHandlerNestedPaging failed with %d\n", VBOXSTRICTRC_VAL(rc)));
2213#endif
2214 /* Need to go back to the recompiler to emulate the instruction. */
2215 TRPMResetTrap(pVCpu);
2216 break;
2217 }
2218
2219 case SVM_EXIT_VINTR:
2220 /* A virtual interrupt is about to be delivered, which means IF=1. */
2221 Log(("SVM_EXIT_VINTR IF=%d\n", pCtx->eflags.Bits.u1IF));
2222 pvVMCB->ctrl.IntCtrl.n.u1VIrqValid = 0;
2223 pvVMCB->ctrl.IntCtrl.n.u8VIrqVector = 0;
2224 goto ResumeExecution;
2225
2226 case SVM_EXIT_FERR_FREEZE:
2227 case SVM_EXIT_INTR:
2228 case SVM_EXIT_NMI:
2229 case SVM_EXIT_SMI:
2230 case SVM_EXIT_INIT:
2231 /* External interrupt; leave to allow it to be dispatched again. */
2232 rc = VINF_EM_RAW_INTERRUPT;
2233 break;
2234
2235 case SVM_EXIT_WBINVD:
2236 case SVM_EXIT_INVD: /* Guest software attempted to execute INVD. */
2237 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
2238 /* Skip instruction and continue directly. */
2239 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2240 /* Continue execution.*/
2241 goto ResumeExecution;
2242
2243 case SVM_EXIT_CPUID: /* Guest software attempted to execute CPUID. */
2244 {
2245 Log2(("SVM: Cpuid at %RGv for %x\n", (RTGCPTR)pCtx->rip, pCtx->eax));
2246 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
2247 rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2248 if (rc == VINF_SUCCESS)
2249 {
2250 /* Update EIP and continue execution. */
2251 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2252 goto ResumeExecution;
2253 }
2254 AssertMsgFailed(("EMU: cpuid failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2255 rc = VINF_EM_RAW_EMULATE_INSTR;
2256 break;
2257 }
2258
2259 case SVM_EXIT_RDTSC: /* Guest software attempted to execute RDTSC. */
2260 {
2261 Log2(("SVM: Rdtsc\n"));
2262 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
2263 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2264 if (rc == VINF_SUCCESS)
2265 {
2266 /* Update EIP and continue execution. */
2267 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2268 goto ResumeExecution;
2269 }
2270 rc = VINF_EM_RAW_EMULATE_INSTR;
2271 break;
2272 }
2273
2274 case SVM_EXIT_RDPMC: /* Guest software attempted to execute RDPMC. */
2275 {
2276 Log2(("SVM: Rdpmc %x\n", pCtx->ecx));
2277 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
2278 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2279 if (rc == VINF_SUCCESS)
2280 {
2281 /* Update EIP and continue execution. */
2282 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2283 goto ResumeExecution;
2284 }
2285 rc = VINF_EM_RAW_EMULATE_INSTR;
2286 break;
2287 }
2288
2289 case SVM_EXIT_RDTSCP: /* Guest software attempted to execute RDTSCP. */
2290 {
2291 Log2(("SVM: Rdtscp\n"));
2292 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
2293 rc = EMInterpretRdtscp(pVM, pVCpu, pCtx);
2294 if (rc == VINF_SUCCESS)
2295 {
2296 /* Update EIP and continue execution. */
2297 pCtx->rip += 3; /* Note! hardcoded opcode size! */
2298 goto ResumeExecution;
2299 }
2300 AssertMsgFailed(("EMU: rdtscp failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2301 rc = VINF_EM_RAW_EMULATE_INSTR;
2302 break;
2303 }
2304
2305 case SVM_EXIT_INVLPG: /* Guest software attempted to execute INVLPG. */
2306 {
2307 Log2(("SVM: invlpg\n"));
2308 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
2309
2310 Assert(!pVM->hm.s.fNestedPaging);
2311
2312 /* Truly a pita. Why can't SVM give the same information as VT-x? */
2313 rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2314 if (rc == VINF_SUCCESS)
2315 {
2316 goto ResumeExecution; /* eip already updated */
2317 }
2318 break;
2319 }
2320
2321 case SVM_EXIT_WRITE_CR0: case SVM_EXIT_WRITE_CR1: case SVM_EXIT_WRITE_CR2: case SVM_EXIT_WRITE_CR3:
2322 case SVM_EXIT_WRITE_CR4: case SVM_EXIT_WRITE_CR5: case SVM_EXIT_WRITE_CR6: case SVM_EXIT_WRITE_CR7:
2323 case SVM_EXIT_WRITE_CR8: case SVM_EXIT_WRITE_CR9: case SVM_EXIT_WRITE_CR10: case SVM_EXIT_WRITE_CR11:
2324 case SVM_EXIT_WRITE_CR12: case SVM_EXIT_WRITE_CR13: case SVM_EXIT_WRITE_CR14: case SVM_EXIT_WRITE_CR15:
2325 {
2326 Log2(("SVM: %RGv mov cr%d, \n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_CR0));
2327 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxWrite[exitCode - SVM_EXIT_WRITE_CR0]);
2328 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2329
2330 switch (exitCode - SVM_EXIT_WRITE_CR0)
2331 {
2332 case 0:
2333 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
2334 break;
2335 case 2:
2336 break;
2337 case 3:
2338 Assert(!pVM->hm.s.fNestedPaging);
2339 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
2340 break;
2341 case 4:
2342 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
2343 break;
2344 case 8:
2345 break;
2346 default:
2347 AssertFailed();
2348 }
2349 if (rc == VINF_SUCCESS)
2350 {
2351 /* EIP has been updated already. */
2352 /* Only resume if successful. */
2353 goto ResumeExecution;
2354 }
2355 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2356 break;
2357 }
2358
2359 case SVM_EXIT_READ_CR0: case SVM_EXIT_READ_CR1: case SVM_EXIT_READ_CR2: case SVM_EXIT_READ_CR3:
2360 case SVM_EXIT_READ_CR4: case SVM_EXIT_READ_CR5: case SVM_EXIT_READ_CR6: case SVM_EXIT_READ_CR7:
2361 case SVM_EXIT_READ_CR8: case SVM_EXIT_READ_CR9: case SVM_EXIT_READ_CR10: case SVM_EXIT_READ_CR11:
2362 case SVM_EXIT_READ_CR12: case SVM_EXIT_READ_CR13: case SVM_EXIT_READ_CR14: case SVM_EXIT_READ_CR15:
2363 {
2364 Log2(("SVM: %RGv mov x, cr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_CR0));
2365 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[exitCode - SVM_EXIT_READ_CR0]);
2366 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2367 if (rc == VINF_SUCCESS)
2368 {
2369 /* EIP has been updated already. */
2370 /* Only resume if successful. */
2371 goto ResumeExecution;
2372 }
2373 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2374 break;
2375 }
2376
2377 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2378 case SVM_EXIT_WRITE_DR4: case SVM_EXIT_WRITE_DR5: case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7:
2379 case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9: case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11:
2380 case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13: case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
2381 {
2382 Log2(("SVM: %RGv mov dr%d, x\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_DR0));
2383 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
2384
2385 if ( !DBGFIsStepping(pVCpu)
2386 && !CPUMIsHyperDebugStateActive(pVCpu))
2387 {
2388 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
2389
2390 /* Disable drx move intercepts. */
2391 pvVMCB->ctrl.u16InterceptRdDRx = 0;
2392 pvVMCB->ctrl.u16InterceptWrDRx = 0;
2393
2394 /* Save the host and load the guest debug state. */
2395 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2396 AssertRC(rc2);
2397 goto ResumeExecution;
2398 }
2399
2400 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2401 if (rc == VINF_SUCCESS)
2402 {
2403 /* EIP has been updated already. */
2404 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
2405
2406 /* Only resume if successful. */
2407 goto ResumeExecution;
2408 }
2409 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2410 break;
2411 }
2412
2413 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2414 case SVM_EXIT_READ_DR4: case SVM_EXIT_READ_DR5: case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7:
2415 case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9: case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11:
2416 case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13: case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2417 {
2418 Log2(("SVM: %RGv mov x, dr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_DR0));
2419 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
2420
2421 if (!DBGFIsStepping(pVCpu))
2422 {
2423 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
2424
2425 /* Disable DRx move intercepts. */
2426 pvVMCB->ctrl.u16InterceptRdDRx = 0;
2427 pvVMCB->ctrl.u16InterceptWrDRx = 0;
2428
2429 /* Save the host and load the guest debug state. */
2430 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2431 AssertRC(rc2);
2432 goto ResumeExecution;
2433 }
2434
2435 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2436 if (rc == VINF_SUCCESS)
2437 {
2438 /* EIP has been updated already. */
2439 /* Only resume if successful. */
2440 goto ResumeExecution;
2441 }
2442 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2443 break;
2444 }
2445
2446 /* Note: We'll get a #GP if the IO instruction isn't allowed (IOPL or TSS bitmap); no need to double check. */
2447 case SVM_EXIT_IOIO: /* I/O instruction. */
2448 {
2449 SVM_IOIO_EXIT IoExitInfo;
2450
2451 IoExitInfo.au32[0] = pvVMCB->ctrl.u64ExitInfo1;
2452 unsigned uIdx = (IoExitInfo.au32[0] >> 4) & 0x7;
2453 uint32_t uIOSize = g_aIOSize[uIdx];
2454 uint32_t uAndVal = g_aIOOpAnd[uIdx];
2455 if (RT_UNLIKELY(!uIOSize))
2456 {
2457 AssertFailed(); /* should be fatal. */
2458 rc = VINF_EM_RAW_EMULATE_INSTR; /** @todo r=ramshankar: would this really fall back to the recompiler and work? */
2459 break;
2460 }
2461
2462 if (IoExitInfo.n.u1STR)
2463 {
2464 /* ins/outs */
2465 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2466
2467 /* Disassemble manually to deal with segment prefixes. */
2468 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
2469 if (rc == VINF_SUCCESS)
2470 {
2471 if (IoExitInfo.n.u1Type == 0)
2472 {
2473 Log2(("IOMInterpretOUTSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2474 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
2475 rc = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2476 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2477 }
2478 else
2479 {
2480 Log2(("IOMInterpretINSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2481 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
2482 rc = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2483 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2484 }
2485 }
2486 else
2487 rc = VINF_EM_RAW_EMULATE_INSTR;
2488 }
2489 else
2490 {
2491 /* Normal in/out */
2492 Assert(!IoExitInfo.n.u1REP);
2493
2494 if (IoExitInfo.n.u1Type == 0)
2495 {
2496 Log2(("IOMIOPortWrite %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, pCtx->eax & uAndVal,
2497 uIOSize));
2498 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
2499 rc = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
2500 if (rc == VINF_IOM_R3_IOPORT_WRITE)
2501 {
2502 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pvVMCB->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2503 uAndVal, uIOSize);
2504 }
2505 }
2506 else
2507 {
2508 uint32_t u32Val = 0;
2509
2510 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
2511 rc = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, uIOSize);
2512 if (IOM_SUCCESS(rc))
2513 {
2514 /* Write back to the EAX register. */
2515 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
2516 Log2(("IOMIOPortRead %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, u32Val & uAndVal,
2517 uIOSize));
2518 }
2519 else if (rc == VINF_IOM_R3_IOPORT_READ)
2520 {
2521 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pvVMCB->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2522 uAndVal, uIOSize);
2523 }
2524 }
2525 }
2526
2527 /*
2528 * Handled the I/O return codes.
2529 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
2530 */
2531 if (IOM_SUCCESS(rc))
2532 {
2533 /* Update EIP and continue execution. */
2534 pCtx->rip = pvVMCB->ctrl.u64ExitInfo2; /* RIP/EIP of the next instruction is saved in EXITINFO2. */
2535 if (RT_LIKELY(rc == VINF_SUCCESS))
2536 {
2537 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
2538 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
2539 {
2540 /* IO operation lookup arrays. */
2541 static uint32_t const aIOSize[4] = { 1, 2, 0, 4 };
2542
2543 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
2544 for (unsigned i = 0; i < 4; i++)
2545 {
2546 unsigned uBPLen = aIOSize[X86_DR7_GET_LEN(pCtx->dr[7], i)];
2547
2548 if ( (IoExitInfo.n.u16Port >= pCtx->dr[i] && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen)
2549 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
2550 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
2551 {
2552 SVM_EVENT Event;
2553
2554 Assert(CPUMIsGuestDebugStateActive(pVCpu));
2555
2556 /* Clear all breakpoint status flags and set the one we just hit. */
2557 pCtx->dr[6] &= ~(X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3);
2558 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
2559
2560 /*
2561 * Note: AMD64 Architecture Programmer's Manual 13.1:
2562 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
2563 * by software after the contents have been read.
2564 */
2565 pvVMCB->guest.u64DR6 = pCtx->dr[6];
2566
2567 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
2568 pCtx->dr[7] &= ~X86_DR7_GD;
2569
2570 /* Paranoia. */
2571 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
2572 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
2573 pCtx->dr[7] |= 0x400; /* must be one */
2574
2575 pvVMCB->guest.u64DR7 = pCtx->dr[7];
2576
2577 /* Inject the exception. */
2578 Log(("Inject IO debug trap at %RGv\n", (RTGCPTR)pCtx->rip));
2579
2580 Event.au64[0] = 0;
2581 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
2582 Event.n.u1Valid = 1;
2583 Event.n.u8Vector = X86_XCPT_DB;
2584
2585 hmR0SvmSetPendingEvent(pVCpu, &Event);
2586 goto ResumeExecution;
2587 }
2588 }
2589 }
2590 goto ResumeExecution;
2591 }
2592 Log2(("EM status from IO at %RGv %x size %d: %Rrc\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize,
2593 VBOXSTRICTRC_VAL(rc)));
2594 break;
2595 }
2596
2597#ifdef VBOX_STRICT
2598 if (rc == VINF_IOM_R3_IOPORT_READ)
2599 Assert(IoExitInfo.n.u1Type != 0);
2600 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
2601 Assert(IoExitInfo.n.u1Type == 0);
2602 else
2603 {
2604 AssertMsg( RT_FAILURE(rc)
2605 || rc == VINF_EM_RAW_EMULATE_INSTR
2606 || rc == VINF_EM_RAW_GUEST_TRAP
2607 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rc)));
2608 }
2609#endif
2610 Log2(("Failed IO at %RGv %x size %d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2611 break;
2612 }
2613
2614 case SVM_EXIT_HLT:
2615 /* Check if external interrupts are pending; if so, don't switch back. */
2616 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
2617 pCtx->rip++; /* skip hlt */
2618 if (EMShouldContinueAfterHalt(pVCpu, pCtx))
2619 goto ResumeExecution;
2620
2621 rc = VINF_EM_HALT;
2622 break;
2623
2624 case SVM_EXIT_MWAIT_UNCOND:
2625 Log2(("SVM: mwait\n"));
2626 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
2627 rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2628 if ( rc == VINF_EM_HALT
2629 || rc == VINF_SUCCESS)
2630 {
2631 /* Update EIP and continue execution. */
2632 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2633
2634 /* Check if external interrupts are pending; if so, don't switch back. */
2635 if ( rc == VINF_SUCCESS
2636 || ( rc == VINF_EM_HALT
2637 && EMShouldContinueAfterHalt(pVCpu, pCtx))
2638 )
2639 goto ResumeExecution;
2640 }
2641 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_EM_HALT, ("EMU: mwait failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2642 break;
2643
2644 case SVM_EXIT_MONITOR:
2645 {
2646 Log2(("SVM: monitor\n"));
2647
2648 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
2649 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2650 if (rc == VINF_SUCCESS)
2651 {
2652 /* Update EIP and continue execution. */
2653 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2654 goto ResumeExecution;
2655 }
2656 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: monitor failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2657 break;
2658 }
2659
2660 case SVM_EXIT_VMMCALL:
2661 rc = hmR0SvmEmulateTprVMMCall(pVM, pVCpu, pCtx);
2662 if (rc == VINF_SUCCESS)
2663 {
2664 goto ResumeExecution; /* rip already updated. */
2665 }
2666 /* no break */
2667
2668 case SVM_EXIT_RSM:
2669 case SVM_EXIT_INVLPGA:
2670 case SVM_EXIT_VMRUN:
2671 case SVM_EXIT_VMLOAD:
2672 case SVM_EXIT_VMSAVE:
2673 case SVM_EXIT_STGI:
2674 case SVM_EXIT_CLGI:
2675 case SVM_EXIT_SKINIT:
2676 {
2677 /* Unsupported instructions. */
2678 SVM_EVENT Event;
2679
2680 Event.au64[0] = 0;
2681 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2682 Event.n.u1Valid = 1;
2683 Event.n.u8Vector = X86_XCPT_UD;
2684
2685 Log(("Forced #UD trap at %RGv\n", (RTGCPTR)pCtx->rip));
2686 hmR0SvmSetPendingEvent(pVCpu, &Event);
2687 goto ResumeExecution;
2688 }
2689
2690 /* Emulate in ring-3. */
2691 case SVM_EXIT_MSR:
2692 {
2693 /* When an interrupt is pending, we'll let MSR_K8_LSTAR writes fault in our TPR patch code. */
2694 if ( pVM->hm.s.fTPRPatchingActive
2695 && pCtx->ecx == MSR_K8_LSTAR
2696 && pvVMCB->ctrl.u64ExitInfo1 == 1 /* wrmsr */)
2697 {
2698 if ((pCtx->eax & 0xff) != u8LastTPR)
2699 {
2700 Log(("SVM: Faulting MSR_K8_LSTAR write with new TPR value %x\n", pCtx->eax & 0xff));
2701
2702 /* Our patch code uses LSTAR for TPR caching. */
2703 rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
2704 AssertRC(rc2);
2705 }
2706
2707 /* Skip the instruction and continue. */
2708 pCtx->rip += 2; /* wrmsr = [0F 30] */
2709
2710 /* Only resume if successful. */
2711 goto ResumeExecution;
2712 }
2713
2714 /*
2715 * The Intel spec. claims there's an REX version of RDMSR that's slightly different,
2716 * so we play safe by completely disassembling the instruction.
2717 */
2718 STAM_COUNTER_INC((pvVMCB->ctrl.u64ExitInfo1 == 0) ? &pVCpu->hm.s.StatExitRdmsr : &pVCpu->hm.s.StatExitWrmsr);
2719 Log(("SVM: %s\n", (pvVMCB->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr"));
2720 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2721 if (rc == VINF_SUCCESS)
2722 {
2723 /* EIP has been updated already. */
2724 /* Only resume if successful. */
2725 goto ResumeExecution;
2726 }
2727 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: %s failed with %Rrc\n", (pvVMCB->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr",
2728 VBOXSTRICTRC_VAL(rc)));
2729 break;
2730 }
2731
2732 case SVM_EXIT_TASK_SWITCH: /* too complicated to emulate, so fall back to the recompiler */
2733 Log(("SVM_EXIT_TASK_SWITCH: exit2=%RX64\n", pvVMCB->ctrl.u64ExitInfo2));
2734 if ( !(pvVMCB->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
2735 && pVCpu->hm.s.Event.fPending)
2736 {
2737 SVM_EVENT Event;
2738 Event.au64[0] = pVCpu->hm.s.Event.u64IntrInfo;
2739
2740 /* Caused by an injected interrupt. */
2741 pVCpu->hm.s.Event.fPending = false;
2742 switch (Event.n.u3Type)
2743 {
2744 case SVM_EVENT_EXTERNAL_IRQ:
2745 case SVM_EVENT_NMI:
2746 Log(("SVM_EXIT_TASK_SWITCH: reassert trap %d\n", Event.n.u8Vector));
2747 Assert(!Event.n.u1ErrorCodeValid);
2748 rc2 = TRPMAssertTrap(pVCpu, Event.n.u8Vector, TRPM_HARDWARE_INT);
2749 AssertRC(rc2);
2750 break;
2751
2752 default:
2753 /* Exceptions and software interrupts can just be restarted. */
2754 break;
2755 }
2756 }
2757 rc = VERR_EM_INTERPRETER;
2758 break;
2759
2760 case SVM_EXIT_PAUSE:
2761 case SVM_EXIT_MWAIT_ARMED:
2762 rc = VERR_EM_INTERPRETER;
2763 break;
2764
2765 case SVM_EXIT_SHUTDOWN:
2766 rc = VINF_EM_RESET; /* Triple fault equals a reset. */
2767 break;
2768
2769 case SVM_EXIT_IDTR_READ:
2770 case SVM_EXIT_GDTR_READ:
2771 case SVM_EXIT_LDTR_READ:
2772 case SVM_EXIT_TR_READ:
2773 case SVM_EXIT_IDTR_WRITE:
2774 case SVM_EXIT_GDTR_WRITE:
2775 case SVM_EXIT_LDTR_WRITE:
2776 case SVM_EXIT_TR_WRITE:
2777 case SVM_EXIT_CR0_SEL_WRITE:
2778 default:
2779 /* Unexpected exit codes. */
2780 rc = VERR_SVM_UNEXPECTED_EXIT;
2781 AssertMsgFailed(("Unexpected exit code %x\n", exitCode)); /* Can't happen. */
2782 break;
2783 }
2784
2785end:
2786
2787 /*
2788 * We are now going back to ring-3, so clear the forced action flag.
2789 */
2790 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2791
2792 /*
2793 * Signal changes to the recompiler.
2794 */
2795 CPUMSetChangedFlags(pVCpu,
2796 CPUM_CHANGED_SYSENTER_MSR
2797 | CPUM_CHANGED_LDTR
2798 | CPUM_CHANGED_GDTR
2799 | CPUM_CHANGED_IDTR
2800 | CPUM_CHANGED_TR
2801 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2802
2803 /*
2804 * If we executed vmrun and an external IRQ was pending, then we don't have to do a full sync the next time.
2805 */
2806 if (exitCode == SVM_EXIT_INTR)
2807 {
2808 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2809 /* On the next entry we'll only sync the host context. */
2810 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
2811 }
2812 else
2813 {
2814 /* On the next entry we'll sync everything. */
2815 /** @todo we can do better than this */
2816 /* Not in the VINF_PGM_CHANGE_MODE though! */
2817 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_ALL;
2818 }
2819
2820 /* Translate into a less severe return code */
2821 if (rc == VERR_EM_INTERPRETER)
2822 rc = VINF_EM_RAW_EMULATE_INSTR;
2823
2824 /* Just set the correct state here instead of trying to catch every goto above. */
2825 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
2826
2827#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2828 /* Restore interrupts if we exitted after disabling them. */
2829 if (uOldEFlags != ~(RTCCUINTREG)0)
2830 ASMSetFlags(uOldEFlags);
2831#endif
2832
2833 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
2834 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
2835 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
2836 return VBOXSTRICTRC_TODO(rc);
2837}
2838
2839
2840/**
2841 * Emulate simple mov tpr instruction.
2842 *
2843 * @returns VBox status code.
2844 * @param pVM Pointer to the VM.
2845 * @param pVCpu Pointer to the VMCPU.
2846 * @param pCtx Pointer to the guest CPU context.
2847 */
2848static int hmR0SvmEmulateTprVMMCall(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2849{
2850 int rc;
2851
2852 LogFlow(("Emulated VMMCall TPR access replacement at %RGv\n", pCtx->rip));
2853
2854 for (;;)
2855 {
2856 bool fPending;
2857 uint8_t u8Tpr;
2858
2859 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2860 if (!pPatch)
2861 break;
2862
2863 switch (pPatch->enmType)
2864 {
2865 case HMTPRINSTR_READ:
2866 /* TPR caching in CR8 */
2867 rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
2868 AssertRC(rc);
2869
2870 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
2871 AssertRC(rc);
2872
2873 LogFlow(("Emulated read successfully\n"));
2874 pCtx->rip += pPatch->cbOp;
2875 break;
2876
2877 case HMTPRINSTR_WRITE_REG:
2878 case HMTPRINSTR_WRITE_IMM:
2879 /* Fetch the new TPR value */
2880 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
2881 {
2882 uint32_t val;
2883
2884 rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &val);
2885 AssertRC(rc);
2886 u8Tpr = val;
2887 }
2888 else
2889 u8Tpr = (uint8_t)pPatch->uSrcOperand;
2890
2891 rc = PDMApicSetTPR(pVCpu, u8Tpr);
2892 AssertRC(rc);
2893 LogFlow(("Emulated write successfully\n"));
2894 pCtx->rip += pPatch->cbOp;
2895 break;
2896
2897 default:
2898 AssertMsgFailedReturn(("Unexpected type %d\n", pPatch->enmType), VERR_SVM_UNEXPECTED_PATCH_TYPE);
2899 }
2900 }
2901 return VINF_SUCCESS;
2902}
2903
2904
2905/**
2906 * Enters the AMD-V session.
2907 *
2908 * @returns VBox status code.
2909 * @param pVM Pointer to the VM.
2910 * @param pVCpu Pointer to the VMCPU.
2911 * @param pCpu Pointer to the CPU info struct.
2912 */
2913VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
2914{
2915 Assert(pVM->hm.s.svm.fSupported);
2916
2917 LogFlow(("SVMR0Enter cpu%d last=%d asid=%d\n", pCpu->idCpu, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.uCurrentAsid));
2918 pVCpu->hm.s.fResumeVM = false;
2919
2920 /* Force to reload LDTR, so we'll execute VMLoad to load additional guest state. */
2921 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_LDTR;
2922
2923 return VINF_SUCCESS;
2924}
2925
2926
2927/**
2928 * Leaves the AMD-V session.
2929 *
2930 * @returns VBox status code.
2931 * @param pVM Pointer to the VM.
2932 * @param pVCpu Pointer to the VMCPU.
2933 * @param pCtx Pointer to the guest CPU context.
2934 */
2935VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2936{
2937 SVM_VMCB *pvVMCB = (SVM_VMCB *)pVCpu->hm.s.svm.pvVMCB;
2938
2939 Assert(pVM->hm.s.svm.fSupported);
2940
2941#ifdef DEBUG
2942 if (CPUMIsHyperDebugStateActive(pVCpu))
2943 {
2944 CPUMR0LoadHostDebugState(pVM, pVCpu);
2945 }
2946 else
2947#endif
2948 /* Save the guest debug state if necessary. */
2949 if (CPUMIsGuestDebugStateActive(pVCpu))
2950 {
2951 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, false /* skip DR6 */);
2952
2953 /* Intercept all DRx reads and writes again. Changed later on. */
2954 pvVMCB->ctrl.u16InterceptRdDRx = 0xFFFF;
2955 pvVMCB->ctrl.u16InterceptWrDRx = 0xFFFF;
2956
2957 /* Resync the debug registers the next time. */
2958 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
2959 }
2960 else
2961 Assert(pvVMCB->ctrl.u16InterceptRdDRx == 0xFFFF && pvVMCB->ctrl.u16InterceptWrDRx == 0xFFFF);
2962
2963 return VINF_SUCCESS;
2964}
2965
2966
2967/**
2968 * Worker for Interprets INVLPG.
2969 *
2970 * @return VBox status code.
2971 * @param pVCpu Pointer to the VMCPU.
2972 * @param pCpu Pointer to the CPU info struct.
2973 * @param pRegFrame Pointer to the register frame.
2974 */
2975static int hmR0svmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
2976{
2977 DISQPVPARAMVAL param1;
2978 RTGCPTR addr;
2979
2980 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &param1, DISQPVWHICH_SRC);
2981 if (RT_FAILURE(rc))
2982 return VERR_EM_INTERPRETER;
2983
2984 switch (param1.type)
2985 {
2986 case DISQPV_TYPE_IMMEDIATE:
2987 case DISQPV_TYPE_ADDRESS:
2988 if (!(param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
2989 return VERR_EM_INTERPRETER;
2990 addr = param1.val.val64;
2991 break;
2992
2993 default:
2994 return VERR_EM_INTERPRETER;
2995 }
2996
2997 /** @todo is addr always a flat linear address or ds based
2998 * (in absence of segment override prefixes)????
2999 */
3000 rc = PGMInvalidatePage(pVCpu, addr);
3001 if (RT_SUCCESS(rc))
3002 return VINF_SUCCESS;
3003
3004 AssertRC(rc);
3005 return rc;
3006}
3007
3008
3009/**
3010 * Interprets INVLPG.
3011 *
3012 * @returns VBox status code.
3013 * @retval VINF_* Scheduling instructions.
3014 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3015 * @retval VERR_* Fatal errors.
3016 *
3017 * @param pVM Pointer to the VM.
3018 * @param pRegFrame Pointer to the register frame.
3019 *
3020 * @remarks Updates the EIP if an instruction was executed successfully.
3021 */
3022static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
3023{
3024 /*
3025 * Only allow 32 & 64 bit code.
3026 */
3027 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3028 {
3029 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3030 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
3031 if (RT_SUCCESS(rc) && pDis->pCurInstr->uOpcode == OP_INVLPG)
3032 {
3033 rc = hmR0svmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
3034 if (RT_SUCCESS(rc))
3035 pRegFrame->rip += pDis->cbInstr; /* Move on to the next instruction. */
3036 return rc;
3037 }
3038 }
3039 return VERR_EM_INTERPRETER;
3040}
3041
3042
3043/**
3044 * Invalidates a guest page by guest virtual address.
3045 *
3046 * @returns VBox status code.
3047 * @param pVM Pointer to the VM.
3048 * @param pVCpu Pointer to the VMCPU.
3049 * @param GCVirt Guest virtual address of the page to invalidate.
3050 */
3051VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
3052{
3053 bool fFlushPending = pVM->hm.s.svm.fAlwaysFlushTLB | VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
3054
3055 /* Skip it if a TLB flush is already pending. */
3056 if (!fFlushPending)
3057 {
3058 SVM_VMCB *pvVMCB;
3059
3060 Log2(("SVMR0InvalidatePage %RGv\n", GCVirt));
3061 AssertReturn(pVM, VERR_INVALID_PARAMETER);
3062 Assert(pVM->hm.s.svm.fSupported);
3063
3064 pvVMCB = (SVM_VMCB *)pVCpu->hm.s.svm.pvVMCB;
3065 AssertMsgReturn(pvVMCB, ("Invalid pvVMCB\n"), VERR_SVM_INVALID_PVMCB);
3066
3067#if HC_ARCH_BITS == 32
3068 /* If we get a flush in 64 bits guest mode, then force a full TLB flush. Invlpga takes only 32 bits addresses. */
3069 if (CPUMIsGuestInLongMode(pVCpu))
3070 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3071 else
3072#endif
3073 {
3074 SVMR0InvlpgA(GCVirt, pvVMCB->ctrl.TLBCtrl.n.u32ASID);
3075 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
3076 }
3077 }
3078 return VINF_SUCCESS;
3079}
3080
3081
3082#if 0 /* obsolete, but left here for clarification. */
3083/**
3084 * Invalidates a guest page by physical address.
3085 *
3086 * @returns VBox status code.
3087 * @param pVM Pointer to the VM.
3088 * @param pVCpu Pointer to the VMCPU.
3089 * @param GCPhys Guest physical address of the page to invalidate.
3090 */
3091VMMR0DECL(int) SVMR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
3092{
3093 Assert(pVM->hm.s.fNestedPaging);
3094 /* invlpga only invalidates TLB entries for guest virtual addresses; we have no choice but to force a TLB flush here. */
3095 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3096 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgPhys);
3097 return VINF_SUCCESS;
3098}
3099#endif
3100
3101
3102#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
3103/**
3104 * Prepares for and executes VMRUN (64-bit guests from a 32-bit host).
3105 *
3106 * @returns VBox status code.
3107 * @param HCPhysVMCBHost Physical address of host VMCB.
3108 * @param HCPhysVMCB Physical address of the VMCB.
3109 * @param pCtx Pointer to the guest CPU context.
3110 * @param pVM Pointer to the VM.
3111 * @param pVCpu Pointer to the VMCPU.
3112 */
3113DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVMCBHost, RTHCPHYS HCPhysVMCB, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
3114{
3115 uint32_t aParam[4];
3116
3117 aParam[0] = (uint32_t)(HCPhysVMCBHost); /* Param 1: HCPhysVMCBHost - Lo. */
3118 aParam[1] = (uint32_t)(HCPhysVMCBHost >> 32); /* Param 1: HCPhysVMCBHost - Hi. */
3119 aParam[2] = (uint32_t)(HCPhysVMCB); /* Param 2: HCPhysVMCB - Lo. */
3120 aParam[3] = (uint32_t)(HCPhysVMCB >> 32); /* Param 2: HCPhysVMCB - Hi. */
3121
3122 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_SVMRCVMRun64, 4, &aParam[0]);
3123}
3124
3125
3126/**
3127 * Executes the specified handler in 64-bit mode.
3128 *
3129 * @returns VBox status code.
3130 * @param pVM Pointer to the VM.
3131 * @param pVCpu Pointer to the VMCPU.
3132 * @param pCtx Pointer to the guest CPU context.
3133 * @param enmOp The operation to perform.
3134 * @param cbParam Number of parameters.
3135 * @param paParam Array of 32-bit parameters.
3136 */
3137VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp, uint32_t cbParam,
3138 uint32_t *paParam)
3139{
3140 int rc;
3141 RTHCUINTREG uOldEFlags;
3142
3143 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
3144 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
3145
3146 /* Disable interrupts. */
3147 uOldEFlags = ASMIntDisableFlags();
3148
3149#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
3150 RTCPUID idHostCpu = RTMpCpuId();
3151 CPUMR0SetLApic(pVM, idHostCpu);
3152#endif
3153
3154 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
3155 CPUMSetHyperEIP(pVCpu, enmOp);
3156 for (int i = (int)cbParam - 1; i >= 0; i--)
3157 CPUMPushHyper(pVCpu, paParam[i]);
3158
3159 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
3160 /* Call switcher. */
3161 rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
3162 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
3163
3164 ASMSetFlags(uOldEFlags);
3165 return rc;
3166}
3167
3168#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
3169
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