VirtualBox

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

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

VMM/HMSVMR0: Bits.

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