VirtualBox

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

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

VMM: renamed HM_[DISABLE|RESTORE]_PREEMPT_IF_NEEDED() macro.

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

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