VirtualBox

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

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

VMM/HMSVMR0: Fix non-nested paging w/ #PF injection. DSL now boots without nested paging as well.

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