VirtualBox

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

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

VMM/HMSVMR0: VMCB Clean Bits MBZ when it's not supported by the CPU.

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

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