VirtualBox

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

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

VMM/HMSVMR0: AMD-V bits.

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