VirtualBox

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

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

VMM: Propagate errors properly while leaving HM context.

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