VirtualBox

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

Last change on this file since 51326 was 51230, checked in by vboxsync, 11 years ago

VMM/HMVMXR0,HMSVMR0: debug build fixes.

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