VirtualBox

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

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

VMM/HMSVMR0: nit.

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