VirtualBox

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

Last change on this file since 50667 was 49990, checked in by vboxsync, 11 years ago

VMM/HMSVMR0: nit.

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