VirtualBox

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

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

VMM/HM: One extra char. to make typing without autocomplete easier.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 180.0 KB
Line 
1/* $Id: HMSVMR0.cpp 47771 2013-08-15 14:35:16Z 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
1621 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
1622
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 if (pVCpu->hm.s.fLeaveDone)
1899 {
1900 RTThreadPreemptRestore(&PreemptState);
1901 return;
1902 }
1903 }
1904
1905 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
1906 if (CPUMIsGuestFPUStateActive(pVCpu))
1907 {
1908 CPUMR0SaveGuestFPU(pVM, pVCpu, pCtx);
1909 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
1910 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
1911 }
1912
1913 /*
1914 * Restore host debug registers if necessary and resync on next R0 reentry.
1915 */
1916#ifdef VBOX_STRICT
1917 if (CPUMIsHyperDebugStateActive(pVCpu))
1918 {
1919 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1920 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
1921 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
1922 }
1923#endif
1924 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */))
1925 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
1926
1927 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1928 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1929
1930 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
1931 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
1932 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
1933 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
1934 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1935
1936 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
1937
1938 /* Restore preemption if we previous disabled it ourselves. */
1939 if (fPreemptDisabled)
1940 {
1941 pVCpu->hm.s.fLeaveDone = true;
1942 RTThreadPreemptRestore(&PreemptState);
1943 }
1944}
1945
1946
1947/**
1948 * Does the necessary state syncing before doing a longjmp to ring-3.
1949 *
1950 * @param pVM Pointer to the VM.
1951 * @param pVCpu Pointer to the VMCPU.
1952 * @param pCtx Pointer to the guest-CPU context.
1953 *
1954 * @remarks No-long-jmp zone!!!
1955 */
1956static void hmR0SvmLongJmpToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1957{
1958 hmR0SvmLeave(pVM, pVCpu, pCtx);
1959}
1960
1961
1962/**
1963 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
1964 * any remaining host state) before we longjump to ring-3 and possibly get
1965 * preempted.
1966 *
1967 * @param pVCpu Pointer to the VMCPU.
1968 * @param enmOperation The operation causing the ring-3 longjump.
1969 * @param pvUser The user argument (pointer to the possibly
1970 * out-of-date guest-CPU context).
1971 *
1972 * @remarks Must never be called with @a enmOperation ==
1973 * VMMCALLRING3_VM_R0_ASSERTION.
1974 */
1975DECLCALLBACK(void) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
1976{
1977 /* VMMRZCallRing3() already makes sure we never get called as a result of an longjmp due to an assertion, */
1978 Assert(pVCpu);
1979 Assert(pvUser);
1980 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1981 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1982
1983 VMMRZCallRing3Disable(pVCpu);
1984 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1985
1986 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
1987 hmR0SvmLongJmpToRing3(pVCpu->CTX_SUFF(pVM), pVCpu, (PCPUMCTX)pvUser);
1988
1989 VMMRZCallRing3Enable(pVCpu);
1990}
1991
1992
1993/**
1994 * Take necessary actions before going back to ring-3.
1995 *
1996 * An action requires us to go back to ring-3. This function does the necessary
1997 * steps before we can safely return to ring-3. This is not the same as longjmps
1998 * to ring-3, this is voluntary.
1999 *
2000 * @param pVM Pointer to the VM.
2001 * @param pVCpu Pointer to the VMCPU.
2002 * @param pCtx Pointer to the guest-CPU context.
2003 * @param rcExit The reason for exiting to ring-3. Can be
2004 * VINF_VMM_UNKNOWN_RING3_CALL.
2005 */
2006static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
2007{
2008 Assert(pVM);
2009 Assert(pVCpu);
2010 Assert(pCtx);
2011 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2012
2013 if (RT_UNLIKELY(rcExit == VERR_SVM_INVALID_GUEST_STATE))
2014 {
2015 /* We don't need to do any syncing here, we're not going to come back to execute anything again. */
2016 return;
2017 }
2018
2019 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
2020 VMMRZCallRing3Disable(pVCpu);
2021 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
2022
2023 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
2024 if (pVCpu->hm.s.Event.fPending)
2025 {
2026 hmR0SvmPendingEventToTrpmTrap(pVCpu);
2027 Assert(!pVCpu->hm.s.Event.fPending);
2028 }
2029
2030 /* Sync. the necessary state for going back to ring-3. */
2031 hmR0SvmLeave(pVM, pVCpu, pCtx);
2032 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2033
2034 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2035 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
2036 | CPUM_CHANGED_LDTR
2037 | CPUM_CHANGED_GDTR
2038 | CPUM_CHANGED_IDTR
2039 | CPUM_CHANGED_TR
2040 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2041 if ( pVM->hm.s.fNestedPaging
2042 && CPUMIsGuestPagingEnabledEx(pCtx))
2043 {
2044 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2045 }
2046
2047 /* Make sure we've undo the trap flag if we tried to single step something. */
2048 if (pVCpu->hm.s.fClearTrapFlag)
2049 {
2050 pCtx->eflags.Bits.u1TF = 0;
2051 pVCpu->hm.s.fClearTrapFlag = false;
2052 }
2053
2054 /* On our way back from ring-3 the following needs to be done. */
2055 /** @todo This can change with preemption hooks. */
2056 if (rcExit == VINF_EM_RAW_INTERRUPT)
2057 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
2058 else
2059 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
2060
2061 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
2062 VMMRZCallRing3Enable(pVCpu);
2063}
2064
2065
2066/**
2067 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
2068 * intercepts.
2069 *
2070 * @param pVCpu Pointer to the VMCPU.
2071 *
2072 * @remarks No-long-jump zone!!!
2073 */
2074static void hmR0SvmUpdateTscOffsetting(PVMCPU pVCpu)
2075{
2076 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2077 if (TMCpuTickCanUseRealTSC(pVCpu, &pVmcb->ctrl.u64TSCOffset))
2078 {
2079 uint64_t u64CurTSC = ASMReadTSC();
2080 if (u64CurTSC + pVmcb->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
2081 {
2082 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
2083 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
2084 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
2085 }
2086 else
2087 {
2088 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
2089 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
2090 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
2091 }
2092 }
2093 else
2094 {
2095 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
2096 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
2097 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
2098 }
2099
2100 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2101}
2102
2103
2104/**
2105 * Sets an event as a pending event to be injected into the guest.
2106 *
2107 * @param pVCpu Pointer to the VMCPU.
2108 * @param pEvent Pointer to the SVM event.
2109 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
2110 * page-fault.
2111 *
2112 * @remarks Statistics counter assumes this is a guest event being reflected to
2113 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
2114 */
2115DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
2116{
2117 Assert(!pVCpu->hm.s.Event.fPending);
2118 Assert(pEvent->n.u1Valid);
2119
2120 pVCpu->hm.s.Event.u64IntrInfo = pEvent->u;
2121 pVCpu->hm.s.Event.fPending = true;
2122 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
2123
2124 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2125 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2126
2127 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
2128}
2129
2130
2131/**
2132 * Injects an event into the guest upon VMRUN by updating the relevant field
2133 * in the VMCB.
2134 *
2135 * @param pVCpu Pointer to the VMCPU.
2136 * @param pVmcb Pointer to the guest VMCB.
2137 * @param pCtx Pointer to the guest-CPU context.
2138 * @param pEvent Pointer to the event.
2139 *
2140 * @remarks No-long-jump zone!!!
2141 * @remarks Requires CR0!
2142 */
2143DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
2144{
2145 pVmcb->ctrl.EventInject.u = pEvent->u;
2146 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
2147
2148 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2149 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2150}
2151
2152
2153
2154/**
2155 * Converts any TRPM trap into a pending HM event. This is typically used when
2156 * entering from ring-3 (not longjmp returns).
2157 *
2158 * @param pVCpu Pointer to the VMCPU.
2159 */
2160static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
2161{
2162 Assert(TRPMHasTrap(pVCpu));
2163 Assert(!pVCpu->hm.s.Event.fPending);
2164
2165 uint8_t uVector;
2166 TRPMEVENT enmTrpmEvent;
2167 RTGCUINT uErrCode;
2168 RTGCUINTPTR GCPtrFaultAddress;
2169 uint8_t cbInstr;
2170
2171 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
2172 AssertRC(rc);
2173
2174 SVMEVENT Event;
2175 Event.u = 0;
2176 Event.n.u1Valid = 1;
2177 Event.n.u8Vector = uVector;
2178
2179 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
2180 if (enmTrpmEvent == TRPM_TRAP)
2181 {
2182 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2183 switch (uVector)
2184 {
2185 case X86_XCPT_PF:
2186 case X86_XCPT_DF:
2187 case X86_XCPT_TS:
2188 case X86_XCPT_NP:
2189 case X86_XCPT_SS:
2190 case X86_XCPT_GP:
2191 case X86_XCPT_AC:
2192 {
2193 Event.n.u1ErrorCodeValid = 1;
2194 Event.n.u32ErrorCode = uErrCode;
2195 break;
2196 }
2197 }
2198 }
2199 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
2200 {
2201 if (uVector == X86_XCPT_NMI)
2202 Event.n.u3Type = SVM_EVENT_NMI;
2203 else
2204 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2205 }
2206 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
2207 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
2208 else
2209 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
2210
2211 rc = TRPMResetTrap(pVCpu);
2212 AssertRC(rc);
2213
2214 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
2215 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
2216
2217 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
2218 STAM_COUNTER_DEC(&pVCpu->hm.s.StatInjectPendingReflect);
2219}
2220
2221
2222/**
2223 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
2224 * AMD-V to execute any instruction.
2225 *
2226 * @param pvCpu Pointer to the VMCPU.
2227 */
2228static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
2229{
2230 Assert(pVCpu->hm.s.Event.fPending);
2231 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
2232
2233 SVMEVENT Event;
2234 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2235
2236 uint8_t uVector = Event.n.u8Vector;
2237 uint8_t uVectorType = Event.n.u3Type;
2238
2239 TRPMEVENT enmTrapType;
2240 switch (uVectorType)
2241 {
2242 case SVM_EVENT_EXTERNAL_IRQ:
2243 case SVM_EVENT_NMI:
2244 enmTrapType = TRPM_HARDWARE_INT;
2245 break;
2246 case SVM_EVENT_SOFTWARE_INT:
2247 enmTrapType = TRPM_SOFTWARE_INT;
2248 break;
2249 case SVM_EVENT_EXCEPTION:
2250 enmTrapType = TRPM_TRAP;
2251 break;
2252 default:
2253 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
2254 enmTrapType = TRPM_32BIT_HACK;
2255 break;
2256 }
2257
2258 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
2259
2260 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
2261 AssertRC(rc);
2262
2263 if (Event.n.u1ErrorCodeValid)
2264 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
2265
2266 if ( uVectorType == SVM_EVENT_EXCEPTION
2267 && uVector == X86_XCPT_PF)
2268 {
2269 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
2270 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
2271 }
2272 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
2273 {
2274 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
2275 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
2276 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
2277 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
2278 }
2279 pVCpu->hm.s.Event.fPending = false;
2280}
2281
2282
2283/**
2284 * Gets the guest's interrupt-shadow.
2285 *
2286 * @returns The guest's interrupt-shadow.
2287 * @param pVCpu Pointer to the VMCPU.
2288 * @param pCtx Pointer to the guest-CPU context.
2289 *
2290 * @remarks No-long-jump zone!!!
2291 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
2292 */
2293DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
2294{
2295 /*
2296 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
2297 * inhibit interrupts or clear any existing interrupt-inhibition.
2298 */
2299 uint32_t uIntrState = 0;
2300 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2301 {
2302 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2303 {
2304 /*
2305 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
2306 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
2307 */
2308 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2309 }
2310 else
2311 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
2312 }
2313 return uIntrState;
2314}
2315
2316
2317/**
2318 * Sets the virtual interrupt intercept control in the VMCB which
2319 * instructs AMD-V to cause a #VMEXIT as soon as the guest is in a state to
2320 * receive interrupts.
2321 *
2322 * @param pVmcb Pointer to the VMCB.
2323 */
2324DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
2325{
2326 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
2327 {
2328 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
2329 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
2330 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
2331 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
2332
2333 Log4(("Setting VINTR intercept\n"));
2334 }
2335}
2336
2337
2338/**
2339 * Injects any pending events into the guest if the guest is in a state to
2340 * receive them.
2341 *
2342 * @param pVCpu Pointer to the VMCPU.
2343 * @param pCtx Pointer to the guest-CPU context.
2344 */
2345static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2346{
2347 Assert(!TRPMHasTrap(pVCpu));
2348 Log4Func(("\n"));
2349
2350 const bool fIntShadow = !!hmR0SvmGetGuestIntrShadow(pVCpu, pCtx);
2351 const bool fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2352 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2353
2354 SVMEVENT Event;
2355 Event.u = 0;
2356 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2357 {
2358 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2359 Assert(Event.n.u1Valid);
2360 bool fInject = true;
2361 if ( Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
2362 && ( fBlockInt
2363 || fIntShadow))
2364 {
2365 fInject = false;
2366 }
2367 else if ( Event.n.u3Type == SVM_EVENT_NMI
2368 && fIntShadow)
2369 {
2370 fInject = false;
2371 }
2372
2373 if (fInject)
2374 {
2375 Log4(("Injecting pending HM event.\n"));
2376
2377 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2378 pVCpu->hm.s.Event.fPending = false;
2379
2380#ifdef VBOX_WITH_STATISTICS
2381 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2382 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2383 else
2384 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2385#endif
2386 }
2387 else
2388 hmR0SvmSetVirtIntrIntercept(pVmcb);
2389 } /** @todo SMI. SMIs take priority over NMIs. */
2390 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2391 {
2392 if (!fIntShadow)
2393 {
2394 Log4(("Injecting NMI\n"));
2395
2396 Event.n.u1Valid = 1;
2397 Event.n.u8Vector = X86_XCPT_NMI;
2398 Event.n.u3Type = SVM_EVENT_NMI;
2399
2400 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2401 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2402
2403 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2404 }
2405 else
2406 hmR0SvmSetVirtIntrIntercept(pVmcb);
2407 }
2408 else if (VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)))
2409 {
2410 /* Check if there are guest external interrupts (PIC/APIC) pending and inject them, if the guest can receive them. */
2411 if ( !fBlockInt
2412 && !fIntShadow)
2413 {
2414 uint8_t u8Interrupt;
2415 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2416 if (RT_SUCCESS(rc))
2417 {
2418 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2419
2420 Event.n.u1Valid = 1;
2421 Event.n.u8Vector = u8Interrupt;
2422 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2423
2424 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2425 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2426 }
2427 else
2428 {
2429 /** @todo Does this actually happen? If not turn it into an assertion. */
2430 Assert(!VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
2431 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2432 }
2433 }
2434 else
2435 hmR0SvmSetVirtIntrIntercept(pVmcb);
2436 }
2437
2438 /* Update the guest interrupt shadow in the VMCB. */
2439 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2440}
2441
2442
2443/**
2444 * Reports world-switch error and dumps some useful debug info.
2445 *
2446 * @param pVM Pointer to the VM.
2447 * @param pVCpu Pointer to the VMCPU.
2448 * @param rcVMRun The return code from VMRUN (or
2449 * VERR_SVM_INVALID_GUEST_STATE for invalid
2450 * guest-state).
2451 * @param pCtx Pointer to the guest-CPU context.
2452 */
2453static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2454{
2455 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2456 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2457
2458 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2459 {
2460 HMDumpRegs(pVM, pVCpu, pCtx);
2461#ifdef VBOX_STRICT
2462 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2463 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2464 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2465 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2466 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2467 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2468 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2469 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2470 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2471 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2472 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2473
2474 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2475 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2476 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2477
2478 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2479 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2480 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2481 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2482 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2483 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2484 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2485 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2486 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2487 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2488
2489 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2490 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2491 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2492 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2493 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2494 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2495 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2496 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2497 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2498 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2499 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2500 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2501 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2502 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2503 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2504 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2505 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2506
2507 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2508 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2509
2510 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2511 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2512 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2513 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2514 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2515 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2516 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2517 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2518 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2519 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2520 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2521 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2522 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2523 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2524 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2525 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2526 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2527 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2528 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2529 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2530
2531 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2532 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2533
2534 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2535 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2536 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2537 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2538
2539 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2540 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2541
2542 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2543 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2544 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2545 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2546
2547 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2548 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2549 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2550 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2551 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2552 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2553 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2554
2555 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2556 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2557 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2558 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2559
2560 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2561 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2562 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2563
2564 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2565 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2566 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2567 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2568 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2569 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2570 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2571 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2572 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2573 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2574 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2575 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2576#endif
2577 }
2578 else
2579 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2580}
2581
2582
2583/**
2584 * Check per-VM and per-VCPU force flag actions that require us to go back to
2585 * ring-3 for one reason or another.
2586 *
2587 * @returns VBox status code (information status code included).
2588 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2589 * ring-3.
2590 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2591 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2592 * interrupts)
2593 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2594 * all EMTs to be in ring-3.
2595 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2596 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2597 * to the EM loop.
2598 *
2599 * @param pVM Pointer to the VM.
2600 * @param pVCpu Pointer to the VMCPU.
2601 * @param pCtx Pointer to the guest-CPU context.
2602 */
2603static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2604{
2605 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2606
2607 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
2608 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2609 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
2610
2611 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
2612 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2613 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
2614 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2615 {
2616 /* Pending PGM C3 sync. */
2617 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2618 {
2619 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2620 if (rc != VINF_SUCCESS)
2621 {
2622 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2623 return rc;
2624 }
2625 }
2626
2627 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2628 /* -XXX- what was that about single stepping? */
2629 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2630 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2631 {
2632 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2633 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2634 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2635 return rc;
2636 }
2637
2638 /* Pending VM request packets, such as hardware interrupts. */
2639 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2640 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2641 {
2642 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2643 return VINF_EM_PENDING_REQUEST;
2644 }
2645
2646 /* Pending PGM pool flushes. */
2647 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2648 {
2649 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2650 return VINF_PGM_POOL_FLUSH_PENDING;
2651 }
2652
2653 /* Pending DMA requests. */
2654 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2655 {
2656 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2657 return VINF_EM_RAW_TO_R3;
2658 }
2659 }
2660
2661 return VINF_SUCCESS;
2662}
2663
2664
2665/**
2666 * Does the preparations before executing guest code in AMD-V.
2667 *
2668 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2669 * recompiler. We must be cautious what we do here regarding committing
2670 * guest-state information into the the VMCB assuming we assuredly execute the
2671 * guest in AMD-V. If we fall back to the recompiler after updating the VMCB and
2672 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2673 * that the recompiler can (and should) use them when it resumes guest
2674 * execution. Otherwise such operations must be done when we can no longer
2675 * exit to ring-3.
2676 *
2677 * @returns VBox status code (informational status codes included).
2678 * @retval VINF_SUCCESS if we can proceed with running the guest.
2679 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2680 *
2681 * @param pVM Pointer to the VM.
2682 * @param pVCpu Pointer to the VMCPU.
2683 * @param pCtx Pointer to the guest-CPU context.
2684 * @param pSvmTransient Pointer to the SVM transient structure.
2685 */
2686DECLINLINE(int) hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2687{
2688 /* Check force flag actions that might require us to go back to ring-3. */
2689 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2690 if (rc != VINF_SUCCESS)
2691 return rc;
2692
2693#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2694 /* We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.) */
2695 pSvmTransient->uEFlags = ASMIntDisableFlags();
2696 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2697 {
2698 ASMSetFlags(pSvmTransient->uEFlags);
2699 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2700 /* Don't use VINF_EM_RAW_INTERRUPT_HYPER as we can't assume the host does kernel preemption. Maybe some day? */
2701 return VINF_EM_RAW_INTERRUPT;
2702 }
2703 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2704 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2705#endif
2706
2707 /* Convert any pending TRPM traps to HM events for injection. */
2708 /** @todo Optimization: move this before disabling interrupts, restore state
2709 * using pVmcb->ctrl.EventInject.u. */
2710 if (TRPMHasTrap(pVCpu))
2711 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2712
2713 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
2714
2715 return VINF_SUCCESS;
2716}
2717
2718
2719/**
2720 * Prepares to run guest code in AMD-V and we've committed to doing so. This
2721 * means there is no backing out to ring-3 or anywhere else at this
2722 * point.
2723 *
2724 * @param pVM Pointer to the VM.
2725 * @param pVCpu Pointer to the VMCPU.
2726 * @param pCtx Pointer to the guest-CPU context.
2727 * @param pSvmTransient Pointer to the SVM transient structure.
2728 *
2729 * @remarks Called with preemption disabled.
2730 * @remarks No-long-jump zone!!!
2731 */
2732DECLINLINE(void) hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2733{
2734 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2735 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2736
2737#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2738 /** @todo I don't see the point of this, VMMR0EntryFast() already disables interrupts for the entire period. */
2739 pSvmTransient->uEFlags = ASMIntDisableFlags();
2740 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2741#endif
2742
2743 /*
2744 * Re-enable nested paging (automatically disabled on every VM-exit). See AMD spec. 15.25.3 "Enabling Nested Paging".
2745 * We avoid changing the corresponding VMCB Clean Bit as we're not changing it to a different value since the previous run.
2746 */
2747 /** @todo The above assumption could be wrong. It's not documented what
2748 * should be done wrt to the VMCB Clean Bit, but we'll find out the
2749 * hard way. */
2750 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2751 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
2752
2753#ifdef HMSVM_SYNC_FULL_GUEST_STATE
2754 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_ALL_GUEST;
2755#endif
2756
2757 /* Load the guest state. */
2758 int rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
2759 AssertRC(rc);
2760 AssertMsg(!pVCpu->hm.s.fContextUseFlags, ("fContextUseFlags =%#x\n", pVCpu->hm.s.fContextUseFlags));
2761 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
2762
2763 /* If VMCB Clean Bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
2764 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
2765 pVmcb->ctrl.u64VmcbCleanBits = 0;
2766
2767 /*
2768 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
2769 * so we can update it on the way back if the guest changed the TPR.
2770 */
2771 if (pVCpu->hm.s.svm.fSyncVTpr)
2772 {
2773 if (pVM->hm.s.fTPRPatchingActive)
2774 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
2775 else
2776 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
2777 }
2778
2779 /* Setup TSC offsetting. */
2780 if ( pSvmTransient->fUpdateTscOffsetting
2781 || HMR0GetCurrentCpu()->idCpu != pVCpu->hm.s.idLastCpu)
2782 {
2783 hmR0SvmUpdateTscOffsetting(pVCpu);
2784 pSvmTransient->fUpdateTscOffsetting = false;
2785 }
2786
2787 /* Flush the appropriate tagged-TLB entries. */
2788 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB-shootdowns, set this across the world switch. */
2789 hmR0SvmFlushTaggedTlb(pVCpu);
2790 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
2791
2792 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
2793
2794 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
2795 to start executing. */
2796
2797 /*
2798 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
2799 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
2800 *
2801 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
2802 */
2803 pSvmTransient->fRestoreTscAuxMsr = false;
2804 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2805 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
2806 {
2807 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
2808 uint64_t u64GuestTscAux = 0;
2809 int rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
2810 AssertRC(rc2);
2811 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
2812 {
2813 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
2814 pSvmTransient->fRestoreTscAuxMsr = true;
2815 }
2816 }
2817}
2818
2819
2820/**
2821 * Wrapper for running the guest code in AMD-V.
2822 *
2823 * @returns VBox strict status code.
2824 * @param pVM Pointer to the VM.
2825 * @param pVCpu Pointer to the VMCPU.
2826 * @param pCtx Pointer to the guest-CPU context.
2827 *
2828 * @remarks No-long-jump zone!!!
2829 */
2830DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2831{
2832 /*
2833 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
2834 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
2835 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
2836 */
2837#ifdef VBOX_WITH_KERNEL_USING_XMM
2838 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
2839 pVCpu->hm.s.svm.pfnVMRun);
2840#else
2841 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
2842#endif
2843}
2844
2845
2846/**
2847 * Performs some essential restoration of state after running guest code in
2848 * AMD-V.
2849 *
2850 * @param pVM Pointer to the VM.
2851 * @param pVCpu Pointer to the VMCPU.
2852 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
2853 * out-of-sync. Make sure to update the required fields
2854 * before using them.
2855 * @param pSvmTransient Pointer to the SVM transient structure.
2856 * @param rcVMRun Return code of VMRUN.
2857 *
2858 * @remarks Called with interrupts disabled.
2859 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
2860 * unconditionally when it is safe to do so.
2861 */
2862DECLINLINE(void) hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
2863{
2864 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2865
2866 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB-shootdowns. */
2867 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for TLB-shootdowns. */
2868
2869 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2870 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
2871
2872 if (pSvmTransient->fRestoreTscAuxMsr)
2873 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
2874
2875 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
2876 {
2877 /** @todo Find a way to fix hardcoding a guestimate. */
2878 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset - 0x400);
2879 }
2880
2881 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
2882 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
2883 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2884
2885 Assert(!(ASMGetFlags() & X86_EFL_IF));
2886 ASMSetFlags(pSvmTransient->uEFlags); /* Enable interrupts. */
2887
2888 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pMixedCtx);
2889 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
2890
2891 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
2892 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
2893 {
2894 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
2895 return;
2896 }
2897
2898 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
2899 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
2900 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
2901
2902 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
2903 {
2904 if (pVCpu->hm.s.svm.fSyncVTpr)
2905 {
2906 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
2907 if ( pVM->hm.s.fTPRPatchingActive
2908 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
2909 {
2910 int rc = PDMApicSetTPR(pVCpu, pMixedCtx->msrLSTAR & 0xff);
2911 AssertRC(rc);
2912 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
2913 }
2914 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
2915 {
2916 int rc = PDMApicSetTPR(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
2917 AssertRC(rc);
2918 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
2919 }
2920 }
2921 }
2922}
2923
2924
2925/**
2926 * Runs the guest code using AMD-V.
2927 *
2928 * @returns VBox status code.
2929 * @param pVM Pointer to the VM.
2930 * @param pVCpu Pointer to the VMCPU.
2931 * @param pCtx Pointer to the guest-CPU context.
2932 */
2933VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2934{
2935 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2936 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2937
2938 SVMTRANSIENT SvmTransient;
2939 SvmTransient.fUpdateTscOffsetting = true;
2940 uint32_t cLoops = 0;
2941 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2942 int rc = VERR_INTERNAL_ERROR_5;
2943
2944 for (;; cLoops++)
2945 {
2946 Assert(!HMR0SuspendPending());
2947 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
2948 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
2949 (unsigned)RTMpCpuId(), cLoops));
2950
2951 /* Preparatory work for running guest code, this may return to ring-3 for some last minute updates. */
2952 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
2953 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
2954 if (rc != VINF_SUCCESS)
2955 break;
2956
2957 /*
2958 * No longjmps to ring-3 from this point on!!!
2959 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
2960 * This also disables flushing of the R0-logger instance (if any).
2961 */
2962 VMMRZCallRing3Disable(pVCpu);
2963 VMMRZCallRing3RemoveNotification(pVCpu);
2964 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
2965
2966 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
2967
2968 /*
2969 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
2970 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
2971 */
2972 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
2973 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
2974 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
2975 {
2976 if (rc == VINF_SUCCESS)
2977 rc = VERR_SVM_INVALID_GUEST_STATE;
2978 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
2979 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
2980 return rc;
2981 }
2982
2983 /* Handle the #VMEXIT. */
2984 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
2985 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
2986 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
2987 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
2988 if (rc != VINF_SUCCESS)
2989 break;
2990 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
2991 {
2992 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
2993 rc = VINF_EM_RAW_INTERRUPT;
2994 break;
2995 }
2996 }
2997
2998 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
2999 if (rc == VERR_EM_INTERPRETER)
3000 rc = VINF_EM_RAW_EMULATE_INSTR;
3001 else if (rc == VINF_EM_RESET)
3002 rc = VINF_EM_TRIPLE_FAULT;
3003 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
3004 return rc;
3005}
3006
3007
3008/**
3009 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
3010 *
3011 * @returns VBox status code (informational status codes included).
3012 * @param pVCpu Pointer to the VMCPU.
3013 * @param pCtx Pointer to the guest-CPU context.
3014 * @param pSvmTransient Pointer to the SVM transient structure.
3015 */
3016DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3017{
3018 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
3019 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
3020
3021 /*
3022 * The ordering of the case labels is based on most-frequently-occurring VM-exits for most guests under
3023 * normal workloads (for some definition of "normal").
3024 */
3025 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
3026 switch (pSvmTransient->u64ExitCode)
3027 {
3028 case SVM_EXIT_NPF:
3029 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
3030
3031 case SVM_EXIT_IOIO:
3032 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
3033
3034 case SVM_EXIT_RDTSC:
3035 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
3036
3037 case SVM_EXIT_RDTSCP:
3038 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
3039
3040 case SVM_EXIT_CPUID:
3041 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
3042
3043 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
3044 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
3045
3046 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
3047 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
3048
3049 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
3050 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
3051
3052 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
3053 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
3054
3055 case SVM_EXIT_MONITOR:
3056 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
3057
3058 case SVM_EXIT_MWAIT:
3059 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
3060
3061 case SVM_EXIT_HLT:
3062 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
3063
3064 case SVM_EXIT_READ_CR0:
3065 case SVM_EXIT_READ_CR3:
3066 case SVM_EXIT_READ_CR4:
3067 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
3068
3069 case SVM_EXIT_WRITE_CR0:
3070 case SVM_EXIT_WRITE_CR3:
3071 case SVM_EXIT_WRITE_CR4:
3072 case SVM_EXIT_WRITE_CR8:
3073 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
3074
3075 case SVM_EXIT_VINTR:
3076 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
3077
3078 case SVM_EXIT_INTR:
3079 case SVM_EXIT_FERR_FREEZE:
3080 case SVM_EXIT_NMI:
3081 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
3082
3083 case SVM_EXIT_MSR:
3084 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
3085
3086 case SVM_EXIT_INVLPG:
3087 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
3088
3089 case SVM_EXIT_WBINVD:
3090 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
3091
3092 case SVM_EXIT_INVD:
3093 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
3094
3095 case SVM_EXIT_RDPMC:
3096 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
3097
3098 default:
3099 {
3100 switch (pSvmTransient->u64ExitCode)
3101 {
3102 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
3103 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
3104 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
3105 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
3106 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3107
3108 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
3109 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
3110 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3111 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3112 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3113
3114 case SVM_EXIT_TASK_SWITCH:
3115 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3116
3117 case SVM_EXIT_VMMCALL:
3118 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3119
3120 case SVM_EXIT_SHUTDOWN:
3121 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3122
3123 case SVM_EXIT_SMI:
3124 case SVM_EXIT_INIT:
3125 {
3126 /*
3127 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3128 * we want to know about it so log the exit code and bail.
3129 */
3130 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3131 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3132 return VERR_SVM_UNEXPECTED_EXIT;
3133 }
3134
3135 case SVM_EXIT_INVLPGA:
3136 case SVM_EXIT_RSM:
3137 case SVM_EXIT_VMRUN:
3138 case SVM_EXIT_VMLOAD:
3139 case SVM_EXIT_VMSAVE:
3140 case SVM_EXIT_STGI:
3141 case SVM_EXIT_CLGI:
3142 case SVM_EXIT_SKINIT:
3143 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3144
3145#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3146 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3147 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3148 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3149 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3150 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3151 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3152 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3153 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3154 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3155 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3156 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3157 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3158 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3159 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3160 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3161 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3162 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3163 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3164 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3165
3166 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3167 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3168 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3169 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3170 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3171 {
3172 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3173 SVMEVENT Event;
3174 Event.u = 0;
3175 Event.n.u1Valid = 1;
3176 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3177 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3178
3179 switch (Event.n.u8Vector)
3180 {
3181 case X86_XCPT_DE:
3182 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3183 break;
3184
3185 case X86_XCPT_BP:
3186 /** Saves the wrong EIP on the stack (pointing to the int3) instead of the
3187 * next instruction. */
3188 /** @todo Investigate this later. */
3189 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
3190 break;
3191
3192 case X86_XCPT_UD:
3193 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
3194 break;
3195
3196 case X86_XCPT_NP:
3197 Event.n.u1ErrorCodeValid = 1;
3198 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3199 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3200 break;
3201
3202 case X86_XCPT_SS:
3203 Event.n.u1ErrorCodeValid = 1;
3204 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3205 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3206 break;
3207
3208 case X86_XCPT_GP:
3209 Event.n.u1ErrorCodeValid = 1;
3210 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3211 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3212 break;
3213
3214 default:
3215 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3216 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3217 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3218 }
3219
3220 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3221 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3222 return VINF_SUCCESS;
3223 }
3224#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3225
3226 default:
3227 {
3228 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3229 pVCpu->hm.s.u32HMError = u32ExitCode;
3230 return VERR_SVM_UNKNOWN_EXIT;
3231 }
3232 }
3233 }
3234 }
3235 return VERR_INTERNAL_ERROR_5; /* Should never happen. */
3236}
3237
3238
3239#ifdef DEBUG
3240/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3241# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3242 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3243
3244# define HMSVM_ASSERT_PREEMPT_CPUID() \
3245 do \
3246 { \
3247 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3248 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3249 } while (0)
3250
3251# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3252 do { \
3253 AssertPtr(pVCpu); \
3254 AssertPtr(pCtx); \
3255 AssertPtr(pSvmTransient); \
3256 Assert(ASMIntAreEnabled()); \
3257 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
3258 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3259 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)); \
3260 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
3261 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3262 HMSVM_ASSERT_PREEMPT_CPUID(); \
3263 } while (0)
3264#else /* Release builds */
3265# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { } while(0)
3266#endif
3267
3268
3269/**
3270 * Worker for hmR0SvmInterpretInvlpg().
3271 *
3272 * @return VBox status code.
3273 * @param pVCpu Pointer to the VMCPU.
3274 * @param pCpu Pointer to the disassembler state.
3275 * @param pRegFrame Pointer to the register frame.
3276 */
3277static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
3278{
3279 DISQPVPARAMVAL Param1;
3280 RTGCPTR GCPtrPage;
3281
3282 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3283 if (RT_FAILURE(rc))
3284 return VERR_EM_INTERPRETER;
3285
3286 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3287 || Param1.type == DISQPV_TYPE_ADDRESS)
3288 {
3289 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3290 return VERR_EM_INTERPRETER;
3291
3292 GCPtrPage = Param1.val.val64;
3293 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, pRegFrame, GCPtrPage);
3294 rc = VBOXSTRICTRC_VAL(rc2);
3295 }
3296 else
3297 {
3298 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3299 rc = VERR_EM_INTERPRETER;
3300 }
3301
3302 return rc;
3303}
3304
3305
3306/**
3307 * Interprets INVLPG.
3308 *
3309 * @returns VBox status code.
3310 * @retval VINF_* Scheduling instructions.
3311 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3312 * @retval VERR_* Fatal errors.
3313 *
3314 * @param pVM Pointer to the VM.
3315 * @param pRegFrame Pointer to the register frame.
3316 *
3317 * @remarks Updates the RIP if the instruction was executed successfully.
3318 */
3319static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
3320{
3321 /* Only allow 32 & 64 bit code. */
3322 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3323 {
3324 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3325 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3326 if ( RT_SUCCESS(rc)
3327 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3328 {
3329 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
3330 if (RT_SUCCESS(rc))
3331 pRegFrame->rip += pDis->cbInstr;
3332 return rc;
3333 }
3334 else
3335 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3336 }
3337 return VERR_EM_INTERPRETER;
3338}
3339
3340
3341/**
3342 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
3343 *
3344 * @param pVCpu Pointer to the VMCPU.
3345 */
3346DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3347{
3348 SVMEVENT Event;
3349 Event.u = 0;
3350 Event.n.u1Valid = 1;
3351 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3352 Event.n.u8Vector = X86_XCPT_UD;
3353 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3354}
3355
3356
3357/**
3358 * Sets a debug (#DB) exception as pending-for-injection into the VM.
3359 *
3360 * @param pVCpu Pointer to the VMCPU.
3361 */
3362DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3363{
3364 SVMEVENT Event;
3365 Event.u = 0;
3366 Event.n.u1Valid = 1;
3367 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3368 Event.n.u8Vector = X86_XCPT_DB;
3369 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3370}
3371
3372
3373/**
3374 * Sets a page fault (#PF) exception as pending-for-injection into the VM.
3375 *
3376 * @param pVCpu Pointer to the VMCPU.
3377 * @param pCtx Pointer to the guest-CPU context.
3378 * @param u32ErrCode The error-code for the page-fault.
3379 * @param uFaultAddress The page fault address (CR2).
3380 *
3381 * @remarks This updates the guest CR2 with @a uFaultAddress!
3382 */
3383DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3384{
3385 SVMEVENT Event;
3386 Event.u = 0;
3387 Event.n.u1Valid = 1;
3388 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3389 Event.n.u8Vector = X86_XCPT_PF;
3390 Event.n.u1ErrorCodeValid = 1;
3391 Event.n.u32ErrorCode = u32ErrCode;
3392
3393 /* Update CR2 of the guest. */
3394 if (pCtx->cr2 != uFaultAddress)
3395 {
3396 pCtx->cr2 = uFaultAddress;
3397 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR2;
3398 }
3399
3400 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3401}
3402
3403
3404/**
3405 * Sets a device-not-available (#NM) exception as pending-for-injection into the
3406 * VM.
3407 *
3408 * @param pVCpu Pointer to the VMCPU.
3409 */
3410DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3411{
3412 SVMEVENT Event;
3413 Event.u = 0;
3414 Event.n.u1Valid = 1;
3415 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3416 Event.n.u8Vector = X86_XCPT_NM;
3417 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3418}
3419
3420
3421/**
3422 * Sets a math-fault (#MF) exception as pending-for-injection into the VM.
3423 *
3424 * @param pVCpu Pointer to the VMCPU.
3425 */
3426DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3427{
3428 SVMEVENT Event;
3429 Event.u = 0;
3430 Event.n.u1Valid = 1;
3431 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3432 Event.n.u8Vector = X86_XCPT_MF;
3433 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3434}
3435
3436
3437/**
3438 * Sets a double fault (#DF) exception as pending-for-injection into the VM.
3439 *
3440 * @param pVCpu Pointer to the VMCPU.
3441 */
3442DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3443{
3444 SVMEVENT Event;
3445 Event.u = 0;
3446 Event.n.u1Valid = 1;
3447 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3448 Event.n.u8Vector = X86_XCPT_DF;
3449 Event.n.u1ErrorCodeValid = 1;
3450 Event.n.u32ErrorCode = 0;
3451 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3452}
3453
3454
3455/**
3456 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3457 * guests. This simply looks up the patch record at EIP and does the required.
3458 *
3459 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3460 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3461 * TPR). See hmR3ReplaceTprInstr() for the details.
3462 *
3463 * @returns VBox status code.
3464 * @param pVM Pointer to the VM.
3465 * @param pVCpu Pointer to the VMCPU.
3466 * @param pCtx Pointer to the guest-CPU context.
3467 */
3468static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3469{
3470 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3471 for (;;)
3472 {
3473 bool fPending;
3474 uint8_t u8Tpr;
3475
3476 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
3477 if (!pPatch)
3478 break;
3479
3480 switch (pPatch->enmType)
3481 {
3482 case HMTPRINSTR_READ:
3483 {
3484 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
3485 AssertRC(rc);
3486
3487 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
3488 AssertRC(rc);
3489 pCtx->rip += pPatch->cbOp;
3490 break;
3491 }
3492
3493 case HMTPRINSTR_WRITE_REG:
3494 case HMTPRINSTR_WRITE_IMM:
3495 {
3496 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
3497 {
3498 uint32_t u32Val;
3499 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
3500 AssertRC(rc);
3501 u8Tpr = u32Val;
3502 }
3503 else
3504 u8Tpr = (uint8_t)pPatch->uSrcOperand;
3505
3506 int rc2 = PDMApicSetTPR(pVCpu, u8Tpr);
3507 AssertRC(rc2);
3508 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3509
3510 pCtx->rip += pPatch->cbOp;
3511 break;
3512 }
3513
3514 default:
3515 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
3516 pVCpu->hm.s.u32HMError = pPatch->enmType;
3517 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
3518 }
3519 }
3520
3521 return VINF_SUCCESS;
3522}
3523
3524/**
3525 * Determines if an exception is a contributory exception. Contributory
3526 * exceptions are ones which can cause double-faults. Page-fault is
3527 * intentionally not included here as it's a conditional contributory exception.
3528 *
3529 * @returns true if the exception is contributory, false otherwise.
3530 * @param uVector The exception vector.
3531 */
3532DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
3533{
3534 switch (uVector)
3535 {
3536 case X86_XCPT_GP:
3537 case X86_XCPT_SS:
3538 case X86_XCPT_NP:
3539 case X86_XCPT_TS:
3540 case X86_XCPT_DE:
3541 return true;
3542 default:
3543 break;
3544 }
3545 return false;
3546}
3547
3548
3549/**
3550 * Handle a condition that occurred while delivering an event through the guest
3551 * IDT.
3552 *
3553 * @returns VBox status code (informational error codes included).
3554 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
3555 * @retval VINF_HM_DOUBLE_FAULT if a #DF condition was detected and we ought to
3556 * continue execution of the guest which will delivery the #DF.
3557 * @retval VINF_EM_RESET if we detected a triple-fault condition.
3558 *
3559 * @param pVCpu Pointer to the VMCPU.
3560 * @param pCtx Pointer to the guest-CPU context.
3561 * @param pSvmTransient Pointer to the SVM transient structure.
3562 *
3563 * @remarks No-long-jump zone!!!
3564 */
3565static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3566{
3567 int rc = VINF_SUCCESS;
3568 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3569
3570 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
3571 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
3572 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
3573 {
3574 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
3575
3576 typedef enum
3577 {
3578 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
3579 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
3580 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
3581 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
3582 } SVMREFLECTXCPT;
3583
3584 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
3585 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
3586 {
3587 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
3588 {
3589 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
3590
3591#ifdef VBOX_STRICT
3592 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
3593 && uExitVector == X86_XCPT_PF)
3594 {
3595 Log4(("IDT: Contributory #PF uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
3596 }
3597#endif
3598 if ( uExitVector == X86_XCPT_PF
3599 && uIdtVector == X86_XCPT_PF)
3600 {
3601 pSvmTransient->fVectoringPF = true;
3602 Log4(("IDT: Vectoring #PF uCR2=%#RX64\n", pCtx->cr2));
3603 }
3604 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
3605 && hmR0SvmIsContributoryXcpt(uExitVector)
3606 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
3607 || uIdtVector == X86_XCPT_PF))
3608 {
3609 enmReflect = SVMREFLECTXCPT_DF;
3610 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntrInfo,
3611 uIdtVector, uExitVector));
3612 }
3613 else if (uIdtVector == X86_XCPT_DF)
3614 {
3615 enmReflect = SVMREFLECTXCPT_TF;
3616 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntrInfo,
3617 uIdtVector, uExitVector));
3618 }
3619 else
3620 enmReflect = SVMREFLECTXCPT_XCPT;
3621 }
3622 else
3623 {
3624 /*
3625 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
3626 * exception to the guest after handling the VM-exit.
3627 */
3628 enmReflect = SVMREFLECTXCPT_XCPT;
3629 }
3630 }
3631 else if (pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
3632 {
3633 /* Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
3634 enmReflect = SVMREFLECTXCPT_XCPT;
3635 }
3636
3637 switch (enmReflect)
3638 {
3639 case SVMREFLECTXCPT_XCPT:
3640 {
3641 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
3642 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
3643
3644 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
3645 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
3646 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
3647 break;
3648 }
3649
3650 case SVMREFLECTXCPT_DF:
3651 {
3652 hmR0SvmSetPendingXcptDF(pVCpu);
3653 rc = VINF_HM_DOUBLE_FAULT;
3654 break;
3655 }
3656
3657 case SVMREFLECTXCPT_TF:
3658 {
3659 rc = VINF_EM_RESET;
3660 break;
3661 }
3662
3663 default:
3664 Assert(rc == VINF_SUCCESS);
3665 break;
3666 }
3667 }
3668 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET);
3669 return rc;
3670}
3671
3672
3673/**
3674 * Advances the guest RIP in the if the NRIP_SAVE feature is supported by the
3675 * CPU, otherwise advances the RIP by @a cb bytes.
3676 *
3677 * @param pVCpu Pointer to the VMCPU.
3678 * @param pCtx Pointer to the guest-CPU context.
3679 * @param cb RIP increment value in bytes.
3680 *
3681 * @remarks Use this function only from #VMEXIT's where the NRIP value is valid
3682 * when NRIP_SAVE is supported by the CPU!
3683 */
3684DECLINLINE(void) hmR0SvmUpdateRip(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
3685{
3686 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
3687 {
3688 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3689 pCtx->rip = pVmcb->ctrl.u64NextRIP;
3690 }
3691 else
3692 pCtx->rip += cb;
3693}
3694
3695
3696/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
3697/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
3698/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
3699
3700/** @name VM-exit handlers.
3701 * @{
3702 */
3703
3704/**
3705 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
3706 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
3707 */
3708HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3709{
3710 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3711
3712 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
3713 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmi);
3714 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
3715 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
3716
3717 /*
3718 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
3719 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
3720 * interrupt it is until the host actually take the interrupt.
3721 *
3722 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
3723 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
3724 */
3725 return VINF_EM_RAW_INTERRUPT;
3726}
3727
3728
3729/**
3730 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
3731 */
3732HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3733{
3734 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3735
3736 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3737 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
3738 int rc = VINF_SUCCESS;
3739 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3740 return rc;
3741}
3742
3743
3744/**
3745 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
3746 */
3747HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3748{
3749 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3750
3751 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3752 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
3753 int rc = VINF_SUCCESS;
3754 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3755 return rc;
3756}
3757
3758
3759/**
3760 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
3761 */
3762HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3763{
3764 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3765 PVM pVM = pVCpu->CTX_SUFF(pVM);
3766 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3767 if (RT_LIKELY(rc == VINF_SUCCESS))
3768 {
3769 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3770 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3771 }
3772 else
3773 {
3774 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
3775 rc = VERR_EM_INTERPRETER;
3776 }
3777 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
3778 return rc;
3779}
3780
3781
3782/**
3783 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
3784 */
3785HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3786{
3787 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3788 PVM pVM = pVCpu->CTX_SUFF(pVM);
3789 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3790 if (RT_LIKELY(rc == VINF_SUCCESS))
3791 {
3792 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3793 pSvmTransient->fUpdateTscOffsetting = true;
3794
3795 /* Single step check. */
3796 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3797 }
3798 else
3799 {
3800 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
3801 rc = VERR_EM_INTERPRETER;
3802 }
3803 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
3804 return rc;
3805}
3806
3807
3808/**
3809 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
3810 */
3811HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3812{
3813 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3814 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
3815 if (RT_LIKELY(rc == VINF_SUCCESS))
3816 {
3817 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3818 pSvmTransient->fUpdateTscOffsetting = true;
3819 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3820 }
3821 else
3822 {
3823 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
3824 rc = VERR_EM_INTERPRETER;
3825 }
3826 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
3827 return rc;
3828}
3829
3830
3831/**
3832 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
3833 */
3834HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3835{
3836 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3837 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3838 if (RT_LIKELY(rc == VINF_SUCCESS))
3839 {
3840 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3841 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3842 }
3843 else
3844 {
3845 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
3846 rc = VERR_EM_INTERPRETER;
3847 }
3848 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
3849 return rc;
3850}
3851
3852
3853/**
3854 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
3855 */
3856HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3857{
3858 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3859 PVM pVM = pVCpu->CTX_SUFF(pVM);
3860 Assert(!pVM->hm.s.fNestedPaging);
3861
3862 /** @todo Decode Assist. */
3863 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx)); /* Updates RIP if successful. */
3864 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
3865 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
3866 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3867 return rc;
3868}
3869
3870
3871/**
3872 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
3873 */
3874HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3875{
3876 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3877 hmR0SvmUpdateRip(pVCpu, pCtx, 1);
3878 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
3879 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3880 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
3881 return rc;
3882}
3883
3884
3885/**
3886 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
3887 */
3888HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3889{
3890 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3891 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3892 if (RT_LIKELY(rc == VINF_SUCCESS))
3893 {
3894 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3895 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3896 }
3897 else
3898 {
3899 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
3900 rc = VERR_EM_INTERPRETER;
3901 }
3902 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
3903 return rc;
3904}
3905
3906
3907/**
3908 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
3909 */
3910HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3911{
3912 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3913 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3914 int rc = VBOXSTRICTRC_VAL(rc2);
3915 if ( rc == VINF_EM_HALT
3916 || rc == VINF_SUCCESS)
3917 {
3918 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3919
3920 if ( rc == VINF_EM_HALT
3921 && EMShouldContinueAfterHalt(pVCpu, pCtx))
3922 {
3923 rc = VINF_SUCCESS;
3924 }
3925 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3926 }
3927 else
3928 {
3929 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
3930 rc = VERR_EM_INTERPRETER;
3931 }
3932 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
3933 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
3934 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
3935 return rc;
3936}
3937
3938
3939/**
3940 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
3941 * Conditional #VMEXIT.
3942 */
3943HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3944{
3945 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3946 return VINF_EM_RESET;
3947}
3948
3949
3950/**
3951 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
3952 */
3953HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3954{
3955 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3956
3957 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
3958
3959 /** @todo Decode Assist. */
3960 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3961 int rc = VBOXSTRICTRC_VAL(rc2);
3962 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
3963 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
3964 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
3965 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
3966 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3967 return rc;
3968}
3969
3970
3971/**
3972 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
3973 */
3974HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3975{
3976 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3977 /** @todo Decode Assist. */
3978 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3979 int rc = VBOXSTRICTRC_VAL(rc2);
3980 if (rc == VINF_SUCCESS)
3981 {
3982 /* RIP has been updated by EMInterpretInstruction(). */
3983 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
3984 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
3985 {
3986 case 0: /* CR0. */
3987 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
3988 break;
3989
3990 case 3: /* CR3. */
3991 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
3992 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
3993 break;
3994
3995 case 4: /* CR4. */
3996 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
3997 break;
3998
3999 case 8: /* CR8 (TPR). */
4000 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4001 break;
4002
4003 default:
4004 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x CRx=%#RX64\n",
4005 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
4006 break;
4007 }
4008 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4009 }
4010 else
4011 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
4012 return rc;
4013}
4014
4015
4016/**
4017 * #VMEXIT handler for instructions that result in a #UD exception delivered to
4018 * the guest.
4019 */
4020HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4021{
4022 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4023 hmR0SvmSetPendingXcptUD(pVCpu);
4024 return VINF_SUCCESS;
4025}
4026
4027
4028/**
4029 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
4030 */
4031HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4032{
4033 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4034 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4035 PVM pVM = pVCpu->CTX_SUFF(pVM);
4036
4037 int rc;
4038 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
4039 {
4040 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
4041
4042 /* Handle TPR patching; intercepted LSTAR write. */
4043 if ( pVM->hm.s.fTPRPatchingActive
4044 && pCtx->ecx == MSR_K8_LSTAR)
4045 {
4046 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
4047 {
4048 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
4049 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
4050 AssertRC(rc2);
4051 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4052 }
4053 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4054 rc = VINF_SUCCESS;
4055 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4056 return rc;
4057 }
4058
4059 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4060 {
4061 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4062 if (RT_LIKELY(rc == VINF_SUCCESS))
4063 {
4064 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4065 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4066 }
4067 else
4068 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
4069 }
4070 else
4071 {
4072 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
4073 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4074 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4075 /* RIP updated by EMInterpretInstruction(). */
4076 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4077 }
4078
4079 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
4080 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
4081 && pCtx->ecx <= MSR_IA32_X2APIC_END)
4082 {
4083 /* We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
4084 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
4085 EMInterpretWrmsr() changes it. */
4086 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4087 }
4088 else if (pCtx->ecx == MSR_K6_EFER)
4089 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_EFER_MSR;
4090 else if (pCtx->ecx == MSR_IA32_TSC)
4091 pSvmTransient->fUpdateTscOffsetting = true;
4092 }
4093 else
4094 {
4095 /* MSR Read access. */
4096 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
4097 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
4098
4099 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4100 {
4101 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4102 if (RT_LIKELY(rc == VINF_SUCCESS))
4103 {
4104 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4105 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4106 }
4107 else
4108 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
4109 }
4110 else
4111 {
4112 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
4113 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4114 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4115 /* RIP updated by EMInterpretInstruction(). */
4116 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4117 }
4118 }
4119
4120 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
4121 return rc;
4122}
4123
4124
4125/**
4126 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
4127 */
4128HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4129{
4130 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4131 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
4132
4133 /* We should -not- get this VM-exit if the guest is debugging. */
4134 AssertMsgReturn(!CPUMIsGuestDebugStateActive(pVCpu),
4135 ("hmR0SvmExitReadDRx: Unexpected exit. pVCpu=%p pCtx=%p\n", pVCpu, pCtx),
4136 VERR_SVM_UNEXPECTED_EXIT);
4137
4138 /*
4139 * Lazy DR0-3 loading?
4140 */
4141 if (!CPUMIsHyperDebugStateActive(pVCpu))
4142 {
4143 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4144 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4145
4146 /* Don't intercept DRx read and writes. */
4147 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4148 pVmcb->ctrl.u16InterceptRdDRx = 0;
4149 pVmcb->ctrl.u16InterceptWrDRx = 0;
4150 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4151
4152 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4153 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4154 Assert(CPUMIsGuestDebugStateActive(pVCpu));
4155
4156 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4157 return VINF_SUCCESS;
4158 }
4159
4160 /*
4161 * Interpret the read/writing of DRx.
4162 */
4163 /** @todo Decode assist. */
4164 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4165 Log5(("hmR0SvmExitReadDRx: Emulatined DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4166 if (RT_LIKELY(rc == VINF_SUCCESS))
4167 {
4168 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4169 /** @todo CPUM should set this flag! */
4170 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
4171 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4172 }
4173 else
4174 Assert(rc == VERR_EM_INTERPRETER);
4175 return VBOXSTRICTRC_TODO(rc);
4176}
4177
4178
4179/**
4180 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
4181 */
4182HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4183{
4184 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4185 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4186 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4187 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4188 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4189 return rc;
4190}
4191
4192
4193/**
4194 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
4195 */
4196HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4197{
4198 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4199
4200 /* I/O operation lookup arrays. */
4201 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4202 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4203 the result (in AL/AX/EAX). */
4204 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4205
4206 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4207 PVM pVM = pVCpu->CTX_SUFF(pVM);
4208
4209 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4210 SVMIOIOEXIT IoExitInfo;
4211 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4212 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4213 uint32_t cbValue = s_aIOSize[uIOWidth];
4214 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4215
4216 if (RT_UNLIKELY(!cbValue))
4217 {
4218 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4219 return VERR_EM_INTERPRETER;
4220 }
4221
4222 VBOXSTRICTRC rcStrict;
4223 if (IoExitInfo.n.u1STR)
4224 {
4225 /* INS/OUTS - I/O String instruction. */
4226 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4227
4228 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4229 * in EXITINFO1? Investigate once this thing is up and running. */
4230
4231 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4232 if (rcStrict == VINF_SUCCESS)
4233 {
4234 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4235 {
4236 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4237 (DISCPUMODE)pDis->uAddrMode, cbValue);
4238 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4239 }
4240 else
4241 {
4242 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4243 (DISCPUMODE)pDis->uAddrMode, cbValue);
4244 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4245 }
4246 }
4247 else
4248 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
4249 }
4250 else
4251 {
4252 /* IN/OUT - I/O instruction. */
4253 Assert(!IoExitInfo.n.u1REP);
4254
4255 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4256 {
4257 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
4258 if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4259 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4260
4261 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4262 }
4263 else
4264 {
4265 uint32_t u32Val = 0;
4266
4267 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
4268 if (IOM_SUCCESS(rcStrict))
4269 {
4270 /* Save result of I/O IN instr. in AL/AX/EAX. */
4271 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4272 }
4273 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4274 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4275
4276 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
4277 }
4278 }
4279
4280 if (IOM_SUCCESS(rcStrict))
4281 {
4282 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
4283 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
4284
4285 /*
4286 * If any I/O breakpoints are armed, we need to check if one triggered
4287 * and take appropriate action.
4288 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
4289 */
4290 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
4291 * execution engines about whether hyper BPs and such are pending. */
4292 uint32_t const uDr7 = pCtx->dr[7];
4293 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
4294 && X86_DR7_ANY_RW_IO(uDr7)
4295 && (pCtx->cr4 & X86_CR4_DE))
4296 || DBGFBpIsHwIoArmed(pVM)))
4297 {
4298 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
4299 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
4300
4301 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
4302 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
4303 {
4304 /* Raise #DB. */
4305 pVmcb->guest.u64DR6 = pCtx->dr[6];
4306 pVmcb->guest.u64DR7 = pCtx->dr[7];
4307 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4308 hmR0SvmSetPendingXcptDB(pVCpu);
4309 }
4310 /* rcStrict is VINF_SUCCESS or in [VINF_EM_FIRST..VINF_EM_LAST]. */
4311 else if ( rcStrict2 != VINF_SUCCESS
4312 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
4313 rcStrict = rcStrict2;
4314 }
4315
4316 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4317 }
4318
4319#ifdef VBOX_STRICT
4320 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4321 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
4322 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4323 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
4324 else
4325 {
4326 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
4327 * statuses, that the VMM device and some others may return. See
4328 * IOM_SUCCESS() for guidance. */
4329 AssertMsg( RT_FAILURE(rcStrict)
4330 || rcStrict == VINF_SUCCESS
4331 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
4332 || rcStrict == VINF_EM_DBG_BREAKPOINT
4333 || rcStrict == VINF_EM_RAW_GUEST_TRAP
4334 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
4335 }
4336#endif
4337 return VBOXSTRICTRC_TODO(rcStrict);
4338}
4339
4340
4341/**
4342 * #VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional
4343 * #VMEXIT.
4344 */
4345HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4346{
4347 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4348 PVM pVM = pVCpu->CTX_SUFF(pVM);
4349 Assert(pVM->hm.s.fNestedPaging);
4350
4351 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4352
4353 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
4354 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4355 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4356 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
4357
4358 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
4359
4360#ifdef VBOX_HM_WITH_GUEST_PATCHING
4361 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
4362 if ( pVM->hm.s.fTRPPatchingAllowed
4363 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80 /* TPR offset. */
4364 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
4365 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
4366 && !CPUMGetGuestCPL(pVCpu)
4367 && !CPUMIsGuestInLongModeEx(pCtx)
4368 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4369 {
4370 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
4371 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4372
4373 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
4374 {
4375 /* Only attempt to patch the instruction once. */
4376 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4377 if (!pPatch)
4378 return VINF_EM_HM_PATCH_TPR_INSTR;
4379 }
4380 }
4381#endif
4382
4383 /*
4384 * Determine the nested paging mode.
4385 */
4386 PGMMODE enmNestedPagingMode;
4387#if HC_ARCH_BITS == 32
4388 if (CPUMIsGuestInLongModeEx(pCtx))
4389 enmNestedPagingMode = PGMMODE_AMD64_NX;
4390 else
4391#endif
4392 enmNestedPagingMode = PGMGetHostMode(pVM);
4393
4394 /*
4395 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
4396 */
4397 int rc;
4398 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
4399 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
4400 {
4401 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
4402 u32ErrCode);
4403 rc = VBOXSTRICTRC_VAL(rc2);
4404
4405 /*
4406 * If we succeed, resume guest execution.
4407 * If we fail in interpreting the instruction because we couldn't get the guest physical address
4408 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
4409 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
4410 * weird case. See @bugref{6043}.
4411 */
4412 if ( rc == VINF_SUCCESS
4413 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4414 || rc == VERR_PAGE_NOT_PRESENT)
4415 {
4416 /* Successfully handled MMIO operation. */
4417 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4418 rc = VINF_SUCCESS;
4419 }
4420 return rc;
4421 }
4422
4423 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
4424 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
4425 TRPMResetTrap(pVCpu);
4426
4427 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
4428
4429 /*
4430 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
4431 */
4432 if ( rc == VINF_SUCCESS
4433 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4434 || rc == VERR_PAGE_NOT_PRESENT)
4435 {
4436 /* We've successfully synced our shadow page tables. */
4437 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4438 rc = VINF_SUCCESS;
4439 }
4440
4441 return rc;
4442}
4443
4444
4445/**
4446 * #VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional #VMEXIT.
4447 */
4448HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4449{
4450 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4451
4452 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4453 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one before reentry. */
4454 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
4455
4456 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
4457 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
4458 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
4459
4460 /* Deliver the pending interrupt via hmR0SvmPreRunGuest()->hmR0SvmInjectEventVmcb() and resume guest execution. */
4461 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
4462 return VINF_SUCCESS;
4463}
4464
4465
4466/**
4467 * #VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional #VMEXIT.
4468 */
4469HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4470{
4471 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4472
4473#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
4474 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4475#endif
4476
4477 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
4478 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4479 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
4480 && pVCpu->hm.s.Event.fPending)
4481 {
4482 /*
4483 * AMD-V does not provide us with the original exception but we have it in u64IntrInfo since we
4484 * injected the event during VM-entry. Software interrupts and exceptions will be regenerated
4485 * when the recompiler restarts the instruction.
4486 */
4487 SVMEVENT Event;
4488 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
4489 if ( Event.n.u3Type == SVM_EVENT_EXCEPTION
4490 || Event.n.u3Type == SVM_EVENT_SOFTWARE_INT)
4491 {
4492 pVCpu->hm.s.Event.fPending = false;
4493 }
4494 else
4495 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery. Kept pending u8Vector=%#x\n", Event.n.u8Vector));
4496 }
4497
4498 /** @todo Emulate task switch someday, currently just going back to ring-3 for
4499 * emulation. */
4500 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
4501 return VERR_EM_INTERPRETER;
4502}
4503
4504
4505/**
4506 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
4507 */
4508HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4509{
4510 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4511
4512 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4513 if (RT_LIKELY(rc == VINF_SUCCESS))
4514 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4515 else
4516 hmR0SvmSetPendingXcptUD(pVCpu);
4517 return VINF_SUCCESS;
4518}
4519
4520
4521/**
4522 * #VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E). Conditional
4523 * #VMEXIT.
4524 */
4525HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4526{
4527 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4528
4529 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4530
4531 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
4532 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4533 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4534 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
4535 PVM pVM = pVCpu->CTX_SUFF(pVM);
4536
4537#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
4538 if (pVM->hm.s.fNestedPaging)
4539 {
4540 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4541 if (!pSvmTransient->fVectoringPF)
4542 {
4543 /* A genuine guest #PF, reflect it to the guest. */
4544 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4545 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
4546 uFaultAddress, u32ErrCode));
4547 }
4548 else
4549 {
4550 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4551 hmR0SvmSetPendingXcptDF(pVCpu);
4552 Log4(("Pending #DF due to vectoring #PF. NP\n"));
4553 }
4554 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4555 return VINF_SUCCESS;
4556 }
4557#endif
4558
4559 Assert(!pVM->hm.s.fNestedPaging);
4560
4561#ifdef VBOX_HM_WITH_GUEST_PATCHING
4562 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
4563 if ( pVM->hm.s.fTRPPatchingAllowed
4564 && (uFaultAddress & 0xfff) == 0x80 /* TPR offset. */
4565 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
4566 && !CPUMGetGuestCPL(pVCpu)
4567 && !CPUMIsGuestInLongModeEx(pCtx)
4568 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4569 {
4570 RTGCPHYS GCPhysApicBase;
4571 GCPhysApicBase = pCtx->msrApicBase;
4572 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4573
4574 /* Check if the page at the fault-address is the APIC base. */
4575 RTGCPHYS GCPhysPage;
4576 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
4577 if ( rc2 == VINF_SUCCESS
4578 && GCPhysPage == GCPhysApicBase)
4579 {
4580 /* Only attempt to patch the instruction once. */
4581 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4582 if (!pPatch)
4583 return VINF_EM_HM_PATCH_TPR_INSTR;
4584 }
4585 }
4586#endif
4587
4588 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
4589 pCtx->rip, u32ErrCode, pCtx->cr3));
4590
4591 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
4592 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
4593
4594 Log4(("#PF rc=%Rrc\n", rc));
4595
4596 if (rc == VINF_SUCCESS)
4597 {
4598 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
4599 TRPMResetTrap(pVCpu);
4600 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4601 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4602 return rc;
4603 }
4604 else if (rc == VINF_EM_RAW_GUEST_TRAP)
4605 {
4606 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4607
4608 if (!pSvmTransient->fVectoringPF)
4609 {
4610 /* It's a guest page fault and needs to be reflected to the guest. */
4611 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
4612 TRPMResetTrap(pVCpu);
4613 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4614 }
4615 else
4616 {
4617 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4618 TRPMResetTrap(pVCpu);
4619 hmR0SvmSetPendingXcptDF(pVCpu);
4620 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
4621 }
4622
4623 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4624 return VINF_SUCCESS;
4625 }
4626
4627 TRPMResetTrap(pVCpu);
4628 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
4629 return rc;
4630}
4631
4632
4633/**
4634 * #VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
4635 * Conditional #VMEXIT.
4636 */
4637HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4638{
4639 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4640
4641 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4642
4643#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
4644 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
4645#endif
4646
4647 /* Lazy FPU loading; load the guest-FPU state transparently and continue execution of the guest. */
4648 int rc = CPUMR0LoadGuestFPU(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4649 if (rc == VINF_SUCCESS)
4650 {
4651 Assert(CPUMIsGuestFPUStateActive(pVCpu));
4652 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
4653 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
4654 return VINF_SUCCESS;
4655 }
4656
4657 /* Forward #NM to the guest. */
4658 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
4659 hmR0SvmSetPendingXcptNM(pVCpu);
4660 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
4661 return VINF_SUCCESS;
4662}
4663
4664
4665/**
4666 * #VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
4667 * Conditional #VMEXIT.
4668 */
4669HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4670{
4671 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4672
4673 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4674
4675 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
4676
4677 if (!(pCtx->cr0 & X86_CR0_NE))
4678 {
4679 /* Old-style FPU error reporting needs some extra work. */
4680 /** @todo don't fall back to the recompiler, but do it manually. */
4681 return VERR_EM_INTERPRETER;
4682 }
4683
4684 hmR0SvmSetPendingXcptMF(pVCpu);
4685 return VINF_SUCCESS;
4686}
4687
4688
4689/**
4690 * #VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
4691 * #VMEXIT.
4692 */
4693HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4694{
4695 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4696
4697 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4698
4699 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
4700
4701 /* If we set the trap flag above, we have to clear it. */
4702 if (pVCpu->hm.s.fClearTrapFlag)
4703 {
4704 pVCpu->hm.s.fClearTrapFlag = false;
4705 pCtx->eflags.Bits.u1TF = 0;
4706 }
4707
4708 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
4709 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
4710 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4711 PVM pVM = pVCpu->CTX_SUFF(pVM);
4712 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
4713 if (rc == VINF_EM_RAW_GUEST_TRAP)
4714 {
4715 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
4716 if (CPUMIsHyperDebugStateActive(pVCpu))
4717 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
4718
4719 /* Reflect the exception back to the guest. */
4720 hmR0SvmSetPendingXcptDB(pVCpu);
4721 rc = VINF_SUCCESS;
4722 }
4723
4724 /*
4725 * Update DR6.
4726 */
4727 if (CPUMIsHyperDebugStateActive(pVCpu))
4728 {
4729 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
4730 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
4731 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4732 }
4733 else
4734 {
4735 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
4736 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
4737 }
4738
4739 return rc;
4740}
4741
4742/** @} */
4743
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