VirtualBox

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

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

VMM/HMSVMR0: todo addressed in r91390.

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

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