VirtualBox

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

最後變更 在這個檔案從49808是 49770,由 vboxsync 提交於 11 年 前

VMM/HM: Fix typo in TRPPatchingAllowed member.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette