VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HMSVMR0.cpp@ 57546

Last change on this file since 57546 was 57477, checked in by vboxsync, 9 years ago

VMM/HM: Implement PAUSE filter exiting for VT-x & AMD-V. Also corrected some reserved bits in EPT_VPID capability MSRs.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 207.4 KB
Line 
1/* $Id: HMSVMR0.cpp 57477 2015-08-20 14:20:26Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#include <iprt/asm-amd64-x86.h>
24#include <iprt/thread.h>
25
26#include <VBox/vmm/pdmapi.h>
27#include <VBox/vmm/dbgf.h>
28#include <VBox/vmm/iem.h>
29#include <VBox/vmm/iom.h>
30#include <VBox/vmm/tm.h>
31#include <VBox/vmm/gim.h>
32#include "HMInternal.h"
33#include <VBox/vmm/vm.h>
34#include "HMSVMR0.h"
35#include "dtrace/VBoxVMM.h"
36
37#ifdef DEBUG_ramshankar
38# define HMSVM_SYNC_FULL_GUEST_STATE
39# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
40# define HMSVM_ALWAYS_TRAP_PF
41# define HMSVM_ALWAYS_TRAP_TASK_SWITCH
42#endif
43
44
45/*********************************************************************************************************************************
46* Defined Constants And Macros *
47*********************************************************************************************************************************/
48#ifdef VBOX_WITH_STATISTICS
49# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
50 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
51 if ((u64ExitCode) == SVM_EXIT_NPF) \
52 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
53 else \
54 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
55 } while (0)
56#else
57# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
58#endif
59
60/** If we decide to use a function table approach this can be useful to
61 * switch to a "static DECLCALLBACK(int)". */
62#define HMSVM_EXIT_DECL static int
63
64/** @name Segment attribute conversion between CPU and AMD-V VMCB format.
65 *
66 * The CPU format of the segment attribute is described in X86DESCATTRBITS
67 * which is 16-bits (i.e. includes 4 bits of the segment limit).
68 *
69 * The AMD-V VMCB format the segment attribute is compact 12-bits (strictly
70 * only the attribute bits and nothing else). Upper 4-bits are unused.
71 *
72 * @{ */
73#define HMSVM_CPU_2_VMCB_SEG_ATTR(a) ( ((a) & 0xff) | (((a) & 0xf000) >> 4) )
74#define HMSVM_VMCB_2_CPU_SEG_ATTR(a) ( ((a) & 0xff) | (((a) & 0x0f00) << 4) )
75/** @} */
76
77/** @name Macros for loading, storing segment registers to/from the VMCB.
78 * @{ */
79#define HMSVM_LOAD_SEG_REG(REG, reg) \
80 do \
81 { \
82 Assert(pCtx->reg.fFlags & CPUMSELREG_FLAGS_VALID); \
83 Assert(pCtx->reg.ValidSel == pCtx->reg.Sel); \
84 pVmcb->guest.REG.u16Sel = pCtx->reg.Sel; \
85 pVmcb->guest.REG.u32Limit = pCtx->reg.u32Limit; \
86 pVmcb->guest.REG.u64Base = pCtx->reg.u64Base; \
87 pVmcb->guest.REG.u16Attr = HMSVM_CPU_2_VMCB_SEG_ATTR(pCtx->reg.Attr.u); \
88 } while (0)
89
90#define HMSVM_SAVE_SEG_REG(REG, reg) \
91 do \
92 { \
93 pMixedCtx->reg.Sel = pVmcb->guest.REG.u16Sel; \
94 pMixedCtx->reg.ValidSel = pVmcb->guest.REG.u16Sel; \
95 pMixedCtx->reg.fFlags = CPUMSELREG_FLAGS_VALID; \
96 pMixedCtx->reg.u32Limit = pVmcb->guest.REG.u32Limit; \
97 pMixedCtx->reg.u64Base = pVmcb->guest.REG.u64Base; \
98 pMixedCtx->reg.Attr.u = HMSVM_VMCB_2_CPU_SEG_ATTR(pVmcb->guest.REG.u16Attr); \
99 } while (0)
100/** @} */
101
102/** Macro for checking and returning from the using function for
103 * \#VMEXIT intercepts that maybe caused during delivering of another
104 * event in the guest. */
105#define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
106 do \
107 { \
108 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
109 if (RT_UNLIKELY(rc == VINF_HM_DOUBLE_FAULT)) \
110 return VINF_SUCCESS; \
111 else if (RT_UNLIKELY(rc == VINF_EM_RESET)) \
112 return rc; \
113 } while (0)
114
115/** Macro for upgrading a @a a_rc to VINF_EM_DBG_STEPPED after emulating an
116 * instruction that exited. */
117#define HMSVM_CHECK_SINGLE_STEP(a_pVCpu, a_rc) \
118 do { \
119 if ((a_pVCpu)->hm.s.fSingleInstruction && (a_rc) == VINF_SUCCESS) \
120 (a_rc) = VINF_EM_DBG_STEPPED; \
121 } while (0)
122
123/** Assert that preemption is disabled or covered by thread-context hooks. */
124#define HMSVM_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
125 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
126
127/** Assert that we haven't migrated CPUs when thread-context hooks are not
128 * used. */
129#define HMSVM_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
130 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
131 ("Illegal migration! Entered on CPU %u Current %u\n", \
132 pVCpu->hm.s.idEnteredCpu, RTMpCpuId()));
133
134/** Exception bitmap mask for all contributory exceptions.
135 *
136 * Page fault is deliberately excluded here as it's conditional as to whether
137 * it's contributory or benign. Page faults are handled separately.
138 */
139#define HMSVM_CONTRIBUTORY_XCPT_MASK ( RT_BIT(X86_XCPT_GP) | RT_BIT(X86_XCPT_NP) | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_TS) \
140 | RT_BIT(X86_XCPT_DE))
141
142/** @name VMCB Clean Bits.
143 *
144 * These flags are used for VMCB-state caching. A set VMCB Clean bit indicates
145 * AMD-V doesn't need to reload the corresponding value(s) from the VMCB in
146 * memory.
147 *
148 * @{ */
149/** All intercepts vectors, TSC offset, PAUSE filter counter. */
150#define HMSVM_VMCB_CLEAN_INTERCEPTS RT_BIT(0)
151/** I/O permission bitmap, MSR permission bitmap. */
152#define HMSVM_VMCB_CLEAN_IOPM_MSRPM RT_BIT(1)
153/** ASID. */
154#define HMSVM_VMCB_CLEAN_ASID RT_BIT(2)
155/** TRP: V_TPR, V_IRQ, V_INTR_PRIO, V_IGN_TPR, V_INTR_MASKING,
156V_INTR_VECTOR. */
157#define HMSVM_VMCB_CLEAN_TPR RT_BIT(3)
158/** Nested Paging: Nested CR3 (nCR3), PAT. */
159#define HMSVM_VMCB_CLEAN_NP RT_BIT(4)
160/** Control registers (CR0, CR3, CR4, EFER). */
161#define HMSVM_VMCB_CLEAN_CRX_EFER RT_BIT(5)
162/** Debug registers (DR6, DR7). */
163#define HMSVM_VMCB_CLEAN_DRX RT_BIT(6)
164/** GDT, IDT limit and base. */
165#define HMSVM_VMCB_CLEAN_DT RT_BIT(7)
166/** Segment register: CS, SS, DS, ES limit and base. */
167#define HMSVM_VMCB_CLEAN_SEG RT_BIT(8)
168/** CR2.*/
169#define HMSVM_VMCB_CLEAN_CR2 RT_BIT(9)
170/** Last-branch record (DbgCtlMsr, br_from, br_to, lastint_from, lastint_to) */
171#define HMSVM_VMCB_CLEAN_LBR RT_BIT(10)
172/** AVIC (AVIC APIC_BAR; AVIC APIC_BACKING_PAGE, AVIC
173PHYSICAL_TABLE and AVIC LOGICAL_TABLE Pointers). */
174#define HMSVM_VMCB_CLEAN_AVIC RT_BIT(11)
175/** Mask of all valid VMCB Clean bits. */
176#define HMSVM_VMCB_CLEAN_ALL ( HMSVM_VMCB_CLEAN_INTERCEPTS \
177 | HMSVM_VMCB_CLEAN_IOPM_MSRPM \
178 | HMSVM_VMCB_CLEAN_ASID \
179 | HMSVM_VMCB_CLEAN_TPR \
180 | HMSVM_VMCB_CLEAN_NP \
181 | HMSVM_VMCB_CLEAN_CRX_EFER \
182 | HMSVM_VMCB_CLEAN_DRX \
183 | HMSVM_VMCB_CLEAN_DT \
184 | HMSVM_VMCB_CLEAN_SEG \
185 | HMSVM_VMCB_CLEAN_CR2 \
186 | HMSVM_VMCB_CLEAN_LBR \
187 | HMSVM_VMCB_CLEAN_AVIC)
188/** @} */
189
190/** @name SVM transient.
191 *
192 * A state structure for holding miscellaneous information across AMD-V
193 * VMRUN/#VMEXIT operation, restored after the transition.
194 *
195 * @{ */
196typedef struct SVMTRANSIENT
197{
198 /** The host's rflags/eflags. */
199 RTCCUINTREG fEFlags;
200#if HC_ARCH_BITS == 32
201 uint32_t u32Alignment0;
202#endif
203
204 /** The #VMEXIT exit code (the EXITCODE field in the VMCB). */
205 uint64_t u64ExitCode;
206 /** The guest's TPR value used for TPR shadowing. */
207 uint8_t u8GuestTpr;
208 /** Alignment. */
209 uint8_t abAlignment0[7];
210
211 /** Whether the guest FPU state was active at the time of #VMEXIT. */
212 bool fWasGuestFPUStateActive;
213 /** Whether the guest debug state was active at the time of #VMEXIT. */
214 bool fWasGuestDebugStateActive;
215 /** Whether the hyper debug state was active at the time of #VMEXIT. */
216 bool fWasHyperDebugStateActive;
217 /** Whether the TSC offset mode needs to be updated. */
218 bool fUpdateTscOffsetting;
219 /** Whether the TSC_AUX MSR needs restoring on #VMEXIT. */
220 bool fRestoreTscAuxMsr;
221 /** Whether the #VMEXIT was caused by a page-fault during delivery of a
222 * contributary exception or a page-fault. */
223 bool fVectoringDoublePF;
224 /** Whether the #VMEXIT was caused by a page-fault during delivery of an
225 * external interrupt or NMI. */
226 bool fVectoringPF;
227} SVMTRANSIENT, *PSVMTRANSIENT;
228AssertCompileMemberAlignment(SVMTRANSIENT, u64ExitCode, sizeof(uint64_t));
229AssertCompileMemberAlignment(SVMTRANSIENT, fWasGuestFPUStateActive, sizeof(uint64_t));
230/** @} */
231
232/**
233 * MSRPM (MSR permission bitmap) read permissions (for guest RDMSR).
234 */
235typedef enum SVMMSREXITREAD
236{
237 /** Reading this MSR causes a #VMEXIT. */
238 SVMMSREXIT_INTERCEPT_READ = 0xb,
239 /** Reading this MSR does not cause a #VMEXIT. */
240 SVMMSREXIT_PASSTHRU_READ
241} SVMMSREXITREAD;
242
243/**
244 * MSRPM (MSR permission bitmap) write permissions (for guest WRMSR).
245 */
246typedef enum SVMMSREXITWRITE
247{
248 /** Writing to this MSR causes a #VMEXIT. */
249 SVMMSREXIT_INTERCEPT_WRITE = 0xd,
250 /** Writing to this MSR does not cause a #VMEXIT. */
251 SVMMSREXIT_PASSTHRU_WRITE
252} SVMMSREXITWRITE;
253
254/**
255 * SVM #VMEXIT handler.
256 *
257 * @returns VBox status code.
258 * @param pVCpu Pointer to the VMCPU.
259 * @param pMixedCtx Pointer to the guest-CPU context.
260 * @param pSvmTransient Pointer to the SVM-transient structure.
261 */
262typedef int FNSVMEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
263
264
265/*********************************************************************************************************************************
266* Internal Functions *
267*********************************************************************************************************************************/
268static void hmR0SvmSetMsrPermission(PVMCPU pVCpu, unsigned uMsr, SVMMSREXITREAD enmRead, SVMMSREXITWRITE enmWrite);
269static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu);
270static void hmR0SvmLeave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
271
272/** @name #VMEXIT handlers.
273 * @{
274 */
275static FNSVMEXITHANDLER hmR0SvmExitIntr;
276static FNSVMEXITHANDLER hmR0SvmExitWbinvd;
277static FNSVMEXITHANDLER hmR0SvmExitInvd;
278static FNSVMEXITHANDLER hmR0SvmExitCpuid;
279static FNSVMEXITHANDLER hmR0SvmExitRdtsc;
280static FNSVMEXITHANDLER hmR0SvmExitRdtscp;
281static FNSVMEXITHANDLER hmR0SvmExitRdpmc;
282static FNSVMEXITHANDLER hmR0SvmExitInvlpg;
283static FNSVMEXITHANDLER hmR0SvmExitHlt;
284static FNSVMEXITHANDLER hmR0SvmExitMonitor;
285static FNSVMEXITHANDLER hmR0SvmExitMwait;
286static FNSVMEXITHANDLER hmR0SvmExitShutdown;
287static FNSVMEXITHANDLER hmR0SvmExitReadCRx;
288static FNSVMEXITHANDLER hmR0SvmExitWriteCRx;
289static FNSVMEXITHANDLER hmR0SvmExitSetPendingXcptUD;
290static FNSVMEXITHANDLER hmR0SvmExitMsr;
291static FNSVMEXITHANDLER hmR0SvmExitReadDRx;
292static FNSVMEXITHANDLER hmR0SvmExitWriteDRx;
293static FNSVMEXITHANDLER hmR0SvmExitXsetbv;
294static FNSVMEXITHANDLER hmR0SvmExitIOInstr;
295static FNSVMEXITHANDLER hmR0SvmExitNestedPF;
296static FNSVMEXITHANDLER hmR0SvmExitVIntr;
297static FNSVMEXITHANDLER hmR0SvmExitTaskSwitch;
298static FNSVMEXITHANDLER hmR0SvmExitVmmCall;
299static FNSVMEXITHANDLER hmR0SvmExitPause;
300static FNSVMEXITHANDLER hmR0SvmExitIret;
301static FNSVMEXITHANDLER hmR0SvmExitXcptPF;
302static FNSVMEXITHANDLER hmR0SvmExitXcptNM;
303static FNSVMEXITHANDLER hmR0SvmExitXcptUD;
304static FNSVMEXITHANDLER hmR0SvmExitXcptMF;
305static FNSVMEXITHANDLER hmR0SvmExitXcptDB;
306/** @} */
307
308DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient);
309
310
311/*********************************************************************************************************************************
312* Global Variables *
313*********************************************************************************************************************************/
314/** Ring-0 memory object for the IO bitmap. */
315RTR0MEMOBJ g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
316/** Physical address of the IO bitmap. */
317RTHCPHYS g_HCPhysIOBitmap = 0;
318/** Virtual address of the IO bitmap. */
319R0PTRTYPE(void *) g_pvIOBitmap = NULL;
320
321
322/**
323 * Sets up and activates AMD-V on the current CPU.
324 *
325 * @returns VBox status code.
326 * @param pCpu Pointer to the CPU info struct.
327 * @param pVM Pointer to the VM (can be NULL after a resume!).
328 * @param pvCpuPage Pointer to the global CPU page.
329 * @param HCPhysCpuPage Physical address of the global CPU page.
330 * @param fEnabledByHost Whether the host OS has already initialized AMD-V.
331 * @param pvArg Unused on AMD-V.
332 */
333VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBALCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
334 void *pvArg)
335{
336 Assert(!fEnabledByHost);
337 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
338 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
339 Assert(pvCpuPage);
340 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
341
342 NOREF(pvArg);
343 NOREF(fEnabledByHost);
344
345 /* Paranoid: Disable interrupt as, in theory, interrupt handlers might mess with EFER. */
346 RTCCUINTREG fEFlags = ASMIntDisableFlags();
347
348 /*
349 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per CPU.
350 */
351 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
352 if (u64HostEfer & MSR_K6_EFER_SVME)
353 {
354 /* If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V. */
355 if ( pVM
356 && pVM->hm.s.svm.fIgnoreInUseError)
357 {
358 pCpu->fIgnoreAMDVInUseError = true;
359 }
360
361 if (!pCpu->fIgnoreAMDVInUseError)
362 {
363 ASMSetFlags(fEFlags);
364 return VERR_SVM_IN_USE;
365 }
366 }
367
368 /* Turn on AMD-V in the EFER MSR. */
369 ASMWrMsr(MSR_K6_EFER, u64HostEfer | MSR_K6_EFER_SVME);
370
371 /* Write the physical page address where the CPU will store the host state while executing the VM. */
372 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
373
374 /* Restore interrupts. */
375 ASMSetFlags(fEFlags);
376
377 /*
378 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all non-zero ASIDs
379 * when enabling SVM. AMD doesn't have an SVM instruction to flush all ASIDs (flushing is done
380 * upon VMRUN). Therefore, just set the fFlushAsidBeforeUse flag which instructs hmR0SvmSetupTLB()
381 * to flush the TLB with before using a new ASID.
382 */
383 pCpu->fFlushAsidBeforeUse = true;
384
385 /*
386 * Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}.
387 */
388 ++pCpu->cTlbFlushes;
389
390 return VINF_SUCCESS;
391}
392
393
394/**
395 * Deactivates AMD-V on the current CPU.
396 *
397 * @returns VBox status code.
398 * @param pCpu Pointer to the CPU info struct.
399 * @param pvCpuPage Pointer to the global CPU page.
400 * @param HCPhysCpuPage Physical address of the global CPU page.
401 */
402VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBALCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
403{
404 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
405 AssertReturn( HCPhysCpuPage
406 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
407 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
408 NOREF(pCpu);
409
410 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with EFER. */
411 RTCCUINTREG fEFlags = ASMIntDisableFlags();
412
413 /* Turn off AMD-V in the EFER MSR. */
414 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
415 ASMWrMsr(MSR_K6_EFER, u64HostEfer & ~MSR_K6_EFER_SVME);
416
417 /* Invalidate host state physical address. */
418 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
419
420 /* Restore interrupts. */
421 ASMSetFlags(fEFlags);
422
423 return VINF_SUCCESS;
424}
425
426
427/**
428 * Does global AMD-V initialization (called during module initialization).
429 *
430 * @returns VBox status code.
431 */
432VMMR0DECL(int) SVMR0GlobalInit(void)
433{
434 /*
435 * Allocate 12 KB for the IO bitmap. Since this is non-optional and we always intercept all IO accesses, it's done
436 * once globally here instead of per-VM.
437 */
438 Assert(g_hMemObjIOBitmap == NIL_RTR0MEMOBJ);
439 int rc = RTR0MemObjAllocCont(&g_hMemObjIOBitmap, 3 << PAGE_SHIFT, false /* fExecutable */);
440 if (RT_FAILURE(rc))
441 return rc;
442
443 g_pvIOBitmap = RTR0MemObjAddress(g_hMemObjIOBitmap);
444 g_HCPhysIOBitmap = RTR0MemObjGetPagePhysAddr(g_hMemObjIOBitmap, 0 /* iPage */);
445
446 /* Set all bits to intercept all IO accesses. */
447 ASMMemFill32(g_pvIOBitmap, 3 << PAGE_SHIFT, UINT32_C(0xffffffff));
448 return VINF_SUCCESS;
449}
450
451
452/**
453 * Does global AMD-V termination (called during module termination).
454 */
455VMMR0DECL(void) SVMR0GlobalTerm(void)
456{
457 if (g_hMemObjIOBitmap != NIL_RTR0MEMOBJ)
458 {
459 RTR0MemObjFree(g_hMemObjIOBitmap, true /* fFreeMappings */);
460 g_pvIOBitmap = NULL;
461 g_HCPhysIOBitmap = 0;
462 g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
463 }
464}
465
466
467/**
468 * Frees any allocated per-VCPU structures for a VM.
469 *
470 * @param pVM Pointer to the VM.
471 */
472DECLINLINE(void) hmR0SvmFreeStructs(PVM pVM)
473{
474 for (uint32_t i = 0; i < pVM->cCpus; i++)
475 {
476 PVMCPU pVCpu = &pVM->aCpus[i];
477 AssertPtr(pVCpu);
478
479 if (pVCpu->hm.s.svm.hMemObjVmcbHost != NIL_RTR0MEMOBJ)
480 {
481 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcbHost, false);
482 pVCpu->hm.s.svm.pvVmcbHost = 0;
483 pVCpu->hm.s.svm.HCPhysVmcbHost = 0;
484 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
485 }
486
487 if (pVCpu->hm.s.svm.hMemObjVmcb != NIL_RTR0MEMOBJ)
488 {
489 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcb, false);
490 pVCpu->hm.s.svm.pvVmcb = 0;
491 pVCpu->hm.s.svm.HCPhysVmcb = 0;
492 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
493 }
494
495 if (pVCpu->hm.s.svm.hMemObjMsrBitmap != NIL_RTR0MEMOBJ)
496 {
497 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjMsrBitmap, false);
498 pVCpu->hm.s.svm.pvMsrBitmap = 0;
499 pVCpu->hm.s.svm.HCPhysMsrBitmap = 0;
500 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
501 }
502 }
503}
504
505
506/**
507 * Does per-VM AMD-V initialization.
508 *
509 * @returns VBox status code.
510 * @param pVM Pointer to the VM.
511 */
512VMMR0DECL(int) SVMR0InitVM(PVM pVM)
513{
514 int rc = VERR_INTERNAL_ERROR_5;
515
516 /*
517 * Check for an AMD CPU erratum which requires us to flush the TLB before every world-switch.
518 */
519 uint32_t u32Family;
520 uint32_t u32Model;
521 uint32_t u32Stepping;
522 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
523 {
524 Log4(("SVMR0InitVM: AMD cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
525 pVM->hm.s.svm.fAlwaysFlushTLB = true;
526 }
527
528 /*
529 * Initialize the R0 memory objects up-front so we can properly cleanup on allocation failures.
530 */
531 for (VMCPUID i = 0; i < pVM->cCpus; i++)
532 {
533 PVMCPU pVCpu = &pVM->aCpus[i];
534 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
535 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
536 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
537 }
538
539 for (VMCPUID i = 0; i < pVM->cCpus; i++)
540 {
541 PVMCPU pVCpu = &pVM->aCpus[i];
542
543 /*
544 * Allocate one page for the host-context VM control block (VMCB). This is used for additional host-state (such as
545 * FS, GS, Kernel GS Base, etc.) apart from the host-state save area specified in MSR_K8_VM_HSAVE_PA.
546 */
547 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcbHost, 1 << PAGE_SHIFT, false /* fExecutable */);
548 if (RT_FAILURE(rc))
549 goto failure_cleanup;
550
551 pVCpu->hm.s.svm.pvVmcbHost = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcbHost);
552 pVCpu->hm.s.svm.HCPhysVmcbHost = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcbHost, 0 /* iPage */);
553 Assert(pVCpu->hm.s.svm.HCPhysVmcbHost < _4G);
554 ASMMemZeroPage(pVCpu->hm.s.svm.pvVmcbHost);
555
556 /*
557 * Allocate one page for the guest-state VMCB.
558 */
559 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcb, 1 << PAGE_SHIFT, false /* fExecutable */);
560 if (RT_FAILURE(rc))
561 goto failure_cleanup;
562
563 pVCpu->hm.s.svm.pvVmcb = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcb);
564 pVCpu->hm.s.svm.HCPhysVmcb = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcb, 0 /* iPage */);
565 Assert(pVCpu->hm.s.svm.HCPhysVmcb < _4G);
566 ASMMemZeroPage(pVCpu->hm.s.svm.pvVmcb);
567
568 /*
569 * Allocate two pages (8 KB) for the MSR permission bitmap. There doesn't seem to be a way to convince
570 * SVM to not require one.
571 */
572 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjMsrBitmap, 2 << PAGE_SHIFT, false /* fExecutable */);
573 if (RT_FAILURE(rc))
574 goto failure_cleanup;
575
576 pVCpu->hm.s.svm.pvMsrBitmap = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjMsrBitmap);
577 pVCpu->hm.s.svm.HCPhysMsrBitmap = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjMsrBitmap, 0 /* iPage */);
578 /* Set all bits to intercept all MSR accesses (changed later on). */
579 ASMMemFill32(pVCpu->hm.s.svm.pvMsrBitmap, 2 << PAGE_SHIFT, UINT32_C(0xffffffff));
580 }
581
582 return VINF_SUCCESS;
583
584failure_cleanup:
585 hmR0SvmFreeStructs(pVM);
586 return rc;
587}
588
589
590/**
591 * Does per-VM AMD-V termination.
592 *
593 * @returns VBox status code.
594 * @param pVM Pointer to the VM.
595 */
596VMMR0DECL(int) SVMR0TermVM(PVM pVM)
597{
598 hmR0SvmFreeStructs(pVM);
599 return VINF_SUCCESS;
600}
601
602
603/**
604 * Sets the permission bits for the specified MSR in the MSRPM.
605 *
606 * @param pVCpu Pointer to the VMCPU.
607 * @param uMsr The MSR for which the access permissions are being set.
608 * @param enmRead MSR read permissions.
609 * @param enmWrite MSR write permissions.
610 */
611static void hmR0SvmSetMsrPermission(PVMCPU pVCpu, unsigned uMsr, SVMMSREXITREAD enmRead, SVMMSREXITWRITE enmWrite)
612{
613 unsigned ulBit;
614 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
615
616 /*
617 * Layout:
618 * Byte offset MSR range
619 * 0x000 - 0x7ff 0x00000000 - 0x00001fff
620 * 0x800 - 0xfff 0xc0000000 - 0xc0001fff
621 * 0x1000 - 0x17ff 0xc0010000 - 0xc0011fff
622 * 0x1800 - 0x1fff Reserved
623 */
624 if (uMsr <= 0x00001FFF)
625 {
626 /* Pentium-compatible MSRs. */
627 ulBit = uMsr * 2;
628 }
629 else if ( uMsr >= 0xC0000000
630 && uMsr <= 0xC0001FFF)
631 {
632 /* AMD Sixth Generation x86 Processor MSRs. */
633 ulBit = (uMsr - 0xC0000000) * 2;
634 pbMsrBitmap += 0x800;
635 }
636 else if ( uMsr >= 0xC0010000
637 && uMsr <= 0xC0011FFF)
638 {
639 /* AMD Seventh and Eighth Generation Processor MSRs. */
640 ulBit = (uMsr - 0xC0001000) * 2;
641 pbMsrBitmap += 0x1000;
642 }
643 else
644 {
645 AssertFailed();
646 return;
647 }
648
649 Assert(ulBit < 0x3fff /* 16 * 1024 - 1 */);
650 if (enmRead == SVMMSREXIT_INTERCEPT_READ)
651 ASMBitSet(pbMsrBitmap, ulBit);
652 else
653 ASMBitClear(pbMsrBitmap, ulBit);
654
655 if (enmWrite == SVMMSREXIT_INTERCEPT_WRITE)
656 ASMBitSet(pbMsrBitmap, ulBit + 1);
657 else
658 ASMBitClear(pbMsrBitmap, ulBit + 1);
659
660 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
661 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
662}
663
664
665/**
666 * Sets up AMD-V for the specified VM.
667 * This function is only called once per-VM during initalization.
668 *
669 * @returns VBox status code.
670 * @param pVM Pointer to the VM.
671 */
672VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
673{
674 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
675 AssertReturn(pVM, VERR_INVALID_PARAMETER);
676 Assert(pVM->hm.s.svm.fSupported);
677
678 bool const fPauseFilter = RT_BOOL(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER);
679 bool const fPauseFilterThreshold = RT_BOOL(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD);
680 bool const fUsePauseFilter = fPauseFilter && pVM->hm.s.svm.cPauseFilter && pVM->hm.s.svm.cPauseFilterThresholdTicks;
681
682 for (VMCPUID i = 0; i < pVM->cCpus; i++)
683 {
684 PVMCPU pVCpu = &pVM->aCpus[i];
685 PSVMVMCB pVmcb = (PSVMVMCB)pVM->aCpus[i].hm.s.svm.pvVmcb;
686
687 AssertMsgReturn(pVmcb, ("Invalid pVmcb for vcpu[%u]\n", i), VERR_SVM_INVALID_PVMCB);
688
689 /* Initialize the #VMEXIT history array with end-of-array markers (UINT16_MAX). */
690 Assert(!pVCpu->hm.s.idxExitHistoryFree);
691 HMCPU_EXIT_HISTORY_RESET(pVCpu);
692
693 /* Trap exceptions unconditionally (debug purposes). */
694#ifdef HMSVM_ALWAYS_TRAP_PF
695 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
696#endif
697#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
698 /* If you add any exceptions here, make sure to update hmR0SvmHandleExit(). */
699 pVmcb->ctrl.u32InterceptException |= 0
700 | RT_BIT(X86_XCPT_BP)
701 | RT_BIT(X86_XCPT_DB)
702 | RT_BIT(X86_XCPT_DE)
703 | RT_BIT(X86_XCPT_NM)
704 | RT_BIT(X86_XCPT_UD)
705 | RT_BIT(X86_XCPT_NP)
706 | RT_BIT(X86_XCPT_SS)
707 | RT_BIT(X86_XCPT_GP)
708 | RT_BIT(X86_XCPT_PF)
709 | RT_BIT(X86_XCPT_MF)
710 ;
711#endif
712
713 /* Set up unconditional intercepts and conditions. */
714 pVmcb->ctrl.u32InterceptCtrl1 = SVM_CTRL1_INTERCEPT_INTR /* External interrupt causes a #VMEXIT. */
715 | SVM_CTRL1_INTERCEPT_NMI /* Non-maskable interrupts causes a #VMEXIT. */
716 | SVM_CTRL1_INTERCEPT_INIT /* INIT signal causes a #VMEXIT. */
717 | SVM_CTRL1_INTERCEPT_RDPMC /* RDPMC causes a #VMEXIT. */
718 | SVM_CTRL1_INTERCEPT_CPUID /* CPUID causes a #VMEXIT. */
719 | SVM_CTRL1_INTERCEPT_RSM /* RSM causes a #VMEXIT. */
720 | SVM_CTRL1_INTERCEPT_HLT /* HLT causes a #VMEXIT. */
721 | SVM_CTRL1_INTERCEPT_INOUT_BITMAP /* Use the IOPM to cause IOIO #VMEXITs. */
722 | SVM_CTRL1_INTERCEPT_MSR_SHADOW /* MSR access not covered by MSRPM causes a #VMEXIT.*/
723 | SVM_CTRL1_INTERCEPT_INVLPGA /* INVLPGA causes a #VMEXIT. */
724 | SVM_CTRL1_INTERCEPT_SHUTDOWN /* Shutdown events causes a #VMEXIT. */
725 | SVM_CTRL1_INTERCEPT_FERR_FREEZE; /* Intercept "freezing" during legacy FPU handling. */
726
727 pVmcb->ctrl.u32InterceptCtrl2 = SVM_CTRL2_INTERCEPT_VMRUN /* VMRUN causes a #VMEXIT. */
728 | SVM_CTRL2_INTERCEPT_VMMCALL /* VMMCALL causes a #VMEXIT. */
729 | SVM_CTRL2_INTERCEPT_VMLOAD /* VMLOAD causes a #VMEXIT. */
730 | SVM_CTRL2_INTERCEPT_VMSAVE /* VMSAVE causes a #VMEXIT. */
731 | SVM_CTRL2_INTERCEPT_STGI /* STGI causes a #VMEXIT. */
732 | SVM_CTRL2_INTERCEPT_CLGI /* CLGI causes a #VMEXIT. */
733 | SVM_CTRL2_INTERCEPT_SKINIT /* SKINIT causes a #VMEXIT. */
734 | SVM_CTRL2_INTERCEPT_WBINVD /* WBINVD causes a #VMEXIT. */
735 | SVM_CTRL2_INTERCEPT_MONITOR /* MONITOR causes a #VMEXIT. */
736 | SVM_CTRL2_INTERCEPT_MWAIT /* MWAIT causes a #VMEXIT. */
737 | SVM_CTRL2_INTERCEPT_XSETBV; /* XSETBV causes a #VMEXIT. */
738
739 /* CR0, CR4 reads must be intercepted, our shadow values are not necessarily the same as the guest's. */
740 pVmcb->ctrl.u16InterceptRdCRx = RT_BIT(0) | RT_BIT(4);
741
742 /* CR0, CR4 writes must be intercepted for the same reasons as above. */
743 pVmcb->ctrl.u16InterceptWrCRx = RT_BIT(0) | RT_BIT(4);
744
745 /* Intercept all DRx reads and writes by default. Changed later on. */
746 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
747 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
748
749 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
750 pVmcb->ctrl.IntCtrl.n.u1VIrqMasking = 1;
751
752 /* Ignore the priority in the TPR. This is necessary for delivering PIC style (ExtInt) interrupts and we currently
753 deliver both PIC and APIC interrupts alike. See hmR0SvmInjectPendingEvent() */
754 pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR = 1;
755
756 /* Set IO and MSR bitmap permission bitmap physical addresses. */
757 pVmcb->ctrl.u64IOPMPhysAddr = g_HCPhysIOBitmap;
758 pVmcb->ctrl.u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
759
760 /* No LBR virtualization. */
761 pVmcb->ctrl.u64LBRVirt = 0;
762
763 /* Initially set all VMCB clean bits to 0 indicating that everything should be loaded from the VMCB in memory. */
764 pVmcb->ctrl.u64VmcbCleanBits = 0;
765
766 /* The host ASID MBZ, for the guest start with 1. */
767 pVmcb->ctrl.TLBCtrl.n.u32ASID = 1;
768
769 /*
770 * Setup the PAT MSR (applicable for Nested Paging only).
771 * The default value should be 0x0007040600070406ULL, but we want to treat all guest memory as WB,
772 * so choose type 6 for all PAT slots.
773 */
774 pVmcb->guest.u64GPAT = UINT64_C(0x0006060606060606);
775
776 /* Setup Nested Paging. This doesn't change throughout the execution time of the VM. */
777 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
778
779 /* Without Nested Paging, we need additionally intercepts. */
780 if (!pVM->hm.s.fNestedPaging)
781 {
782 /* CR3 reads/writes must be intercepted; our shadow values differ from the guest values. */
783 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(3);
784 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(3);
785
786 /* Intercept INVLPG and task switches (may change CR3, EFLAGS, LDT). */
787 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_INVLPG
788 | SVM_CTRL1_INTERCEPT_TASK_SWITCH;
789
790 /* Page faults must be intercepted to implement shadow paging. */
791 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
792 }
793
794#ifdef HMSVM_ALWAYS_TRAP_TASK_SWITCH
795 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_TASK_SWITCH;
796#endif
797
798 /* Apply the exceptions intercepts needed by the GIM provider. */
799 if (pVCpu->hm.s.fGIMTrapXcptUD)
800 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_UD);
801
802 /* Setup Pause Filter for guest pause-loop (spinlock) exiting. */
803 if (fUsePauseFilter)
804 {
805 pVmcb->ctrl.u16PauseFilterCount = pVM->hm.s.svm.cPauseFilter;
806 if (fPauseFilterThreshold)
807 pVmcb->ctrl.u16PauseFilterThreshold = pVM->hm.s.svm.cPauseFilterThresholdTicks;
808 }
809
810 /*
811 * The following MSRs are saved/restored automatically during the world-switch.
812 * Don't intercept guest read/write accesses to these MSRs.
813 */
814 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
815 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_CSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
816 hmR0SvmSetMsrPermission(pVCpu, MSR_K6_STAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
817 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_SF_MASK, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
818 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_FS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
819 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
820 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
821 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_CS, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
822 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_ESP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
823 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_EIP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
824 }
825
826 return VINF_SUCCESS;
827}
828
829
830/**
831 * Invalidates a guest page by guest virtual address.
832 *
833 * @returns VBox status code.
834 * @param pVM Pointer to the VM.
835 * @param pVCpu Pointer to the VMCPU.
836 * @param GCVirt Guest virtual address of the page to invalidate.
837 */
838VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
839{
840 AssertReturn(pVM, VERR_INVALID_PARAMETER);
841 Assert(pVM->hm.s.svm.fSupported);
842
843 bool fFlushPending = pVM->hm.s.svm.fAlwaysFlushTLB || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_FLUSH);
844
845 /* Skip it if a TLB flush is already pending. */
846 if (!fFlushPending)
847 {
848 Log4(("SVMR0InvalidatePage %RGv\n", GCVirt));
849
850 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
851 AssertMsgReturn(pVmcb, ("Invalid pVmcb!\n"), VERR_SVM_INVALID_PVMCB);
852
853#if HC_ARCH_BITS == 32
854 /* If we get a flush in 64-bit guest mode, then force a full TLB flush. INVLPGA takes only 32-bit addresses. */
855 if (CPUMIsGuestInLongMode(pVCpu))
856 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
857 else
858#endif
859 {
860 SVMR0InvlpgA(GCVirt, pVmcb->ctrl.TLBCtrl.n.u32ASID);
861 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
862 }
863 }
864 return VINF_SUCCESS;
865}
866
867
868/**
869 * Flushes the appropriate tagged-TLB entries.
870 *
871 * @param pVM Pointer to the VM.
872 * @param pVCpu Pointer to the VMCPU.
873 */
874static void hmR0SvmFlushTaggedTlb(PVMCPU pVCpu)
875{
876 PVM pVM = pVCpu->CTX_SUFF(pVM);
877 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
878 PHMGLOBALCPUINFO pCpu = HMR0GetCurrentCpu();
879
880 /*
881 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
882 * This can happen both for start & resume due to long jumps back to ring-3.
883 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
884 * so we cannot reuse the ASIDs without flushing.
885 */
886 bool fNewAsid = false;
887 Assert(pCpu->idCpu != NIL_RTCPUID);
888 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
889 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
890 {
891 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
892 pVCpu->hm.s.fForceTLBFlush = true;
893 fNewAsid = true;
894 }
895
896 /* Set TLB flush state as checked until we return from the world switch. */
897 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
898
899 /* Check for explicit TLB flushes. */
900 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
901 {
902 pVCpu->hm.s.fForceTLBFlush = true;
903 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
904 }
905
906 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
907
908 if (pVM->hm.s.svm.fAlwaysFlushTLB)
909 {
910 /*
911 * This is the AMD erratum 170. We need to flush the entire TLB for each world switch. Sad.
912 */
913 pCpu->uCurrentAsid = 1;
914 pVCpu->hm.s.uCurrentAsid = 1;
915 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
916 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
917
918 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
919 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
920 }
921 else if (pVCpu->hm.s.fForceTLBFlush)
922 {
923 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
924 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
925
926 if (fNewAsid)
927 {
928 ++pCpu->uCurrentAsid;
929 bool fHitASIDLimit = false;
930 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
931 {
932 pCpu->uCurrentAsid = 1; /* Wraparound at 1; host uses 0 */
933 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
934 fHitASIDLimit = true;
935
936 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
937 {
938 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
939 pCpu->fFlushAsidBeforeUse = true;
940 }
941 else
942 {
943 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
944 pCpu->fFlushAsidBeforeUse = false;
945 }
946 }
947
948 if ( !fHitASIDLimit
949 && pCpu->fFlushAsidBeforeUse)
950 {
951 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
952 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
953 else
954 {
955 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
956 pCpu->fFlushAsidBeforeUse = false;
957 }
958 }
959
960 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
961 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
962 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
963 }
964 else
965 {
966 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
967 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
968 else
969 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
970 }
971
972 pVCpu->hm.s.fForceTLBFlush = false;
973 }
974
975 /* Update VMCB with the ASID. */
976 if (pVmcb->ctrl.TLBCtrl.n.u32ASID != pVCpu->hm.s.uCurrentAsid)
977 {
978 pVmcb->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
979 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_ASID;
980 }
981
982 AssertMsg(pVCpu->hm.s.idLastCpu == pCpu->idCpu,
983 ("vcpu idLastCpu=%u pcpu idCpu=%u\n", pVCpu->hm.s.idLastCpu, pCpu->idCpu));
984 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
985 ("Flush count mismatch for cpu %u (%u vs %u)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
986 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
987 ("cpu%d uCurrentAsid = %x\n", pCpu->idCpu, pCpu->uCurrentAsid));
988 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
989 ("cpu%d VM uCurrentAsid = %x\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
990
991#ifdef VBOX_WITH_STATISTICS
992 if (pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
993 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
994 else if ( pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
995 || pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
996 {
997 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
998 }
999 else
1000 {
1001 Assert(pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_ENTIRE);
1002 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushEntire);
1003 }
1004#endif
1005}
1006
1007
1008/** @name 64-bit guest on 32-bit host OS helper functions.
1009 *
1010 * The host CPU is still 64-bit capable but the host OS is running in 32-bit
1011 * mode (code segment, paging). These wrappers/helpers perform the necessary
1012 * bits for the 32->64 switcher.
1013 *
1014 * @{ */
1015#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1016/**
1017 * Prepares for and executes VMRUN (64-bit guests on a 32-bit host).
1018 *
1019 * @returns VBox status code.
1020 * @param HCPhysVmcbHost Physical address of host VMCB.
1021 * @param HCPhysVmcb Physical address of the VMCB.
1022 * @param pCtx Pointer to the guest-CPU context.
1023 * @param pVM Pointer to the VM.
1024 * @param pVCpu Pointer to the VMCPU.
1025 */
1026DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVmcbHost, RTHCPHYS HCPhysVmcb, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
1027{
1028 uint32_t aParam[8];
1029 aParam[0] = (uint32_t)(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Lo. */
1030 aParam[1] = (uint32_t)(HCPhysVmcbHost >> 32); /* Param 1: HCPhysVmcbHost - Hi. */
1031 aParam[2] = (uint32_t)(HCPhysVmcb); /* Param 2: HCPhysVmcb - Lo. */
1032 aParam[3] = (uint32_t)(HCPhysVmcb >> 32); /* Param 2: HCPhysVmcb - Hi. */
1033 aParam[4] = VM_RC_ADDR(pVM, pVM);
1034 aParam[5] = 0;
1035 aParam[6] = VM_RC_ADDR(pVM, pVCpu);
1036 aParam[7] = 0;
1037
1038 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_SVMRCVMRun64, RT_ELEMENTS(aParam), &aParam[0]);
1039}
1040
1041
1042/**
1043 * Executes the specified VMRUN handler in 64-bit mode.
1044 *
1045 * @returns VBox status code.
1046 * @param pVM Pointer to the VM.
1047 * @param pVCpu Pointer to the VMCPU.
1048 * @param pCtx Pointer to the guest-CPU context.
1049 * @param enmOp The operation to perform.
1050 * @param cParams Number of parameters.
1051 * @param paParam Array of 32-bit parameters.
1052 */
1053VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp,
1054 uint32_t cParams, uint32_t *paParam)
1055{
1056 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
1057 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
1058
1059 /* Disable interrupts. */
1060 RTHCUINTREG uOldEFlags = ASMIntDisableFlags();
1061
1062#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
1063 RTCPUID idHostCpu = RTMpCpuId();
1064 CPUMR0SetLApic(pVCpu, idHostCpu);
1065#endif
1066
1067 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
1068 CPUMSetHyperEIP(pVCpu, enmOp);
1069 for (int i = (int)cParams - 1; i >= 0; i--)
1070 CPUMPushHyper(pVCpu, paParam[i]);
1071
1072 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
1073 /* Call the switcher. */
1074 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
1075 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
1076
1077 /* Restore interrupts. */
1078 ASMSetFlags(uOldEFlags);
1079 return rc;
1080}
1081
1082#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
1083/** @} */
1084
1085
1086/**
1087 * Adds an exception to the intercept exception bitmap in the VMCB and updates
1088 * the corresponding VMCB Clean bit.
1089 *
1090 * @param pVmcb Pointer to the VM control block.
1091 * @param u32Xcpt The value of the exception (X86_XCPT_*).
1092 */
1093DECLINLINE(void) hmR0SvmAddXcptIntercept(PSVMVMCB pVmcb, uint32_t u32Xcpt)
1094{
1095 if (!(pVmcb->ctrl.u32InterceptException & RT_BIT(u32Xcpt)))
1096 {
1097 pVmcb->ctrl.u32InterceptException |= RT_BIT(u32Xcpt);
1098 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1099 }
1100}
1101
1102
1103/**
1104 * Removes an exception from the intercept-exception bitmap in the VMCB and
1105 * updates the corresponding VMCB Clean bit.
1106 *
1107 * @param pVmcb Pointer to the VM control block.
1108 * @param u32Xcpt The value of the exception (X86_XCPT_*).
1109 */
1110DECLINLINE(void) hmR0SvmRemoveXcptIntercept(PSVMVMCB pVmcb, uint32_t u32Xcpt)
1111{
1112#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
1113 if (pVmcb->ctrl.u32InterceptException & RT_BIT(u32Xcpt))
1114 {
1115 pVmcb->ctrl.u32InterceptException &= ~RT_BIT(u32Xcpt);
1116 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1117 }
1118#endif
1119}
1120
1121
1122/**
1123 * Loads the guest CR0 control register into the guest-state area in the VMCB.
1124 * Although the guest CR0 is a separate field in the VMCB we have to consider
1125 * the FPU state itself which is shared between the host and the guest.
1126 *
1127 * @returns VBox status code.
1128 * @param pVM Pointer to the VMCPU.
1129 * @param pVmcb Pointer to the VM control block.
1130 * @param pCtx Pointer to the guest-CPU context.
1131 *
1132 * @remarks No-long-jump zone!!!
1133 */
1134static void hmR0SvmLoadSharedCR0(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1135{
1136 /*
1137 * Guest CR0.
1138 */
1139 PVM pVM = pVCpu->CTX_SUFF(pVM);
1140 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
1141 {
1142 uint64_t u64GuestCR0 = pCtx->cr0;
1143
1144 /* Always enable caching. */
1145 u64GuestCR0 &= ~(X86_CR0_CD | X86_CR0_NW);
1146
1147 /*
1148 * When Nested Paging is not available use shadow page tables and intercept #PFs (the latter done in SVMR0SetupVM()).
1149 */
1150 if (!pVM->hm.s.fNestedPaging)
1151 {
1152 u64GuestCR0 |= X86_CR0_PG; /* When Nested Paging is not available, use shadow page tables. */
1153 u64GuestCR0 |= X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF #VMEXIT. */
1154 }
1155
1156 /*
1157 * Guest FPU bits.
1158 */
1159 bool fInterceptNM = false;
1160 bool fInterceptMF = false;
1161 u64GuestCR0 |= X86_CR0_NE; /* Use internal x87 FPU exceptions handling rather than external interrupts. */
1162 if (CPUMIsGuestFPUStateActive(pVCpu))
1163 {
1164 /* Catch floating point exceptions if we need to report them to the guest in a different way. */
1165 if (!(pCtx->cr0 & X86_CR0_NE))
1166 {
1167 Log4(("hmR0SvmLoadGuestControlRegs: Intercepting Guest CR0.MP Old-style FPU handling!!!\n"));
1168 fInterceptMF = true;
1169 }
1170 }
1171 else
1172 {
1173 fInterceptNM = true; /* Guest FPU inactive, #VMEXIT on #NM for lazy FPU loading. */
1174 u64GuestCR0 |= X86_CR0_TS /* Guest can task switch quickly and do lazy FPU syncing. */
1175 | X86_CR0_MP; /* FWAIT/WAIT should not ignore CR0.TS and should generate #NM. */
1176 }
1177
1178 /*
1179 * Update the exception intercept bitmap.
1180 */
1181 if (fInterceptNM)
1182 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_NM);
1183 else
1184 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_NM);
1185
1186 if (fInterceptMF)
1187 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_MF);
1188 else
1189 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_MF);
1190
1191 pVmcb->guest.u64CR0 = u64GuestCR0;
1192 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1193 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR0);
1194 }
1195}
1196
1197
1198/**
1199 * Loads the guest control registers (CR2, CR3, CR4) into the VMCB.
1200 *
1201 * @returns VBox status code.
1202 * @param pVCpu Pointer to the VMCPU.
1203 * @param pVmcb Pointer to the VM control block.
1204 * @param pCtx Pointer to the guest-CPU context.
1205 *
1206 * @remarks No-long-jump zone!!!
1207 */
1208static int hmR0SvmLoadGuestControlRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1209{
1210 PVM pVM = pVCpu->CTX_SUFF(pVM);
1211
1212 /*
1213 * Guest CR2.
1214 */
1215 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR2))
1216 {
1217 pVmcb->guest.u64CR2 = pCtx->cr2;
1218 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CR2;
1219 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR2);
1220 }
1221
1222 /*
1223 * Guest CR3.
1224 */
1225 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR3))
1226 {
1227 if (pVM->hm.s.fNestedPaging)
1228 {
1229 PGMMODE enmShwPagingMode;
1230#if HC_ARCH_BITS == 32
1231 if (CPUMIsGuestInLongModeEx(pCtx))
1232 enmShwPagingMode = PGMMODE_AMD64_NX;
1233 else
1234#endif
1235 enmShwPagingMode = PGMGetHostMode(pVM);
1236
1237 pVmcb->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
1238 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1239 Assert(pVmcb->ctrl.u64NestedPagingCR3);
1240 pVmcb->guest.u64CR3 = pCtx->cr3;
1241 }
1242 else
1243 pVmcb->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
1244
1245 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1246 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR3);
1247 }
1248
1249 /*
1250 * Guest CR4.
1251 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
1252 */
1253 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR4))
1254 {
1255 uint64_t u64GuestCR4 = pCtx->cr4;
1256 if (!pVM->hm.s.fNestedPaging)
1257 {
1258 switch (pVCpu->hm.s.enmShadowMode)
1259 {
1260 case PGMMODE_REAL:
1261 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
1262 AssertFailed();
1263 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1264
1265 case PGMMODE_32_BIT: /* 32-bit paging. */
1266 u64GuestCR4 &= ~X86_CR4_PAE;
1267 break;
1268
1269 case PGMMODE_PAE: /* PAE paging. */
1270 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1271 /** Must use PAE paging as we could use physical memory > 4 GB */
1272 u64GuestCR4 |= X86_CR4_PAE;
1273 break;
1274
1275 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1276 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1277#ifdef VBOX_ENABLE_64_BITS_GUESTS
1278 break;
1279#else
1280 AssertFailed();
1281 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1282#endif
1283
1284 default: /* shut up gcc */
1285 AssertFailed();
1286 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1287 }
1288 }
1289
1290 pVmcb->guest.u64CR4 = u64GuestCR4;
1291 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1292
1293 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
1294 pVCpu->hm.s.fLoadSaveGuestXcr0 = (u64GuestCR4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
1295
1296 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR4);
1297 }
1298
1299 return VINF_SUCCESS;
1300}
1301
1302
1303/**
1304 * Loads the guest segment registers into the VMCB.
1305 *
1306 * @returns VBox status code.
1307 * @param pVCpu Pointer to the VMCPU.
1308 * @param pVmcb Pointer to the VM control block.
1309 * @param pCtx Pointer to the guest-CPU context.
1310 *
1311 * @remarks No-long-jump zone!!!
1312 */
1313static void hmR0SvmLoadGuestSegmentRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1314{
1315 /* Guest Segment registers: CS, SS, DS, ES, FS, GS. */
1316 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS))
1317 {
1318 HMSVM_LOAD_SEG_REG(CS, cs);
1319 HMSVM_LOAD_SEG_REG(SS, ss);
1320 HMSVM_LOAD_SEG_REG(DS, ds);
1321 HMSVM_LOAD_SEG_REG(ES, es);
1322 HMSVM_LOAD_SEG_REG(FS, fs);
1323 HMSVM_LOAD_SEG_REG(GS, gs);
1324
1325 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1326 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_SEG;
1327 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS);
1328 }
1329
1330 /* Guest TR. */
1331 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_TR))
1332 {
1333 HMSVM_LOAD_SEG_REG(TR, tr);
1334 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_TR);
1335 }
1336
1337 /* Guest LDTR. */
1338 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LDTR))
1339 {
1340 HMSVM_LOAD_SEG_REG(LDTR, ldtr);
1341 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LDTR);
1342 }
1343
1344 /* Guest GDTR. */
1345 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_GDTR))
1346 {
1347 pVmcb->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
1348 pVmcb->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
1349 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1350 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_GDTR);
1351 }
1352
1353 /* Guest IDTR. */
1354 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_IDTR))
1355 {
1356 pVmcb->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
1357 pVmcb->guest.IDTR.u64Base = pCtx->idtr.pIdt;
1358 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1359 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_IDTR);
1360 }
1361}
1362
1363
1364/**
1365 * Loads the guest MSRs into the VMCB.
1366 *
1367 * @param pVCpu Pointer to the VMCPU.
1368 * @param pVmcb Pointer to the VM control block.
1369 * @param pCtx Pointer to the guest-CPU context.
1370 *
1371 * @remarks No-long-jump zone!!!
1372 */
1373static void hmR0SvmLoadGuestMsrs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1374{
1375 /* Guest Sysenter MSRs. */
1376 pVmcb->guest.u64SysEnterCS = pCtx->SysEnter.cs;
1377 pVmcb->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
1378 pVmcb->guest.u64SysEnterESP = pCtx->SysEnter.esp;
1379
1380 /*
1381 * Guest EFER MSR.
1382 * AMD-V requires guest EFER.SVME to be set. Weird.
1383 * See AMD spec. 15.5.1 "Basic Operation" | "Canonicalization and Consistency Checks".
1384 */
1385 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_EFER_MSR))
1386 {
1387 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
1388 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1389 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
1390 }
1391
1392 /* 64-bit MSRs. */
1393 if (CPUMIsGuestInLongModeEx(pCtx))
1394 {
1395 pVmcb->guest.FS.u64Base = pCtx->fs.u64Base;
1396 pVmcb->guest.GS.u64Base = pCtx->gs.u64Base;
1397 }
1398 else
1399 {
1400 /* If the guest isn't in 64-bit mode, clear MSR_K6_LME bit from guest EFER otherwise AMD-V expects amd64 shadow paging. */
1401 if (pCtx->msrEFER & MSR_K6_EFER_LME)
1402 {
1403 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1404 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1405 }
1406 }
1407
1408
1409 /** @todo The following are used in 64-bit only (SYSCALL/SYSRET) but they might
1410 * be writable in 32-bit mode. Clarify with AMD spec. */
1411 pVmcb->guest.u64STAR = pCtx->msrSTAR;
1412 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR;
1413 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR;
1414 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK;
1415 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE;
1416}
1417
1418
1419/**
1420 * Loads the guest state into the VMCB and programs the necessary intercepts
1421 * accordingly.
1422 *
1423 * @param pVCpu Pointer to the VMCPU.
1424 * @param pVmcb Pointer to the VM control block.
1425 * @param pCtx Pointer to the guest-CPU context.
1426 *
1427 * @remarks No-long-jump zone!!!
1428 * @remarks Requires EFLAGS to be up-to-date in the VMCB!
1429 */
1430static void hmR0SvmLoadSharedDebugState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1431{
1432 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
1433 return;
1434 Assert((pCtx->dr[6] & X86_DR6_RA1_MASK) == X86_DR6_RA1_MASK); Assert((pCtx->dr[6] & X86_DR6_RAZ_MASK) == 0);
1435 Assert((pCtx->dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK); Assert((pCtx->dr[7] & X86_DR7_RAZ_MASK) == 0);
1436
1437 bool fInterceptDB = false;
1438 bool fInterceptMovDRx = false;
1439
1440 /*
1441 * Anyone single stepping on the host side? If so, we'll have to use the
1442 * trap flag in the guest EFLAGS since AMD-V doesn't have a trap flag on
1443 * the VMM level like the VT-x implementations does.
1444 */
1445 bool const fStepping = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
1446 if (fStepping)
1447 {
1448 pVCpu->hm.s.fClearTrapFlag = true;
1449 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1450 fInterceptDB = true;
1451 fInterceptMovDRx = true; /* Need clean DR6, no guest mess. */
1452 }
1453
1454 if ( fStepping
1455 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
1456 {
1457 /*
1458 * Use the combined guest and host DRx values found in the hypervisor
1459 * register set because the debugger has breakpoints active or someone
1460 * is single stepping on the host side.
1461 *
1462 * Note! DBGF expects a clean DR6 state before executing guest code.
1463 */
1464#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1465 if ( CPUMIsGuestInLongModeEx(pCtx)
1466 && !CPUMIsHyperDebugStateActivePending(pVCpu))
1467 {
1468 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1469 Assert(!CPUMIsGuestDebugStateActivePending(pVCpu));
1470 Assert(CPUMIsHyperDebugStateActivePending(pVCpu));
1471 }
1472 else
1473#endif
1474 if (!CPUMIsHyperDebugStateActive(pVCpu))
1475 {
1476 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1477 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1478 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1479 }
1480
1481 /* Update DR6 & DR7. (The other DRx values are handled by CPUM one way or the other.) */
1482 if ( pVmcb->guest.u64DR6 != X86_DR6_INIT_VAL
1483 || pVmcb->guest.u64DR7 != CPUMGetHyperDR7(pVCpu))
1484 {
1485 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1486 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
1487 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1488 pVCpu->hm.s.fUsingHyperDR7 = true;
1489 }
1490
1491 /** @todo If we cared, we could optimize to allow the guest to read registers
1492 * with the same values. */
1493 fInterceptDB = true;
1494 fInterceptMovDRx = true;
1495 Log5(("hmR0SvmLoadSharedDebugState: Loaded hyper DRx\n"));
1496 }
1497 else
1498 {
1499 /*
1500 * Update DR6, DR7 with the guest values if necessary.
1501 */
1502 if ( pVmcb->guest.u64DR7 != pCtx->dr[7]
1503 || pVmcb->guest.u64DR6 != pCtx->dr[6])
1504 {
1505 pVmcb->guest.u64DR7 = pCtx->dr[7];
1506 pVmcb->guest.u64DR6 = pCtx->dr[6];
1507 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1508 pVCpu->hm.s.fUsingHyperDR7 = false;
1509 }
1510
1511 /*
1512 * If the guest has enabled debug registers, we need to load them prior to
1513 * executing guest code so they'll trigger at the right time.
1514 */
1515 if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
1516 {
1517#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1518 if ( CPUMIsGuestInLongModeEx(pCtx)
1519 && !CPUMIsGuestDebugStateActivePending(pVCpu))
1520 {
1521 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
1522 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1523 Assert(!CPUMIsHyperDebugStateActivePending(pVCpu));
1524 Assert(CPUMIsGuestDebugStateActivePending(pVCpu));
1525 }
1526 else
1527#endif
1528 if (!CPUMIsGuestDebugStateActive(pVCpu))
1529 {
1530 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
1531 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1532 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1533 Assert(CPUMIsGuestDebugStateActive(pVCpu));
1534 }
1535 Log5(("hmR0SvmLoadSharedDebugState: Loaded guest DRx\n"));
1536 }
1537 /*
1538 * If no debugging enabled, we'll lazy load DR0-3. We don't need to
1539 * intercept #DB as DR6 is updated in the VMCB.
1540 */
1541#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1542 else if ( !CPUMIsGuestDebugStateActivePending(pVCpu)
1543 && !CPUMIsGuestDebugStateActive(pVCpu))
1544#else
1545 else if (!CPUMIsGuestDebugStateActive(pVCpu))
1546#endif
1547 {
1548 fInterceptMovDRx = true;
1549 }
1550 }
1551
1552 /*
1553 * Set up the intercepts.
1554 */
1555 if (fInterceptDB)
1556 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_DB);
1557 else
1558 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_DB);
1559
1560 if (fInterceptMovDRx)
1561 {
1562 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
1563 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
1564 {
1565 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
1566 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
1567 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1568 }
1569 }
1570 else
1571 {
1572 if ( pVmcb->ctrl.u16InterceptRdDRx
1573 || pVmcb->ctrl.u16InterceptWrDRx)
1574 {
1575 pVmcb->ctrl.u16InterceptRdDRx = 0;
1576 pVmcb->ctrl.u16InterceptWrDRx = 0;
1577 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1578 }
1579 }
1580
1581 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_DEBUG);
1582}
1583
1584
1585/**
1586 * Loads the guest APIC state (currently just the TPR).
1587 *
1588 * @returns VBox status code.
1589 * @param pVCpu Pointer to the VMCPU.
1590 * @param pVmcb Pointer to the VM control block.
1591 * @param pCtx Pointer to the guest-CPU context.
1592 */
1593static int hmR0SvmLoadGuestApicState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1594{
1595 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE))
1596 return VINF_SUCCESS;
1597
1598 bool fPendingIntr;
1599 uint8_t u8Tpr;
1600 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
1601 AssertRCReturn(rc, rc);
1602
1603 /* Assume that we need to trap all TPR accesses and thus need not check on
1604 every #VMEXIT if we should update the TPR. */
1605 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqMasking);
1606 pVCpu->hm.s.svm.fSyncVTpr = false;
1607
1608 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
1609 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive)
1610 {
1611 pCtx->msrLSTAR = u8Tpr;
1612
1613 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
1614 if (fPendingIntr)
1615 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
1616 else
1617 {
1618 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1619 pVCpu->hm.s.svm.fSyncVTpr = true;
1620 }
1621 }
1622 else
1623 {
1624 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
1625 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
1626
1627 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we can deliver the interrupt to the guest. */
1628 if (fPendingIntr)
1629 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1630 else
1631 {
1632 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1633 pVCpu->hm.s.svm.fSyncVTpr = true;
1634 }
1635
1636 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
1637 }
1638
1639 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
1640 return rc;
1641}
1642
1643
1644/**
1645 * Loads the exception interrupts required for guest execution in the VMCB.
1646 *
1647 * @returns VBox status code.
1648 * @param pVCpu Pointer to the VMCPU.
1649 * @param pVmcb Pointer to the VM control block.
1650 * @param pCtx Pointer to the guest-CPU context.
1651 */
1652static int hmR0SvmLoadGuestXcptIntercepts(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1653{
1654 int rc = VINF_SUCCESS;
1655 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
1656 {
1657 /* The remaining intercepts are handled elsewhere, e.g. in hmR0SvmLoadSharedCR0(). */
1658 if (pVCpu->hm.s.fGIMTrapXcptUD)
1659 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_UD);
1660 else
1661 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_UD);
1662 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
1663 }
1664 return rc;
1665}
1666
1667
1668/**
1669 * Sets up the appropriate function to run guest code.
1670 *
1671 * @returns VBox status code.
1672 * @param pVCpu Pointer to the VMCPU.
1673 * @param pCtx Pointer to the guest-CPU context.
1674 *
1675 * @remarks No-long-jump zone!!!
1676 */
1677static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pCtx)
1678{
1679 if (CPUMIsGuestInLongModeEx(pCtx))
1680 {
1681#ifndef VBOX_ENABLE_64_BITS_GUESTS
1682 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1683#endif
1684 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
1685#if HC_ARCH_BITS == 32
1686 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
1687 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
1688#else
1689 /* 64-bit host or hybrid host. */
1690 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1691#endif
1692 }
1693 else
1694 {
1695 /* Guest is not in long mode, use the 32-bit handler. */
1696 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1697 }
1698 return VINF_SUCCESS;
1699}
1700
1701
1702/**
1703 * Enters the AMD-V session.
1704 *
1705 * @returns VBox status code.
1706 * @param pVM Pointer to the VM.
1707 * @param pVCpu Pointer to the VMCPU.
1708 * @param pCpu Pointer to the CPU info struct.
1709 */
1710VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1711{
1712 AssertPtr(pVM);
1713 AssertPtr(pVCpu);
1714 Assert(pVM->hm.s.svm.fSupported);
1715 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1716 NOREF(pVM); NOREF(pCpu);
1717
1718 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
1719 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
1720
1721 pVCpu->hm.s.fLeaveDone = false;
1722 return VINF_SUCCESS;
1723}
1724
1725
1726/**
1727 * Thread-context callback for AMD-V.
1728 *
1729 * @param enmEvent The thread-context event.
1730 * @param pVCpu Pointer to the VMCPU.
1731 * @param fGlobalInit Whether global VT-x/AMD-V init. is used.
1732 * @thread EMT(pVCpu)
1733 */
1734VMMR0DECL(void) SVMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
1735{
1736 NOREF(fGlobalInit);
1737
1738 switch (enmEvent)
1739 {
1740 case RTTHREADCTXEVENT_OUT:
1741 {
1742 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1743 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
1744 VMCPU_ASSERT_EMT(pVCpu);
1745
1746 PVM pVM = pVCpu->CTX_SUFF(pVM);
1747 PCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
1748
1749 /* No longjmps (log-flush, locks) in this fragile context. */
1750 VMMRZCallRing3Disable(pVCpu);
1751
1752 if (!pVCpu->hm.s.fLeaveDone)
1753 {
1754 hmR0SvmLeave(pVM, pVCpu, pCtx);
1755 pVCpu->hm.s.fLeaveDone = true;
1756 }
1757
1758 /* Leave HM context, takes care of local init (term). */
1759 int rc = HMR0LeaveCpu(pVCpu);
1760 AssertRC(rc); NOREF(rc);
1761
1762 /* Restore longjmp state. */
1763 VMMRZCallRing3Enable(pVCpu);
1764 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
1765 break;
1766 }
1767
1768 case RTTHREADCTXEVENT_IN:
1769 {
1770 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1771 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
1772 VMCPU_ASSERT_EMT(pVCpu);
1773
1774 /* No longjmps (log-flush, locks) in this fragile context. */
1775 VMMRZCallRing3Disable(pVCpu);
1776
1777 /*
1778 * Initialize the bare minimum state required for HM. This takes care of
1779 * initializing AMD-V if necessary (onlined CPUs, local init etc.)
1780 */
1781 int rc = HMR0EnterCpu(pVCpu);
1782 AssertRC(rc); NOREF(rc);
1783 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
1784
1785 pVCpu->hm.s.fLeaveDone = false;
1786
1787 /* Restore longjmp state. */
1788 VMMRZCallRing3Enable(pVCpu);
1789 break;
1790 }
1791
1792 default:
1793 break;
1794 }
1795}
1796
1797
1798/**
1799 * Saves the host state.
1800 *
1801 * @returns VBox status code.
1802 * @param pVM Pointer to the VM.
1803 * @param pVCpu Pointer to the VMCPU.
1804 *
1805 * @remarks No-long-jump zone!!!
1806 */
1807VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
1808{
1809 NOREF(pVM);
1810 NOREF(pVCpu);
1811 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
1812 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT);
1813 return VINF_SUCCESS;
1814}
1815
1816
1817/**
1818 * Loads the guest state into the VMCB.
1819 *
1820 * The CPU state will be loaded from these fields on every successful VM-entry.
1821 * Also sets up the appropriate VMRUN function to execute guest code based on
1822 * the guest CPU mode.
1823 *
1824 * @returns VBox status code.
1825 * @param pVM Pointer to the VM.
1826 * @param pVCpu Pointer to the VMCPU.
1827 * @param pCtx Pointer to the guest-CPU context.
1828 *
1829 * @remarks No-long-jump zone!!!
1830 */
1831static int hmR0SvmLoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1832{
1833 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1834 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1835
1836 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
1837
1838 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
1839 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1840
1841 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
1842 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
1843
1844 pVmcb->guest.u64RIP = pCtx->rip;
1845 pVmcb->guest.u64RSP = pCtx->rsp;
1846 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
1847 pVmcb->guest.u64RAX = pCtx->rax;
1848
1849 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
1850 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1851
1852 rc = hmR0SvmLoadGuestXcptIntercepts(pVCpu, pVmcb, pCtx);
1853 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestXcptIntercepts! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1854
1855 rc = hmR0SvmSetupVMRunHandler(pVCpu, pCtx);
1856 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1857
1858 /* Clear any unused and reserved bits. */
1859 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
1860 | HM_CHANGED_GUEST_RSP
1861 | HM_CHANGED_GUEST_RFLAGS
1862 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
1863 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
1864 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
1865 | HM_CHANGED_GUEST_LAZY_MSRS /* Unused. */
1866 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
1867 | HM_CHANGED_SVM_RESERVED2
1868 | HM_CHANGED_SVM_RESERVED3
1869 | HM_CHANGED_SVM_RESERVED4);
1870
1871 /* All the guest state bits should be loaded except maybe the host context and/or shared host/guest bits. */
1872 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
1873 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
1874 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
1875
1876 Log4(("Load: CS:RIP=%04x:%RX64 EFL=%#x SS:RSP=%04x:%RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->eflags.u, pCtx->ss.Sel, pCtx->rsp));
1877 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
1878 return rc;
1879}
1880
1881
1882/**
1883 * Loads the state shared between the host and guest into the
1884 * VMCB.
1885 *
1886 * @param pVCpu Pointer to the VMCPU.
1887 * @param pVmcb Pointer to the VM control block.
1888 * @param pCtx Pointer to the guest-CPU context.
1889 *
1890 * @remarks No-long-jump zone!!!
1891 */
1892static void hmR0SvmLoadSharedState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1893{
1894 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1895 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1896
1897 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
1898 hmR0SvmLoadSharedCR0(pVCpu, pVmcb, pCtx);
1899
1900 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
1901 hmR0SvmLoadSharedDebugState(pVCpu, pVmcb, pCtx);
1902
1903 /* Unused on AMD-V. */
1904 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
1905
1906 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
1907 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
1908}
1909
1910
1911/**
1912 * Saves the entire guest state from the VMCB into the
1913 * guest-CPU context. Currently there is no residual state left in the CPU that
1914 * is not updated in the VMCB.
1915 *
1916 * @returns VBox status code.
1917 * @param pVCpu Pointer to the VMCPU.
1918 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1919 * out-of-sync. Make sure to update the required fields
1920 * before using them.
1921 */
1922static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1923{
1924 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1925
1926 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1927
1928 pMixedCtx->rip = pVmcb->guest.u64RIP;
1929 pMixedCtx->rsp = pVmcb->guest.u64RSP;
1930 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1931 pMixedCtx->rax = pVmcb->guest.u64RAX;
1932
1933 /*
1934 * Guest interrupt shadow.
1935 */
1936 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1937 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
1938 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1939 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1940
1941 /*
1942 * Guest Control registers: CR2, CR3 (handled at the end) - accesses to other control registers are always intercepted.
1943 */
1944 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
1945
1946 /*
1947 * Guest MSRs.
1948 */
1949 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1950 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1951 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1952 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1953 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1954 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1955 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1956 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1957
1958 /*
1959 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
1960 */
1961 HMSVM_SAVE_SEG_REG(CS, cs);
1962 HMSVM_SAVE_SEG_REG(SS, ss);
1963 HMSVM_SAVE_SEG_REG(DS, ds);
1964 HMSVM_SAVE_SEG_REG(ES, es);
1965 HMSVM_SAVE_SEG_REG(FS, fs);
1966 HMSVM_SAVE_SEG_REG(GS, gs);
1967
1968 /*
1969 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
1970 * register (yet).
1971 */
1972 /** @todo SELM might need to be fixed as it too should not care about the
1973 * granularity bit. See @bugref{6785}. */
1974 if ( !pMixedCtx->cs.Attr.n.u1Granularity
1975 && pMixedCtx->cs.Attr.n.u1Present
1976 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
1977 {
1978 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
1979 pMixedCtx->cs.Attr.n.u1Granularity = 1;
1980 }
1981
1982#ifdef VBOX_STRICT
1983# define HMSVM_ASSERT_SEG_GRANULARITY(reg) \
1984 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
1985 || ( pMixedCtx->reg.Attr.n.u1Granularity \
1986 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
1987 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
1988 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", pMixedCtx->reg.u32Limit, \
1989 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
1990
1991 HMSVM_ASSERT_SEG_GRANULARITY(cs);
1992 HMSVM_ASSERT_SEG_GRANULARITY(ss);
1993 HMSVM_ASSERT_SEG_GRANULARITY(ds);
1994 HMSVM_ASSERT_SEG_GRANULARITY(es);
1995 HMSVM_ASSERT_SEG_GRANULARITY(fs);
1996 HMSVM_ASSERT_SEG_GRANULARITY(gs);
1997
1998# undef HMSVM_ASSERT_SEL_GRANULARITY
1999#endif
2000
2001 /*
2002 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
2003 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
2004 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
2005 * See AMD spec. 15.5.1 "Basic operation".
2006 */
2007 Assert(!(pVmcb->guest.u8CPL & ~0x3));
2008 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
2009
2010 /*
2011 * Guest TR.
2012 * Fixup TR attributes so it's compatible with Intel. Important when saved-states are used
2013 * between Intel and AMD. See @bugref{6208#c39}.
2014 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2015 */
2016 HMSVM_SAVE_SEG_REG(TR, tr);
2017 if (pMixedCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2018 {
2019 if ( pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2020 || CPUMIsGuestInLongModeEx(pMixedCtx))
2021 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2022 else if (pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2023 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2024 }
2025
2026 /*
2027 * Guest Descriptor-Table registers.
2028 */
2029 HMSVM_SAVE_SEG_REG(LDTR, ldtr);
2030 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
2031 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
2032
2033 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
2034 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
2035
2036 /*
2037 * Guest Debug registers.
2038 */
2039 if (!pVCpu->hm.s.fUsingHyperDR7)
2040 {
2041 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
2042 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
2043 }
2044 else
2045 {
2046 Assert(pVmcb->guest.u64DR7 == CPUMGetHyperDR7(pVCpu));
2047 CPUMSetHyperDR6(pVCpu, pVmcb->guest.u64DR6);
2048 }
2049
2050 /*
2051 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
2052 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
2053 */
2054 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
2055 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
2056 {
2057 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
2058 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
2059 }
2060}
2061
2062
2063/**
2064 * Does the necessary state syncing before returning to ring-3 for any reason
2065 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
2066 *
2067 * @param pVM Pointer to the VM.
2068 * @param pVCpu Pointer to the VMCPU.
2069 * @param pMixedCtx Pointer to the guest-CPU context.
2070 *
2071 * @remarks No-long-jmp zone!!!
2072 */
2073static void hmR0SvmLeave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2074{
2075 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2076 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2077 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2078
2079 /*
2080 * !!! IMPORTANT !!!
2081 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2082 */
2083
2084 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
2085 if (CPUMIsGuestFPUStateActive(pVCpu))
2086 {
2087 CPUMR0SaveGuestFPU(pVM, pVCpu, pCtx);
2088 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
2089 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
2090 }
2091
2092 /*
2093 * Restore host debug registers if necessary and resync on next R0 reentry.
2094 */
2095#ifdef VBOX_STRICT
2096 if (CPUMIsHyperDebugStateActive(pVCpu))
2097 {
2098 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2099 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
2100 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
2101 }
2102#endif
2103 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */))
2104 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
2105
2106 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
2107 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
2108
2109 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
2110 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
2111 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
2112 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
2113 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2114
2115 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
2116}
2117
2118
2119/**
2120 * Leaves the AMD-V session.
2121 *
2122 * @returns VBox status code.
2123 * @param pVM Pointer to the VM.
2124 * @param pVCpu Pointer to the VMCPU.
2125 * @param pCtx Pointer to the guest-CPU context.
2126 */
2127static int hmR0SvmLeaveSession(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2128{
2129 HM_DISABLE_PREEMPT();
2130 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2131 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2132
2133 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
2134 and done this from the SVMR0ThreadCtxCallback(). */
2135 if (!pVCpu->hm.s.fLeaveDone)
2136 {
2137 hmR0SvmLeave(pVM, pVCpu, pCtx);
2138 pVCpu->hm.s.fLeaveDone = true;
2139 }
2140
2141 /*
2142 * !!! IMPORTANT !!!
2143 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2144 */
2145
2146 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2147 /* Deregister hook now that we've left HM context before re-enabling preemption. */
2148 VMMR0ThreadCtxHookDisable(pVCpu);
2149
2150 /* Leave HM context. This takes care of local init (term). */
2151 int rc = HMR0LeaveCpu(pVCpu);
2152
2153 HM_RESTORE_PREEMPT();
2154 return rc;
2155}
2156
2157
2158/**
2159 * Does the necessary state syncing before doing a longjmp to ring-3.
2160 *
2161 * @returns VBox status code.
2162 * @param pVM Pointer to the VM.
2163 * @param pVCpu Pointer to the VMCPU.
2164 * @param pCtx Pointer to the guest-CPU context.
2165 *
2166 * @remarks No-long-jmp zone!!!
2167 */
2168static int hmR0SvmLongJmpToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2169{
2170 return hmR0SvmLeaveSession(pVM, pVCpu, pCtx);
2171}
2172
2173
2174/**
2175 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
2176 * any remaining host state) before we longjump to ring-3 and possibly get
2177 * preempted.
2178 *
2179 * @param pVCpu Pointer to the VMCPU.
2180 * @param enmOperation The operation causing the ring-3 longjump.
2181 * @param pvUser The user argument (pointer to the possibly
2182 * out-of-date guest-CPU context).
2183 */
2184static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
2185{
2186 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
2187 {
2188 /*
2189 * !!! IMPORTANT !!!
2190 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
2191 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
2192 */
2193 VMMRZCallRing3RemoveNotification(pVCpu);
2194 VMMRZCallRing3Disable(pVCpu);
2195 HM_DISABLE_PREEMPT();
2196
2197 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
2198 if (CPUMIsGuestFPUStateActive(pVCpu))
2199 CPUMR0SaveGuestFPU(pVCpu->CTX_SUFF(pVM), pVCpu, (PCPUMCTX)pvUser);
2200
2201 /* Restore host debug registers if necessary and resync on next R0 reentry. */
2202 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
2203
2204 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
2205 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2206 VMMR0ThreadCtxHookDisable(pVCpu);
2207
2208 /* Leave HM context. This takes care of local init (term). */
2209 HMR0LeaveCpu(pVCpu);
2210
2211 HM_RESTORE_PREEMPT();
2212 return VINF_SUCCESS;
2213 }
2214
2215 Assert(pVCpu);
2216 Assert(pvUser);
2217 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2218 HMSVM_ASSERT_PREEMPT_SAFE();
2219
2220 VMMRZCallRing3Disable(pVCpu);
2221 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2222
2223 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
2224 int rc = hmR0SvmLongJmpToRing3(pVCpu->CTX_SUFF(pVM), pVCpu, (PCPUMCTX)pvUser);
2225 AssertRCReturn(rc, rc);
2226
2227 VMMRZCallRing3Enable(pVCpu);
2228 return VINF_SUCCESS;
2229}
2230
2231
2232/**
2233 * Take necessary actions before going back to ring-3.
2234 *
2235 * An action requires us to go back to ring-3. This function does the necessary
2236 * steps before we can safely return to ring-3. This is not the same as longjmps
2237 * to ring-3, this is voluntary.
2238 *
2239 * @param pVM Pointer to the VM.
2240 * @param pVCpu Pointer to the VMCPU.
2241 * @param pCtx Pointer to the guest-CPU context.
2242 * @param rcExit The reason for exiting to ring-3. Can be
2243 * VINF_VMM_UNKNOWN_RING3_CALL.
2244 */
2245static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
2246{
2247 Assert(pVM);
2248 Assert(pVCpu);
2249 Assert(pCtx);
2250 HMSVM_ASSERT_PREEMPT_SAFE();
2251
2252 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
2253 VMMRZCallRing3Disable(pVCpu);
2254 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
2255
2256 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
2257 if (pVCpu->hm.s.Event.fPending)
2258 {
2259 hmR0SvmPendingEventToTrpmTrap(pVCpu);
2260 Assert(!pVCpu->hm.s.Event.fPending);
2261 }
2262
2263 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
2264 and if we're injecting an event we should have a TRPM trap pending. */
2265 Assert(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu));
2266 Assert(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu));
2267
2268 /* Sync. the necessary state for going back to ring-3. */
2269 hmR0SvmLeaveSession(pVM, pVCpu, pCtx);
2270 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2271
2272 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2273 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
2274 | CPUM_CHANGED_LDTR
2275 | CPUM_CHANGED_GDTR
2276 | CPUM_CHANGED_IDTR
2277 | CPUM_CHANGED_TR
2278 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2279 if ( pVM->hm.s.fNestedPaging
2280 && CPUMIsGuestPagingEnabledEx(pCtx))
2281 {
2282 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2283 }
2284
2285 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
2286 if (rcExit != VINF_EM_RAW_INTERRUPT)
2287 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
2288
2289 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
2290
2291 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
2292 VMMRZCallRing3RemoveNotification(pVCpu);
2293 VMMRZCallRing3Enable(pVCpu);
2294}
2295
2296
2297/**
2298 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
2299 * intercepts.
2300 *
2301 * @param pVM The shared VM handle.
2302 * @param pVCpu Pointer to the VMCPU.
2303 *
2304 * @remarks No-long-jump zone!!!
2305 */
2306static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu)
2307{
2308 bool fParavirtTsc;
2309 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2310 bool fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &pVmcb->ctrl.u64TSCOffset, &fParavirtTsc);
2311 if (fCanUseRealTsc)
2312 {
2313 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
2314 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
2315 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
2316 }
2317 else
2318 {
2319 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
2320 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
2321 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
2322 }
2323 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2324
2325 /** @todo later optimize this to be done elsewhere and not before every
2326 * VM-entry. */
2327 if (fParavirtTsc)
2328 {
2329 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
2330 information before every VM-entry, hence disable it for performance sake. */
2331#if 0
2332 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
2333 AssertRC(rc);
2334#endif
2335 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
2336 }
2337}
2338
2339
2340/**
2341 * Sets an event as a pending event to be injected into the guest.
2342 *
2343 * @param pVCpu Pointer to the VMCPU.
2344 * @param pEvent Pointer to the SVM event.
2345 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
2346 * page-fault.
2347 *
2348 * @remarks Statistics counter assumes this is a guest event being reflected to
2349 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
2350 */
2351DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
2352{
2353 Assert(!pVCpu->hm.s.Event.fPending);
2354 Assert(pEvent->n.u1Valid);
2355
2356 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
2357 pVCpu->hm.s.Event.fPending = true;
2358 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
2359
2360 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2361 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2362
2363 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
2364}
2365
2366
2367/**
2368 * Injects an event into the guest upon VMRUN by updating the relevant field
2369 * in the VMCB.
2370 *
2371 * @param pVCpu Pointer to the VMCPU.
2372 * @param pVmcb Pointer to the guest VM control block.
2373 * @param pCtx Pointer to the guest-CPU context.
2374 * @param pEvent Pointer to the event.
2375 *
2376 * @remarks No-long-jump zone!!!
2377 * @remarks Requires CR0!
2378 */
2379DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
2380{
2381 NOREF(pVCpu); NOREF(pCtx);
2382
2383 pVmcb->ctrl.EventInject.u = pEvent->u;
2384 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
2385
2386 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2387 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2388}
2389
2390
2391
2392/**
2393 * Converts any TRPM trap into a pending HM event. This is typically used when
2394 * entering from ring-3 (not longjmp returns).
2395 *
2396 * @param pVCpu Pointer to the VMCPU.
2397 */
2398static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
2399{
2400 Assert(TRPMHasTrap(pVCpu));
2401 Assert(!pVCpu->hm.s.Event.fPending);
2402
2403 uint8_t uVector;
2404 TRPMEVENT enmTrpmEvent;
2405 RTGCUINT uErrCode;
2406 RTGCUINTPTR GCPtrFaultAddress;
2407 uint8_t cbInstr;
2408
2409 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
2410 AssertRC(rc);
2411
2412 SVMEVENT Event;
2413 Event.u = 0;
2414 Event.n.u1Valid = 1;
2415 Event.n.u8Vector = uVector;
2416
2417 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
2418 if (enmTrpmEvent == TRPM_TRAP)
2419 {
2420 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2421 switch (uVector)
2422 {
2423 case X86_XCPT_NMI:
2424 {
2425 Event.n.u3Type = SVM_EVENT_NMI;
2426 break;
2427 }
2428
2429 case X86_XCPT_PF:
2430 case X86_XCPT_DF:
2431 case X86_XCPT_TS:
2432 case X86_XCPT_NP:
2433 case X86_XCPT_SS:
2434 case X86_XCPT_GP:
2435 case X86_XCPT_AC:
2436 {
2437 Event.n.u1ErrorCodeValid = 1;
2438 Event.n.u32ErrorCode = uErrCode;
2439 break;
2440 }
2441 }
2442 }
2443 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
2444 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2445 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
2446 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
2447 else
2448 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
2449
2450 rc = TRPMResetTrap(pVCpu);
2451 AssertRC(rc);
2452
2453 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
2454 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
2455
2456 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
2457 STAM_COUNTER_DEC(&pVCpu->hm.s.StatInjectPendingReflect);
2458}
2459
2460
2461/**
2462 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
2463 * AMD-V to execute any instruction.
2464 *
2465 * @param pvCpu Pointer to the VMCPU.
2466 */
2467static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
2468{
2469 Assert(pVCpu->hm.s.Event.fPending);
2470 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
2471
2472 SVMEVENT Event;
2473 Event.u = pVCpu->hm.s.Event.u64IntInfo;
2474
2475 uint8_t uVector = Event.n.u8Vector;
2476 uint8_t uVectorType = Event.n.u3Type;
2477
2478 TRPMEVENT enmTrapType;
2479 switch (uVectorType)
2480 {
2481 case SVM_EVENT_EXTERNAL_IRQ:
2482 enmTrapType = TRPM_HARDWARE_INT;
2483 break;
2484 case SVM_EVENT_SOFTWARE_INT:
2485 enmTrapType = TRPM_SOFTWARE_INT;
2486 break;
2487 case SVM_EVENT_EXCEPTION:
2488 case SVM_EVENT_NMI:
2489 enmTrapType = TRPM_TRAP;
2490 break;
2491 default:
2492 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
2493 enmTrapType = TRPM_32BIT_HACK;
2494 break;
2495 }
2496
2497 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
2498
2499 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
2500 AssertRC(rc);
2501
2502 if (Event.n.u1ErrorCodeValid)
2503 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
2504
2505 if ( uVectorType == SVM_EVENT_EXCEPTION
2506 && uVector == X86_XCPT_PF)
2507 {
2508 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
2509 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
2510 }
2511 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
2512 {
2513 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
2514 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
2515 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
2516 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
2517 }
2518 pVCpu->hm.s.Event.fPending = false;
2519}
2520
2521
2522/**
2523 * Gets the guest's interrupt-shadow.
2524 *
2525 * @returns The guest's interrupt-shadow.
2526 * @param pVCpu Pointer to the VMCPU.
2527 * @param pCtx Pointer to the guest-CPU context.
2528 *
2529 * @remarks No-long-jump zone!!!
2530 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
2531 */
2532DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
2533{
2534 /*
2535 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
2536 * inhibit interrupts or clear any existing interrupt-inhibition.
2537 */
2538 uint32_t uIntrState = 0;
2539 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2540 {
2541 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2542 {
2543 /*
2544 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
2545 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
2546 */
2547 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2548 }
2549 else
2550 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
2551 }
2552 return uIntrState;
2553}
2554
2555
2556/**
2557 * Sets the virtual interrupt intercept control in the VMCB which
2558 * instructs AMD-V to cause a #VMEXIT as soon as the guest is in a state to
2559 * receive interrupts.
2560 *
2561 * @param pVmcb Pointer to the VM control block.
2562 */
2563DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
2564{
2565 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
2566 {
2567 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
2568 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
2569 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
2570 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
2571
2572 Log4(("Setting VINTR intercept\n"));
2573 }
2574}
2575
2576
2577/**
2578 * Sets the IRET intercept control in the VMCB which instructs AMD-V to cause a
2579 * #VMEXIT as soon as a guest starts executing an IRET. This is used to unblock
2580 * virtual NMIs.
2581 *
2582 * @param pVmcb Pointer to the VM control block.
2583 */
2584DECLINLINE(void) hmR0SvmSetIretIntercept(PSVMVMCB pVmcb)
2585{
2586 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_IRET))
2587 {
2588 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_IRET;
2589 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2590
2591 Log4(("Setting IRET intercept\n"));
2592 }
2593}
2594
2595
2596/**
2597 * Clears the IRET intercept control in the VMCB.
2598 *
2599 * @param pVmcb Pointer to the VM control block.
2600 */
2601DECLINLINE(void) hmR0SvmClearIretIntercept(PSVMVMCB pVmcb)
2602{
2603 if (pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_IRET)
2604 {
2605 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_IRET;
2606 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2607
2608 Log4(("Clearing IRET intercept\n"));
2609 }
2610}
2611
2612
2613/**
2614 * Evaluates the event to be delivered to the guest and sets it as the pending
2615 * event.
2616 *
2617 * @param pVCpu Pointer to the VMCPU.
2618 * @param pCtx Pointer to the guest-CPU context.
2619 */
2620static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2621{
2622 Assert(!pVCpu->hm.s.Event.fPending);
2623 Log4Func(("\n"));
2624
2625 bool const fIntShadow = RT_BOOL(hmR0SvmGetGuestIntrShadow(pVCpu, pCtx));
2626 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2627 bool const fBlockNmi = RT_BOOL(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS));
2628 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2629
2630 SVMEVENT Event;
2631 Event.u = 0;
2632 /** @todo SMI. SMIs take priority over NMIs. */
2633 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2634 {
2635 if (fBlockNmi)
2636 hmR0SvmSetIretIntercept(pVmcb);
2637 else if (fIntShadow)
2638 hmR0SvmSetVirtIntrIntercept(pVmcb);
2639 else
2640 {
2641 Log4(("Pending NMI\n"));
2642
2643 Event.n.u1Valid = 1;
2644 Event.n.u8Vector = X86_XCPT_NMI;
2645 Event.n.u3Type = SVM_EVENT_NMI;
2646
2647 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2648 hmR0SvmSetIretIntercept(pVmcb);
2649 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2650 }
2651 }
2652 else if (VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)))
2653 {
2654 /*
2655 * Check if the guest can receive external interrupts (PIC/APIC). Once we do PDMGetInterrupt() we -must- deliver
2656 * the interrupt ASAP. We must not execute any guest code until we inject the interrupt which is why it is
2657 * evaluated here and not set as pending, solely based on the force-flags.
2658 */
2659 if ( !fBlockInt
2660 && !fIntShadow)
2661 {
2662 uint8_t u8Interrupt;
2663 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2664 if (RT_SUCCESS(rc))
2665 {
2666 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2667
2668 Event.n.u1Valid = 1;
2669 Event.n.u8Vector = u8Interrupt;
2670 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2671
2672 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2673 }
2674 else
2675 {
2676 /** @todo Does this actually happen? If not turn it into an assertion. */
2677 Assert(!VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
2678 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2679 }
2680 }
2681 else
2682 hmR0SvmSetVirtIntrIntercept(pVmcb);
2683 }
2684}
2685
2686
2687/**
2688 * Injects any pending events into the guest if the guest is in a state to
2689 * receive them.
2690 *
2691 * @param pVCpu Pointer to the VMCPU.
2692 * @param pCtx Pointer to the guest-CPU context.
2693 */
2694static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2695{
2696 Assert(!TRPMHasTrap(pVCpu));
2697 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2698
2699 bool const fIntShadow = RT_BOOL(hmR0SvmGetGuestIntrShadow(pVCpu, pCtx));
2700 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2701 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2702
2703 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2704 {
2705 SVMEVENT Event;
2706 Event.u = pVCpu->hm.s.Event.u64IntInfo;
2707 Assert(Event.n.u1Valid);
2708#ifdef VBOX_STRICT
2709 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2710 {
2711 Assert(!fBlockInt);
2712 Assert(!fIntShadow);
2713 }
2714 else if (Event.n.u3Type == SVM_EVENT_NMI)
2715 Assert(!fIntShadow);
2716#endif
2717
2718 Log4(("Injecting pending HM event.\n"));
2719 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2720 pVCpu->hm.s.Event.fPending = false;
2721
2722#ifdef VBOX_WITH_STATISTICS
2723 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2724 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2725 else
2726 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2727#endif
2728 }
2729
2730 /* Update the guest interrupt shadow in the VMCB. */
2731 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2732 NOREF(fBlockInt);
2733}
2734
2735
2736/**
2737 * Reports world-switch error and dumps some useful debug info.
2738 *
2739 * @param pVM Pointer to the VM.
2740 * @param pVCpu Pointer to the VMCPU.
2741 * @param rcVMRun The return code from VMRUN (or
2742 * VERR_SVM_INVALID_GUEST_STATE for invalid
2743 * guest-state).
2744 * @param pCtx Pointer to the guest-CPU context.
2745 */
2746static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2747{
2748 NOREF(pCtx);
2749 HMSVM_ASSERT_PREEMPT_SAFE();
2750 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2751
2752 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2753 {
2754 HMDumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
2755#ifdef VBOX_STRICT
2756 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2757 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2758 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2759 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2760 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2761 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2762 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2763 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2764 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2765 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2766 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2767
2768 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2769 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2770 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2771
2772 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2773 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2774 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2775 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2776 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2777 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2778 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2779 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2780 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2781 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2782
2783 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2784 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2785 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2786 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2787 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2788 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2789 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2790 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2791 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2792 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2793 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2794 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2795 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2796 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2797 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2798 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2799 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2800
2801 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2802 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2803
2804 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2805 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2806 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2807 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2808 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2809 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2810 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2811 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2812 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2813 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2814 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2815 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2816 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2817 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2818 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2819 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2820 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2821 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2822 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2823 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2824
2825 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2826 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2827
2828 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2829 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2830 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2831 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2832
2833 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2834 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2835
2836 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2837 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2838 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2839 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2840
2841 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2842 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2843 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2844 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2845 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2846 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2847 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2848
2849 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2850 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2851 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2852 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2853
2854 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2855 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2856 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2857
2858 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2859 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2860 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2861 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2862 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2863 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2864 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2865 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2866 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2867 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2868 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2869 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2870#else
2871 NOREF(pVmcb);
2872#endif /* VBOX_STRICT */
2873 }
2874 else
2875 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2876}
2877
2878
2879/**
2880 * Check per-VM and per-VCPU force flag actions that require us to go back to
2881 * ring-3 for one reason or another.
2882 *
2883 * @returns VBox status code (information status code included).
2884 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2885 * ring-3.
2886 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2887 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2888 * interrupts)
2889 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2890 * all EMTs to be in ring-3.
2891 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2892 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2893 * to the EM loop.
2894 *
2895 * @param pVM Pointer to the VM.
2896 * @param pVCpu Pointer to the VMCPU.
2897 * @param pCtx Pointer to the guest-CPU context.
2898 */
2899static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2900{
2901 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2902
2903 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
2904 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2905 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
2906
2907 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
2908 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2909 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
2910 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2911 {
2912 /* Pending PGM C3 sync. */
2913 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2914 {
2915 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2916 if (rc != VINF_SUCCESS)
2917 {
2918 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2919 return rc;
2920 }
2921 }
2922
2923 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2924 /* -XXX- what was that about single stepping? */
2925 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2926 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2927 {
2928 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2929 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2930 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2931 return rc;
2932 }
2933
2934 /* Pending VM request packets, such as hardware interrupts. */
2935 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2936 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2937 {
2938 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2939 return VINF_EM_PENDING_REQUEST;
2940 }
2941
2942 /* Pending PGM pool flushes. */
2943 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2944 {
2945 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2946 return VINF_PGM_POOL_FLUSH_PENDING;
2947 }
2948
2949 /* Pending DMA requests. */
2950 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2951 {
2952 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2953 return VINF_EM_RAW_TO_R3;
2954 }
2955 }
2956
2957 return VINF_SUCCESS;
2958}
2959
2960
2961/**
2962 * Does the preparations before executing guest code in AMD-V.
2963 *
2964 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2965 * recompiler. We must be cautious what we do here regarding committing
2966 * guest-state information into the the VMCB assuming we assuredly execute the
2967 * guest in AMD-V. If we fall back to the recompiler after updating the VMCB and
2968 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2969 * that the recompiler can (and should) use them when it resumes guest
2970 * execution. Otherwise such operations must be done when we can no longer
2971 * exit to ring-3.
2972 *
2973 * @returns VBox status code (informational status codes included).
2974 * @retval VINF_SUCCESS if we can proceed with running the guest.
2975 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2976 *
2977 * @param pVM Pointer to the VM.
2978 * @param pVCpu Pointer to the VMCPU.
2979 * @param pCtx Pointer to the guest-CPU context.
2980 * @param pSvmTransient Pointer to the SVM transient structure.
2981 */
2982static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2983{
2984 HMSVM_ASSERT_PREEMPT_SAFE();
2985
2986 /* Check force flag actions that might require us to go back to ring-3. */
2987 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2988 if (rc != VINF_SUCCESS)
2989 return rc;
2990
2991 if (TRPMHasTrap(pVCpu))
2992 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2993 else if (!pVCpu->hm.s.Event.fPending)
2994 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
2995
2996#ifdef HMSVM_SYNC_FULL_GUEST_STATE
2997 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
2998#endif
2999
3000 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
3001 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
3002 AssertRCReturn(rc, rc);
3003 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
3004
3005 /*
3006 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
3007 * so we can update it on the way back if the guest changed the TPR.
3008 */
3009 if (pVCpu->hm.s.svm.fSyncVTpr)
3010 {
3011 if (pVM->hm.s.fTPRPatchingActive)
3012 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
3013 else
3014 {
3015 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3016 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
3017 }
3018 }
3019
3020 /*
3021 * No longjmps to ring-3 from this point on!!!
3022 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3023 * This also disables flushing of the R0-logger instance (if any).
3024 */
3025 VMMRZCallRing3Disable(pVCpu);
3026
3027 /*
3028 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
3029 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
3030 *
3031 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
3032 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
3033 *
3034 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
3035 * executing guest code.
3036 */
3037 pSvmTransient->fEFlags = ASMIntDisableFlags();
3038 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
3039 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
3040 {
3041 ASMSetFlags(pSvmTransient->fEFlags);
3042 VMMRZCallRing3Enable(pVCpu);
3043 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
3044 return VINF_EM_RAW_TO_R3;
3045 }
3046 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
3047 {
3048 ASMSetFlags(pSvmTransient->fEFlags);
3049 VMMRZCallRing3Enable(pVCpu);
3050 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
3051 return VINF_EM_RAW_INTERRUPT;
3052 }
3053
3054 /*
3055 * If we are injecting an NMI, we must set VMCPU_FF_BLOCK_NMIS only when we are going to execute
3056 * guest code for certain (no exits to ring-3). Otherwise, we could re-read the flag on re-entry into
3057 * AMD-V and conclude that NMI inhibition is active when we have not even delivered the NMI.
3058 *
3059 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set the
3060 * VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
3061 */
3062 if (pVCpu->hm.s.Event.fPending)
3063 {
3064 SVMEVENT Event;
3065 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3066 if ( Event.n.u1Valid
3067 && Event.n.u3Type == SVM_EVENT_NMI
3068 && Event.n.u8Vector == X86_XCPT_NMI
3069 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
3070 {
3071 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
3072 }
3073 }
3074
3075 return VINF_SUCCESS;
3076}
3077
3078
3079/**
3080 * Prepares to run guest code in AMD-V and we've committed to doing so. This
3081 * means there is no backing out to ring-3 or anywhere else at this
3082 * point.
3083 *
3084 * @param pVM Pointer to the VM.
3085 * @param pVCpu Pointer to the VMCPU.
3086 * @param pCtx Pointer to the guest-CPU context.
3087 * @param pSvmTransient Pointer to the SVM transient structure.
3088 *
3089 * @remarks Called with preemption disabled.
3090 * @remarks No-long-jump zone!!!
3091 */
3092static void hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3093{
3094 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3095 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3096 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3097
3098 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3099 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
3100
3101 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
3102
3103 if ( pVCpu->hm.s.fPreloadGuestFpu
3104 && !CPUMIsGuestFPUStateActive(pVCpu))
3105 {
3106 CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
3107 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
3108 }
3109
3110 /* Load the state shared between host and guest (FPU, debug). */
3111 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3112 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
3113 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
3114 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
3115 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
3116
3117 /* Setup TSC offsetting. */
3118 RTCPUID idCurrentCpu = HMR0GetCurrentCpu()->idCpu;
3119 if ( pSvmTransient->fUpdateTscOffsetting
3120 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
3121 {
3122 hmR0SvmUpdateTscOffsetting(pVM, pVCpu);
3123 pSvmTransient->fUpdateTscOffsetting = false;
3124 }
3125
3126 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
3127 if (idCurrentCpu != pVCpu->hm.s.idLastCpu)
3128 pVmcb->ctrl.u64VmcbCleanBits = 0;
3129
3130 /* Store status of the shared guest-host state at the time of VMRUN. */
3131#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
3132 if (CPUMIsGuestInLongModeEx(pCtx))
3133 {
3134 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
3135 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
3136 }
3137 else
3138#endif
3139 {
3140 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
3141 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
3142 }
3143 pSvmTransient->fWasGuestFPUStateActive = CPUMIsGuestFPUStateActive(pVCpu);
3144
3145 /* Flush the appropriate tagged-TLB entries. */
3146 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
3147 hmR0SvmFlushTaggedTlb(pVCpu);
3148 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
3149
3150 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
3151
3152 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
3153 to start executing. */
3154
3155 /*
3156 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
3157 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
3158 *
3159 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
3160 */
3161 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
3162 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
3163 {
3164 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
3165 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
3166 uint64_t u64GuestTscAux = CPUMR0GetGuestTscAux(pVCpu);
3167 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
3168 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
3169 pSvmTransient->fRestoreTscAuxMsr = true;
3170 }
3171 else
3172 {
3173 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
3174 pSvmTransient->fRestoreTscAuxMsr = false;
3175 }
3176
3177 /* If VMCB Clean bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
3178 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
3179 pVmcb->ctrl.u64VmcbCleanBits = 0;
3180}
3181
3182
3183/**
3184 * Wrapper for running the guest code in AMD-V.
3185 *
3186 * @returns VBox strict status code.
3187 * @param pVM Pointer to the VM.
3188 * @param pVCpu Pointer to the VMCPU.
3189 * @param pCtx Pointer to the guest-CPU context.
3190 *
3191 * @remarks No-long-jump zone!!!
3192 */
3193DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3194{
3195 /*
3196 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
3197 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
3198 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
3199 */
3200#ifdef VBOX_WITH_KERNEL_USING_XMM
3201 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
3202 pVCpu->hm.s.svm.pfnVMRun);
3203#else
3204 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
3205#endif
3206}
3207
3208
3209/**
3210 * Performs some essential restoration of state after running guest code in
3211 * AMD-V.
3212 *
3213 * @param pVM Pointer to the VM.
3214 * @param pVCpu Pointer to the VMCPU.
3215 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
3216 * out-of-sync. Make sure to update the required fields
3217 * before using them.
3218 * @param pSvmTransient Pointer to the SVM transient structure.
3219 * @param rcVMRun Return code of VMRUN.
3220 *
3221 * @remarks Called with interrupts disabled.
3222 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
3223 * unconditionally when it is safe to do so.
3224 */
3225static void hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
3226{
3227 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3228
3229 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
3230 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
3231
3232 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3233 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
3234
3235 if (pSvmTransient->fRestoreTscAuxMsr)
3236 {
3237 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
3238 CPUMR0SetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
3239 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
3240 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
3241 }
3242
3243 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
3244 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset);
3245
3246 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
3247 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
3248 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3249
3250 Assert(!(ASMGetFlags() & X86_EFL_IF));
3251 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
3252 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
3253
3254 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
3255 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
3256 {
3257 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
3258 return;
3259 }
3260
3261 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
3262 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmcb->ctrl.u64ExitCode); /* Update the #VMEXIT history array. */
3263 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
3264 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
3265
3266 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
3267
3268 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
3269 {
3270 if (pVCpu->hm.s.svm.fSyncVTpr)
3271 {
3272 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
3273 if ( pVM->hm.s.fTPRPatchingActive
3274 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
3275 {
3276 int rc = PDMApicSetTPR(pVCpu, pMixedCtx->msrLSTAR & 0xff);
3277 AssertRC(rc);
3278 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3279 }
3280 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
3281 {
3282 int rc = PDMApicSetTPR(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
3283 AssertRC(rc);
3284 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3285 }
3286 }
3287 }
3288}
3289
3290
3291/**
3292 * Runs the guest code using AMD-V.
3293 *
3294 * @returns VBox status code.
3295 * @param pVM Pointer to the VM.
3296 * @param pVCpu Pointer to the VMCPU.
3297 */
3298static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3299{
3300 SVMTRANSIENT SvmTransient;
3301 SvmTransient.fUpdateTscOffsetting = true;
3302 uint32_t cLoops = 0;
3303 int rc = VERR_INTERNAL_ERROR_5;
3304
3305 for (;; cLoops++)
3306 {
3307 Assert(!HMR0SuspendPending());
3308 HMSVM_ASSERT_CPU_SAFE();
3309
3310 /* Preparatory work for running guest code, this may force us to return
3311 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3312 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3313 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3314 if (rc != VINF_SUCCESS)
3315 break;
3316
3317 /*
3318 * No longjmps to ring-3 from this point on!!!
3319 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3320 * This also disables flushing of the R0-logger instance (if any).
3321 */
3322 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3323 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3324
3325 /* Restore any residual host-state and save any bits shared between host
3326 and guest into the guest-CPU state. Re-enables interrupts! */
3327 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3328
3329 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3330 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3331 {
3332 if (rc == VINF_SUCCESS)
3333 rc = VERR_SVM_INVALID_GUEST_STATE;
3334 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3335 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3336 break;
3337 }
3338
3339 /* Handle the #VMEXIT. */
3340 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3341 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3342 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb);
3343 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3344 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3345 if (rc != VINF_SUCCESS)
3346 break;
3347 if (cLoops > pVM->hm.s.cMaxResumeLoops)
3348 {
3349 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
3350 rc = VINF_EM_RAW_INTERRUPT;
3351 break;
3352 }
3353 }
3354
3355 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3356 return rc;
3357}
3358
3359
3360/**
3361 * Runs the guest code using AMD-V in single step mode.
3362 *
3363 * @returns VBox status code.
3364 * @param pVM Pointer to the VM.
3365 * @param pVCpu Pointer to the VMCPU.
3366 * @param pCtx Pointer to the guest-CPU context.
3367 */
3368static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3369{
3370 SVMTRANSIENT SvmTransient;
3371 SvmTransient.fUpdateTscOffsetting = true;
3372 uint32_t cLoops = 0;
3373 int rc = VERR_INTERNAL_ERROR_5;
3374 uint16_t uCsStart = pCtx->cs.Sel;
3375 uint64_t uRipStart = pCtx->rip;
3376
3377 for (;; cLoops++)
3378 {
3379 Assert(!HMR0SuspendPending());
3380 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
3381 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
3382 (unsigned)RTMpCpuId(), cLoops));
3383
3384 /* Preparatory work for running guest code, this may force us to return
3385 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3386 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3387 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3388 if (rc != VINF_SUCCESS)
3389 break;
3390
3391 /*
3392 * No longjmps to ring-3 from this point on!!!
3393 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3394 * This also disables flushing of the R0-logger instance (if any).
3395 */
3396 VMMRZCallRing3Disable(pVCpu);
3397 VMMRZCallRing3RemoveNotification(pVCpu);
3398 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3399
3400 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3401
3402 /*
3403 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
3404 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
3405 */
3406 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3407 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3408 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3409 {
3410 if (rc == VINF_SUCCESS)
3411 rc = VERR_SVM_INVALID_GUEST_STATE;
3412 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3413 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3414 return rc;
3415 }
3416
3417 /* Handle the #VMEXIT. */
3418 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3419 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3420 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb);
3421 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3422 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3423 if (rc != VINF_SUCCESS)
3424 break;
3425 if (cLoops > pVM->hm.s.cMaxResumeLoops)
3426 {
3427 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
3428 rc = VINF_EM_RAW_INTERRUPT;
3429 break;
3430 }
3431
3432 /*
3433 * Did the RIP change, if so, consider it a single step.
3434 * Otherwise, make sure one of the TFs gets set.
3435 */
3436 if ( pCtx->rip != uRipStart
3437 || pCtx->cs.Sel != uCsStart)
3438 {
3439 rc = VINF_EM_DBG_STEPPED;
3440 break;
3441 }
3442 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
3443 }
3444
3445 /*
3446 * Clear the X86_EFL_TF if necessary.
3447 */
3448 if (pVCpu->hm.s.fClearTrapFlag)
3449 {
3450 pVCpu->hm.s.fClearTrapFlag = false;
3451 pCtx->eflags.Bits.u1TF = 0;
3452 }
3453
3454 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3455 return rc;
3456}
3457
3458
3459/**
3460 * Runs the guest code using AMD-V.
3461 *
3462 * @returns VBox status code.
3463 * @param pVM Pointer to the VM.
3464 * @param pVCpu Pointer to the VMCPU.
3465 * @param pCtx Pointer to the guest-CPU context.
3466 */
3467VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3468{
3469 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3470 HMSVM_ASSERT_PREEMPT_SAFE();
3471 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
3472
3473 int rc;
3474 if (!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu))
3475 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx);
3476 else
3477 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx);
3478
3479 if (rc == VERR_EM_INTERPRETER)
3480 rc = VINF_EM_RAW_EMULATE_INSTR;
3481 else if (rc == VINF_EM_RESET)
3482 rc = VINF_EM_TRIPLE_FAULT;
3483
3484 /* Prepare to return to ring-3. This will remove longjmp notifications. */
3485 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
3486 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
3487 return rc;
3488}
3489
3490
3491/**
3492 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
3493 *
3494 * @returns VBox status code (informational status codes included).
3495 * @param pVCpu Pointer to the VMCPU.
3496 * @param pCtx Pointer to the guest-CPU context.
3497 * @param pSvmTransient Pointer to the SVM transient structure.
3498 */
3499DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3500{
3501 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
3502 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
3503
3504 /*
3505 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs for most guests under
3506 * normal workloads (for some definition of "normal").
3507 */
3508 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
3509 switch (pSvmTransient->u64ExitCode)
3510 {
3511 case SVM_EXIT_NPF:
3512 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
3513
3514 case SVM_EXIT_IOIO:
3515 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
3516
3517 case SVM_EXIT_RDTSC:
3518 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
3519
3520 case SVM_EXIT_RDTSCP:
3521 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
3522
3523 case SVM_EXIT_CPUID:
3524 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
3525
3526 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
3527 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
3528
3529 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
3530 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
3531
3532 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3533 return hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient);
3534
3535 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
3536 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
3537
3538 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
3539 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
3540
3541 case SVM_EXIT_MONITOR:
3542 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
3543
3544 case SVM_EXIT_MWAIT:
3545 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
3546
3547 case SVM_EXIT_HLT:
3548 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
3549
3550 case SVM_EXIT_READ_CR0:
3551 case SVM_EXIT_READ_CR3:
3552 case SVM_EXIT_READ_CR4:
3553 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
3554
3555 case SVM_EXIT_WRITE_CR0:
3556 case SVM_EXIT_WRITE_CR3:
3557 case SVM_EXIT_WRITE_CR4:
3558 case SVM_EXIT_WRITE_CR8:
3559 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
3560
3561 case SVM_EXIT_PAUSE:
3562 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
3563
3564 case SVM_EXIT_VMMCALL:
3565 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3566
3567 case SVM_EXIT_VINTR:
3568 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
3569
3570 case SVM_EXIT_INTR:
3571 case SVM_EXIT_FERR_FREEZE:
3572 case SVM_EXIT_NMI:
3573 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
3574
3575 case SVM_EXIT_MSR:
3576 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
3577
3578 case SVM_EXIT_INVLPG:
3579 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
3580
3581 case SVM_EXIT_WBINVD:
3582 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
3583
3584 case SVM_EXIT_INVD:
3585 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
3586
3587 case SVM_EXIT_RDPMC:
3588 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
3589
3590 default:
3591 {
3592 switch (pSvmTransient->u64ExitCode)
3593 {
3594 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
3595 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
3596 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
3597 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
3598 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3599
3600 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
3601 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
3602 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3603 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3604 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3605
3606 case SVM_EXIT_XSETBV:
3607 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
3608
3609 case SVM_EXIT_TASK_SWITCH:
3610 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3611
3612 case SVM_EXIT_IRET:
3613 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
3614
3615 case SVM_EXIT_SHUTDOWN:
3616 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3617
3618 case SVM_EXIT_SMI:
3619 case SVM_EXIT_INIT:
3620 {
3621 /*
3622 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3623 * we want to know about it so log the exit code and bail.
3624 */
3625 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3626 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3627 return VERR_SVM_UNEXPECTED_EXIT;
3628 }
3629
3630 case SVM_EXIT_INVLPGA:
3631 case SVM_EXIT_RSM:
3632 case SVM_EXIT_VMRUN:
3633 case SVM_EXIT_VMLOAD:
3634 case SVM_EXIT_VMSAVE:
3635 case SVM_EXIT_STGI:
3636 case SVM_EXIT_CLGI:
3637 case SVM_EXIT_SKINIT:
3638 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3639
3640#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3641 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3642 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3643 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3644 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3645 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3646 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3647 /* case SVM_EXIT_EXCEPTION_6: */ /* X86_XCPT_UD - Handled above. */
3648 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3649 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3650 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3651 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3652 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3653 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3654 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3655 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3656 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3657 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3658 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3659 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3660 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3661 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3662 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3663 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3664 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3665 {
3666 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3667 SVMEVENT Event;
3668 Event.u = 0;
3669 Event.n.u1Valid = 1;
3670 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3671 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3672
3673 switch (Event.n.u8Vector)
3674 {
3675 case X86_XCPT_DE:
3676 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3677 break;
3678
3679 case X86_XCPT_BP:
3680 /** Saves the wrong EIP on the stack (pointing to the int3) instead of the
3681 * next instruction. */
3682 /** @todo Investigate this later. */
3683 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
3684 break;
3685
3686 case X86_XCPT_NP:
3687 Event.n.u1ErrorCodeValid = 1;
3688 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3689 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3690 break;
3691
3692 case X86_XCPT_SS:
3693 Event.n.u1ErrorCodeValid = 1;
3694 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3695 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3696 break;
3697
3698 case X86_XCPT_GP:
3699 Event.n.u1ErrorCodeValid = 1;
3700 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3701 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3702 break;
3703
3704 default:
3705 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3706 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3707 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3708 }
3709
3710 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3711 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3712 return VINF_SUCCESS;
3713 }
3714#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3715
3716 default:
3717 {
3718 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3719 pVCpu->hm.s.u32HMError = u32ExitCode;
3720 return VERR_SVM_UNKNOWN_EXIT;
3721 }
3722 }
3723 }
3724 }
3725 return VERR_INTERNAL_ERROR_5; /* Should never happen. */
3726}
3727
3728
3729#ifdef DEBUG
3730/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3731# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3732 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3733
3734# define HMSVM_ASSERT_PREEMPT_CPUID() \
3735 do \
3736 { \
3737 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3738 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3739 } while (0)
3740
3741# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3742 do { \
3743 AssertPtr(pVCpu); \
3744 AssertPtr(pCtx); \
3745 AssertPtr(pSvmTransient); \
3746 Assert(ASMIntAreEnabled()); \
3747 HMSVM_ASSERT_PREEMPT_SAFE(); \
3748 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3749 Log4Func(("vcpu[%u] -v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-\n", (uint32_t)pVCpu->idCpu)); \
3750 HMSVM_ASSERT_PREEMPT_SAFE(); \
3751 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3752 HMSVM_ASSERT_PREEMPT_CPUID(); \
3753 } while (0)
3754#else /* Release builds */
3755# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
3756#endif
3757
3758
3759/**
3760 * Worker for hmR0SvmInterpretInvlpg().
3761 *
3762 * @return VBox status code.
3763 * @param pVCpu Pointer to the VMCPU.
3764 * @param pCpu Pointer to the disassembler state.
3765 * @param pCtx The guest CPU context.
3766 */
3767static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
3768{
3769 DISQPVPARAMVAL Param1;
3770 RTGCPTR GCPtrPage;
3771
3772 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3773 if (RT_FAILURE(rc))
3774 return VERR_EM_INTERPRETER;
3775
3776 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3777 || Param1.type == DISQPV_TYPE_ADDRESS)
3778 {
3779 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3780 return VERR_EM_INTERPRETER;
3781
3782 GCPtrPage = Param1.val.val64;
3783 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
3784 rc = VBOXSTRICTRC_VAL(rc2);
3785 }
3786 else
3787 {
3788 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3789 rc = VERR_EM_INTERPRETER;
3790 }
3791
3792 return rc;
3793}
3794
3795
3796/**
3797 * Interprets INVLPG.
3798 *
3799 * @returns VBox status code.
3800 * @retval VINF_* Scheduling instructions.
3801 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3802 * @retval VERR_* Fatal errors.
3803 *
3804 * @param pVM Pointer to the VM.
3805 * @param pCtx The guest CPU context.
3806 *
3807 * @remarks Updates the RIP if the instruction was executed successfully.
3808 */
3809static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3810{
3811 /* Only allow 32 & 64 bit code. */
3812 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3813 {
3814 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3815 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3816 if ( RT_SUCCESS(rc)
3817 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3818 {
3819 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
3820 if (RT_SUCCESS(rc))
3821 pCtx->rip += pDis->cbInstr;
3822 return rc;
3823 }
3824 else
3825 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3826 }
3827 return VERR_EM_INTERPRETER;
3828}
3829
3830
3831/**
3832 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
3833 *
3834 * @param pVCpu Pointer to the VMCPU.
3835 */
3836DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3837{
3838 SVMEVENT Event;
3839 Event.u = 0;
3840 Event.n.u1Valid = 1;
3841 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3842 Event.n.u8Vector = X86_XCPT_UD;
3843 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3844}
3845
3846
3847/**
3848 * Sets a debug (#DB) exception as pending-for-injection into the VM.
3849 *
3850 * @param pVCpu Pointer to the VMCPU.
3851 */
3852DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3853{
3854 SVMEVENT Event;
3855 Event.u = 0;
3856 Event.n.u1Valid = 1;
3857 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3858 Event.n.u8Vector = X86_XCPT_DB;
3859 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3860}
3861
3862
3863/**
3864 * Sets a page fault (#PF) exception as pending-for-injection into the VM.
3865 *
3866 * @param pVCpu Pointer to the VMCPU.
3867 * @param pCtx Pointer to the guest-CPU context.
3868 * @param u32ErrCode The error-code for the page-fault.
3869 * @param uFaultAddress The page fault address (CR2).
3870 *
3871 * @remarks This updates the guest CR2 with @a uFaultAddress!
3872 */
3873DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3874{
3875 SVMEVENT Event;
3876 Event.u = 0;
3877 Event.n.u1Valid = 1;
3878 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3879 Event.n.u8Vector = X86_XCPT_PF;
3880 Event.n.u1ErrorCodeValid = 1;
3881 Event.n.u32ErrorCode = u32ErrCode;
3882
3883 /* Update CR2 of the guest. */
3884 if (pCtx->cr2 != uFaultAddress)
3885 {
3886 pCtx->cr2 = uFaultAddress;
3887 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3888 }
3889
3890 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3891}
3892
3893
3894/**
3895 * Sets a device-not-available (#NM) exception as pending-for-injection into the
3896 * VM.
3897 *
3898 * @param pVCpu Pointer to the VMCPU.
3899 */
3900DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3901{
3902 SVMEVENT Event;
3903 Event.u = 0;
3904 Event.n.u1Valid = 1;
3905 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3906 Event.n.u8Vector = X86_XCPT_NM;
3907 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3908}
3909
3910
3911/**
3912 * Sets a math-fault (#MF) exception as pending-for-injection into the VM.
3913 *
3914 * @param pVCpu Pointer to the VMCPU.
3915 */
3916DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3917{
3918 SVMEVENT Event;
3919 Event.u = 0;
3920 Event.n.u1Valid = 1;
3921 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3922 Event.n.u8Vector = X86_XCPT_MF;
3923 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3924}
3925
3926
3927/**
3928 * Sets a double fault (#DF) exception as pending-for-injection into the VM.
3929 *
3930 * @param pVCpu Pointer to the VMCPU.
3931 */
3932DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3933{
3934 SVMEVENT Event;
3935 Event.u = 0;
3936 Event.n.u1Valid = 1;
3937 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3938 Event.n.u8Vector = X86_XCPT_DF;
3939 Event.n.u1ErrorCodeValid = 1;
3940 Event.n.u32ErrorCode = 0;
3941 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3942}
3943
3944
3945/**
3946 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3947 * guests. This simply looks up the patch record at EIP and does the required.
3948 *
3949 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3950 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3951 * TPR). See hmR3ReplaceTprInstr() for the details.
3952 *
3953 * @returns VBox status code.
3954 * @retval VINF_SUCCESS if the access was handled successfully.
3955 * @retval VERR_NOT_FOUND if no patch record for this RIP could be found.
3956 * @retval VERR_SVM_UNEXPECTED_PATCH_TYPE if the found patch type is invalid.
3957 *
3958 * @param pVM Pointer to the VM.
3959 * @param pVCpu Pointer to the VMCPU.
3960 * @param pCtx Pointer to the guest-CPU context.
3961 */
3962static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3963{
3964 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3965
3966 /*
3967 * We do this in a loop as we increment the RIP after a successful emulation
3968 * and the new RIP may be a patched instruction which needs emulation as well.
3969 */
3970 bool fPatchFound = false;
3971 for (;;)
3972 {
3973 bool fPending;
3974 uint8_t u8Tpr;
3975
3976 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
3977 if (!pPatch)
3978 break;
3979
3980 fPatchFound = true;
3981 switch (pPatch->enmType)
3982 {
3983 case HMTPRINSTR_READ:
3984 {
3985 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
3986 AssertRC(rc);
3987
3988 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
3989 AssertRC(rc);
3990 pCtx->rip += pPatch->cbOp;
3991 break;
3992 }
3993
3994 case HMTPRINSTR_WRITE_REG:
3995 case HMTPRINSTR_WRITE_IMM:
3996 {
3997 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
3998 {
3999 uint32_t u32Val;
4000 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
4001 AssertRC(rc);
4002 u8Tpr = u32Val;
4003 }
4004 else
4005 u8Tpr = (uint8_t)pPatch->uSrcOperand;
4006
4007 int rc2 = PDMApicSetTPR(pVCpu, u8Tpr);
4008 AssertRC(rc2);
4009 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4010
4011 pCtx->rip += pPatch->cbOp;
4012 break;
4013 }
4014
4015 default:
4016 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
4017 pVCpu->hm.s.u32HMError = pPatch->enmType;
4018 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
4019 }
4020 }
4021
4022 if (fPatchFound)
4023 return VINF_SUCCESS;
4024 return VERR_NOT_FOUND;
4025}
4026
4027
4028/**
4029 * Determines if an exception is a contributory exception.
4030 *
4031 * Contributory exceptions are ones which can cause double-faults unless the
4032 * original exception was a benign exception. Page-fault is intentionally not
4033 * included here as it's a conditional contributory exception.
4034 *
4035 * @returns true if the exception is contributory, false otherwise.
4036 * @param uVector The exception vector.
4037 */
4038DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
4039{
4040 switch (uVector)
4041 {
4042 case X86_XCPT_GP:
4043 case X86_XCPT_SS:
4044 case X86_XCPT_NP:
4045 case X86_XCPT_TS:
4046 case X86_XCPT_DE:
4047 return true;
4048 default:
4049 break;
4050 }
4051 return false;
4052}
4053
4054
4055/**
4056 * Handle a condition that occurred while delivering an event through the guest
4057 * IDT.
4058 *
4059 * @returns VBox status code (informational error codes included).
4060 * @retval VINF_SUCCESS if we should continue handling the #VMEXIT.
4061 * @retval VINF_HM_DOUBLE_FAULT if a #DF condition was detected and we ought to
4062 * continue execution of the guest which will delivery the #DF.
4063 * @retval VINF_EM_RESET if we detected a triple-fault condition.
4064 *
4065 * @param pVCpu Pointer to the VMCPU.
4066 * @param pCtx Pointer to the guest-CPU context.
4067 * @param pSvmTransient Pointer to the SVM transient structure.
4068 *
4069 * @remarks No-long-jump zone!!!
4070 */
4071static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4072{
4073 int rc = VINF_SUCCESS;
4074 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4075
4076 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
4077 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
4078 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
4079 {
4080 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
4081
4082 typedef enum
4083 {
4084 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
4085 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
4086 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
4087 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
4088 } SVMREFLECTXCPT;
4089
4090 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
4091 bool fReflectingNmi = false;
4092 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
4093 {
4094 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
4095 {
4096 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
4097
4098#ifdef VBOX_STRICT
4099 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
4100 && uExitVector == X86_XCPT_PF)
4101 {
4102 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
4103 }
4104#endif
4105 if ( uExitVector == X86_XCPT_PF
4106 && uIdtVector == X86_XCPT_PF)
4107 {
4108 pSvmTransient->fVectoringDoublePF = true;
4109 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
4110 }
4111 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
4112 && hmR0SvmIsContributoryXcpt(uExitVector)
4113 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
4114 || uIdtVector == X86_XCPT_PF))
4115 {
4116 enmReflect = SVMREFLECTXCPT_DF;
4117 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
4118 uIdtVector, uExitVector));
4119 }
4120 else if (uIdtVector == X86_XCPT_DF)
4121 {
4122 enmReflect = SVMREFLECTXCPT_TF;
4123 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
4124 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
4125 }
4126 else
4127 enmReflect = SVMREFLECTXCPT_XCPT;
4128 }
4129 else
4130 {
4131 /*
4132 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
4133 * exception to the guest after handling the #VMEXIT.
4134 */
4135 enmReflect = SVMREFLECTXCPT_XCPT;
4136 }
4137 }
4138 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
4139 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
4140 {
4141 enmReflect = SVMREFLECTXCPT_XCPT;
4142 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
4143
4144 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
4145 {
4146 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
4147 if (uExitVector == X86_XCPT_PF)
4148 {
4149 pSvmTransient->fVectoringPF = true;
4150 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
4151 }
4152 }
4153 }
4154 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
4155
4156 switch (enmReflect)
4157 {
4158 case SVMREFLECTXCPT_XCPT:
4159 {
4160 /* If we are re-injecting the NMI, clear NMI blocking. */
4161 if (fReflectingNmi)
4162 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
4163
4164 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
4165 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
4166
4167 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
4168 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
4169 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
4170 break;
4171 }
4172
4173 case SVMREFLECTXCPT_DF:
4174 {
4175 hmR0SvmSetPendingXcptDF(pVCpu);
4176 rc = VINF_HM_DOUBLE_FAULT;
4177 break;
4178 }
4179
4180 case SVMREFLECTXCPT_TF:
4181 {
4182 rc = VINF_EM_RESET;
4183 break;
4184 }
4185
4186 default:
4187 Assert(rc == VINF_SUCCESS);
4188 break;
4189 }
4190 }
4191 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET);
4192 NOREF(pCtx);
4193 return rc;
4194}
4195
4196
4197/**
4198 * Advances the guest RIP in the if the NRIP_SAVE feature is supported by the
4199 * CPU, otherwise advances the RIP by @a cb bytes.
4200 *
4201 * @param pVCpu Pointer to the VMCPU.
4202 * @param pCtx Pointer to the guest-CPU context.
4203 * @param cb RIP increment value in bytes.
4204 *
4205 * @remarks Use this function only from #VMEXIT's where the NRIP value is valid
4206 * when NRIP_SAVE is supported by the CPU!
4207 */
4208DECLINLINE(void) hmR0SvmUpdateRip(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
4209{
4210 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4211 {
4212 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4213 Assert(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb);
4214 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4215 }
4216 else
4217 pCtx->rip += cb;
4218}
4219
4220
4221/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4222/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
4223/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4224
4225/** @name #VMEXIT handlers.
4226 * @{
4227 */
4228
4229/**
4230 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
4231 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
4232 */
4233HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4234{
4235 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4236
4237 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
4238 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
4239 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
4240 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
4241
4242 /*
4243 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
4244 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
4245 * interrupt it is until the host actually take the interrupt.
4246 *
4247 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
4248 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
4249 */
4250 return VINF_EM_RAW_INTERRUPT;
4251}
4252
4253
4254/**
4255 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
4256 */
4257HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4258{
4259 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4260
4261 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4262 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
4263 int rc = VINF_SUCCESS;
4264 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4265 return rc;
4266}
4267
4268
4269/**
4270 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
4271 */
4272HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4273{
4274 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4275
4276 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4277 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
4278 int rc = VINF_SUCCESS;
4279 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4280 return rc;
4281}
4282
4283
4284/**
4285 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
4286 */
4287HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4288{
4289 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4290 PVM pVM = pVCpu->CTX_SUFF(pVM);
4291 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4292 if (RT_LIKELY(rc == VINF_SUCCESS))
4293 {
4294 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4295 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4296 }
4297 else
4298 {
4299 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
4300 rc = VERR_EM_INTERPRETER;
4301 }
4302 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
4303 return rc;
4304}
4305
4306
4307/**
4308 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
4309 */
4310HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4311{
4312 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4313 PVM pVM = pVCpu->CTX_SUFF(pVM);
4314 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4315 if (RT_LIKELY(rc == VINF_SUCCESS))
4316 {
4317 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4318 pSvmTransient->fUpdateTscOffsetting = true;
4319
4320 /* Single step check. */
4321 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4322 }
4323 else
4324 {
4325 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
4326 rc = VERR_EM_INTERPRETER;
4327 }
4328 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
4329 return rc;
4330}
4331
4332
4333/**
4334 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
4335 */
4336HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4337{
4338 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4339 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4340 if (RT_LIKELY(rc == VINF_SUCCESS))
4341 {
4342 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4343 pSvmTransient->fUpdateTscOffsetting = true;
4344 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4345 }
4346 else
4347 {
4348 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
4349 rc = VERR_EM_INTERPRETER;
4350 }
4351 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
4352 return rc;
4353}
4354
4355
4356/**
4357 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
4358 */
4359HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4360{
4361 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4362 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4363 if (RT_LIKELY(rc == VINF_SUCCESS))
4364 {
4365 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4366 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4367 }
4368 else
4369 {
4370 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
4371 rc = VERR_EM_INTERPRETER;
4372 }
4373 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
4374 return rc;
4375}
4376
4377
4378/**
4379 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
4380 */
4381HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4382{
4383 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4384 PVM pVM = pVCpu->CTX_SUFF(pVM);
4385 Assert(!pVM->hm.s.fNestedPaging);
4386
4387 /** @todo Decode Assist. */
4388 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
4389 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
4390 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
4391 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4392 return rc;
4393}
4394
4395
4396/**
4397 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
4398 */
4399HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4400{
4401 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4402
4403 hmR0SvmUpdateRip(pVCpu, pCtx, 1);
4404 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
4405 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4406 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
4407 if (rc != VINF_SUCCESS)
4408 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
4409 return rc;
4410}
4411
4412
4413/**
4414 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
4415 */
4416HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4417{
4418 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4419 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4420 if (RT_LIKELY(rc == VINF_SUCCESS))
4421 {
4422 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4423 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4424 }
4425 else
4426 {
4427 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
4428 rc = VERR_EM_INTERPRETER;
4429 }
4430 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
4431 return rc;
4432}
4433
4434
4435/**
4436 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
4437 */
4438HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4439{
4440 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4441 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4442 int rc = VBOXSTRICTRC_VAL(rc2);
4443 if ( rc == VINF_EM_HALT
4444 || rc == VINF_SUCCESS)
4445 {
4446 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4447
4448 if ( rc == VINF_EM_HALT
4449 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
4450 {
4451 rc = VINF_SUCCESS;
4452 }
4453 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4454 }
4455 else
4456 {
4457 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
4458 rc = VERR_EM_INTERPRETER;
4459 }
4460 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
4461 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
4462 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
4463 return rc;
4464}
4465
4466
4467/**
4468 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
4469 * Conditional #VMEXIT.
4470 */
4471HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4472{
4473 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4474 return VINF_EM_RESET;
4475}
4476
4477
4478/**
4479 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
4480 */
4481HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4482{
4483 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4484
4485 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4486
4487 /** @todo Decode Assist. */
4488 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4489 int rc = VBOXSTRICTRC_VAL(rc2);
4490 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
4491 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
4492 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
4493 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
4494 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4495 return rc;
4496}
4497
4498
4499/**
4500 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
4501 */
4502HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4503{
4504 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4505
4506 /** @todo Decode Assist. */
4507 VBOXSTRICTRC rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
4508 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
4509 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
4510 rcStrict = VERR_EM_INTERPRETER;
4511 if (rcStrict == VINF_SUCCESS)
4512 {
4513 /* RIP has been updated by EMInterpretInstruction(). */
4514 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
4515 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
4516 {
4517 case 0: /* CR0. */
4518 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4519 break;
4520
4521 case 3: /* CR3. */
4522 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4523 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
4524 break;
4525
4526 case 4: /* CR4. */
4527 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
4528 break;
4529
4530 case 8: /* CR8 (TPR). */
4531 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4532 break;
4533
4534 default:
4535 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
4536 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
4537 break;
4538 }
4539 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4540 }
4541 else
4542 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
4543 return VBOXSTRICTRC_TODO(rcStrict);
4544}
4545
4546
4547/**
4548 * #VMEXIT handler for instructions that result in a #UD exception delivered to
4549 * the guest.
4550 */
4551HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4552{
4553 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4554 hmR0SvmSetPendingXcptUD(pVCpu);
4555 return VINF_SUCCESS;
4556}
4557
4558
4559/**
4560 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
4561 */
4562HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4563{
4564 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4565 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4566 PVM pVM = pVCpu->CTX_SUFF(pVM);
4567
4568 int rc;
4569 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
4570 {
4571 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
4572
4573 /* Handle TPR patching; intercepted LSTAR write. */
4574 if ( pVM->hm.s.fTPRPatchingActive
4575 && pCtx->ecx == MSR_K8_LSTAR)
4576 {
4577 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
4578 {
4579 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
4580 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
4581 AssertRC(rc2);
4582 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4583 }
4584 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4585 rc = VINF_SUCCESS;
4586 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4587 return rc;
4588 }
4589
4590 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4591 {
4592 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4593 if (RT_LIKELY(rc == VINF_SUCCESS))
4594 {
4595 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4596 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4597 }
4598 else
4599 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
4600 }
4601 else
4602 {
4603 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
4604 if (RT_LIKELY(rc == VINF_SUCCESS))
4605 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
4606 else
4607 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4608 }
4609
4610 if (rc == VINF_SUCCESS)
4611 {
4612 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
4613 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
4614 && pCtx->ecx <= MSR_IA32_X2APIC_END)
4615 {
4616 /*
4617 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
4618 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
4619 * EMInterpretWrmsr() changes it.
4620 */
4621 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4622 }
4623 else if (pCtx->ecx == MSR_K6_EFER)
4624 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
4625 else if (pCtx->ecx == MSR_IA32_TSC)
4626 pSvmTransient->fUpdateTscOffsetting = true;
4627 }
4628 }
4629 else
4630 {
4631 /* MSR Read access. */
4632 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
4633 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
4634
4635 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4636 {
4637 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4638 if (RT_LIKELY(rc == VINF_SUCCESS))
4639 {
4640 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4641 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4642 }
4643 else
4644 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
4645 }
4646 else
4647 {
4648 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
4649 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4650 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4651 /* RIP updated by EMInterpretInstruction(). */
4652 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4653 }
4654 }
4655
4656 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
4657 return rc;
4658}
4659
4660
4661/**
4662 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
4663 */
4664HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4665{
4666 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4667 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
4668
4669 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
4670 if (pSvmTransient->fWasGuestDebugStateActive)
4671 {
4672 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
4673 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
4674 return VERR_SVM_UNEXPECTED_EXIT;
4675 }
4676
4677 /*
4678 * Lazy DR0-3 loading.
4679 */
4680 if (!pSvmTransient->fWasHyperDebugStateActive)
4681 {
4682 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4683 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4684
4685 /* Don't intercept DRx read and writes. */
4686 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4687 pVmcb->ctrl.u16InterceptRdDRx = 0;
4688 pVmcb->ctrl.u16InterceptWrDRx = 0;
4689 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4690
4691 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
4692 VMMRZCallRing3Disable(pVCpu);
4693 HM_DISABLE_PREEMPT();
4694
4695 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4696 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4697 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
4698
4699 HM_RESTORE_PREEMPT();
4700 VMMRZCallRing3Enable(pVCpu);
4701
4702 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4703 return VINF_SUCCESS;
4704 }
4705
4706 /*
4707 * Interpret the read/writing of DRx.
4708 */
4709 /** @todo Decode assist. */
4710 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4711 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4712 if (RT_LIKELY(rc == VINF_SUCCESS))
4713 {
4714 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4715 /** @todo CPUM should set this flag! */
4716 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
4717 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4718 }
4719 else
4720 Assert(rc == VERR_EM_INTERPRETER);
4721 return VBOXSTRICTRC_TODO(rc);
4722}
4723
4724
4725/**
4726 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
4727 */
4728HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4729{
4730 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4731 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4732 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4733 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4734 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4735 return rc;
4736}
4737
4738
4739/**
4740 * #VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional #VMEXIT.
4741 */
4742HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4743{
4744 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4745
4746 /** @todo decode assists... */
4747 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
4748 if (rcStrict == VINF_IEM_RAISED_XCPT)
4749 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4750
4751 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
4752 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
4753 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
4754
4755 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4756 return VBOXSTRICTRC_TODO(rcStrict);
4757}
4758
4759
4760/**
4761 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
4762 */
4763HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4764{
4765 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4766
4767 /* I/O operation lookup arrays. */
4768 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4769 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4770 the result (in AL/AX/EAX). */
4771 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4772
4773 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4774 PVM pVM = pVCpu->CTX_SUFF(pVM);
4775
4776 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4777 SVMIOIOEXIT IoExitInfo;
4778 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4779 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4780 uint32_t cbValue = s_aIOSize[uIOWidth];
4781 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4782
4783 if (RT_UNLIKELY(!cbValue))
4784 {
4785 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4786 return VERR_EM_INTERPRETER;
4787 }
4788
4789 VBOXSTRICTRC rcStrict;
4790 bool fUpdateRipAlready = false;
4791 if (IoExitInfo.n.u1STR)
4792 {
4793#ifdef VBOX_WITH_2ND_IEM_STEP
4794 /* INS/OUTS - I/O String instruction. */
4795 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4796 * in EXITINFO1? Investigate once this thing is up and running. */
4797 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
4798 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
4799 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
4800 static IEMMODE const s_aenmAddrMode[8] =
4801 {
4802 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
4803 };
4804 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
4805 if (enmAddrMode != (IEMMODE)-1)
4806 {
4807 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
4808 if (cbInstr <= 15 && cbInstr >= 1)
4809 {
4810 Assert(cbInstr >= 1U + IoExitInfo.n.u1REP);
4811 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4812 {
4813 /* Don't know exactly how to detect whether u3SEG is valid, currently
4814 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
4815 2384 Opterons when only checking NRIP. */
4816 if ( (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4817 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
4818 {
4819 AssertMsg(IoExitInfo.n.u3SEG == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1REP,
4820 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3SEG, cbInstr, IoExitInfo.n.u1REP));
4821 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4822 IoExitInfo.n.u3SEG);
4823 }
4824 else if (cbInstr == 1U + IoExitInfo.n.u1REP)
4825 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4826 X86_SREG_DS);
4827 else
4828 rcStrict = IEMExecOne(pVCpu);
4829 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4830 }
4831 else
4832 {
4833 AssertMsg(IoExitInfo.n.u3SEG == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3SEG));
4834 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr);
4835 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4836 }
4837 }
4838 else
4839 {
4840 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
4841 rcStrict = IEMExecOne(pVCpu);
4842 }
4843 }
4844 else
4845 {
4846 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
4847 rcStrict = IEMExecOne(pVCpu);
4848 }
4849 fUpdateRipAlready = true;
4850
4851#else
4852 /* INS/OUTS - I/O String instruction. */
4853 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4854
4855 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4856 * in EXITINFO1? Investigate once this thing is up and running. */
4857
4858 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4859 if (rcStrict == VINF_SUCCESS)
4860 {
4861 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4862 {
4863 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4864 (DISCPUMODE)pDis->uAddrMode, cbValue);
4865 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4866 }
4867 else
4868 {
4869 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4870 (DISCPUMODE)pDis->uAddrMode, cbValue);
4871 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4872 }
4873 }
4874 else
4875 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
4876#endif
4877 }
4878 else
4879 {
4880 /* IN/OUT - I/O instruction. */
4881 Assert(!IoExitInfo.n.u1REP);
4882
4883 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4884 {
4885 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
4886 if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4887 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4888
4889 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4890 }
4891 else
4892 {
4893 uint32_t u32Val = 0;
4894 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
4895 if (IOM_SUCCESS(rcStrict))
4896 {
4897 /* Save result of I/O IN instr. in AL/AX/EAX. */
4898 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
4899 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4900 }
4901 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4902 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4903
4904 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
4905 }
4906 }
4907
4908 if (IOM_SUCCESS(rcStrict))
4909 {
4910 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
4911 if (!fUpdateRipAlready)
4912 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
4913
4914 /*
4915 * If any I/O breakpoints are armed, we need to check if one triggered
4916 * and take appropriate action.
4917 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
4918 */
4919 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
4920 * execution engines about whether hyper BPs and such are pending. */
4921 uint32_t const uDr7 = pCtx->dr[7];
4922 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
4923 && X86_DR7_ANY_RW_IO(uDr7)
4924 && (pCtx->cr4 & X86_CR4_DE))
4925 || DBGFBpIsHwIoArmed(pVM)))
4926 {
4927 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
4928 VMMRZCallRing3Disable(pVCpu);
4929 HM_DISABLE_PREEMPT();
4930
4931 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
4932 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
4933
4934 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
4935 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
4936 {
4937 /* Raise #DB. */
4938 pVmcb->guest.u64DR6 = pCtx->dr[6];
4939 pVmcb->guest.u64DR7 = pCtx->dr[7];
4940 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4941 hmR0SvmSetPendingXcptDB(pVCpu);
4942 }
4943 /* rcStrict is VINF_SUCCESS or in [VINF_EM_FIRST..VINF_EM_LAST]. */
4944 else if ( rcStrict2 != VINF_SUCCESS
4945 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
4946 rcStrict = rcStrict2;
4947
4948 HM_RESTORE_PREEMPT();
4949 VMMRZCallRing3Enable(pVCpu);
4950 }
4951
4952 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4953 }
4954
4955#ifdef VBOX_STRICT
4956 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4957 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
4958 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4959 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
4960 else
4961 {
4962 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
4963 * statuses, that the VMM device and some others may return. See
4964 * IOM_SUCCESS() for guidance. */
4965 AssertMsg( RT_FAILURE(rcStrict)
4966 || rcStrict == VINF_SUCCESS
4967 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
4968 || rcStrict == VINF_EM_DBG_BREAKPOINT
4969 || rcStrict == VINF_EM_RAW_GUEST_TRAP
4970 || rcStrict == VINF_EM_RAW_TO_R3
4971 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
4972 }
4973#endif
4974 return VBOXSTRICTRC_TODO(rcStrict);
4975}
4976
4977
4978/**
4979 * #VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional
4980 * #VMEXIT.
4981 */
4982HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4983{
4984 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4985 PVM pVM = pVCpu->CTX_SUFF(pVM);
4986 Assert(pVM->hm.s.fNestedPaging);
4987
4988 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4989
4990 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
4991 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4992 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4993 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
4994
4995 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
4996
4997#ifdef VBOX_HM_WITH_GUEST_PATCHING
4998 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
4999 if ( pVM->hm.s.fTprPatchingAllowed
5000 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80 /* TPR offset. */
5001 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
5002 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
5003 && !CPUMIsGuestInLongModeEx(pCtx)
5004 && !CPUMGetGuestCPL(pVCpu)
5005 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
5006 {
5007 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
5008 GCPhysApicBase &= PAGE_BASE_GC_MASK;
5009
5010 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
5011 {
5012 /* Only attempt to patch the instruction once. */
5013 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
5014 if (!pPatch)
5015 return VINF_EM_HM_PATCH_TPR_INSTR;
5016 }
5017 }
5018#endif
5019
5020 /*
5021 * Determine the nested paging mode.
5022 */
5023 PGMMODE enmNestedPagingMode;
5024#if HC_ARCH_BITS == 32
5025 if (CPUMIsGuestInLongModeEx(pCtx))
5026 enmNestedPagingMode = PGMMODE_AMD64_NX;
5027 else
5028#endif
5029 enmNestedPagingMode = PGMGetHostMode(pVM);
5030
5031 /*
5032 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
5033 */
5034 int rc;
5035 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
5036 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
5037 {
5038 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
5039 u32ErrCode);
5040 rc = VBOXSTRICTRC_VAL(rc2);
5041
5042 /*
5043 * If we succeed, resume guest execution.
5044 * If we fail in interpreting the instruction because we couldn't get the guest physical address
5045 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
5046 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
5047 * weird case. See @bugref{6043}.
5048 */
5049 if ( rc == VINF_SUCCESS
5050 || rc == VERR_PAGE_TABLE_NOT_PRESENT
5051 || rc == VERR_PAGE_NOT_PRESENT)
5052 {
5053 /* Successfully handled MMIO operation. */
5054 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
5055 rc = VINF_SUCCESS;
5056 }
5057 return rc;
5058 }
5059
5060 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
5061 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
5062 TRPMResetTrap(pVCpu);
5063
5064 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
5065
5066 /*
5067 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
5068 */
5069 if ( rc == VINF_SUCCESS
5070 || rc == VERR_PAGE_TABLE_NOT_PRESENT
5071 || rc == VERR_PAGE_NOT_PRESENT)
5072 {
5073 /* We've successfully synced our shadow page tables. */
5074 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
5075 rc = VINF_SUCCESS;
5076 }
5077
5078 return rc;
5079}
5080
5081
5082/**
5083 * #VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional #VMEXIT.
5084 */
5085HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5086{
5087 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5088
5089 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5090 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one/NMI before reentry. */
5091 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
5092
5093 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive interrupts/NMIs, it is now ready. */
5094 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
5095 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
5096
5097 /* Deliver the pending interrupt/NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
5098 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
5099 return VINF_SUCCESS;
5100}
5101
5102
5103/**
5104 * #VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional #VMEXIT.
5105 */
5106HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5107{
5108 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5109
5110#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
5111 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5112#endif
5113
5114 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
5115 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5116 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
5117 && pVCpu->hm.s.Event.fPending) /** @todo fPending cannot be 'true', see hmR0SvmInjectPendingEvent(). See @bugref{7362}.*/
5118 {
5119 /*
5120 * AMD-V does not provide us with the original exception but we have it in u64IntInfo since we
5121 * injected the event during VM-entry.
5122 */
5123 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
5124 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
5125 return VINF_EM_RAW_INJECT_TRPM_EVENT;
5126 }
5127
5128 /** @todo Emulate task switch someday, currently just going back to ring-3 for
5129 * emulation. */
5130 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
5131 return VERR_EM_INTERPRETER;
5132}
5133
5134
5135/**
5136 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
5137 */
5138HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5139{
5140 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5141 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
5142
5143 /* First check if this is a patched VMMCALL for mov TPR */
5144 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
5145 if (rc == VINF_SUCCESS)
5146 {
5147 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
5148 return VINF_SUCCESS;
5149 }
5150 else if (rc == VERR_NOT_FOUND)
5151 {
5152 if (pVCpu->hm.s.fHypercallsEnabled)
5153 {
5154 rc = GIMHypercall(pVCpu, pCtx);
5155 if (RT_SUCCESS(rc))
5156 {
5157 /* If the hypercall changes anything other than guest general-purpose registers,
5158 we would need to reload the guest changed bits here before VM-reentry. */
5159 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
5160 return VINF_SUCCESS;
5161 }
5162 }
5163 }
5164
5165 hmR0SvmSetPendingXcptUD(pVCpu);
5166 return VINF_SUCCESS;
5167}
5168
5169
5170/**
5171 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
5172 */
5173HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5174{
5175 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5176 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
5177 return VINF_EM_RAW_INTERRUPT;
5178}
5179
5180
5181/**
5182 * #VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional #VMEXIT.
5183 */
5184HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5185{
5186 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5187
5188 /* Clear NMI blocking. */
5189 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5190
5191 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
5192 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5193 hmR0SvmClearIretIntercept(pVmcb);
5194
5195 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
5196 return VINF_SUCCESS;
5197}
5198
5199
5200/**
5201 * #VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E). Conditional
5202 * #VMEXIT.
5203 */
5204HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5205{
5206 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5207
5208 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5209
5210 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
5211 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5212 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
5213 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
5214 PVM pVM = pVCpu->CTX_SUFF(pVM);
5215
5216#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
5217 if (pVM->hm.s.fNestedPaging)
5218 {
5219 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
5220 if (!pSvmTransient->fVectoringDoublePF)
5221 {
5222 /* A genuine guest #PF, reflect it to the guest. */
5223 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5224 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
5225 uFaultAddress, u32ErrCode));
5226 }
5227 else
5228 {
5229 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
5230 hmR0SvmSetPendingXcptDF(pVCpu);
5231 Log4(("Pending #DF due to vectoring #PF. NP\n"));
5232 }
5233 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
5234 return VINF_SUCCESS;
5235 }
5236#endif
5237
5238 Assert(!pVM->hm.s.fNestedPaging);
5239
5240#ifdef VBOX_HM_WITH_GUEST_PATCHING
5241 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
5242 if ( pVM->hm.s.fTprPatchingAllowed
5243 && (uFaultAddress & 0xfff) == 0x80 /* TPR offset. */
5244 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
5245 && !CPUMIsGuestInLongModeEx(pCtx)
5246 && !CPUMGetGuestCPL(pVCpu)
5247 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
5248 {
5249 RTGCPHYS GCPhysApicBase;
5250 GCPhysApicBase = pCtx->msrApicBase;
5251 GCPhysApicBase &= PAGE_BASE_GC_MASK;
5252
5253 /* Check if the page at the fault-address is the APIC base. */
5254 RTGCPHYS GCPhysPage;
5255 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
5256 if ( rc2 == VINF_SUCCESS
5257 && GCPhysPage == GCPhysApicBase)
5258 {
5259 /* Only attempt to patch the instruction once. */
5260 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
5261 if (!pPatch)
5262 return VINF_EM_HM_PATCH_TPR_INSTR;
5263 }
5264 }
5265#endif
5266
5267 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
5268 pCtx->rip, u32ErrCode, pCtx->cr3));
5269
5270 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
5271 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
5272 if (pSvmTransient->fVectoringPF)
5273 {
5274 Assert(pVCpu->hm.s.Event.fPending);
5275 return VINF_EM_RAW_INJECT_TRPM_EVENT;
5276 }
5277
5278 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
5279 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
5280
5281 Log4(("#PF rc=%Rrc\n", rc));
5282
5283 if (rc == VINF_SUCCESS)
5284 {
5285 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
5286 TRPMResetTrap(pVCpu);
5287 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
5288 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
5289 return rc;
5290 }
5291 else if (rc == VINF_EM_RAW_GUEST_TRAP)
5292 {
5293 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
5294
5295 if (!pSvmTransient->fVectoringDoublePF)
5296 {
5297 /* It's a guest page fault and needs to be reflected to the guest. */
5298 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
5299 TRPMResetTrap(pVCpu);
5300 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5301 }
5302 else
5303 {
5304 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
5305 TRPMResetTrap(pVCpu);
5306 hmR0SvmSetPendingXcptDF(pVCpu);
5307 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
5308 }
5309
5310 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
5311 return VINF_SUCCESS;
5312 }
5313
5314 TRPMResetTrap(pVCpu);
5315 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
5316 return rc;
5317}
5318
5319
5320/**
5321 * #VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
5322 * Conditional #VMEXIT.
5323 */
5324HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5325{
5326 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5327
5328 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5329
5330 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
5331 VMMRZCallRing3Disable(pVCpu);
5332 HM_DISABLE_PREEMPT();
5333
5334 int rc;
5335 /* If the guest FPU was active at the time of the #NM exit, then it's a guest fault. */
5336 if (pSvmTransient->fWasGuestFPUStateActive)
5337 {
5338 rc = VINF_EM_RAW_GUEST_TRAP;
5339 Assert(CPUMIsGuestFPUStateActive(pVCpu) || HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
5340 }
5341 else
5342 {
5343#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5344 Assert(!pSvmTransient->fWasGuestFPUStateActive);
5345#endif
5346 rc = CPUMR0Trap07Handler(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
5347 Assert(rc == VINF_EM_RAW_GUEST_TRAP || (rc == VINF_SUCCESS && CPUMIsGuestFPUStateActive(pVCpu)));
5348 }
5349
5350 HM_RESTORE_PREEMPT();
5351 VMMRZCallRing3Enable(pVCpu);
5352
5353 if (rc == VINF_SUCCESS)
5354 {
5355 /* Guest FPU state was activated, we'll want to change CR0 FPU intercepts before the next VM-reentry. */
5356 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
5357 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
5358 pVCpu->hm.s.fPreloadGuestFpu = true;
5359 }
5360 else
5361 {
5362 /* Forward #NM to the guest. */
5363 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
5364 hmR0SvmSetPendingXcptNM(pVCpu);
5365 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
5366 }
5367 return VINF_SUCCESS;
5368}
5369
5370
5371/**
5372 * #VMEXIT handler for undefined opcode (SVM_EXIT_EXCEPTION_6).
5373 * Conditional #VMEXIT.
5374 */
5375HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5376{
5377 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5378
5379 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5380
5381 if (pVCpu->hm.s.fGIMTrapXcptUD)
5382 GIMXcptUD(pVCpu, pCtx, NULL /* pDis */);
5383 else
5384 hmR0SvmSetPendingXcptUD(pVCpu);
5385
5386 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
5387 return VINF_SUCCESS;
5388}
5389
5390
5391/**
5392 * #VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
5393 * Conditional #VMEXIT.
5394 */
5395HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5396{
5397 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5398
5399 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5400
5401 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
5402
5403 if (!(pCtx->cr0 & X86_CR0_NE))
5404 {
5405 PVM pVM = pVCpu->CTX_SUFF(pVM);
5406 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5407 unsigned cbOp;
5408 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
5409 if (RT_SUCCESS(rc))
5410 {
5411 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
5412 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
5413 if (RT_SUCCESS(rc))
5414 pCtx->rip += cbOp;
5415 }
5416 else
5417 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5418 return rc;
5419 }
5420
5421 hmR0SvmSetPendingXcptMF(pVCpu);
5422 return VINF_SUCCESS;
5423}
5424
5425
5426/**
5427 * #VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
5428 * #VMEXIT.
5429 */
5430HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5431{
5432 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5433
5434 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5435
5436 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
5437
5438 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
5439 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
5440 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5441 PVM pVM = pVCpu->CTX_SUFF(pVM);
5442 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
5443 if (rc == VINF_EM_RAW_GUEST_TRAP)
5444 {
5445 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
5446 if (CPUMIsHyperDebugStateActive(pVCpu))
5447 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
5448
5449 /* Reflect the exception back to the guest. */
5450 hmR0SvmSetPendingXcptDB(pVCpu);
5451 rc = VINF_SUCCESS;
5452 }
5453
5454 /*
5455 * Update DR6.
5456 */
5457 if (CPUMIsHyperDebugStateActive(pVCpu))
5458 {
5459 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
5460 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
5461 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
5462 }
5463 else
5464 {
5465 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
5466 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
5467 }
5468
5469 return rc;
5470}
5471
5472/** @} */
5473
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