VirtualBox

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

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

nit.

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