VirtualBox

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

Last change on this file since 51721 was 51662, checked in by vboxsync, 11 years ago

VMM/HMSVMR0: Use VMCB offsetting until we fix TM. Makes Hyper-V guests more stable.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette