VirtualBox

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

Last change on this file since 51661 was 51660, checked in by vboxsync, 11 years ago

VMM/HMSVMR0: RT_BOOL.

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

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