VirtualBox

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

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

VMM: GIM raw-mode support.

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

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