VirtualBox

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

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

VMM/HM: Preemption hoooks, work in progress.

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