VirtualBox

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

Last change on this file since 65912 was 65912, checked in by vboxsync, 8 years ago

VMM: Nested Hw.virt: unused function fix.

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