VirtualBox

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

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

VMM/HMSVMR0: Unused param build fix.

  • 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 64771 2016-12-01 12:34:50Z 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 NOREF(pCtx);
1673 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
1674 {
1675 /* Trap #UD for GIM provider (e.g. for hypercalls). */
1676 if (pVCpu->hm.s.fGIMTrapXcptUD)
1677 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_UD);
1678 else
1679 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_UD);
1680
1681 /* Trap #BP for INT3 debug breakpoints set by the VM debugger. */
1682 if (pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
1683 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_BP);
1684 else
1685 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_BP);
1686
1687 /* The remaining intercepts are handled elsewhere, e.g. in hmR0SvmLoadSharedCR0(). */
1688 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
1689 }
1690 return VINF_SUCCESS;
1691}
1692
1693
1694/**
1695 * Sets up the appropriate function to run guest code.
1696 *
1697 * @returns VBox status code.
1698 * @param pVCpu The cross context virtual CPU structure.
1699 * @param pCtx Pointer to the guest-CPU context.
1700 *
1701 * @remarks No-long-jump zone!!!
1702 */
1703static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pCtx)
1704{
1705 if (CPUMIsGuestInLongModeEx(pCtx))
1706 {
1707#ifndef VBOX_ENABLE_64_BITS_GUESTS
1708 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1709#endif
1710 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
1711#if HC_ARCH_BITS == 32
1712 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
1713 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
1714#else
1715 /* 64-bit host or hybrid host. */
1716 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1717#endif
1718 }
1719 else
1720 {
1721 /* Guest is not in long mode, use the 32-bit handler. */
1722 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1723 }
1724 return VINF_SUCCESS;
1725}
1726
1727
1728/**
1729 * Enters the AMD-V session.
1730 *
1731 * @returns VBox status code.
1732 * @param pVM The cross context VM structure.
1733 * @param pVCpu The cross context virtual CPU structure.
1734 * @param pCpu Pointer to the CPU info struct.
1735 */
1736VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1737{
1738 AssertPtr(pVM);
1739 AssertPtr(pVCpu);
1740 Assert(pVM->hm.s.svm.fSupported);
1741 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1742 NOREF(pVM); NOREF(pCpu);
1743
1744 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
1745 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
1746
1747 pVCpu->hm.s.fLeaveDone = false;
1748 return VINF_SUCCESS;
1749}
1750
1751
1752/**
1753 * Thread-context callback for AMD-V.
1754 *
1755 * @param enmEvent The thread-context event.
1756 * @param pVCpu The cross context virtual CPU structure.
1757 * @param fGlobalInit Whether global VT-x/AMD-V init. is used.
1758 * @thread EMT(pVCpu)
1759 */
1760VMMR0DECL(void) SVMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
1761{
1762 NOREF(fGlobalInit);
1763
1764 switch (enmEvent)
1765 {
1766 case RTTHREADCTXEVENT_OUT:
1767 {
1768 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1769 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
1770 VMCPU_ASSERT_EMT(pVCpu);
1771
1772 /* No longjmps (log-flush, locks) in this fragile context. */
1773 VMMRZCallRing3Disable(pVCpu);
1774
1775 if (!pVCpu->hm.s.fLeaveDone)
1776 {
1777 hmR0SvmLeave(pVCpu);
1778 pVCpu->hm.s.fLeaveDone = true;
1779 }
1780
1781 /* Leave HM context, takes care of local init (term). */
1782 int rc = HMR0LeaveCpu(pVCpu);
1783 AssertRC(rc); NOREF(rc);
1784
1785 /* Restore longjmp state. */
1786 VMMRZCallRing3Enable(pVCpu);
1787 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
1788 break;
1789 }
1790
1791 case RTTHREADCTXEVENT_IN:
1792 {
1793 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1794 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
1795 VMCPU_ASSERT_EMT(pVCpu);
1796
1797 /* No longjmps (log-flush, locks) in this fragile context. */
1798 VMMRZCallRing3Disable(pVCpu);
1799
1800 /*
1801 * Initialize the bare minimum state required for HM. This takes care of
1802 * initializing AMD-V if necessary (onlined CPUs, local init etc.)
1803 */
1804 int rc = HMR0EnterCpu(pVCpu);
1805 AssertRC(rc); NOREF(rc);
1806 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
1807
1808 pVCpu->hm.s.fLeaveDone = false;
1809
1810 /* Restore longjmp state. */
1811 VMMRZCallRing3Enable(pVCpu);
1812 break;
1813 }
1814
1815 default:
1816 break;
1817 }
1818}
1819
1820
1821/**
1822 * Saves the host state.
1823 *
1824 * @returns VBox status code.
1825 * @param pVM The cross context VM structure.
1826 * @param pVCpu The cross context virtual CPU structure.
1827 *
1828 * @remarks No-long-jump zone!!!
1829 */
1830VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
1831{
1832 NOREF(pVM);
1833 NOREF(pVCpu);
1834 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
1835 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT);
1836 return VINF_SUCCESS;
1837}
1838
1839
1840/**
1841 * Loads the guest state into the VMCB.
1842 *
1843 * The CPU state will be loaded from these fields on every successful VM-entry.
1844 * Also sets up the appropriate VMRUN function to execute guest code based on
1845 * the guest CPU mode.
1846 *
1847 * @returns VBox status code.
1848 * @param pVM The cross context VM structure.
1849 * @param pVCpu The cross context virtual CPU structure.
1850 * @param pCtx Pointer to the guest-CPU context.
1851 *
1852 * @remarks No-long-jump zone!!!
1853 */
1854static int hmR0SvmLoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1855{
1856 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1857 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1858
1859 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
1860
1861 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
1862 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1863
1864 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
1865 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
1866
1867 pVmcb->guest.u64RIP = pCtx->rip;
1868 pVmcb->guest.u64RSP = pCtx->rsp;
1869 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
1870 pVmcb->guest.u64RAX = pCtx->rax;
1871
1872 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
1873 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1874
1875 rc = hmR0SvmLoadGuestXcptIntercepts(pVCpu, pVmcb, pCtx);
1876 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestXcptIntercepts! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1877
1878 rc = hmR0SvmSetupVMRunHandler(pVCpu, pCtx);
1879 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1880
1881 /* Clear any unused and reserved bits. */
1882 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
1883 | HM_CHANGED_GUEST_RSP
1884 | HM_CHANGED_GUEST_RFLAGS
1885 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
1886 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
1887 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
1888 | HM_CHANGED_GUEST_LAZY_MSRS /* Unused. */
1889 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
1890 | HM_CHANGED_SVM_RESERVED2
1891 | HM_CHANGED_SVM_RESERVED3
1892 | HM_CHANGED_SVM_RESERVED4);
1893
1894 /* All the guest state bits should be loaded except maybe the host context and/or shared host/guest bits. */
1895 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
1896 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
1897 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
1898
1899 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));
1900 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
1901 return rc;
1902}
1903
1904
1905/**
1906 * Loads the state shared between the host and guest into the
1907 * VMCB.
1908 *
1909 * @param pVCpu The cross context virtual CPU structure.
1910 * @param pVmcb Pointer to the VM control block.
1911 * @param pCtx Pointer to the guest-CPU context.
1912 *
1913 * @remarks No-long-jump zone!!!
1914 */
1915static void hmR0SvmLoadSharedState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1916{
1917 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1918 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1919
1920 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
1921 hmR0SvmLoadSharedCR0(pVCpu, pVmcb, pCtx);
1922
1923 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
1924 hmR0SvmLoadSharedDebugState(pVCpu, pVmcb, pCtx);
1925
1926 /* Unused on AMD-V. */
1927 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
1928
1929 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
1930 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
1931}
1932
1933
1934/**
1935 * Saves the entire guest state from the VMCB into the
1936 * guest-CPU context. Currently there is no residual state left in the CPU that
1937 * is not updated in the VMCB.
1938 *
1939 * @returns VBox status code.
1940 * @param pVCpu The cross context virtual CPU structure.
1941 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1942 * out-of-sync. Make sure to update the required fields
1943 * before using them.
1944 */
1945static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1946{
1947 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1948
1949 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1950
1951 pMixedCtx->rip = pVmcb->guest.u64RIP;
1952 pMixedCtx->rsp = pVmcb->guest.u64RSP;
1953 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1954 pMixedCtx->rax = pVmcb->guest.u64RAX;
1955
1956 /*
1957 * Guest interrupt shadow.
1958 */
1959 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1960 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
1961 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1962 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1963
1964 /*
1965 * Guest Control registers: CR2, CR3 (handled at the end) - accesses to other control registers are always intercepted.
1966 */
1967 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
1968
1969 /*
1970 * Guest MSRs.
1971 */
1972 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1973 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1974 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1975 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1976 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1977 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1978 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1979 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1980
1981 /*
1982 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
1983 */
1984 HMSVM_SAVE_SEG_REG(CS, cs);
1985 HMSVM_SAVE_SEG_REG(SS, ss);
1986 HMSVM_SAVE_SEG_REG(DS, ds);
1987 HMSVM_SAVE_SEG_REG(ES, es);
1988 HMSVM_SAVE_SEG_REG(FS, fs);
1989 HMSVM_SAVE_SEG_REG(GS, gs);
1990
1991 /*
1992 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
1993 * register (yet).
1994 */
1995 /** @todo SELM might need to be fixed as it too should not care about the
1996 * granularity bit. See @bugref{6785}. */
1997 if ( !pMixedCtx->cs.Attr.n.u1Granularity
1998 && pMixedCtx->cs.Attr.n.u1Present
1999 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
2000 {
2001 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
2002 pMixedCtx->cs.Attr.n.u1Granularity = 1;
2003 }
2004
2005#ifdef VBOX_STRICT
2006# define HMSVM_ASSERT_SEG_GRANULARITY(reg) \
2007 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
2008 || ( pMixedCtx->reg.Attr.n.u1Granularity \
2009 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
2010 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
2011 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", pMixedCtx->reg.u32Limit, \
2012 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
2013
2014 HMSVM_ASSERT_SEG_GRANULARITY(cs);
2015 HMSVM_ASSERT_SEG_GRANULARITY(ss);
2016 HMSVM_ASSERT_SEG_GRANULARITY(ds);
2017 HMSVM_ASSERT_SEG_GRANULARITY(es);
2018 HMSVM_ASSERT_SEG_GRANULARITY(fs);
2019 HMSVM_ASSERT_SEG_GRANULARITY(gs);
2020
2021# undef HMSVM_ASSERT_SEL_GRANULARITY
2022#endif
2023
2024 /*
2025 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
2026 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
2027 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
2028 * See AMD spec. 15.5.1 "Basic operation".
2029 */
2030 Assert(!(pVmcb->guest.u8CPL & ~0x3));
2031 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
2032
2033 /*
2034 * Guest TR.
2035 * Fixup TR attributes so it's compatible with Intel. Important when saved-states are used
2036 * between Intel and AMD. See @bugref{6208#c39}.
2037 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2038 */
2039 HMSVM_SAVE_SEG_REG(TR, tr);
2040 if (pMixedCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2041 {
2042 if ( pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2043 || CPUMIsGuestInLongModeEx(pMixedCtx))
2044 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2045 else if (pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2046 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2047 }
2048
2049 /*
2050 * Guest Descriptor-Table registers.
2051 */
2052 HMSVM_SAVE_SEG_REG(LDTR, ldtr);
2053 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
2054 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
2055
2056 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
2057 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
2058
2059 /*
2060 * Guest Debug registers.
2061 */
2062 if (!pVCpu->hm.s.fUsingHyperDR7)
2063 {
2064 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
2065 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
2066 }
2067 else
2068 {
2069 Assert(pVmcb->guest.u64DR7 == CPUMGetHyperDR7(pVCpu));
2070 CPUMSetHyperDR6(pVCpu, pVmcb->guest.u64DR6);
2071 }
2072
2073 /*
2074 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
2075 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
2076 */
2077 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
2078 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
2079 {
2080 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
2081 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
2082 }
2083}
2084
2085
2086/**
2087 * Does the necessary state syncing before returning to ring-3 for any reason
2088 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
2089 *
2090 * @param pVCpu The cross context virtual CPU structure.
2091 *
2092 * @remarks No-long-jmp zone!!!
2093 */
2094static void hmR0SvmLeave(PVMCPU pVCpu)
2095{
2096 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2097 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2098 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2099
2100 /*
2101 * !!! IMPORTANT !!!
2102 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2103 */
2104
2105 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
2106 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu))
2107 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
2108
2109 /*
2110 * Restore host debug registers if necessary and resync on next R0 reentry.
2111 */
2112#ifdef VBOX_STRICT
2113 if (CPUMIsHyperDebugStateActive(pVCpu))
2114 {
2115 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2116 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
2117 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
2118 }
2119#endif
2120 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */))
2121 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
2122
2123 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
2124 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
2125
2126 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
2127 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
2128 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
2129 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
2130 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2131
2132 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
2133}
2134
2135
2136/**
2137 * Leaves the AMD-V session.
2138 *
2139 * @returns VBox status code.
2140 * @param pVCpu The cross context virtual CPU structure.
2141 */
2142static int hmR0SvmLeaveSession(PVMCPU pVCpu)
2143{
2144 HM_DISABLE_PREEMPT();
2145 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2146 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2147
2148 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
2149 and done this from the SVMR0ThreadCtxCallback(). */
2150 if (!pVCpu->hm.s.fLeaveDone)
2151 {
2152 hmR0SvmLeave(pVCpu);
2153 pVCpu->hm.s.fLeaveDone = true;
2154 }
2155
2156 /*
2157 * !!! IMPORTANT !!!
2158 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2159 */
2160
2161 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2162 /* Deregister hook now that we've left HM context before re-enabling preemption. */
2163 VMMR0ThreadCtxHookDisable(pVCpu);
2164
2165 /* Leave HM context. This takes care of local init (term). */
2166 int rc = HMR0LeaveCpu(pVCpu);
2167
2168 HM_RESTORE_PREEMPT();
2169 return rc;
2170}
2171
2172
2173/**
2174 * Does the necessary state syncing before doing a longjmp to ring-3.
2175 *
2176 * @returns VBox status code.
2177 * @param pVCpu The cross context virtual CPU structure.
2178 *
2179 * @remarks No-long-jmp zone!!!
2180 */
2181static int hmR0SvmLongJmpToRing3(PVMCPU pVCpu)
2182{
2183 return hmR0SvmLeaveSession(pVCpu);
2184}
2185
2186
2187/**
2188 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
2189 * any remaining host state) before we longjump to ring-3 and possibly get
2190 * preempted.
2191 *
2192 * @param pVCpu The cross context virtual CPU structure.
2193 * @param enmOperation The operation causing the ring-3 longjump.
2194 * @param pvUser The user argument (pointer to the possibly
2195 * out-of-date guest-CPU context).
2196 */
2197static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
2198{
2199 RT_NOREF_PV(pvUser);
2200
2201 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
2202 {
2203 /*
2204 * !!! IMPORTANT !!!
2205 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
2206 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
2207 */
2208 VMMRZCallRing3RemoveNotification(pVCpu);
2209 VMMRZCallRing3Disable(pVCpu);
2210 HM_DISABLE_PREEMPT();
2211
2212 /* Restore host FPU state if necessary and resync on next R0 reentry. */
2213 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
2214
2215 /* Restore host debug registers if necessary and resync on next R0 reentry. */
2216 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
2217
2218 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
2219 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2220 VMMR0ThreadCtxHookDisable(pVCpu);
2221
2222 /* Leave HM context. This takes care of local init (term). */
2223 HMR0LeaveCpu(pVCpu);
2224
2225 HM_RESTORE_PREEMPT();
2226 return VINF_SUCCESS;
2227 }
2228
2229 Assert(pVCpu);
2230 Assert(pvUser);
2231 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2232 HMSVM_ASSERT_PREEMPT_SAFE();
2233
2234 VMMRZCallRing3Disable(pVCpu);
2235 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2236
2237 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
2238 int rc = hmR0SvmLongJmpToRing3(pVCpu);
2239 AssertRCReturn(rc, rc);
2240
2241 VMMRZCallRing3Enable(pVCpu);
2242 return VINF_SUCCESS;
2243}
2244
2245
2246/**
2247 * Take necessary actions before going back to ring-3.
2248 *
2249 * An action requires us to go back to ring-3. This function does the necessary
2250 * steps before we can safely return to ring-3. This is not the same as longjmps
2251 * to ring-3, this is voluntary.
2252 *
2253 * @param pVM The cross context VM structure.
2254 * @param pVCpu The cross context virtual CPU structure.
2255 * @param pCtx Pointer to the guest-CPU context.
2256 * @param rcExit The reason for exiting to ring-3. Can be
2257 * VINF_VMM_UNKNOWN_RING3_CALL.
2258 */
2259static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
2260{
2261 Assert(pVM);
2262 Assert(pVCpu);
2263 Assert(pCtx);
2264 HMSVM_ASSERT_PREEMPT_SAFE();
2265
2266 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
2267 VMMRZCallRing3Disable(pVCpu);
2268 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
2269
2270 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
2271 if (pVCpu->hm.s.Event.fPending)
2272 {
2273 hmR0SvmPendingEventToTrpmTrap(pVCpu);
2274 Assert(!pVCpu->hm.s.Event.fPending);
2275 }
2276
2277 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
2278 and if we're injecting an event we should have a TRPM trap pending. */
2279 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("rcExit=%Rrc\n", rcExit));
2280 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("rcExit=%Rrc\n", rcExit));
2281
2282 /* Sync. the necessary state for going back to ring-3. */
2283 hmR0SvmLeaveSession(pVCpu);
2284 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2285
2286 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2287 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
2288 | CPUM_CHANGED_LDTR
2289 | CPUM_CHANGED_GDTR
2290 | CPUM_CHANGED_IDTR
2291 | CPUM_CHANGED_TR
2292 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2293 if ( pVM->hm.s.fNestedPaging
2294 && CPUMIsGuestPagingEnabledEx(pCtx))
2295 {
2296 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2297 }
2298
2299 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
2300 if (rcExit != VINF_EM_RAW_INTERRUPT)
2301 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
2302
2303 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
2304
2305 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
2306 VMMRZCallRing3RemoveNotification(pVCpu);
2307 VMMRZCallRing3Enable(pVCpu);
2308}
2309
2310
2311/**
2312 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
2313 * intercepts.
2314 *
2315 * @param pVM The cross context VM structure.
2316 * @param pVCpu The cross context virtual CPU structure.
2317 *
2318 * @remarks No-long-jump zone!!!
2319 */
2320static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu)
2321{
2322 bool fParavirtTsc;
2323 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2324 bool fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &pVmcb->ctrl.u64TSCOffset, &fParavirtTsc);
2325 if (fCanUseRealTsc)
2326 {
2327 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
2328 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
2329 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
2330 }
2331 else
2332 {
2333 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
2334 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
2335 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
2336 }
2337 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2338
2339 /** @todo later optimize this to be done elsewhere and not before every
2340 * VM-entry. */
2341 if (fParavirtTsc)
2342 {
2343 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
2344 information before every VM-entry, hence disable it for performance sake. */
2345#if 0
2346 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
2347 AssertRC(rc);
2348#endif
2349 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
2350 }
2351}
2352
2353
2354/**
2355 * Sets an event as a pending event to be injected into the guest.
2356 *
2357 * @param pVCpu The cross context virtual CPU structure.
2358 * @param pEvent Pointer to the SVM event.
2359 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
2360 * page-fault.
2361 *
2362 * @remarks Statistics counter assumes this is a guest event being reflected to
2363 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
2364 */
2365DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
2366{
2367 Assert(!pVCpu->hm.s.Event.fPending);
2368 Assert(pEvent->n.u1Valid);
2369
2370 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
2371 pVCpu->hm.s.Event.fPending = true;
2372 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
2373
2374 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2375 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2376}
2377
2378
2379/**
2380 * Injects an event into the guest upon VMRUN by updating the relevant field
2381 * in the VMCB.
2382 *
2383 * @param pVCpu The cross context virtual CPU structure.
2384 * @param pVmcb Pointer to the guest VM control block.
2385 * @param pCtx Pointer to the guest-CPU context.
2386 * @param pEvent Pointer to the event.
2387 *
2388 * @remarks No-long-jump zone!!!
2389 * @remarks Requires CR0!
2390 */
2391DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
2392{
2393 NOREF(pVCpu); NOREF(pCtx);
2394
2395 pVmcb->ctrl.EventInject.u = pEvent->u;
2396 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
2397
2398 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2399 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2400}
2401
2402
2403
2404/**
2405 * Converts any TRPM trap into a pending HM event. This is typically used when
2406 * entering from ring-3 (not longjmp returns).
2407 *
2408 * @param pVCpu The cross context virtual CPU structure.
2409 */
2410static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
2411{
2412 Assert(TRPMHasTrap(pVCpu));
2413 Assert(!pVCpu->hm.s.Event.fPending);
2414
2415 uint8_t uVector;
2416 TRPMEVENT enmTrpmEvent;
2417 RTGCUINT uErrCode;
2418 RTGCUINTPTR GCPtrFaultAddress;
2419 uint8_t cbInstr;
2420
2421 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
2422 AssertRC(rc);
2423
2424 SVMEVENT Event;
2425 Event.u = 0;
2426 Event.n.u1Valid = 1;
2427 Event.n.u8Vector = uVector;
2428
2429 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
2430 if (enmTrpmEvent == TRPM_TRAP)
2431 {
2432 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2433 switch (uVector)
2434 {
2435 case X86_XCPT_NMI:
2436 {
2437 Event.n.u3Type = SVM_EVENT_NMI;
2438 break;
2439 }
2440
2441 case X86_XCPT_PF:
2442 case X86_XCPT_DF:
2443 case X86_XCPT_TS:
2444 case X86_XCPT_NP:
2445 case X86_XCPT_SS:
2446 case X86_XCPT_GP:
2447 case X86_XCPT_AC:
2448 {
2449 Event.n.u1ErrorCodeValid = 1;
2450 Event.n.u32ErrorCode = uErrCode;
2451 break;
2452 }
2453 }
2454 }
2455 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
2456 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2457 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
2458 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
2459 else
2460 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
2461
2462 rc = TRPMResetTrap(pVCpu);
2463 AssertRC(rc);
2464
2465 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
2466 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
2467
2468 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
2469}
2470
2471
2472/**
2473 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
2474 * AMD-V to execute any instruction.
2475 *
2476 * @param pVCpu The cross context virtual CPU structure.
2477 */
2478static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
2479{
2480 Assert(pVCpu->hm.s.Event.fPending);
2481 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
2482
2483 SVMEVENT Event;
2484 Event.u = pVCpu->hm.s.Event.u64IntInfo;
2485
2486 uint8_t uVector = Event.n.u8Vector;
2487 uint8_t uVectorType = Event.n.u3Type;
2488
2489 TRPMEVENT enmTrapType;
2490 switch (uVectorType)
2491 {
2492 case SVM_EVENT_EXTERNAL_IRQ:
2493 enmTrapType = TRPM_HARDWARE_INT;
2494 break;
2495 case SVM_EVENT_SOFTWARE_INT:
2496 enmTrapType = TRPM_SOFTWARE_INT;
2497 break;
2498 case SVM_EVENT_EXCEPTION:
2499 case SVM_EVENT_NMI:
2500 enmTrapType = TRPM_TRAP;
2501 break;
2502 default:
2503 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
2504 enmTrapType = TRPM_32BIT_HACK;
2505 break;
2506 }
2507
2508 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
2509
2510 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
2511 AssertRC(rc);
2512
2513 if (Event.n.u1ErrorCodeValid)
2514 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
2515
2516 if ( uVectorType == SVM_EVENT_EXCEPTION
2517 && uVector == X86_XCPT_PF)
2518 {
2519 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
2520 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
2521 }
2522 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
2523 {
2524 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
2525 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
2526 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
2527 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
2528 }
2529 pVCpu->hm.s.Event.fPending = false;
2530}
2531
2532
2533/**
2534 * Gets the guest's interrupt-shadow.
2535 *
2536 * @returns The guest's interrupt-shadow.
2537 * @param pVCpu The cross context virtual CPU structure.
2538 * @param pCtx Pointer to the guest-CPU context.
2539 *
2540 * @remarks No-long-jump zone!!!
2541 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
2542 */
2543DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
2544{
2545 /*
2546 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
2547 * inhibit interrupts or clear any existing interrupt-inhibition.
2548 */
2549 uint32_t uIntrState = 0;
2550 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2551 {
2552 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2553 {
2554 /*
2555 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
2556 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
2557 */
2558 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2559 }
2560 else
2561 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
2562 }
2563 return uIntrState;
2564}
2565
2566
2567/**
2568 * Sets the virtual interrupt intercept control in the VMCB which
2569 * instructs AMD-V to cause a \#VMEXIT as soon as the guest is in a state to
2570 * receive interrupts.
2571 *
2572 * @param pVmcb Pointer to the VM control block.
2573 */
2574DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
2575{
2576 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
2577 {
2578 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
2579 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
2580 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
2581 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
2582
2583 Log4(("Setting VINTR intercept\n"));
2584 }
2585}
2586
2587
2588/**
2589 * Sets the IRET intercept control in the VMCB which instructs AMD-V to cause a
2590 * \#VMEXIT as soon as a guest starts executing an IRET. This is used to unblock
2591 * virtual NMIs.
2592 *
2593 * @param pVmcb Pointer to the VM control block.
2594 */
2595DECLINLINE(void) hmR0SvmSetIretIntercept(PSVMVMCB pVmcb)
2596{
2597 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_IRET))
2598 {
2599 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_IRET;
2600 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2601
2602 Log4(("Setting IRET intercept\n"));
2603 }
2604}
2605
2606
2607/**
2608 * Clears the IRET intercept control in the VMCB.
2609 *
2610 * @param pVmcb Pointer to the VM control block.
2611 */
2612DECLINLINE(void) hmR0SvmClearIretIntercept(PSVMVMCB pVmcb)
2613{
2614 if (pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_IRET)
2615 {
2616 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_IRET;
2617 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2618
2619 Log4(("Clearing IRET intercept\n"));
2620 }
2621}
2622
2623
2624/**
2625 * Evaluates the event to be delivered to the guest and sets it as the pending
2626 * event.
2627 *
2628 * @param pVCpu The cross context virtual CPU structure.
2629 * @param pCtx Pointer to the guest-CPU context.
2630 */
2631static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2632{
2633 Assert(!pVCpu->hm.s.Event.fPending);
2634 Log4Func(("\n"));
2635
2636 bool const fIntShadow = RT_BOOL(hmR0SvmGetGuestIntrShadow(pVCpu, pCtx));
2637 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2638 bool const fBlockNmi = RT_BOOL(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS));
2639 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2640
2641 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
2642 APICUpdatePendingInterrupts(pVCpu);
2643
2644 SVMEVENT Event;
2645 Event.u = 0;
2646 /** @todo SMI. SMIs take priority over NMIs. */
2647 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2648 {
2649 if (fBlockNmi)
2650 hmR0SvmSetIretIntercept(pVmcb);
2651 else if (fIntShadow)
2652 hmR0SvmSetVirtIntrIntercept(pVmcb);
2653 else
2654 {
2655 Log4(("Pending NMI\n"));
2656
2657 Event.n.u1Valid = 1;
2658 Event.n.u8Vector = X86_XCPT_NMI;
2659 Event.n.u3Type = SVM_EVENT_NMI;
2660
2661 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2662 hmR0SvmSetIretIntercept(pVmcb);
2663 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2664 }
2665 }
2666 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
2667 && !pVCpu->hm.s.fSingleInstruction)
2668 {
2669 /*
2670 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
2671 * a valid interrupt we must- deliver the interrupt. We can no longer re-request it from the APIC.
2672 */
2673 if ( !fBlockInt
2674 && !fIntShadow)
2675 {
2676 uint8_t u8Interrupt;
2677 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2678 if (RT_SUCCESS(rc))
2679 {
2680 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2681
2682 Event.n.u1Valid = 1;
2683 Event.n.u8Vector = u8Interrupt;
2684 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2685
2686 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2687 }
2688 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
2689 {
2690 /*
2691 * AMD-V has no TPR thresholding feature. We just avoid posting the interrupt.
2692 * We just avoid delivering the TPR-masked interrupt here. TPR will be updated
2693 * always via hmR0SvmLoadGuestState() -> hmR0SvmLoadGuestApicState().
2694 */
2695 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
2696 }
2697 else
2698 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2699 }
2700 else
2701 hmR0SvmSetVirtIntrIntercept(pVmcb);
2702 }
2703}
2704
2705
2706/**
2707 * Injects any pending events into the guest if the guest is in a state to
2708 * receive them.
2709 *
2710 * @param pVCpu The cross context virtual CPU structure.
2711 * @param pCtx Pointer to the guest-CPU context.
2712 */
2713static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2714{
2715 Assert(!TRPMHasTrap(pVCpu));
2716 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2717
2718 bool const fIntShadow = RT_BOOL(hmR0SvmGetGuestIntrShadow(pVCpu, pCtx));
2719 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2720 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2721
2722 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2723 {
2724 SVMEVENT Event;
2725 Event.u = pVCpu->hm.s.Event.u64IntInfo;
2726 Assert(Event.n.u1Valid);
2727#ifdef VBOX_STRICT
2728 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2729 {
2730 Assert(!fBlockInt);
2731 Assert(!fIntShadow);
2732 }
2733 else if (Event.n.u3Type == SVM_EVENT_NMI)
2734 Assert(!fIntShadow);
2735#endif
2736
2737 Log4(("Injecting pending HM event.\n"));
2738 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2739 pVCpu->hm.s.Event.fPending = false;
2740
2741#ifdef VBOX_WITH_STATISTICS
2742 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2743 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2744 else
2745 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2746#endif
2747 }
2748
2749 /* Update the guest interrupt shadow in the VMCB. */
2750 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2751 NOREF(fBlockInt);
2752}
2753
2754
2755/**
2756 * Reports world-switch error and dumps some useful debug info.
2757 *
2758 * @param pVM The cross context VM structure.
2759 * @param pVCpu The cross context virtual CPU structure.
2760 * @param rcVMRun The return code from VMRUN (or
2761 * VERR_SVM_INVALID_GUEST_STATE for invalid
2762 * guest-state).
2763 * @param pCtx Pointer to the guest-CPU context.
2764 */
2765static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2766{
2767 NOREF(pCtx);
2768 HMSVM_ASSERT_PREEMPT_SAFE();
2769 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2770
2771 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2772 {
2773 HMDumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
2774#ifdef VBOX_STRICT
2775 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2776 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2777 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2778 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2779 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2780 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2781 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2782 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2783 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2784 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2785 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2786
2787 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2788 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2789 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2790
2791 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2792 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2793 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2794 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2795 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2796 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2797 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2798 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2799 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2800 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2801
2802 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2803 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2804 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2805 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2806 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2807 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2808 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2809 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2810 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2811 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2812 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2813 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2814 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2815 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2816 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2817 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2818 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2819
2820 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2821 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2822
2823 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2824 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2825 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2826 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2827 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2828 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2829 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2830 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2831 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2832 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2833 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2834 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2835 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2836 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2837 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2838 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2839 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2840 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2841 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2842 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2843
2844 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2845 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2846
2847 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2848 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2849 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2850 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2851
2852 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2853 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2854
2855 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2856 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2857 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2858 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2859
2860 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2861 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2862 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2863 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2864 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2865 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2866 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2867
2868 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2869 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2870 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2871 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2872
2873 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2874 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2875 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2876
2877 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2878 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2879 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2880 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2881 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2882 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2883 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2884 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2885 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2886 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2887 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2888 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2889#endif /* VBOX_STRICT */
2890 }
2891 else
2892 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2893
2894 NOREF(pVmcb);
2895}
2896
2897
2898/**
2899 * Check per-VM and per-VCPU force flag actions that require us to go back to
2900 * ring-3 for one reason or another.
2901 *
2902 * @returns VBox status code (information status code included).
2903 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2904 * ring-3.
2905 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2906 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2907 * interrupts)
2908 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2909 * all EMTs to be in ring-3.
2910 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2911 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2912 * to the EM loop.
2913 *
2914 * @param pVM The cross context VM structure.
2915 * @param pVCpu The cross context virtual CPU structure.
2916 * @param pCtx Pointer to the guest-CPU context.
2917 */
2918static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2919{
2920 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2921
2922 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
2923 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2924 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
2925
2926 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
2927 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2928 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
2929 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2930 {
2931 /* Pending PGM C3 sync. */
2932 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2933 {
2934 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2935 if (rc != VINF_SUCCESS)
2936 {
2937 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2938 return rc;
2939 }
2940 }
2941
2942 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2943 /* -XXX- what was that about single stepping? */
2944 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2945 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2946 {
2947 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2948 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2949 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2950 return rc;
2951 }
2952
2953 /* Pending VM request packets, such as hardware interrupts. */
2954 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2955 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2956 {
2957 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2958 return VINF_EM_PENDING_REQUEST;
2959 }
2960
2961 /* Pending PGM pool flushes. */
2962 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2963 {
2964 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2965 return VINF_PGM_POOL_FLUSH_PENDING;
2966 }
2967
2968 /* Pending DMA requests. */
2969 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2970 {
2971 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2972 return VINF_EM_RAW_TO_R3;
2973 }
2974 }
2975
2976 return VINF_SUCCESS;
2977}
2978
2979
2980/**
2981 * Does the preparations before executing guest code in AMD-V.
2982 *
2983 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2984 * recompiler. We must be cautious what we do here regarding committing
2985 * guest-state information into the VMCB assuming we assuredly execute the guest
2986 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
2987 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2988 * that the recompiler can (and should) use them when it resumes guest
2989 * execution. Otherwise such operations must be done when we can no longer
2990 * exit to ring-3.
2991 *
2992 * @returns VBox status code (informational status codes included).
2993 * @retval VINF_SUCCESS if we can proceed with running the guest.
2994 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2995 *
2996 * @param pVM The cross context VM structure.
2997 * @param pVCpu The cross context virtual CPU structure.
2998 * @param pCtx Pointer to the guest-CPU context.
2999 * @param pSvmTransient Pointer to the SVM transient structure.
3000 */
3001static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3002{
3003 HMSVM_ASSERT_PREEMPT_SAFE();
3004
3005 /* Check force flag actions that might require us to go back to ring-3. */
3006 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
3007 if (rc != VINF_SUCCESS)
3008 return rc;
3009
3010 if (TRPMHasTrap(pVCpu))
3011 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
3012 else if (!pVCpu->hm.s.Event.fPending)
3013 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
3014
3015 /*
3016 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
3017 * Just do it in software, see @bugref{8411}.
3018 * NB: If we could continue a task switch exit we wouldn't need to do this.
3019 */
3020 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
3021 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
3022 return VINF_EM_RAW_INJECT_TRPM_EVENT;
3023
3024#ifdef HMSVM_SYNC_FULL_GUEST_STATE
3025 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
3026#endif
3027
3028 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
3029 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
3030 AssertRCReturn(rc, rc);
3031 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
3032
3033 /*
3034 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
3035 * so we can update it on the way back if the guest changed the TPR.
3036 */
3037 if (pVCpu->hm.s.svm.fSyncVTpr)
3038 {
3039 if (pVM->hm.s.fTPRPatchingActive)
3040 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
3041 else
3042 {
3043 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3044 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
3045 }
3046 }
3047
3048 /*
3049 * No longjmps to ring-3 from this point on!!!
3050 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3051 * This also disables flushing of the R0-logger instance (if any).
3052 */
3053 VMMRZCallRing3Disable(pVCpu);
3054
3055 /*
3056 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
3057 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
3058 *
3059 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
3060 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
3061 *
3062 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
3063 * executing guest code.
3064 */
3065 pSvmTransient->fEFlags = ASMIntDisableFlags();
3066 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
3067 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
3068 {
3069 ASMSetFlags(pSvmTransient->fEFlags);
3070 VMMRZCallRing3Enable(pVCpu);
3071 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
3072 return VINF_EM_RAW_TO_R3;
3073 }
3074 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
3075 {
3076 ASMSetFlags(pSvmTransient->fEFlags);
3077 VMMRZCallRing3Enable(pVCpu);
3078 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
3079 return VINF_EM_RAW_INTERRUPT;
3080 }
3081
3082 /*
3083 * If we are injecting an NMI, we must set VMCPU_FF_BLOCK_NMIS only when we are going to execute
3084 * guest code for certain (no exits to ring-3). Otherwise, we could re-read the flag on re-entry into
3085 * AMD-V and conclude that NMI inhibition is active when we have not even delivered the NMI.
3086 *
3087 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set the
3088 * VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
3089 */
3090 if (pVCpu->hm.s.Event.fPending)
3091 {
3092 SVMEVENT Event;
3093 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3094 if ( Event.n.u1Valid
3095 && Event.n.u3Type == SVM_EVENT_NMI
3096 && Event.n.u8Vector == X86_XCPT_NMI
3097 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
3098 {
3099 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
3100 }
3101 }
3102
3103 return VINF_SUCCESS;
3104}
3105
3106
3107/**
3108 * Prepares to run guest code in AMD-V and we've committed to doing so. This
3109 * means there is no backing out to ring-3 or anywhere else at this
3110 * point.
3111 *
3112 * @param pVM The cross context VM structure.
3113 * @param pVCpu The cross context virtual CPU structure.
3114 * @param pCtx Pointer to the guest-CPU context.
3115 * @param pSvmTransient Pointer to the SVM transient structure.
3116 *
3117 * @remarks Called with preemption disabled.
3118 * @remarks No-long-jump zone!!!
3119 */
3120static void hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3121{
3122 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3123 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3124 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3125
3126 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3127 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
3128
3129 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
3130
3131 if ( pVCpu->hm.s.fPreloadGuestFpu
3132 && !CPUMIsGuestFPUStateActive(pVCpu))
3133 {
3134 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
3135 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
3136 }
3137
3138 /* Load the state shared between host and guest (FPU, debug). */
3139 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3140 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
3141 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
3142 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
3143 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
3144
3145 /* Setup TSC offsetting. */
3146 RTCPUID idCurrentCpu = HMR0GetCurrentCpu()->idCpu;
3147 if ( pSvmTransient->fUpdateTscOffsetting
3148 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
3149 {
3150 hmR0SvmUpdateTscOffsetting(pVM, pVCpu);
3151 pSvmTransient->fUpdateTscOffsetting = false;
3152 }
3153
3154 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
3155 if (idCurrentCpu != pVCpu->hm.s.idLastCpu)
3156 pVmcb->ctrl.u64VmcbCleanBits = 0;
3157
3158 /* Store status of the shared guest-host state at the time of VMRUN. */
3159#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
3160 if (CPUMIsGuestInLongModeEx(pCtx))
3161 {
3162 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
3163 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
3164 }
3165 else
3166#endif
3167 {
3168 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
3169 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
3170 }
3171 pSvmTransient->fWasGuestFPUStateActive = CPUMIsGuestFPUStateActive(pVCpu);
3172
3173 /* Flush the appropriate tagged-TLB entries. */
3174 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
3175 hmR0SvmFlushTaggedTlb(pVCpu);
3176 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
3177
3178 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
3179
3180 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
3181 to start executing. */
3182
3183 /*
3184 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
3185 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
3186 *
3187 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
3188 */
3189 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
3190 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
3191 {
3192 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
3193 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
3194 uint64_t u64GuestTscAux = CPUMR0GetGuestTscAux(pVCpu);
3195 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
3196 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
3197 pSvmTransient->fRestoreTscAuxMsr = true;
3198 }
3199 else
3200 {
3201 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
3202 pSvmTransient->fRestoreTscAuxMsr = false;
3203 }
3204
3205 /* If VMCB Clean bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
3206 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
3207 pVmcb->ctrl.u64VmcbCleanBits = 0;
3208}
3209
3210
3211/**
3212 * Wrapper for running the guest code in AMD-V.
3213 *
3214 * @returns VBox strict status code.
3215 * @param pVM The cross context VM structure.
3216 * @param pVCpu The cross context virtual CPU structure.
3217 * @param pCtx Pointer to the guest-CPU context.
3218 *
3219 * @remarks No-long-jump zone!!!
3220 */
3221DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3222{
3223 /*
3224 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
3225 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
3226 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
3227 */
3228#ifdef VBOX_WITH_KERNEL_USING_XMM
3229 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
3230 pVCpu->hm.s.svm.pfnVMRun);
3231#else
3232 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
3233#endif
3234}
3235
3236
3237/**
3238 * Performs some essential restoration of state after running guest code in
3239 * AMD-V.
3240 *
3241 * @param pVM The cross context VM structure.
3242 * @param pVCpu The cross context virtual CPU structure.
3243 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
3244 * out-of-sync. Make sure to update the required fields
3245 * before using them.
3246 * @param pSvmTransient Pointer to the SVM transient structure.
3247 * @param rcVMRun Return code of VMRUN.
3248 *
3249 * @remarks Called with interrupts disabled.
3250 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
3251 * unconditionally when it is safe to do so.
3252 */
3253static void hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
3254{
3255 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3256
3257 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
3258 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
3259
3260 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3261 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
3262
3263 /* TSC read must be done early for maximum accuracy. */
3264 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
3265 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset);
3266
3267 if (pSvmTransient->fRestoreTscAuxMsr)
3268 {
3269 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
3270 CPUMR0SetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
3271 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
3272 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
3273 }
3274
3275 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
3276 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
3277 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3278
3279 Assert(!(ASMGetFlags() & X86_EFL_IF));
3280 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
3281 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
3282
3283 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
3284 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
3285 {
3286 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
3287 return;
3288 }
3289
3290 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
3291 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmcb->ctrl.u64ExitCode); /* Update the #VMEXIT history array. */
3292 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
3293 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
3294
3295 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
3296
3297 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
3298 {
3299 if (pVCpu->hm.s.svm.fSyncVTpr)
3300 {
3301 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
3302 if ( pVM->hm.s.fTPRPatchingActive
3303 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
3304 {
3305 int rc = APICSetTpr(pVCpu, pMixedCtx->msrLSTAR & 0xff);
3306 AssertRC(rc);
3307 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3308 }
3309 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
3310 {
3311 int rc = APICSetTpr(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
3312 AssertRC(rc);
3313 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3314 }
3315 }
3316 }
3317}
3318
3319
3320/**
3321 * Runs the guest code using AMD-V.
3322 *
3323 * @returns VBox status code.
3324 * @param pVM The cross context VM structure.
3325 * @param pVCpu The cross context virtual CPU structure.
3326 * @param pCtx Pointer to the guest-CPU context.
3327 */
3328static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3329{
3330 SVMTRANSIENT SvmTransient;
3331 SvmTransient.fUpdateTscOffsetting = true;
3332 uint32_t cLoops = 0;
3333 int rc = VERR_INTERNAL_ERROR_5;
3334
3335 for (;; cLoops++)
3336 {
3337 Assert(!HMR0SuspendPending());
3338 HMSVM_ASSERT_CPU_SAFE();
3339
3340 /* Preparatory work for running guest code, this may force us to return
3341 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3342 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3343 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3344 if (rc != VINF_SUCCESS)
3345 break;
3346
3347 /*
3348 * No longjmps to ring-3 from this point on!!!
3349 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3350 * This also disables flushing of the R0-logger instance (if any).
3351 */
3352 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3353 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3354
3355 /* Restore any residual host-state and save any bits shared between host
3356 and guest into the guest-CPU state. Re-enables interrupts! */
3357 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3358
3359 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3360 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3361 {
3362 if (rc == VINF_SUCCESS)
3363 rc = VERR_SVM_INVALID_GUEST_STATE;
3364 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3365 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3366 break;
3367 }
3368
3369 /* Handle the #VMEXIT. */
3370 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3371 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3372 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb);
3373 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3374 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3375 if (rc != VINF_SUCCESS)
3376 break;
3377 if (cLoops > pVM->hm.s.cMaxResumeLoops)
3378 {
3379 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
3380 rc = VINF_EM_RAW_INTERRUPT;
3381 break;
3382 }
3383 }
3384
3385 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3386 return rc;
3387}
3388
3389
3390/**
3391 * Runs the guest code using AMD-V in single step mode.
3392 *
3393 * @returns VBox status code.
3394 * @param pVM The cross context VM structure.
3395 * @param pVCpu The cross context virtual CPU structure.
3396 * @param pCtx Pointer to the guest-CPU context.
3397 */
3398static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3399{
3400 SVMTRANSIENT SvmTransient;
3401 SvmTransient.fUpdateTscOffsetting = true;
3402 uint32_t cLoops = 0;
3403 int rc = VERR_INTERNAL_ERROR_5;
3404 uint16_t uCsStart = pCtx->cs.Sel;
3405 uint64_t uRipStart = pCtx->rip;
3406
3407 for (;; cLoops++)
3408 {
3409 Assert(!HMR0SuspendPending());
3410 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
3411 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
3412 (unsigned)RTMpCpuId(), cLoops));
3413
3414 /* Preparatory work for running guest code, this may force us to return
3415 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3416 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3417 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3418 if (rc != VINF_SUCCESS)
3419 break;
3420
3421 /*
3422 * No longjmps to ring-3 from this point on!!!
3423 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3424 * This also disables flushing of the R0-logger instance (if any).
3425 */
3426 VMMRZCallRing3Disable(pVCpu);
3427 VMMRZCallRing3RemoveNotification(pVCpu);
3428 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3429
3430 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3431
3432 /*
3433 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
3434 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
3435 */
3436 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3437 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3438 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3439 {
3440 if (rc == VINF_SUCCESS)
3441 rc = VERR_SVM_INVALID_GUEST_STATE;
3442 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3443 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3444 return rc;
3445 }
3446
3447 /* Handle the #VMEXIT. */
3448 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3449 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3450 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb);
3451 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3452 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3453 if (rc != VINF_SUCCESS)
3454 break;
3455 if (cLoops > pVM->hm.s.cMaxResumeLoops)
3456 {
3457 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
3458 rc = VINF_EM_RAW_INTERRUPT;
3459 break;
3460 }
3461
3462 /*
3463 * Did the RIP change, if so, consider it a single step.
3464 * Otherwise, make sure one of the TFs gets set.
3465 */
3466 if ( pCtx->rip != uRipStart
3467 || pCtx->cs.Sel != uCsStart)
3468 {
3469 rc = VINF_EM_DBG_STEPPED;
3470 break;
3471 }
3472 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
3473 }
3474
3475 /*
3476 * Clear the X86_EFL_TF if necessary.
3477 */
3478 if (pVCpu->hm.s.fClearTrapFlag)
3479 {
3480 pVCpu->hm.s.fClearTrapFlag = false;
3481 pCtx->eflags.Bits.u1TF = 0;
3482 }
3483
3484 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3485 return rc;
3486}
3487
3488
3489/**
3490 * Runs the guest code using AMD-V.
3491 *
3492 * @returns Strict VBox status code.
3493 * @param pVM The cross context VM structure.
3494 * @param pVCpu The cross context virtual CPU structure.
3495 * @param pCtx Pointer to the guest-CPU context.
3496 */
3497VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3498{
3499 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3500 HMSVM_ASSERT_PREEMPT_SAFE();
3501 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
3502
3503 int rc;
3504 if (!pVCpu->hm.s.fSingleInstruction)
3505 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx);
3506 else
3507 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx);
3508
3509 if (rc == VERR_EM_INTERPRETER)
3510 rc = VINF_EM_RAW_EMULATE_INSTR;
3511 else if (rc == VINF_EM_RESET)
3512 rc = VINF_EM_TRIPLE_FAULT;
3513
3514 /* Prepare to return to ring-3. This will remove longjmp notifications. */
3515 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
3516 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
3517 return rc;
3518}
3519
3520
3521/**
3522 * Handles a \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
3523 *
3524 * @returns VBox status code (informational status codes included).
3525 * @param pVCpu The cross context virtual CPU structure.
3526 * @param pCtx Pointer to the guest-CPU context.
3527 * @param pSvmTransient Pointer to the SVM transient structure.
3528 */
3529DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3530{
3531 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
3532 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
3533
3534 /*
3535 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs for most guests under
3536 * normal workloads (for some definition of "normal").
3537 */
3538 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
3539 switch (pSvmTransient->u64ExitCode)
3540 {
3541 case SVM_EXIT_NPF:
3542 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
3543
3544 case SVM_EXIT_IOIO:
3545 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
3546
3547 case SVM_EXIT_RDTSC:
3548 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
3549
3550 case SVM_EXIT_RDTSCP:
3551 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
3552
3553 case SVM_EXIT_CPUID:
3554 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
3555
3556 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
3557 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
3558
3559 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
3560 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
3561
3562 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3563 return hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient);
3564
3565 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
3566 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
3567
3568 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
3569 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
3570
3571 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3572 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
3573
3574 case SVM_EXIT_MONITOR:
3575 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
3576
3577 case SVM_EXIT_MWAIT:
3578 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
3579
3580 case SVM_EXIT_HLT:
3581 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
3582
3583 case SVM_EXIT_READ_CR0:
3584 case SVM_EXIT_READ_CR3:
3585 case SVM_EXIT_READ_CR4:
3586 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
3587
3588 case SVM_EXIT_WRITE_CR0:
3589 case SVM_EXIT_WRITE_CR3:
3590 case SVM_EXIT_WRITE_CR4:
3591 case SVM_EXIT_WRITE_CR8:
3592 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
3593
3594 case SVM_EXIT_PAUSE:
3595 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
3596
3597 case SVM_EXIT_VMMCALL:
3598 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3599
3600 case SVM_EXIT_VINTR:
3601 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
3602
3603 case SVM_EXIT_INTR:
3604 case SVM_EXIT_FERR_FREEZE:
3605 case SVM_EXIT_NMI:
3606 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
3607
3608 case SVM_EXIT_MSR:
3609 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
3610
3611 case SVM_EXIT_INVLPG:
3612 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
3613
3614 case SVM_EXIT_WBINVD:
3615 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
3616
3617 case SVM_EXIT_INVD:
3618 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
3619
3620 case SVM_EXIT_RDPMC:
3621 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
3622
3623 default:
3624 {
3625 switch (pSvmTransient->u64ExitCode)
3626 {
3627 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
3628 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
3629 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
3630 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
3631 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3632
3633 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
3634 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
3635 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3636 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3637 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3638
3639 case SVM_EXIT_XSETBV:
3640 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
3641
3642 case SVM_EXIT_TASK_SWITCH:
3643 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3644
3645 case SVM_EXIT_IRET:
3646 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
3647
3648 case SVM_EXIT_SHUTDOWN:
3649 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3650
3651 case SVM_EXIT_SMI:
3652 case SVM_EXIT_INIT:
3653 {
3654 /*
3655 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3656 * we want to know about it so log the exit code and bail.
3657 */
3658 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3659 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3660 return VERR_SVM_UNEXPECTED_EXIT;
3661 }
3662
3663 case SVM_EXIT_INVLPGA:
3664 case SVM_EXIT_RSM:
3665 case SVM_EXIT_VMRUN:
3666 case SVM_EXIT_VMLOAD:
3667 case SVM_EXIT_VMSAVE:
3668 case SVM_EXIT_STGI:
3669 case SVM_EXIT_CLGI:
3670 case SVM_EXIT_SKINIT:
3671 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3672
3673#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3674 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3675 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3676 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3677 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3678 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3679 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3680 /* case SVM_EXIT_EXCEPTION_6: */ /* X86_XCPT_UD - Handled above. */
3681 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3682 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3683 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3684 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3685 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3686 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3687 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3688 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3689 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3690 /* SVM_EXIT_EXCEPTION_11: */ /* X86_XCPT_AC - Handled above. */
3691 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3692 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3693 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3694 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3695 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3696 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3697 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3698 {
3699 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3700 SVMEVENT Event;
3701 Event.u = 0;
3702 Event.n.u1Valid = 1;
3703 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3704 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3705
3706 switch (Event.n.u8Vector)
3707 {
3708 case X86_XCPT_DE:
3709 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3710 break;
3711
3712 case X86_XCPT_BP:
3713 /** Saves the wrong EIP on the stack (pointing to the int3) instead of the
3714 * next instruction. */
3715 /** @todo Investigate this later. */
3716 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
3717 break;
3718
3719 case X86_XCPT_NP:
3720 Event.n.u1ErrorCodeValid = 1;
3721 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3722 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3723 break;
3724
3725 case X86_XCPT_SS:
3726 Event.n.u1ErrorCodeValid = 1;
3727 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3728 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3729 break;
3730
3731 case X86_XCPT_GP:
3732 Event.n.u1ErrorCodeValid = 1;
3733 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3734 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3735 break;
3736
3737 default:
3738 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3739 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3740 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3741 }
3742
3743 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3744 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3745 return VINF_SUCCESS;
3746 }
3747#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3748
3749 default:
3750 {
3751 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3752 pVCpu->hm.s.u32HMError = u32ExitCode;
3753 return VERR_SVM_UNKNOWN_EXIT;
3754 }
3755 }
3756 }
3757 }
3758 /* not reached */
3759}
3760
3761
3762#ifdef DEBUG
3763/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3764# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3765 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3766
3767# define HMSVM_ASSERT_PREEMPT_CPUID() \
3768 do \
3769 { \
3770 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3771 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3772 } while (0)
3773
3774# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3775 do { \
3776 AssertPtr(pVCpu); \
3777 AssertPtr(pCtx); \
3778 AssertPtr(pSvmTransient); \
3779 Assert(ASMIntAreEnabled()); \
3780 HMSVM_ASSERT_PREEMPT_SAFE(); \
3781 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3782 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)); \
3783 HMSVM_ASSERT_PREEMPT_SAFE(); \
3784 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3785 HMSVM_ASSERT_PREEMPT_CPUID(); \
3786 } while (0)
3787#else /* Release builds */
3788# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
3789#endif
3790
3791
3792/**
3793 * Worker for hmR0SvmInterpretInvlpg().
3794 *
3795 * @return VBox status code.
3796 * @param pVCpu The cross context virtual CPU structure.
3797 * @param pCpu Pointer to the disassembler state.
3798 * @param pCtx The guest CPU context.
3799 */
3800static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
3801{
3802 DISQPVPARAMVAL Param1;
3803 RTGCPTR GCPtrPage;
3804
3805 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3806 if (RT_FAILURE(rc))
3807 return VERR_EM_INTERPRETER;
3808
3809 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3810 || Param1.type == DISQPV_TYPE_ADDRESS)
3811 {
3812 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3813 return VERR_EM_INTERPRETER;
3814
3815 GCPtrPage = Param1.val.val64;
3816 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
3817 rc = VBOXSTRICTRC_VAL(rc2);
3818 }
3819 else
3820 {
3821 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3822 rc = VERR_EM_INTERPRETER;
3823 }
3824
3825 return rc;
3826}
3827
3828
3829/**
3830 * Interprets INVLPG.
3831 *
3832 * @returns VBox status code.
3833 * @retval VINF_* Scheduling instructions.
3834 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3835 * @retval VERR_* Fatal errors.
3836 *
3837 * @param pVM The cross context VM structure.
3838 * @param pVCpu The cross context virtual CPU structure.
3839 * @param pCtx The guest CPU context.
3840 *
3841 * @remarks Updates the RIP if the instruction was executed successfully.
3842 */
3843static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3844{
3845 /* Only allow 32 & 64 bit code. */
3846 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3847 {
3848 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3849 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3850 if ( RT_SUCCESS(rc)
3851 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3852 {
3853 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
3854 if (RT_SUCCESS(rc))
3855 pCtx->rip += pDis->cbInstr;
3856 return rc;
3857 }
3858 else
3859 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3860 }
3861 return VERR_EM_INTERPRETER;
3862}
3863
3864
3865/**
3866 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
3867 *
3868 * @param pVCpu The cross context virtual CPU structure.
3869 */
3870DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3871{
3872 SVMEVENT Event;
3873 Event.u = 0;
3874 Event.n.u1Valid = 1;
3875 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3876 Event.n.u8Vector = X86_XCPT_UD;
3877 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3878}
3879
3880
3881/**
3882 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
3883 *
3884 * @param pVCpu The cross context virtual CPU structure.
3885 */
3886DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3887{
3888 SVMEVENT Event;
3889 Event.u = 0;
3890 Event.n.u1Valid = 1;
3891 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3892 Event.n.u8Vector = X86_XCPT_DB;
3893 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3894}
3895
3896
3897/**
3898 * Sets a page fault (\#PF) exception as pending-for-injection into the VM.
3899 *
3900 * @param pVCpu The cross context virtual CPU structure.
3901 * @param pCtx Pointer to the guest-CPU context.
3902 * @param u32ErrCode The error-code for the page-fault.
3903 * @param uFaultAddress The page fault address (CR2).
3904 *
3905 * @remarks This updates the guest CR2 with @a uFaultAddress!
3906 */
3907DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3908{
3909 SVMEVENT Event;
3910 Event.u = 0;
3911 Event.n.u1Valid = 1;
3912 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3913 Event.n.u8Vector = X86_XCPT_PF;
3914 Event.n.u1ErrorCodeValid = 1;
3915 Event.n.u32ErrorCode = u32ErrCode;
3916
3917 /* Update CR2 of the guest. */
3918 if (pCtx->cr2 != uFaultAddress)
3919 {
3920 pCtx->cr2 = uFaultAddress;
3921 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3922 }
3923
3924 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3925}
3926
3927
3928/**
3929 * Sets a device-not-available (\#NM) exception as pending-for-injection into
3930 * the VM.
3931 *
3932 * @param pVCpu The cross context virtual CPU structure.
3933 */
3934DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3935{
3936 SVMEVENT Event;
3937 Event.u = 0;
3938 Event.n.u1Valid = 1;
3939 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3940 Event.n.u8Vector = X86_XCPT_NM;
3941 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3942}
3943
3944
3945/**
3946 * Sets a math-fault (\#MF) exception as pending-for-injection into the VM.
3947 *
3948 * @param pVCpu The cross context virtual CPU structure.
3949 */
3950DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3951{
3952 SVMEVENT Event;
3953 Event.u = 0;
3954 Event.n.u1Valid = 1;
3955 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3956 Event.n.u8Vector = X86_XCPT_MF;
3957 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3958}
3959
3960
3961/**
3962 * Sets a double fault (\#DF) exception as pending-for-injection into the VM.
3963 *
3964 * @param pVCpu The cross context virtual CPU structure.
3965 */
3966DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3967{
3968 SVMEVENT Event;
3969 Event.u = 0;
3970 Event.n.u1Valid = 1;
3971 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3972 Event.n.u8Vector = X86_XCPT_DF;
3973 Event.n.u1ErrorCodeValid = 1;
3974 Event.n.u32ErrorCode = 0;
3975 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3976}
3977
3978
3979/**
3980 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3981 * guests. This simply looks up the patch record at EIP and does the required.
3982 *
3983 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3984 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3985 * TPR). See hmR3ReplaceTprInstr() for the details.
3986 *
3987 * @returns VBox status code.
3988 * @retval VINF_SUCCESS if the access was handled successfully.
3989 * @retval VERR_NOT_FOUND if no patch record for this RIP could be found.
3990 * @retval VERR_SVM_UNEXPECTED_PATCH_TYPE if the found patch type is invalid.
3991 *
3992 * @param pVM The cross context VM structure.
3993 * @param pVCpu The cross context virtual CPU structure.
3994 * @param pCtx Pointer to the guest-CPU context.
3995 */
3996static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3997{
3998 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3999
4000 /*
4001 * We do this in a loop as we increment the RIP after a successful emulation
4002 * and the new RIP may be a patched instruction which needs emulation as well.
4003 */
4004 bool fPatchFound = false;
4005 for (;;)
4006 {
4007 bool fPending;
4008 uint8_t u8Tpr;
4009
4010 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4011 if (!pPatch)
4012 break;
4013
4014 fPatchFound = true;
4015 switch (pPatch->enmType)
4016 {
4017 case HMTPRINSTR_READ:
4018 {
4019 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
4020 AssertRC(rc);
4021
4022 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
4023 AssertRC(rc);
4024 pCtx->rip += pPatch->cbOp;
4025 break;
4026 }
4027
4028 case HMTPRINSTR_WRITE_REG:
4029 case HMTPRINSTR_WRITE_IMM:
4030 {
4031 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
4032 {
4033 uint32_t u32Val;
4034 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
4035 AssertRC(rc);
4036 u8Tpr = u32Val;
4037 }
4038 else
4039 u8Tpr = (uint8_t)pPatch->uSrcOperand;
4040
4041 int rc2 = APICSetTpr(pVCpu, u8Tpr);
4042 AssertRC(rc2);
4043 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4044
4045 pCtx->rip += pPatch->cbOp;
4046 break;
4047 }
4048
4049 default:
4050 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
4051 pVCpu->hm.s.u32HMError = pPatch->enmType;
4052 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
4053 }
4054 }
4055
4056 if (fPatchFound)
4057 return VINF_SUCCESS;
4058 return VERR_NOT_FOUND;
4059}
4060
4061
4062/**
4063 * Determines if an exception is a contributory exception.
4064 *
4065 * Contributory exceptions are ones which can cause double-faults unless the
4066 * original exception was a benign exception. Page-fault is intentionally not
4067 * included here as it's a conditional contributory exception.
4068 *
4069 * @returns true if the exception is contributory, false otherwise.
4070 * @param uVector The exception vector.
4071 */
4072DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
4073{
4074 switch (uVector)
4075 {
4076 case X86_XCPT_GP:
4077 case X86_XCPT_SS:
4078 case X86_XCPT_NP:
4079 case X86_XCPT_TS:
4080 case X86_XCPT_DE:
4081 return true;
4082 default:
4083 break;
4084 }
4085 return false;
4086}
4087
4088
4089/**
4090 * Handle a condition that occurred while delivering an event through the guest
4091 * IDT.
4092 *
4093 * @returns VBox status code (informational error codes included).
4094 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
4095 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
4096 * continue execution of the guest which will delivery the \#DF.
4097 * @retval VINF_EM_RESET if we detected a triple-fault condition.
4098 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
4099 *
4100 * @param pVCpu The cross context virtual CPU structure.
4101 * @param pCtx Pointer to the guest-CPU context.
4102 * @param pSvmTransient Pointer to the SVM transient structure.
4103 *
4104 * @remarks No-long-jump zone!!!
4105 */
4106static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4107{
4108 int rc = VINF_SUCCESS;
4109 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4110
4111 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
4112 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
4113 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
4114
4115 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
4116 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
4117 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
4118 {
4119 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
4120
4121 typedef enum
4122 {
4123 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
4124 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
4125 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
4126 SVMREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
4127 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
4128 } SVMREFLECTXCPT;
4129
4130 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
4131 bool fReflectingNmi = false;
4132 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
4133 {
4134 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
4135 {
4136 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
4137
4138#ifdef VBOX_STRICT
4139 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
4140 && uExitVector == X86_XCPT_PF)
4141 {
4142 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
4143 }
4144#endif
4145
4146 if ( uIdtVector == X86_XCPT_BP
4147 || uIdtVector == X86_XCPT_OF)
4148 {
4149 /* Ignore INT3/INTO, just re-execute. See @bugref{8357}. */
4150 }
4151 else if ( uExitVector == X86_XCPT_PF
4152 && uIdtVector == X86_XCPT_PF)
4153 {
4154 pSvmTransient->fVectoringDoublePF = true;
4155 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
4156 }
4157 else if ( uExitVector == X86_XCPT_AC
4158 && uIdtVector == X86_XCPT_AC)
4159 {
4160 enmReflect = SVMREFLECTXCPT_HANG;
4161 Log4(("IDT: Nested #AC - Bad guest\n"));
4162 }
4163 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
4164 && hmR0SvmIsContributoryXcpt(uExitVector)
4165 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
4166 || uIdtVector == X86_XCPT_PF))
4167 {
4168 enmReflect = SVMREFLECTXCPT_DF;
4169 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
4170 uIdtVector, uExitVector));
4171 }
4172 else if (uIdtVector == X86_XCPT_DF)
4173 {
4174 enmReflect = SVMREFLECTXCPT_TF;
4175 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
4176 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
4177 }
4178 else
4179 enmReflect = SVMREFLECTXCPT_XCPT;
4180 }
4181 else
4182 {
4183 /*
4184 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
4185 * exception to the guest after handling the #VMEXIT.
4186 */
4187 enmReflect = SVMREFLECTXCPT_XCPT;
4188 }
4189 }
4190 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
4191 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
4192 {
4193 enmReflect = SVMREFLECTXCPT_XCPT;
4194 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
4195
4196 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
4197 {
4198 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
4199 if (uExitVector == X86_XCPT_PF)
4200 {
4201 pSvmTransient->fVectoringPF = true;
4202 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
4203 }
4204 }
4205 }
4206 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
4207
4208 switch (enmReflect)
4209 {
4210 case SVMREFLECTXCPT_XCPT:
4211 {
4212 /* If we are re-injecting the NMI, clear NMI blocking. */
4213 if (fReflectingNmi)
4214 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
4215
4216 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
4217 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
4218 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
4219
4220 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
4221 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
4222 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
4223 break;
4224 }
4225
4226 case SVMREFLECTXCPT_DF:
4227 {
4228 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
4229 hmR0SvmSetPendingXcptDF(pVCpu);
4230 rc = VINF_HM_DOUBLE_FAULT;
4231 break;
4232 }
4233
4234 case SVMREFLECTXCPT_TF:
4235 {
4236 rc = VINF_EM_RESET;
4237 break;
4238 }
4239
4240 case SVMREFLECTXCPT_HANG:
4241 {
4242 rc = VERR_EM_GUEST_CPU_HANG;
4243 break;
4244 }
4245
4246 default:
4247 Assert(rc == VINF_SUCCESS);
4248 break;
4249 }
4250 }
4251 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
4252 NOREF(pCtx);
4253 return rc;
4254}
4255
4256/**
4257 * Updates interrupt shadow for the current RIP.
4258 */
4259#define HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx) \
4260 do { \
4261 /* Update interrupt shadow. */ \
4262 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS) \
4263 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu)) \
4264 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS); \
4265 } while (0)
4266
4267/**
4268 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
4269 * supported, otherwise advances the RIP by the number of bytes specified in
4270 * @a cb.
4271 *
4272 * @param pVCpu The cross context virtual CPU structure.
4273 * @param pCtx Pointer to the guest-CPU context.
4274 * @param cb RIP increment value in bytes.
4275 *
4276 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
4277 * when NRIP_SAVE is supported by the CPU, otherwise use
4278 * hmR0SvmAdvanceRipDumb!
4279 */
4280DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
4281{
4282 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4283 {
4284 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4285 Assert(pVmcb->ctrl.u64NextRIP);
4286 Assert(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb);
4287 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4288 }
4289 else
4290 pCtx->rip += cb;
4291
4292 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
4293}
4294
4295
4296/**
4297 * Advances the guest RIP by the number of bytes specified in @a cb. This does
4298 * not make use of any hardware features to determine the instruction length.
4299 *
4300 * @param pVCpu The cross context virtual CPU structure.
4301 * @param pCtx Pointer to the guest-CPU context.
4302 * @param cb RIP increment value in bytes.
4303 */
4304DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
4305{
4306 pCtx->rip += cb;
4307 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
4308}
4309#undef HMSVM_UPDATE_INTR_SHADOW
4310
4311
4312/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4313/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
4314/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4315
4316/** @name \#VMEXIT handlers.
4317 * @{
4318 */
4319
4320/**
4321 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
4322 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
4323 */
4324HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4325{
4326 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4327
4328 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
4329 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
4330 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
4331 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
4332
4333 /*
4334 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
4335 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
4336 * interrupt it is until the host actually take the interrupt.
4337 *
4338 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
4339 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
4340 */
4341 return VINF_EM_RAW_INTERRUPT;
4342}
4343
4344
4345/**
4346 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
4347 */
4348HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4349{
4350 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4351
4352 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4353 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
4354 int rc = VINF_SUCCESS;
4355 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4356 return rc;
4357}
4358
4359
4360/**
4361 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
4362 */
4363HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4364{
4365 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4366
4367 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4368 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
4369 int rc = VINF_SUCCESS;
4370 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4371 return rc;
4372}
4373
4374
4375/**
4376 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
4377 */
4378HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4379{
4380 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4381 PVM pVM = pVCpu->CTX_SUFF(pVM);
4382 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4383 if (RT_LIKELY(rc == VINF_SUCCESS))
4384 {
4385 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4386 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4387 }
4388 else
4389 {
4390 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
4391 rc = VERR_EM_INTERPRETER;
4392 }
4393 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
4394 return rc;
4395}
4396
4397
4398/**
4399 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
4400 */
4401HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4402{
4403 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4404 PVM pVM = pVCpu->CTX_SUFF(pVM);
4405 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4406 if (RT_LIKELY(rc == VINF_SUCCESS))
4407 {
4408 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4409 pSvmTransient->fUpdateTscOffsetting = true;
4410
4411 /* Single step check. */
4412 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4413 }
4414 else
4415 {
4416 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
4417 rc = VERR_EM_INTERPRETER;
4418 }
4419 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
4420 return rc;
4421}
4422
4423
4424/**
4425 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
4426 */
4427HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4428{
4429 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4430 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4431 if (RT_LIKELY(rc == VINF_SUCCESS))
4432 {
4433 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
4434 pSvmTransient->fUpdateTscOffsetting = true;
4435 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4436 }
4437 else
4438 {
4439 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
4440 rc = VERR_EM_INTERPRETER;
4441 }
4442 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
4443 return rc;
4444}
4445
4446
4447/**
4448 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
4449 */
4450HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4451{
4452 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4453 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4454 if (RT_LIKELY(rc == VINF_SUCCESS))
4455 {
4456 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4457 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4458 }
4459 else
4460 {
4461 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
4462 rc = VERR_EM_INTERPRETER;
4463 }
4464 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
4465 return rc;
4466}
4467
4468
4469/**
4470 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
4471 */
4472HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4473{
4474 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4475 PVM pVM = pVCpu->CTX_SUFF(pVM);
4476 Assert(!pVM->hm.s.fNestedPaging);
4477
4478 /** @todo Decode Assist. */
4479 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
4480 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
4481 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
4482 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4483 return rc;
4484}
4485
4486
4487/**
4488 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
4489 */
4490HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4491{
4492 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4493
4494 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
4495 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
4496 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4497 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
4498 if (rc != VINF_SUCCESS)
4499 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
4500 return rc;
4501}
4502
4503
4504/**
4505 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
4506 */
4507HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4508{
4509 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4510 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4511 if (RT_LIKELY(rc == VINF_SUCCESS))
4512 {
4513 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
4514 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4515 }
4516 else
4517 {
4518 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
4519 rc = VERR_EM_INTERPRETER;
4520 }
4521 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
4522 return rc;
4523}
4524
4525
4526/**
4527 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
4528 */
4529HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4530{
4531 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4532 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4533 int rc = VBOXSTRICTRC_VAL(rc2);
4534 if ( rc == VINF_EM_HALT
4535 || rc == VINF_SUCCESS)
4536 {
4537 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
4538
4539 if ( rc == VINF_EM_HALT
4540 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
4541 {
4542 rc = VINF_SUCCESS;
4543 }
4544 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4545 }
4546 else
4547 {
4548 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
4549 rc = VERR_EM_INTERPRETER;
4550 }
4551 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
4552 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
4553 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
4554 return rc;
4555}
4556
4557
4558/**
4559 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
4560 * \#VMEXIT.
4561 */
4562HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4563{
4564 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4565 return VINF_EM_RESET;
4566}
4567
4568
4569/**
4570 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
4571 */
4572HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4573{
4574 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4575
4576 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4577
4578 /** @todo Decode Assist. */
4579 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4580 int rc = VBOXSTRICTRC_VAL(rc2);
4581 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
4582 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
4583 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
4584 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
4585 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4586 return rc;
4587}
4588
4589
4590/**
4591 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
4592 */
4593HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4594{
4595 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4596
4597 /** @todo Decode Assist. */
4598 VBOXSTRICTRC rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
4599 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
4600 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
4601 rcStrict = VERR_EM_INTERPRETER;
4602 if (rcStrict == VINF_SUCCESS)
4603 {
4604 /* RIP has been updated by EMInterpretInstruction(). */
4605 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
4606 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
4607 {
4608 case 0: /* CR0. */
4609 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4610 break;
4611
4612 case 3: /* CR3. */
4613 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4614 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
4615 break;
4616
4617 case 4: /* CR4. */
4618 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
4619 break;
4620
4621 case 8: /* CR8 (TPR). */
4622 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4623 break;
4624
4625 default:
4626 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
4627 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
4628 break;
4629 }
4630 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4631 }
4632 else
4633 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
4634 return VBOXSTRICTRC_TODO(rcStrict);
4635}
4636
4637
4638/**
4639 * \#VMEXIT handler for instructions that result in a \#UD exception delivered
4640 * to the guest.
4641 */
4642HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4643{
4644 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4645 hmR0SvmSetPendingXcptUD(pVCpu);
4646 return VINF_SUCCESS;
4647}
4648
4649
4650/**
4651 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
4652 * \#VMEXIT.
4653 */
4654HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4655{
4656 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4657 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4658 PVM pVM = pVCpu->CTX_SUFF(pVM);
4659
4660 int rc;
4661 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
4662 {
4663 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
4664
4665 /* Handle TPR patching; intercepted LSTAR write. */
4666 if ( pVM->hm.s.fTPRPatchingActive
4667 && pCtx->ecx == MSR_K8_LSTAR)
4668 {
4669 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
4670 {
4671 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
4672 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
4673 AssertRC(rc2);
4674 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4675 }
4676 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4677 rc = VINF_SUCCESS;
4678 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4679 return rc;
4680 }
4681
4682 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4683 {
4684 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4685 if (RT_LIKELY(rc == VINF_SUCCESS))
4686 {
4687 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4688 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4689 }
4690 else
4691 AssertMsg( rc == VERR_EM_INTERPRETER
4692 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
4693 }
4694 else
4695 {
4696 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
4697 if (RT_LIKELY(rc == VINF_SUCCESS))
4698 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
4699 else
4700 AssertMsg( rc == VERR_EM_INTERPRETER
4701 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4702 }
4703
4704 if (rc == VINF_SUCCESS)
4705 {
4706 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
4707 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
4708 && pCtx->ecx <= MSR_IA32_X2APIC_END)
4709 {
4710 /*
4711 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
4712 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
4713 * EMInterpretWrmsr() changes it.
4714 */
4715 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4716 }
4717 else if (pCtx->ecx == MSR_K6_EFER)
4718 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
4719 else if (pCtx->ecx == MSR_IA32_TSC)
4720 pSvmTransient->fUpdateTscOffsetting = true;
4721 }
4722 }
4723 else
4724 {
4725 /* MSR Read access. */
4726 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
4727 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
4728
4729 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4730 {
4731 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4732 if (RT_LIKELY(rc == VINF_SUCCESS))
4733 {
4734 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4735 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4736 }
4737 else
4738 AssertMsg( rc == VERR_EM_INTERPRETER
4739 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
4740 }
4741 else
4742 {
4743 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
4744 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4745 {
4746 AssertMsg( rc == VERR_EM_INTERPRETER
4747 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4748 }
4749 /* RIP updated by EMInterpretInstruction(). */
4750 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4751 }
4752 }
4753
4754 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
4755 return rc;
4756}
4757
4758
4759/**
4760 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
4761 */
4762HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4763{
4764 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4765 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
4766
4767 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
4768 if (pSvmTransient->fWasGuestDebugStateActive)
4769 {
4770 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
4771 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
4772 return VERR_SVM_UNEXPECTED_EXIT;
4773 }
4774
4775 /*
4776 * Lazy DR0-3 loading.
4777 */
4778 if (!pSvmTransient->fWasHyperDebugStateActive)
4779 {
4780 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4781 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4782
4783 /* Don't intercept DRx read and writes. */
4784 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4785 pVmcb->ctrl.u16InterceptRdDRx = 0;
4786 pVmcb->ctrl.u16InterceptWrDRx = 0;
4787 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4788
4789 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
4790 VMMRZCallRing3Disable(pVCpu);
4791 HM_DISABLE_PREEMPT();
4792
4793 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4794 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4795 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
4796
4797 HM_RESTORE_PREEMPT();
4798 VMMRZCallRing3Enable(pVCpu);
4799
4800 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4801 return VINF_SUCCESS;
4802 }
4803
4804 /*
4805 * Interpret the read/writing of DRx.
4806 */
4807 /** @todo Decode assist. */
4808 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4809 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4810 if (RT_LIKELY(rc == VINF_SUCCESS))
4811 {
4812 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4813 /** @todo CPUM should set this flag! */
4814 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
4815 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4816 }
4817 else
4818 Assert(rc == VERR_EM_INTERPRETER);
4819 return VBOXSTRICTRC_TODO(rc);
4820}
4821
4822
4823/**
4824 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
4825 */
4826HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4827{
4828 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4829 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4830 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4831 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4832 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4833 return rc;
4834}
4835
4836
4837/**
4838 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
4839 */
4840HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4841{
4842 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4843
4844 /** @todo decode assists... */
4845 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
4846 if (rcStrict == VINF_IEM_RAISED_XCPT)
4847 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4848
4849 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
4850 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
4851 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
4852
4853 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4854 return VBOXSTRICTRC_TODO(rcStrict);
4855}
4856
4857
4858/**
4859 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
4860 */
4861HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4862{
4863 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4864
4865 /* I/O operation lookup arrays. */
4866 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4867 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4868 the result (in AL/AX/EAX). */
4869 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4870
4871 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4872 PVM pVM = pVCpu->CTX_SUFF(pVM);
4873
4874 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4875 SVMIOIOEXIT IoExitInfo;
4876 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4877 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4878 uint32_t cbValue = s_aIOSize[uIOWidth];
4879 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4880
4881 if (RT_UNLIKELY(!cbValue))
4882 {
4883 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4884 return VERR_EM_INTERPRETER;
4885 }
4886
4887 VBOXSTRICTRC rcStrict;
4888 bool fUpdateRipAlready = false;
4889 if (IoExitInfo.n.u1STR)
4890 {
4891#ifdef VBOX_WITH_2ND_IEM_STEP
4892 /* INS/OUTS - I/O String instruction. */
4893 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4894 * in EXITINFO1? Investigate once this thing is up and running. */
4895 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
4896 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
4897 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
4898 static IEMMODE const s_aenmAddrMode[8] =
4899 {
4900 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
4901 };
4902 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
4903 if (enmAddrMode != (IEMMODE)-1)
4904 {
4905 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
4906 if (cbInstr <= 15 && cbInstr >= 1)
4907 {
4908 Assert(cbInstr >= 1U + IoExitInfo.n.u1REP);
4909 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4910 {
4911 /* Don't know exactly how to detect whether u3SEG is valid, currently
4912 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
4913 2384 Opterons when only checking NRIP. */
4914 if ( (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4915 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
4916 {
4917 AssertMsg(IoExitInfo.n.u3SEG == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1REP,
4918 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3SEG, cbInstr, IoExitInfo.n.u1REP));
4919 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4920 IoExitInfo.n.u3SEG, true /*fIoChecked*/);
4921 }
4922 else if (cbInstr == 1U + IoExitInfo.n.u1REP)
4923 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4924 X86_SREG_DS, true /*fIoChecked*/);
4925 else
4926 rcStrict = IEMExecOne(pVCpu);
4927 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4928 }
4929 else
4930 {
4931 AssertMsg(IoExitInfo.n.u3SEG == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3SEG));
4932 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4933 true /*fIoChecked*/);
4934 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4935 }
4936 }
4937 else
4938 {
4939 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
4940 rcStrict = IEMExecOne(pVCpu);
4941 }
4942 }
4943 else
4944 {
4945 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
4946 rcStrict = IEMExecOne(pVCpu);
4947 }
4948 fUpdateRipAlready = true;
4949
4950#else
4951 /* INS/OUTS - I/O String instruction. */
4952 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4953
4954 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4955 * in EXITINFO1? Investigate once this thing is up and running. */
4956
4957 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4958 if (rcStrict == VINF_SUCCESS)
4959 {
4960 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4961 {
4962 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4963 (DISCPUMODE)pDis->uAddrMode, cbValue);
4964 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4965 }
4966 else
4967 {
4968 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4969 (DISCPUMODE)pDis->uAddrMode, cbValue);
4970 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4971 }
4972 }
4973 else
4974 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
4975#endif
4976 }
4977 else
4978 {
4979 /* IN/OUT - I/O instruction. */
4980 Assert(!IoExitInfo.n.u1REP);
4981
4982 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4983 {
4984 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
4985 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4986 }
4987 else
4988 {
4989 uint32_t u32Val = 0;
4990 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
4991 if (IOM_SUCCESS(rcStrict))
4992 {
4993 /* Save result of I/O IN instr. in AL/AX/EAX. */
4994 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
4995 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4996 }
4997 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4998 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4999
5000 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
5001 }
5002 }
5003
5004 if (IOM_SUCCESS(rcStrict))
5005 {
5006 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
5007 if (!fUpdateRipAlready)
5008 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
5009
5010 /*
5011 * If any I/O breakpoints are armed, we need to check if one triggered
5012 * and take appropriate action.
5013 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
5014 */
5015 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
5016 * execution engines about whether hyper BPs and such are pending. */
5017 uint32_t const uDr7 = pCtx->dr[7];
5018 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
5019 && X86_DR7_ANY_RW_IO(uDr7)
5020 && (pCtx->cr4 & X86_CR4_DE))
5021 || DBGFBpIsHwIoArmed(pVM)))
5022 {
5023 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
5024 VMMRZCallRing3Disable(pVCpu);
5025 HM_DISABLE_PREEMPT();
5026
5027 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
5028 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
5029
5030 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
5031 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
5032 {
5033 /* Raise #DB. */
5034 pVmcb->guest.u64DR6 = pCtx->dr[6];
5035 pVmcb->guest.u64DR7 = pCtx->dr[7];
5036 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
5037 hmR0SvmSetPendingXcptDB(pVCpu);
5038 }
5039 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
5040 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
5041 else if ( rcStrict2 != VINF_SUCCESS
5042 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
5043 rcStrict = rcStrict2;
5044 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
5045
5046 HM_RESTORE_PREEMPT();
5047 VMMRZCallRing3Enable(pVCpu);
5048 }
5049
5050 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
5051 }
5052
5053#ifdef VBOX_STRICT
5054 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
5055 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
5056 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
5057 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
5058 else
5059 {
5060 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
5061 * statuses, that the VMM device and some others may return. See
5062 * IOM_SUCCESS() for guidance. */
5063 AssertMsg( RT_FAILURE(rcStrict)
5064 || rcStrict == VINF_SUCCESS
5065 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
5066 || rcStrict == VINF_EM_DBG_BREAKPOINT
5067 || rcStrict == VINF_EM_RAW_GUEST_TRAP
5068 || rcStrict == VINF_EM_RAW_TO_R3
5069 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
5070 }
5071#endif
5072 return VBOXSTRICTRC_TODO(rcStrict);
5073}
5074
5075
5076/**
5077 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
5078 */
5079HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5080{
5081 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5082 PVM pVM = pVCpu->CTX_SUFF(pVM);
5083 Assert(pVM->hm.s.fNestedPaging);
5084
5085 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5086
5087 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
5088 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5089 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
5090 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
5091
5092 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
5093
5094#ifdef VBOX_HM_WITH_GUEST_PATCHING
5095 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
5096 if ( pVM->hm.s.fTprPatchingAllowed
5097 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80 /* TPR offset. */
5098 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
5099 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
5100 && !CPUMIsGuestInLongModeEx(pCtx)
5101 && !CPUMGetGuestCPL(pVCpu)
5102 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
5103 {
5104 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
5105 GCPhysApicBase &= PAGE_BASE_GC_MASK;
5106
5107 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
5108 {
5109 /* Only attempt to patch the instruction once. */
5110 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
5111 if (!pPatch)
5112 return VINF_EM_HM_PATCH_TPR_INSTR;
5113 }
5114 }
5115#endif
5116
5117 /*
5118 * Determine the nested paging mode.
5119 */
5120 PGMMODE enmNestedPagingMode;
5121#if HC_ARCH_BITS == 32
5122 if (CPUMIsGuestInLongModeEx(pCtx))
5123 enmNestedPagingMode = PGMMODE_AMD64_NX;
5124 else
5125#endif
5126 enmNestedPagingMode = PGMGetHostMode(pVM);
5127
5128 /*
5129 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
5130 */
5131 int rc;
5132 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
5133 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
5134 {
5135 /* If event delivery causes an MMIO #NPF, go back to instruction emulation as
5136 otherwise injecting the original pending event would most likely cause the same MMIO #NPF. */
5137 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
5138 return VERR_EM_INTERPRETER;
5139
5140 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
5141 u32ErrCode);
5142 rc = VBOXSTRICTRC_VAL(rc2);
5143
5144 /*
5145 * If we succeed, resume guest execution.
5146 * If we fail in interpreting the instruction because we couldn't get the guest physical address
5147 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
5148 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
5149 * weird case. See @bugref{6043}.
5150 */
5151 if ( rc == VINF_SUCCESS
5152 || rc == VERR_PAGE_TABLE_NOT_PRESENT
5153 || rc == VERR_PAGE_NOT_PRESENT)
5154 {
5155 /* Successfully handled MMIO operation. */
5156 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
5157 rc = VINF_SUCCESS;
5158 }
5159 return rc;
5160 }
5161
5162 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
5163 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
5164 TRPMResetTrap(pVCpu);
5165
5166 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
5167
5168 /*
5169 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
5170 */
5171 if ( rc == VINF_SUCCESS
5172 || rc == VERR_PAGE_TABLE_NOT_PRESENT
5173 || rc == VERR_PAGE_NOT_PRESENT)
5174 {
5175 /* We've successfully synced our shadow page tables. */
5176 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
5177 rc = VINF_SUCCESS;
5178 }
5179
5180 return rc;
5181}
5182
5183
5184/**
5185 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
5186 * \#VMEXIT.
5187 */
5188HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5189{
5190 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5191
5192 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5193 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one/NMI before reentry. */
5194 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
5195
5196 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive interrupts/NMIs, it is now ready. */
5197 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
5198 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
5199
5200 /* Deliver the pending interrupt/NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
5201 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
5202 return VINF_SUCCESS;
5203}
5204
5205
5206/**
5207 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
5208 * \#VMEXIT.
5209 */
5210HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5211{
5212 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5213
5214 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5215
5216#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
5217 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5218#endif
5219
5220 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
5221 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
5222 {
5223 /*
5224 * AMD-V provides us with the exception which caused the TS; we collect
5225 * the information in the call to hmR0SvmCheckExitDueToEventDelivery.
5226 */
5227 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
5228 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
5229 return VINF_EM_RAW_INJECT_TRPM_EVENT;
5230 }
5231
5232 /** @todo Emulate task switch someday, currently just going back to ring-3 for
5233 * emulation. */
5234 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
5235 return VERR_EM_INTERPRETER;
5236}
5237
5238
5239/**
5240 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
5241 */
5242HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5243{
5244 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5245 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
5246
5247 /* First check if this is a patched VMMCALL for mov TPR */
5248 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
5249 if (rc == VINF_SUCCESS)
5250 {
5251 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
5252 return VINF_SUCCESS;
5253 }
5254
5255 if (rc == VERR_NOT_FOUND)
5256 {
5257 if (pVCpu->hm.s.fHypercallsEnabled)
5258 {
5259 VBOXSTRICTRC rcStrict = GIMHypercall(pVCpu, pCtx);
5260 if (RT_SUCCESS(VBOXSTRICTRC_VAL(rcStrict)))
5261 {
5262 if (rcStrict == VINF_SUCCESS)
5263 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
5264 else
5265 Assert( rcStrict == VINF_GIM_HYPERCALL_CONTINUING
5266 || rcStrict == VINF_GIM_R3_HYPERCALL);
5267
5268 /* If the hypercall changes anything other than guest's general-purpose registers,
5269 we would need to reload the guest changed bits here before VM-entry. */
5270 }
5271 rc = VBOXSTRICTRC_VAL(rcStrict);
5272 }
5273 else
5274 Log4(("hmR0SvmExitVmmCall: Hypercalls not enabled\n"));
5275 }
5276
5277 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
5278 if (RT_FAILURE(rc))
5279 {
5280 hmR0SvmSetPendingXcptUD(pVCpu);
5281 rc = VINF_SUCCESS;
5282 }
5283
5284 return rc;
5285}
5286
5287
5288/**
5289 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
5290 */
5291HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5292{
5293 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5294 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
5295 return VINF_EM_RAW_INTERRUPT;
5296}
5297
5298
5299/**
5300 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
5301 */
5302HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5303{
5304 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5305
5306 /* Clear NMI blocking. */
5307 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5308
5309 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
5310 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5311 hmR0SvmClearIretIntercept(pVmcb);
5312
5313 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
5314 return VINF_SUCCESS;
5315}
5316
5317
5318/**
5319 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E).
5320 * Conditional \#VMEXIT.
5321 */
5322HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5323{
5324 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5325
5326 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5327
5328 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
5329 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5330 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
5331 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
5332 PVM pVM = pVCpu->CTX_SUFF(pVM);
5333
5334#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
5335 if (pVM->hm.s.fNestedPaging)
5336 {
5337 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
5338 if (!pSvmTransient->fVectoringDoublePF)
5339 {
5340 /* A genuine guest #PF, reflect it to the guest. */
5341 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5342 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
5343 uFaultAddress, u32ErrCode));
5344 }
5345 else
5346 {
5347 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
5348 hmR0SvmSetPendingXcptDF(pVCpu);
5349 Log4(("Pending #DF due to vectoring #PF. NP\n"));
5350 }
5351 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
5352 return VINF_SUCCESS;
5353 }
5354#endif
5355
5356 Assert(!pVM->hm.s.fNestedPaging);
5357
5358#ifdef VBOX_HM_WITH_GUEST_PATCHING
5359 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
5360 if ( pVM->hm.s.fTprPatchingAllowed
5361 && (uFaultAddress & 0xfff) == 0x80 /* TPR offset. */
5362 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
5363 && !CPUMIsGuestInLongModeEx(pCtx)
5364 && !CPUMGetGuestCPL(pVCpu)
5365 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
5366 {
5367 RTGCPHYS GCPhysApicBase;
5368 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
5369 GCPhysApicBase &= PAGE_BASE_GC_MASK;
5370
5371 /* Check if the page at the fault-address is the APIC base. */
5372 RTGCPHYS GCPhysPage;
5373 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
5374 if ( rc2 == VINF_SUCCESS
5375 && GCPhysPage == GCPhysApicBase)
5376 {
5377 /* Only attempt to patch the instruction once. */
5378 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
5379 if (!pPatch)
5380 return VINF_EM_HM_PATCH_TPR_INSTR;
5381 }
5382 }
5383#endif
5384
5385 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
5386 pCtx->rip, u32ErrCode, pCtx->cr3));
5387
5388 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
5389 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
5390 if (pSvmTransient->fVectoringPF)
5391 {
5392 Assert(pVCpu->hm.s.Event.fPending);
5393 return VINF_EM_RAW_INJECT_TRPM_EVENT;
5394 }
5395
5396 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
5397 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
5398
5399 Log4(("#PF rc=%Rrc\n", rc));
5400
5401 if (rc == VINF_SUCCESS)
5402 {
5403 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
5404 TRPMResetTrap(pVCpu);
5405 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
5406 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
5407 return rc;
5408 }
5409 else if (rc == VINF_EM_RAW_GUEST_TRAP)
5410 {
5411 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
5412
5413 if (!pSvmTransient->fVectoringDoublePF)
5414 {
5415 /* It's a guest page fault and needs to be reflected to the guest. */
5416 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
5417 TRPMResetTrap(pVCpu);
5418 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5419 }
5420 else
5421 {
5422 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
5423 TRPMResetTrap(pVCpu);
5424 hmR0SvmSetPendingXcptDF(pVCpu);
5425 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
5426 }
5427
5428 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
5429 return VINF_SUCCESS;
5430 }
5431
5432 TRPMResetTrap(pVCpu);
5433 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
5434 return rc;
5435}
5436
5437
5438/**
5439 * \#VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
5440 * Conditional \#VMEXIT.
5441 */
5442HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5443{
5444 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5445
5446 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
5447 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb; NOREF(pVmcb);
5448 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid);
5449
5450 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
5451 VMMRZCallRing3Disable(pVCpu);
5452 HM_DISABLE_PREEMPT();
5453
5454 int rc;
5455 /* If the guest FPU was active at the time of the #NM exit, then it's a guest fault. */
5456 if (pSvmTransient->fWasGuestFPUStateActive)
5457 {
5458 rc = VINF_EM_RAW_GUEST_TRAP;
5459 Assert(CPUMIsGuestFPUStateActive(pVCpu) || HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
5460 }
5461 else
5462 {
5463#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5464 Assert(!pSvmTransient->fWasGuestFPUStateActive);
5465#endif
5466 rc = CPUMR0Trap07Handler(pVCpu->CTX_SUFF(pVM), pVCpu); /* (No need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
5467 Assert( rc == VINF_EM_RAW_GUEST_TRAP
5468 || ((rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED) && CPUMIsGuestFPUStateActive(pVCpu)));
5469 }
5470
5471 HM_RESTORE_PREEMPT();
5472 VMMRZCallRing3Enable(pVCpu);
5473
5474 if (rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED)
5475 {
5476 /* Guest FPU state was activated, we'll want to change CR0 FPU intercepts before the next VM-reentry. */
5477 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
5478 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
5479 pVCpu->hm.s.fPreloadGuestFpu = true;
5480 }
5481 else
5482 {
5483 /* Forward #NM to the guest. */
5484 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
5485 hmR0SvmSetPendingXcptNM(pVCpu);
5486 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
5487 }
5488 return VINF_SUCCESS;
5489}
5490
5491
5492/**
5493 * \#VMEXIT handler for undefined opcode (SVM_EXIT_EXCEPTION_6).
5494 * Conditional \#VMEXIT.
5495 */
5496HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5497{
5498 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5499
5500 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
5501 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb; NOREF(pVmcb);
5502 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid);
5503
5504 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
5505 if (pVCpu->hm.s.fGIMTrapXcptUD)
5506 {
5507 uint8_t cbInstr = 0;
5508 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
5509 if (rcStrict == VINF_SUCCESS)
5510 {
5511 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
5512 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
5513 rc = VINF_SUCCESS;
5514 }
5515 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
5516 rc = VINF_SUCCESS;
5517 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
5518 rc = VINF_GIM_R3_HYPERCALL;
5519 else
5520 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
5521 }
5522
5523 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
5524 if (RT_FAILURE(rc))
5525 {
5526 hmR0SvmSetPendingXcptUD(pVCpu);
5527 rc = VINF_SUCCESS;
5528 }
5529
5530 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
5531 return rc;
5532}
5533
5534
5535/**
5536 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
5537 * Conditional \#VMEXIT.
5538 */
5539HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5540{
5541 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5542
5543 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
5544 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb; NOREF(pVmcb);
5545 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid);
5546
5547 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
5548
5549 if (!(pCtx->cr0 & X86_CR0_NE))
5550 {
5551 PVM pVM = pVCpu->CTX_SUFF(pVM);
5552 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5553 unsigned cbOp;
5554 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
5555 if (RT_SUCCESS(rc))
5556 {
5557 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
5558 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
5559 if (RT_SUCCESS(rc))
5560 pCtx->rip += cbOp;
5561 }
5562 else
5563 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5564 return rc;
5565 }
5566
5567 hmR0SvmSetPendingXcptMF(pVCpu);
5568 return VINF_SUCCESS;
5569}
5570
5571
5572/**
5573 * \#VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
5574 * \#VMEXIT.
5575 */
5576HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5577{
5578 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5579
5580 /* If this #DB is the result of delivering an event, go back to the interpreter. */
5581 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5582 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
5583 {
5584 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
5585 return VERR_EM_INTERPRETER;
5586 }
5587
5588 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
5589
5590 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
5591 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
5592 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5593 PVM pVM = pVCpu->CTX_SUFF(pVM);
5594 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
5595 if (rc == VINF_EM_RAW_GUEST_TRAP)
5596 {
5597 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
5598 if (CPUMIsHyperDebugStateActive(pVCpu))
5599 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
5600
5601 /* Reflect the exception back to the guest. */
5602 hmR0SvmSetPendingXcptDB(pVCpu);
5603 rc = VINF_SUCCESS;
5604 }
5605
5606 /*
5607 * Update DR6.
5608 */
5609 if (CPUMIsHyperDebugStateActive(pVCpu))
5610 {
5611 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
5612 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
5613 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
5614 }
5615 else
5616 {
5617 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
5618 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
5619 }
5620
5621 return rc;
5622}
5623
5624
5625/**
5626 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_EXCEPTION_11).
5627 * Conditional \#VMEXIT.
5628 */
5629HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5630{
5631 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5632
5633 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5634
5635 SVMEVENT Event;
5636 Event.u = 0;
5637 Event.n.u1Valid = 1;
5638 Event.n.u3Type = SVM_EVENT_EXCEPTION;
5639 Event.n.u8Vector = X86_XCPT_AC;
5640 Event.n.u1ErrorCodeValid = 1;
5641 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
5642 return VINF_SUCCESS;
5643}
5644
5645/** @} */
5646
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