VirtualBox

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

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

VMM/HMSVMR0: nit.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 193.1 KB
 
1/* $Id: HMSVMR0.cpp 49971 2013-12-18 01:14:44Z 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 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
3022 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
3023 {
3024 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
3025 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
3026 uint64_t u64GuestTscAux = CPUMR0GetGuestTscAux(pVCpu);
3027 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
3028 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
3029 pSvmTransient->fRestoreTscAuxMsr = true;
3030 }
3031 else
3032 {
3033 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
3034 pSvmTransient->fRestoreTscAuxMsr = false;
3035 }
3036
3037 /* If VMCB Clean bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
3038 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
3039 pVmcb->ctrl.u64VmcbCleanBits = 0;
3040}
3041
3042
3043/**
3044 * Wrapper for running the guest code in AMD-V.
3045 *
3046 * @returns VBox strict status code.
3047 * @param pVM Pointer to the VM.
3048 * @param pVCpu Pointer to the VMCPU.
3049 * @param pCtx Pointer to the guest-CPU context.
3050 *
3051 * @remarks No-long-jump zone!!!
3052 */
3053DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3054{
3055 /*
3056 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
3057 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
3058 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
3059 */
3060#ifdef VBOX_WITH_KERNEL_USING_XMM
3061 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
3062 pVCpu->hm.s.svm.pfnVMRun);
3063#else
3064 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
3065#endif
3066}
3067
3068
3069/**
3070 * Performs some essential restoration of state after running guest code in
3071 * AMD-V.
3072 *
3073 * @param pVM Pointer to the VM.
3074 * @param pVCpu Pointer to the VMCPU.
3075 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
3076 * out-of-sync. Make sure to update the required fields
3077 * before using them.
3078 * @param pSvmTransient Pointer to the SVM transient structure.
3079 * @param rcVMRun Return code of VMRUN.
3080 *
3081 * @remarks Called with interrupts disabled.
3082 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
3083 * unconditionally when it is safe to do so.
3084 */
3085static void hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
3086{
3087 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3088
3089 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB-shootdowns. */
3090 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for TLB-shootdowns. */
3091
3092 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3093 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
3094
3095 if (pSvmTransient->fRestoreTscAuxMsr)
3096 {
3097 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
3098 CPUMR0SetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
3099 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
3100 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
3101 }
3102
3103 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
3104 {
3105 /** @todo Find a way to fix hardcoding a guestimate. */
3106 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset - 0x400);
3107 }
3108
3109 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
3110 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
3111 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3112
3113 Assert(!(ASMGetFlags() & X86_EFL_IF));
3114 ASMSetFlags(pSvmTransient->uEflags); /* Enable interrupts. */
3115 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
3116
3117 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
3118 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
3119 {
3120 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
3121 return;
3122 }
3123
3124 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
3125 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
3126 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
3127
3128 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
3129 {
3130 if (pVCpu->hm.s.svm.fSyncVTpr)
3131 {
3132 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
3133 if ( pVM->hm.s.fTPRPatchingActive
3134 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
3135 {
3136 int rc = PDMApicSetTPR(pVCpu, pMixedCtx->msrLSTAR & 0xff);
3137 AssertRC(rc);
3138 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3139 }
3140 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
3141 {
3142 int rc = PDMApicSetTPR(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
3143 AssertRC(rc);
3144 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3145 }
3146 }
3147 }
3148}
3149
3150
3151/**
3152 * Runs the guest code using AMD-V.
3153 *
3154 * @returns VBox status code.
3155 * @param pVM Pointer to the VM.
3156 * @param pVCpu Pointer to the VMCPU.
3157 */
3158static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3159{
3160 SVMTRANSIENT SvmTransient;
3161 SvmTransient.fUpdateTscOffsetting = true;
3162 uint32_t cLoops = 0;
3163 int rc = VERR_INTERNAL_ERROR_5;
3164
3165 for (;; cLoops++)
3166 {
3167 Assert(!HMR0SuspendPending());
3168 HMSVM_ASSERT_CPU_SAFE();
3169
3170 /* Preparatory work for running guest code, this may force us to return
3171 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3172 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3173 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3174 if (rc != VINF_SUCCESS)
3175 break;
3176
3177 /*
3178 * No longjmps to ring-3 from this point on!!!
3179 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3180 * This also disables flushing of the R0-logger instance (if any).
3181 */
3182 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3183 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3184
3185 /* Restore any residual host-state and save any bits shared between host
3186 and guest into the guest-CPU state. Re-enables interrupts! */
3187 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3188
3189 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3190 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3191 {
3192 if (rc == VINF_SUCCESS)
3193 rc = VERR_SVM_INVALID_GUEST_STATE;
3194 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3195 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3196 break;
3197 }
3198
3199 /* Handle the #VMEXIT. */
3200 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3201 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3202 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3203 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3204 if (rc != VINF_SUCCESS)
3205 break;
3206 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
3207 {
3208 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
3209 rc = VINF_EM_RAW_INTERRUPT;
3210 break;
3211 }
3212 }
3213
3214 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3215 return rc;
3216}
3217
3218
3219/**
3220 * Runs the guest code using AMD-V in single step mode.
3221 *
3222 * @returns VBox status code.
3223 * @param pVM Pointer to the VM.
3224 * @param pVCpu Pointer to the VMCPU.
3225 * @param pCtx Pointer to the guest-CPU context.
3226 */
3227static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3228{
3229 SVMTRANSIENT SvmTransient;
3230 SvmTransient.fUpdateTscOffsetting = true;
3231 uint32_t cLoops = 0;
3232 int rc = VERR_INTERNAL_ERROR_5;
3233 uint16_t uCsStart = pCtx->cs.Sel;
3234 uint64_t uRipStart = pCtx->rip;
3235
3236 for (;; cLoops++)
3237 {
3238 Assert(!HMR0SuspendPending());
3239 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
3240 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
3241 (unsigned)RTMpCpuId(), cLoops));
3242
3243 /* Preparatory work for running guest code, this may force us to return
3244 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3245 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3246 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3247 if (rc != VINF_SUCCESS)
3248 break;
3249
3250 /*
3251 * No longjmps to ring-3 from this point on!!!
3252 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3253 * This also disables flushing of the R0-logger instance (if any).
3254 */
3255 VMMRZCallRing3Disable(pVCpu);
3256 VMMRZCallRing3RemoveNotification(pVCpu);
3257 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3258
3259 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3260
3261 /*
3262 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
3263 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
3264 */
3265 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3266 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3267 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3268 {
3269 if (rc == VINF_SUCCESS)
3270 rc = VERR_SVM_INVALID_GUEST_STATE;
3271 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3272 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3273 return rc;
3274 }
3275
3276 /* Handle the #VMEXIT. */
3277 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3278 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3279 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3280 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3281 if (rc != VINF_SUCCESS)
3282 break;
3283 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
3284 {
3285 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
3286 rc = VINF_EM_RAW_INTERRUPT;
3287 break;
3288 }
3289
3290 /*
3291 * Did the RIP change, if so, consider it a single step.
3292 * Otherwise, make sure one of the TFs gets set.
3293 */
3294 if ( pCtx->rip != uRipStart
3295 || pCtx->cs.Sel != uCsStart)
3296 {
3297 rc = VINF_EM_DBG_STEPPED;
3298 break;
3299 }
3300 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
3301 }
3302
3303 /*
3304 * Clear the X86_EFL_TF if necessary.
3305 */
3306 if (pVCpu->hm.s.fClearTrapFlag)
3307 {
3308 pVCpu->hm.s.fClearTrapFlag = false;
3309 pCtx->eflags.Bits.u1TF = 0;
3310 }
3311
3312 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3313 return rc;
3314}
3315
3316
3317/**
3318 * Runs the guest code using AMD-V.
3319 *
3320 * @returns VBox status code.
3321 * @param pVM Pointer to the VM.
3322 * @param pVCpu Pointer to the VMCPU.
3323 * @param pCtx Pointer to the guest-CPU context.
3324 */
3325VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3326{
3327 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3328 HMSVM_ASSERT_PREEMPT_SAFE();
3329 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
3330
3331 int rc;
3332 if (!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu))
3333 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx);
3334 else
3335 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx);
3336
3337 if (rc == VERR_EM_INTERPRETER)
3338 rc = VINF_EM_RAW_EMULATE_INSTR;
3339 else if (rc == VINF_EM_RESET)
3340 rc = VINF_EM_TRIPLE_FAULT;
3341
3342 /* Prepare to return to ring-3. This will remove longjmp notifications. */
3343 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
3344 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
3345 return rc;
3346}
3347
3348
3349/**
3350 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
3351 *
3352 * @returns VBox status code (informational status codes included).
3353 * @param pVCpu Pointer to the VMCPU.
3354 * @param pCtx Pointer to the guest-CPU context.
3355 * @param pSvmTransient Pointer to the SVM transient structure.
3356 */
3357DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3358{
3359 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
3360 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
3361
3362 /*
3363 * The ordering of the case labels is based on most-frequently-occurring VM-exits for most guests under
3364 * normal workloads (for some definition of "normal").
3365 */
3366 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
3367 switch (pSvmTransient->u64ExitCode)
3368 {
3369 case SVM_EXIT_NPF:
3370 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
3371
3372 case SVM_EXIT_IOIO:
3373 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
3374
3375 case SVM_EXIT_RDTSC:
3376 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
3377
3378 case SVM_EXIT_RDTSCP:
3379 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
3380
3381 case SVM_EXIT_CPUID:
3382 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
3383
3384 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
3385 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
3386
3387 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
3388 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
3389
3390 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
3391 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
3392
3393 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
3394 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
3395
3396 case SVM_EXIT_MONITOR:
3397 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
3398
3399 case SVM_EXIT_MWAIT:
3400 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
3401
3402 case SVM_EXIT_HLT:
3403 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
3404
3405 case SVM_EXIT_READ_CR0:
3406 case SVM_EXIT_READ_CR3:
3407 case SVM_EXIT_READ_CR4:
3408 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
3409
3410 case SVM_EXIT_WRITE_CR0:
3411 case SVM_EXIT_WRITE_CR3:
3412 case SVM_EXIT_WRITE_CR4:
3413 case SVM_EXIT_WRITE_CR8:
3414 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
3415
3416 case SVM_EXIT_VINTR:
3417 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
3418
3419 case SVM_EXIT_INTR:
3420 case SVM_EXIT_FERR_FREEZE:
3421 case SVM_EXIT_NMI:
3422 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
3423
3424 case SVM_EXIT_MSR:
3425 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
3426
3427 case SVM_EXIT_INVLPG:
3428 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
3429
3430 case SVM_EXIT_WBINVD:
3431 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
3432
3433 case SVM_EXIT_INVD:
3434 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
3435
3436 case SVM_EXIT_RDPMC:
3437 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
3438
3439 default:
3440 {
3441 switch (pSvmTransient->u64ExitCode)
3442 {
3443 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
3444 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
3445 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
3446 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
3447 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3448
3449 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
3450 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
3451 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3452 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3453 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3454
3455 case SVM_EXIT_TASK_SWITCH:
3456 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3457
3458 case SVM_EXIT_VMMCALL:
3459 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3460
3461 case SVM_EXIT_SHUTDOWN:
3462 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3463
3464 case SVM_EXIT_SMI:
3465 case SVM_EXIT_INIT:
3466 {
3467 /*
3468 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3469 * we want to know about it so log the exit code and bail.
3470 */
3471 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3472 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3473 return VERR_SVM_UNEXPECTED_EXIT;
3474 }
3475
3476 case SVM_EXIT_INVLPGA:
3477 case SVM_EXIT_RSM:
3478 case SVM_EXIT_VMRUN:
3479 case SVM_EXIT_VMLOAD:
3480 case SVM_EXIT_VMSAVE:
3481 case SVM_EXIT_STGI:
3482 case SVM_EXIT_CLGI:
3483 case SVM_EXIT_SKINIT:
3484 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3485
3486#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3487 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3488 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3489 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3490 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3491 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3492 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3493 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3494 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3495 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3496 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3497 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3498 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3499 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3500 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3501 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3502 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3503 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3504 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3505 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3506 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3507 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3508 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3509 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3510 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3511 {
3512 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3513 SVMEVENT Event;
3514 Event.u = 0;
3515 Event.n.u1Valid = 1;
3516 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3517 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3518
3519 switch (Event.n.u8Vector)
3520 {
3521 case X86_XCPT_DE:
3522 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3523 break;
3524
3525 case X86_XCPT_BP:
3526 /** Saves the wrong EIP on the stack (pointing to the int3) instead of the
3527 * next instruction. */
3528 /** @todo Investigate this later. */
3529 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
3530 break;
3531
3532 case X86_XCPT_UD:
3533 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
3534 break;
3535
3536 case X86_XCPT_NP:
3537 Event.n.u1ErrorCodeValid = 1;
3538 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3539 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3540 break;
3541
3542 case X86_XCPT_SS:
3543 Event.n.u1ErrorCodeValid = 1;
3544 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3545 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3546 break;
3547
3548 case X86_XCPT_GP:
3549 Event.n.u1ErrorCodeValid = 1;
3550 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3551 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3552 break;
3553
3554 default:
3555 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3556 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3557 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3558 }
3559
3560 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3561 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3562 return VINF_SUCCESS;
3563 }
3564#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3565
3566 default:
3567 {
3568 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3569 pVCpu->hm.s.u32HMError = u32ExitCode;
3570 return VERR_SVM_UNKNOWN_EXIT;
3571 }
3572 }
3573 }
3574 }
3575 return VERR_INTERNAL_ERROR_5; /* Should never happen. */
3576}
3577
3578
3579#ifdef DEBUG
3580/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3581# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3582 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3583
3584# define HMSVM_ASSERT_PREEMPT_CPUID() \
3585 do \
3586 { \
3587 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3588 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3589 } while (0)
3590
3591# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3592 do { \
3593 AssertPtr(pVCpu); \
3594 AssertPtr(pCtx); \
3595 AssertPtr(pSvmTransient); \
3596 Assert(ASMIntAreEnabled()); \
3597 HMSVM_ASSERT_PREEMPT_SAFE(); \
3598 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3599 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)); \
3600 HMSVM_ASSERT_PREEMPT_SAFE(); \
3601 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3602 HMSVM_ASSERT_PREEMPT_CPUID(); \
3603 } while (0)
3604#else /* Release builds */
3605# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
3606#endif
3607
3608
3609/**
3610 * Worker for hmR0SvmInterpretInvlpg().
3611 *
3612 * @return VBox status code.
3613 * @param pVCpu Pointer to the VMCPU.
3614 * @param pCpu Pointer to the disassembler state.
3615 * @param pRegFrame Pointer to the register frame.
3616 */
3617static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
3618{
3619 DISQPVPARAMVAL Param1;
3620 RTGCPTR GCPtrPage;
3621
3622 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3623 if (RT_FAILURE(rc))
3624 return VERR_EM_INTERPRETER;
3625
3626 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3627 || Param1.type == DISQPV_TYPE_ADDRESS)
3628 {
3629 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3630 return VERR_EM_INTERPRETER;
3631
3632 GCPtrPage = Param1.val.val64;
3633 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, pRegFrame, GCPtrPage);
3634 rc = VBOXSTRICTRC_VAL(rc2);
3635 }
3636 else
3637 {
3638 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3639 rc = VERR_EM_INTERPRETER;
3640 }
3641
3642 return rc;
3643}
3644
3645
3646/**
3647 * Interprets INVLPG.
3648 *
3649 * @returns VBox status code.
3650 * @retval VINF_* Scheduling instructions.
3651 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3652 * @retval VERR_* Fatal errors.
3653 *
3654 * @param pVM Pointer to the VM.
3655 * @param pRegFrame Pointer to the register frame.
3656 *
3657 * @remarks Updates the RIP if the instruction was executed successfully.
3658 */
3659static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
3660{
3661 /* Only allow 32 & 64 bit code. */
3662 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3663 {
3664 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3665 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3666 if ( RT_SUCCESS(rc)
3667 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3668 {
3669 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
3670 if (RT_SUCCESS(rc))
3671 pRegFrame->rip += pDis->cbInstr;
3672 return rc;
3673 }
3674 else
3675 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3676 }
3677 return VERR_EM_INTERPRETER;
3678}
3679
3680
3681/**
3682 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
3683 *
3684 * @param pVCpu Pointer to the VMCPU.
3685 */
3686DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3687{
3688 SVMEVENT Event;
3689 Event.u = 0;
3690 Event.n.u1Valid = 1;
3691 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3692 Event.n.u8Vector = X86_XCPT_UD;
3693 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3694}
3695
3696
3697/**
3698 * Sets a debug (#DB) exception as pending-for-injection into the VM.
3699 *
3700 * @param pVCpu Pointer to the VMCPU.
3701 */
3702DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3703{
3704 SVMEVENT Event;
3705 Event.u = 0;
3706 Event.n.u1Valid = 1;
3707 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3708 Event.n.u8Vector = X86_XCPT_DB;
3709 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3710}
3711
3712
3713/**
3714 * Sets a page fault (#PF) exception as pending-for-injection into the VM.
3715 *
3716 * @param pVCpu Pointer to the VMCPU.
3717 * @param pCtx Pointer to the guest-CPU context.
3718 * @param u32ErrCode The error-code for the page-fault.
3719 * @param uFaultAddress The page fault address (CR2).
3720 *
3721 * @remarks This updates the guest CR2 with @a uFaultAddress!
3722 */
3723DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3724{
3725 SVMEVENT Event;
3726 Event.u = 0;
3727 Event.n.u1Valid = 1;
3728 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3729 Event.n.u8Vector = X86_XCPT_PF;
3730 Event.n.u1ErrorCodeValid = 1;
3731 Event.n.u32ErrorCode = u32ErrCode;
3732
3733 /* Update CR2 of the guest. */
3734 if (pCtx->cr2 != uFaultAddress)
3735 {
3736 pCtx->cr2 = uFaultAddress;
3737 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3738 }
3739
3740 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3741}
3742
3743
3744/**
3745 * Sets a device-not-available (#NM) exception as pending-for-injection into the
3746 * VM.
3747 *
3748 * @param pVCpu Pointer to the VMCPU.
3749 */
3750DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3751{
3752 SVMEVENT Event;
3753 Event.u = 0;
3754 Event.n.u1Valid = 1;
3755 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3756 Event.n.u8Vector = X86_XCPT_NM;
3757 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3758}
3759
3760
3761/**
3762 * Sets a math-fault (#MF) exception as pending-for-injection into the VM.
3763 *
3764 * @param pVCpu Pointer to the VMCPU.
3765 */
3766DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3767{
3768 SVMEVENT Event;
3769 Event.u = 0;
3770 Event.n.u1Valid = 1;
3771 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3772 Event.n.u8Vector = X86_XCPT_MF;
3773 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3774}
3775
3776
3777/**
3778 * Sets a double fault (#DF) exception as pending-for-injection into the VM.
3779 *
3780 * @param pVCpu Pointer to the VMCPU.
3781 */
3782DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3783{
3784 SVMEVENT Event;
3785 Event.u = 0;
3786 Event.n.u1Valid = 1;
3787 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3788 Event.n.u8Vector = X86_XCPT_DF;
3789 Event.n.u1ErrorCodeValid = 1;
3790 Event.n.u32ErrorCode = 0;
3791 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3792}
3793
3794
3795/**
3796 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3797 * guests. This simply looks up the patch record at EIP and does the required.
3798 *
3799 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3800 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3801 * TPR). See hmR3ReplaceTprInstr() for the details.
3802 *
3803 * @returns VBox status code.
3804 * @param pVM Pointer to the VM.
3805 * @param pVCpu Pointer to the VMCPU.
3806 * @param pCtx Pointer to the guest-CPU context.
3807 */
3808static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3809{
3810 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3811 for (;;)
3812 {
3813 bool fPending;
3814 uint8_t u8Tpr;
3815
3816 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
3817 if (!pPatch)
3818 break;
3819
3820 switch (pPatch->enmType)
3821 {
3822 case HMTPRINSTR_READ:
3823 {
3824 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
3825 AssertRC(rc);
3826
3827 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
3828 AssertRC(rc);
3829 pCtx->rip += pPatch->cbOp;
3830 break;
3831 }
3832
3833 case HMTPRINSTR_WRITE_REG:
3834 case HMTPRINSTR_WRITE_IMM:
3835 {
3836 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
3837 {
3838 uint32_t u32Val;
3839 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
3840 AssertRC(rc);
3841 u8Tpr = u32Val;
3842 }
3843 else
3844 u8Tpr = (uint8_t)pPatch->uSrcOperand;
3845
3846 int rc2 = PDMApicSetTPR(pVCpu, u8Tpr);
3847 AssertRC(rc2);
3848 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3849
3850 pCtx->rip += pPatch->cbOp;
3851 break;
3852 }
3853
3854 default:
3855 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
3856 pVCpu->hm.s.u32HMError = pPatch->enmType;
3857 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
3858 }
3859 }
3860
3861 return VINF_SUCCESS;
3862}
3863
3864
3865/**
3866 * Determines if an exception is a contributory exception. Contributory
3867 * exceptions are ones which can cause double-faults. Page-fault is
3868 * intentionally not included here as it's a conditional contributory exception.
3869 *
3870 * @returns true if the exception is contributory, false otherwise.
3871 * @param uVector The exception vector.
3872 */
3873DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
3874{
3875 switch (uVector)
3876 {
3877 case X86_XCPT_GP:
3878 case X86_XCPT_SS:
3879 case X86_XCPT_NP:
3880 case X86_XCPT_TS:
3881 case X86_XCPT_DE:
3882 return true;
3883 default:
3884 break;
3885 }
3886 return false;
3887}
3888
3889
3890/**
3891 * Handle a condition that occurred while delivering an event through the guest
3892 * IDT.
3893 *
3894 * @returns VBox status code (informational error codes included).
3895 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
3896 * @retval VINF_HM_DOUBLE_FAULT if a #DF condition was detected and we ought to
3897 * continue execution of the guest which will delivery the #DF.
3898 * @retval VINF_EM_RESET if we detected a triple-fault condition.
3899 *
3900 * @param pVCpu Pointer to the VMCPU.
3901 * @param pCtx Pointer to the guest-CPU context.
3902 * @param pSvmTransient Pointer to the SVM transient structure.
3903 *
3904 * @remarks No-long-jump zone!!!
3905 */
3906static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3907{
3908 int rc = VINF_SUCCESS;
3909 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3910
3911 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
3912 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
3913 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
3914 {
3915 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
3916
3917 typedef enum
3918 {
3919 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
3920 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
3921 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
3922 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
3923 } SVMREFLECTXCPT;
3924
3925 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
3926 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
3927 {
3928 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
3929 {
3930 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
3931
3932#ifdef VBOX_STRICT
3933 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
3934 && uExitVector == X86_XCPT_PF)
3935 {
3936 Log4(("IDT: Contributory #PF uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
3937 }
3938#endif
3939 if ( uExitVector == X86_XCPT_PF
3940 && uIdtVector == X86_XCPT_PF)
3941 {
3942 pSvmTransient->fVectoringPF = true;
3943 Log4(("IDT: Vectoring #PF uCR2=%#RX64\n", pCtx->cr2));
3944 }
3945 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
3946 && hmR0SvmIsContributoryXcpt(uExitVector)
3947 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
3948 || uIdtVector == X86_XCPT_PF))
3949 {
3950 enmReflect = SVMREFLECTXCPT_DF;
3951 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
3952 uIdtVector, uExitVector));
3953 }
3954 else if (uIdtVector == X86_XCPT_DF)
3955 {
3956 enmReflect = SVMREFLECTXCPT_TF;
3957 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
3958 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
3959 }
3960 else
3961 enmReflect = SVMREFLECTXCPT_XCPT;
3962 }
3963 else
3964 {
3965 /*
3966 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
3967 * exception to the guest after handling the VM-exit.
3968 */
3969 enmReflect = SVMREFLECTXCPT_XCPT;
3970 }
3971 }
3972 else if (pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
3973 {
3974 /* Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
3975 enmReflect = SVMREFLECTXCPT_XCPT;
3976 }
3977
3978 switch (enmReflect)
3979 {
3980 case SVMREFLECTXCPT_XCPT:
3981 {
3982 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
3983 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
3984
3985 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
3986 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
3987 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
3988 break;
3989 }
3990
3991 case SVMREFLECTXCPT_DF:
3992 {
3993 hmR0SvmSetPendingXcptDF(pVCpu);
3994 rc = VINF_HM_DOUBLE_FAULT;
3995 break;
3996 }
3997
3998 case SVMREFLECTXCPT_TF:
3999 {
4000 rc = VINF_EM_RESET;
4001 break;
4002 }
4003
4004 default:
4005 Assert(rc == VINF_SUCCESS);
4006 break;
4007 }
4008 }
4009 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET);
4010 NOREF(pCtx);
4011 return rc;
4012}
4013
4014
4015/**
4016 * Advances the guest RIP in the if the NRIP_SAVE feature is supported by the
4017 * CPU, otherwise advances the RIP by @a cb bytes.
4018 *
4019 * @param pVCpu Pointer to the VMCPU.
4020 * @param pCtx Pointer to the guest-CPU context.
4021 * @param cb RIP increment value in bytes.
4022 *
4023 * @remarks Use this function only from #VMEXIT's where the NRIP value is valid
4024 * when NRIP_SAVE is supported by the CPU!
4025 */
4026DECLINLINE(void) hmR0SvmUpdateRip(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
4027{
4028 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4029 {
4030 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4031 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4032 }
4033 else
4034 pCtx->rip += cb;
4035}
4036
4037
4038/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4039/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
4040/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4041
4042/** @name VM-exit handlers.
4043 * @{
4044 */
4045
4046/**
4047 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
4048 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
4049 */
4050HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4051{
4052 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4053
4054 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
4055 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
4056 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
4057 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
4058
4059 /*
4060 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
4061 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
4062 * interrupt it is until the host actually take the interrupt.
4063 *
4064 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
4065 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
4066 */
4067 return VINF_EM_RAW_INTERRUPT;
4068}
4069
4070
4071/**
4072 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
4073 */
4074HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4075{
4076 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4077
4078 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4079 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
4080 int rc = VINF_SUCCESS;
4081 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4082 return rc;
4083}
4084
4085
4086/**
4087 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
4088 */
4089HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4090{
4091 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4092
4093 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4094 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
4095 int rc = VINF_SUCCESS;
4096 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4097 return rc;
4098}
4099
4100
4101/**
4102 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
4103 */
4104HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4105{
4106 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4107 PVM pVM = pVCpu->CTX_SUFF(pVM);
4108 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4109 if (RT_LIKELY(rc == VINF_SUCCESS))
4110 {
4111 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4112 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4113 }
4114 else
4115 {
4116 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
4117 rc = VERR_EM_INTERPRETER;
4118 }
4119 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
4120 return rc;
4121}
4122
4123
4124/**
4125 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
4126 */
4127HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4128{
4129 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4130 PVM pVM = pVCpu->CTX_SUFF(pVM);
4131 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4132 if (RT_LIKELY(rc == VINF_SUCCESS))
4133 {
4134 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4135 pSvmTransient->fUpdateTscOffsetting = true;
4136
4137 /* Single step check. */
4138 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4139 }
4140 else
4141 {
4142 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
4143 rc = VERR_EM_INTERPRETER;
4144 }
4145 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
4146 return rc;
4147}
4148
4149
4150/**
4151 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
4152 */
4153HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4154{
4155 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4156 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4157 if (RT_LIKELY(rc == VINF_SUCCESS))
4158 {
4159 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4160 pSvmTransient->fUpdateTscOffsetting = true;
4161 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4162 }
4163 else
4164 {
4165 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
4166 rc = VERR_EM_INTERPRETER;
4167 }
4168 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
4169 return rc;
4170}
4171
4172
4173/**
4174 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
4175 */
4176HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4177{
4178 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4179 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4180 if (RT_LIKELY(rc == VINF_SUCCESS))
4181 {
4182 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4183 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4184 }
4185 else
4186 {
4187 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
4188 rc = VERR_EM_INTERPRETER;
4189 }
4190 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
4191 return rc;
4192}
4193
4194
4195/**
4196 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
4197 */
4198HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4199{
4200 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4201 PVM pVM = pVCpu->CTX_SUFF(pVM);
4202 Assert(!pVM->hm.s.fNestedPaging);
4203
4204 /** @todo Decode Assist. */
4205 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx)); /* Updates RIP if successful. */
4206 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
4207 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
4208 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4209 return rc;
4210}
4211
4212
4213/**
4214 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
4215 */
4216HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4217{
4218 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4219 hmR0SvmUpdateRip(pVCpu, pCtx, 1);
4220 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
4221 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4222 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
4223 return rc;
4224}
4225
4226
4227/**
4228 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
4229 */
4230HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4231{
4232 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4233 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4234 if (RT_LIKELY(rc == VINF_SUCCESS))
4235 {
4236 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4237 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4238 }
4239 else
4240 {
4241 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
4242 rc = VERR_EM_INTERPRETER;
4243 }
4244 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
4245 return rc;
4246}
4247
4248
4249/**
4250 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
4251 */
4252HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4253{
4254 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4255 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4256 int rc = VBOXSTRICTRC_VAL(rc2);
4257 if ( rc == VINF_EM_HALT
4258 || rc == VINF_SUCCESS)
4259 {
4260 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4261
4262 if ( rc == VINF_EM_HALT
4263 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
4264 {
4265 rc = VINF_SUCCESS;
4266 }
4267 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4268 }
4269 else
4270 {
4271 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
4272 rc = VERR_EM_INTERPRETER;
4273 }
4274 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
4275 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
4276 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
4277 return rc;
4278}
4279
4280
4281/**
4282 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
4283 * Conditional #VMEXIT.
4284 */
4285HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4286{
4287 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4288 return VINF_EM_RESET;
4289}
4290
4291
4292/**
4293 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
4294 */
4295HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4296{
4297 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4298
4299 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4300
4301 /** @todo Decode Assist. */
4302 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4303 int rc = VBOXSTRICTRC_VAL(rc2);
4304 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
4305 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
4306 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
4307 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
4308 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4309 return rc;
4310}
4311
4312
4313/**
4314 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
4315 */
4316HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4317{
4318 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4319 /** @todo Decode Assist. */
4320 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4321 int rc = VBOXSTRICTRC_VAL(rc2);
4322 if (rc == VINF_SUCCESS)
4323 {
4324 /* RIP has been updated by EMInterpretInstruction(). */
4325 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
4326 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
4327 {
4328 case 0: /* CR0. */
4329 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4330 break;
4331
4332 case 3: /* CR3. */
4333 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4334 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
4335 break;
4336
4337 case 4: /* CR4. */
4338 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
4339 break;
4340
4341 case 8: /* CR8 (TPR). */
4342 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4343 break;
4344
4345 default:
4346 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x CRx=%#RX64\n",
4347 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
4348 break;
4349 }
4350 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4351 }
4352 else
4353 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
4354 return rc;
4355}
4356
4357
4358/**
4359 * #VMEXIT handler for instructions that result in a #UD exception delivered to
4360 * the guest.
4361 */
4362HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4363{
4364 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4365 hmR0SvmSetPendingXcptUD(pVCpu);
4366 return VINF_SUCCESS;
4367}
4368
4369
4370/**
4371 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
4372 */
4373HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4374{
4375 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4376 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4377 PVM pVM = pVCpu->CTX_SUFF(pVM);
4378
4379 int rc;
4380 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
4381 {
4382 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
4383
4384 /* Handle TPR patching; intercepted LSTAR write. */
4385 if ( pVM->hm.s.fTPRPatchingActive
4386 && pCtx->ecx == MSR_K8_LSTAR)
4387 {
4388 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
4389 {
4390 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
4391 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
4392 AssertRC(rc2);
4393 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4394 }
4395 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4396 rc = VINF_SUCCESS;
4397 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4398 return rc;
4399 }
4400
4401 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4402 {
4403 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4404 if (RT_LIKELY(rc == VINF_SUCCESS))
4405 {
4406 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4407 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4408 }
4409 else
4410 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
4411 }
4412 else
4413 {
4414 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
4415 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4416 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4417 /* RIP updated by EMInterpretInstruction(). */
4418 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4419 }
4420
4421 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
4422 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
4423 && pCtx->ecx <= MSR_IA32_X2APIC_END)
4424 {
4425 /*
4426 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
4427 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
4428 * EMInterpretWrmsr() changes it.
4429 */
4430 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4431 }
4432 else if (pCtx->ecx == MSR_K6_EFER)
4433 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_EFER_MSR);
4434 else if (pCtx->ecx == MSR_IA32_TSC)
4435 pSvmTransient->fUpdateTscOffsetting = true;
4436 }
4437 else
4438 {
4439 /* MSR Read access. */
4440 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
4441 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
4442
4443 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4444 {
4445 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4446 if (RT_LIKELY(rc == VINF_SUCCESS))
4447 {
4448 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4449 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4450 }
4451 else
4452 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
4453 }
4454 else
4455 {
4456 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
4457 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4458 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4459 /* RIP updated by EMInterpretInstruction(). */
4460 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4461 }
4462 }
4463
4464 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
4465 return rc;
4466}
4467
4468
4469/**
4470 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
4471 */
4472HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4473{
4474 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4475 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
4476
4477 /* We should -not- get this VM-exit if the guest's debug registers were active. */
4478 if (pSvmTransient->fWasGuestDebugStateActive)
4479 {
4480 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
4481 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
4482 return VERR_SVM_UNEXPECTED_EXIT;
4483 }
4484
4485 /*
4486 * Lazy DR0-3 loading.
4487 */
4488 if (!pSvmTransient->fWasHyperDebugStateActive)
4489 {
4490 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4491 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4492
4493 /* Don't intercept DRx read and writes. */
4494 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4495 pVmcb->ctrl.u16InterceptRdDRx = 0;
4496 pVmcb->ctrl.u16InterceptWrDRx = 0;
4497 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4498
4499 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
4500 VMMRZCallRing3Disable(pVCpu);
4501 HM_DISABLE_PREEMPT_IF_NEEDED();
4502
4503 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4504 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4505 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
4506
4507 HM_RESTORE_PREEMPT_IF_NEEDED();
4508 VMMRZCallRing3Enable(pVCpu);
4509
4510 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4511 return VINF_SUCCESS;
4512 }
4513
4514 /*
4515 * Interpret the read/writing of DRx.
4516 */
4517 /** @todo Decode assist. */
4518 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4519 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4520 if (RT_LIKELY(rc == VINF_SUCCESS))
4521 {
4522 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4523 /** @todo CPUM should set this flag! */
4524 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
4525 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4526 }
4527 else
4528 Assert(rc == VERR_EM_INTERPRETER);
4529 return VBOXSTRICTRC_TODO(rc);
4530}
4531
4532
4533/**
4534 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
4535 */
4536HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4537{
4538 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4539 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4540 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4541 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4542 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4543 return rc;
4544}
4545
4546
4547/**
4548 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
4549 */
4550HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4551{
4552 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4553
4554 /* I/O operation lookup arrays. */
4555 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4556 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4557 the result (in AL/AX/EAX). */
4558 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4559
4560 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4561 PVM pVM = pVCpu->CTX_SUFF(pVM);
4562
4563 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4564 SVMIOIOEXIT IoExitInfo;
4565 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4566 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4567 uint32_t cbValue = s_aIOSize[uIOWidth];
4568 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4569
4570 if (RT_UNLIKELY(!cbValue))
4571 {
4572 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4573 return VERR_EM_INTERPRETER;
4574 }
4575
4576 VBOXSTRICTRC rcStrict;
4577 if (IoExitInfo.n.u1STR)
4578 {
4579 /* INS/OUTS - I/O String instruction. */
4580 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4581
4582 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4583 * in EXITINFO1? Investigate once this thing is up and running. */
4584
4585 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4586 if (rcStrict == VINF_SUCCESS)
4587 {
4588 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4589 {
4590 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4591 (DISCPUMODE)pDis->uAddrMode, cbValue);
4592 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4593 }
4594 else
4595 {
4596 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4597 (DISCPUMODE)pDis->uAddrMode, cbValue);
4598 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4599 }
4600 }
4601 else
4602 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
4603 }
4604 else
4605 {
4606 /* IN/OUT - I/O instruction. */
4607 Assert(!IoExitInfo.n.u1REP);
4608
4609 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4610 {
4611 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
4612 if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4613 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4614
4615 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4616 }
4617 else
4618 {
4619 uint32_t u32Val = 0;
4620
4621 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
4622 if (IOM_SUCCESS(rcStrict))
4623 {
4624 /* Save result of I/O IN instr. in AL/AX/EAX. */
4625 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4626 }
4627 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4628 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4629
4630 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
4631 }
4632 }
4633
4634 if (IOM_SUCCESS(rcStrict))
4635 {
4636 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
4637 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
4638
4639 /*
4640 * If any I/O breakpoints are armed, we need to check if one triggered
4641 * and take appropriate action.
4642 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
4643 */
4644 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
4645 * execution engines about whether hyper BPs and such are pending. */
4646 uint32_t const uDr7 = pCtx->dr[7];
4647 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
4648 && X86_DR7_ANY_RW_IO(uDr7)
4649 && (pCtx->cr4 & X86_CR4_DE))
4650 || DBGFBpIsHwIoArmed(pVM)))
4651 {
4652 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
4653 VMMRZCallRing3Disable(pVCpu);
4654 HM_DISABLE_PREEMPT_IF_NEEDED();
4655
4656 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
4657 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
4658
4659 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
4660 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
4661 {
4662 /* Raise #DB. */
4663 pVmcb->guest.u64DR6 = pCtx->dr[6];
4664 pVmcb->guest.u64DR7 = pCtx->dr[7];
4665 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4666 hmR0SvmSetPendingXcptDB(pVCpu);
4667 }
4668 /* rcStrict is VINF_SUCCESS or in [VINF_EM_FIRST..VINF_EM_LAST]. */
4669 else if ( rcStrict2 != VINF_SUCCESS
4670 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
4671 rcStrict = rcStrict2;
4672
4673 HM_RESTORE_PREEMPT_IF_NEEDED();
4674 VMMRZCallRing3Enable(pVCpu);
4675 }
4676
4677 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4678 }
4679
4680#ifdef VBOX_STRICT
4681 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4682 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
4683 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4684 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
4685 else
4686 {
4687 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
4688 * statuses, that the VMM device and some others may return. See
4689 * IOM_SUCCESS() for guidance. */
4690 AssertMsg( RT_FAILURE(rcStrict)
4691 || rcStrict == VINF_SUCCESS
4692 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
4693 || rcStrict == VINF_EM_DBG_BREAKPOINT
4694 || rcStrict == VINF_EM_RAW_GUEST_TRAP
4695 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
4696 }
4697#endif
4698 return VBOXSTRICTRC_TODO(rcStrict);
4699}
4700
4701
4702/**
4703 * #VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional
4704 * #VMEXIT.
4705 */
4706HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4707{
4708 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4709 PVM pVM = pVCpu->CTX_SUFF(pVM);
4710 Assert(pVM->hm.s.fNestedPaging);
4711
4712 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4713
4714 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
4715 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4716 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4717 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
4718
4719 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
4720
4721#ifdef VBOX_HM_WITH_GUEST_PATCHING
4722 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
4723 if ( pVM->hm.s.fTprPatchingAllowed
4724 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80 /* TPR offset. */
4725 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
4726 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
4727 && !CPUMIsGuestInLongModeEx(pCtx)
4728 && !CPUMGetGuestCPL(pVCpu)
4729 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4730 {
4731 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
4732 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4733
4734 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
4735 {
4736 /* Only attempt to patch the instruction once. */
4737 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4738 if (!pPatch)
4739 return VINF_EM_HM_PATCH_TPR_INSTR;
4740 }
4741 }
4742#endif
4743
4744 /*
4745 * Determine the nested paging mode.
4746 */
4747 PGMMODE enmNestedPagingMode;
4748#if HC_ARCH_BITS == 32
4749 if (CPUMIsGuestInLongModeEx(pCtx))
4750 enmNestedPagingMode = PGMMODE_AMD64_NX;
4751 else
4752#endif
4753 enmNestedPagingMode = PGMGetHostMode(pVM);
4754
4755 /*
4756 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
4757 */
4758 int rc;
4759 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
4760 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
4761 {
4762 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
4763 u32ErrCode);
4764 rc = VBOXSTRICTRC_VAL(rc2);
4765
4766 /*
4767 * If we succeed, resume guest execution.
4768 * If we fail in interpreting the instruction because we couldn't get the guest physical address
4769 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
4770 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
4771 * weird case. See @bugref{6043}.
4772 */
4773 if ( rc == VINF_SUCCESS
4774 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4775 || rc == VERR_PAGE_NOT_PRESENT)
4776 {
4777 /* Successfully handled MMIO operation. */
4778 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4779 rc = VINF_SUCCESS;
4780 }
4781 return rc;
4782 }
4783
4784 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
4785 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
4786 TRPMResetTrap(pVCpu);
4787
4788 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
4789
4790 /*
4791 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
4792 */
4793 if ( rc == VINF_SUCCESS
4794 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4795 || rc == VERR_PAGE_NOT_PRESENT)
4796 {
4797 /* We've successfully synced our shadow page tables. */
4798 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4799 rc = VINF_SUCCESS;
4800 }
4801
4802 return rc;
4803}
4804
4805
4806/**
4807 * #VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional #VMEXIT.
4808 */
4809HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4810{
4811 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4812
4813 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4814 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one before reentry. */
4815 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
4816
4817 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
4818 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
4819 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
4820
4821 /* Deliver the pending interrupt via hmR0SvmPreRunGuest()->hmR0SvmInjectEventVmcb() and resume guest execution. */
4822 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
4823 return VINF_SUCCESS;
4824}
4825
4826
4827/**
4828 * #VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional #VMEXIT.
4829 */
4830HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4831{
4832 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4833
4834#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
4835 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4836#endif
4837
4838 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
4839 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4840 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
4841 && pVCpu->hm.s.Event.fPending)
4842 {
4843 /*
4844 * AMD-V does not provide us with the original exception but we have it in u64IntInfo since we
4845 * injected the event during VM-entry. Software interrupts and exceptions will be regenerated
4846 * when the recompiler restarts the instruction.
4847 */
4848 SVMEVENT Event;
4849 Event.u = pVCpu->hm.s.Event.u64IntInfo;
4850 if ( Event.n.u3Type == SVM_EVENT_EXCEPTION
4851 || Event.n.u3Type == SVM_EVENT_SOFTWARE_INT)
4852 {
4853 pVCpu->hm.s.Event.fPending = false;
4854 }
4855 else
4856 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery. Kept pending u8Vector=%#x\n", Event.n.u8Vector));
4857 }
4858
4859 /** @todo Emulate task switch someday, currently just going back to ring-3 for
4860 * emulation. */
4861 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
4862 return VERR_EM_INTERPRETER;
4863}
4864
4865
4866/**
4867 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
4868 */
4869HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4870{
4871 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4872
4873 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4874 if (RT_LIKELY(rc == VINF_SUCCESS))
4875 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4876 else
4877 hmR0SvmSetPendingXcptUD(pVCpu);
4878 return VINF_SUCCESS;
4879}
4880
4881
4882/**
4883 * #VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E). Conditional
4884 * #VMEXIT.
4885 */
4886HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4887{
4888 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4889
4890 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4891
4892 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
4893 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4894 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4895 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
4896 PVM pVM = pVCpu->CTX_SUFF(pVM);
4897
4898#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
4899 if (pVM->hm.s.fNestedPaging)
4900 {
4901 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4902 if (!pSvmTransient->fVectoringPF)
4903 {
4904 /* A genuine guest #PF, reflect it to the guest. */
4905 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4906 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
4907 uFaultAddress, u32ErrCode));
4908 }
4909 else
4910 {
4911 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4912 hmR0SvmSetPendingXcptDF(pVCpu);
4913 Log4(("Pending #DF due to vectoring #PF. NP\n"));
4914 }
4915 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4916 return VINF_SUCCESS;
4917 }
4918#endif
4919
4920 Assert(!pVM->hm.s.fNestedPaging);
4921
4922#ifdef VBOX_HM_WITH_GUEST_PATCHING
4923 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
4924 if ( pVM->hm.s.fTprPatchingAllowed
4925 && (uFaultAddress & 0xfff) == 0x80 /* TPR offset. */
4926 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
4927 && !CPUMIsGuestInLongModeEx(pCtx)
4928 && !CPUMGetGuestCPL(pVCpu)
4929 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4930 {
4931 RTGCPHYS GCPhysApicBase;
4932 GCPhysApicBase = pCtx->msrApicBase;
4933 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4934
4935 /* Check if the page at the fault-address is the APIC base. */
4936 RTGCPHYS GCPhysPage;
4937 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
4938 if ( rc2 == VINF_SUCCESS
4939 && GCPhysPage == GCPhysApicBase)
4940 {
4941 /* Only attempt to patch the instruction once. */
4942 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4943 if (!pPatch)
4944 return VINF_EM_HM_PATCH_TPR_INSTR;
4945 }
4946 }
4947#endif
4948
4949 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
4950 pCtx->rip, u32ErrCode, pCtx->cr3));
4951
4952 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
4953 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
4954
4955 Log4(("#PF rc=%Rrc\n", rc));
4956
4957 if (rc == VINF_SUCCESS)
4958 {
4959 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
4960 TRPMResetTrap(pVCpu);
4961 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4962 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4963 return rc;
4964 }
4965 else if (rc == VINF_EM_RAW_GUEST_TRAP)
4966 {
4967 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4968
4969 if (!pSvmTransient->fVectoringPF)
4970 {
4971 /* It's a guest page fault and needs to be reflected to the guest. */
4972 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
4973 TRPMResetTrap(pVCpu);
4974 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4975 }
4976 else
4977 {
4978 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4979 TRPMResetTrap(pVCpu);
4980 hmR0SvmSetPendingXcptDF(pVCpu);
4981 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
4982 }
4983
4984 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4985 return VINF_SUCCESS;
4986 }
4987
4988 TRPMResetTrap(pVCpu);
4989 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
4990 return rc;
4991}
4992
4993
4994/**
4995 * #VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
4996 * Conditional #VMEXIT.
4997 */
4998HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4999{
5000 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5001
5002 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5003
5004 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
5005 VMMRZCallRing3Disable(pVCpu);
5006 HM_DISABLE_PREEMPT_IF_NEEDED();
5007
5008 int rc;
5009 /* If the guest FPU was active at the time of the #NM exit, then it's a guest fault. */
5010 if (pSvmTransient->fWasGuestFPUStateActive)
5011 {
5012 rc = VINF_EM_RAW_GUEST_TRAP;
5013 Assert(CPUMIsGuestFPUStateActive(pVCpu) || HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
5014 }
5015 else
5016 {
5017#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5018 Assert(!pSvmTransient->fWasGuestFPUStateActive);
5019#endif
5020 rc = CPUMR0Trap07Handler(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
5021 Assert(rc == VINF_EM_RAW_GUEST_TRAP || (rc == VINF_SUCCESS && CPUMIsGuestFPUStateActive(pVCpu)));
5022 }
5023
5024 HM_RESTORE_PREEMPT_IF_NEEDED();
5025 VMMRZCallRing3Enable(pVCpu);
5026
5027 if (rc == VINF_SUCCESS)
5028 {
5029 /* Guest FPU state was activated, we'll want to change CR0 FPU intercepts before the next VM-reentry. */
5030 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
5031 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
5032 pVCpu->hm.s.fUseGuestFpu = true;
5033 }
5034 else
5035 {
5036 /* Forward #NM to the guest. */
5037 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
5038 hmR0SvmSetPendingXcptNM(pVCpu);
5039 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
5040 }
5041 return VINF_SUCCESS;
5042}
5043
5044
5045/**
5046 * #VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
5047 * Conditional #VMEXIT.
5048 */
5049HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5050{
5051 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5052
5053 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5054
5055 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
5056
5057 if (!(pCtx->cr0 & X86_CR0_NE))
5058 {
5059 PVM pVM = pVCpu->CTX_SUFF(pVM);
5060 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5061 unsigned cbOp;
5062 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
5063 if (RT_SUCCESS(rc))
5064 {
5065 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
5066 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
5067 if (RT_SUCCESS(rc))
5068 pCtx->rip += cbOp;
5069 }
5070 else
5071 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5072 return rc;
5073 }
5074
5075 hmR0SvmSetPendingXcptMF(pVCpu);
5076 return VINF_SUCCESS;
5077}
5078
5079
5080/**
5081 * #VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
5082 * #VMEXIT.
5083 */
5084HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5085{
5086 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5087
5088 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5089
5090 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
5091
5092
5093 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
5094 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
5095 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5096 PVM pVM = pVCpu->CTX_SUFF(pVM);
5097 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
5098 if (rc == VINF_EM_RAW_GUEST_TRAP)
5099 {
5100 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
5101 if (CPUMIsHyperDebugStateActive(pVCpu))
5102 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
5103
5104 /* Reflect the exception back to the guest. */
5105 hmR0SvmSetPendingXcptDB(pVCpu);
5106 rc = VINF_SUCCESS;
5107 }
5108
5109 /*
5110 * Update DR6.
5111 */
5112 if (CPUMIsHyperDebugStateActive(pVCpu))
5113 {
5114 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
5115 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
5116 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
5117 }
5118 else
5119 {
5120 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
5121 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
5122 }
5123
5124 return rc;
5125}
5126
5127/** @} */
5128
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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