VirtualBox

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

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

VMM/HMSVMR0: AMD-V bits.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 123.0 KB
Line 
1/* $Id: HWSVMR0.cpp 46444 2013-06-07 17:02:46Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2006-2013 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 pVmcb->guest.REG.u16Sel = pCtx->reg.Sel; \
73 pVmcb->guest.REG.u32Limit = pCtx->reg.u32Limit; \
74 pVmcb->guest.REG.u64Base = pCtx->reg.u64Base; \
75 pVmcb->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 = pVmcb->guest.REG.u16Sel; \
82 pCtx->reg.ValidSel = pVmcb->guest.REG.u16Sel; \
83 pCtx->reg.fFlags = CPUMSELREG_FLAGS_VALID; \
84 pCtx->reg.u32Limit = pVmcb->guest.REG.u32Limit; \
85 pCtx->reg.u64Base = pVmcb->guest.REG.u64Base; \
86 pCtx->reg.Attr.u = SVM_HIDSEGATTR_SVM2VMX(pVmcb->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 PSVMVMCB pVmcb = (PSVMVMCB)pVM->aCpus[i].hm.s.svm.pvVmcb;
337
338 AssertMsgReturn(pVmcb, ("Invalid pVmcb\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 pVmcb->ctrl.u16InterceptRdCRx = RT_BIT(0) | RT_BIT(4);
346
347 /* CR0/4 writes must be intercepted for obvious reasons. */
348 pVmcb->ctrl.u16InterceptWrCRx = RT_BIT(0) | RT_BIT(4);
349
350 /* Intercept all DRx reads and writes by default. Changed later on. */
351 pVmcb->ctrl.u16InterceptRdDRx = 0xFFFF;
352 pVmcb->ctrl.u16InterceptWrDRx = 0xFFFF;
353
354 /* Intercept traps; only #NM is always intercepted. */
355 pVmcb->ctrl.u32InterceptException = RT_BIT(X86_XCPT_NM);
356#ifdef VBOX_ALWAYS_TRAP_PF
357 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
358#endif
359#ifdef VBOX_STRICT
360 pVmcb->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 pVmcb->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 pVmcb->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(("pVmcb->ctrl.u32InterceptException = %x\n", pVmcb->ctrl.u32InterceptException));
400 Log(("pVmcb->ctrl.u32InterceptCtrl1 = %x\n", pVmcb->ctrl.u32InterceptCtrl1));
401 Log(("pVmcb->ctrl.u32InterceptCtrl2 = %x\n", pVmcb->ctrl.u32InterceptCtrl2));
402
403 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
404 pVmcb->ctrl.IntCtrl.n.u1VIrqMasking = 1;
405
406 /* Ignore the priority in the TPR; just deliver it when we tell it to. */
407 pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR = 1;
408
409 /* Set IO and MSR bitmap addresses. */
410 pVmcb->ctrl.u64IOPMPhysAddr = pVM->hm.s.svm.HCPhysIOBitmap;
411 pVmcb->ctrl.u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
412
413 /* No LBR virtualization. */
414 pVmcb->ctrl.u64LBRVirt = 0;
415
416 /* The ASID must start at 1; the host uses 0. */
417 pVmcb->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 pVmcb->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 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(3);
431 pVmcb->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 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_INVLPG
439 | SVM_CTRL1_INTERCEPT_TASK_SWITCH;
440
441 /* Page faults must be intercepted to implement shadow paging. */
442 pVmcb->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, SVMEVENT *pEvent)
524{
525#ifdef VBOX_STRICT
526 Log(("SVM: Set pending event: intInfo=%016llx\n", pEvent->u));
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->u;
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 pVmcb 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, PSVMVMCB pVmcb, CPUMCTX *pCtx, SVMEVENT *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->u));
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_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
563 Assert(pCtx->eflags.u32 & X86_EFL_IF);
564 }
565#endif
566
567 /* Set event injection state. */
568 pVmcb->ctrl.EventInject.u = pEvent->u;
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 pVmcb Pointer to the VMCB.
579 * @param pCtx Pointer to the guest CPU Context.
580 */
581static int hmR0SvmCheckPendingInterrupt(PVM pVM, PVMCPU pVCpu, PSVMVMCB pVmcb, 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 SVMEVENT 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.u = pVCpu->hm.s.Event.u64IntrInfo;
597 hmR0SvmInjectEvent(pVCpu, pVmcb, 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_TEST_AND_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI))
609 {
610 SVMEVENT 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, pVmcb, 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_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)))
628 {
629 if ( !(pCtx->eflags.u32 & X86_EFL_IF)
630 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
631 {
632 if (!pVmcb->ctrl.IntCtrl.n.u1VIrqValid)
633 {
634 if (!VMCPU_FF_IS_SET(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 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
645 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1;
646 pVmcb->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_IS_PENDING(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_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
682 && TRPMHasTrap(pVCpu)
683 )
684 {
685 uint8_t u8Vector;
686 TRPMEVENT enmType;
687 SVMEVENT Event;
688 RTGCUINT u32ErrorCode;
689
690 Event.u = 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, pVmcb, 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 PSVMVMCB pVmcb;
769
770 if (pVM == NULL)
771 return VERR_INVALID_PARAMETER;
772
773 /* Setup AMD SVM. */
774 Assert(pVM->hm.s.svm.fSupported);
775
776 pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
777 AssertMsgReturn(pVmcb, ("Invalid pVmcb\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 pVmcb->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
806 pVmcb->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 pVmcb->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
813 pVmcb->guest.IDTR.u64Base = pCtx->idtr.pIdt;
814 }
815
816 /*
817 * Sysenter MSRs (unconditional)
818 */
819 pVmcb->guest.u64SysEnterCS = pCtx->SysEnter.cs;
820 pVmcb->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
821 pVmcb->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 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_MF);
841 }
842 val |= X86_CR0_NE; /* always turn on the native mechanism to report FPU errors (old style uses interrupts) */
843 }
844 /* Always enable caching. */
845 val &= ~(X86_CR0_CD|X86_CR0_NW);
846
847 /*
848 * Note: WP is not relevant in nested paging mode as we catch accesses on the (guest) physical level.
849 * Note: In nested paging mode, the guest is allowed to run with paging disabled; the guest-physical to host-physical
850 * translation will remain active.
851 */
852 if (!pVM->hm.s.fNestedPaging)
853 {
854 val |= X86_CR0_PG; /* Paging is always enabled; even when the guest is running in real mode or PE without paging. */
855 val |= X86_CR0_WP; /* Must set this as we rely on protecting various pages and supervisor writes must be caught. */
856 }
857 pVmcb->guest.u64CR0 = val;
858 }
859 /* CR2 as well */
860 pVmcb->guest.u64CR2 = pCtx->cr2;
861
862 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR3)
863 {
864 /* Save our shadow CR3 register. */
865 if (pVM->hm.s.fNestedPaging)
866 {
867 PGMMODE enmShwPagingMode;
868
869#if HC_ARCH_BITS == 32
870 if (CPUMIsGuestInLongModeEx(pCtx))
871 enmShwPagingMode = PGMMODE_AMD64_NX;
872 else
873#endif
874 enmShwPagingMode = PGMGetHostMode(pVM);
875
876 pVmcb->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
877 Assert(pVmcb->ctrl.u64NestedPagingCR3);
878 pVmcb->guest.u64CR3 = pCtx->cr3;
879 }
880 else
881 {
882 pVmcb->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
883 Assert(pVmcb->guest.u64CR3 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
884 }
885 }
886
887 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR4)
888 {
889 val = pCtx->cr4;
890 if (!pVM->hm.s.fNestedPaging)
891 {
892 switch (pVCpu->hm.s.enmShadowMode)
893 {
894 case PGMMODE_REAL:
895 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
896 AssertFailed();
897 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
898
899 case PGMMODE_32_BIT: /* 32-bit paging. */
900 val &= ~X86_CR4_PAE;
901 break;
902
903 case PGMMODE_PAE: /* PAE paging. */
904 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
905 /** Must use PAE paging as we could use physical memory > 4 GB */
906 val |= X86_CR4_PAE;
907 break;
908
909 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
910 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
911#ifdef VBOX_ENABLE_64_BITS_GUESTS
912 break;
913#else
914 AssertFailed();
915 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
916#endif
917
918 default: /* shut up gcc */
919 AssertFailed();
920 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
921 }
922 }
923 pVmcb->guest.u64CR4 = val;
924 }
925
926 /* Debug registers. */
927 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_DEBUG)
928 {
929 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* set all reserved bits to 1. */
930 pCtx->dr[6] &= ~RT_BIT(12); /* must be zero. */
931
932 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
933 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
934 pCtx->dr[7] |= 0x400; /* must be one */
935
936 pVmcb->guest.u64DR7 = pCtx->dr[7];
937 pVmcb->guest.u64DR6 = pCtx->dr[6];
938
939#ifdef DEBUG
940 /* Sync the hypervisor debug state now if any breakpoint is armed. */
941 if ( CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK|X86_DR7_GD)
942 && !CPUMIsHyperDebugStateActive(pVCpu)
943 && !DBGFIsStepping(pVCpu))
944 {
945 /* Save the host and load the hypervisor debug state. */
946 int rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
947 AssertRC(rc);
948
949 /* DRx intercepts remain enabled. */
950
951 /* Override dr6 & dr7 with the hypervisor values. */
952 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
953 pVmcb->guest.u64DR6 = CPUMGetHyperDR6(pVCpu);
954 }
955 else
956#endif
957 /* Sync the debug state now if any breakpoint is armed. */
958 if ( (pCtx->dr[7] & (X86_DR7_ENABLED_MASK|X86_DR7_GD))
959 && !CPUMIsGuestDebugStateActive(pVCpu)
960 && !DBGFIsStepping(pVCpu))
961 {
962 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
963
964 /* Disable drx move intercepts. */
965 pVmcb->ctrl.u16InterceptRdDRx = 0;
966 pVmcb->ctrl.u16InterceptWrDRx = 0;
967
968 /* Save the host and load the guest debug state. */
969 int rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
970 AssertRC(rc);
971 }
972 }
973
974 /* EIP, ESP and EFLAGS */
975 pVmcb->guest.u64RIP = pCtx->rip;
976 pVmcb->guest.u64RSP = pCtx->rsp;
977 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
978
979 /* Set CPL */
980 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
981
982 /* RAX/EAX too, as VMRUN uses RAX as an implicit parameter. */
983 pVmcb->guest.u64RAX = pCtx->rax;
984
985 /* vmrun will fail without MSR_K6_EFER_SVME. */
986 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
987
988 /* 64 bits guest mode? */
989 if (CPUMIsGuestInLongModeEx(pCtx))
990 {
991#if !defined(VBOX_ENABLE_64_BITS_GUESTS)
992 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
993#elif HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
994 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
995#else
996# ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
997 if (!pVM->hm.s.fAllow64BitGuests)
998 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
999# endif
1000 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1001#endif
1002 /* Unconditionally update these as wrmsr might have changed them. (HM_CHANGED_GUEST_SEGMENT_REGS will not be set) */
1003 pVmcb->guest.FS.u64Base = pCtx->fs.u64Base;
1004 pVmcb->guest.GS.u64Base = pCtx->gs.u64Base;
1005 }
1006 else
1007 {
1008 /* Filter out the MSR_K6_LME bit or else AMD-V expects amd64 shadow paging. */
1009 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1010
1011 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1012 }
1013
1014 /* TSC offset. */
1015 if (TMCpuTickCanUseRealTSC(pVCpu, &pVmcb->ctrl.u64TSCOffset))
1016 {
1017 uint64_t u64CurTSC = ASMReadTSC();
1018 if (u64CurTSC + pVmcb->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
1019 {
1020 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
1021 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
1022 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
1023 }
1024 else
1025 {
1026 /* Fall back to rdtsc emulation as we would otherwise pass decreasing tsc values to the guest. */
1027 LogFlow(("TSC %RX64 offset %RX64 time=%RX64 last=%RX64 (diff=%RX64, virt_tsc=%RX64)\n", u64CurTSC,
1028 pVmcb->ctrl.u64TSCOffset, u64CurTSC + pVmcb->ctrl.u64TSCOffset, TMCpuTickGetLastSeen(pVCpu),
1029 TMCpuTickGetLastSeen(pVCpu) - u64CurTSC - pVmcb->ctrl.u64TSCOffset, TMCpuTickGet(pVCpu)));
1030 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1031 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1032 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
1033 }
1034 }
1035 else
1036 {
1037 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1038 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1039 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
1040 }
1041
1042 /* Sync the various MSRs for 64-bit mode. */
1043 pVmcb->guest.u64STAR = pCtx->msrSTAR; /* legacy syscall eip, cs & ss */
1044 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR; /* 64-bit mode syscall rip */
1045 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR; /* compatibility mode syscall rip */
1046 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK; /* syscall flag mask */
1047 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE; /* SWAPGS exchange value */
1048
1049#ifdef DEBUG
1050 /* Intercept X86_XCPT_DB if stepping is enabled */
1051 if ( DBGFIsStepping(pVCpu)
1052 || CPUMIsHyperDebugStateActive(pVCpu))
1053 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_DB);
1054 else
1055 pVmcb->ctrl.u32InterceptException &= ~RT_BIT(X86_XCPT_DB);
1056#endif
1057
1058 /* Done. */
1059 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_ALL_GUEST;
1060
1061 return VINF_SUCCESS;
1062}
1063
1064
1065/**
1066 * Setup TLB for ASID.
1067 *
1068 * @param pVM Pointer to the VM.
1069 * @param pVCpu Pointer to the VMCPU.
1070 */
1071static void hmR0SvmSetupTLB(PVM pVM, PVMCPU pVCpu)
1072{
1073 PHMGLOBLCPUINFO pCpu;
1074
1075 AssertPtr(pVM);
1076 AssertPtr(pVCpu);
1077
1078 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1079 pCpu = HMR0GetCurrentCpu();
1080
1081 /*
1082 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
1083 * This can happen both for start & resume due to long jumps back to ring-3.
1084 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
1085 * so we cannot reuse the ASIDs without flushing.
1086 */
1087 bool fNewAsid = false;
1088 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
1089 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
1090 {
1091 pVCpu->hm.s.fForceTLBFlush = true;
1092 fNewAsid = true;
1093 }
1094
1095 /*
1096 * Set TLB flush state as checked until we return from the world switch.
1097 */
1098 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
1099
1100 /*
1101 * Check for TLB shootdown flushes.
1102 */
1103 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
1104 pVCpu->hm.s.fForceTLBFlush = true;
1105
1106 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
1107 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
1108
1109 if (RT_UNLIKELY(pVM->hm.s.svm.fAlwaysFlushTLB))
1110 {
1111 /*
1112 * This is the AMD erratum 170. We need to flush the entire TLB for each world switch. Sad.
1113 */
1114 pCpu->uCurrentAsid = 1;
1115 pVCpu->hm.s.uCurrentAsid = 1;
1116 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1117 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1118 }
1119 else if (pVCpu->hm.s.fForceTLBFlush)
1120 {
1121 if (fNewAsid)
1122 {
1123 ++pCpu->uCurrentAsid;
1124 bool fHitASIDLimit = false;
1125 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
1126 {
1127 pCpu->uCurrentAsid = 1; /* start at 1; host uses 0 */
1128 pCpu->cTlbFlushes++;
1129 fHitASIDLimit = true;
1130
1131 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1132 {
1133 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1134 pCpu->fFlushAsidBeforeUse = true;
1135 }
1136 else
1137 {
1138 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1139 pCpu->fFlushAsidBeforeUse = false;
1140 }
1141 }
1142
1143 if ( !fHitASIDLimit
1144 && pCpu->fFlushAsidBeforeUse)
1145 {
1146 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1147 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1148 else
1149 {
1150 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1151 pCpu->fFlushAsidBeforeUse = false;
1152 }
1153 }
1154
1155 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
1156 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1157 }
1158 else
1159 {
1160 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1161 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1162 else
1163 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1164 }
1165
1166 pVCpu->hm.s.fForceTLBFlush = false;
1167 }
1168 else
1169 {
1170 /** @todo We never set VMCPU_FF_TLB_SHOOTDOWN anywhere so this path should
1171 * not be executed. See hmQueueInvlPage() where it is commented
1172 * out. Support individual entry flushing someday. */
1173 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
1174 {
1175 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
1176 STAM_COUNTER_INC(&pVCpu->hm.s.StatTlbShootdown);
1177 for (uint32_t i = 0; i < pVCpu->hm.s.TlbShootdown.cPages; i++)
1178 SVMR0InvlpgA(pVCpu->hm.s.TlbShootdown.aPages[i], pVmcb->ctrl.TLBCtrl.n.u32ASID);
1179 }
1180 }
1181
1182 pVCpu->hm.s.TlbShootdown.cPages = 0;
1183 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
1184
1185 /* Update VMCB with the ASID. */
1186 pVmcb->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
1187
1188 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
1189 ("Flush count mismatch for cpu %d (%x vs %x)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
1190 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
1191 ("cpu%d uCurrentAsid = %x\n", pCpu->idCpu, pCpu->uCurrentAsid));
1192 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
1193 ("cpu%d VM uCurrentAsid = %x\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
1194
1195#ifdef VBOX_WITH_STATISTICS
1196 if (pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
1197 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
1198 else if ( pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
1199 || pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
1200 {
1201 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
1202 }
1203 else
1204 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
1205#endif
1206}
1207
1208
1209/**
1210 * Runs guest code in an AMD-V VM.
1211 *
1212 * @returns VBox status code.
1213 * @param pVM Pointer to the VM.
1214 * @param pVCpu Pointer to the VMCPU.
1215 * @param pCtx Pointer to the guest CPU context.
1216 */
1217VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1218{
1219 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
1220 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
1221 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
1222
1223 VBOXSTRICTRC rc = VINF_SUCCESS;
1224 int rc2;
1225 uint64_t exitCode = (uint64_t)SVM_EXIT_INVALID;
1226 PSVMVMCB pVmcb = NULL;
1227 bool fSyncTPR = false;
1228 unsigned cResume = 0;
1229 uint8_t u8LastTPR = 0; /* Initialized for potentially stupid compilers. */
1230 uint32_t u32HostExtFeatures = 0;
1231 PHMGLOBLCPUINFO pCpu = 0;
1232 RTCCUINTREG uOldEFlags = ~(RTCCUINTREG)0;
1233#ifdef VBOX_STRICT
1234 RTCPUID idCpuCheck;
1235#endif
1236#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1237 uint64_t u64LastTime = RTTimeMilliTS();
1238#endif
1239
1240 pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1241 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1242
1243 /*
1244 * We can jump to this point to resume execution after determining that a VM-exit is innocent.
1245 */
1246ResumeExecution:
1247 if (!STAM_PROFILE_ADV_IS_RUNNING(&pVCpu->hm.s.StatEntry))
1248 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit2, &pVCpu->hm.s.StatEntry, x);
1249 Assert(!HMR0SuspendPending());
1250
1251 /*
1252 * Safety precaution; looping for too long here can have a very bad effect on the host.
1253 */
1254 if (RT_UNLIKELY(++cResume > pVM->hm.s.cMaxResumeLoops))
1255 {
1256 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
1257 rc = VINF_EM_RAW_INTERRUPT;
1258 goto end;
1259 }
1260
1261 /*
1262 * Check for IRQ inhibition due to instruction fusing (sti, mov ss).
1263 */
1264 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1265 {
1266 Log(("VM_FF_INHIBIT_INTERRUPTS at %RGv successor %RGv\n", (RTGCPTR)pCtx->rip, EMGetInhibitInterruptsPC(pVCpu)));
1267 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
1268 {
1269 /*
1270 * Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here.
1271 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
1272 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
1273 * break the guest. Sounds very unlikely, but such timing sensitive problems are not as rare as you might think.
1274 */
1275 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1276 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1277 pVmcb->ctrl.u64IntShadow = 0;
1278 }
1279 }
1280 else
1281 {
1282 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1283 pVmcb->ctrl.u64IntShadow = 0;
1284 }
1285
1286#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1287 if (RT_UNLIKELY((cResume & 0xf) == 0))
1288 {
1289 uint64_t u64CurTime = RTTimeMilliTS();
1290
1291 if (RT_UNLIKELY(u64CurTime > u64LastTime))
1292 {
1293 u64LastTime = u64CurTime;
1294 TMTimerPollVoid(pVM, pVCpu);
1295 }
1296 }
1297#endif
1298
1299 /*
1300 * Check for pending actions that force us to go back to ring-3.
1301 */
1302 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK | VM_FF_REQUEST | VM_FF_PGM_POOL_FLUSH_PENDING | VM_FF_PDM_DMA)
1303 || VMCPU_FF_IS_PENDING(pVCpu,
1304 VMCPU_FF_HM_TO_R3_MASK
1305 | VMCPU_FF_PGM_SYNC_CR3
1306 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
1307 | VMCPU_FF_REQUEST))
1308 {
1309 /* Check if a sync operation is pending. */
1310 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
1311 {
1312 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
1313 AssertRC(VBOXSTRICTRC_VAL(rc));
1314 if (rc != VINF_SUCCESS)
1315 {
1316 Log(("Pending pool sync is forcing us back to ring 3; rc=%d\n", VBOXSTRICTRC_VAL(rc)));
1317 goto end;
1318 }
1319 }
1320
1321#ifdef DEBUG
1322 /* Intercept X86_XCPT_DB if stepping is enabled */
1323 if (!DBGFIsStepping(pVCpu))
1324#endif
1325 {
1326 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
1327 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
1328 {
1329 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
1330 rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
1331 goto end;
1332 }
1333 }
1334
1335 /* Pending request packets might contain actions that need immediate attention, such as pending hardware interrupts. */
1336 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
1337 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
1338 {
1339 rc = VINF_EM_PENDING_REQUEST;
1340 goto end;
1341 }
1342
1343 /* Check if a pgm pool flush is in progress. */
1344 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
1345 {
1346 rc = VINF_PGM_POOL_FLUSH_PENDING;
1347 goto end;
1348 }
1349
1350 /* Check if DMA work is pending (2nd+ run). */
1351 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA) && cResume > 1)
1352 {
1353 rc = VINF_EM_RAW_TO_R3;
1354 goto end;
1355 }
1356 }
1357
1358#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1359 /*
1360 * Exit to ring-3 preemption/work is pending.
1361 *
1362 * Interrupts are disabled before the call to make sure we don't miss any interrupt
1363 * that would flag preemption (IPI, timer tick, ++). (Would've been nice to do this
1364 * further down, but hmR0SvmCheckPendingInterrupt makes that impossible.)
1365 *
1366 * Note! Interrupts must be disabled done *before* we check for TLB flushes; TLB
1367 * shootdowns rely on this.
1368 */
1369 uOldEFlags = ASMIntDisableFlags();
1370 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
1371 {
1372 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
1373 rc = VINF_EM_RAW_INTERRUPT;
1374 goto end;
1375 }
1376 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1377#endif
1378
1379 /*
1380 * When external interrupts are pending, we should exit the VM when IF is set.
1381 * Note: *After* VM_FF_INHIBIT_INTERRUPTS check!!
1382 */
1383 rc = hmR0SvmCheckPendingInterrupt(pVM, pVCpu, pVmcb, pCtx);
1384 if (RT_FAILURE(rc))
1385 goto end;
1386
1387 /*
1388 * TPR caching using CR8 is only available in 64-bit mode or with 32-bit guests when X86_CPUID_AMD_FEATURE_ECX_CR8L is
1389 * supported.
1390 * Note: we can't do this in LoddGuestState as PDMApicGetTPR can jump back to ring 3 (lock)! (no longer true)
1391 */
1392 /** @todo query and update the TPR only when it could have been changed (mmio access)
1393 */
1394 if (pVM->hm.s.fHasIoApic)
1395 {
1396 /* TPR caching in CR8 */
1397 bool fPending;
1398 rc2 = PDMApicGetTPR(pVCpu, &u8LastTPR, &fPending, NULL /* pu8PendingIrq */);
1399 AssertRC(rc2);
1400
1401 if (pVM->hm.s.fTPRPatchingActive)
1402 {
1403 /* Our patch code uses LSTAR for TPR caching. */
1404 pCtx->msrLSTAR = u8LastTPR;
1405
1406 if (fPending)
1407 {
1408 /* A TPR change could activate a pending interrupt, so catch lstar writes. */
1409 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, false);
1410 }
1411 else
1412 {
1413 /*
1414 * No interrupts are pending, so we don't need to be explicitely notified.
1415 * There are enough world switches for detecting pending interrupts.
1416 */
1417 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
1418 }
1419 }
1420 else
1421 {
1422 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1423 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8LastTPR >> 4);
1424
1425 if (fPending)
1426 {
1427 /* A TPR change could activate a pending interrupt, so catch cr8 writes. */
1428 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1429 }
1430 else
1431 {
1432 /*
1433 * No interrupts are pending, so we don't need to be explicitly notified.
1434 * There are enough world switches for detecting pending interrupts.
1435 */
1436 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1437 }
1438 }
1439 fSyncTPR = !fPending;
1440 }
1441
1442 /* All done! Let's start VM execution. */
1443
1444 /* Enable nested paging if necessary (disabled each time after #VMEXIT). */
1445 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
1446
1447#ifdef LOG_ENABLED
1448 pCpu = HMR0GetCurrentCpu();
1449 if (pVCpu->hm.s.idLastCpu != pCpu->idCpu)
1450 LogFlow(("Force TLB flush due to rescheduling to a different cpu (%d vs %d)\n", pVCpu->hm.s.idLastCpu, pCpu->idCpu));
1451 else if (pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
1452 LogFlow(("Force TLB flush due to changed TLB flush count (%x vs %x)\n", pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
1453 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TLB_FLUSH))
1454 LogFlow(("Manual TLB flush\n"));
1455#endif
1456
1457 /*
1458 * NOTE: DO NOT DO ANYTHING AFTER THIS POINT THAT MIGHT JUMP BACK TO RING 3!
1459 * (until the actual world switch)
1460 */
1461#ifdef VBOX_STRICT
1462 idCpuCheck = RTMpCpuId();
1463#endif
1464 VMMR0LogFlushDisable(pVCpu);
1465
1466 /*
1467 * Load the guest state; *must* be here as it sets up the shadow CR0 for lazy FPU syncing!
1468 */
1469 rc = SVMR0LoadGuestState(pVM, pVCpu, pCtx);
1470 if (RT_UNLIKELY(rc != VINF_SUCCESS))
1471 {
1472 VMMR0LogFlushEnable(pVCpu);
1473 goto end;
1474 }
1475
1476#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1477 /*
1478 * Disable interrupts to make sure a poke will interrupt execution.
1479 * This must be done *before* we check for TLB flushes; TLB shootdowns rely on this.
1480 */
1481 uOldEFlags = ASMIntDisableFlags();
1482 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1483#endif
1484 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
1485
1486 /* Setup TLB control and ASID in the VMCB. */
1487 hmR0SvmSetupTLB(pVM, pVCpu);
1488
1489 /* In case we execute a goto ResumeExecution later on. */
1490 pVCpu->hm.s.fResumeVM = true;
1491 pVCpu->hm.s.fForceTLBFlush = pVM->hm.s.svm.fAlwaysFlushTLB;
1492
1493 Assert(sizeof(pVCpu->hm.s.svm.HCPhysVmcb) == 8);
1494 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqMasking);
1495 Assert(pVmcb->ctrl.u64IOPMPhysAddr == pVM->hm.s.svm.HCPhysIOBitmap);
1496 Assert(pVmcb->ctrl.u64MSRPMPhysAddr == pVCpu->hm.s.svm.HCPhysMsrBitmap);
1497 Assert(pVmcb->ctrl.u64LBRVirt == 0);
1498
1499#ifdef VBOX_STRICT
1500 Assert(idCpuCheck == RTMpCpuId());
1501#endif
1502 TMNotifyStartOfExecution(pVCpu);
1503
1504 /*
1505 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
1506 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
1507 */
1508 u32HostExtFeatures = pVM->hm.s.cpuid.u32AMDFeatureEDX;
1509 if ( (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1510 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
1511 {
1512 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
1513 uint64_t u64GuestTscAux = 0;
1514 rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
1515 AssertRC(rc2);
1516 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
1517 }
1518
1519#ifdef VBOX_WITH_KERNEL_USING_XMM
1520 HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
1521 pVCpu->hm.s.svm.pfnVMRun);
1522#else
1523 pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
1524#endif
1525
1526 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false);
1527 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits);
1528 /* Possibly the last TSC value seen by the guest (too high) (only when we're in TSC offset mode). */
1529 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
1530 {
1531 /* Restore host's TSC_AUX. */
1532 if (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1533 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
1534
1535 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() +
1536 pVmcb->ctrl.u64TSCOffset - 0x400 /* guestimate of world switch overhead in clock ticks */);
1537 }
1538
1539 TMNotifyEndOfExecution(pVCpu);
1540 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
1541 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
1542 ASMSetFlags(uOldEFlags);
1543#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1544 uOldEFlags = ~(RTCCUINTREG)0;
1545#endif
1546
1547 /*
1548 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1549 * 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
1550 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1551 */
1552
1553 /* Reason for the VM exit */
1554 exitCode = pVmcb->ctrl.u64ExitCode;
1555
1556 if (RT_UNLIKELY(exitCode == (uint64_t)SVM_EXIT_INVALID)) /* Invalid guest state. */
1557 {
1558 HMDumpRegs(pVM, pVCpu, pCtx);
1559#ifdef DEBUG
1560 Log(("ctrl.u16InterceptRdCRx %x\n", pVmcb->ctrl.u16InterceptRdCRx));
1561 Log(("ctrl.u16InterceptWrCRx %x\n", pVmcb->ctrl.u16InterceptWrCRx));
1562 Log(("ctrl.u16InterceptRdDRx %x\n", pVmcb->ctrl.u16InterceptRdDRx));
1563 Log(("ctrl.u16InterceptWrDRx %x\n", pVmcb->ctrl.u16InterceptWrDRx));
1564 Log(("ctrl.u32InterceptException %x\n", pVmcb->ctrl.u32InterceptException));
1565 Log(("ctrl.u32InterceptCtrl1 %x\n", pVmcb->ctrl.u32InterceptCtrl1));
1566 Log(("ctrl.u32InterceptCtrl2 %x\n", pVmcb->ctrl.u32InterceptCtrl2));
1567 Log(("ctrl.u64IOPMPhysAddr %RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
1568 Log(("ctrl.u64MSRPMPhysAddr %RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
1569 Log(("ctrl.u64TSCOffset %RX64\n", pVmcb->ctrl.u64TSCOffset));
1570
1571 Log(("ctrl.TLBCtrl.u32ASID %x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
1572 Log(("ctrl.TLBCtrl.u8TLBFlush %x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
1573 Log(("ctrl.TLBCtrl.u24Reserved %x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
1574
1575 Log(("ctrl.IntCtrl.u8VTPR %x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
1576 Log(("ctrl.IntCtrl.u1VIrqValid %x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
1577 Log(("ctrl.IntCtrl.u7Reserved %x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
1578 Log(("ctrl.IntCtrl.u4VIrqPriority %x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
1579 Log(("ctrl.IntCtrl.u1IgnoreTPR %x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
1580 Log(("ctrl.IntCtrl.u3Reserved %x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
1581 Log(("ctrl.IntCtrl.u1VIrqMasking %x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
1582 Log(("ctrl.IntCtrl.u6Reserved %x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
1583 Log(("ctrl.IntCtrl.u8VIrqVector %x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
1584 Log(("ctrl.IntCtrl.u24Reserved %x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
1585
1586 Log(("ctrl.u64IntShadow %RX64\n", pVmcb->ctrl.u64IntShadow));
1587 Log(("ctrl.u64ExitCode %RX64\n", pVmcb->ctrl.u64ExitCode));
1588 Log(("ctrl.u64ExitInfo1 %RX64\n", pVmcb->ctrl.u64ExitInfo1));
1589 Log(("ctrl.u64ExitInfo2 %RX64\n", pVmcb->ctrl.u64ExitInfo2));
1590 Log(("ctrl.ExitIntInfo.u8Vector %x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
1591 Log(("ctrl.ExitIntInfo.u3Type %x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
1592 Log(("ctrl.ExitIntInfo.u1ErrorCodeValid %x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
1593 Log(("ctrl.ExitIntInfo.u19Reserved %x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
1594 Log(("ctrl.ExitIntInfo.u1Valid %x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
1595 Log(("ctrl.ExitIntInfo.u32ErrorCode %x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
1596 Log(("ctrl.NestedPaging %RX64\n", pVmcb->ctrl.NestedPaging.u));
1597 Log(("ctrl.EventInject.u8Vector %x\n", pVmcb->ctrl.EventInject.n.u8Vector));
1598 Log(("ctrl.EventInject.u3Type %x\n", pVmcb->ctrl.EventInject.n.u3Type));
1599 Log(("ctrl.EventInject.u1ErrorCodeValid %x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
1600 Log(("ctrl.EventInject.u19Reserved %x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
1601 Log(("ctrl.EventInject.u1Valid %x\n", pVmcb->ctrl.EventInject.n.u1Valid));
1602 Log(("ctrl.EventInject.u32ErrorCode %x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
1603
1604 Log(("ctrl.u64NestedPagingCR3 %RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
1605 Log(("ctrl.u64LBRVirt %RX64\n", pVmcb->ctrl.u64LBRVirt));
1606
1607 Log(("guest.CS.u16Sel %04X\n", pVmcb->guest.CS.u16Sel));
1608 Log(("guest.CS.u16Attr %04X\n", pVmcb->guest.CS.u16Attr));
1609 Log(("guest.CS.u32Limit %X\n", pVmcb->guest.CS.u32Limit));
1610 Log(("guest.CS.u64Base %RX64\n", pVmcb->guest.CS.u64Base));
1611 Log(("guest.DS.u16Sel %04X\n", pVmcb->guest.DS.u16Sel));
1612 Log(("guest.DS.u16Attr %04X\n", pVmcb->guest.DS.u16Attr));
1613 Log(("guest.DS.u32Limit %X\n", pVmcb->guest.DS.u32Limit));
1614 Log(("guest.DS.u64Base %RX64\n", pVmcb->guest.DS.u64Base));
1615 Log(("guest.ES.u16Sel %04X\n", pVmcb->guest.ES.u16Sel));
1616 Log(("guest.ES.u16Attr %04X\n", pVmcb->guest.ES.u16Attr));
1617 Log(("guest.ES.u32Limit %X\n", pVmcb->guest.ES.u32Limit));
1618 Log(("guest.ES.u64Base %RX64\n", pVmcb->guest.ES.u64Base));
1619 Log(("guest.FS.u16Sel %04X\n", pVmcb->guest.FS.u16Sel));
1620 Log(("guest.FS.u16Attr %04X\n", pVmcb->guest.FS.u16Attr));
1621 Log(("guest.FS.u32Limit %X\n", pVmcb->guest.FS.u32Limit));
1622 Log(("guest.FS.u64Base %RX64\n", pVmcb->guest.FS.u64Base));
1623 Log(("guest.GS.u16Sel %04X\n", pVmcb->guest.GS.u16Sel));
1624 Log(("guest.GS.u16Attr %04X\n", pVmcb->guest.GS.u16Attr));
1625 Log(("guest.GS.u32Limit %X\n", pVmcb->guest.GS.u32Limit));
1626 Log(("guest.GS.u64Base %RX64\n", pVmcb->guest.GS.u64Base));
1627
1628 Log(("guest.GDTR.u32Limit %X\n", pVmcb->guest.GDTR.u32Limit));
1629 Log(("guest.GDTR.u64Base %RX64\n", pVmcb->guest.GDTR.u64Base));
1630
1631 Log(("guest.LDTR.u16Sel %04X\n", pVmcb->guest.LDTR.u16Sel));
1632 Log(("guest.LDTR.u16Attr %04X\n", pVmcb->guest.LDTR.u16Attr));
1633 Log(("guest.LDTR.u32Limit %X\n", pVmcb->guest.LDTR.u32Limit));
1634 Log(("guest.LDTR.u64Base %RX64\n", pVmcb->guest.LDTR.u64Base));
1635
1636 Log(("guest.IDTR.u32Limit %X\n", pVmcb->guest.IDTR.u32Limit));
1637 Log(("guest.IDTR.u64Base %RX64\n", pVmcb->guest.IDTR.u64Base));
1638
1639 Log(("guest.TR.u16Sel %04X\n", pVmcb->guest.TR.u16Sel));
1640 Log(("guest.TR.u16Attr %04X\n", pVmcb->guest.TR.u16Attr));
1641 Log(("guest.TR.u32Limit %X\n", pVmcb->guest.TR.u32Limit));
1642 Log(("guest.TR.u64Base %RX64\n", pVmcb->guest.TR.u64Base));
1643
1644 Log(("guest.u8CPL %X\n", pVmcb->guest.u8CPL));
1645 Log(("guest.u64CR0 %RX64\n", pVmcb->guest.u64CR0));
1646 Log(("guest.u64CR2 %RX64\n", pVmcb->guest.u64CR2));
1647 Log(("guest.u64CR3 %RX64\n", pVmcb->guest.u64CR3));
1648 Log(("guest.u64CR4 %RX64\n", pVmcb->guest.u64CR4));
1649 Log(("guest.u64DR6 %RX64\n", pVmcb->guest.u64DR6));
1650 Log(("guest.u64DR7 %RX64\n", pVmcb->guest.u64DR7));
1651
1652 Log(("guest.u64RIP %RX64\n", pVmcb->guest.u64RIP));
1653 Log(("guest.u64RSP %RX64\n", pVmcb->guest.u64RSP));
1654 Log(("guest.u64RAX %RX64\n", pVmcb->guest.u64RAX));
1655 Log(("guest.u64RFlags %RX64\n", pVmcb->guest.u64RFlags));
1656
1657 Log(("guest.u64SysEnterCS %RX64\n", pVmcb->guest.u64SysEnterCS));
1658 Log(("guest.u64SysEnterEIP %RX64\n", pVmcb->guest.u64SysEnterEIP));
1659 Log(("guest.u64SysEnterESP %RX64\n", pVmcb->guest.u64SysEnterESP));
1660
1661 Log(("guest.u64EFER %RX64\n", pVmcb->guest.u64EFER));
1662 Log(("guest.u64STAR %RX64\n", pVmcb->guest.u64STAR));
1663 Log(("guest.u64LSTAR %RX64\n", pVmcb->guest.u64LSTAR));
1664 Log(("guest.u64CSTAR %RX64\n", pVmcb->guest.u64CSTAR));
1665 Log(("guest.u64SFMASK %RX64\n", pVmcb->guest.u64SFMASK));
1666 Log(("guest.u64KernelGSBase %RX64\n", pVmcb->guest.u64KernelGSBase));
1667 Log(("guest.u64GPAT %RX64\n", pVmcb->guest.u64GPAT));
1668 Log(("guest.u64DBGCTL %RX64\n", pVmcb->guest.u64DBGCTL));
1669 Log(("guest.u64BR_FROM %RX64\n", pVmcb->guest.u64BR_FROM));
1670 Log(("guest.u64BR_TO %RX64\n", pVmcb->guest.u64BR_TO));
1671 Log(("guest.u64LASTEXCPFROM %RX64\n", pVmcb->guest.u64LASTEXCPFROM));
1672 Log(("guest.u64LASTEXCPTO %RX64\n", pVmcb->guest.u64LASTEXCPTO));
1673#endif
1674 rc = VERR_SVM_UNABLE_TO_START_VM;
1675 VMMR0LogFlushEnable(pVCpu);
1676 goto end;
1677 }
1678
1679 /* Let's first sync back EIP, ESP, and EFLAGS. */
1680 pCtx->rip = pVmcb->guest.u64RIP;
1681 pCtx->rsp = pVmcb->guest.u64RSP;
1682 pCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1683 /* eax is saved/restore across the vmrun instruction */
1684 pCtx->rax = pVmcb->guest.u64RAX;
1685
1686 /*
1687 * Save all the MSRs that can be changed by the guest without causing a world switch.
1688 * FS & GS base are saved with SVM_READ_SELREG.
1689 */
1690 pCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1691 pCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1692 pCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1693 pCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1694 pCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1695 pCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1696 pCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1697 pCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1698
1699 /* Can be updated behind our back in the nested paging case. */
1700 pCtx->cr2 = pVmcb->guest.u64CR2;
1701
1702 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1703 SVM_READ_SELREG(SS, ss);
1704 SVM_READ_SELREG(CS, cs);
1705 SVM_READ_SELREG(DS, ds);
1706 SVM_READ_SELREG(ES, es);
1707 SVM_READ_SELREG(FS, fs);
1708 SVM_READ_SELREG(GS, gs);
1709
1710 /*
1711 * Correct the hidden CS granularity flag. Haven't seen it being wrong in any other
1712 * register (yet).
1713 */
1714 if ( !pCtx->cs.Attr.n.u1Granularity
1715 && pCtx->cs.Attr.n.u1Present
1716 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
1717 {
1718 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
1719 pCtx->cs.Attr.n.u1Granularity = 1;
1720 }
1721#define SVM_ASSERT_SEL_GRANULARITY(reg) \
1722 AssertMsg( !pCtx->reg.Attr.n.u1Present \
1723 || ( pCtx->reg.Attr.n.u1Granularity \
1724 ? (pCtx->reg.u32Limit & 0xfff) == 0xfff \
1725 : pCtx->reg.u32Limit <= 0xfffff), \
1726 ("%#x %#x %#llx\n", pCtx->reg.u32Limit, pCtx->reg.Attr.u, pCtx->reg.u64Base))
1727 SVM_ASSERT_SEL_GRANULARITY(ss);
1728 SVM_ASSERT_SEL_GRANULARITY(cs);
1729 SVM_ASSERT_SEL_GRANULARITY(ds);
1730 SVM_ASSERT_SEL_GRANULARITY(es);
1731 SVM_ASSERT_SEL_GRANULARITY(fs);
1732 SVM_ASSERT_SEL_GRANULARITY(gs);
1733#undef SVM_ASSERT_SEL_GRANULARITY
1734
1735 /*
1736 * Correct the hidden SS DPL field. It can be wrong on certain CPUs
1737 * sometimes (seen it on AMD Fusion CPUs with 64-bit guests). The CPU
1738 * always uses the CPL field in the VMCB instead of the DPL in the hidden
1739 * SS (chapter AMD spec. 15.5.1 Basic operation).
1740 */
1741 Assert(!(pVmcb->guest.u8CPL & ~0x3));
1742 pCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
1743
1744 /*
1745 * Remaining guest CPU context: TR, IDTR, GDTR, LDTR;
1746 * must sync everything otherwise we can get out of sync when jumping back to ring-3.
1747 */
1748 SVM_READ_SELREG(LDTR, ldtr);
1749 SVM_READ_SELREG(TR, tr);
1750
1751 pCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
1752 pCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
1753
1754 pCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
1755 pCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
1756
1757 /*
1758 * No reason to sync back the CRx and DRx registers as they cannot be changed by the guest
1759 * unless in the nested paging case where CR3 can be changed by the guest.
1760 */
1761 if ( pVM->hm.s.fNestedPaging
1762 && pCtx->cr3 != pVmcb->guest.u64CR3)
1763 {
1764 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
1765 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
1766 }
1767
1768 /* Note! NOW IT'S SAFE FOR LOGGING! */
1769 VMMR0LogFlushEnable(pVCpu);
1770
1771 /* Take care of instruction fusing (sti, mov ss) (see AMD spec. 15.20.5 Interrupt Shadows) */
1772 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1773 {
1774 Log(("uInterruptState %x rip=%RGv\n", pVmcb->ctrl.u64IntShadow, (RTGCPTR)pCtx->rip));
1775 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip);
1776 }
1777 else
1778 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1779
1780 Log2(("exitCode = %x\n", exitCode));
1781
1782 /* Sync back DR6 as it could have been changed by hitting breakpoints. */
1783 pCtx->dr[6] = pVmcb->guest.u64DR6;
1784 /* DR7.GD can be cleared by debug exceptions, so sync it back as well. */
1785 pCtx->dr[7] = pVmcb->guest.u64DR7;
1786
1787 /* Check if an injected event was interrupted prematurely. */
1788 pVCpu->hm.s.Event.u64IntrInfo = pVmcb->ctrl.ExitIntInfo.u;
1789 if ( pVmcb->ctrl.ExitIntInfo.n.u1Valid
1790 /* we don't care about 'int xx' as the instruction will be restarted. */
1791 && pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
1792 {
1793 Log(("Pending inject %RX64 at %RGv exit=%08x\n", pVCpu->hm.s.Event.u64IntrInfo, (RTGCPTR)pCtx->rip, exitCode));
1794
1795#ifdef LOG_ENABLED
1796 SVMEVENT Event;
1797 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
1798
1799 if ( exitCode == SVM_EXIT_EXCEPTION_E
1800 && Event.n.u8Vector == 0xE)
1801 {
1802 Log(("Double fault!\n"));
1803 }
1804#endif
1805
1806 pVCpu->hm.s.Event.fPending = true;
1807 /* Error code present? (redundant) */
1808 if (pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid)
1809 pVCpu->hm.s.Event.u32ErrCode = pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode;
1810 else
1811 pVCpu->hm.s.Event.u32ErrCode = 0;
1812 }
1813#ifdef VBOX_WITH_STATISTICS
1814 if (exitCode == SVM_EXIT_NPF)
1815 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
1816 else
1817 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[exitCode & MASK_EXITREASON_STAT]);
1818#endif
1819
1820 /* Sync back the TPR if it was changed. */
1821 if (fSyncTPR)
1822 {
1823 if (pVM->hm.s.fTPRPatchingActive)
1824 {
1825 if ((pCtx->msrLSTAR & 0xff) != u8LastTPR)
1826 {
1827 /* Our patch code uses LSTAR for TPR caching. */
1828 rc2 = PDMApicSetTPR(pVCpu, pCtx->msrLSTAR & 0xff);
1829 AssertRC(rc2);
1830 }
1831 }
1832 else
1833 {
1834 if ((uint8_t)(u8LastTPR >> 4) != pVmcb->ctrl.IntCtrl.n.u8VTPR)
1835 {
1836 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1837 rc2 = PDMApicSetTPR(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
1838 AssertRC(rc2);
1839 }
1840 }
1841 }
1842
1843#ifdef DBGFTRACE_ENABLED /** @todo DTrace */
1844 RTTraceBufAddMsgF(pVM->CTX_SUFF(hTraceBuf), "vmexit %08x at %04:%08RX64 %RX64 %RX64 %RX64",
1845 exitCode, pCtx->cs.Sel, pCtx->rip,
1846 pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2, pVmcb->ctrl.ExitIntInfo.u);
1847#endif
1848#if ARCH_BITS == 64 /* for the time being */
1849 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, exitCode, pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2,
1850 pVmcb->ctrl.ExitIntInfo.u, UINT64_MAX);
1851#endif
1852 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
1853
1854 /* Deal with the reason of the VM-exit. */
1855 switch (exitCode)
1856 {
1857 case SVM_EXIT_EXCEPTION_0: case SVM_EXIT_EXCEPTION_1: case SVM_EXIT_EXCEPTION_2: case SVM_EXIT_EXCEPTION_3:
1858 case SVM_EXIT_EXCEPTION_4: case SVM_EXIT_EXCEPTION_5: case SVM_EXIT_EXCEPTION_6: case SVM_EXIT_EXCEPTION_7:
1859 case SVM_EXIT_EXCEPTION_8: case SVM_EXIT_EXCEPTION_9: case SVM_EXIT_EXCEPTION_A: case SVM_EXIT_EXCEPTION_B:
1860 case SVM_EXIT_EXCEPTION_C: case SVM_EXIT_EXCEPTION_D: case SVM_EXIT_EXCEPTION_E: case SVM_EXIT_EXCEPTION_F:
1861 case SVM_EXIT_EXCEPTION_10: case SVM_EXIT_EXCEPTION_11: case SVM_EXIT_EXCEPTION_12: case SVM_EXIT_EXCEPTION_13:
1862 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16: case SVM_EXIT_EXCEPTION_17:
1863 case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19: case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B:
1864 case SVM_EXIT_EXCEPTION_1C: case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
1865 {
1866 /* Pending trap. */
1867 SVMEVENT Event;
1868 uint32_t vector = exitCode - SVM_EXIT_EXCEPTION_0;
1869
1870 Log2(("Hardware/software interrupt %d\n", vector));
1871 switch (vector)
1872 {
1873 case X86_XCPT_DB:
1874 {
1875 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
1876
1877 /* Note that we don't support guest and host-initiated debugging at the same time. */
1878 Assert(DBGFIsStepping(pVCpu) || CPUMIsHyperDebugStateActive(pVCpu));
1879
1880 rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pCtx->dr[6]);
1881 if (rc == VINF_EM_RAW_GUEST_TRAP)
1882 {
1883 Log(("Trap %x (debug) at %016RX64\n", vector, pCtx->rip));
1884
1885 /* Reinject the exception. */
1886 Event.u = 0;
1887 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
1888 Event.n.u1Valid = 1;
1889 Event.n.u8Vector = X86_XCPT_DB;
1890
1891 hmR0SvmSetPendingEvent(pVCpu, &Event);
1892 goto ResumeExecution;
1893 }
1894 /* Return to ring 3 to deal with the debug exit code. */
1895 Log(("Debugger hardware BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs.Sel, pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1896 break;
1897 }
1898
1899 case X86_XCPT_NM:
1900 {
1901 Log(("#NM fault at %RGv\n", (RTGCPTR)pCtx->rip));
1902
1903 /** @todo don't intercept #NM exceptions anymore when we've activated the guest FPU state. */
1904 /* If we sync the FPU/XMM state on-demand, then we can continue execution as if nothing has happened. */
1905 rc = CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
1906 if (rc == VINF_SUCCESS)
1907 {
1908 Assert(CPUMIsGuestFPUStateActive(pVCpu));
1909 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
1910
1911 /* Continue execution. */
1912 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
1913
1914 goto ResumeExecution;
1915 }
1916
1917 Log(("Forward #NM fault to the guest\n"));
1918 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
1919
1920 Event.u = 0;
1921 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1922 Event.n.u1Valid = 1;
1923 Event.n.u8Vector = X86_XCPT_NM;
1924
1925 hmR0SvmSetPendingEvent(pVCpu, &Event);
1926 goto ResumeExecution;
1927 }
1928
1929 case X86_XCPT_PF: /* Page fault */
1930 {
1931 uint32_t errCode = pVmcb->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
1932 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
1933
1934#ifdef VBOX_ALWAYS_TRAP_PF
1935 if (pVM->hm.s.fNestedPaging)
1936 {
1937 /*
1938 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
1939 */
1940 Log(("Guest page fault at %04X:%RGv cr2=%RGv error code %x rsp=%RGv\n", pCtx->cs, (RTGCPTR)pCtx->rip,
1941 uFaultAddress, errCode, (RTGCPTR)pCtx->rsp));
1942 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
1943
1944 /* Now we must update CR2. */
1945 pCtx->cr2 = uFaultAddress;
1946
1947 Event.u = 0;
1948 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1949 Event.n.u1Valid = 1;
1950 Event.n.u8Vector = X86_XCPT_PF;
1951 Event.n.u1ErrorCodeValid = 1;
1952 Event.n.u32ErrorCode = errCode;
1953
1954 hmR0SvmSetPendingEvent(pVCpu, &Event);
1955 goto ResumeExecution;
1956 }
1957#endif
1958 Assert(!pVM->hm.s.fNestedPaging);
1959
1960#ifdef VBOX_HM_WITH_GUEST_PATCHING
1961 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
1962 if ( pVM->hm.s.fTRPPatchingAllowed
1963 && (uFaultAddress & 0xfff) == 0x080
1964 && !(errCode & X86_TRAP_PF_P) /* not present */
1965 && CPUMGetGuestCPL(pVCpu) == 0
1966 && !CPUMIsGuestInLongModeEx(pCtx)
1967 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
1968 {
1969 RTGCPHYS GCPhysApicBase, GCPhys;
1970 GCPhysApicBase = pCtx->msrApicBase;
1971 GCPhysApicBase &= PAGE_BASE_GC_MASK;
1972
1973 rc = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL, &GCPhys);
1974 if ( rc == VINF_SUCCESS
1975 && GCPhys == GCPhysApicBase)
1976 {
1977 /* Only attempt to patch the instruction once. */
1978 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
1979 if (!pPatch)
1980 {
1981 rc = VINF_EM_HM_PATCH_TPR_INSTR;
1982 break;
1983 }
1984 }
1985 }
1986#endif
1987
1988 Log2(("Page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
1989 /* Exit qualification contains the linear address of the page fault. */
1990 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
1991 TRPMSetErrorCode(pVCpu, errCode);
1992 TRPMSetFaultAddress(pVCpu, uFaultAddress);
1993
1994 /* Forward it to our trap handler first, in case our shadow pages are out of sync. */
1995 rc = PGMTrap0eHandler(pVCpu, errCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
1996 Log2(("PGMTrap0eHandler %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1997 if (rc == VINF_SUCCESS)
1998 {
1999 /* We've successfully synced our shadow pages, so let's just continue execution. */
2000 Log2(("Shadow page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
2001 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
2002
2003 TRPMResetTrap(pVCpu);
2004 goto ResumeExecution;
2005 }
2006 else if (rc == VINF_EM_RAW_GUEST_TRAP)
2007 {
2008 /*
2009 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
2010 */
2011 Log2(("Forward page fault to the guest\n"));
2012 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
2013 /* The error code might have been changed. */
2014 errCode = TRPMGetErrorCode(pVCpu);
2015
2016 TRPMResetTrap(pVCpu);
2017
2018 /* Now we must update CR2. */
2019 pCtx->cr2 = uFaultAddress;
2020
2021 Event.u = 0;
2022 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2023 Event.n.u1Valid = 1;
2024 Event.n.u8Vector = X86_XCPT_PF;
2025 Event.n.u1ErrorCodeValid = 1;
2026 Event.n.u32ErrorCode = errCode;
2027
2028 hmR0SvmSetPendingEvent(pVCpu, &Event);
2029 goto ResumeExecution;
2030 }
2031#ifdef VBOX_STRICT
2032 if (rc != VINF_EM_RAW_EMULATE_INSTR && rc != VINF_EM_RAW_EMULATE_IO_BLOCK)
2033 LogFlow(("PGMTrap0eHandler failed with %d\n", VBOXSTRICTRC_VAL(rc)));
2034#endif
2035 /* Need to go back to the recompiler to emulate the instruction. */
2036 TRPMResetTrap(pVCpu);
2037 break;
2038 }
2039
2040 case X86_XCPT_MF: /* Floating point exception. */
2041 {
2042 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
2043 if (!(pCtx->cr0 & X86_CR0_NE))
2044 {
2045 /* old style FPU error reporting needs some extra work. */
2046 /** @todo don't fall back to the recompiler, but do it manually. */
2047 rc = VINF_EM_RAW_EMULATE_INSTR;
2048 break;
2049 }
2050 Log(("Trap %x at %RGv\n", vector, (RTGCPTR)pCtx->rip));
2051
2052 Event.u = 0;
2053 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2054 Event.n.u1Valid = 1;
2055 Event.n.u8Vector = X86_XCPT_MF;
2056
2057 hmR0SvmSetPendingEvent(pVCpu, &Event);
2058 goto ResumeExecution;
2059 }
2060
2061#ifdef VBOX_STRICT
2062 case X86_XCPT_BP: /* Breakpoint. */
2063 case X86_XCPT_GP: /* General protection failure exception.*/
2064 case X86_XCPT_UD: /* Unknown opcode exception. */
2065 case X86_XCPT_DE: /* Divide error. */
2066 case X86_XCPT_SS: /* Stack segment exception. */
2067 case X86_XCPT_NP: /* Segment not present exception. */
2068 {
2069 Event.u = 0;
2070 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2071 Event.n.u1Valid = 1;
2072 Event.n.u8Vector = vector;
2073
2074 switch (vector)
2075 {
2076 case X86_XCPT_GP:
2077 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
2078 Event.n.u1ErrorCodeValid = 1;
2079 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2080 break;
2081 case X86_XCPT_BP:
2082 /** Saves the wrong EIP on the stack (pointing to the int3 instead of the next instruction. */
2083 break;
2084 case X86_XCPT_DE:
2085 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
2086 break;
2087 case X86_XCPT_UD:
2088 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
2089 break;
2090 case X86_XCPT_SS:
2091 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
2092 Event.n.u1ErrorCodeValid = 1;
2093 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2094 break;
2095 case X86_XCPT_NP:
2096 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
2097 Event.n.u1ErrorCodeValid = 1;
2098 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2099 break;
2100 }
2101 Log(("Trap %x at %04x:%RGv esi=%x\n", vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip, pCtx->esi));
2102 hmR0SvmSetPendingEvent(pVCpu, &Event);
2103 goto ResumeExecution;
2104 }
2105#endif
2106 default:
2107 AssertMsgFailed(("Unexpected vm-exit caused by exception %x\n", vector));
2108 rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
2109 break;
2110
2111 } /* switch (vector) */
2112 break;
2113 }
2114
2115 case SVM_EXIT_NPF:
2116 {
2117 /* EXITINFO1 contains fault errorcode; EXITINFO2 contains the guest physical address causing the fault. */
2118 uint32_t errCode = pVmcb->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2119 RTGCPHYS GCPhysFault = pVmcb->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
2120 PGMMODE enmShwPagingMode;
2121
2122 Assert(pVM->hm.s.fNestedPaging);
2123 LogFlow(("Nested page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2124
2125#ifdef VBOX_HM_WITH_GUEST_PATCHING
2126 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
2127 if ( pVM->hm.s.fTRPPatchingAllowed
2128 && (GCPhysFault & PAGE_OFFSET_MASK) == 0x080
2129 && ( !(errCode & X86_TRAP_PF_P) /* not present */
2130 || (errCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD) /* mmio optimization */)
2131 && CPUMGetGuestCPL(pVCpu) == 0
2132 && !CPUMIsGuestInLongModeEx(pCtx)
2133 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
2134 {
2135 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
2136 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2137
2138 if (GCPhysFault == GCPhysApicBase + 0x80)
2139 {
2140 /* Only attempt to patch the instruction once. */
2141 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2142 if (!pPatch)
2143 {
2144 rc = VINF_EM_HM_PATCH_TPR_INSTR;
2145 break;
2146 }
2147 }
2148 }
2149#endif
2150
2151 /* Handle the pagefault trap for the nested shadow table. */
2152#if HC_ARCH_BITS == 32 /** @todo shadow this in a variable. */
2153 if (CPUMIsGuestInLongModeEx(pCtx))
2154 enmShwPagingMode = PGMMODE_AMD64_NX;
2155 else
2156#endif
2157 enmShwPagingMode = PGMGetHostMode(pVM);
2158
2159 /* MMIO optimization */
2160 Assert((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
2161 if ((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
2162 {
2163 rc = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmShwPagingMode, CPUMCTX2CORE(pCtx), GCPhysFault, errCode);
2164
2165 /*
2166 * If we succeed, resume execution.
2167 * Or, if fail in interpreting the instruction because we couldn't get the guest physical address
2168 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
2169 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
2170 * weird case. See @bugref{6043}.
2171 */
2172 if ( rc == VINF_SUCCESS
2173 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2174 || rc == VERR_PAGE_NOT_PRESENT)
2175 {
2176 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2177 goto ResumeExecution;
2178 }
2179 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2180 break;
2181 }
2182
2183 /* Exit qualification contains the linear address of the page fault. */
2184 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
2185 TRPMSetErrorCode(pVCpu, errCode);
2186 TRPMSetFaultAddress(pVCpu, GCPhysFault);
2187
2188 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmShwPagingMode, errCode, CPUMCTX2CORE(pCtx), GCPhysFault);
2189 Log2(("PGMR0Trap0eHandlerNestedPaging %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
2190
2191 /*
2192 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
2193 */
2194 if ( rc == VINF_SUCCESS
2195 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2196 || rc == VERR_PAGE_NOT_PRESENT)
2197 {
2198 /* We've successfully synced our shadow pages, so let's just continue execution. */
2199 Log2(("Shadow page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2200 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
2201
2202 TRPMResetTrap(pVCpu);
2203 goto ResumeExecution;
2204 }
2205
2206#ifdef VBOX_STRICT
2207 if (rc != VINF_EM_RAW_EMULATE_INSTR)
2208 LogFlow(("PGMTrap0eHandlerNestedPaging failed with %d\n", VBOXSTRICTRC_VAL(rc)));
2209#endif
2210 /* Need to go back to the recompiler to emulate the instruction. */
2211 TRPMResetTrap(pVCpu);
2212 break;
2213 }
2214
2215 case SVM_EXIT_VINTR:
2216 /* A virtual interrupt is about to be delivered, which means IF=1. */
2217 Log(("SVM_EXIT_VINTR IF=%d\n", pCtx->eflags.Bits.u1IF));
2218 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0;
2219 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
2220 goto ResumeExecution;
2221
2222 case SVM_EXIT_FERR_FREEZE:
2223 case SVM_EXIT_INTR:
2224 case SVM_EXIT_NMI:
2225 case SVM_EXIT_SMI:
2226 case SVM_EXIT_INIT:
2227 /* External interrupt; leave to allow it to be dispatched again. */
2228 rc = VINF_EM_RAW_INTERRUPT;
2229 break;
2230
2231 case SVM_EXIT_WBINVD:
2232 case SVM_EXIT_INVD: /* Guest software attempted to execute INVD. */
2233 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
2234 /* Skip instruction and continue directly. */
2235 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2236 /* Continue execution.*/
2237 goto ResumeExecution;
2238
2239 case SVM_EXIT_CPUID: /* Guest software attempted to execute CPUID. */
2240 {
2241 Log2(("SVM: Cpuid at %RGv for %x\n", (RTGCPTR)pCtx->rip, pCtx->eax));
2242 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
2243 rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2244 if (rc == VINF_SUCCESS)
2245 {
2246 /* Update EIP and continue execution. */
2247 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2248 goto ResumeExecution;
2249 }
2250 AssertMsgFailed(("EMU: cpuid failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2251 rc = VINF_EM_RAW_EMULATE_INSTR;
2252 break;
2253 }
2254
2255 case SVM_EXIT_RDTSC: /* Guest software attempted to execute RDTSC. */
2256 {
2257 Log2(("SVM: Rdtsc\n"));
2258 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
2259 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2260 if (rc == VINF_SUCCESS)
2261 {
2262 /* Update EIP and continue execution. */
2263 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2264 goto ResumeExecution;
2265 }
2266 rc = VINF_EM_RAW_EMULATE_INSTR;
2267 break;
2268 }
2269
2270 case SVM_EXIT_RDPMC: /* Guest software attempted to execute RDPMC. */
2271 {
2272 Log2(("SVM: Rdpmc %x\n", pCtx->ecx));
2273 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
2274 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2275 if (rc == VINF_SUCCESS)
2276 {
2277 /* Update EIP and continue execution. */
2278 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2279 goto ResumeExecution;
2280 }
2281 rc = VINF_EM_RAW_EMULATE_INSTR;
2282 break;
2283 }
2284
2285 case SVM_EXIT_RDTSCP: /* Guest software attempted to execute RDTSCP. */
2286 {
2287 Log2(("SVM: Rdtscp\n"));
2288 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
2289 rc = EMInterpretRdtscp(pVM, pVCpu, pCtx);
2290 if (rc == VINF_SUCCESS)
2291 {
2292 /* Update EIP and continue execution. */
2293 pCtx->rip += 3; /* Note! hardcoded opcode size! */
2294 goto ResumeExecution;
2295 }
2296 AssertMsgFailed(("EMU: rdtscp failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2297 rc = VINF_EM_RAW_EMULATE_INSTR;
2298 break;
2299 }
2300
2301 case SVM_EXIT_INVLPG: /* Guest software attempted to execute INVLPG. */
2302 {
2303 Log2(("SVM: invlpg\n"));
2304 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
2305
2306 Assert(!pVM->hm.s.fNestedPaging);
2307
2308 /* Truly a pita. Why can't SVM give the same information as VT-x? */
2309 rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2310 if (rc == VINF_SUCCESS)
2311 {
2312 goto ResumeExecution; /* eip already updated */
2313 }
2314 break;
2315 }
2316
2317 case SVM_EXIT_WRITE_CR0: case SVM_EXIT_WRITE_CR1: case SVM_EXIT_WRITE_CR2: case SVM_EXIT_WRITE_CR3:
2318 case SVM_EXIT_WRITE_CR4: case SVM_EXIT_WRITE_CR5: case SVM_EXIT_WRITE_CR6: case SVM_EXIT_WRITE_CR7:
2319 case SVM_EXIT_WRITE_CR8: case SVM_EXIT_WRITE_CR9: case SVM_EXIT_WRITE_CR10: case SVM_EXIT_WRITE_CR11:
2320 case SVM_EXIT_WRITE_CR12: case SVM_EXIT_WRITE_CR13: case SVM_EXIT_WRITE_CR14: case SVM_EXIT_WRITE_CR15:
2321 {
2322 Log2(("SVM: %RGv mov cr%d, \n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_CR0));
2323 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxWrite[exitCode - SVM_EXIT_WRITE_CR0]);
2324 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2325
2326 switch (exitCode - SVM_EXIT_WRITE_CR0)
2327 {
2328 case 0:
2329 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
2330 break;
2331 case 2:
2332 break;
2333 case 3:
2334 Assert(!pVM->hm.s.fNestedPaging);
2335 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
2336 break;
2337 case 4:
2338 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
2339 break;
2340 case 8:
2341 break;
2342 default:
2343 AssertFailed();
2344 }
2345 if (rc == VINF_SUCCESS)
2346 {
2347 /* EIP has been updated already. */
2348 /* Only resume if successful. */
2349 goto ResumeExecution;
2350 }
2351 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2352 break;
2353 }
2354
2355 case SVM_EXIT_READ_CR0: case SVM_EXIT_READ_CR1: case SVM_EXIT_READ_CR2: case SVM_EXIT_READ_CR3:
2356 case SVM_EXIT_READ_CR4: case SVM_EXIT_READ_CR5: case SVM_EXIT_READ_CR6: case SVM_EXIT_READ_CR7:
2357 case SVM_EXIT_READ_CR8: case SVM_EXIT_READ_CR9: case SVM_EXIT_READ_CR10: case SVM_EXIT_READ_CR11:
2358 case SVM_EXIT_READ_CR12: case SVM_EXIT_READ_CR13: case SVM_EXIT_READ_CR14: case SVM_EXIT_READ_CR15:
2359 {
2360 Log2(("SVM: %RGv mov x, cr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_CR0));
2361 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[exitCode - SVM_EXIT_READ_CR0]);
2362 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2363 if (rc == VINF_SUCCESS)
2364 {
2365 /* EIP has been updated already. */
2366 /* Only resume if successful. */
2367 goto ResumeExecution;
2368 }
2369 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2370 break;
2371 }
2372
2373 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2374 case SVM_EXIT_WRITE_DR4: case SVM_EXIT_WRITE_DR5: case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7:
2375 case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9: case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11:
2376 case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13: case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
2377 {
2378 Log2(("SVM: %RGv mov dr%d, x\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_DR0));
2379 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
2380
2381 if ( !DBGFIsStepping(pVCpu)
2382 && !CPUMIsHyperDebugStateActive(pVCpu))
2383 {
2384 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
2385
2386 /* Disable drx move intercepts. */
2387 pVmcb->ctrl.u16InterceptRdDRx = 0;
2388 pVmcb->ctrl.u16InterceptWrDRx = 0;
2389
2390 /* Save the host and load the guest debug state. */
2391 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2392 AssertRC(rc2);
2393 goto ResumeExecution;
2394 }
2395
2396 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2397 if (rc == VINF_SUCCESS)
2398 {
2399 /* EIP has been updated already. */
2400 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
2401
2402 /* Only resume if successful. */
2403 goto ResumeExecution;
2404 }
2405 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2406 break;
2407 }
2408
2409 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2410 case SVM_EXIT_READ_DR4: case SVM_EXIT_READ_DR5: case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7:
2411 case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9: case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11:
2412 case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13: case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2413 {
2414 Log2(("SVM: %RGv mov x, dr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_DR0));
2415 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
2416
2417 if (!DBGFIsStepping(pVCpu))
2418 {
2419 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
2420
2421 /* Disable DRx move intercepts. */
2422 pVmcb->ctrl.u16InterceptRdDRx = 0;
2423 pVmcb->ctrl.u16InterceptWrDRx = 0;
2424
2425 /* Save the host and load the guest debug state. */
2426 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2427 AssertRC(rc2);
2428 goto ResumeExecution;
2429 }
2430
2431 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2432 if (rc == VINF_SUCCESS)
2433 {
2434 /* EIP has been updated already. */
2435 /* Only resume if successful. */
2436 goto ResumeExecution;
2437 }
2438 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2439 break;
2440 }
2441
2442 /* Note: We'll get a #GP if the IO instruction isn't allowed (IOPL or TSS bitmap); no need to double check. */
2443 case SVM_EXIT_IOIO: /* I/O instruction. */
2444 {
2445 SVMIOIOEXIT IoExitInfo;
2446
2447 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
2448 unsigned uIdx = (IoExitInfo.u >> 4) & 0x7;
2449 uint32_t uIOSize = g_aIOSize[uIdx];
2450 uint32_t uAndVal = g_aIOOpAnd[uIdx];
2451 if (RT_UNLIKELY(!uIOSize))
2452 {
2453 AssertFailed(); /* should be fatal. */
2454 rc = VINF_EM_RAW_EMULATE_INSTR; /** @todo r=ramshankar: would this really fall back to the recompiler and work? */
2455 break;
2456 }
2457
2458 if (IoExitInfo.n.u1STR)
2459 {
2460 /* ins/outs */
2461 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
2462
2463 /* Disassemble manually to deal with segment prefixes. */
2464 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
2465 if (rc == VINF_SUCCESS)
2466 {
2467 if (IoExitInfo.n.u1Type == 0)
2468 {
2469 Log2(("IOMInterpretOUTSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2470 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
2471 rc = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2472 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2473 }
2474 else
2475 {
2476 Log2(("IOMInterpretINSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2477 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
2478 rc = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2479 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2480 }
2481 }
2482 else
2483 rc = VINF_EM_RAW_EMULATE_INSTR;
2484 }
2485 else
2486 {
2487 /* Normal in/out */
2488 Assert(!IoExitInfo.n.u1REP);
2489
2490 if (IoExitInfo.n.u1Type == 0)
2491 {
2492 Log2(("IOMIOPortWrite %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, pCtx->eax & uAndVal,
2493 uIOSize));
2494 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
2495 rc = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
2496 if (rc == VINF_IOM_R3_IOPORT_WRITE)
2497 {
2498 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2499 uAndVal, uIOSize);
2500 }
2501 }
2502 else
2503 {
2504 uint32_t u32Val = 0;
2505
2506 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
2507 rc = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, uIOSize);
2508 if (IOM_SUCCESS(rc))
2509 {
2510 /* Write back to the EAX register. */
2511 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
2512 Log2(("IOMIOPortRead %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, u32Val & uAndVal,
2513 uIOSize));
2514 }
2515 else if (rc == VINF_IOM_R3_IOPORT_READ)
2516 {
2517 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2518 uAndVal, uIOSize);
2519 }
2520 }
2521 }
2522
2523 /*
2524 * Handled the I/O return codes.
2525 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
2526 */
2527 if (IOM_SUCCESS(rc))
2528 {
2529 /* Update EIP and continue execution. */
2530 pCtx->rip = pVmcb->ctrl.u64ExitInfo2; /* RIP/EIP of the next instruction is saved in EXITINFO2. */
2531 if (RT_LIKELY(rc == VINF_SUCCESS))
2532 {
2533 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
2534 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
2535 {
2536 /* IO operation lookup arrays. */
2537 static uint32_t const aIOSize[4] = { 1, 2, 0, 4 };
2538
2539 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
2540 for (unsigned i = 0; i < 4; i++)
2541 {
2542 unsigned uBPLen = aIOSize[X86_DR7_GET_LEN(pCtx->dr[7], i)];
2543
2544 if ( (IoExitInfo.n.u16Port >= pCtx->dr[i] && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen)
2545 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
2546 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
2547 {
2548 SVMEVENT Event;
2549
2550 Assert(CPUMIsGuestDebugStateActive(pVCpu));
2551
2552 /* Clear all breakpoint status flags and set the one we just hit. */
2553 pCtx->dr[6] &= ~(X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3);
2554 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
2555
2556 /*
2557 * Note: AMD64 Architecture Programmer's Manual 13.1:
2558 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
2559 * by software after the contents have been read.
2560 */
2561 pVmcb->guest.u64DR6 = pCtx->dr[6];
2562
2563 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
2564 pCtx->dr[7] &= ~X86_DR7_GD;
2565
2566 /* Paranoia. */
2567 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
2568 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
2569 pCtx->dr[7] |= 0x400; /* must be one */
2570
2571 pVmcb->guest.u64DR7 = pCtx->dr[7];
2572
2573 /* Inject the exception. */
2574 Log(("Inject IO debug trap at %RGv\n", (RTGCPTR)pCtx->rip));
2575
2576 Event.u = 0;
2577 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
2578 Event.n.u1Valid = 1;
2579 Event.n.u8Vector = X86_XCPT_DB;
2580
2581 hmR0SvmSetPendingEvent(pVCpu, &Event);
2582 goto ResumeExecution;
2583 }
2584 }
2585 }
2586 goto ResumeExecution;
2587 }
2588 Log2(("EM status from IO at %RGv %x size %d: %Rrc\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize,
2589 VBOXSTRICTRC_VAL(rc)));
2590 break;
2591 }
2592
2593#ifdef VBOX_STRICT
2594 if (rc == VINF_IOM_R3_IOPORT_READ)
2595 Assert(IoExitInfo.n.u1Type != 0);
2596 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
2597 Assert(IoExitInfo.n.u1Type == 0);
2598 else
2599 {
2600 AssertMsg( RT_FAILURE(rc)
2601 || rc == VINF_EM_RAW_EMULATE_INSTR
2602 || rc == VINF_EM_RAW_GUEST_TRAP
2603 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rc)));
2604 }
2605#endif
2606 Log2(("Failed IO at %RGv %x size %d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2607 break;
2608 }
2609
2610 case SVM_EXIT_HLT:
2611 /* Check if external interrupts are pending; if so, don't switch back. */
2612 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
2613 pCtx->rip++; /* skip hlt */
2614 if (EMShouldContinueAfterHalt(pVCpu, pCtx))
2615 goto ResumeExecution;
2616
2617 rc = VINF_EM_HALT;
2618 break;
2619
2620 case SVM_EXIT_MWAIT_UNCOND:
2621 Log2(("SVM: mwait\n"));
2622 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
2623 rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2624 if ( rc == VINF_EM_HALT
2625 || rc == VINF_SUCCESS)
2626 {
2627 /* Update EIP and continue execution. */
2628 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2629
2630 /* Check if external interrupts are pending; if so, don't switch back. */
2631 if ( rc == VINF_SUCCESS
2632 || ( rc == VINF_EM_HALT
2633 && EMShouldContinueAfterHalt(pVCpu, pCtx))
2634 )
2635 goto ResumeExecution;
2636 }
2637 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_EM_HALT, ("EMU: mwait failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2638 break;
2639
2640 case SVM_EXIT_MONITOR:
2641 {
2642 Log2(("SVM: monitor\n"));
2643
2644 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
2645 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2646 if (rc == VINF_SUCCESS)
2647 {
2648 /* Update EIP and continue execution. */
2649 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2650 goto ResumeExecution;
2651 }
2652 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: monitor failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2653 break;
2654 }
2655
2656 case SVM_EXIT_VMMCALL:
2657 rc = hmR0SvmEmulateTprVMMCall(pVM, pVCpu, pCtx);
2658 if (rc == VINF_SUCCESS)
2659 {
2660 goto ResumeExecution; /* rip already updated. */
2661 }
2662 /* no break */
2663
2664 case SVM_EXIT_RSM:
2665 case SVM_EXIT_INVLPGA:
2666 case SVM_EXIT_VMRUN:
2667 case SVM_EXIT_VMLOAD:
2668 case SVM_EXIT_VMSAVE:
2669 case SVM_EXIT_STGI:
2670 case SVM_EXIT_CLGI:
2671 case SVM_EXIT_SKINIT:
2672 {
2673 /* Unsupported instructions. */
2674 SVMEVENT Event;
2675
2676 Event.u = 0;
2677 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2678 Event.n.u1Valid = 1;
2679 Event.n.u8Vector = X86_XCPT_UD;
2680
2681 Log(("Forced #UD trap at %RGv\n", (RTGCPTR)pCtx->rip));
2682 hmR0SvmSetPendingEvent(pVCpu, &Event);
2683 goto ResumeExecution;
2684 }
2685
2686 /* Emulate in ring-3. */
2687 case SVM_EXIT_MSR:
2688 {
2689 /* When an interrupt is pending, we'll let MSR_K8_LSTAR writes fault in our TPR patch code. */
2690 if ( pVM->hm.s.fTPRPatchingActive
2691 && pCtx->ecx == MSR_K8_LSTAR
2692 && pVmcb->ctrl.u64ExitInfo1 == 1 /* wrmsr */)
2693 {
2694 if ((pCtx->eax & 0xff) != u8LastTPR)
2695 {
2696 Log(("SVM: Faulting MSR_K8_LSTAR write with new TPR value %x\n", pCtx->eax & 0xff));
2697
2698 /* Our patch code uses LSTAR for TPR caching. */
2699 rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
2700 AssertRC(rc2);
2701 }
2702
2703 /* Skip the instruction and continue. */
2704 pCtx->rip += 2; /* wrmsr = [0F 30] */
2705
2706 /* Only resume if successful. */
2707 goto ResumeExecution;
2708 }
2709
2710 /*
2711 * The Intel spec. claims there's an REX version of RDMSR that's slightly different,
2712 * so we play safe by completely disassembling the instruction.
2713 */
2714 STAM_COUNTER_INC((pVmcb->ctrl.u64ExitInfo1 == 0) ? &pVCpu->hm.s.StatExitRdmsr : &pVCpu->hm.s.StatExitWrmsr);
2715 Log(("SVM: %s\n", (pVmcb->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr"));
2716 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2717 if (rc == VINF_SUCCESS)
2718 {
2719 /* EIP has been updated already. */
2720 /* Only resume if successful. */
2721 goto ResumeExecution;
2722 }
2723 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: %s failed with %Rrc\n", (pVmcb->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr",
2724 VBOXSTRICTRC_VAL(rc)));
2725 break;
2726 }
2727
2728 case SVM_EXIT_TASK_SWITCH: /* too complicated to emulate, so fall back to the recompiler */
2729 Log(("SVM_EXIT_TASK_SWITCH: exit2=%RX64\n", pVmcb->ctrl.u64ExitInfo2));
2730 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
2731 && pVCpu->hm.s.Event.fPending)
2732 {
2733 SVMEVENT Event;
2734 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2735
2736 /* Caused by an injected interrupt. */
2737 pVCpu->hm.s.Event.fPending = false;
2738 switch (Event.n.u3Type)
2739 {
2740 case SVM_EVENT_EXTERNAL_IRQ:
2741 case SVM_EVENT_NMI:
2742 Log(("SVM_EXIT_TASK_SWITCH: reassert trap %d\n", Event.n.u8Vector));
2743 Assert(!Event.n.u1ErrorCodeValid);
2744 rc2 = TRPMAssertTrap(pVCpu, Event.n.u8Vector, TRPM_HARDWARE_INT);
2745 AssertRC(rc2);
2746 break;
2747
2748 default:
2749 /* Exceptions and software interrupts can just be restarted. */
2750 break;
2751 }
2752 }
2753 rc = VERR_EM_INTERPRETER;
2754 break;
2755
2756 case SVM_EXIT_PAUSE:
2757 case SVM_EXIT_MWAIT_ARMED:
2758 rc = VERR_EM_INTERPRETER;
2759 break;
2760
2761 case SVM_EXIT_SHUTDOWN:
2762 rc = VINF_EM_RESET; /* Triple fault equals a reset. */
2763 break;
2764
2765 case SVM_EXIT_IDTR_READ:
2766 case SVM_EXIT_GDTR_READ:
2767 case SVM_EXIT_LDTR_READ:
2768 case SVM_EXIT_TR_READ:
2769 case SVM_EXIT_IDTR_WRITE:
2770 case SVM_EXIT_GDTR_WRITE:
2771 case SVM_EXIT_LDTR_WRITE:
2772 case SVM_EXIT_TR_WRITE:
2773 case SVM_EXIT_CR0_SEL_WRITE:
2774 default:
2775 /* Unexpected exit codes. */
2776 rc = VERR_SVM_UNEXPECTED_EXIT;
2777 AssertMsgFailed(("Unexpected exit code %x\n", exitCode)); /* Can't happen. */
2778 break;
2779 }
2780
2781end:
2782
2783 /*
2784 * We are now going back to ring-3, so clear the forced action flag.
2785 */
2786 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2787
2788 /*
2789 * Signal changes to the recompiler.
2790 */
2791 CPUMSetChangedFlags(pVCpu,
2792 CPUM_CHANGED_SYSENTER_MSR
2793 | CPUM_CHANGED_LDTR
2794 | CPUM_CHANGED_GDTR
2795 | CPUM_CHANGED_IDTR
2796 | CPUM_CHANGED_TR
2797 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2798
2799 /*
2800 * If we executed vmrun and an external IRQ was pending, then we don't have to do a full sync the next time.
2801 */
2802 if (exitCode == SVM_EXIT_INTR)
2803 {
2804 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2805 /* On the next entry we'll only sync the host context. */
2806 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
2807 }
2808 else
2809 {
2810 /* On the next entry we'll sync everything. */
2811 /** @todo we can do better than this */
2812 /* Not in the VINF_PGM_CHANGE_MODE though! */
2813 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_ALL;
2814 }
2815
2816 /* Translate into a less severe return code */
2817 if (rc == VERR_EM_INTERPRETER)
2818 rc = VINF_EM_RAW_EMULATE_INSTR;
2819
2820 /* Just set the correct state here instead of trying to catch every goto above. */
2821 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
2822
2823#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2824 /* Restore interrupts if we exitted after disabling them. */
2825 if (uOldEFlags != ~(RTCCUINTREG)0)
2826 ASMSetFlags(uOldEFlags);
2827#endif
2828
2829 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
2830 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
2831 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
2832 return VBOXSTRICTRC_TODO(rc);
2833}
2834
2835
2836/**
2837 * Emulate simple mov tpr instruction.
2838 *
2839 * @returns VBox status code.
2840 * @param pVM Pointer to the VM.
2841 * @param pVCpu Pointer to the VMCPU.
2842 * @param pCtx Pointer to the guest CPU context.
2843 */
2844static int hmR0SvmEmulateTprVMMCall(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2845{
2846 int rc;
2847
2848 LogFlow(("Emulated VMMCall TPR access replacement at %RGv\n", pCtx->rip));
2849
2850 for (;;)
2851 {
2852 bool fPending;
2853 uint8_t u8Tpr;
2854
2855 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2856 if (!pPatch)
2857 break;
2858
2859 switch (pPatch->enmType)
2860 {
2861 case HMTPRINSTR_READ:
2862 /* TPR caching in CR8 */
2863 rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
2864 AssertRC(rc);
2865
2866 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
2867 AssertRC(rc);
2868
2869 LogFlow(("Emulated read successfully\n"));
2870 pCtx->rip += pPatch->cbOp;
2871 break;
2872
2873 case HMTPRINSTR_WRITE_REG:
2874 case HMTPRINSTR_WRITE_IMM:
2875 /* Fetch the new TPR value */
2876 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
2877 {
2878 uint32_t val;
2879
2880 rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &val);
2881 AssertRC(rc);
2882 u8Tpr = val;
2883 }
2884 else
2885 u8Tpr = (uint8_t)pPatch->uSrcOperand;
2886
2887 rc = PDMApicSetTPR(pVCpu, u8Tpr);
2888 AssertRC(rc);
2889 LogFlow(("Emulated write successfully\n"));
2890 pCtx->rip += pPatch->cbOp;
2891 break;
2892
2893 default:
2894 AssertMsgFailedReturn(("Unexpected type %d\n", pPatch->enmType), VERR_SVM_UNEXPECTED_PATCH_TYPE);
2895 }
2896 }
2897 return VINF_SUCCESS;
2898}
2899
2900
2901/**
2902 * Enters the AMD-V session.
2903 *
2904 * @returns VBox status code.
2905 * @param pVM Pointer to the VM.
2906 * @param pVCpu Pointer to the VMCPU.
2907 * @param pCpu Pointer to the CPU info struct.
2908 */
2909VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
2910{
2911 Assert(pVM->hm.s.svm.fSupported);
2912
2913 LogFlow(("SVMR0Enter cpu%d last=%d asid=%d\n", pCpu->idCpu, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.uCurrentAsid));
2914 pVCpu->hm.s.fResumeVM = false;
2915
2916 /* Force to reload LDTR, so we'll execute VMLoad to load additional guest state. */
2917 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_LDTR;
2918
2919 return VINF_SUCCESS;
2920}
2921
2922
2923/**
2924 * Leaves the AMD-V session.
2925 *
2926 * @returns VBox status code.
2927 * @param pVM Pointer to the VM.
2928 * @param pVCpu Pointer to the VMCPU.
2929 * @param pCtx Pointer to the guest CPU context.
2930 */
2931VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2932{
2933 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2934
2935 Assert(pVM->hm.s.svm.fSupported);
2936
2937#ifdef DEBUG
2938 if (CPUMIsHyperDebugStateActive(pVCpu))
2939 {
2940 CPUMR0LoadHostDebugState(pVM, pVCpu);
2941 }
2942 else
2943#endif
2944 /* Save the guest debug state if necessary. */
2945 if (CPUMIsGuestDebugStateActive(pVCpu))
2946 {
2947 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, false /* skip DR6 */);
2948
2949 /* Intercept all DRx reads and writes again. Changed later on. */
2950 pVmcb->ctrl.u16InterceptRdDRx = 0xFFFF;
2951 pVmcb->ctrl.u16InterceptWrDRx = 0xFFFF;
2952
2953 /* Resync the debug registers the next time. */
2954 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
2955 }
2956 else
2957 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xFFFF && pVmcb->ctrl.u16InterceptWrDRx == 0xFFFF);
2958
2959 return VINF_SUCCESS;
2960}
2961
2962
2963/**
2964 * Worker for Interprets INVLPG.
2965 *
2966 * @return VBox status code.
2967 * @param pVCpu Pointer to the VMCPU.
2968 * @param pCpu Pointer to the CPU info struct.
2969 * @param pRegFrame Pointer to the register frame.
2970 */
2971static int hmR0svmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
2972{
2973 DISQPVPARAMVAL param1;
2974 RTGCPTR addr;
2975
2976 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &param1, DISQPVWHICH_SRC);
2977 if (RT_FAILURE(rc))
2978 return VERR_EM_INTERPRETER;
2979
2980 switch (param1.type)
2981 {
2982 case DISQPV_TYPE_IMMEDIATE:
2983 case DISQPV_TYPE_ADDRESS:
2984 if (!(param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
2985 return VERR_EM_INTERPRETER;
2986 addr = param1.val.val64;
2987 break;
2988
2989 default:
2990 return VERR_EM_INTERPRETER;
2991 }
2992
2993 /** @todo is addr always a flat linear address or ds based
2994 * (in absence of segment override prefixes)????
2995 */
2996 rc = PGMInvalidatePage(pVCpu, addr);
2997 if (RT_SUCCESS(rc))
2998 return VINF_SUCCESS;
2999
3000 AssertRC(rc);
3001 return rc;
3002}
3003
3004
3005/**
3006 * Interprets INVLPG.
3007 *
3008 * @returns VBox status code.
3009 * @retval VINF_* Scheduling instructions.
3010 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3011 * @retval VERR_* Fatal errors.
3012 *
3013 * @param pVM Pointer to the VM.
3014 * @param pRegFrame Pointer to the register frame.
3015 *
3016 * @remarks Updates the EIP if an instruction was executed successfully.
3017 */
3018static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
3019{
3020 /*
3021 * Only allow 32 & 64 bit code.
3022 */
3023 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3024 {
3025 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3026 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
3027 if (RT_SUCCESS(rc) && pDis->pCurInstr->uOpcode == OP_INVLPG)
3028 {
3029 rc = hmR0svmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
3030 if (RT_SUCCESS(rc))
3031 pRegFrame->rip += pDis->cbInstr; /* Move on to the next instruction. */
3032 return rc;
3033 }
3034 }
3035 return VERR_EM_INTERPRETER;
3036}
3037
3038
3039/**
3040 * Invalidates a guest page by guest virtual address.
3041 *
3042 * @returns VBox status code.
3043 * @param pVM Pointer to the VM.
3044 * @param pVCpu Pointer to the VMCPU.
3045 * @param GCVirt Guest virtual address of the page to invalidate.
3046 */
3047VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
3048{
3049 bool fFlushPending = pVM->hm.s.svm.fAlwaysFlushTLB | VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3050
3051 /* Skip it if a TLB flush is already pending. */
3052 if (!fFlushPending)
3053 {
3054 PSVMVMCB pVmcb;
3055
3056 Log2(("SVMR0InvalidatePage %RGv\n", GCVirt));
3057 AssertReturn(pVM, VERR_INVALID_PARAMETER);
3058 Assert(pVM->hm.s.svm.fSupported);
3059
3060 pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3061 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
3062
3063#if HC_ARCH_BITS == 32
3064 /* If we get a flush in 64 bits guest mode, then force a full TLB flush. Invlpga takes only 32 bits addresses. */
3065 if (CPUMIsGuestInLongMode(pVCpu))
3066 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3067 else
3068#endif
3069 {
3070 SVMR0InvlpgA(GCVirt, pVmcb->ctrl.TLBCtrl.n.u32ASID);
3071 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
3072 }
3073 }
3074 return VINF_SUCCESS;
3075}
3076
3077
3078#if 0 /* obsolete, but left here for clarification. */
3079/**
3080 * Invalidates a guest page by physical address.
3081 *
3082 * @returns VBox status code.
3083 * @param pVM Pointer to the VM.
3084 * @param pVCpu Pointer to the VMCPU.
3085 * @param GCPhys Guest physical address of the page to invalidate.
3086 */
3087VMMR0DECL(int) SVMR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
3088{
3089 Assert(pVM->hm.s.fNestedPaging);
3090 /* invlpga only invalidates TLB entries for guest virtual addresses; we have no choice but to force a TLB flush here. */
3091 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3092 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgPhys);
3093 return VINF_SUCCESS;
3094}
3095#endif
3096
3097
3098#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
3099/**
3100 * Prepares for and executes VMRUN (64-bit guests from a 32-bit host).
3101 *
3102 * @returns VBox status code.
3103 * @param HCPhysVmcbHost Physical address of host VMCB.
3104 * @param HCPhysVmcb Physical address of the VMCB.
3105 * @param pCtx Pointer to the guest CPU context.
3106 * @param pVM Pointer to the VM.
3107 * @param pVCpu Pointer to the VMCPU.
3108 */
3109DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVmcbHost, RTHCPHYS HCPhysVmcb, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
3110{
3111 uint32_t aParam[4];
3112
3113 aParam[0] = (uint32_t)(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Lo. */
3114 aParam[1] = (uint32_t)(HCPhysVmcbHost >> 32); /* Param 1: HCPhysVmcbHost - Hi. */
3115 aParam[2] = (uint32_t)(HCPhysVmcb); /* Param 2: HCPhysVmcb - Lo. */
3116 aParam[3] = (uint32_t)(HCPhysVmcb >> 32); /* Param 2: HCPhysVmcb - Hi. */
3117
3118 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_SVMRCVMRun64, 4, &aParam[0]);
3119}
3120
3121
3122/**
3123 * Executes the specified handler in 64-bit mode.
3124 *
3125 * @returns VBox status code.
3126 * @param pVM Pointer to the VM.
3127 * @param pVCpu Pointer to the VMCPU.
3128 * @param pCtx Pointer to the guest CPU context.
3129 * @param enmOp The operation to perform.
3130 * @param cbParam Number of parameters.
3131 * @param paParam Array of 32-bit parameters.
3132 */
3133VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp, uint32_t cbParam,
3134 uint32_t *paParam)
3135{
3136 int rc;
3137 RTHCUINTREG uOldEFlags;
3138
3139 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
3140 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
3141
3142 /* Disable interrupts. */
3143 uOldEFlags = ASMIntDisableFlags();
3144
3145#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
3146 RTCPUID idHostCpu = RTMpCpuId();
3147 CPUMR0SetLApic(pVM, idHostCpu);
3148#endif
3149
3150 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
3151 CPUMSetHyperEIP(pVCpu, enmOp);
3152 for (int i = (int)cbParam - 1; i >= 0; i--)
3153 CPUMPushHyper(pVCpu, paParam[i]);
3154
3155 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
3156 /* Call switcher. */
3157 rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
3158 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
3159
3160 ASMSetFlags(uOldEFlags);
3161 return rc;
3162}
3163
3164#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
3165
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