VirtualBox

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

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

VMM: More debugging related stuff.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 176.6 KB
Line 
1/* $Id: HMSVMR0.cpp 47671 2013-08-12 11:16:55Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_HM
22#include <iprt/asm-amd64-x86.h>
23#include <iprt/thread.h>
24
25#include "HMInternal.h"
26#include <VBox/vmm/vm.h>
27#include "HMSVMR0.h"
28#include <VBox/vmm/pdmapi.h>
29#include <VBox/vmm/dbgf.h>
30#include <VBox/vmm/iom.h>
31#include <VBox/vmm/tm.h>
32
33#ifdef DEBUG_ramshankar
34# define HMSVM_SYNC_FULL_GUEST_STATE
35# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
36# define HMSVM_ALWAYS_TRAP_PF
37# define HMSVM_ALWAYS_TRAP_TASK_SWITCH
38#endif
39
40
41/*******************************************************************************
42* Defined Constants And Macros *
43*******************************************************************************/
44#ifdef VBOX_WITH_STATISTICS
45# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
46 if ((u64ExitCode) == SVM_EXIT_NPF) \
47 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
48 else \
49 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
50 } while (0)
51#else
52# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
53#endif
54
55/** If we decide to use a function table approach this can be useful to
56 * switch to a "static DECLCALLBACK(int)". */
57#define HMSVM_EXIT_DECL static int
58
59
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 Assert((pCtx->dr[6] & X86_DR6_RA1_MASK) == X86_DR6_RA1_MASK); Assert((pCtx->dr[6] & X86_DR6_RAZ_MASK) == 0);
1324 Assert((pCtx->dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK); Assert((pCtx->dr[7] & X86_DR7_RAZ_MASK) == 0);
1325
1326 bool fInterceptDB = false;
1327 bool fInterceptMovDRx = false;
1328
1329 /*
1330 * Anyone single stepping on the host side? If so, we'll have to use the
1331 * trap flag in the guest EFLAGS since AMD-V doesn't have a trap flag on
1332 * the VMM level like VT-x implementations does.
1333 */
1334 bool const fStepping = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
1335 if (fStepping)
1336 {
1337 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1338 fInterceptDB = true;
1339 fInterceptMovDRx = true; /* Need clean DR6, no guest mess. */
1340 }
1341
1342 PVM pVM = pVCpu->CTX_SUFF(pVM);
1343 if (fStepping || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
1344 {
1345 /*
1346 * Use the combined guest and host DRx values found in the hypervisor
1347 * register set because the debugger has breakpoints active or someone
1348 * is single stepping on the host side.
1349 *
1350 * Note! DBGF expects a clean DR6 state before executing guest code.
1351 */
1352 if (!CPUMIsHyperDebugStateActive(pVCpu))
1353 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1354 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1355 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1356
1357 /* Update DR6 & DR7. (The other DRx values are handled by CPUM one way or the other.) */
1358 if ( pVmcb->guest.u64DR6 != X86_DR6_INIT_VAL
1359 || pVmcb->guest.u64DR7 != CPUMGetHyperDR7(pVCpu) )
1360 {
1361 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1362 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
1363 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1364 }
1365
1366 /** @todo If we cared, we could optimize to allow the guest to read registers
1367 * with the same values. */
1368 fInterceptDB = true;
1369 fInterceptMovDRx = true;
1370 Log5(("hm: Loaded hyper DRx\n"));
1371 }
1372 else
1373 {
1374 /*
1375 * Update DR6, DR7 with the guest values if necessary.
1376 */
1377 if ( pVmcb->guest.u64DR7 != pCtx->dr[7]
1378 || pVmcb->guest.u64DR6 != pCtx->dr[6])
1379 {
1380 pVmcb->guest.u64DR7 = pCtx->dr[7];
1381 pVmcb->guest.u64DR6 = pCtx->dr[6];
1382 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1383 }
1384
1385 /*
1386 * If the guest has enabled debug registers, we need to load them prior to
1387 * executing guest code so they'll trigger at the right time.
1388 */
1389 if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
1390 {
1391 if (!CPUMIsGuestDebugStateActive(pVCpu))
1392 {
1393 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
1394 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1395 }
1396 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1397 Assert(CPUMIsGuestDebugStateActive(pVCpu));
1398 Log5(("hm: Loaded guest DRx\n"));
1399 }
1400 /*
1401 * If no debugging enabled, we'll lazy load DR0-3.
1402 */
1403 else if (!CPUMIsGuestDebugStateActive(pVCpu))
1404 fInterceptMovDRx = true;
1405 }
1406
1407 /*
1408 * Set up the intercepts.
1409 */
1410 if (fInterceptDB)
1411 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_DB);
1412 else
1413 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_DB);
1414
1415 if (fInterceptMovDRx)
1416 {
1417 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
1418 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
1419 {
1420 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
1421 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
1422 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1423 }
1424 }
1425 else
1426 {
1427 if ( pVmcb->ctrl.u16InterceptRdDRx
1428 || pVmcb->ctrl.u16InterceptWrDRx)
1429 {
1430 pVmcb->ctrl.u16InterceptRdDRx = 0;
1431 pVmcb->ctrl.u16InterceptWrDRx = 0;
1432 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1433 }
1434 }
1435
1436 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_DEBUG;
1437}
1438
1439
1440/**
1441 * Loads the guest APIC state (currently just the TPR).
1442 *
1443 * @returns VBox status code.
1444 * @param pVCpu Pointer to the VMCPU.
1445 * @param pVmcb Pointer to the VMCB.
1446 * @param pCtx Pointer to the guest-CPU context.
1447 */
1448DECLINLINE(int) hmR0SvmLoadGuestApicState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1449{
1450 if (!(pVCpu->hm.s.fContextUseFlags & HM_CHANGED_SVM_GUEST_APIC_STATE))
1451 return VINF_SUCCESS;
1452
1453 bool fPendingIntr;
1454 uint8_t u8Tpr;
1455 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
1456 AssertRCReturn(rc, rc);
1457
1458 /** Assume that we need to trap all TPR accesses and thus need not check on
1459 * every #VMEXIT if we should update the TPR. */
1460 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqMasking);
1461 pVCpu->hm.s.svm.fSyncVTpr = false;
1462
1463 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
1464 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive)
1465 {
1466 pCtx->msrLSTAR = u8Tpr;
1467
1468 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
1469 if (fPendingIntr)
1470 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
1471 else
1472 {
1473 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1474 pVCpu->hm.s.svm.fSyncVTpr = true;
1475 }
1476 }
1477 else
1478 {
1479 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
1480 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
1481
1482 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we can deliver the interrupt to the guest. */
1483 if (fPendingIntr)
1484 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1485 else
1486 {
1487 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1488 pVCpu->hm.s.svm.fSyncVTpr = true;
1489 }
1490
1491 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
1492 }
1493
1494 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_SVM_GUEST_APIC_STATE;
1495 return rc;
1496}
1497
1498
1499/**
1500 * Sets up the appropriate function to run guest code.
1501 *
1502 * @returns VBox status code.
1503 * @param pVCpu Pointer to the VMCPU.
1504 * @param pCtx Pointer to the guest-CPU context.
1505 *
1506 * @remarks No-long-jump zone!!!
1507 */
1508static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pCtx)
1509{
1510 if (CPUMIsGuestInLongModeEx(pCtx))
1511 {
1512#ifndef VBOX_ENABLE_64_BITS_GUESTS
1513 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1514#endif
1515 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
1516#if HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1517 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
1518 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
1519#else
1520 /* 64-bit host or hybrid host. */
1521 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1522#endif
1523 }
1524 else
1525 {
1526 /* Guest is not in long mode, use the 32-bit handler. */
1527 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1528 }
1529 return VINF_SUCCESS;
1530}
1531
1532
1533/**
1534 * Enters the AMD-V session.
1535 *
1536 * @returns VBox status code.
1537 * @param pVM Pointer to the VM.
1538 * @param pVCpu Pointer to the VMCPU.
1539 * @param pCpu Pointer to the CPU info struct.
1540 */
1541VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
1542{
1543 AssertPtr(pVM);
1544 AssertPtr(pVCpu);
1545 Assert(pVM->hm.s.svm.fSupported);
1546 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1547 NOREF(pCpu);
1548
1549 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
1550
1551 /* Nothing to do here. */
1552 return VINF_SUCCESS;
1553}
1554
1555
1556/**
1557 * Leaves the AMD-V session.
1558 *
1559 * @returns VBox status code.
1560 * @param pVM Pointer to the VM.
1561 * @param pVCpu Pointer to the VMCPU.
1562 * @param pCtx Pointer to the guest-CPU context.
1563 */
1564VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1565{
1566 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1567 NOREF(pVM);
1568 NOREF(pVCpu);
1569 NOREF(pCtx);
1570
1571 /* Nothing to do here. Everything is taken care of in hmR0SvmLongJmpToRing3(). */
1572 return VINF_SUCCESS;
1573}
1574
1575
1576/**
1577 * Saves the host state.
1578 *
1579 * @returns VBox status code.
1580 * @param pVM Pointer to the VM.
1581 * @param pVCpu Pointer to the VMCPU.
1582 *
1583 * @remarks No-long-jump zone!!!
1584 */
1585VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
1586{
1587 NOREF(pVM);
1588 NOREF(pVCpu);
1589 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
1590 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_HOST_CONTEXT;
1591 return VINF_SUCCESS;
1592}
1593
1594
1595/**
1596 * Loads the guest state into the VMCB. The CPU state will be loaded from these
1597 * fields on every successful VM-entry.
1598 *
1599 * Sets up the appropriate VMRUN function to execute guest code based
1600 * on the guest CPU mode.
1601 *
1602 * @returns VBox status code.
1603 * @param pVM Pointer to the VM.
1604 * @param pVCpu Pointer to the VMCPU.
1605 * @param pMixedCtx Pointer to the guest-CPU context.
1606 *
1607 * @remarks No-long-jump zone!!!
1608 */
1609static int hmR0SvmLoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1610{
1611 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1612 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1613
1614 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
1615
1616 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
1617 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1618
1619 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
1620 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
1621
1622 pVmcb->guest.u64RIP = pCtx->rip;
1623 pVmcb->guest.u64RSP = pCtx->rsp;
1624 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
1625 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1626 pVmcb->guest.u64RAX = pCtx->rax;
1627
1628 /* hmR0SvmLoadGuestDebugRegs() must be called -after- updating guest RFLAGS as the RFLAGS may need to be changed. */
1629 hmR0SvmLoadGuestDebugRegs(pVCpu, pVmcb, pCtx);
1630
1631 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
1632 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1633
1634 rc = hmR0SvmSetupVMRunHandler(pVCpu, pCtx);
1635 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1636
1637 /* Clear any unused and reserved bits. */
1638 pVCpu->hm.s.fContextUseFlags &= ~( HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
1639 | HM_CHANGED_GUEST_RSP
1640 | HM_CHANGED_GUEST_RFLAGS
1641 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
1642 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
1643 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
1644 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
1645 | HM_CHANGED_SVM_RESERVED2
1646 | HM_CHANGED_SVM_RESERVED3);
1647
1648 AssertMsg(!pVCpu->hm.s.fContextUseFlags,
1649 ("Missed updating flags while loading guest state. pVM=%p pVCpu=%p fContextUseFlags=%#RX32\n",
1650 pVM, pVCpu, pVCpu->hm.s.fContextUseFlags));
1651
1652 Log4(("Load: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
1653
1654 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
1655 return rc;
1656}
1657
1658
1659/**
1660 * Loads the guest state on the way from ring-3.
1661 *
1662 * @returns VBox status code.
1663 * @param pVM Pointer to the VM.
1664 * @param pVCpu Pointer to the VMCPU.
1665 * @param pCtx Pointer to the guest-CPU context.
1666 *
1667 * @remarks No-long-jump zone!!!
1668 */
1669VMMR0DECL(int) SVMR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1670{
1671 /*
1672 * Avoid reloading the guest state on longjmp reentrants and do it lazily just before executing the guest.
1673 * This only helps when we get rescheduled more than once to a different host CPU on a longjmp trip before
1674 * finally executing guest code.
1675 */
1676 return VINF_SUCCESS;
1677}
1678
1679
1680/**
1681 * Saves the entire guest state from the VMCB into the
1682 * guest-CPU context. Currently there is no residual state left in the CPU that
1683 * is not updated in the VMCB.
1684 *
1685 * @returns VBox status code.
1686 * @param pVCpu Pointer to the VMCPU.
1687 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1688 * out-of-sync. Make sure to update the required fields
1689 * before using them.
1690 */
1691static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1692{
1693 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1694
1695 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1696
1697 pMixedCtx->rip = pVmcb->guest.u64RIP;
1698 pMixedCtx->rsp = pVmcb->guest.u64RSP;
1699 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1700 pMixedCtx->rax = pVmcb->guest.u64RAX;
1701
1702 /*
1703 * Guest interrupt shadow.
1704 */
1705 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1706 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
1707 else
1708 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1709
1710 /*
1711 * Guest Control registers: CR2, CR3 (handled at the end) - accesses to other control registers are always intercepted.
1712 */
1713 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
1714
1715 /*
1716 * Guest MSRs.
1717 */
1718 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1719 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1720 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1721 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1722 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1723 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1724 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1725 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1726
1727 /*
1728 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
1729 */
1730 HMSVM_SAVE_SEG_REG(CS, cs);
1731 HMSVM_SAVE_SEG_REG(SS, ss);
1732 HMSVM_SAVE_SEG_REG(DS, ds);
1733 HMSVM_SAVE_SEG_REG(ES, es);
1734 HMSVM_SAVE_SEG_REG(FS, fs);
1735 HMSVM_SAVE_SEG_REG(GS, gs);
1736
1737 /*
1738 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
1739 * register (yet).
1740 */
1741 /** @todo SELM might need to be fixed as it too should not care about the
1742 * granularity bit. See @bugref{6785}. */
1743 if ( !pMixedCtx->cs.Attr.n.u1Granularity
1744 && pMixedCtx->cs.Attr.n.u1Present
1745 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
1746 {
1747 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
1748 pMixedCtx->cs.Attr.n.u1Granularity = 1;
1749 }
1750
1751#ifdef VBOX_STRICT
1752# define HMSVM_ASSERT_SEG_GRANULARITY(reg) \
1753 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
1754 || ( pMixedCtx->reg.Attr.n.u1Granularity \
1755 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
1756 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
1757 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", pMixedCtx->reg.u32Limit, \
1758 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
1759
1760 HMSVM_ASSERT_SEG_GRANULARITY(cs);
1761 HMSVM_ASSERT_SEG_GRANULARITY(ss);
1762 HMSVM_ASSERT_SEG_GRANULARITY(ds);
1763 HMSVM_ASSERT_SEG_GRANULARITY(es);
1764 HMSVM_ASSERT_SEG_GRANULARITY(fs);
1765 HMSVM_ASSERT_SEG_GRANULARITY(gs);
1766
1767# undef HMSVM_ASSERT_SEL_GRANULARITY
1768#endif
1769
1770 /*
1771 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
1772 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
1773 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
1774 * See AMD spec. 15.5.1 "Basic operation".
1775 */
1776 Assert(!(pVmcb->guest.u8CPL & ~0x3));
1777 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
1778
1779 /*
1780 * Guest Descriptor-Table registers.
1781 */
1782 HMSVM_SAVE_SEG_REG(TR, tr);
1783 HMSVM_SAVE_SEG_REG(LDTR, ldtr);
1784 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
1785 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
1786
1787 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
1788 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
1789
1790 /*
1791 * Guest Debug registers.
1792 */
1793 if (!CPUMIsHyperDebugStateActive(pVCpu))
1794 {
1795 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
1796 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
1797 }
1798 else
1799 {
1800 Assert(pVmcb->guest.u64DR7 == CPUMGetHyperDR7(pVCpu));
1801 CPUMSetHyperDR6(pVCpu, pVmcb->guest.u64DR6);
1802 }
1803
1804 /*
1805 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
1806 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
1807 */
1808 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
1809 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
1810 {
1811 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
1812 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
1813 }
1814}
1815
1816
1817/**
1818 * Does the necessary state syncing before doing a longjmp to ring-3.
1819 *
1820 * @param pVM Pointer to the VM.
1821 * @param pVCpu Pointer to the VMCPU.
1822 * @param pCtx Pointer to the guest-CPU context.
1823 * @param rcExit The reason for exiting to ring-3. Can be
1824 * VINF_VMM_UNKNOWN_RING3_CALL.
1825 *
1826 * @remarks No-long-jmp zone!!!
1827 */
1828static void hmR0SvmLongJmpToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
1829{
1830 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1831 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1832
1833 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
1834 if (CPUMIsGuestFPUStateActive(pVCpu))
1835 {
1836 CPUMR0SaveGuestFPU(pVM, pVCpu, pCtx);
1837 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
1838 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
1839 }
1840
1841 /*
1842 * Restore host debug registers if necessary and resync on next R0 reentry.
1843 */
1844#ifdef VBOX_STRICT
1845 if (CPUMIsHyperDebugStateActive(pVCpu))
1846 {
1847 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1848 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
1849 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
1850 }
1851#endif
1852 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */))
1853 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
1854 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1855 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1856
1857 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
1858 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
1859 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
1860 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
1861 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1862
1863 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
1864}
1865
1866
1867/**
1868 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
1869 * any remaining host state) before we longjump to ring-3 and possibly get
1870 * preempted.
1871 *
1872 * @param pVCpu Pointer to the VMCPU.
1873 * @param enmOperation The operation causing the ring-3 longjump.
1874 * @param pvUser The user argument (pointer to the possibly
1875 * out-of-date guest-CPU context).
1876 *
1877 * @remarks Must never be called with @a enmOperation ==
1878 * VMMCALLRING3_VM_R0_ASSERTION.
1879 */
1880DECLCALLBACK(void) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
1881{
1882 /* VMMRZCallRing3() already makes sure we never get called as a result of an longjmp due to an assertion, */
1883 Assert(pVCpu);
1884 Assert(pvUser);
1885 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1886 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1887
1888 VMMRZCallRing3Disable(pVCpu);
1889 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1890 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
1891 hmR0SvmLongJmpToRing3(pVCpu->CTX_SUFF(pVM), pVCpu, (PCPUMCTX)pvUser, VINF_VMM_UNKNOWN_RING3_CALL);
1892 VMMRZCallRing3Enable(pVCpu);
1893}
1894
1895
1896/**
1897 * An action requires us to go back to ring-3. This function does the necessary
1898 * steps before we can safely return to ring-3. This is not the same as longjmps
1899 * to ring-3, this is voluntary.
1900 *
1901 * @param pVM Pointer to the VM.
1902 * @param pVCpu Pointer to the VMCPU.
1903 * @param pCtx Pointer to the guest-CPU context.
1904 * @param rcExit The reason for exiting to ring-3. Can be
1905 * VINF_VMM_UNKNOWN_RING3_CALL.
1906 */
1907static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
1908{
1909 Assert(pVM);
1910 Assert(pVCpu);
1911 Assert(pCtx);
1912 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1913
1914 if (RT_UNLIKELY(rcExit == VERR_SVM_INVALID_GUEST_STATE))
1915 {
1916 /* We don't need to do any syncing here, we're not going to come back to execute anything again. */
1917 return;
1918 }
1919
1920 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
1921 VMMRZCallRing3Disable(pVCpu);
1922 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
1923
1924 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
1925 if (pVCpu->hm.s.Event.fPending)
1926 {
1927 hmR0SvmPendingEventToTrpmTrap(pVCpu);
1928 Assert(!pVCpu->hm.s.Event.fPending);
1929 }
1930
1931 /* Sync. the guest state. */
1932 hmR0SvmLongJmpToRing3(pVM, pVCpu, pCtx, rcExit);
1933 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1934
1935 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
1936 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
1937 | CPUM_CHANGED_LDTR
1938 | CPUM_CHANGED_GDTR
1939 | CPUM_CHANGED_IDTR
1940 | CPUM_CHANGED_TR
1941 | CPUM_CHANGED_HIDDEN_SEL_REGS);
1942
1943 /* On our way back from ring-3 the following needs to be done. */
1944 /** @todo This can change with preemption hooks. */
1945 if (rcExit == VINF_EM_RAW_INTERRUPT)
1946 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
1947 else
1948 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
1949
1950 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
1951 VMMRZCallRing3Enable(pVCpu);
1952}
1953
1954
1955/**
1956 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
1957 * intercepts.
1958 *
1959 * @param pVCpu Pointer to the VMCPU.
1960 *
1961 * @remarks No-long-jump zone!!!
1962 */
1963static void hmR0SvmUpdateTscOffsetting(PVMCPU pVCpu)
1964{
1965 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1966 if (TMCpuTickCanUseRealTSC(pVCpu, &pVmcb->ctrl.u64TSCOffset))
1967 {
1968 uint64_t u64CurTSC = ASMReadTSC();
1969 if (u64CurTSC + pVmcb->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
1970 {
1971 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
1972 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
1973 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
1974 }
1975 else
1976 {
1977 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1978 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1979 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
1980 }
1981 }
1982 else
1983 {
1984 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1985 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1986 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
1987 }
1988
1989 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1990}
1991
1992
1993/**
1994 * Sets an event as a pending event to be injected into the guest.
1995 *
1996 * @param pVCpu Pointer to the VMCPU.
1997 * @param pEvent Pointer to the SVM event.
1998 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
1999 * page-fault.
2000 *
2001 * @remarks Statistics counter assumes this is a guest event being reflected to
2002 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
2003 */
2004DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
2005{
2006 Assert(!pVCpu->hm.s.Event.fPending);
2007 Assert(pEvent->n.u1Valid);
2008
2009 pVCpu->hm.s.Event.u64IntrInfo = pEvent->u;
2010 pVCpu->hm.s.Event.fPending = true;
2011 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
2012
2013 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2014 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2015
2016 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
2017}
2018
2019
2020/**
2021 * Injects an event into the guest upon VMRUN by updating the relevant field
2022 * in the VMCB.
2023 *
2024 * @param pVCpu Pointer to the VMCPU.
2025 * @param pVmcb Pointer to the guest VMCB.
2026 * @param pCtx Pointer to the guest-CPU context.
2027 * @param pEvent Pointer to the event.
2028 *
2029 * @remarks No-long-jump zone!!!
2030 * @remarks Requires CR0!
2031 */
2032DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
2033{
2034 pVmcb->ctrl.EventInject.u = pEvent->u;
2035 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
2036
2037 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2038 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2039}
2040
2041
2042
2043/**
2044 * Converts any TRPM trap into a pending HM event. This is typically used when
2045 * entering from ring-3 (not longjmp returns).
2046 *
2047 * @param pVCpu Pointer to the VMCPU.
2048 */
2049static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
2050{
2051 Assert(TRPMHasTrap(pVCpu));
2052 Assert(!pVCpu->hm.s.Event.fPending);
2053
2054 uint8_t uVector;
2055 TRPMEVENT enmTrpmEvent;
2056 RTGCUINT uErrCode;
2057 RTGCUINTPTR GCPtrFaultAddress;
2058 uint8_t cbInstr;
2059
2060 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
2061 AssertRC(rc);
2062
2063 SVMEVENT Event;
2064 Event.u = 0;
2065 Event.n.u1Valid = 1;
2066 Event.n.u8Vector = uVector;
2067
2068 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
2069 if (enmTrpmEvent == TRPM_TRAP)
2070 {
2071 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2072 switch (uVector)
2073 {
2074 case X86_XCPT_PF:
2075 case X86_XCPT_DF:
2076 case X86_XCPT_TS:
2077 case X86_XCPT_NP:
2078 case X86_XCPT_SS:
2079 case X86_XCPT_GP:
2080 case X86_XCPT_AC:
2081 {
2082 Event.n.u1ErrorCodeValid = 1;
2083 Event.n.u32ErrorCode = uErrCode;
2084 break;
2085 }
2086 }
2087 }
2088 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
2089 {
2090 if (uVector == X86_XCPT_NMI)
2091 Event.n.u3Type = SVM_EVENT_NMI;
2092 else
2093 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2094 }
2095 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
2096 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
2097 else
2098 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
2099
2100 rc = TRPMResetTrap(pVCpu);
2101 AssertRC(rc);
2102
2103 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
2104 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
2105
2106 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
2107 STAM_COUNTER_DEC(&pVCpu->hm.s.StatInjectPendingReflect);
2108}
2109
2110
2111/**
2112 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
2113 * AMD-V to execute any instruction.
2114 *
2115 * @param pvCpu Pointer to the VMCPU.
2116 */
2117static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
2118{
2119 Assert(pVCpu->hm.s.Event.fPending);
2120 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
2121
2122 SVMEVENT Event;
2123 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2124
2125 uint8_t uVector = Event.n.u8Vector;
2126 uint8_t uVectorType = Event.n.u3Type;
2127
2128 TRPMEVENT enmTrapType;
2129 switch (uVectorType)
2130 {
2131 case SVM_EVENT_EXTERNAL_IRQ:
2132 case SVM_EVENT_NMI:
2133 enmTrapType = TRPM_HARDWARE_INT;
2134 break;
2135 case SVM_EVENT_SOFTWARE_INT:
2136 enmTrapType = TRPM_SOFTWARE_INT;
2137 break;
2138 case SVM_EVENT_EXCEPTION:
2139 enmTrapType = TRPM_TRAP;
2140 break;
2141 default:
2142 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
2143 enmTrapType = TRPM_32BIT_HACK;
2144 break;
2145 }
2146
2147 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
2148
2149 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
2150 AssertRC(rc);
2151
2152 if (Event.n.u1ErrorCodeValid)
2153 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
2154
2155 if ( uVectorType == SVM_EVENT_EXCEPTION
2156 && uVector == X86_XCPT_PF)
2157 {
2158 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
2159 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
2160 }
2161 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
2162 {
2163 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
2164 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
2165 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
2166 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
2167 }
2168 pVCpu->hm.s.Event.fPending = false;
2169}
2170
2171
2172/**
2173 * Gets the guest's interrupt-shadow.
2174 *
2175 * @returns The guest's interrupt-shadow.
2176 * @param pVCpu Pointer to the VMCPU.
2177 * @param pCtx Pointer to the guest-CPU context.
2178 *
2179 * @remarks No-long-jump zone!!!
2180 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
2181 */
2182DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
2183{
2184 /*
2185 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
2186 * inhibit interrupts or clear any existing interrupt-inhibition.
2187 */
2188 uint32_t uIntrState = 0;
2189 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2190 {
2191 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2192 {
2193 /*
2194 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
2195 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
2196 */
2197 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2198 }
2199 else
2200 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
2201 }
2202 return uIntrState;
2203}
2204
2205
2206/**
2207 * Sets the virtual interrupt intercept control in the VMCB which
2208 * instructs AMD-V to cause a #VMEXIT as soon as the guest is in a state to
2209 * receive interrupts.
2210 *
2211 * @param pVmcb Pointer to the VMCB.
2212 */
2213DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
2214{
2215 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
2216 {
2217 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
2218 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
2219 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
2220 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
2221
2222 Log4(("Setting VINTR intercept\n"));
2223 }
2224}
2225
2226
2227/**
2228 * Injects any pending events into the guest if the guest is in a state to
2229 * receive them.
2230 *
2231 * @param pVCpu Pointer to the VMCPU.
2232 * @param pCtx Pointer to the guest-CPU context.
2233 */
2234static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2235{
2236 Assert(!TRPMHasTrap(pVCpu));
2237 Log4Func(("\n"));
2238
2239 const bool fIntShadow = !!hmR0SvmGetGuestIntrShadow(pVCpu, pCtx);
2240 const bool fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2241 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2242
2243 SVMEVENT Event;
2244 Event.u = 0;
2245 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2246 {
2247 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2248 Assert(Event.n.u1Valid);
2249 bool fInject = true;
2250 if ( Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
2251 && ( fBlockInt
2252 || fIntShadow))
2253 {
2254 fInject = false;
2255 }
2256 else if ( Event.n.u3Type == SVM_EVENT_NMI
2257 && fIntShadow)
2258 {
2259 fInject = false;
2260 }
2261
2262 if (fInject)
2263 {
2264 Log4(("Injecting pending HM event.\n"));
2265
2266 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2267 pVCpu->hm.s.Event.fPending = false;
2268
2269#ifdef VBOX_WITH_STATISTICS
2270 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2271 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2272 else
2273 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2274#endif
2275 }
2276 else
2277 hmR0SvmSetVirtIntrIntercept(pVmcb);
2278 } /** @todo SMI. SMIs take priority over NMIs. */
2279 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2280 {
2281 if (!fIntShadow)
2282 {
2283 Log4(("Injecting NMI\n"));
2284
2285 Event.n.u1Valid = 1;
2286 Event.n.u8Vector = X86_XCPT_NMI;
2287 Event.n.u3Type = SVM_EVENT_NMI;
2288
2289 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2290 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2291
2292 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2293 }
2294 else
2295 hmR0SvmSetVirtIntrIntercept(pVmcb);
2296 }
2297 else if (VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)))
2298 {
2299 /* Check if there are guest external interrupts (PIC/APIC) pending and inject them, if the guest can receive them. */
2300 if ( !fBlockInt
2301 && !fIntShadow)
2302 {
2303 uint8_t u8Interrupt;
2304 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2305 if (RT_SUCCESS(rc))
2306 {
2307 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2308
2309 Event.n.u1Valid = 1;
2310 Event.n.u8Vector = u8Interrupt;
2311 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2312
2313 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2314 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2315 }
2316 else
2317 {
2318 /** @todo Does this actually happen? If not turn it into an assertion. */
2319 Assert(!VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
2320 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2321 }
2322 }
2323 else
2324 hmR0SvmSetVirtIntrIntercept(pVmcb);
2325 }
2326
2327 /* Update the guest interrupt shadow in the VMCB. */
2328 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2329}
2330
2331
2332/**
2333 * Reports world-switch error and dumps some useful debug info.
2334 *
2335 * @param pVM Pointer to the VM.
2336 * @param pVCpu Pointer to the VMCPU.
2337 * @param rcVMRun The return code from VMRUN (or
2338 * VERR_SVM_INVALID_GUEST_STATE for invalid
2339 * guest-state).
2340 * @param pCtx Pointer to the guest-CPU context.
2341 */
2342static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2343{
2344 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2345 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2346
2347 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2348 {
2349 HMDumpRegs(pVM, pVCpu, pCtx);
2350#ifdef VBOX_STRICT
2351 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2352 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2353 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2354 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2355 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2356 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2357 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2358 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2359 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2360 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2361 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2362
2363 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2364 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2365 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2366
2367 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2368 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2369 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2370 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2371 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2372 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2373 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2374 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2375 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2376 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2377
2378 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2379 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2380 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2381 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2382 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2383 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2384 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2385 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2386 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2387 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2388 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2389 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2390 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2391 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2392 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2393 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2394 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2395
2396 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2397 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2398
2399 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2400 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2401 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2402 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2403 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2404 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2405 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2406 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2407 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2408 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2409 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2410 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2411 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2412 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2413 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2414 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2415 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2416 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2417 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2418 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2419
2420 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2421 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2422
2423 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2424 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2425 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2426 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2427
2428 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2429 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2430
2431 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2432 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2433 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2434 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2435
2436 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2437 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2438 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2439 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2440 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2441 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2442 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2443
2444 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2445 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2446 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2447 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2448
2449 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2450 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2451 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2452
2453 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2454 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2455 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2456 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2457 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2458 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2459 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2460 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2461 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2462 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2463 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2464 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2465#endif
2466 }
2467 else
2468 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2469}
2470
2471
2472/**
2473 * Check per-VM and per-VCPU force flag actions that require us to go back to
2474 * ring-3 for one reason or another.
2475 *
2476 * @returns VBox status code (information status code included).
2477 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2478 * ring-3.
2479 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2480 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2481 * interrupts)
2482 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2483 * all EMTs to be in ring-3.
2484 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2485 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2486 * to the EM loop.
2487 *
2488 * @param pVM Pointer to the VM.
2489 * @param pVCpu Pointer to the VMCPU.
2490 * @param pCtx Pointer to the guest-CPU context.
2491 */
2492static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2493{
2494 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2495
2496 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
2497 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2498 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
2499
2500 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
2501 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2502 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
2503 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2504 {
2505 /* Pending PGM C3 sync. */
2506 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2507 {
2508 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2509 if (rc != VINF_SUCCESS)
2510 {
2511 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2512 return rc;
2513 }
2514 }
2515
2516 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2517 /* -XXX- what was that about single stepping? */
2518 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2519 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2520 {
2521 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2522 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2523 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2524 return rc;
2525 }
2526
2527 /* Pending VM request packets, such as hardware interrupts. */
2528 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2529 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2530 {
2531 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2532 return VINF_EM_PENDING_REQUEST;
2533 }
2534
2535 /* Pending PGM pool flushes. */
2536 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2537 {
2538 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2539 return VINF_PGM_POOL_FLUSH_PENDING;
2540 }
2541
2542 /* Pending DMA requests. */
2543 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2544 {
2545 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2546 return VINF_EM_RAW_TO_R3;
2547 }
2548 }
2549
2550 return VINF_SUCCESS;
2551}
2552
2553
2554/**
2555 * Does the preparations before executing guest code in AMD-V.
2556 *
2557 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2558 * recompiler. We must be cautious what we do here regarding committing
2559 * guest-state information into the the VMCB assuming we assuredly execute the
2560 * guest in AMD-V. If we fall back to the recompiler after updating the VMCB and
2561 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2562 * that the recompiler can (and should) use them when it resumes guest
2563 * execution. Otherwise such operations must be done when we can no longer
2564 * exit to ring-3.
2565 *
2566 * @returns VBox status code (informational status codes included).
2567 * @retval VINF_SUCCESS if we can proceed with running the guest.
2568 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2569 *
2570 * @param pVM Pointer to the VM.
2571 * @param pVCpu Pointer to the VMCPU.
2572 * @param pCtx Pointer to the guest-CPU context.
2573 * @param pSvmTransient Pointer to the SVM transient structure.
2574 */
2575DECLINLINE(int) hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2576{
2577 /* Check force flag actions that might require us to go back to ring-3. */
2578 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2579 if (rc != VINF_SUCCESS)
2580 return rc;
2581
2582#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2583 /* We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.) */
2584 pSvmTransient->uEFlags = ASMIntDisableFlags();
2585 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2586 {
2587 ASMSetFlags(pSvmTransient->uEFlags);
2588 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2589 /* Don't use VINF_EM_RAW_INTERRUPT_HYPER as we can't assume the host does kernel preemption. Maybe some day? */
2590 return VINF_EM_RAW_INTERRUPT;
2591 }
2592 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2593 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2594#endif
2595
2596 /* Convert any pending TRPM traps to HM events for injection. */
2597 /** @todo Optimization: move this before disabling interrupts, restore state
2598 * using pVmcb->ctrl.EventInject.u. */
2599 if (TRPMHasTrap(pVCpu))
2600 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2601
2602 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
2603
2604 return VINF_SUCCESS;
2605}
2606
2607
2608/**
2609 * Prepares to run guest code in AMD-V and we've committed to doing so. This
2610 * means there is no backing out to ring-3 or anywhere else at this
2611 * point.
2612 *
2613 * @param pVM Pointer to the VM.
2614 * @param pVCpu Pointer to the VMCPU.
2615 * @param pCtx Pointer to the guest-CPU context.
2616 * @param pSvmTransient Pointer to the SVM transient structure.
2617 *
2618 * @remarks Called with preemption disabled.
2619 * @remarks No-long-jump zone!!!
2620 */
2621DECLINLINE(void) hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2622{
2623 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2624 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2625
2626#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2627 /** @todo I don't see the point of this, VMMR0EntryFast() already disables interrupts for the entire period. */
2628 pSvmTransient->uEFlags = ASMIntDisableFlags();
2629 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2630#endif
2631
2632 /*
2633 * Re-enable nested paging (automatically disabled on every VM-exit). See AMD spec. 15.25.3 "Enabling Nested Paging".
2634 * We avoid changing the corresponding VMCB Clean Bit as we're not changing it to a different value since the previous run.
2635 */
2636 /** @todo The above assumption could be wrong. It's not documented what
2637 * should be done wrt to the VMCB Clean Bit, but we'll find out the
2638 * hard way. */
2639 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2640 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
2641
2642#ifdef HMSVM_SYNC_FULL_GUEST_STATE
2643 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_ALL_GUEST;
2644#endif
2645
2646 /* Load the guest state. */
2647 int rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
2648 AssertRC(rc);
2649 AssertMsg(!pVCpu->hm.s.fContextUseFlags, ("fContextUseFlags =%#x\n", pVCpu->hm.s.fContextUseFlags));
2650 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
2651
2652 /* If VMCB Clean Bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
2653 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
2654 pVmcb->ctrl.u64VmcbCleanBits = 0;
2655
2656 /*
2657 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
2658 * so we can update it on the way back if the guest changed the TPR.
2659 */
2660 if (pVCpu->hm.s.svm.fSyncVTpr)
2661 {
2662 if (pVM->hm.s.fTPRPatchingActive)
2663 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
2664 else
2665 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
2666 }
2667
2668 /* Setup TSC offsetting. */
2669 if ( pSvmTransient->fUpdateTscOffsetting
2670 || HMR0GetCurrentCpu()->idCpu != pVCpu->hm.s.idLastCpu)
2671 {
2672 hmR0SvmUpdateTscOffsetting(pVCpu);
2673 pSvmTransient->fUpdateTscOffsetting = false;
2674 }
2675
2676 /* Flush the appropriate tagged-TLB entries. */
2677 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB-shootdowns, set this across the world switch. */
2678 hmR0SvmFlushTaggedTlb(pVCpu);
2679 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
2680
2681 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
2682
2683 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
2684 to start executing. */
2685
2686 /*
2687 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
2688 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
2689 *
2690 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
2691 */
2692 pSvmTransient->fRestoreTscAuxMsr = false;
2693 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2694 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
2695 {
2696 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
2697 uint64_t u64GuestTscAux = 0;
2698 int rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
2699 AssertRC(rc2);
2700 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
2701 {
2702 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
2703 pSvmTransient->fRestoreTscAuxMsr = true;
2704 }
2705 }
2706}
2707
2708
2709/**
2710 * Wrapper for running the guest code in AMD-V.
2711 *
2712 * @returns VBox strict status code.
2713 * @param pVM Pointer to the VM.
2714 * @param pVCpu Pointer to the VMCPU.
2715 * @param pCtx Pointer to the guest-CPU context.
2716 *
2717 * @remarks No-long-jump zone!!!
2718 */
2719DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2720{
2721 /*
2722 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
2723 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
2724 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
2725 */
2726#ifdef VBOX_WITH_KERNEL_USING_XMM
2727 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
2728 pVCpu->hm.s.svm.pfnVMRun);
2729#else
2730 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
2731#endif
2732}
2733
2734
2735/**
2736 * Performs some essential restoration of state after running guest code in
2737 * AMD-V.
2738 *
2739 * @param pVM Pointer to the VM.
2740 * @param pVCpu Pointer to the VMCPU.
2741 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
2742 * out-of-sync. Make sure to update the required fields
2743 * before using them.
2744 * @param pSvmTransient Pointer to the SVM transient structure.
2745 * @param rcVMRun Return code of VMRUN.
2746 *
2747 * @remarks Called with interrupts disabled.
2748 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
2749 * unconditionally when it is safe to do so.
2750 */
2751DECLINLINE(void) hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
2752{
2753 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2754
2755 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB-shootdowns. */
2756 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for TLB-shootdowns. */
2757
2758 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2759 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
2760
2761 if (pSvmTransient->fRestoreTscAuxMsr)
2762 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
2763
2764 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
2765 {
2766 /** @todo Find a way to fix hardcoding a guestimate. */
2767 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset - 0x400);
2768 }
2769
2770 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
2771 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
2772 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2773
2774 Assert(!(ASMGetFlags() & X86_EFL_IF));
2775 ASMSetFlags(pSvmTransient->uEFlags); /* Enable interrupts. */
2776
2777 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pMixedCtx);
2778 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
2779
2780 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
2781 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
2782 {
2783 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
2784 return;
2785 }
2786
2787 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
2788 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
2789 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
2790
2791 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
2792 {
2793 if (pVCpu->hm.s.svm.fSyncVTpr)
2794 {
2795 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
2796 if ( pVM->hm.s.fTPRPatchingActive
2797 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
2798 {
2799 int rc = PDMApicSetTPR(pVCpu, pMixedCtx->msrLSTAR & 0xff);
2800 AssertRC(rc);
2801 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
2802 }
2803 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
2804 {
2805 int rc = PDMApicSetTPR(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
2806 AssertRC(rc);
2807 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
2808 }
2809 }
2810 }
2811}
2812
2813
2814/**
2815 * Runs the guest code using AMD-V.
2816 *
2817 * @returns VBox status code.
2818 * @param pVM Pointer to the VM.
2819 * @param pVCpu Pointer to the VMCPU.
2820 * @param pCtx Pointer to the guest-CPU context.
2821 */
2822VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2823{
2824 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2825 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2826
2827 SVMTRANSIENT SvmTransient;
2828 SvmTransient.fUpdateTscOffsetting = true;
2829 uint32_t cLoops = 0;
2830 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2831 int rc = VERR_INTERNAL_ERROR_5;
2832
2833 for (;; cLoops++)
2834 {
2835 Assert(!HMR0SuspendPending());
2836 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
2837 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
2838 (unsigned)RTMpCpuId(), cLoops));
2839
2840 /* Preparatory work for running guest code, this may return to ring-3 for some last minute updates. */
2841 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
2842 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
2843 if (rc != VINF_SUCCESS)
2844 break;
2845
2846 /*
2847 * No longjmps to ring-3 from this point on!!!
2848 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
2849 * This also disables flushing of the R0-logger instance (if any).
2850 */
2851 VMMRZCallRing3Disable(pVCpu);
2852 VMMRZCallRing3RemoveNotification(pVCpu);
2853 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
2854
2855 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
2856
2857 /*
2858 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
2859 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
2860 */
2861 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
2862 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
2863 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
2864 {
2865 if (rc == VINF_SUCCESS)
2866 rc = VERR_SVM_INVALID_GUEST_STATE;
2867 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
2868 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
2869 return rc;
2870 }
2871
2872 /* Handle the #VMEXIT. */
2873 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
2874 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
2875 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
2876 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
2877 if (rc != VINF_SUCCESS)
2878 break;
2879 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
2880 {
2881 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
2882 rc = VINF_EM_RAW_INTERRUPT;
2883 break;
2884 }
2885 }
2886
2887 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
2888 if (rc == VERR_EM_INTERPRETER)
2889 rc = VINF_EM_RAW_EMULATE_INSTR;
2890 else if (rc == VINF_EM_RESET)
2891 rc = VINF_EM_TRIPLE_FAULT;
2892 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
2893 return rc;
2894}
2895
2896
2897/**
2898 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
2899 *
2900 * @returns VBox status code (informational status codes included).
2901 * @param pVCpu Pointer to the VMCPU.
2902 * @param pCtx Pointer to the guest-CPU context.
2903 * @param pSvmTransient Pointer to the SVM transient structure.
2904 */
2905DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2906{
2907 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
2908 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
2909
2910 /*
2911 * The ordering of the case labels is based on most-frequently-occurring VM-exits for most guests under
2912 * normal workloads (for some definition of "normal").
2913 */
2914 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
2915 switch (pSvmTransient->u64ExitCode)
2916 {
2917 case SVM_EXIT_NPF:
2918 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
2919
2920 case SVM_EXIT_IOIO:
2921 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
2922
2923 case SVM_EXIT_RDTSC:
2924 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
2925
2926 case SVM_EXIT_RDTSCP:
2927 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
2928
2929 case SVM_EXIT_CPUID:
2930 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
2931
2932 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
2933 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
2934
2935 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
2936 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
2937
2938 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
2939 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
2940
2941 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
2942 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
2943
2944 case SVM_EXIT_MONITOR:
2945 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
2946
2947 case SVM_EXIT_MWAIT:
2948 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
2949
2950 case SVM_EXIT_HLT:
2951 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
2952
2953 case SVM_EXIT_READ_CR0:
2954 case SVM_EXIT_READ_CR3:
2955 case SVM_EXIT_READ_CR4:
2956 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
2957
2958 case SVM_EXIT_WRITE_CR0:
2959 case SVM_EXIT_WRITE_CR3:
2960 case SVM_EXIT_WRITE_CR4:
2961 case SVM_EXIT_WRITE_CR8:
2962 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
2963
2964 case SVM_EXIT_VINTR:
2965 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
2966
2967 case SVM_EXIT_INTR:
2968 case SVM_EXIT_FERR_FREEZE:
2969 case SVM_EXIT_NMI:
2970 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
2971
2972 case SVM_EXIT_MSR:
2973 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
2974
2975 case SVM_EXIT_INVLPG:
2976 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
2977
2978 case SVM_EXIT_WBINVD:
2979 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
2980
2981 case SVM_EXIT_INVD:
2982 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
2983
2984 case SVM_EXIT_RDPMC:
2985 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
2986
2987 default:
2988 {
2989 switch (pSvmTransient->u64ExitCode)
2990 {
2991 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2992 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
2993 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
2994 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2995 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
2996
2997 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2998 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
2999 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3000 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3001 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3002
3003 case SVM_EXIT_TASK_SWITCH:
3004 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3005
3006 case SVM_EXIT_VMMCALL:
3007 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3008
3009 case SVM_EXIT_SHUTDOWN:
3010 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3011
3012 case SVM_EXIT_SMI:
3013 case SVM_EXIT_INIT:
3014 {
3015 /*
3016 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3017 * we want to know about it so log the exit code and bail.
3018 */
3019 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3020 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3021 return VERR_SVM_UNEXPECTED_EXIT;
3022 }
3023
3024 case SVM_EXIT_INVLPGA:
3025 case SVM_EXIT_RSM:
3026 case SVM_EXIT_VMRUN:
3027 case SVM_EXIT_VMLOAD:
3028 case SVM_EXIT_VMSAVE:
3029 case SVM_EXIT_STGI:
3030 case SVM_EXIT_CLGI:
3031 case SVM_EXIT_SKINIT:
3032 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3033
3034#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3035 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3036 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3037 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3038 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3039 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3040 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3041 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3042 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3043 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3044 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3045 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3046 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3047 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3048 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3049 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3050 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3051 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3052 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3053 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3054
3055 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3056 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3057 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3058 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3059 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3060 {
3061 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3062 SVMEVENT Event;
3063 Event.u = 0;
3064 Event.n.u1Valid = 1;
3065 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3066 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3067
3068 switch (Event.n.u8Vector)
3069 {
3070 case X86_XCPT_DE:
3071 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3072 break;
3073
3074 case X86_XCPT_BP:
3075 /** Saves the wrong EIP on the stack (pointing to the int3) instead of the
3076 * next instruction. */
3077 /** @todo Investigate this later. */
3078 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
3079 break;
3080
3081 case X86_XCPT_UD:
3082 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
3083 break;
3084
3085 case X86_XCPT_NP:
3086 Event.n.u1ErrorCodeValid = 1;
3087 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3088 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3089 break;
3090
3091 case X86_XCPT_SS:
3092 Event.n.u1ErrorCodeValid = 1;
3093 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3094 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3095 break;
3096
3097 case X86_XCPT_GP:
3098 Event.n.u1ErrorCodeValid = 1;
3099 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3100 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3101 break;
3102
3103 default:
3104 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3105 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3106 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3107 }
3108
3109 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3110 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3111 return VINF_SUCCESS;
3112 }
3113#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3114
3115 default:
3116 {
3117 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3118 pVCpu->hm.s.u32HMError = u32ExitCode;
3119 return VERR_SVM_UNKNOWN_EXIT;
3120 }
3121 }
3122 }
3123 }
3124 return VERR_INTERNAL_ERROR_5; /* Should never happen. */
3125}
3126
3127
3128#ifdef DEBUG
3129/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3130# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3131 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3132
3133# define HMSVM_ASSERT_PREEMPT_CPUID() \
3134 do \
3135 { \
3136 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3137 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3138 } while (0)
3139
3140# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3141 do { \
3142 AssertPtr(pVCpu); \
3143 AssertPtr(pCtx); \
3144 AssertPtr(pSvmTransient); \
3145 Assert(ASMIntAreEnabled()); \
3146 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
3147 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3148 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)); \
3149 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
3150 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3151 HMSVM_ASSERT_PREEMPT_CPUID(); \
3152 } while (0)
3153#else /* Release builds */
3154# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { } while(0)
3155#endif
3156
3157
3158/**
3159 * Worker for hmR0SvmInterpretInvlpg().
3160 *
3161 * @return VBox status code.
3162 * @param pVCpu Pointer to the VMCPU.
3163 * @param pCpu Pointer to the disassembler state.
3164 * @param pRegFrame Pointer to the register frame.
3165 */
3166static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
3167{
3168 DISQPVPARAMVAL Param1;
3169 RTGCPTR GCPtrPage;
3170
3171 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3172 if (RT_FAILURE(rc))
3173 return VERR_EM_INTERPRETER;
3174
3175 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3176 || Param1.type == DISQPV_TYPE_ADDRESS)
3177 {
3178 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3179 return VERR_EM_INTERPRETER;
3180
3181 GCPtrPage = Param1.val.val64;
3182 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, pRegFrame, GCPtrPage);
3183 rc = VBOXSTRICTRC_VAL(rc2);
3184 }
3185 else
3186 {
3187 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3188 rc = VERR_EM_INTERPRETER;
3189 }
3190
3191 return rc;
3192}
3193
3194
3195/**
3196 * Interprets INVLPG.
3197 *
3198 * @returns VBox status code.
3199 * @retval VINF_* Scheduling instructions.
3200 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3201 * @retval VERR_* Fatal errors.
3202 *
3203 * @param pVM Pointer to the VM.
3204 * @param pRegFrame Pointer to the register frame.
3205 *
3206 * @remarks Updates the RIP if the instruction was executed successfully.
3207 */
3208static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
3209{
3210 /* Only allow 32 & 64 bit code. */
3211 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3212 {
3213 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3214 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3215 if ( RT_SUCCESS(rc)
3216 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3217 {
3218 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
3219 if (RT_SUCCESS(rc))
3220 pRegFrame->rip += pDis->cbInstr;
3221 return rc;
3222 }
3223 else
3224 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3225 }
3226 return VERR_EM_INTERPRETER;
3227}
3228
3229
3230/**
3231 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
3232 *
3233 * @param pVCpu Pointer to the VMCPU.
3234 */
3235DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
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_UD;
3242 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3243}
3244
3245
3246/**
3247 * Sets a debug (#DB) exception as pending-for-injection into the VM.
3248 *
3249 * @param pVCpu Pointer to the VMCPU.
3250 */
3251DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3252{
3253 SVMEVENT Event;
3254 Event.u = 0;
3255 Event.n.u1Valid = 1;
3256 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3257 Event.n.u8Vector = X86_XCPT_DB;
3258 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3259}
3260
3261
3262/**
3263 * Sets a page fault (#PF) exception as pending-for-injection into the VM.
3264 *
3265 * @param pVCpu Pointer to the VMCPU.
3266 * @param pCtx Pointer to the guest-CPU context.
3267 * @param u32ErrCode The error-code for the page-fault.
3268 * @param uFaultAddress The page fault address (CR2).
3269 *
3270 * @remarks This updates the guest CR2 with @a uFaultAddress!
3271 */
3272DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3273{
3274 SVMEVENT Event;
3275 Event.u = 0;
3276 Event.n.u1Valid = 1;
3277 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3278 Event.n.u8Vector = X86_XCPT_PF;
3279 Event.n.u1ErrorCodeValid = 1;
3280 Event.n.u32ErrorCode = u32ErrCode;
3281
3282 /* Update CR2 of the guest. */
3283 if (pCtx->cr2 != uFaultAddress)
3284 {
3285 pCtx->cr2 = uFaultAddress;
3286 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR2;
3287 }
3288
3289 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3290}
3291
3292
3293/**
3294 * Sets a device-not-available (#NM) exception as pending-for-injection into the
3295 * VM.
3296 *
3297 * @param pVCpu Pointer to the VMCPU.
3298 */
3299DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3300{
3301 SVMEVENT Event;
3302 Event.u = 0;
3303 Event.n.u1Valid = 1;
3304 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3305 Event.n.u8Vector = X86_XCPT_NM;
3306 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3307}
3308
3309
3310/**
3311 * Sets a math-fault (#MF) exception as pending-for-injection into the VM.
3312 *
3313 * @param pVCpu Pointer to the VMCPU.
3314 */
3315DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3316{
3317 SVMEVENT Event;
3318 Event.u = 0;
3319 Event.n.u1Valid = 1;
3320 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3321 Event.n.u8Vector = X86_XCPT_MF;
3322 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3323}
3324
3325
3326/**
3327 * Sets a double fault (#DF) exception as pending-for-injection into the VM.
3328 *
3329 * @param pVCpu Pointer to the VMCPU.
3330 */
3331DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3332{
3333 SVMEVENT Event;
3334 Event.u = 0;
3335 Event.n.u1Valid = 1;
3336 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3337 Event.n.u8Vector = X86_XCPT_DF;
3338 Event.n.u1ErrorCodeValid = 1;
3339 Event.n.u32ErrorCode = 0;
3340 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3341}
3342
3343
3344/**
3345 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3346 * guests. This simply looks up the patch record at EIP and does the required.
3347 *
3348 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3349 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3350 * TPR). See hmR3ReplaceTprInstr() for the details.
3351 *
3352 * @returns VBox status code.
3353 * @param pVM Pointer to the VM.
3354 * @param pVCpu Pointer to the VMCPU.
3355 * @param pCtx Pointer to the guest-CPU context.
3356 */
3357static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3358{
3359 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3360 for (;;)
3361 {
3362 bool fPending;
3363 uint8_t u8Tpr;
3364
3365 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
3366 if (!pPatch)
3367 break;
3368
3369 switch (pPatch->enmType)
3370 {
3371 case HMTPRINSTR_READ:
3372 {
3373 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
3374 AssertRC(rc);
3375
3376 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
3377 AssertRC(rc);
3378 pCtx->rip += pPatch->cbOp;
3379 break;
3380 }
3381
3382 case HMTPRINSTR_WRITE_REG:
3383 case HMTPRINSTR_WRITE_IMM:
3384 {
3385 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
3386 {
3387 uint32_t u32Val;
3388 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
3389 AssertRC(rc);
3390 u8Tpr = u32Val;
3391 }
3392 else
3393 u8Tpr = (uint8_t)pPatch->uSrcOperand;
3394
3395 int rc2 = PDMApicSetTPR(pVCpu, u8Tpr);
3396 AssertRC(rc2);
3397 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3398
3399 pCtx->rip += pPatch->cbOp;
3400 break;
3401 }
3402
3403 default:
3404 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
3405 pVCpu->hm.s.u32HMError = pPatch->enmType;
3406 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
3407 }
3408 }
3409
3410 return VINF_SUCCESS;
3411}
3412
3413/**
3414 * Determines if an exception is a contributory exception. Contributory
3415 * exceptions are ones which can cause double-faults. Page-fault is
3416 * intentionally not included here as it's a conditional contributory exception.
3417 *
3418 * @returns true if the exception is contributory, false otherwise.
3419 * @param uVector The exception vector.
3420 */
3421DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
3422{
3423 switch (uVector)
3424 {
3425 case X86_XCPT_GP:
3426 case X86_XCPT_SS:
3427 case X86_XCPT_NP:
3428 case X86_XCPT_TS:
3429 case X86_XCPT_DE:
3430 return true;
3431 default:
3432 break;
3433 }
3434 return false;
3435}
3436
3437
3438/**
3439 * Handle a condition that occurred while delivering an event through the guest
3440 * IDT.
3441 *
3442 * @returns VBox status code (informational error codes included).
3443 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
3444 * @retval VINF_HM_DOUBLE_FAULT if a #DF condition was detected and we ought to
3445 * continue execution of the guest which will delivery the #DF.
3446 * @retval VINF_EM_RESET if we detected a triple-fault condition.
3447 *
3448 * @param pVCpu Pointer to the VMCPU.
3449 * @param pCtx Pointer to the guest-CPU context.
3450 * @param pSvmTransient Pointer to the SVM transient structure.
3451 *
3452 * @remarks No-long-jump zone!!!
3453 */
3454static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3455{
3456 int rc = VINF_SUCCESS;
3457 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3458
3459 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
3460 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
3461 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
3462 {
3463 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
3464
3465 typedef enum
3466 {
3467 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
3468 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
3469 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
3470 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
3471 } SVMREFLECTXCPT;
3472
3473 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
3474 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
3475 {
3476 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
3477 {
3478 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
3479
3480#ifdef VBOX_STRICT
3481 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
3482 && uExitVector == X86_XCPT_PF)
3483 {
3484 Log4(("IDT: Contributory #PF uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
3485 }
3486#endif
3487 if ( uExitVector == X86_XCPT_PF
3488 && uIdtVector == X86_XCPT_PF)
3489 {
3490 pSvmTransient->fVectoringPF = true;
3491 Log4(("IDT: Vectoring #PF uCR2=%#RX64\n", pCtx->cr2));
3492 }
3493 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
3494 && hmR0SvmIsContributoryXcpt(uExitVector)
3495 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
3496 || uIdtVector == X86_XCPT_PF))
3497 {
3498 enmReflect = SVMREFLECTXCPT_DF;
3499 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntrInfo,
3500 uIdtVector, uExitVector));
3501 }
3502 else if (uIdtVector == X86_XCPT_DF)
3503 {
3504 enmReflect = SVMREFLECTXCPT_TF;
3505 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntrInfo,
3506 uIdtVector, uExitVector));
3507 }
3508 else
3509 enmReflect = SVMREFLECTXCPT_XCPT;
3510 }
3511 else
3512 {
3513 /*
3514 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
3515 * exception to the guest after handling the VM-exit.
3516 */
3517 enmReflect = SVMREFLECTXCPT_XCPT;
3518 }
3519 }
3520 else if (pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
3521 {
3522 /* Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
3523 enmReflect = SVMREFLECTXCPT_XCPT;
3524 }
3525
3526 switch (enmReflect)
3527 {
3528 case SVMREFLECTXCPT_XCPT:
3529 {
3530 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
3531 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
3532
3533 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
3534 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
3535 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
3536 break;
3537 }
3538
3539 case SVMREFLECTXCPT_DF:
3540 {
3541 hmR0SvmSetPendingXcptDF(pVCpu);
3542 rc = VINF_HM_DOUBLE_FAULT;
3543 break;
3544 }
3545
3546 case SVMREFLECTXCPT_TF:
3547 {
3548 rc = VINF_EM_RESET;
3549 break;
3550 }
3551
3552 default:
3553 Assert(rc == VINF_SUCCESS);
3554 break;
3555 }
3556 }
3557 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET);
3558 return rc;
3559}
3560
3561
3562/**
3563 * Advances the guest RIP in the if the NRIP_SAVE feature is supported by the
3564 * CPU, otherwise advances the RIP by @a cb bytes.
3565 *
3566 * @param pVCpu Pointer to the VMCPU.
3567 * @param pCtx Pointer to the guest-CPU context.
3568 * @param cb RIP increment value in bytes.
3569 *
3570 * @remarks Use this function only from #VMEXIT's where the NRIP value is valid
3571 * when NRIP_SAVE is supported by the CPU!
3572 */
3573DECLINLINE(void) hmR0SvmUpdateRip(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
3574{
3575 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
3576 {
3577 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3578 pCtx->rip = pVmcb->ctrl.u64NextRIP;
3579 }
3580 else
3581 pCtx->rip += cb;
3582}
3583
3584
3585/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
3586/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
3587/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
3588
3589/** @name VM-exit handlers.
3590 * @{
3591 */
3592
3593/**
3594 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
3595 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
3596 */
3597HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3598{
3599 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3600
3601 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
3602 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmi);
3603 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
3604 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
3605
3606 /*
3607 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
3608 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
3609 * interrupt it is until the host actually take the interrupt.
3610 *
3611 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
3612 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
3613 */
3614 return VINF_EM_RAW_INTERRUPT;
3615}
3616
3617
3618/**
3619 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
3620 */
3621HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3622{
3623 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3624
3625 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3626 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
3627 return VINF_SUCCESS;
3628}
3629
3630
3631/**
3632 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
3633 */
3634HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3635{
3636 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3637
3638 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3639 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
3640 return VINF_SUCCESS;
3641}
3642
3643
3644/**
3645 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
3646 */
3647HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3648{
3649 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3650 PVM pVM = pVCpu->CTX_SUFF(pVM);
3651 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3652 if (RT_LIKELY(rc == VINF_SUCCESS))
3653 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3654 else
3655 {
3656 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
3657 rc = VERR_EM_INTERPRETER;
3658 }
3659 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
3660 return rc;
3661}
3662
3663
3664/**
3665 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
3666 */
3667HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3668{
3669 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3670 PVM pVM = pVCpu->CTX_SUFF(pVM);
3671 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3672 if (RT_LIKELY(rc == VINF_SUCCESS))
3673 {
3674 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3675 pSvmTransient->fUpdateTscOffsetting = true;
3676 }
3677 else
3678 {
3679 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
3680 rc = VERR_EM_INTERPRETER;
3681 }
3682 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
3683 return rc;
3684}
3685
3686
3687/**
3688 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
3689 */
3690HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3691{
3692 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3693 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
3694 if (RT_LIKELY(rc == VINF_SUCCESS))
3695 {
3696 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3697 pSvmTransient->fUpdateTscOffsetting = true;
3698 }
3699 else
3700 {
3701 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
3702 rc = VERR_EM_INTERPRETER;
3703 }
3704 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
3705 return rc;
3706}
3707
3708
3709/**
3710 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
3711 */
3712HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3713{
3714 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3715 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3716 if (RT_LIKELY(rc == VINF_SUCCESS))
3717 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3718 else
3719 {
3720 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
3721 rc = VERR_EM_INTERPRETER;
3722 }
3723 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
3724 return rc;
3725}
3726
3727
3728/**
3729 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
3730 */
3731HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3732{
3733 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3734 PVM pVM = pVCpu->CTX_SUFF(pVM);
3735 Assert(!pVM->hm.s.fNestedPaging);
3736
3737 /** @todo Decode Assist. */
3738 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx)); /* Updates RIP if successful. */
3739 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
3740 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
3741 return rc;
3742}
3743
3744
3745/**
3746 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
3747 */
3748HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3749{
3750 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3751 hmR0SvmUpdateRip(pVCpu, pCtx, 1);
3752 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
3753 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
3754 return rc;
3755}
3756
3757
3758/**
3759 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
3760 */
3761HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3762{
3763 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3764 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3765 if (RT_LIKELY(rc == VINF_SUCCESS))
3766 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3767 else
3768 {
3769 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
3770 rc = VERR_EM_INTERPRETER;
3771 }
3772 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
3773 return rc;
3774}
3775
3776
3777/**
3778 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
3779 */
3780HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3781{
3782 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3783 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3784 int rc = VBOXSTRICTRC_VAL(rc2);
3785 if ( rc == VINF_EM_HALT
3786 || rc == VINF_SUCCESS)
3787 {
3788 hmR0SvmUpdateRip(pVCpu, pCtx, 3);
3789
3790 if ( rc == VINF_EM_HALT
3791 && EMShouldContinueAfterHalt(pVCpu, pCtx))
3792 {
3793 rc = VINF_SUCCESS;
3794 }
3795 }
3796 else
3797 {
3798 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
3799 rc = VERR_EM_INTERPRETER;
3800 }
3801 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
3802 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
3803 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
3804 return rc;
3805}
3806
3807
3808/**
3809 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
3810 * Conditional #VMEXIT.
3811 */
3812HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3813{
3814 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3815 return VINF_EM_RESET;
3816}
3817
3818
3819/**
3820 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
3821 */
3822HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3823{
3824 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3825
3826 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
3827
3828 /** @todo Decode Assist. */
3829 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3830 int rc = VBOXSTRICTRC_VAL(rc2);
3831 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
3832 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
3833 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
3834 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
3835 return rc;
3836}
3837
3838
3839/**
3840 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
3841 */
3842HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3843{
3844 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3845 /** @todo Decode Assist. */
3846 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3847 int rc = VBOXSTRICTRC_VAL(rc2);
3848 if (rc == VINF_SUCCESS)
3849 {
3850 /* RIP has been updated by EMInterpretInstruction(). */
3851 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
3852 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
3853 {
3854 case 0: /* CR0. */
3855 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
3856 break;
3857
3858 case 3: /* CR3. */
3859 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
3860 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
3861 break;
3862
3863 case 4: /* CR4. */
3864 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
3865 break;
3866
3867 case 8: /* CR8 (TPR). */
3868 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3869 break;
3870
3871 default:
3872 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x CRx=%#RX64\n",
3873 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
3874 break;
3875 }
3876 }
3877 else
3878 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3879 return rc;
3880}
3881
3882
3883/**
3884 * #VMEXIT handler for instructions that result in a #UD exception delivered to
3885 * the guest.
3886 */
3887HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3888{
3889 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3890 hmR0SvmSetPendingXcptUD(pVCpu);
3891 return VINF_SUCCESS;
3892}
3893
3894
3895/**
3896 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
3897 */
3898HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3899{
3900 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3901 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3902 PVM pVM = pVCpu->CTX_SUFF(pVM);
3903
3904 int rc;
3905 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
3906 {
3907 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
3908
3909 /* Handle TPR patching; intercepted LSTAR write. */
3910 if ( pVM->hm.s.fTPRPatchingActive
3911 && pCtx->ecx == MSR_K8_LSTAR)
3912 {
3913 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
3914 {
3915 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
3916 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
3917 AssertRC(rc2);
3918 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3919 }
3920 hmR0SvmUpdateRip(pVCpu, pCtx, 2);
3921 return VINF_SUCCESS;
3922 }
3923
3924 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
3925 {
3926 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3927 if (RT_LIKELY(rc == VINF_SUCCESS))
3928 pCtx->rip = pVmcb->ctrl.u64NextRIP;
3929 else
3930 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
3931 }
3932 else
3933 {
3934 VBOXSTRICTRC rcStrict = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3935 rc = VBOXSTRICTRC_VAL(rcStrict);
3936 if (RT_UNLIKELY(rc != VINF_SUCCESS))
3937 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
3938 /* RIP updated by EMInterpretInstruction(). */
3939 }
3940
3941 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
3942 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
3943 && pCtx->ecx <= MSR_IA32_X2APIC_END)
3944 {
3945 /* We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
3946 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
3947 EMInterpretWrmsr() changes it. */
3948 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3949 }
3950 else if (pCtx->ecx == MSR_K6_EFER)
3951 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_EFER_MSR;
3952 else if (pCtx->ecx == MSR_IA32_TSC)
3953 pSvmTransient->fUpdateTscOffsetting = true;
3954 }
3955 else
3956 {
3957 /* MSR Read access. */
3958 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
3959 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
3960
3961 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
3962 {
3963 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3964 if (RT_LIKELY(rc == VINF_SUCCESS))
3965 pCtx->rip = pVmcb->ctrl.u64NextRIP;
3966 else
3967 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
3968 }
3969 else
3970 {
3971 VBOXSTRICTRC rcStrict = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
3972 rc = VBOXSTRICTRC_VAL(rcStrict);
3973 if (RT_UNLIKELY(rc != VINF_SUCCESS))
3974 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
3975 /* RIP updated by EMInterpretInstruction(). */
3976 }
3977 }
3978
3979 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
3980 return rc;
3981}
3982
3983
3984/**
3985 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
3986 */
3987HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3988{
3989 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3990 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
3991
3992 /* We should -not- get this VM-exit if the guest is debugging. */
3993 AssertMsgReturn(!CPUMIsGuestDebugStateActive(pVCpu),
3994 ("hmR0SvmExitReadDRx: Unexpected exit. pVCpu=%p pCtx=%p\n", pVCpu, pCtx),
3995 VERR_SVM_UNEXPECTED_EXIT);
3996
3997 /*
3998 * Lazy DR0-3 loading?
3999 */
4000 if (!CPUMIsHyperDebugStateActive(pVCpu))
4001 {
4002 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4003 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4004
4005 /* Don't intercept DRx read and writes. */
4006 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4007 pVmcb->ctrl.u16InterceptRdDRx = 0;
4008 pVmcb->ctrl.u16InterceptWrDRx = 0;
4009 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4010
4011 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4012 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4013 Assert(CPUMIsGuestDebugStateActive(pVCpu));
4014
4015 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4016 return VINF_SUCCESS;
4017 }
4018
4019 /*
4020 * Interpret the read/writing of DRx.
4021 */
4022 /** @todo Decode assist. */
4023 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4024 Log5(("hmR0SvmExitReadDRx: Emulatined DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4025 if (RT_LIKELY(rc == VINF_SUCCESS))
4026 {
4027 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4028 /** @todo CPUM should set this flag! */
4029 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
4030 }
4031 else
4032 Assert(rc == VERR_EM_INTERPRETER);
4033 return VBOXSTRICTRC_TODO(rc);
4034}
4035
4036
4037/**
4038 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
4039 */
4040HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4041{
4042 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4043 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4044 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4045 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4046 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4047 return rc;
4048}
4049
4050
4051/**
4052 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
4053 */
4054HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4055{
4056 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4057
4058 /* I/O operation lookup arrays. */
4059 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4060 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4061 the result (in AL/AX/EAX). */
4062 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4063
4064 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4065 PVM pVM = pVCpu->CTX_SUFF(pVM);
4066
4067 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4068 SVMIOIOEXIT IoExitInfo;
4069 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4070 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4071 uint32_t uIOSize = s_aIOSize[uIOWidth];
4072 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4073
4074 if (RT_UNLIKELY(!uIOSize))
4075 {
4076 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4077 return VERR_EM_INTERPRETER;
4078 }
4079
4080 int rc;
4081 if (IoExitInfo.n.u1STR)
4082 {
4083 /* INS/OUTS - I/O String instruction. */
4084 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4085
4086 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4087 * in EXITINFO1? Investigate once this thing is up and running. */
4088
4089 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4090 if (rc == VINF_SUCCESS)
4091 {
4092 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4093 {
4094 VBOXSTRICTRC rc2 = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4095 (DISCPUMODE)pDis->uAddrMode, uIOSize);
4096 rc = VBOXSTRICTRC_VAL(rc2);
4097 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4098 }
4099 else
4100 {
4101 VBOXSTRICTRC rc2 = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4102 (DISCPUMODE)pDis->uAddrMode, uIOSize);
4103 rc = VBOXSTRICTRC_VAL(rc2);
4104 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4105 }
4106 }
4107 else
4108 rc = VINF_EM_RAW_EMULATE_INSTR;
4109 }
4110 else
4111 {
4112 /* IN/OUT - I/O instruction. */
4113 Assert(!IoExitInfo.n.u1REP);
4114
4115 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4116 {
4117 VBOXSTRICTRC rc2 = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
4118 rc = VBOXSTRICTRC_VAL(rc2);
4119 if (rc == VINF_IOM_R3_IOPORT_WRITE)
4120 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, uIOSize);
4121
4122 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4123 }
4124 else
4125 {
4126 uint32_t u32Val = 0;
4127
4128 VBOXSTRICTRC rc2 = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, uIOSize);
4129 rc = VBOXSTRICTRC_VAL(rc2);
4130 if (IOM_SUCCESS(rc))
4131 {
4132 /* Save result of I/O IN instr. in AL/AX/EAX. */
4133 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4134 }
4135 else if (rc == VINF_IOM_R3_IOPORT_READ)
4136 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, uIOSize);
4137
4138 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
4139 }
4140 }
4141
4142 if (IOM_SUCCESS(rc))
4143 {
4144 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
4145 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
4146
4147 if (RT_LIKELY(rc == VINF_SUCCESS))
4148 {
4149 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
4150 /** @todo This is inefficient and wrong according to intel and amd specs
4151 * (regardless of which is correct). See the same code in the VT-x case.
4152 * write testcase and refactor the code to use a mostly shared
4153 * implementation after the initial DR7/CR4 checks. */
4154 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
4155 {
4156 /* I/O breakpoint length, in bytes. */
4157 static uint32_t const s_aIOBPLen[4] = { 1, 2, 0, 4 };
4158
4159 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
4160 for (unsigned i = 0; i < 4; i++)
4161 {
4162 unsigned uBPLen = s_aIOBPLen[X86_DR7_GET_LEN(pCtx->dr[7], i)];
4163
4164 if ( IoExitInfo.n.u16Port >= pCtx->dr[i]
4165 && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen
4166 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
4167 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
4168 {
4169 Assert(CPUMIsGuestDebugStateActive(pVCpu));
4170
4171 /* Clear all breakpoint status flags and set the one we just hit. */
4172 pCtx->dr[6] &= ~(X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3);
4173 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
4174
4175 /*
4176 * Note: AMD64 Architecture Programmer's Manual 13.1:
4177 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
4178 * by software after the contents have been read.
4179 */
4180 pVmcb->guest.u64DR6 = pCtx->dr[6];
4181
4182 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
4183 pCtx->dr[7] &= ~X86_DR7_GD;
4184
4185 /* Paranoia. */
4186 pCtx->dr[7] &= 0xffffffff; /* Upper 32 bits MBZ. */
4187 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* MBZ. */
4188 pCtx->dr[7] |= 0x400; /* MB1. */
4189
4190 pVmcb->guest.u64DR7 = pCtx->dr[7];
4191 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4192
4193 /* Inject the debug exception. */
4194 hmR0SvmSetPendingXcptDB(pVCpu);
4195 break;
4196 }
4197 }
4198 }
4199 }
4200 }
4201
4202#ifdef VBOX_STRICT
4203 if (rc == VINF_IOM_R3_IOPORT_READ)
4204 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
4205 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
4206 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
4207 else
4208 {
4209 AssertMsg( RT_FAILURE(rc)
4210 || rc == VINF_SUCCESS
4211 || rc == VINF_EM_RAW_EMULATE_INSTR
4212 || rc == VINF_EM_RAW_GUEST_TRAP
4213 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", rc));
4214 }
4215#endif
4216 return rc;
4217}
4218
4219
4220/**
4221 * #VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional
4222 * #VMEXIT.
4223 */
4224HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4225{
4226 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4227 PVM pVM = pVCpu->CTX_SUFF(pVM);
4228 Assert(pVM->hm.s.fNestedPaging);
4229
4230 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4231
4232 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
4233 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4234 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4235 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
4236
4237 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
4238
4239#ifdef VBOX_HM_WITH_GUEST_PATCHING
4240 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
4241 if ( pVM->hm.s.fTRPPatchingAllowed
4242 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80 /* TPR offset. */
4243 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
4244 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
4245 && !CPUMGetGuestCPL(pVCpu)
4246 && !CPUMIsGuestInLongModeEx(pCtx)
4247 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4248 {
4249 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
4250 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4251
4252 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
4253 {
4254 /* Only attempt to patch the instruction once. */
4255 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4256 if (!pPatch)
4257 return VINF_EM_HM_PATCH_TPR_INSTR;
4258 }
4259 }
4260#endif
4261
4262 /*
4263 * Determine the nested paging mode.
4264 */
4265 PGMMODE enmNestedPagingMode;
4266#if HC_ARCH_BITS == 32
4267 if (CPUMIsGuestInLongModeEx(pCtx))
4268 enmNestedPagingMode = PGMMODE_AMD64_NX;
4269 else
4270#endif
4271 enmNestedPagingMode = PGMGetHostMode(pVM);
4272
4273 /*
4274 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
4275 */
4276 int rc;
4277 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
4278 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
4279 {
4280 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
4281 u32ErrCode);
4282 rc = VBOXSTRICTRC_VAL(rc2);
4283
4284 /*
4285 * If we succeed, resume guest execution.
4286 * If we fail in interpreting the instruction because we couldn't get the guest physical address
4287 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
4288 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
4289 * weird case. See @bugref{6043}.
4290 */
4291 if ( rc == VINF_SUCCESS
4292 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4293 || rc == VERR_PAGE_NOT_PRESENT)
4294 {
4295 /* Successfully handled MMIO operation. */
4296 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4297 rc = VINF_SUCCESS;
4298 }
4299 return rc;
4300 }
4301
4302 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
4303 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
4304 TRPMResetTrap(pVCpu);
4305
4306 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
4307
4308 /*
4309 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
4310 */
4311 if ( rc == VINF_SUCCESS
4312 || rc == VERR_PAGE_TABLE_NOT_PRESENT
4313 || rc == VERR_PAGE_NOT_PRESENT)
4314 {
4315 /* We've successfully synced our shadow page tables. */
4316 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4317 rc = VINF_SUCCESS;
4318 }
4319
4320 return rc;
4321}
4322
4323
4324/**
4325 * #VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional #VMEXIT.
4326 */
4327HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4328{
4329 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4330
4331 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4332 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one before reentry. */
4333 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
4334
4335 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
4336 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
4337 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
4338
4339 /* Deliver the pending interrupt via hmR0SvmPreRunGuest()->hmR0SvmInjectEventVmcb() and resume guest execution. */
4340 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
4341 return VINF_SUCCESS;
4342}
4343
4344
4345/**
4346 * #VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional #VMEXIT.
4347 */
4348HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4349{
4350 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4351
4352#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
4353 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4354#endif
4355
4356 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
4357 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4358 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
4359 && pVCpu->hm.s.Event.fPending)
4360 {
4361 /*
4362 * AMD-V does not provide us with the original exception but we have it in u64IntrInfo since we
4363 * injected the event during VM-entry. Software interrupts and exceptions will be regenerated
4364 * when the recompiler restarts the instruction.
4365 */
4366 SVMEVENT Event;
4367 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
4368 if ( Event.n.u3Type == SVM_EVENT_EXCEPTION
4369 || Event.n.u3Type == SVM_EVENT_SOFTWARE_INT)
4370 {
4371 pVCpu->hm.s.Event.fPending = false;
4372 }
4373 else
4374 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery. Kept pending u8Vector=%#x\n", Event.n.u8Vector));
4375 }
4376
4377 /** @todo Emulate task switch someday, currently just going back to ring-3 for
4378 * emulation. */
4379 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
4380 return VERR_EM_INTERPRETER;
4381}
4382
4383
4384/**
4385 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
4386 */
4387HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4388{
4389 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4390
4391 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4392 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4393 hmR0SvmSetPendingXcptUD(pVCpu);
4394 return VINF_SUCCESS;
4395}
4396
4397
4398/**
4399 * #VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E). Conditional
4400 * #VMEXIT.
4401 */
4402HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4403{
4404 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4405
4406 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4407
4408 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
4409 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4410 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
4411 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
4412 PVM pVM = pVCpu->CTX_SUFF(pVM);
4413
4414#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
4415 if (pVM->hm.s.fNestedPaging)
4416 {
4417 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4418 if (!pSvmTransient->fVectoringPF)
4419 {
4420 /* A genuine guest #PF, reflect it to the guest. */
4421 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4422 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
4423 uFaultAddress, u32ErrCode));
4424 }
4425 else
4426 {
4427 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4428 hmR0SvmSetPendingXcptDF(pVCpu);
4429 Log4(("Pending #DF due to vectoring #PF. NP\n"));
4430 }
4431 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4432 return VINF_SUCCESS;
4433 }
4434#endif
4435
4436 Assert(!pVM->hm.s.fNestedPaging);
4437
4438#ifdef VBOX_HM_WITH_GUEST_PATCHING
4439 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
4440 if ( pVM->hm.s.fTRPPatchingAllowed
4441 && (uFaultAddress & 0xfff) == 0x80 /* TPR offset. */
4442 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
4443 && !CPUMGetGuestCPL(pVCpu)
4444 && !CPUMIsGuestInLongModeEx(pCtx)
4445 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
4446 {
4447 RTGCPHYS GCPhysApicBase;
4448 GCPhysApicBase = pCtx->msrApicBase;
4449 GCPhysApicBase &= PAGE_BASE_GC_MASK;
4450
4451 /* Check if the page at the fault-address is the APIC base. */
4452 RTGCPHYS GCPhysPage;
4453 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
4454 if ( rc2 == VINF_SUCCESS
4455 && GCPhysPage == GCPhysApicBase)
4456 {
4457 /* Only attempt to patch the instruction once. */
4458 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4459 if (!pPatch)
4460 return VINF_EM_HM_PATCH_TPR_INSTR;
4461 }
4462 }
4463#endif
4464
4465 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
4466 pCtx->rip, u32ErrCode, pCtx->cr3));
4467
4468 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
4469 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
4470
4471 Log4(("#PF rc=%Rrc\n", rc));
4472
4473 if (rc == VINF_SUCCESS)
4474 {
4475 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
4476 TRPMResetTrap(pVCpu);
4477 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
4478 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
4479 return rc;
4480 }
4481 else if (rc == VINF_EM_RAW_GUEST_TRAP)
4482 {
4483 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
4484
4485 if (!pSvmTransient->fVectoringPF)
4486 {
4487 /* It's a guest page fault and needs to be reflected to the guest. */
4488 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
4489 TRPMResetTrap(pVCpu);
4490 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
4491 }
4492 else
4493 {
4494 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
4495 TRPMResetTrap(pVCpu);
4496 hmR0SvmSetPendingXcptDF(pVCpu);
4497 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
4498 }
4499
4500 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
4501 return VINF_SUCCESS;
4502 }
4503
4504 TRPMResetTrap(pVCpu);
4505 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
4506 return rc;
4507}
4508
4509
4510/**
4511 * #VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
4512 * Conditional #VMEXIT.
4513 */
4514HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4515{
4516 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4517
4518 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4519
4520#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
4521 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
4522#endif
4523
4524 /* Lazy FPU loading; load the guest-FPU state transparently and continue execution of the guest. */
4525 int rc = CPUMR0LoadGuestFPU(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4526 if (rc == VINF_SUCCESS)
4527 {
4528 Assert(CPUMIsGuestFPUStateActive(pVCpu));
4529 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
4530 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
4531 return VINF_SUCCESS;
4532 }
4533
4534 /* Forward #NM to the guest. */
4535 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
4536 hmR0SvmSetPendingXcptNM(pVCpu);
4537 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
4538 return VINF_SUCCESS;
4539}
4540
4541
4542/**
4543 * #VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
4544 * Conditional #VMEXIT.
4545 */
4546HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4547{
4548 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4549
4550 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4551
4552 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
4553
4554 if (!(pCtx->cr0 & X86_CR0_NE))
4555 {
4556 /* Old-style FPU error reporting needs some extra work. */
4557 /** @todo don't fall back to the recompiler, but do it manually. */
4558 return VERR_EM_INTERPRETER;
4559 }
4560
4561 hmR0SvmSetPendingXcptMF(pVCpu);
4562 return VINF_SUCCESS;
4563}
4564
4565
4566/**
4567 * #VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
4568 * #VMEXIT.
4569 */
4570HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4571{
4572 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4573
4574 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
4575
4576 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
4577
4578 /* If we set the trap flag above, we have to clear it. */
4579 /** @todo HM should remember what it does and possibly do this elsewhere! */
4580 if (pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu))
4581 pCtx->eflags.Bits.u1TF = 0;
4582
4583 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
4584 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
4585 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4586 PVM pVM = pVCpu->CTX_SUFF(pVM);
4587 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
4588 if (rc == VINF_EM_RAW_GUEST_TRAP)
4589 {
4590 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
4591 if (CPUMIsHyperDebugStateActive(pVCpu))
4592 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
4593
4594 /* Reflect the exception back to the guest. */
4595 hmR0SvmSetPendingXcptDB(pVCpu);
4596 rc = VINF_SUCCESS;
4597 }
4598
4599 /*
4600 * Update DR6.
4601 */
4602 if (CPUMIsHyperDebugStateActive(pVCpu))
4603 {
4604 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
4605 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
4606 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
4607 }
4608 else
4609 {
4610 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
4611 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
4612 }
4613
4614 return rc;
4615}
4616
4617/** @} */
4618
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