VirtualBox

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

Last change on this file since 48448 was 48370, checked in by vboxsync, 11 years ago

EM,HM: MWait fix, clearing the active bit too early.

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

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