VirtualBox

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

Last change on this file since 64770 was 64770, checked in by vboxsync, 8 years ago

VMM/DBGF, HM: Fix int3 based breakpoints set in the VM debugger when using VT-x.

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