VirtualBox

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

Last change on this file since 53631 was 53631, checked in by vboxsync, 10 years ago

vmexit trace points.

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