VirtualBox

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

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

VMM/HMSVMR0: Avoid MSR write when possible.

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

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