VirtualBox

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

Last change on this file since 58591 was 58545, checked in by vboxsync, 9 years ago

HMSVMR0.cpp: ulBit -> uBit.

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