VirtualBox

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

Last change on this file since 48455 was 48449, checked in by vboxsync, 11 years ago

VMM/HMSVMR0: Leave AMD-V properly on invalid-guest state gurus.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 183.1 KB
Line 
1/* $Id: HMSVMR0.cpp 48449 2013-09-12 13:07:28Z 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 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
2076 VMMRZCallRing3Disable(pVCpu);
2077 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
2078
2079 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
2080 if (pVCpu->hm.s.Event.fPending)
2081 {
2082 hmR0SvmPendingEventToTrpmTrap(pVCpu);
2083 Assert(!pVCpu->hm.s.Event.fPending);
2084 }
2085
2086 /* Sync. the necessary state for going back to ring-3. */
2087 hmR0SvmLeaveSession(pVM, pVCpu, pCtx);
2088 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2089
2090 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2091 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
2092 | CPUM_CHANGED_LDTR
2093 | CPUM_CHANGED_GDTR
2094 | CPUM_CHANGED_IDTR
2095 | CPUM_CHANGED_TR
2096 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2097 if ( pVM->hm.s.fNestedPaging
2098 && CPUMIsGuestPagingEnabledEx(pCtx))
2099 {
2100 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2101 }
2102
2103 /* Make sure we've undo the trap flag if we tried to single step something. */
2104 if (pVCpu->hm.s.fClearTrapFlag)
2105 {
2106 pCtx->eflags.Bits.u1TF = 0;
2107 pVCpu->hm.s.fClearTrapFlag = false;
2108 }
2109
2110 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
2111 if (rcExit != VINF_EM_RAW_INTERRUPT)
2112 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_ALL_GUEST;
2113
2114 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
2115
2116 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
2117 VMMRZCallRing3RemoveNotification(pVCpu);
2118 VMMRZCallRing3Enable(pVCpu);
2119}
2120
2121
2122/**
2123 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
2124 * intercepts.
2125 *
2126 * @param pVCpu Pointer to the VMCPU.
2127 *
2128 * @remarks No-long-jump zone!!!
2129 */
2130static void hmR0SvmUpdateTscOffsetting(PVMCPU pVCpu)
2131{
2132 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2133 if (TMCpuTickCanUseRealTSC(pVCpu, &pVmcb->ctrl.u64TSCOffset))
2134 {
2135 uint64_t u64CurTSC = ASMReadTSC();
2136 if (u64CurTSC + pVmcb->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
2137 {
2138 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
2139 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
2140 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
2141 }
2142 else
2143 {
2144 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
2145 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
2146 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
2147 }
2148 }
2149 else
2150 {
2151 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
2152 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
2153 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
2154 }
2155
2156 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2157}
2158
2159
2160/**
2161 * Sets an event as a pending event to be injected into the guest.
2162 *
2163 * @param pVCpu Pointer to the VMCPU.
2164 * @param pEvent Pointer to the SVM event.
2165 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
2166 * page-fault.
2167 *
2168 * @remarks Statistics counter assumes this is a guest event being reflected to
2169 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
2170 */
2171DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
2172{
2173 Assert(!pVCpu->hm.s.Event.fPending);
2174 Assert(pEvent->n.u1Valid);
2175
2176 pVCpu->hm.s.Event.u64IntrInfo = pEvent->u;
2177 pVCpu->hm.s.Event.fPending = true;
2178 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
2179
2180 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2181 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2182
2183 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
2184}
2185
2186
2187/**
2188 * Injects an event into the guest upon VMRUN by updating the relevant field
2189 * in the VMCB.
2190 *
2191 * @param pVCpu Pointer to the VMCPU.
2192 * @param pVmcb Pointer to the guest VMCB.
2193 * @param pCtx Pointer to the guest-CPU context.
2194 * @param pEvent Pointer to the event.
2195 *
2196 * @remarks No-long-jump zone!!!
2197 * @remarks Requires CR0!
2198 */
2199DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
2200{
2201 pVmcb->ctrl.EventInject.u = pEvent->u;
2202 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
2203
2204 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2205 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2206}
2207
2208
2209
2210/**
2211 * Converts any TRPM trap into a pending HM event. This is typically used when
2212 * entering from ring-3 (not longjmp returns).
2213 *
2214 * @param pVCpu Pointer to the VMCPU.
2215 */
2216static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
2217{
2218 Assert(TRPMHasTrap(pVCpu));
2219 Assert(!pVCpu->hm.s.Event.fPending);
2220
2221 uint8_t uVector;
2222 TRPMEVENT enmTrpmEvent;
2223 RTGCUINT uErrCode;
2224 RTGCUINTPTR GCPtrFaultAddress;
2225 uint8_t cbInstr;
2226
2227 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
2228 AssertRC(rc);
2229
2230 SVMEVENT Event;
2231 Event.u = 0;
2232 Event.n.u1Valid = 1;
2233 Event.n.u8Vector = uVector;
2234
2235 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
2236 if (enmTrpmEvent == TRPM_TRAP)
2237 {
2238 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2239 switch (uVector)
2240 {
2241 case X86_XCPT_PF:
2242 case X86_XCPT_DF:
2243 case X86_XCPT_TS:
2244 case X86_XCPT_NP:
2245 case X86_XCPT_SS:
2246 case X86_XCPT_GP:
2247 case X86_XCPT_AC:
2248 {
2249 Event.n.u1ErrorCodeValid = 1;
2250 Event.n.u32ErrorCode = uErrCode;
2251 break;
2252 }
2253 }
2254 }
2255 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
2256 {
2257 if (uVector == X86_XCPT_NMI)
2258 Event.n.u3Type = SVM_EVENT_NMI;
2259 else
2260 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2261 }
2262 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
2263 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
2264 else
2265 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
2266
2267 rc = TRPMResetTrap(pVCpu);
2268 AssertRC(rc);
2269
2270 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
2271 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
2272
2273 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
2274 STAM_COUNTER_DEC(&pVCpu->hm.s.StatInjectPendingReflect);
2275}
2276
2277
2278/**
2279 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
2280 * AMD-V to execute any instruction.
2281 *
2282 * @param pvCpu Pointer to the VMCPU.
2283 */
2284static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
2285{
2286 Assert(pVCpu->hm.s.Event.fPending);
2287 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
2288
2289 SVMEVENT Event;
2290 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2291
2292 uint8_t uVector = Event.n.u8Vector;
2293 uint8_t uVectorType = Event.n.u3Type;
2294
2295 TRPMEVENT enmTrapType;
2296 switch (uVectorType)
2297 {
2298 case SVM_EVENT_EXTERNAL_IRQ:
2299 case SVM_EVENT_NMI:
2300 enmTrapType = TRPM_HARDWARE_INT;
2301 break;
2302 case SVM_EVENT_SOFTWARE_INT:
2303 enmTrapType = TRPM_SOFTWARE_INT;
2304 break;
2305 case SVM_EVENT_EXCEPTION:
2306 enmTrapType = TRPM_TRAP;
2307 break;
2308 default:
2309 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
2310 enmTrapType = TRPM_32BIT_HACK;
2311 break;
2312 }
2313
2314 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
2315
2316 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
2317 AssertRC(rc);
2318
2319 if (Event.n.u1ErrorCodeValid)
2320 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
2321
2322 if ( uVectorType == SVM_EVENT_EXCEPTION
2323 && uVector == X86_XCPT_PF)
2324 {
2325 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
2326 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
2327 }
2328 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
2329 {
2330 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
2331 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
2332 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
2333 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
2334 }
2335 pVCpu->hm.s.Event.fPending = false;
2336}
2337
2338
2339/**
2340 * Gets the guest's interrupt-shadow.
2341 *
2342 * @returns The guest's interrupt-shadow.
2343 * @param pVCpu Pointer to the VMCPU.
2344 * @param pCtx Pointer to the guest-CPU context.
2345 *
2346 * @remarks No-long-jump zone!!!
2347 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
2348 */
2349DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
2350{
2351 /*
2352 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
2353 * inhibit interrupts or clear any existing interrupt-inhibition.
2354 */
2355 uint32_t uIntrState = 0;
2356 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2357 {
2358 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2359 {
2360 /*
2361 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
2362 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
2363 */
2364 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2365 }
2366 else
2367 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
2368 }
2369 return uIntrState;
2370}
2371
2372
2373/**
2374 * Sets the virtual interrupt intercept control in the VMCB which
2375 * instructs AMD-V to cause a #VMEXIT as soon as the guest is in a state to
2376 * receive interrupts.
2377 *
2378 * @param pVmcb Pointer to the VMCB.
2379 */
2380DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
2381{
2382 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
2383 {
2384 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
2385 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
2386 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
2387 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
2388
2389 Log4(("Setting VINTR intercept\n"));
2390 }
2391}
2392
2393
2394/**
2395 * Evaluates the event to be delivered to the guest and sets it as the pending
2396 * event.
2397 *
2398 * @param pVCpu Pointer to the VMCPU.
2399 * @param pCtx Pointer to the guest-CPU context.
2400 */
2401static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2402{
2403 Assert(!pVCpu->hm.s.Event.fPending);
2404 Log4Func(("\n"));
2405
2406 const bool fIntShadow = !!hmR0SvmGetGuestIntrShadow(pVCpu, pCtx);
2407 const bool fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2408 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2409
2410 SVMEVENT Event;
2411 Event.u = 0;
2412 /** @todo SMI. SMIs take priority over NMIs. */
2413 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2414 {
2415 if (!fIntShadow)
2416 {
2417 Log4(("Pending NMI\n"));
2418
2419 Event.n.u1Valid = 1;
2420 Event.n.u8Vector = X86_XCPT_NMI;
2421 Event.n.u3Type = SVM_EVENT_NMI;
2422
2423 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2424 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2425 }
2426 else
2427 hmR0SvmSetVirtIntrIntercept(pVmcb);
2428 }
2429 else if (VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)))
2430 {
2431 /*
2432 * Check if the guest can receive external interrupts (PIC/APIC). Once we do PDMGetInterrupt() we -must- deliver
2433 * the interrupt ASAP. We must not execute any guest code until we inject the interrupt which is why it is
2434 * evaluated here and not set as pending, solely based on the force-flags.
2435 */
2436 if ( !fBlockInt
2437 && !fIntShadow)
2438 {
2439 uint8_t u8Interrupt;
2440 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2441 if (RT_SUCCESS(rc))
2442 {
2443 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2444
2445 Event.n.u1Valid = 1;
2446 Event.n.u8Vector = u8Interrupt;
2447 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2448
2449 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2450 }
2451 else
2452 {
2453 /** @todo Does this actually happen? If not turn it into an assertion. */
2454 Assert(!VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
2455 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2456 }
2457 }
2458 else
2459 hmR0SvmSetVirtIntrIntercept(pVmcb);
2460 }
2461}
2462
2463
2464/**
2465 * Injects any pending events into the guest if the guest is in a state to
2466 * receive them.
2467 *
2468 * @param pVCpu Pointer to the VMCPU.
2469 * @param pCtx Pointer to the guest-CPU context.
2470 */
2471static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2472{
2473 Assert(!TRPMHasTrap(pVCpu));
2474 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2475 Log4Func(("\n"));
2476
2477 const bool fIntShadow = !!hmR0SvmGetGuestIntrShadow(pVCpu, pCtx);
2478 const bool fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2479 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2480
2481 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2482 {
2483 SVMEVENT Event;
2484 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2485 Assert(Event.n.u1Valid);
2486#ifdef VBOX_STRICT
2487 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2488 {
2489 Assert(!fBlockInt);
2490 Assert(!fIntShadow);
2491 }
2492 else if (Event.n.u3Type == SVM_EVENT_NMI)
2493 Assert(!fIntShadow);
2494#endif
2495
2496 Log4(("Injecting pending HM event.\n"));
2497 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2498 pVCpu->hm.s.Event.fPending = false;
2499
2500#ifdef VBOX_WITH_STATISTICS
2501 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2502 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2503 else
2504 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2505#endif
2506 }
2507
2508 /* Update the guest interrupt shadow in the VMCB. */
2509 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2510}
2511
2512
2513/**
2514 * Reports world-switch error and dumps some useful debug info.
2515 *
2516 * @param pVM Pointer to the VM.
2517 * @param pVCpu Pointer to the VMCPU.
2518 * @param rcVMRun The return code from VMRUN (or
2519 * VERR_SVM_INVALID_GUEST_STATE for invalid
2520 * guest-state).
2521 * @param pCtx Pointer to the guest-CPU context.
2522 */
2523static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2524{
2525 HMSVM_ASSERT_PREEMPT_SAFE();
2526 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2527
2528 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2529 {
2530 HMDumpRegs(pVM, pVCpu, pCtx);
2531#ifdef VBOX_STRICT
2532 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2533 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2534 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2535 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2536 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2537 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2538 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2539 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2540 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2541 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2542 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2543
2544 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2545 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2546 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2547
2548 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2549 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2550 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2551 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2552 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2553 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2554 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2555 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2556 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2557 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2558
2559 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2560 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2561 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2562 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2563 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2564 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2565 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2566 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2567 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2568 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2569 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2570 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2571 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2572 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2573 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2574 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2575 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2576
2577 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2578 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2579
2580 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2581 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2582 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2583 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2584 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2585 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2586 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2587 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2588 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2589 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2590 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2591 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2592 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2593 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2594 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2595 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2596 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2597 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2598 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2599 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2600
2601 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2602 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2603
2604 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2605 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2606 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2607 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2608
2609 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2610 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2611
2612 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2613 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2614 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2615 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2616
2617 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2618 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2619 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2620 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2621 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2622 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2623 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2624
2625 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2626 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2627 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2628 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2629
2630 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2631 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2632 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2633
2634 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2635 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2636 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2637 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2638 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2639 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2640 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2641 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2642 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2643 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2644 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2645 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2646#endif
2647 }
2648 else
2649 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2650}
2651
2652
2653/**
2654 * Check per-VM and per-VCPU force flag actions that require us to go back to
2655 * ring-3 for one reason or another.
2656 *
2657 * @returns VBox status code (information status code included).
2658 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2659 * ring-3.
2660 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2661 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2662 * interrupts)
2663 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2664 * all EMTs to be in ring-3.
2665 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2666 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2667 * to the EM loop.
2668 *
2669 * @param pVM Pointer to the VM.
2670 * @param pVCpu Pointer to the VMCPU.
2671 * @param pCtx Pointer to the guest-CPU context.
2672 */
2673static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2674{
2675 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2676
2677 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
2678 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2679 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
2680
2681 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
2682 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2683 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
2684 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2685 {
2686 /* Pending PGM C3 sync. */
2687 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2688 {
2689 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2690 if (rc != VINF_SUCCESS)
2691 {
2692 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2693 return rc;
2694 }
2695 }
2696
2697 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2698 /* -XXX- what was that about single stepping? */
2699 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2700 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2701 {
2702 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2703 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2704 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2705 return rc;
2706 }
2707
2708 /* Pending VM request packets, such as hardware interrupts. */
2709 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2710 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2711 {
2712 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2713 return VINF_EM_PENDING_REQUEST;
2714 }
2715
2716 /* Pending PGM pool flushes. */
2717 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2718 {
2719 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2720 return VINF_PGM_POOL_FLUSH_PENDING;
2721 }
2722
2723 /* Pending DMA requests. */
2724 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2725 {
2726 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2727 return VINF_EM_RAW_TO_R3;
2728 }
2729 }
2730
2731 return VINF_SUCCESS;
2732}
2733
2734
2735/**
2736 * Does the preparations before executing guest code in AMD-V.
2737 *
2738 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2739 * recompiler. We must be cautious what we do here regarding committing
2740 * guest-state information into the the VMCB assuming we assuredly execute the
2741 * guest in AMD-V. If we fall back to the recompiler after updating the VMCB and
2742 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2743 * that the recompiler can (and should) use them when it resumes guest
2744 * execution. Otherwise such operations must be done when we can no longer
2745 * exit to ring-3.
2746 *
2747 * @returns VBox status code (informational status codes included).
2748 * @retval VINF_SUCCESS if we can proceed with running the guest.
2749 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2750 *
2751 * @param pVM Pointer to the VM.
2752 * @param pVCpu Pointer to the VMCPU.
2753 * @param pCtx Pointer to the guest-CPU context.
2754 * @param pSvmTransient Pointer to the SVM transient structure.
2755 */
2756static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2757{
2758 HMSVM_ASSERT_PREEMPT_SAFE();
2759
2760 /* Check force flag actions that might require us to go back to ring-3. */
2761 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2762 if (rc != VINF_SUCCESS)
2763 return rc;
2764
2765 if (TRPMHasTrap(pVCpu))
2766 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2767 else if (!pVCpu->hm.s.Event.fPending)
2768 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
2769
2770 /*
2771 * Re-enable nested paging (automatically disabled on every VM-exit). See AMD spec. 15.25.3 "Enabling Nested Paging".
2772 * We avoid changing the corresponding VMCB Clean Bit as we're not changing it to a different value since the previous run.
2773 */
2774 /** @todo The above assumption could be wrong. It's not documented what
2775 * should be done wrt to the VMCB Clean Bit, but we'll find out the
2776 * hard way. */
2777 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2778 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
2779
2780#ifdef HMSVM_SYNC_FULL_GUEST_STATE
2781 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_ALL_GUEST;
2782#endif
2783
2784 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
2785 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
2786 AssertRCReturn(rc, rc);
2787 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
2788
2789 /*
2790 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
2791 * so we can update it on the way back if the guest changed the TPR.
2792 */
2793 if (pVCpu->hm.s.svm.fSyncVTpr)
2794 {
2795 if (pVM->hm.s.fTPRPatchingActive)
2796 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
2797 else
2798 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
2799 }
2800
2801 /*
2802 * No longjmps to ring-3 from this point on!!!
2803 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
2804 * This also disables flushing of the R0-logger instance (if any).
2805 */
2806 VMMRZCallRing3Disable(pVCpu);
2807
2808 /*
2809 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
2810 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
2811 *
2812 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
2813 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
2814 *
2815 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
2816 * executing guest code.
2817 */
2818 pSvmTransient->uEflags = ASMIntDisableFlags();
2819 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
2820 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2821 {
2822 ASMSetFlags(pSvmTransient->uEflags);
2823 VMMRZCallRing3Enable(pVCpu);
2824 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2825 return VINF_EM_RAW_TO_R3;
2826 }
2827 else if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2828 {
2829 ASMSetFlags(pSvmTransient->uEflags);
2830 VMMRZCallRing3Enable(pVCpu);
2831 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2832 return VINF_EM_RAW_INTERRUPT;
2833 }
2834
2835 return VINF_SUCCESS;
2836}
2837
2838
2839/**
2840 * Prepares to run guest code in AMD-V and we've committed to doing so. This
2841 * means there is no backing out to ring-3 or anywhere else at this
2842 * point.
2843 *
2844 * @param pVM Pointer to the VM.
2845 * @param pVCpu Pointer to the VMCPU.
2846 * @param pCtx Pointer to the guest-CPU context.
2847 * @param pSvmTransient Pointer to the SVM transient structure.
2848 *
2849 * @remarks Called with preemption disabled.
2850 * @remarks No-long-jump zone!!!
2851 */
2852static void hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2853{
2854 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2855 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2856 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2857
2858 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2859 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
2860
2861 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
2862
2863 /* Load the state shared between host and guest (FPU, debug). */
2864 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2865 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_HOST_GUEST_SHARED_STATE)
2866 hmR0VmxLoadSharedState(pVCpu, pVmcb, pCtx);
2867 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_HOST_CONTEXT; /* Preemption might set this, nothing to do on AMD-V. */
2868 AssertMsg(!pVCpu->hm.s.fContextUseFlags, ("fContextUseFlags=%#x\n", pVCpu->hm.s.fContextUseFlags));
2869
2870 /* If VMCB Clean Bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
2871 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
2872 pVmcb->ctrl.u64VmcbCleanBits = 0;
2873
2874 /* Setup TSC offsetting. */
2875 if ( pSvmTransient->fUpdateTscOffsetting
2876 || HMR0GetCurrentCpu()->idCpu != pVCpu->hm.s.idLastCpu)
2877 {
2878 hmR0SvmUpdateTscOffsetting(pVCpu);
2879 pSvmTransient->fUpdateTscOffsetting = false;
2880 }
2881
2882 /* Flush the appropriate tagged-TLB entries. */
2883 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB-shootdowns, set this across the world switch. */
2884 hmR0SvmFlushTaggedTlb(pVCpu);
2885 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
2886
2887 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
2888
2889 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
2890 to start executing. */
2891
2892 /*
2893 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
2894 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
2895 *
2896 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
2897 */
2898 pSvmTransient->fRestoreTscAuxMsr = false;
2899 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2900 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
2901 {
2902 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
2903 uint64_t u64GuestTscAux = 0;
2904 int rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
2905 AssertRC(rc2);
2906 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
2907 {
2908 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
2909 pSvmTransient->fRestoreTscAuxMsr = true;
2910 }
2911 }
2912}
2913
2914
2915/**
2916 * Wrapper for running the guest code in AMD-V.
2917 *
2918 * @returns VBox strict status code.
2919 * @param pVM Pointer to the VM.
2920 * @param pVCpu Pointer to the VMCPU.
2921 * @param pCtx Pointer to the guest-CPU context.
2922 *
2923 * @remarks No-long-jump zone!!!
2924 */
2925DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2926{
2927 /*
2928 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
2929 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
2930 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
2931 */
2932#ifdef VBOX_WITH_KERNEL_USING_XMM
2933 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
2934 pVCpu->hm.s.svm.pfnVMRun);
2935#else
2936 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
2937#endif
2938}
2939
2940
2941/**
2942 * Performs some essential restoration of state after running guest code in
2943 * AMD-V.
2944 *
2945 * @param pVM Pointer to the VM.
2946 * @param pVCpu Pointer to the VMCPU.
2947 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
2948 * out-of-sync. Make sure to update the required fields
2949 * before using them.
2950 * @param pSvmTransient Pointer to the SVM transient structure.
2951 * @param rcVMRun Return code of VMRUN.
2952 *
2953 * @remarks Called with interrupts disabled.
2954 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
2955 * unconditionally when it is safe to do so.
2956 */
2957static void hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
2958{
2959 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2960
2961 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB-shootdowns. */
2962 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for TLB-shootdowns. */
2963
2964 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2965 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
2966
2967 if (pSvmTransient->fRestoreTscAuxMsr)
2968 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
2969
2970 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
2971 {
2972 /** @todo Find a way to fix hardcoding a guestimate. */
2973 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset - 0x400);
2974 }
2975
2976 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
2977 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
2978 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2979
2980 Assert(!(ASMGetFlags() & X86_EFL_IF));
2981 ASMSetFlags(pSvmTransient->uEflags); /* Enable interrupts. */
2982 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
2983
2984 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
2985 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
2986 {
2987 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
2988 return;
2989 }
2990
2991 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
2992 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
2993 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
2994
2995 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
2996 {
2997 if (pVCpu->hm.s.svm.fSyncVTpr)
2998 {
2999 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
3000 if ( pVM->hm.s.fTPRPatchingActive
3001 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
3002 {
3003 int rc = PDMApicSetTPR(pVCpu, pMixedCtx->msrLSTAR & 0xff);
3004 AssertRC(rc);
3005 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3006 }
3007 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
3008 {
3009 int rc = PDMApicSetTPR(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
3010 AssertRC(rc);
3011 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3012 }
3013 }
3014 }
3015}
3016
3017
3018/**
3019 * Runs the guest code using AMD-V.
3020 *
3021 * @returns VBox status code.
3022 * @param pVM Pointer to the VM.
3023 * @param pVCpu Pointer to the VMCPU.
3024 * @param pCtx Pointer to the guest-CPU context.
3025 */
3026VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3027{
3028 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3029 HMSVM_ASSERT_PREEMPT_SAFE();
3030 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
3031
3032 SVMTRANSIENT SvmTransient;
3033 SvmTransient.fUpdateTscOffsetting = true;
3034 uint32_t cLoops = 0;
3035 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3036 int rc = VERR_INTERNAL_ERROR_5;
3037
3038 for (;; cLoops++)
3039 {
3040 Assert(!HMR0SuspendPending());
3041 HMSVM_ASSERT_CPU_SAFE();
3042
3043 /* Preparatory work for running guest code, this may force us to return
3044 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3045 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3046 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3047 if (rc != VINF_SUCCESS)
3048 break;
3049
3050 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3051 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3052
3053 /* Restore any residual host-state and save any bits shared between host
3054 and guest into the guest-CPU state. Re-enables interrupts! */
3055 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3056
3057 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3058 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3059 {
3060 if (rc == VINF_SUCCESS)
3061 rc = VERR_SVM_INVALID_GUEST_STATE;
3062 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3063 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3064 break;
3065 }
3066
3067 /* Handle the #VMEXIT. */
3068 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3069 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3070 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3071 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3072 if (rc != VINF_SUCCESS)
3073 break;
3074 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
3075 {
3076 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
3077 rc = VINF_EM_RAW_INTERRUPT;
3078 break;
3079 }
3080 }
3081
3082 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3083 if (rc == VERR_EM_INTERPRETER)
3084 rc = VINF_EM_RAW_EMULATE_INSTR;
3085 else if (rc == VINF_EM_RESET)
3086 rc = VINF_EM_TRIPLE_FAULT;
3087
3088 /* Prepare to return to ring-3. This will remove longjmp notifications. */
3089 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
3090 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
3091 return rc;
3092}
3093
3094
3095/**
3096 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
3097 *
3098 * @returns VBox status code (informational status codes included).
3099 * @param pVCpu Pointer to the VMCPU.
3100 * @param pCtx Pointer to the guest-CPU context.
3101 * @param pSvmTransient Pointer to the SVM transient structure.
3102 */
3103DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3104{
3105 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
3106 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
3107
3108 /*
3109 * The ordering of the case labels is based on most-frequently-occurring VM-exits for most guests under
3110 * normal workloads (for some definition of "normal").
3111 */
3112 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
3113 switch (pSvmTransient->u64ExitCode)
3114 {
3115 case SVM_EXIT_NPF:
3116 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
3117
3118 case SVM_EXIT_IOIO:
3119 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
3120
3121 case SVM_EXIT_RDTSC:
3122 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
3123
3124 case SVM_EXIT_RDTSCP:
3125 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
3126
3127 case SVM_EXIT_CPUID:
3128 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
3129
3130 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
3131 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
3132
3133 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
3134 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
3135
3136 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
3137 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
3138
3139 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
3140 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
3141
3142 case SVM_EXIT_MONITOR:
3143 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
3144
3145 case SVM_EXIT_MWAIT:
3146 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
3147
3148 case SVM_EXIT_HLT:
3149 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
3150
3151 case SVM_EXIT_READ_CR0:
3152 case SVM_EXIT_READ_CR3:
3153 case SVM_EXIT_READ_CR4:
3154 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
3155
3156 case SVM_EXIT_WRITE_CR0:
3157 case SVM_EXIT_WRITE_CR3:
3158 case SVM_EXIT_WRITE_CR4:
3159 case SVM_EXIT_WRITE_CR8:
3160 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
3161
3162 case SVM_EXIT_VINTR:
3163 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
3164
3165 case SVM_EXIT_INTR:
3166 case SVM_EXIT_FERR_FREEZE:
3167 case SVM_EXIT_NMI:
3168 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
3169
3170 case SVM_EXIT_MSR:
3171 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
3172
3173 case SVM_EXIT_INVLPG:
3174 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
3175
3176 case SVM_EXIT_WBINVD:
3177 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
3178
3179 case SVM_EXIT_INVD:
3180 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
3181
3182 case SVM_EXIT_RDPMC:
3183 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
3184
3185 default:
3186 {
3187 switch (pSvmTransient->u64ExitCode)
3188 {
3189 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
3190 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
3191 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
3192 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
3193 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3194
3195 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
3196 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
3197 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3198 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3199 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3200
3201 case SVM_EXIT_TASK_SWITCH:
3202 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3203
3204 case SVM_EXIT_VMMCALL:
3205 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3206
3207 case SVM_EXIT_SHUTDOWN:
3208 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3209
3210 case SVM_EXIT_SMI:
3211 case SVM_EXIT_INIT:
3212 {
3213 /*
3214 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3215 * we want to know about it so log the exit code and bail.
3216 */
3217 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3218 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3219 return VERR_SVM_UNEXPECTED_EXIT;
3220 }
3221
3222 case SVM_EXIT_INVLPGA:
3223 case SVM_EXIT_RSM:
3224 case SVM_EXIT_VMRUN:
3225 case SVM_EXIT_VMLOAD:
3226 case SVM_EXIT_VMSAVE:
3227 case SVM_EXIT_STGI:
3228 case SVM_EXIT_CLGI:
3229 case SVM_EXIT_SKINIT:
3230 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3231
3232#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3233 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3234 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3235 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3236 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3237 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3238 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3239 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3240 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3241 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3242 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3243 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3244 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3245 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3246 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3247 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3248 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3249 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3250 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3251 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3252 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3253 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3254 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3255 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3256 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3257 {
3258 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3259 SVMEVENT Event;
3260 Event.u = 0;
3261 Event.n.u1Valid = 1;
3262 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3263 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3264
3265 switch (Event.n.u8Vector)
3266 {
3267 case X86_XCPT_DE:
3268 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3269 break;
3270
3271 case X86_XCPT_BP:
3272 /** Saves the wrong EIP on the stack (pointing to the int3) instead of the
3273 * next instruction. */
3274 /** @todo Investigate this later. */
3275 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
3276 break;
3277
3278 case X86_XCPT_UD:
3279 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
3280 break;
3281
3282 case X86_XCPT_NP:
3283 Event.n.u1ErrorCodeValid = 1;
3284 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3285 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3286 break;
3287
3288 case X86_XCPT_SS:
3289 Event.n.u1ErrorCodeValid = 1;
3290 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3291 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3292 break;
3293
3294 case X86_XCPT_GP:
3295 Event.n.u1ErrorCodeValid = 1;
3296 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3297 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3298 break;
3299
3300 default:
3301 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3302 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3303 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3304 }
3305
3306 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3307 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3308 return VINF_SUCCESS;
3309 }
3310#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3311
3312 default:
3313 {
3314 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3315 pVCpu->hm.s.u32HMError = u32ExitCode;
3316 return VERR_SVM_UNKNOWN_EXIT;
3317 }
3318 }
3319 }
3320 }
3321 return VERR_INTERNAL_ERROR_5; /* Should never happen. */
3322}
3323
3324
3325#ifdef DEBUG
3326/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3327# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3328 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3329
3330# define HMSVM_ASSERT_PREEMPT_CPUID() \
3331 do \
3332 { \
3333 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3334 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3335 } while (0)
3336
3337# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3338 do { \
3339 AssertPtr(pVCpu); \
3340 AssertPtr(pCtx); \
3341 AssertPtr(pSvmTransient); \
3342 Assert(ASMIntAreEnabled()); \
3343 HMSVM_ASSERT_PREEMPT_SAFE(); \
3344 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3345 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)); \
3346 HMSVM_ASSERT_PREEMPT_SAFE(); \
3347 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3348 HMSVM_ASSERT_PREEMPT_CPUID(); \
3349 } while (0)
3350#else /* Release builds */
3351# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { } while(0)
3352#endif
3353
3354
3355/**
3356 * Worker for hmR0SvmInterpretInvlpg().
3357 *
3358 * @return VBox status code.
3359 * @param pVCpu Pointer to the VMCPU.
3360 * @param pCpu Pointer to the disassembler state.
3361 * @param pRegFrame Pointer to the register frame.
3362 */
3363static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
3364{
3365 DISQPVPARAMVAL Param1;
3366 RTGCPTR GCPtrPage;
3367
3368 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3369 if (RT_FAILURE(rc))
3370 return VERR_EM_INTERPRETER;
3371
3372 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3373 || Param1.type == DISQPV_TYPE_ADDRESS)
3374 {
3375 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3376 return VERR_EM_INTERPRETER;
3377
3378 GCPtrPage = Param1.val.val64;
3379 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, pRegFrame, GCPtrPage);
3380 rc = VBOXSTRICTRC_VAL(rc2);
3381 }
3382 else
3383 {
3384 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3385 rc = VERR_EM_INTERPRETER;
3386 }
3387
3388 return rc;
3389}
3390
3391
3392/**
3393 * Interprets INVLPG.
3394 *
3395 * @returns VBox status code.
3396 * @retval VINF_* Scheduling instructions.
3397 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3398 * @retval VERR_* Fatal errors.
3399 *
3400 * @param pVM Pointer to the VM.
3401 * @param pRegFrame Pointer to the register frame.
3402 *
3403 * @remarks Updates the RIP if the instruction was executed successfully.
3404 */
3405static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
3406{
3407 /* Only allow 32 & 64 bit code. */
3408 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3409 {
3410 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3411 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3412 if ( RT_SUCCESS(rc)
3413 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3414 {
3415 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
3416 if (RT_SUCCESS(rc))
3417 pRegFrame->rip += pDis->cbInstr;
3418 return rc;
3419 }
3420 else
3421 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3422 }
3423 return VERR_EM_INTERPRETER;
3424}
3425
3426
3427/**
3428 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
3429 *
3430 * @param pVCpu Pointer to the VMCPU.
3431 */
3432DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3433{
3434 SVMEVENT Event;
3435 Event.u = 0;
3436 Event.n.u1Valid = 1;
3437 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3438 Event.n.u8Vector = X86_XCPT_UD;
3439 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3440}
3441
3442
3443/**
3444 * Sets a debug (#DB) exception as pending-for-injection into the VM.
3445 *
3446 * @param pVCpu Pointer to the VMCPU.
3447 */
3448DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3449{
3450 SVMEVENT Event;
3451 Event.u = 0;
3452 Event.n.u1Valid = 1;
3453 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3454 Event.n.u8Vector = X86_XCPT_DB;
3455 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3456}
3457
3458
3459/**
3460 * Sets a page fault (#PF) exception as pending-for-injection into the VM.
3461 *
3462 * @param pVCpu Pointer to the VMCPU.
3463 * @param pCtx Pointer to the guest-CPU context.
3464 * @param u32ErrCode The error-code for the page-fault.
3465 * @param uFaultAddress The page fault address (CR2).
3466 *
3467 * @remarks This updates the guest CR2 with @a uFaultAddress!
3468 */
3469DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3470{
3471 SVMEVENT Event;
3472 Event.u = 0;
3473 Event.n.u1Valid = 1;
3474 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3475 Event.n.u8Vector = X86_XCPT_PF;
3476 Event.n.u1ErrorCodeValid = 1;
3477 Event.n.u32ErrorCode = u32ErrCode;
3478
3479 /* Update CR2 of the guest. */
3480 if (pCtx->cr2 != uFaultAddress)
3481 {
3482 pCtx->cr2 = uFaultAddress;
3483 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR2;
3484 }
3485
3486 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3487}
3488
3489
3490/**
3491 * Sets a device-not-available (#NM) exception as pending-for-injection into the
3492 * VM.
3493 *
3494 * @param pVCpu Pointer to the VMCPU.
3495 */
3496DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3497{
3498 SVMEVENT Event;
3499 Event.u = 0;
3500 Event.n.u1Valid = 1;
3501 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3502 Event.n.u8Vector = X86_XCPT_NM;
3503 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3504}
3505
3506
3507/**
3508 * Sets a math-fault (#MF) exception as pending-for-injection into the VM.
3509 *
3510 * @param pVCpu Pointer to the VMCPU.
3511 */
3512DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3513{
3514 SVMEVENT Event;
3515 Event.u = 0;
3516 Event.n.u1Valid = 1;
3517 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3518 Event.n.u8Vector = X86_XCPT_MF;
3519 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3520}
3521
3522
3523/**
3524 * Sets a double fault (#DF) exception as pending-for-injection into the VM.
3525 *
3526 * @param pVCpu Pointer to the VMCPU.
3527 */
3528DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3529{
3530 SVMEVENT Event;
3531 Event.u = 0;
3532 Event.n.u1Valid = 1;
3533 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3534 Event.n.u8Vector = X86_XCPT_DF;
3535 Event.n.u1ErrorCodeValid = 1;
3536 Event.n.u32ErrorCode = 0;
3537 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3538}
3539
3540
3541/**
3542 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3543 * guests. This simply looks up the patch record at EIP and does the required.
3544 *
3545 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3546 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3547 * TPR). See hmR3ReplaceTprInstr() for the details.
3548 *
3549 * @returns VBox status code.
3550 * @param pVM Pointer to the VM.
3551 * @param pVCpu Pointer to the VMCPU.
3552 * @param pCtx Pointer to the guest-CPU context.
3553 */
3554static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3555{
3556 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3557 for (;;)
3558 {
3559 bool fPending;
3560 uint8_t u8Tpr;
3561
3562 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
3563 if (!pPatch)
3564 break;
3565
3566 switch (pPatch->enmType)
3567 {
3568 case HMTPRINSTR_READ:
3569 {
3570 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
3571 AssertRC(rc);
3572
3573 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
3574 AssertRC(rc);
3575 pCtx->rip += pPatch->cbOp;
3576 break;
3577 }
3578
3579 case HMTPRINSTR_WRITE_REG:
3580 case HMTPRINSTR_WRITE_IMM:
3581 {
3582 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
3583 {
3584 uint32_t u32Val;
3585 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
3586 AssertRC(rc);
3587 u8Tpr = u32Val;
3588 }
3589 else
3590 u8Tpr = (uint8_t)pPatch->uSrcOperand;
3591
3592 int rc2 = PDMApicSetTPR(pVCpu, u8Tpr);
3593 AssertRC(rc2);
3594 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3595
3596 pCtx->rip += pPatch->cbOp;
3597 break;
3598 }
3599
3600 default:
3601 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
3602 pVCpu->hm.s.u32HMError = pPatch->enmType;
3603 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
3604 }
3605 }
3606
3607 return VINF_SUCCESS;
3608}
3609
3610
3611/**
3612 * Determines if an exception is a contributory exception. Contributory
3613 * exceptions are ones which can cause double-faults. Page-fault is
3614 * intentionally not included here as it's a conditional contributory exception.
3615 *
3616 * @returns true if the exception is contributory, false otherwise.
3617 * @param uVector The exception vector.
3618 */
3619DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
3620{
3621 switch (uVector)
3622 {
3623 case X86_XCPT_GP:
3624 case X86_XCPT_SS:
3625 case X86_XCPT_NP:
3626 case X86_XCPT_TS:
3627 case X86_XCPT_DE:
3628 return true;
3629 default:
3630 break;
3631 }
3632 return false;
3633}
3634
3635
3636/**
3637 * Handle a condition that occurred while delivering an event through the guest
3638 * IDT.
3639 *
3640 * @returns VBox status code (informational error codes included).
3641 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
3642 * @retval VINF_HM_DOUBLE_FAULT if a #DF condition was detected and we ought to
3643 * continue execution of the guest which will delivery the #DF.
3644 * @retval VINF_EM_RESET if we detected a triple-fault condition.
3645 *
3646 * @param pVCpu Pointer to the VMCPU.
3647 * @param pCtx Pointer to the guest-CPU context.
3648 * @param pSvmTransient Pointer to the SVM transient structure.
3649 *
3650 * @remarks No-long-jump zone!!!
3651 */
3652static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3653{
3654 int rc = VINF_SUCCESS;
3655 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3656
3657 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
3658 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
3659 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
3660 {
3661 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
3662
3663 typedef enum
3664 {
3665 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
3666 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
3667 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
3668 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
3669 } SVMREFLECTXCPT;
3670
3671 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
3672 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
3673 {
3674 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
3675 {
3676 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
3677
3678#ifdef VBOX_STRICT
3679 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
3680 && uExitVector == X86_XCPT_PF)
3681 {
3682 Log4(("IDT: Contributory #PF uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
3683 }
3684#endif
3685 if ( uExitVector == X86_XCPT_PF
3686 && uIdtVector == X86_XCPT_PF)
3687 {
3688 pSvmTransient->fVectoringPF = true;
3689 Log4(("IDT: Vectoring #PF uCR2=%#RX64\n", pCtx->cr2));
3690 }
3691 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
3692 && hmR0SvmIsContributoryXcpt(uExitVector)
3693 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
3694 || uIdtVector == X86_XCPT_PF))
3695 {
3696 enmReflect = SVMREFLECTXCPT_DF;
3697 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntrInfo,
3698 uIdtVector, uExitVector));
3699 }
3700 else if (uIdtVector == X86_XCPT_DF)
3701 {
3702 enmReflect = SVMREFLECTXCPT_TF;
3703 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntrInfo,
3704 uIdtVector, uExitVector));
3705 }
3706 else
3707 enmReflect = SVMREFLECTXCPT_XCPT;
3708 }
3709 else
3710 {
3711 /*
3712 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
3713 * exception to the guest after handling the VM-exit.
3714 */
3715 enmReflect = SVMREFLECTXCPT_XCPT;
3716 }
3717 }
3718 else if (pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
3719 {
3720 /* Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
3721 enmReflect = SVMREFLECTXCPT_XCPT;
3722 }
3723
3724 switch (enmReflect)
3725 {
3726 case SVMREFLECTXCPT_XCPT:
3727 {
3728 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
3729 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
3730
3731 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
3732 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
3733 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
3734 break;
3735 }
3736
3737 case SVMREFLECTXCPT_DF:
3738 {
3739 hmR0SvmSetPendingXcptDF(pVCpu);
3740 rc = VINF_HM_DOUBLE_FAULT;
3741 break;
3742 }
3743
3744 case SVMREFLECTXCPT_TF:
3745 {
3746 rc = VINF_EM_RESET;
3747 break;
3748 }
3749
3750 default:
3751 Assert(rc == VINF_SUCCESS);
3752 break;
3753 }
3754 }
3755 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET);
3756 return rc;
3757}
3758
3759
3760/**
3761 * Advances the guest RIP in the if the NRIP_SAVE feature is supported by the
3762 * CPU, otherwise advances the RIP by @a cb bytes.
3763 *
3764 * @param pVCpu Pointer to the VMCPU.
3765 * @param pCtx Pointer to the guest-CPU context.
3766 * @param cb RIP increment value in bytes.
3767 *
3768 * @remarks Use this function only from #VMEXIT's where the NRIP value is valid
3769 * when NRIP_SAVE is supported by the CPU!
3770 */
3771DECLINLINE(void) hmR0SvmUpdateRip(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
3772{
3773 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
3774 {
3775 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3776 pCtx->rip = pVmcb->ctrl.u64NextRIP;
3777 }
3778 else
3779 pCtx->rip += cb;
3780}
3781
3782
3783/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
3784/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
3785/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
3786
3787/** @name VM-exit handlers.
3788 * @{
3789 */
3790
3791/**
3792 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
3793 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
3794 */
3795HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3796{
3797 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3798
3799 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
3800 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
3801 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
3802 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
3803
3804 /*
3805 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
3806 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
3807 * interrupt it is until the host actually take the interrupt.
3808 *
3809 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
3810 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
3811 */
3812 return VINF_EM_RAW_INTERRUPT;
3813}
3814
3815
3816/**
3817 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
3818 */
3819HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3820{
3821 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3822
3823 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3824 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
3825 int rc = VINF_SUCCESS;
3826 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3827 return rc;
3828}
3829
3830
3831/**
3832 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
3833 */
3834HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3835{
3836 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3837
3838 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3839 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
3840 int rc = VINF_SUCCESS;
3841 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3842 return rc;
3843}
3844
3845
3846/**
3847 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
3848 */
3849HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3850{
3851 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3852 PVM pVM = pVCpu->CTX_SUFF(pVM);
3853 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3854 if (RT_LIKELY(rc == VINF_SUCCESS))
3855 {
3856 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3857 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3858 }
3859 else
3860 {
3861 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
3862 rc = VERR_EM_INTERPRETER;
3863 }
3864 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
3865 return rc;
3866}
3867
3868
3869/**
3870 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
3871 */
3872HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3873{
3874 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3875 PVM pVM = pVCpu->CTX_SUFF(pVM);
3876 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3877 if (RT_LIKELY(rc == VINF_SUCCESS))
3878 {
3879 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3880 pSvmTransient->fUpdateTscOffsetting = true;
3881
3882 /* Single step check. */
3883 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3884 }
3885 else
3886 {
3887 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
3888 rc = VERR_EM_INTERPRETER;
3889 }
3890 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
3891 return rc;
3892}
3893
3894
3895/**
3896 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
3897 */
3898HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3899{
3900 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3901 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
3902 if (RT_LIKELY(rc == VINF_SUCCESS))
3903 {
3904 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3905 pSvmTransient->fUpdateTscOffsetting = true;
3906 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3907 }
3908 else
3909 {
3910 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
3911 rc = VERR_EM_INTERPRETER;
3912 }
3913 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
3914 return rc;
3915}
3916
3917
3918/**
3919 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
3920 */
3921HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3922{
3923 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3924 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3925 if (RT_LIKELY(rc == VINF_SUCCESS))
3926 {
3927 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3928 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3929 }
3930 else
3931 {
3932 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
3933 rc = VERR_EM_INTERPRETER;
3934 }
3935 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
3936 return rc;
3937}
3938
3939
3940/**
3941 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
3942 */
3943HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3944{
3945 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3946 PVM pVM = pVCpu->CTX_SUFF(pVM);
3947 Assert(!pVM->hm.s.fNestedPaging);
3948
3949 /** @todo Decode Assist. */
3950 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx)); /* Updates RIP if successful. */
3951 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
3952 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
3953 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3954 return rc;
3955}
3956
3957
3958/**
3959 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
3960 */
3961HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3962{
3963 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3964 hmR0SvmUpdateRip(pVCpu, pCtx, 1);
3965 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
3966 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3967 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
3968 return rc;
3969}
3970
3971
3972/**
3973 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
3974 */
3975HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3976{
3977 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3978 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3979 if (RT_LIKELY(rc == VINF_SUCCESS))
3980 {
3981 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3982 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
3983 }
3984 else
3985 {
3986 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
3987 rc = VERR_EM_INTERPRETER;
3988 }
3989 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
3990 return rc;
3991}
3992
3993
3994/**
3995 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
3996 */
3997HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3998{
3999 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4000 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4001 int rc = VBOXSTRICTRC_VAL(rc2);
4002 if ( rc == VINF_EM_HALT
4003 || rc == VINF_SUCCESS)
4004 {
4005 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
4006
4007 if ( rc == VINF_EM_HALT
4008 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
4009 {
4010 rc = VINF_SUCCESS;
4011 }
4012 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4013 }
4014 else
4015 {
4016 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
4017 rc = VERR_EM_INTERPRETER;
4018 }
4019 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
4020 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
4021 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
4022 return rc;
4023}
4024
4025
4026/**
4027 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
4028 * Conditional #VMEXIT.
4029 */
4030HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4031{
4032 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4033 return VINF_EM_RESET;
4034}
4035
4036
4037/**
4038 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
4039 */
4040HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4041{
4042 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4043
4044 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4045
4046 /** @todo Decode Assist. */
4047 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4048 int rc = VBOXSTRICTRC_VAL(rc2);
4049 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
4050 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
4051 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
4052 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
4053 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4054 return rc;
4055}
4056
4057
4058/**
4059 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
4060 */
4061HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4062{
4063 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4064 /** @todo Decode Assist. */
4065 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4066 int rc = VBOXSTRICTRC_VAL(rc2);
4067 if (rc == VINF_SUCCESS)
4068 {
4069 /* RIP has been updated by EMInterpretInstruction(). */
4070 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
4071 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
4072 {
4073 case 0: /* CR0. */
4074 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
4075 break;
4076
4077 case 3: /* CR3. */
4078 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4079 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
4080 break;
4081
4082 case 4: /* CR4. */
4083 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
4084 break;
4085
4086 case 8: /* CR8 (TPR). */
4087 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4088 break;
4089
4090 default:
4091 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x CRx=%#RX64\n",
4092 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
4093 break;
4094 }
4095 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4096 }
4097 else
4098 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
4099 return rc;
4100}
4101
4102
4103/**
4104 * #VMEXIT handler for instructions that result in a #UD exception delivered to
4105 * the guest.
4106 */
4107HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4108{
4109 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4110 hmR0SvmSetPendingXcptUD(pVCpu);
4111 return VINF_SUCCESS;
4112}
4113
4114
4115/**
4116 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
4117 */
4118HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4119{
4120 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4121 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4122 PVM pVM = pVCpu->CTX_SUFF(pVM);
4123
4124 int rc;
4125 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
4126 {
4127 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
4128
4129 /* Handle TPR patching; intercepted LSTAR write. */
4130 if ( pVM->hm.s.fTPRPatchingActive
4131 && pCtx->ecx == MSR_K8_LSTAR)
4132 {
4133 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
4134 {
4135 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
4136 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
4137 AssertRC(rc2);
4138 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4139 }
4140 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
4141 rc = VINF_SUCCESS;
4142 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4143 return rc;
4144 }
4145
4146 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4147 {
4148 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4149 if (RT_LIKELY(rc == VINF_SUCCESS))
4150 {
4151 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4152 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4153 }
4154 else
4155 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
4156 }
4157 else
4158 {
4159 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
4160 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4161 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4162 /* RIP updated by EMInterpretInstruction(). */
4163 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4164 }
4165
4166 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
4167 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
4168 && pCtx->ecx <= MSR_IA32_X2APIC_END)
4169 {
4170 /* We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
4171 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
4172 EMInterpretWrmsr() changes it. */
4173 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4174 }
4175 else if (pCtx->ecx == MSR_K6_EFER)
4176 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_EFER_MSR;
4177 else if (pCtx->ecx == MSR_IA32_TSC)
4178 pSvmTransient->fUpdateTscOffsetting = true;
4179 }
4180 else
4181 {
4182 /* MSR Read access. */
4183 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
4184 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
4185
4186 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4187 {
4188 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4189 if (RT_LIKELY(rc == VINF_SUCCESS))
4190 {
4191 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4192 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4193 }
4194 else
4195 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
4196 }
4197 else
4198 {
4199 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
4200 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4201 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4202 /* RIP updated by EMInterpretInstruction(). */
4203 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4204 }
4205 }
4206
4207 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
4208 return rc;
4209}
4210
4211
4212/**
4213 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
4214 */
4215HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4216{
4217 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4218 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
4219
4220 /* We should -not- get this VM-exit if the guest is debugging. */
4221 AssertMsgReturn(!CPUMIsGuestDebugStateActive(pVCpu),
4222 ("hmR0SvmExitReadDRx: Unexpected exit. pVCpu=%p pCtx=%p\n", pVCpu, pCtx),
4223 VERR_SVM_UNEXPECTED_EXIT);
4224
4225 /*
4226 * Lazy DR0-3 loading?
4227 */
4228 if (!CPUMIsHyperDebugStateActive(pVCpu))
4229 {
4230 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4231 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4232
4233 /* Don't intercept DRx read and writes. */
4234 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4235 pVmcb->ctrl.u16InterceptRdDRx = 0;
4236 pVmcb->ctrl.u16InterceptWrDRx = 0;
4237 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4238
4239 /* We're playing with the host CPU state here, make sure we don't preempt. */
4240 HM_DISABLE_PREEMPT_IF_NEEDED();
4241
4242 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4243 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4244 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
4245
4246 HM_RESTORE_PREEMPT_IF_NEEDED();
4247
4248 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4249 return VINF_SUCCESS;
4250 }
4251
4252 /*
4253 * Interpret the read/writing of DRx.
4254 */
4255 /** @todo Decode assist. */
4256 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4257 Log5(("hmR0SvmExitReadDRx: Emulatined DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4258 if (RT_LIKELY(rc == VINF_SUCCESS))
4259 {
4260 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4261 /** @todo CPUM should set this flag! */
4262 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
4263 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4264 }
4265 else
4266 Assert(rc == VERR_EM_INTERPRETER);
4267 return VBOXSTRICTRC_TODO(rc);
4268}
4269
4270
4271/**
4272 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
4273 */
4274HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4275{
4276 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4277 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4278 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4279 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4280 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4281 return rc;
4282}
4283
4284
4285/**
4286 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
4287 */
4288HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4289{
4290 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4291
4292 /* I/O operation lookup arrays. */
4293 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4294 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4295 the result (in AL/AX/EAX). */
4296 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4297
4298 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4299 PVM pVM = pVCpu->CTX_SUFF(pVM);
4300
4301 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4302 SVMIOIOEXIT IoExitInfo;
4303 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4304 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4305 uint32_t cbValue = s_aIOSize[uIOWidth];
4306 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4307
4308 if (RT_UNLIKELY(!cbValue))
4309 {
4310 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4311 return VERR_EM_INTERPRETER;
4312 }
4313
4314 VBOXSTRICTRC rcStrict;
4315 if (IoExitInfo.n.u1STR)
4316 {
4317 /* INS/OUTS - I/O String instruction. */
4318 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4319
4320 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4321 * in EXITINFO1? Investigate once this thing is up and running. */
4322
4323 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4324 if (rcStrict == VINF_SUCCESS)
4325 {
4326 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4327 {
4328 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4329 (DISCPUMODE)pDis->uAddrMode, cbValue);
4330 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4331 }
4332 else
4333 {
4334 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4335 (DISCPUMODE)pDis->uAddrMode, cbValue);
4336 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4337 }
4338 }
4339 else
4340 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
4341 }
4342 else
4343 {
4344 /* IN/OUT - I/O instruction. */
4345 Assert(!IoExitInfo.n.u1REP);
4346
4347 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4348 {
4349 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
4350 if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4351 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4352
4353 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4354 }
4355 else
4356 {
4357 uint32_t u32Val = 0;
4358
4359 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
4360 if (IOM_SUCCESS(rcStrict))
4361 {
4362 /* Save result of I/O IN instr. in AL/AX/EAX. */
4363 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4364 }
4365 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4366 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4367
4368 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
4369 }
4370 }
4371
4372 if (IOM_SUCCESS(rcStrict))
4373 {
4374 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
4375 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
4376
4377 /*
4378 * If any I/O breakpoints are armed, we need to check if one triggered
4379 * and take appropriate action.
4380 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
4381 */
4382 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
4383 * execution engines about whether hyper BPs and such are pending. */
4384 uint32_t const uDr7 = pCtx->dr[7];
4385 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
4386 && X86_DR7_ANY_RW_IO(uDr7)
4387 && (pCtx->cr4 & X86_CR4_DE))
4388 || DBGFBpIsHwIoArmed(pVM)))
4389 {
4390 /* We're playing with the host CPU state here, make sure we don't preempt. */
4391 HM_DISABLE_PREEMPT_IF_NEEDED();
4392
4393 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
4394 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
4395
4396 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
4397 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
4398 {
4399 /* Raise #DB. */
4400 pVmcb->guest.u64DR6 = pCtx->dr[6];
4401 pVmcb->guest.u64DR7 = pCtx->dr[7];
4402 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4403 hmR0SvmSetPendingXcptDB(pVCpu);
4404 }
4405 /* rcStrict is VINF_SUCCESS or in [VINF_EM_FIRST..VINF_EM_LAST]. */
4406 else if ( rcStrict2 != VINF_SUCCESS
4407 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
4408 rcStrict = rcStrict2;
4409
4410 HM_RESTORE_PREEMPT_IF_NEEDED();
4411 }
4412
4413 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4414 }
4415
4416#ifdef VBOX_STRICT
4417 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4418 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
4419 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE)
4420 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
4421 else
4422 {
4423 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
4424 * statuses, that the VMM device and some others may return. See
4425 * IOM_SUCCESS() for guidance. */
4426 AssertMsg( RT_FAILURE(rcStrict)
4427 || rcStrict == VINF_SUCCESS
4428 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
4429 || rcStrict == VINF_EM_DBG_BREAKPOINT
4430 || rcStrict == VINF_EM_RAW_GUEST_TRAP
4431 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
4432 }
4433#endif
4434 return VBOXSTRICTRC_TODO(rcStrict);
4435}
4436
4437
4438/**
4439 * #VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional
4440 * #VMEXIT.
4441 */
4442HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4443{
4444 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4445 PVM pVM = pVCpu->CTX_SUFF(pVM);
4446 Assert(pVM->hm.s.fNestedPaging);
4447
4448 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4449
4450 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
4451 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4452 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4453 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
4454
4455 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
4456
4457#ifdef VBOX_HM_WITH_GUEST_PATCHING
4458 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
4459 if ( pVM->hm.s.fTRPPatchingAllowed
4460 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80 /* TPR offset. */
4461 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
4462 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
4463 && !CPUMGetGuestCPL(pVCpu)
4464 && !CPUMIsGuestInLongModeEx(pCtx)
4465 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4466 {
4467 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
4468 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4469
4470 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
4471 {
4472 /* Only attempt to patch the instruction once. */
4473 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4474 if (!pPatch)
4475 return VINF_EM_HM_PATCH_TPR_INSTR;
4476 }
4477 }
4478#endif
4479
4480 /*
4481 * Determine the nested paging mode.
4482 */
4483 PGMMODE enmNestedPagingMode;
4484#if HC_ARCH_BITS == 32
4485 if (CPUMIsGuestInLongModeEx(pCtx))
4486 enmNestedPagingMode = PGMMODE_AMD64_NX;
4487 else
4488#endif
4489 enmNestedPagingMode = PGMGetHostMode(pVM);
4490
4491 /*
4492 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
4493 */
4494 int rc;
4495 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
4496 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
4497 {
4498 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
4499 u32ErrCode);
4500 rc = VBOXSTRICTRC_VAL(rc2);
4501
4502 /*
4503 * If we succeed, resume guest execution.
4504 * If we fail in interpreting the instruction because we couldn't get the guest physical address
4505 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
4506 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
4507 * weird case. See @bugref{6043}.
4508 */
4509 if ( rc == VINF_SUCCESS
4510 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4511 || rc == VERR_PAGE_NOT_PRESENT)
4512 {
4513 /* Successfully handled MMIO operation. */
4514 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4515 rc = VINF_SUCCESS;
4516 }
4517 return rc;
4518 }
4519
4520 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
4521 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
4522 TRPMResetTrap(pVCpu);
4523
4524 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
4525
4526 /*
4527 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
4528 */
4529 if ( rc == VINF_SUCCESS
4530 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4531 || rc == VERR_PAGE_NOT_PRESENT)
4532 {
4533 /* We've successfully synced our shadow page tables. */
4534 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4535 rc = VINF_SUCCESS;
4536 }
4537
4538 return rc;
4539}
4540
4541
4542/**
4543 * #VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional #VMEXIT.
4544 */
4545HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4546{
4547 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4548
4549 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4550 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one before reentry. */
4551 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
4552
4553 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
4554 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
4555 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
4556
4557 /* Deliver the pending interrupt via hmR0SvmPreRunGuest()->hmR0SvmInjectEventVmcb() and resume guest execution. */
4558 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
4559 return VINF_SUCCESS;
4560}
4561
4562
4563/**
4564 * #VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional #VMEXIT.
4565 */
4566HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4567{
4568 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4569
4570#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
4571 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4572#endif
4573
4574 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
4575 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4576 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
4577 && pVCpu->hm.s.Event.fPending)
4578 {
4579 /*
4580 * AMD-V does not provide us with the original exception but we have it in u64IntrInfo since we
4581 * injected the event during VM-entry. Software interrupts and exceptions will be regenerated
4582 * when the recompiler restarts the instruction.
4583 */
4584 SVMEVENT Event;
4585 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
4586 if ( Event.n.u3Type == SVM_EVENT_EXCEPTION
4587 || Event.n.u3Type == SVM_EVENT_SOFTWARE_INT)
4588 {
4589 pVCpu->hm.s.Event.fPending = false;
4590 }
4591 else
4592 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery. Kept pending u8Vector=%#x\n", Event.n.u8Vector));
4593 }
4594
4595 /** @todo Emulate task switch someday, currently just going back to ring-3 for
4596 * emulation. */
4597 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
4598 return VERR_EM_INTERPRETER;
4599}
4600
4601
4602/**
4603 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
4604 */
4605HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4606{
4607 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4608
4609 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4610 if (RT_LIKELY(rc == VINF_SUCCESS))
4611 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4612 else
4613 hmR0SvmSetPendingXcptUD(pVCpu);
4614 return VINF_SUCCESS;
4615}
4616
4617
4618/**
4619 * #VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E). Conditional
4620 * #VMEXIT.
4621 */
4622HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4623{
4624 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4625
4626 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4627
4628 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
4629 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4630 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4631 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
4632 PVM pVM = pVCpu->CTX_SUFF(pVM);
4633
4634#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
4635 if (pVM->hm.s.fNestedPaging)
4636 {
4637 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4638 if (!pSvmTransient->fVectoringPF)
4639 {
4640 /* A genuine guest #PF, reflect it to the guest. */
4641 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4642 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
4643 uFaultAddress, u32ErrCode));
4644 }
4645 else
4646 {
4647 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4648 hmR0SvmSetPendingXcptDF(pVCpu);
4649 Log4(("Pending #DF due to vectoring #PF. NP\n"));
4650 }
4651 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4652 return VINF_SUCCESS;
4653 }
4654#endif
4655
4656 Assert(!pVM->hm.s.fNestedPaging);
4657
4658#ifdef VBOX_HM_WITH_GUEST_PATCHING
4659 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
4660 if ( pVM->hm.s.fTRPPatchingAllowed
4661 && (uFaultAddress & 0xfff) == 0x80 /* TPR offset. */
4662 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
4663 && !CPUMGetGuestCPL(pVCpu)
4664 && !CPUMIsGuestInLongModeEx(pCtx)
4665 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4666 {
4667 RTGCPHYS GCPhysApicBase;
4668 GCPhysApicBase = pCtx->msrApicBase;
4669 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4670
4671 /* Check if the page at the fault-address is the APIC base. */
4672 RTGCPHYS GCPhysPage;
4673 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
4674 if ( rc2 == VINF_SUCCESS
4675 && GCPhysPage == GCPhysApicBase)
4676 {
4677 /* Only attempt to patch the instruction once. */
4678 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4679 if (!pPatch)
4680 return VINF_EM_HM_PATCH_TPR_INSTR;
4681 }
4682 }
4683#endif
4684
4685 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
4686 pCtx->rip, u32ErrCode, pCtx->cr3));
4687
4688 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
4689 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
4690
4691 Log4(("#PF rc=%Rrc\n", rc));
4692
4693 if (rc == VINF_SUCCESS)
4694 {
4695 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
4696 TRPMResetTrap(pVCpu);
4697 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4698 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4699 return rc;
4700 }
4701 else if (rc == VINF_EM_RAW_GUEST_TRAP)
4702 {
4703 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4704
4705 if (!pSvmTransient->fVectoringPF)
4706 {
4707 /* It's a guest page fault and needs to be reflected to the guest. */
4708 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
4709 TRPMResetTrap(pVCpu);
4710 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4711 }
4712 else
4713 {
4714 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4715 TRPMResetTrap(pVCpu);
4716 hmR0SvmSetPendingXcptDF(pVCpu);
4717 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
4718 }
4719
4720 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4721 return VINF_SUCCESS;
4722 }
4723
4724 TRPMResetTrap(pVCpu);
4725 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
4726 return rc;
4727}
4728
4729
4730/**
4731 * #VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
4732 * Conditional #VMEXIT.
4733 */
4734HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4735{
4736 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4737
4738 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4739
4740#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
4741 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
4742#endif
4743
4744 /* We're playing with the host CPU state here, make sure we don't preempt. */
4745 HM_DISABLE_PREEMPT_IF_NEEDED();
4746
4747 /* Lazy FPU loading; load the guest-FPU state transparently and continue execution of the guest. */
4748 int rc = CPUMR0LoadGuestFPU(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4749 if (rc == VINF_SUCCESS)
4750 {
4751 Assert(CPUMIsGuestFPUStateActive(pVCpu));
4752 HM_RESTORE_PREEMPT_IF_NEEDED();
4753
4754 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
4755 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
4756 return VINF_SUCCESS;
4757 }
4758
4759 HM_RESTORE_PREEMPT_IF_NEEDED();
4760
4761 /* Forward #NM to the guest. */
4762 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
4763 hmR0SvmSetPendingXcptNM(pVCpu);
4764 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
4765 return VINF_SUCCESS;
4766}
4767
4768
4769/**
4770 * #VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
4771 * Conditional #VMEXIT.
4772 */
4773HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4774{
4775 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4776
4777 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4778
4779 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
4780
4781 if (!(pCtx->cr0 & X86_CR0_NE))
4782 {
4783 /* Old-style FPU error reporting needs some extra work. */
4784 /** @todo don't fall back to the recompiler, but do it manually. */
4785 return VERR_EM_INTERPRETER;
4786 }
4787
4788 hmR0SvmSetPendingXcptMF(pVCpu);
4789 return VINF_SUCCESS;
4790}
4791
4792
4793/**
4794 * #VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
4795 * #VMEXIT.
4796 */
4797HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4798{
4799 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4800
4801 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4802
4803 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
4804
4805 /* If we set the trap flag above, we have to clear it. */
4806 if (pVCpu->hm.s.fClearTrapFlag)
4807 {
4808 pVCpu->hm.s.fClearTrapFlag = false;
4809 pCtx->eflags.Bits.u1TF = 0;
4810 }
4811
4812 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
4813 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
4814 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4815 PVM pVM = pVCpu->CTX_SUFF(pVM);
4816 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
4817 if (rc == VINF_EM_RAW_GUEST_TRAP)
4818 {
4819 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
4820 if (CPUMIsHyperDebugStateActive(pVCpu))
4821 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
4822
4823 /* Reflect the exception back to the guest. */
4824 hmR0SvmSetPendingXcptDB(pVCpu);
4825 rc = VINF_SUCCESS;
4826 }
4827
4828 /*
4829 * Update DR6.
4830 */
4831 if (CPUMIsHyperDebugStateActive(pVCpu))
4832 {
4833 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
4834 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
4835 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4836 }
4837 else
4838 {
4839 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
4840 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
4841 }
4842
4843 return rc;
4844}
4845
4846/** @} */
4847
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