VirtualBox

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

Last change on this file since 49407 was 49404, checked in by vboxsync, 11 years ago

VMM/HMVMXR0, HMSVMR0: Use IPRT.

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