VirtualBox

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

Last change on this file since 59021 was 58913, checked in by vboxsync, 9 years ago

HM: Some top-level VBOXSTRICTRC use and related work.

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