VirtualBox

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

Last change on this file since 55048 was 55040, checked in by vboxsync, 9 years ago

VMM/HMSVMR0: Fix #UD hypercall handling for GIM KVM.

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