VirtualBox

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

Last change on this file since 47444 was 47433, checked in by vboxsync, 12 years ago

HMR0SVM.cpp: Added todo regarding I/O breakpoints.

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