VirtualBox

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

Last change on this file since 52023 was 52009, checked in by vboxsync, 10 years ago

Comments and nits.

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

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