VirtualBox

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

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

VMM: Rename variable to better reflect its purpose.

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