VirtualBox

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

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

VMM: Addressed a rare corner case stale TLB entry issue.

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