VirtualBox

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

Last change on this file since 47719 was 47718, checked in by vboxsync, 11 years ago

More single stepping work.

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

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