VirtualBox

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

Last change on this file since 72687 was 72661, checked in by vboxsync, 7 years ago

HMSVMR0.cpp: Shortened hmR0SvmImportGuestState a little. bugref:9193

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 323.3 KB
Line 
1/* $Id: HMSVMR0.cpp 72661 2018-06-22 11:36:36Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013-2017 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/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#define VMCPU_INCL_CPUM_GST_CTX
24#include <iprt/asm-amd64-x86.h>
25#include <iprt/thread.h>
26
27#include <VBox/vmm/pdmapi.h>
28#include <VBox/vmm/dbgf.h>
29#include <VBox/vmm/iem.h>
30#include <VBox/vmm/iom.h>
31#include <VBox/vmm/tm.h>
32#include <VBox/vmm/gim.h>
33#include <VBox/vmm/apic.h>
34#include "HMInternal.h"
35#include <VBox/vmm/vm.h>
36#include "HMSVMR0.h"
37#include "dtrace/VBoxVMM.h"
38
39#define HMSVM_USE_IEM_EVENT_REFLECTION
40#ifdef DEBUG_ramshankar
41# define HMSVM_SYNC_FULL_GUEST_STATE
42# define HMSVM_SYNC_FULL_NESTED_GUEST_STATE
43# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
44# define HMSVM_ALWAYS_TRAP_PF
45# define HMSVM_ALWAYS_TRAP_TASK_SWITCH
46#endif
47
48
49/*********************************************************************************************************************************
50* Defined Constants And Macros *
51*********************************************************************************************************************************/
52#ifdef VBOX_WITH_STATISTICS
53# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
54 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
55 if ((u64ExitCode) == SVM_EXIT_NPF) \
56 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
57 else \
58 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
59 } while (0)
60
61# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
62# define HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
63 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
64 if ((u64ExitCode) == SVM_EXIT_NPF) \
65 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitReasonNpf); \
66 else \
67 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
68 } while (0)
69# endif
70#else
71# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
72# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
73# define HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
74# endif
75#endif /* !VBOX_WITH_STATISTICS */
76
77
78/** If we decide to use a function table approach this can be useful to
79 * switch to a "static DECLCALLBACK(int)". */
80#define HMSVM_EXIT_DECL static int
81
82/**
83 * Subset of the guest-CPU state that is kept by SVM R0 code while executing the
84 * guest using hardware-assisted SVM.
85 *
86 * This excludes state like TSC AUX, GPRs (other than RSP, RAX) which are always
87 * are swapped and restored across the world-switch and also registers like
88 * EFER, PAT MSR etc. which cannot be modified by the guest without causing a
89 * \#VMEXIT.
90 */
91#define HMSVM_CPUMCTX_EXTRN_ALL ( CPUMCTX_EXTRN_RIP \
92 | CPUMCTX_EXTRN_RFLAGS \
93 | CPUMCTX_EXTRN_RAX \
94 | CPUMCTX_EXTRN_RSP \
95 | CPUMCTX_EXTRN_SREG_MASK \
96 | CPUMCTX_EXTRN_CR0 \
97 | CPUMCTX_EXTRN_CR2 \
98 | CPUMCTX_EXTRN_CR3 \
99 | CPUMCTX_EXTRN_TABLE_MASK \
100 | CPUMCTX_EXTRN_DR6 \
101 | CPUMCTX_EXTRN_DR7 \
102 | CPUMCTX_EXTRN_KERNEL_GS_BASE \
103 | CPUMCTX_EXTRN_SYSCALL_MSRS \
104 | CPUMCTX_EXTRN_SYSENTER_MSRS \
105 | CPUMCTX_EXTRN_HWVIRT \
106 | CPUMCTX_EXTRN_HM_SVM_MASK)
107
108/** Macro for importing guest state from the VMCB back into CPUMCTX. */
109#define HMSVM_CPUMCTX_IMPORT_STATE(a_pVCpu, a_pCtx, a_fWhat) \
110 do { \
111 if ((a_pCtx)->fExtrn & (a_fWhat)) \
112 hmR0SvmImportGuestState((a_pVCpu), (a_pCtx), (a_fWhat)); \
113 } while (0)
114
115/** Assert that the required state bits are fetched. */
116#define HMSVM_CPUMCTX_ASSERT(a_pVCpu, a_fExtrnMbz) AssertMsg(!((a_pVCpu)->cpum.GstCtx.fExtrn & (a_fExtrnMbz)), \
117 ("fExtrn=%#RX64 fExtrnMbz=%#RX64\n", \
118 (a_pVCpu)->cpum.GstCtx.fExtrn, (a_fExtrnMbz)))
119
120/** Macro for checking and returning from the using function for
121 * \#VMEXIT intercepts that maybe caused during delivering of another
122 * event in the guest. */
123#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
124# define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
125 do \
126 { \
127 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
128 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* continue #VMEXIT handling */ } \
129 else if ( rc == VINF_HM_DOUBLE_FAULT) { return VINF_SUCCESS; } \
130 else if ( rc == VINF_EM_RESET \
131 && CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_SHUTDOWN)) \
132 { \
133 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK); \
134 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_SHUTDOWN, 0, 0)); \
135 } \
136 else \
137 return rc; \
138 } while (0)
139#else
140# define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
141 do \
142 { \
143 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
144 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* continue #VMEXIT handling */ } \
145 else if ( rc == VINF_HM_DOUBLE_FAULT) { return VINF_SUCCESS; } \
146 else \
147 return rc; \
148 } while (0)
149#endif
150
151/** Macro which updates interrupt shadow for the current RIP. */
152#define HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx) \
153 do { \
154 /* Update interrupt shadow. */ \
155 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS) \
156 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu)) \
157 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS); \
158 } while (0)
159
160/** Macro for upgrading a @a a_rc to VINF_EM_DBG_STEPPED after emulating an
161 * instruction that exited. */
162#define HMSVM_CHECK_SINGLE_STEP(a_pVCpu, a_rc) \
163 do { \
164 if ((a_pVCpu)->hm.s.fSingleInstruction && (a_rc) == VINF_SUCCESS) \
165 (a_rc) = VINF_EM_DBG_STEPPED; \
166 } while (0)
167
168/** Assert that preemption is disabled or covered by thread-context hooks. */
169#define HMSVM_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
170 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
171
172/** Assert that we haven't migrated CPUs when thread-context hooks are not
173 * used. */
174#define HMSVM_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
175 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
176 ("Illegal migration! Entered on CPU %u Current %u\n", \
177 pVCpu->hm.s.idEnteredCpu, RTMpCpuId()));
178
179/** Assert that we're not executing a nested-guest. */
180#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
181# define HMSVM_ASSERT_NOT_IN_NESTED_GUEST(a_pCtx) Assert(!CPUMIsGuestInSvmNestedHwVirtMode((a_pCtx)))
182#else
183# define HMSVM_ASSERT_NOT_IN_NESTED_GUEST(a_pCtx) do { NOREF((a_pCtx)); } while (0)
184#endif
185
186/** Assert that we're executing a nested-guest. */
187#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
188# define HMSVM_ASSERT_IN_NESTED_GUEST(a_pCtx) Assert(CPUMIsGuestInSvmNestedHwVirtMode((a_pCtx)))
189#else
190# define HMSVM_ASSERT_IN_NESTED_GUEST(a_pCtx) do { NOREF((a_pCtx)); } while (0)
191#endif
192
193/** Validate segment descriptor granularity bit. */
194#ifdef VBOX_STRICT
195# define HMSVM_ASSERT_SEG_GRANULARITY(a_pCtx, reg) \
196 AssertMsg( !(a_pCtx)->reg.Attr.n.u1Present \
197 || ( (a_pCtx)->reg.Attr.n.u1Granularity \
198 ? ((a_pCtx)->reg.u32Limit & 0xfff) == 0xfff \
199 : (a_pCtx)->reg.u32Limit <= UINT32_C(0xfffff)), \
200 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", (a_pCtx)->reg.u32Limit, \
201 (a_pCtx)->reg.Attr.u, (a_pCtx)->reg.u64Base))
202#else
203# define HMSVM_ASSERT_SEG_GRANULARITY(a_pCtx, reg) do { } while (0)
204#endif
205
206/**
207 * Exception bitmap mask for all contributory exceptions.
208 *
209 * Page fault is deliberately excluded here as it's conditional as to whether
210 * it's contributory or benign. Page faults are handled separately.
211 */
212#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) \
213 | RT_BIT(X86_XCPT_DE))
214
215/**
216 * Mandatory/unconditional guest control intercepts.
217 *
218 * SMIs can and do happen in normal operation. We need not intercept them
219 * while executing the guest (or nested-guest).
220 */
221#define HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS ( SVM_CTRL_INTERCEPT_INTR \
222 | SVM_CTRL_INTERCEPT_NMI \
223 | SVM_CTRL_INTERCEPT_INIT \
224 | SVM_CTRL_INTERCEPT_RDPMC \
225 | SVM_CTRL_INTERCEPT_CPUID \
226 | SVM_CTRL_INTERCEPT_RSM \
227 | SVM_CTRL_INTERCEPT_HLT \
228 | SVM_CTRL_INTERCEPT_IOIO_PROT \
229 | SVM_CTRL_INTERCEPT_MSR_PROT \
230 | SVM_CTRL_INTERCEPT_INVLPGA \
231 | SVM_CTRL_INTERCEPT_SHUTDOWN \
232 | SVM_CTRL_INTERCEPT_FERR_FREEZE \
233 | SVM_CTRL_INTERCEPT_VMRUN \
234 | SVM_CTRL_INTERCEPT_SKINIT \
235 | SVM_CTRL_INTERCEPT_WBINVD \
236 | SVM_CTRL_INTERCEPT_MONITOR \
237 | SVM_CTRL_INTERCEPT_MWAIT \
238 | SVM_CTRL_INTERCEPT_CR0_SEL_WRITE \
239 | SVM_CTRL_INTERCEPT_XSETBV)
240
241/** @name VMCB Clean Bits.
242 *
243 * These flags are used for VMCB-state caching. A set VMCB Clean bit indicates
244 * AMD-V doesn't need to reload the corresponding value(s) from the VMCB in
245 * memory.
246 *
247 * @{ */
248/** All intercepts vectors, TSC offset, PAUSE filter counter. */
249#define HMSVM_VMCB_CLEAN_INTERCEPTS RT_BIT(0)
250/** I/O permission bitmap, MSR permission bitmap. */
251#define HMSVM_VMCB_CLEAN_IOPM_MSRPM RT_BIT(1)
252/** ASID. */
253#define HMSVM_VMCB_CLEAN_ASID RT_BIT(2)
254/** TRP: V_TPR, V_IRQ, V_INTR_PRIO, V_IGN_TPR, V_INTR_MASKING,
255V_INTR_VECTOR. */
256#define HMSVM_VMCB_CLEAN_INT_CTRL RT_BIT(3)
257/** Nested Paging: Nested CR3 (nCR3), PAT. */
258#define HMSVM_VMCB_CLEAN_NP RT_BIT(4)
259/** Control registers (CR0, CR3, CR4, EFER). */
260#define HMSVM_VMCB_CLEAN_CRX_EFER RT_BIT(5)
261/** Debug registers (DR6, DR7). */
262#define HMSVM_VMCB_CLEAN_DRX RT_BIT(6)
263/** GDT, IDT limit and base. */
264#define HMSVM_VMCB_CLEAN_DT RT_BIT(7)
265/** Segment register: CS, SS, DS, ES limit and base. */
266#define HMSVM_VMCB_CLEAN_SEG RT_BIT(8)
267/** CR2.*/
268#define HMSVM_VMCB_CLEAN_CR2 RT_BIT(9)
269/** Last-branch record (DbgCtlMsr, br_from, br_to, lastint_from, lastint_to) */
270#define HMSVM_VMCB_CLEAN_LBR RT_BIT(10)
271/** AVIC (AVIC APIC_BAR; AVIC APIC_BACKING_PAGE, AVIC
272PHYSICAL_TABLE and AVIC LOGICAL_TABLE Pointers). */
273#define HMSVM_VMCB_CLEAN_AVIC RT_BIT(11)
274/** Mask of all valid VMCB Clean bits. */
275#define HMSVM_VMCB_CLEAN_ALL ( HMSVM_VMCB_CLEAN_INTERCEPTS \
276 | HMSVM_VMCB_CLEAN_IOPM_MSRPM \
277 | HMSVM_VMCB_CLEAN_ASID \
278 | HMSVM_VMCB_CLEAN_INT_CTRL \
279 | HMSVM_VMCB_CLEAN_NP \
280 | HMSVM_VMCB_CLEAN_CRX_EFER \
281 | HMSVM_VMCB_CLEAN_DRX \
282 | HMSVM_VMCB_CLEAN_DT \
283 | HMSVM_VMCB_CLEAN_SEG \
284 | HMSVM_VMCB_CLEAN_CR2 \
285 | HMSVM_VMCB_CLEAN_LBR \
286 | HMSVM_VMCB_CLEAN_AVIC)
287/** @} */
288
289/** @name SVM transient.
290 *
291 * A state structure for holding miscellaneous information across AMD-V
292 * VMRUN/\#VMEXIT operation, restored after the transition.
293 *
294 * @{ */
295typedef struct SVMTRANSIENT
296{
297 /** The host's rflags/eflags. */
298 RTCCUINTREG fEFlags;
299#if HC_ARCH_BITS == 32
300 uint32_t u32Alignment0;
301#endif
302
303 /** The \#VMEXIT exit code (the EXITCODE field in the VMCB). */
304 uint64_t u64ExitCode;
305 /** The guest's TPR value used for TPR shadowing. */
306 uint8_t u8GuestTpr;
307 /** Alignment. */
308 uint8_t abAlignment0[7];
309
310 /** Pointer to the currently executing VMCB. */
311 PSVMVMCB pVmcb;
312 /** Whether we are currently executing a nested-guest. */
313 bool fIsNestedGuest;
314
315 /** Whether the guest debug state was active at the time of \#VMEXIT. */
316 bool fWasGuestDebugStateActive;
317 /** Whether the hyper debug state was active at the time of \#VMEXIT. */
318 bool fWasHyperDebugStateActive;
319 /** Whether the TSC offset mode needs to be updated. */
320 bool fUpdateTscOffsetting;
321 /** Whether the TSC_AUX MSR needs restoring on \#VMEXIT. */
322 bool fRestoreTscAuxMsr;
323 /** Whether the \#VMEXIT was caused by a page-fault during delivery of a
324 * contributary exception or a page-fault. */
325 bool fVectoringDoublePF;
326 /** Whether the \#VMEXIT was caused by a page-fault during delivery of an
327 * external interrupt or NMI. */
328 bool fVectoringPF;
329} SVMTRANSIENT, *PSVMTRANSIENT;
330AssertCompileMemberAlignment(SVMTRANSIENT, u64ExitCode, sizeof(uint64_t));
331AssertCompileMemberAlignment(SVMTRANSIENT, pVmcb, sizeof(uint64_t));
332/** @} */
333
334/**
335 * MSRPM (MSR permission bitmap) read permissions (for guest RDMSR).
336 */
337typedef enum SVMMSREXITREAD
338{
339 /** Reading this MSR causes a \#VMEXIT. */
340 SVMMSREXIT_INTERCEPT_READ = 0xb,
341 /** Reading this MSR does not cause a \#VMEXIT. */
342 SVMMSREXIT_PASSTHRU_READ
343} SVMMSREXITREAD;
344
345/**
346 * MSRPM (MSR permission bitmap) write permissions (for guest WRMSR).
347 */
348typedef enum SVMMSREXITWRITE
349{
350 /** Writing to this MSR causes a \#VMEXIT. */
351 SVMMSREXIT_INTERCEPT_WRITE = 0xd,
352 /** Writing to this MSR does not cause a \#VMEXIT. */
353 SVMMSREXIT_PASSTHRU_WRITE
354} SVMMSREXITWRITE;
355
356/**
357 * SVM \#VMEXIT handler.
358 *
359 * @returns VBox status code.
360 * @param pVCpu The cross context virtual CPU structure.
361 * @param pCtx Pointer to the guest-CPU context.
362 * @param pSvmTransient Pointer to the SVM-transient structure.
363 */
364typedef int FNSVMEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
365
366
367/*********************************************************************************************************************************
368* Internal Functions *
369*********************************************************************************************************************************/
370static void hmR0SvmSetMsrPermission(PCCPUMCTX pCtx, uint8_t *pbMsrBitmap, unsigned uMsr, SVMMSREXITREAD enmRead,
371 SVMMSREXITWRITE enmWrite);
372static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu);
373static void hmR0SvmLeave(PVMCPU pVCpu, bool fImportState);
374static void hmR0SvmImportGuestState(PVMCPU pVCpu, PCPUMCTX pCtx, uint64_t fWhat);
375
376
377/** @name \#VMEXIT handlers.
378 * @{
379 */
380static FNSVMEXITHANDLER hmR0SvmExitIntr;
381static FNSVMEXITHANDLER hmR0SvmExitWbinvd;
382static FNSVMEXITHANDLER hmR0SvmExitInvd;
383static FNSVMEXITHANDLER hmR0SvmExitCpuid;
384static FNSVMEXITHANDLER hmR0SvmExitRdtsc;
385static FNSVMEXITHANDLER hmR0SvmExitRdtscp;
386static FNSVMEXITHANDLER hmR0SvmExitRdpmc;
387static FNSVMEXITHANDLER hmR0SvmExitInvlpg;
388static FNSVMEXITHANDLER hmR0SvmExitHlt;
389static FNSVMEXITHANDLER hmR0SvmExitMonitor;
390static FNSVMEXITHANDLER hmR0SvmExitMwait;
391static FNSVMEXITHANDLER hmR0SvmExitShutdown;
392static FNSVMEXITHANDLER hmR0SvmExitUnexpected;
393static FNSVMEXITHANDLER hmR0SvmExitReadCRx;
394static FNSVMEXITHANDLER hmR0SvmExitWriteCRx;
395static FNSVMEXITHANDLER hmR0SvmExitMsr;
396static FNSVMEXITHANDLER hmR0SvmExitReadDRx;
397static FNSVMEXITHANDLER hmR0SvmExitWriteDRx;
398static FNSVMEXITHANDLER hmR0SvmExitXsetbv;
399static FNSVMEXITHANDLER hmR0SvmExitIOInstr;
400static FNSVMEXITHANDLER hmR0SvmExitNestedPF;
401static FNSVMEXITHANDLER hmR0SvmExitVIntr;
402static FNSVMEXITHANDLER hmR0SvmExitTaskSwitch;
403static FNSVMEXITHANDLER hmR0SvmExitVmmCall;
404static FNSVMEXITHANDLER hmR0SvmExitPause;
405static FNSVMEXITHANDLER hmR0SvmExitFerrFreeze;
406static FNSVMEXITHANDLER hmR0SvmExitIret;
407static FNSVMEXITHANDLER hmR0SvmExitXcptPF;
408static FNSVMEXITHANDLER hmR0SvmExitXcptUD;
409static FNSVMEXITHANDLER hmR0SvmExitXcptMF;
410static FNSVMEXITHANDLER hmR0SvmExitXcptDB;
411static FNSVMEXITHANDLER hmR0SvmExitXcptAC;
412static FNSVMEXITHANDLER hmR0SvmExitXcptBP;
413#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT_SVM)
414static FNSVMEXITHANDLER hmR0SvmExitXcptGeneric;
415#endif
416#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
417static FNSVMEXITHANDLER hmR0SvmExitClgi;
418static FNSVMEXITHANDLER hmR0SvmExitStgi;
419static FNSVMEXITHANDLER hmR0SvmExitVmload;
420static FNSVMEXITHANDLER hmR0SvmExitVmsave;
421static FNSVMEXITHANDLER hmR0SvmExitInvlpga;
422static FNSVMEXITHANDLER hmR0SvmExitVmrun;
423static FNSVMEXITHANDLER hmR0SvmNestedExitXcptDB;
424static FNSVMEXITHANDLER hmR0SvmNestedExitXcptBP;
425#endif
426/** @} */
427
428static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
429#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
430static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
431#endif
432
433
434/*********************************************************************************************************************************
435* Global Variables *
436*********************************************************************************************************************************/
437/** Ring-0 memory object for the IO bitmap. */
438static RTR0MEMOBJ g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
439/** Physical address of the IO bitmap. */
440static RTHCPHYS g_HCPhysIOBitmap;
441/** Pointer to the IO bitmap. */
442static R0PTRTYPE(void *) g_pvIOBitmap;
443
444#ifdef VBOX_STRICT
445# define HMSVM_LOG_RBP_RSP RT_BIT_32(0)
446# define HMSVM_LOG_CR_REGS RT_BIT_32(1)
447# define HMSVM_LOG_CS RT_BIT_32(2)
448# define HMSVM_LOG_SS RT_BIT_32(3)
449# define HMSVM_LOG_FS RT_BIT_32(4)
450# define HMSVM_LOG_GS RT_BIT_32(5)
451# define HMSVM_LOG_LBR RT_BIT_32(6)
452# define HMSVM_LOG_ALL ( HMSVM_LOG_RBP_RSP \
453 | HMSVM_LOG_CR_REGS \
454 | HMSVM_LOG_CS \
455 | HMSVM_LOG_SS \
456 | HMSVM_LOG_FS \
457 | HMSVM_LOG_GS \
458 | HMSVM_LOG_LBR)
459
460/**
461 * Dumps virtual CPU state and additional info. to the logger for diagnostics.
462 *
463 * @param pVCpu The cross context virtual CPU structure.
464 * @param pVmcb Pointer to the VM control block.
465 * @param pCtx Pointer to the guest-CPU context.
466 * @param pszPrefix Log prefix.
467 * @param fFlags Log flags, see HMSVM_LOG_XXX.
468 * @param uVerbose The verbosity level, currently unused.
469 */
470static void hmR0SvmLogState(PVMCPU pVCpu, PCSVMVMCB pVmcb, PCCPUMCTX pCtx, const char *pszPrefix, uint32_t fFlags,
471 uint8_t uVerbose)
472{
473 RT_NOREF2(pVCpu, uVerbose);
474
475 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
476 Log4(("%s: cs:rip=%04x:%RX64 efl=%#RX64\n", pszPrefix, pCtx->cs.Sel, pCtx->rip, pCtx->rflags.u));
477
478 if (fFlags & HMSVM_LOG_RBP_RSP)
479 {
480 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RBP);
481 Log4(("%s: rsp=%#RX64 rbp=%#RX64\n", pszPrefix, pCtx->rsp, pCtx->rbp));
482 }
483
484 if (fFlags & HMSVM_LOG_CR_REGS)
485 {
486 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4);
487 Log4(("%s: cr0=%#RX64 cr3=%#RX64 cr4=%#RX64\n", pszPrefix, pCtx->cr0, pCtx->cr3, pCtx->cr4));
488 }
489
490 if (fFlags & HMSVM_LOG_CS)
491 {
492 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS);
493 Log4(("%s: cs={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->cs.Sel, pCtx->cs.u64Base,
494 pCtx->cs.u32Limit, pCtx->cs.Attr.u));
495 }
496 if (fFlags & HMSVM_LOG_SS)
497 {
498 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SS);
499 Log4(("%s: ss={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->ss.Sel, pCtx->ss.u64Base,
500 pCtx->ss.u32Limit, pCtx->ss.Attr.u));
501 }
502 if (fFlags & HMSVM_LOG_FS)
503 {
504 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_FS);
505 Log4(("%s: fs={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->fs.Sel, pCtx->fs.u64Base,
506 pCtx->fs.u32Limit, pCtx->fs.Attr.u));
507 }
508 if (fFlags & HMSVM_LOG_GS)
509 {
510 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GS);
511 Log4(("%s: gs={%04x base=%016RX64 limit=%08x flags=%08x}\n", pszPrefix, pCtx->gs.Sel, pCtx->gs.u64Base,
512 pCtx->gs.u32Limit, pCtx->gs.Attr.u));
513 }
514
515 PCSVMVMCBSTATESAVE pVmcbGuest = &pVmcb->guest;
516 if (fFlags & HMSVM_LOG_LBR)
517 {
518 Log4(("%s: br_from=%#RX64 br_to=%#RX64 lastxcpt_from=%#RX64 lastxcpt_to=%#RX64\n", pszPrefix, pVmcbGuest->u64BR_FROM,
519 pVmcbGuest->u64BR_TO, pVmcbGuest->u64LASTEXCPFROM, pVmcbGuest->u64LASTEXCPTO));
520 }
521 NOREF(pVmcbGuest);
522}
523#endif /* VBOX_STRICT */
524
525
526/**
527 * Sets up and activates AMD-V on the current CPU.
528 *
529 * @returns VBox status code.
530 * @param pCpu Pointer to the CPU info struct.
531 * @param pVM The cross context VM structure. Can be
532 * NULL after a resume!
533 * @param pvCpuPage Pointer to the global CPU page.
534 * @param HCPhysCpuPage Physical address of the global CPU page.
535 * @param fEnabledByHost Whether the host OS has already initialized AMD-V.
536 * @param pvArg Unused on AMD-V.
537 */
538VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBALCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
539 void *pvArg)
540{
541 Assert(!fEnabledByHost);
542 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
543 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
544 Assert(pvCpuPage); NOREF(pvCpuPage);
545 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
546
547 NOREF(pvArg);
548 NOREF(fEnabledByHost);
549
550 /* Paranoid: Disable interrupt as, in theory, interrupt handlers might mess with EFER. */
551 RTCCUINTREG fEFlags = ASMIntDisableFlags();
552
553 /*
554 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per CPU.
555 */
556 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
557 if (u64HostEfer & MSR_K6_EFER_SVME)
558 {
559 /* If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V. */
560 if ( pVM
561 && pVM->hm.s.svm.fIgnoreInUseError)
562 {
563 pCpu->fIgnoreAMDVInUseError = true;
564 }
565
566 if (!pCpu->fIgnoreAMDVInUseError)
567 {
568 ASMSetFlags(fEFlags);
569 return VERR_SVM_IN_USE;
570 }
571 }
572
573 /* Turn on AMD-V in the EFER MSR. */
574 ASMWrMsr(MSR_K6_EFER, u64HostEfer | MSR_K6_EFER_SVME);
575
576 /* Write the physical page address where the CPU will store the host state while executing the VM. */
577 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
578
579 /* Restore interrupts. */
580 ASMSetFlags(fEFlags);
581
582 /*
583 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all non-zero ASIDs
584 * when enabling SVM. AMD doesn't have an SVM instruction to flush all ASIDs (flushing is done
585 * upon VMRUN). Therefore, flag that we need to flush the TLB entirely with before executing any
586 * guest code.
587 */
588 pCpu->fFlushAsidBeforeUse = true;
589
590 /*
591 * Ensure each VCPU scheduled on this CPU gets a new ASID on resume. See @bugref{6255}.
592 */
593 ++pCpu->cTlbFlushes;
594
595 return VINF_SUCCESS;
596}
597
598
599/**
600 * Deactivates AMD-V on the current CPU.
601 *
602 * @returns VBox status code.
603 * @param pCpu Pointer to the CPU info struct.
604 * @param pvCpuPage Pointer to the global CPU page.
605 * @param HCPhysCpuPage Physical address of the global CPU page.
606 */
607VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBALCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
608{
609 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
610 AssertReturn( HCPhysCpuPage
611 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
612 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
613 NOREF(pCpu);
614
615 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with EFER. */
616 RTCCUINTREG fEFlags = ASMIntDisableFlags();
617
618 /* Turn off AMD-V in the EFER MSR. */
619 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
620 ASMWrMsr(MSR_K6_EFER, u64HostEfer & ~MSR_K6_EFER_SVME);
621
622 /* Invalidate host state physical address. */
623 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
624
625 /* Restore interrupts. */
626 ASMSetFlags(fEFlags);
627
628 return VINF_SUCCESS;
629}
630
631
632/**
633 * Does global AMD-V initialization (called during module initialization).
634 *
635 * @returns VBox status code.
636 */
637VMMR0DECL(int) SVMR0GlobalInit(void)
638{
639 /*
640 * Allocate 12 KB (3 pages) for the IO bitmap. Since this is non-optional and we always
641 * intercept all IO accesses, it's done once globally here instead of per-VM.
642 */
643 Assert(g_hMemObjIOBitmap == NIL_RTR0MEMOBJ);
644 int rc = RTR0MemObjAllocCont(&g_hMemObjIOBitmap, SVM_IOPM_PAGES << X86_PAGE_4K_SHIFT, false /* fExecutable */);
645 if (RT_FAILURE(rc))
646 return rc;
647
648 g_pvIOBitmap = RTR0MemObjAddress(g_hMemObjIOBitmap);
649 g_HCPhysIOBitmap = RTR0MemObjGetPagePhysAddr(g_hMemObjIOBitmap, 0 /* iPage */);
650
651 /* Set all bits to intercept all IO accesses. */
652 ASMMemFill32(g_pvIOBitmap, SVM_IOPM_PAGES << X86_PAGE_4K_SHIFT, UINT32_C(0xffffffff));
653
654 return VINF_SUCCESS;
655}
656
657
658/**
659 * Does global AMD-V termination (called during module termination).
660 */
661VMMR0DECL(void) SVMR0GlobalTerm(void)
662{
663 if (g_hMemObjIOBitmap != NIL_RTR0MEMOBJ)
664 {
665 RTR0MemObjFree(g_hMemObjIOBitmap, true /* fFreeMappings */);
666 g_pvIOBitmap = NULL;
667 g_HCPhysIOBitmap = 0;
668 g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
669 }
670}
671
672
673/**
674 * Frees any allocated per-VCPU structures for a VM.
675 *
676 * @param pVM The cross context VM structure.
677 */
678DECLINLINE(void) hmR0SvmFreeStructs(PVM pVM)
679{
680 for (uint32_t i = 0; i < pVM->cCpus; i++)
681 {
682 PVMCPU pVCpu = &pVM->aCpus[i];
683 AssertPtr(pVCpu);
684
685 if (pVCpu->hm.s.svm.hMemObjVmcbHost != NIL_RTR0MEMOBJ)
686 {
687 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcbHost, false);
688 pVCpu->hm.s.svm.HCPhysVmcbHost = 0;
689 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
690 }
691
692 if (pVCpu->hm.s.svm.hMemObjVmcb != NIL_RTR0MEMOBJ)
693 {
694 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcb, false);
695 pVCpu->hm.s.svm.pVmcb = NULL;
696 pVCpu->hm.s.svm.HCPhysVmcb = 0;
697 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
698 }
699
700 if (pVCpu->hm.s.svm.hMemObjMsrBitmap != NIL_RTR0MEMOBJ)
701 {
702 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjMsrBitmap, false);
703 pVCpu->hm.s.svm.pvMsrBitmap = NULL;
704 pVCpu->hm.s.svm.HCPhysMsrBitmap = 0;
705 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
706 }
707 }
708}
709
710
711/**
712 * Does per-VM AMD-V initialization.
713 *
714 * @returns VBox status code.
715 * @param pVM The cross context VM structure.
716 */
717VMMR0DECL(int) SVMR0InitVM(PVM pVM)
718{
719 int rc = VERR_INTERNAL_ERROR_5;
720
721 /*
722 * Check for an AMD CPU erratum which requires us to flush the TLB before every world-switch.
723 */
724 uint32_t u32Family;
725 uint32_t u32Model;
726 uint32_t u32Stepping;
727 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
728 {
729 Log4(("SVMR0InitVM: AMD cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
730 pVM->hm.s.svm.fAlwaysFlushTLB = true;
731 }
732
733 /*
734 * Initialize the R0 memory objects up-front so we can properly cleanup on allocation failures.
735 */
736 for (VMCPUID i = 0; i < pVM->cCpus; i++)
737 {
738 PVMCPU pVCpu = &pVM->aCpus[i];
739 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
740 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
741 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
742 }
743
744 for (VMCPUID i = 0; i < pVM->cCpus; i++)
745 {
746 PVMCPU pVCpu = &pVM->aCpus[i];
747
748 /*
749 * Allocate one page for the host-context VM control block (VMCB). This is used for additional host-state (such as
750 * FS, GS, Kernel GS Base, etc.) apart from the host-state save area specified in MSR_K8_VM_HSAVE_PA.
751 */
752 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcbHost, SVM_VMCB_PAGES << PAGE_SHIFT, false /* fExecutable */);
753 if (RT_FAILURE(rc))
754 goto failure_cleanup;
755
756 void *pvVmcbHost = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcbHost);
757 pVCpu->hm.s.svm.HCPhysVmcbHost = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcbHost, 0 /* iPage */);
758 Assert(pVCpu->hm.s.svm.HCPhysVmcbHost < _4G);
759 ASMMemZeroPage(pvVmcbHost);
760
761 /*
762 * Allocate one page for the guest-state VMCB.
763 */
764 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcb, SVM_VMCB_PAGES << PAGE_SHIFT, false /* fExecutable */);
765 if (RT_FAILURE(rc))
766 goto failure_cleanup;
767
768 pVCpu->hm.s.svm.pVmcb = (PSVMVMCB)RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcb);
769 pVCpu->hm.s.svm.HCPhysVmcb = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcb, 0 /* iPage */);
770 Assert(pVCpu->hm.s.svm.HCPhysVmcb < _4G);
771 ASMMemZeroPage(pVCpu->hm.s.svm.pVmcb);
772
773 /*
774 * Allocate two pages (8 KB) for the MSR permission bitmap. There doesn't seem to be a way to convince
775 * SVM to not require one.
776 */
777 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjMsrBitmap, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT,
778 false /* fExecutable */);
779 if (RT_FAILURE(rc))
780 goto failure_cleanup;
781
782 pVCpu->hm.s.svm.pvMsrBitmap = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjMsrBitmap);
783 pVCpu->hm.s.svm.HCPhysMsrBitmap = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjMsrBitmap, 0 /* iPage */);
784 /* Set all bits to intercept all MSR accesses (changed later on). */
785 ASMMemFill32(pVCpu->hm.s.svm.pvMsrBitmap, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT, UINT32_C(0xffffffff));
786 }
787
788 return VINF_SUCCESS;
789
790failure_cleanup:
791 hmR0SvmFreeStructs(pVM);
792 return rc;
793}
794
795
796/**
797 * Does per-VM AMD-V termination.
798 *
799 * @returns VBox status code.
800 * @param pVM The cross context VM structure.
801 */
802VMMR0DECL(int) SVMR0TermVM(PVM pVM)
803{
804 hmR0SvmFreeStructs(pVM);
805 return VINF_SUCCESS;
806}
807
808
809/**
810 * Returns whether the VMCB Clean Bits feature is supported.
811 *
812 * @return @c true if supported, @c false otherwise.
813 * @param pVCpu The cross context virtual CPU structure.
814 * @param pCtx Pointer to the guest-CPU context.
815 */
816DECLINLINE(bool) hmR0SvmSupportsVmcbCleanBits(PVMCPU pVCpu, PCCPUMCTX pCtx)
817{
818 PVM pVM = pVCpu->CTX_SUFF(pVM);
819#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
820 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
821 {
822 return (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN)
823 && pVM->cpum.ro.GuestFeatures.fSvmVmcbClean;
824 }
825#else
826 RT_NOREF(pCtx);
827#endif
828 return RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN);
829}
830
831
832/**
833 * Returns whether the decode assists feature is supported.
834 *
835 * @return @c true if supported, @c false otherwise.
836 * @param pVCpu The cross context virtual CPU structure.
837 * @param pCtx Pointer to the guest-CPU context.
838 */
839DECLINLINE(bool) hmR0SvmSupportsDecodeAssists(PVMCPU pVCpu, PCPUMCTX pCtx)
840{
841 PVM pVM = pVCpu->CTX_SUFF(pVM);
842#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
843 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
844 {
845 return (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS)
846 && pVM->cpum.ro.GuestFeatures.fSvmDecodeAssists;
847 }
848#else
849 RT_NOREF(pCtx);
850#endif
851 return RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_DECODE_ASSISTS);
852}
853
854
855/**
856 * Returns whether the NRIP_SAVE feature is supported.
857 *
858 * @return @c true if supported, @c false otherwise.
859 * @param pVCpu The cross context virtual CPU structure.
860 * @param pCtx Pointer to the guest-CPU context.
861 */
862DECLINLINE(bool) hmR0SvmSupportsNextRipSave(PVMCPU pVCpu, PCPUMCTX pCtx)
863{
864 PVM pVM = pVCpu->CTX_SUFF(pVM);
865#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
866 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
867 {
868 return (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
869 && pVM->cpum.ro.GuestFeatures.fSvmNextRipSave;
870 }
871#else
872 RT_NOREF(pCtx);
873#endif
874 return RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_NRIP_SAVE);
875}
876
877
878/**
879 * Sets the permission bits for the specified MSR in the MSRPM bitmap.
880 *
881 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
882 * @param pbMsrBitmap Pointer to the MSR bitmap.
883 * @param idMsr The MSR for which the permissions are being set.
884 * @param enmRead MSR read permissions.
885 * @param enmWrite MSR write permissions.
886 *
887 * @remarks This function does -not- clear the VMCB clean bits for MSRPM. The
888 * caller needs to take care of this.
889 */
890static void hmR0SvmSetMsrPermission(PCCPUMCTX pCtx, uint8_t *pbMsrBitmap, uint32_t idMsr, SVMMSREXITREAD enmRead,
891 SVMMSREXITWRITE enmWrite)
892{
893 bool const fInNestedGuestMode = CPUMIsGuestInSvmNestedHwVirtMode(pCtx);
894 uint16_t offMsrpm;
895 uint8_t uMsrpmBit;
896 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
897 AssertRC(rc);
898
899 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
900 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
901
902 pbMsrBitmap += offMsrpm;
903 if (enmRead == SVMMSREXIT_INTERCEPT_READ)
904 *pbMsrBitmap |= RT_BIT(uMsrpmBit);
905 else
906 {
907 if (!fInNestedGuestMode)
908 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit);
909#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
910 else
911 {
912 /* Only clear the bit if the nested-guest is also not intercepting the MSR read.*/
913 uint8_t const *pbNstGstMsrBitmap = (uint8_t *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
914 pbNstGstMsrBitmap += offMsrpm;
915 if (!(*pbNstGstMsrBitmap & RT_BIT(uMsrpmBit)))
916 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit);
917 else
918 Assert(*pbMsrBitmap & RT_BIT(uMsrpmBit));
919 }
920#endif
921 }
922
923 if (enmWrite == SVMMSREXIT_INTERCEPT_WRITE)
924 *pbMsrBitmap |= RT_BIT(uMsrpmBit + 1);
925 else
926 {
927 if (!fInNestedGuestMode)
928 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit + 1);
929#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
930 else
931 {
932 /* Only clear the bit if the nested-guest is also not intercepting the MSR write.*/
933 uint8_t const *pbNstGstMsrBitmap = (uint8_t *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
934 pbNstGstMsrBitmap += offMsrpm;
935 if (!(*pbNstGstMsrBitmap & RT_BIT(uMsrpmBit + 1)))
936 *pbMsrBitmap &= ~RT_BIT(uMsrpmBit + 1);
937 else
938 Assert(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
939 }
940#endif
941 }
942}
943
944
945/**
946 * Sets up AMD-V for the specified VM.
947 * This function is only called once per-VM during initalization.
948 *
949 * @returns VBox status code.
950 * @param pVM The cross context VM structure.
951 */
952VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
953{
954 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
955 AssertReturn(pVM, VERR_INVALID_PARAMETER);
956 Assert(pVM->hm.s.svm.fSupported);
957
958 bool const fPauseFilter = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER);
959 bool const fPauseFilterThreshold = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD);
960 bool const fUsePauseFilter = fPauseFilter && pVM->hm.s.svm.cPauseFilter;
961
962 bool const fLbrVirt = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_LBR_VIRT);
963 bool const fUseLbrVirt = fLbrVirt; /** @todo CFGM, IEM implementation etc. */
964
965#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
966 bool const fVirtVmsaveVmload = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD);
967 bool const fUseVirtVmsaveVmload = fVirtVmsaveVmload && pVM->hm.s.svm.fVirtVmsaveVmload && pVM->hm.s.fNestedPaging;
968
969 bool const fVGif = RT_BOOL(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VGIF);
970 bool const fUseVGif = fVGif && pVM->hm.s.svm.fVGif;
971#endif
972
973 PVMCPU pVCpu = &pVM->aCpus[0];
974 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
975 AssertMsgReturn(pVmcb, ("Invalid pVmcb for vcpu[0]\n"), VERR_SVM_INVALID_PVMCB);
976 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
977
978 /* Always trap #AC for reasons of security. */
979 pVmcbCtrl->u32InterceptXcpt |= RT_BIT_32(X86_XCPT_AC);
980
981 /* Always trap #DB for reasons of security. */
982 pVmcbCtrl->u32InterceptXcpt |= RT_BIT_32(X86_XCPT_DB);
983
984 /* Trap exceptions unconditionally (debug purposes). */
985#ifdef HMSVM_ALWAYS_TRAP_PF
986 pVmcbCtrl->u32InterceptXcpt |= RT_BIT(X86_XCPT_PF);
987#endif
988#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
989 /* If you add any exceptions here, make sure to update hmR0SvmHandleExit(). */
990 pVmcbCtrl->u32InterceptXcpt |= 0
991 | RT_BIT(X86_XCPT_BP)
992 | RT_BIT(X86_XCPT_DE)
993 | RT_BIT(X86_XCPT_NM)
994 | RT_BIT(X86_XCPT_UD)
995 | RT_BIT(X86_XCPT_NP)
996 | RT_BIT(X86_XCPT_SS)
997 | RT_BIT(X86_XCPT_GP)
998 | RT_BIT(X86_XCPT_PF)
999 | RT_BIT(X86_XCPT_MF)
1000 ;
1001#endif
1002
1003 /* Apply the exceptions intercepts needed by the GIM provider. */
1004 if (pVCpu->hm.s.fGIMTrapXcptUD)
1005 pVmcbCtrl->u32InterceptXcpt |= RT_BIT(X86_XCPT_UD);
1006
1007 /* Set up unconditional intercepts and conditions. */
1008 pVmcbCtrl->u64InterceptCtrl = HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS
1009 | SVM_CTRL_INTERCEPT_VMMCALL;
1010
1011#ifdef HMSVM_ALWAYS_TRAP_TASK_SWITCH
1012 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_TASK_SWITCH;
1013#endif
1014
1015#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1016 /* Virtualized VMSAVE/VMLOAD. */
1017 pVmcbCtrl->LbrVirt.n.u1VirtVmsaveVmload = fUseVirtVmsaveVmload;
1018 if (!fUseVirtVmsaveVmload)
1019 {
1020 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_VMSAVE
1021 | SVM_CTRL_INTERCEPT_VMLOAD;
1022 }
1023
1024 /* Virtual GIF. */
1025 pVmcbCtrl->IntCtrl.n.u1VGifEnable = fUseVGif;
1026 if (!fUseVGif)
1027 {
1028 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_CLGI
1029 | SVM_CTRL_INTERCEPT_STGI;
1030 }
1031#endif
1032
1033 /* CR4 writes must always be intercepted for tracking PGM mode changes. */
1034 pVmcbCtrl->u16InterceptWrCRx = RT_BIT(4);
1035
1036 /* Intercept all DRx reads and writes by default. Changed later on. */
1037 pVmcbCtrl->u16InterceptRdDRx = 0xffff;
1038 pVmcbCtrl->u16InterceptWrDRx = 0xffff;
1039
1040 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
1041 pVmcbCtrl->IntCtrl.n.u1VIntrMasking = 1;
1042
1043 /* Ignore the priority in the virtual TPR. This is necessary for delivering PIC style (ExtInt) interrupts
1044 and we currently deliver both PIC and APIC interrupts alike, see hmR0SvmEvaluatePendingEvent() */
1045 pVmcbCtrl->IntCtrl.n.u1IgnoreTPR = 1;
1046
1047 /* Set the IO permission bitmap physical addresses. */
1048 pVmcbCtrl->u64IOPMPhysAddr = g_HCPhysIOBitmap;
1049
1050 /* LBR virtualization. */
1051 pVmcbCtrl->LbrVirt.n.u1LbrVirt = fUseLbrVirt;
1052
1053 /* The host ASID MBZ, for the guest start with 1. */
1054 pVmcbCtrl->TLBCtrl.n.u32ASID = 1;
1055
1056 /* Setup Nested Paging. This doesn't change throughout the execution time of the VM. */
1057 pVmcbCtrl->NestedPagingCtrl.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
1058
1059 /* Without Nested Paging, we need additionally intercepts. */
1060 if (!pVM->hm.s.fNestedPaging)
1061 {
1062 /* CR3 reads/writes must be intercepted; our shadow values differ from the guest values. */
1063 pVmcbCtrl->u16InterceptRdCRx |= RT_BIT(3);
1064 pVmcbCtrl->u16InterceptWrCRx |= RT_BIT(3);
1065
1066 /* Intercept INVLPG and task switches (may change CR3, EFLAGS, LDT). */
1067 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_INVLPG
1068 | SVM_CTRL_INTERCEPT_TASK_SWITCH;
1069
1070 /* Page faults must be intercepted to implement shadow paging. */
1071 pVmcbCtrl->u32InterceptXcpt |= RT_BIT(X86_XCPT_PF);
1072 }
1073
1074 /* Setup Pause Filter for guest pause-loop (spinlock) exiting. */
1075 if (fUsePauseFilter)
1076 {
1077 Assert(pVM->hm.s.svm.cPauseFilter > 0);
1078 pVmcbCtrl->u16PauseFilterCount = pVM->hm.s.svm.cPauseFilter;
1079 if (fPauseFilterThreshold)
1080 pVmcbCtrl->u16PauseFilterThreshold = pVM->hm.s.svm.cPauseFilterThresholdTicks;
1081 pVmcbCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_PAUSE;
1082 }
1083
1084 /*
1085 * Setup the MSR permission bitmap.
1086 * The following MSRs are saved/restored automatically during the world-switch.
1087 * Don't intercept guest read/write accesses to these MSRs.
1088 */
1089 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
1090 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1091 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1092 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_CSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1093 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K6_STAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1094 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_SF_MASK, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1095 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_FS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1096 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1097 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_KERNEL_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1098 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_IA32_SYSENTER_CS, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1099 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_IA32_SYSENTER_ESP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1100 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_IA32_SYSENTER_EIP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1101 pVmcbCtrl->u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
1102
1103 /* Initially all VMCB clean bits MBZ indicating that everything should be loaded from the VMCB in memory. */
1104 Assert(pVmcbCtrl->u32VmcbCleanBits == 0);
1105
1106 for (VMCPUID i = 1; i < pVM->cCpus; i++)
1107 {
1108 PVMCPU pVCpuCur = &pVM->aCpus[i];
1109 PSVMVMCB pVmcbCur = pVM->aCpus[i].hm.s.svm.pVmcb;
1110 AssertMsgReturn(pVmcbCur, ("Invalid pVmcb for vcpu[%u]\n", i), VERR_SVM_INVALID_PVMCB);
1111 PSVMVMCBCTRL pVmcbCtrlCur = &pVmcbCur->ctrl;
1112
1113 /* Copy the VMCB control area. */
1114 memcpy(pVmcbCtrlCur, pVmcbCtrl, sizeof(*pVmcbCtrlCur));
1115
1116 /* Copy the MSR bitmap and setup the VCPU-specific host physical address. */
1117 uint8_t *pbMsrBitmapCur = (uint8_t *)pVCpuCur->hm.s.svm.pvMsrBitmap;
1118 memcpy(pbMsrBitmapCur, pbMsrBitmap, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
1119 pVmcbCtrlCur->u64MSRPMPhysAddr = pVCpuCur->hm.s.svm.HCPhysMsrBitmap;
1120
1121 /* Initially all VMCB clean bits MBZ indicating that everything should be loaded from the VMCB in memory. */
1122 Assert(pVmcbCtrlCur->u32VmcbCleanBits == 0);
1123
1124 /* Verify our assumption that GIM providers trap #UD uniformly across VCPUs initially. */
1125 Assert(pVCpuCur->hm.s.fGIMTrapXcptUD == pVCpu->hm.s.fGIMTrapXcptUD);
1126 }
1127
1128 return VINF_SUCCESS;
1129}
1130
1131
1132/**
1133 * Gets a pointer to the currently active guest (or nested-guest) VMCB.
1134 *
1135 * @returns Pointer to the current context VMCB.
1136 * @param pVCpu The cross context virtual CPU structure.
1137 * @param pCtx Pointer to the guest-CPU context.
1138 */
1139DECLINLINE(PSVMVMCB) hmR0SvmGetCurrentVmcb(PVMCPU pVCpu, PCPUMCTX pCtx)
1140{
1141#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1142 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1143 return pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
1144#else
1145 RT_NOREF(pCtx);
1146#endif
1147 return pVCpu->hm.s.svm.pVmcb;
1148}
1149
1150
1151/**
1152 * Gets a pointer to the nested-guest VMCB cache.
1153 *
1154 * @returns Pointer to the nested-guest VMCB cache.
1155 * @param pVCpu The cross context virtual CPU structure.
1156 */
1157DECLINLINE(PSVMNESTEDVMCBCACHE) hmR0SvmGetNestedVmcbCache(PVMCPU pVCpu)
1158{
1159#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1160 Assert(pVCpu->hm.s.svm.NstGstVmcbCache.fCacheValid);
1161 return &pVCpu->hm.s.svm.NstGstVmcbCache;
1162#else
1163 RT_NOREF(pVCpu);
1164 return NULL;
1165#endif
1166}
1167
1168
1169/**
1170 * Invalidates a guest page by guest virtual address.
1171 *
1172 * @returns VBox status code.
1173 * @param pVM The cross context VM structure.
1174 * @param pVCpu The cross context virtual CPU structure.
1175 * @param GCVirt Guest virtual address of the page to invalidate.
1176 */
1177VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
1178{
1179 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1180 Assert(pVM->hm.s.svm.fSupported);
1181
1182 bool fFlushPending = pVM->hm.s.svm.fAlwaysFlushTLB || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_FLUSH);
1183
1184 /* Skip it if a TLB flush is already pending. */
1185 if (!fFlushPending)
1186 {
1187 Log4(("SVMR0InvalidatePage %RGv\n", GCVirt));
1188
1189 PCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
1190 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
1191 AssertMsgReturn(pVmcb, ("Invalid pVmcb!\n"), VERR_SVM_INVALID_PVMCB);
1192
1193#if HC_ARCH_BITS == 32
1194 /* If we get a flush in 64-bit guest mode, then force a full TLB flush. INVLPGA takes only 32-bit addresses. */
1195 if (CPUMIsGuestInLongMode(pVCpu))
1196 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1197 else
1198#endif
1199 {
1200 SVMR0InvlpgA(GCVirt, pVmcb->ctrl.TLBCtrl.n.u32ASID);
1201 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
1202 }
1203 }
1204 return VINF_SUCCESS;
1205}
1206
1207
1208/**
1209 * Flushes the appropriate tagged-TLB entries.
1210 *
1211 * @param pVCpu The cross context virtual CPU structure.
1212 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
1213 * @param pVmcb Pointer to the VM control block.
1214 * @param pHostCpu Pointer to the HM host-CPU info.
1215 */
1216static void hmR0SvmFlushTaggedTlb(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb, PHMGLOBALCPUINFO pHostCpu)
1217{
1218#ifndef VBOX_WITH_NESTED_HWVIRT_SVM
1219 RT_NOREF(pCtx);
1220#endif
1221 PVM pVM = pVCpu->CTX_SUFF(pVM);
1222
1223 /*
1224 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
1225 * This can happen both for start & resume due to long jumps back to ring-3.
1226 *
1227 * We also force a TLB flush every time when executing a nested-guest VCPU as there is no correlation
1228 * between it and the physical CPU.
1229 *
1230 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
1231 * so we cannot reuse the ASIDs without flushing.
1232 */
1233 bool fNewAsid = false;
1234 Assert(pHostCpu->idCpu != NIL_RTCPUID);
1235 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
1236 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes
1237#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1238 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
1239#endif
1240 )
1241 {
1242 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
1243 pVCpu->hm.s.fForceTLBFlush = true;
1244 fNewAsid = true;
1245 }
1246
1247 /* Set TLB flush state as checked until we return from the world switch. */
1248 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
1249
1250 /* Check for explicit TLB flushes. */
1251 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
1252 {
1253 pVCpu->hm.s.fForceTLBFlush = true;
1254 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
1255 }
1256
1257 /*
1258 * If the AMD CPU erratum 170, We need to flush the entire TLB for each world switch. Sad.
1259 * This Host CPU requirement takes precedence.
1260 */
1261 if (pVM->hm.s.svm.fAlwaysFlushTLB)
1262 {
1263 pHostCpu->uCurrentAsid = 1;
1264 pVCpu->hm.s.uCurrentAsid = 1;
1265 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
1266 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
1267 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1268
1269 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
1270 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1271 }
1272 else
1273 {
1274 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
1275 if (pVCpu->hm.s.fForceTLBFlush)
1276 {
1277 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
1278 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1279
1280 if (fNewAsid)
1281 {
1282 ++pHostCpu->uCurrentAsid;
1283
1284 bool fHitASIDLimit = false;
1285 if (pHostCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
1286 {
1287 pHostCpu->uCurrentAsid = 1; /* Wraparound at 1; host uses 0 */
1288 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new ASID. */
1289 fHitASIDLimit = true;
1290 }
1291
1292 if ( fHitASIDLimit
1293 || pHostCpu->fFlushAsidBeforeUse)
1294 {
1295 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1296 pHostCpu->fFlushAsidBeforeUse = false;
1297 }
1298
1299 pVCpu->hm.s.uCurrentAsid = pHostCpu->uCurrentAsid;
1300 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
1301 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
1302 }
1303 else
1304 {
1305 if (pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1306 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1307 else
1308 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1309 }
1310
1311 pVCpu->hm.s.fForceTLBFlush = false;
1312 }
1313 }
1314
1315 /* Update VMCB with the ASID. */
1316 if (pVmcb->ctrl.TLBCtrl.n.u32ASID != pVCpu->hm.s.uCurrentAsid)
1317 {
1318 pVmcb->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
1319 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_ASID;
1320 }
1321
1322 AssertMsg(pVCpu->hm.s.idLastCpu == pHostCpu->idCpu,
1323 ("vcpu idLastCpu=%u hostcpu idCpu=%u\n", pVCpu->hm.s.idLastCpu, pHostCpu->idCpu));
1324 AssertMsg(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes,
1325 ("Flush count mismatch for cpu %u (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pHostCpu->cTlbFlushes));
1326 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
1327 ("cpu%d uCurrentAsid = %x\n", pHostCpu->idCpu, pHostCpu->uCurrentAsid));
1328 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
1329 ("cpu%d VM uCurrentAsid = %x\n", pHostCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
1330
1331#ifdef VBOX_WITH_STATISTICS
1332 if (pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
1333 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
1334 else if ( pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
1335 || pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
1336 {
1337 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
1338 }
1339 else
1340 {
1341 Assert(pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_ENTIRE);
1342 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushEntire);
1343 }
1344#endif
1345}
1346
1347
1348/** @name 64-bit guest on 32-bit host OS helper functions.
1349 *
1350 * The host CPU is still 64-bit capable but the host OS is running in 32-bit
1351 * mode (code segment, paging). These wrappers/helpers perform the necessary
1352 * bits for the 32->64 switcher.
1353 *
1354 * @{ */
1355#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
1356/**
1357 * Prepares for and executes VMRUN (64-bit guests on a 32-bit host).
1358 *
1359 * @returns VBox status code.
1360 * @param HCPhysVmcbHost Physical address of host VMCB.
1361 * @param HCPhysVmcb Physical address of the VMCB.
1362 * @param pCtx Pointer to the guest-CPU context.
1363 * @param pVM The cross context VM structure.
1364 * @param pVCpu The cross context virtual CPU structure.
1365 */
1366DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVmcbHost, RTHCPHYS HCPhysVmcb, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
1367{
1368 uint32_t aParam[8];
1369 aParam[0] = RT_LO_U32(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Lo. */
1370 aParam[1] = RT_HI_U32(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Hi. */
1371 aParam[2] = RT_LO_U32(HCPhysVmcb); /* Param 2: HCPhysVmcb - Lo. */
1372 aParam[3] = RT_HI_U32(HCPhysVmcb); /* Param 2: HCPhysVmcb - Hi. */
1373 aParam[4] = VM_RC_ADDR(pVM, pVM);
1374 aParam[5] = 0;
1375 aParam[6] = VM_RC_ADDR(pVM, pVCpu);
1376 aParam[7] = 0;
1377
1378 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_SVMRCVMRun64, RT_ELEMENTS(aParam), &aParam[0]);
1379}
1380
1381
1382/**
1383 * Executes the specified VMRUN handler in 64-bit mode.
1384 *
1385 * @returns VBox status code.
1386 * @param pVM The cross context VM structure.
1387 * @param pVCpu The cross context virtual CPU structure.
1388 * @param pCtx Pointer to the guest-CPU context.
1389 * @param enmOp The operation to perform.
1390 * @param cParams Number of parameters.
1391 * @param paParam Array of 32-bit parameters.
1392 */
1393VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp,
1394 uint32_t cParams, uint32_t *paParam)
1395{
1396 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
1397 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
1398
1399 NOREF(pCtx);
1400
1401 /* Disable interrupts. */
1402 RTHCUINTREG uOldEFlags = ASMIntDisableFlags();
1403
1404#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
1405 RTCPUID idHostCpu = RTMpCpuId();
1406 CPUMR0SetLApic(pVCpu, idHostCpu);
1407#endif
1408
1409 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
1410 CPUMSetHyperEIP(pVCpu, enmOp);
1411 for (int i = (int)cParams - 1; i >= 0; i--)
1412 CPUMPushHyper(pVCpu, paParam[i]);
1413
1414 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
1415 /* Call the switcher. */
1416 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
1417 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
1418
1419 /* Restore interrupts. */
1420 ASMSetFlags(uOldEFlags);
1421 return rc;
1422}
1423
1424#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
1425/** @} */
1426
1427
1428/**
1429 * Sets an exception intercept in the specified VMCB.
1430 *
1431 * @param pVmcb Pointer to the VM control block.
1432 * @param uXcpt The exception (X86_XCPT_*).
1433 */
1434DECLINLINE(void) hmR0SvmSetXcptIntercept(PSVMVMCB pVmcb, uint8_t uXcpt)
1435{
1436 if (!(pVmcb->ctrl.u32InterceptXcpt & RT_BIT(uXcpt)))
1437 {
1438 pVmcb->ctrl.u32InterceptXcpt |= RT_BIT(uXcpt);
1439 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1440 }
1441}
1442
1443
1444/**
1445 * Clears an exception intercept in the specified VMCB.
1446 *
1447 * @param pVCpu The cross context virtual CPU structure.
1448 * @param pCtx Pointer to the guest-CPU context.
1449 * @param pVmcb Pointer to the VM control block.
1450 * @param uXcpt The exception (X86_XCPT_*).
1451 *
1452 * @remarks This takes into account if we're executing a nested-guest and only
1453 * removes the exception intercept if both the guest -and- nested-guest
1454 * are not intercepting it.
1455 */
1456DECLINLINE(void) hmR0SvmClearXcptIntercept(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb, uint8_t uXcpt)
1457{
1458 Assert(uXcpt != X86_XCPT_DB);
1459 Assert(uXcpt != X86_XCPT_AC);
1460#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
1461 if (pVmcb->ctrl.u32InterceptXcpt & RT_BIT(uXcpt))
1462 {
1463 bool fRemove = true;
1464#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1465 /* Only remove the intercept if the nested-guest is also not intercepting it! */
1466 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1467 {
1468 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1469 fRemove = !(pVmcbNstGstCache->u32InterceptXcpt & RT_BIT(uXcpt));
1470 }
1471#else
1472 RT_NOREF2(pVCpu, pCtx);
1473#endif
1474 if (fRemove)
1475 {
1476 pVmcb->ctrl.u32InterceptXcpt &= ~RT_BIT(uXcpt);
1477 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1478 }
1479 }
1480#else
1481 RT_NOREF3(pVCpu, pCtx, pVmcb);
1482#endif
1483}
1484
1485
1486/**
1487 * Sets a control intercept in the specified VMCB.
1488 *
1489 * @param pVmcb Pointer to the VM control block.
1490 * @param fCtrlIntercept The control intercept (SVM_CTRL_INTERCEPT_*).
1491 */
1492DECLINLINE(void) hmR0SvmSetCtrlIntercept(PSVMVMCB pVmcb, uint64_t fCtrlIntercept)
1493{
1494 if (!(pVmcb->ctrl.u64InterceptCtrl & fCtrlIntercept))
1495 {
1496 pVmcb->ctrl.u64InterceptCtrl |= fCtrlIntercept;
1497 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1498 }
1499}
1500
1501
1502/**
1503 * Clears a control intercept in the specified VMCB.
1504 *
1505 * @returns @c true if the intercept is still set, @c false otherwise.
1506 * @param pVCpu The cross context virtual CPU structure.
1507 * @param pCtx Pointer to the guest-CPU context.
1508 * @param pVmcb Pointer to the VM control block.
1509 * @param fCtrlIntercept The control intercept (SVM_CTRL_INTERCEPT_*).
1510 *
1511 * @remarks This takes into account if we're executing a nested-guest and only
1512 * removes the control intercept if both the guest -and- nested-guest
1513 * are not intercepting it.
1514 */
1515DECLINLINE(bool) hmR0SvmClearCtrlIntercept(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb, uint64_t fCtrlIntercept)
1516{
1517 if (pVmcb->ctrl.u64InterceptCtrl & fCtrlIntercept)
1518 {
1519 bool fRemove = true;
1520#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
1521 /* Only remove the control intercept if the nested-guest is also not intercepting it! */
1522 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1523 {
1524 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1525 fRemove = !(pVmcbNstGstCache->u64InterceptCtrl & fCtrlIntercept);
1526 }
1527#else
1528 RT_NOREF2(pVCpu, pCtx);
1529#endif
1530 if (fRemove)
1531 {
1532 pVmcb->ctrl.u64InterceptCtrl &= ~fCtrlIntercept;
1533 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1534 }
1535 }
1536
1537 return RT_BOOL(pVmcb->ctrl.u64InterceptCtrl & fCtrlIntercept);
1538}
1539
1540
1541/**
1542 * Loads the guest (or nested-guest) CR0 control register into the guest-state
1543 * area in the VMCB.
1544 *
1545 * Although the guest CR0 is a separate field in the VMCB we have to consider
1546 * the FPU state itself which is shared between the host and the guest.
1547 *
1548 * @returns VBox status code.
1549 * @param pVCpu The cross context virtual CPU structure.
1550 * @param pVmcb Pointer to the VM control block.
1551 * @param pCtx Pointer to the guest-CPU context.
1552 *
1553 * @remarks No-long-jump zone!!!
1554 */
1555static void hmR0SvmLoadSharedCR0(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
1556{
1557 /* The guest FPU is now always pre-loaded before executing guest code, see @bugref{7243#c101}. */
1558 Assert(CPUMIsGuestFPUStateActive(pVCpu));
1559
1560 uint64_t const uGuestCr0 = pCtx->cr0;
1561 uint64_t uShadowCr0 = uGuestCr0;
1562
1563 /* Always enable caching. */
1564 uShadowCr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1565
1566 /* When Nested Paging is not available use shadow page tables and intercept #PFs (the latter done in SVMR0SetupVM()). */
1567 if (!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
1568 {
1569 uShadowCr0 |= X86_CR0_PG /* Use shadow page tables. */
1570 | X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF #VMEXIT. */
1571 }
1572
1573 /*
1574 * Use the #MF style of legacy-FPU error reporting for now. Although AMD-V has MSRs that lets us
1575 * isolate the host from it, IEM/REM still needs work to emulate it properly. see @bugref{7243#c103}.
1576 */
1577 if (!(uGuestCr0 & X86_CR0_NE))
1578 {
1579 uShadowCr0 |= X86_CR0_NE;
1580 hmR0SvmSetXcptIntercept(pVmcb, X86_XCPT_MF);
1581 }
1582 else
1583 hmR0SvmClearXcptIntercept(pVCpu, pCtx, pVmcb, X86_XCPT_MF);
1584
1585 /*
1586 * If the shadow and guest CR0 are identical we can avoid intercepting CR0 reads.
1587 *
1588 * CR0 writes still needs interception as PGM requires tracking paging mode changes, see @bugref{6944}.
1589 * We also don't ever want to honor weird things like cache disable from the guest. However, we can
1590 * avoid intercepting changes to the TS & MP bits by clearing the CR0 write intercept below and keeping
1591 * SVM_CTRL_INTERCEPT_CR0_SEL_WRITE instead.
1592 */
1593 if (uShadowCr0 == uGuestCr0)
1594 {
1595 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1596 {
1597 pVmcb->ctrl.u16InterceptRdCRx &= ~RT_BIT(0);
1598 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(0);
1599 Assert(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_CR0_SEL_WRITE);
1600 }
1601 else
1602 {
1603 /* If the nested-hypervisor intercepts CR0 reads/writes, we need to continue intercepting them. */
1604 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1605 pVmcb->ctrl.u16InterceptRdCRx = (pVmcb->ctrl.u16InterceptRdCRx & ~RT_BIT(0))
1606 | (pVmcbNstGstCache->u16InterceptRdCRx & RT_BIT(0));
1607 pVmcb->ctrl.u16InterceptWrCRx = (pVmcb->ctrl.u16InterceptWrCRx & ~RT_BIT(0))
1608 | (pVmcbNstGstCache->u16InterceptWrCRx & RT_BIT(0));
1609 }
1610 }
1611 else
1612 {
1613 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(0);
1614 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(0);
1615 }
1616 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1617
1618 Assert(RT_HI_U32(uShadowCr0) == 0);
1619 if (pVmcb->guest.u64CR0 != uShadowCr0)
1620 {
1621 pVmcb->guest.u64CR0 = uShadowCr0;
1622 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1623 }
1624}
1625
1626
1627/**
1628 * Loads the guest/nested-guest control registers (CR2, CR3, CR4) into the VMCB.
1629 *
1630 * @returns VBox status code.
1631 * @param pVCpu The cross context virtual CPU structure.
1632 * @param pVmcb Pointer to the VM control block.
1633 * @param pCtx Pointer to the guest-CPU context.
1634 *
1635 * @remarks No-long-jump zone!!!
1636 */
1637static int hmR0SvmLoadGuestControlRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
1638{
1639 PVM pVM = pVCpu->CTX_SUFF(pVM);
1640
1641 /*
1642 * Guest CR2.
1643 */
1644 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR2))
1645 {
1646 pVmcb->guest.u64CR2 = pCtx->cr2;
1647 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CR2;
1648 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR2);
1649 }
1650
1651 /*
1652 * Guest CR3.
1653 */
1654 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR3))
1655 {
1656 if (pVM->hm.s.fNestedPaging)
1657 {
1658 PGMMODE enmShwPagingMode;
1659#if HC_ARCH_BITS == 32
1660 if (CPUMIsGuestInLongModeEx(pCtx))
1661 enmShwPagingMode = PGMMODE_AMD64_NX;
1662 else
1663#endif
1664 enmShwPagingMode = PGMGetHostMode(pVM);
1665
1666 pVmcb->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
1667 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1668 Assert(pVmcb->ctrl.u64NestedPagingCR3);
1669 pVmcb->guest.u64CR3 = pCtx->cr3;
1670 }
1671 else
1672 {
1673 pVmcb->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
1674 Log4(("hmR0SvmLoadGuestControlRegs: CR3=%#RX64 (HyperCR3=%#RX64)\n", pCtx->cr3, pVmcb->guest.u64CR3));
1675 }
1676
1677 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1678 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR3);
1679 }
1680
1681 /*
1682 * Guest CR4.
1683 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
1684 */
1685 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR4))
1686 {
1687 uint64_t uShadowCr4 = pCtx->cr4;
1688 if (!pVM->hm.s.fNestedPaging)
1689 {
1690 switch (pVCpu->hm.s.enmShadowMode)
1691 {
1692 case PGMMODE_REAL:
1693 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
1694 AssertFailed();
1695 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1696
1697 case PGMMODE_32_BIT: /* 32-bit paging. */
1698 uShadowCr4 &= ~X86_CR4_PAE;
1699 break;
1700
1701 case PGMMODE_PAE: /* PAE paging. */
1702 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1703 /** Must use PAE paging as we could use physical memory > 4 GB */
1704 uShadowCr4 |= X86_CR4_PAE;
1705 break;
1706
1707 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1708 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1709#ifdef VBOX_ENABLE_64_BITS_GUESTS
1710 break;
1711#else
1712 AssertFailed();
1713 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1714#endif
1715
1716 default: /* shut up gcc */
1717 AssertFailed();
1718 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1719 }
1720 }
1721
1722 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
1723 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
1724
1725 /* Avoid intercepting CR4 reads if the guest and shadow CR4 values are identical. */
1726 if (uShadowCr4 == pCtx->cr4)
1727 {
1728 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
1729 pVmcb->ctrl.u16InterceptRdCRx &= ~RT_BIT(4);
1730 else
1731 {
1732 /* If the nested-hypervisor intercepts CR4 reads, we need to continue intercepting them. */
1733 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = hmR0SvmGetNestedVmcbCache(pVCpu);
1734 pVmcb->ctrl.u16InterceptRdCRx = (pVmcb->ctrl.u16InterceptRdCRx & ~RT_BIT(4))
1735 | (pVmcbNstGstCache->u16InterceptRdCRx & RT_BIT(4));
1736 }
1737 }
1738 else
1739 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(4);
1740
1741 /* CR4 writes are always intercepted (both guest, nested-guest) from tracking PGM mode changes. */
1742 Assert(pVmcb->ctrl.u16InterceptWrCRx & RT_BIT(4));
1743
1744 /* Update VMCB with the shadow CR4 the appropriate VMCB clean bits. */
1745 Assert(RT_HI_U32(uShadowCr4) == 0);
1746 pVmcb->guest.u64CR4 = uShadowCr4;
1747 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_CRX_EFER | HMSVM_VMCB_CLEAN_INTERCEPTS);
1748
1749 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR4);
1750 }
1751
1752 return VINF_SUCCESS;
1753}
1754
1755
1756/**
1757 * Loads the guest (or nested-guest) segment registers into the VMCB.
1758 *
1759 * @returns VBox status code.
1760 * @param pVCpu The cross context virtual CPU structure.
1761 * @param pVmcb Pointer to the VM control block.
1762 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
1763 *
1764 * @remarks No-long-jump zone!!!
1765 */
1766static void hmR0SvmLoadGuestSegmentRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
1767{
1768 /* Guest Segment registers: CS, SS, DS, ES, FS, GS. */
1769 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS))
1770 {
1771 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, CS, cs);
1772 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, SS, ss);
1773 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, DS, ds);
1774 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, ES, es);
1775 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, FS, fs);
1776 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, GS, gs);
1777
1778 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1779 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_SEG;
1780 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS);
1781 }
1782
1783 /* Guest TR. */
1784 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_TR))
1785 {
1786 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, TR, tr);
1787 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_TR);
1788 }
1789
1790 /* Guest LDTR. */
1791 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LDTR))
1792 {
1793 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, &pVmcb->guest, LDTR, ldtr);
1794 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LDTR);
1795 }
1796
1797 /* Guest GDTR. */
1798 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_GDTR))
1799 {
1800 pVmcb->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
1801 pVmcb->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
1802 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1803 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_GDTR);
1804 }
1805
1806 /* Guest IDTR. */
1807 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_IDTR))
1808 {
1809 pVmcb->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
1810 pVmcb->guest.IDTR.u64Base = pCtx->idtr.pIdt;
1811 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1812 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_IDTR);
1813 }
1814}
1815
1816
1817/**
1818 * Loads the guest (or nested-guest) MSRs into the VMCB.
1819 *
1820 * @param pVCpu The cross context virtual CPU structure.
1821 * @param pVmcb Pointer to the VM control block.
1822 * @param pCtx Pointer to the guest-CPU context.
1823 *
1824 * @remarks No-long-jump zone!!!
1825 */
1826static void hmR0SvmLoadGuestMsrs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
1827{
1828 /* Guest Sysenter MSRs. */
1829 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR))
1830 {
1831 pVmcb->guest.u64SysEnterCS = pCtx->SysEnter.cs;
1832 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR);
1833 }
1834 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR))
1835 {
1836 pVmcb->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
1837 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
1838 }
1839 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR))
1840 {
1841 pVmcb->guest.u64SysEnterESP = pCtx->SysEnter.esp;
1842 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
1843 }
1844
1845 /*
1846 * Guest EFER MSR.
1847 * AMD-V requires guest EFER.SVME to be set. Weird.
1848 * See AMD spec. 15.5.1 "Basic Operation" | "Canonicalization and Consistency Checks".
1849 */
1850 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_EFER_MSR))
1851 {
1852 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
1853 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1854 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
1855 }
1856
1857 /* 64-bit MSRs. */
1858 if (CPUMIsGuestInLongModeEx(pCtx))
1859 {
1860 /* Load these always as the guest may modify FS/GS base using MSRs in 64-bit mode which we don't intercept. */
1861 //pVmcb->guest.FS.u64Base = pCtx->fs.u64Base;
1862 //pVmcb->guest.GS.u64Base = pCtx->gs.u64Base;
1863 //pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_SEG;
1864 }
1865 else
1866 {
1867 /* If the guest isn't in 64-bit mode, clear MSR_K6_LME bit from guest EFER otherwise AMD-V expects amd64 shadow paging. */
1868 if (pCtx->msrEFER & MSR_K6_EFER_LME)
1869 {
1870 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1871 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1872 }
1873 }
1874
1875 /** @todo HM_CHANGED_GUEST_SYSCALL_MSRS,
1876 * HM_CHANGED_GUEST_KERNEL_GS_BASE */
1877 pVmcb->guest.u64STAR = pCtx->msrSTAR;
1878 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR;
1879 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR;
1880 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK;
1881 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE;
1882
1883 /*
1884 * Setup the PAT MSR (applicable for Nested Paging only).
1885 *
1886 * While guests can modify and see the modified values throug the shadow values,
1887 * we shall not honor any guest modifications of this MSR to ensure caching is always
1888 * enabled similar to how we always run with CR0.CD and NW bits cleared.
1889 *
1890 * For nested-guests this needs to always be set as well, see @bugref{7243#c109}.
1891 */
1892 pVmcb->guest.u64PAT = MSR_IA32_CR_PAT_INIT_VAL;
1893
1894 /* Enable the last branch record bit if LBR virtualization is enabled. */
1895 if (pVmcb->ctrl.LbrVirt.n.u1LbrVirt)
1896 pVmcb->guest.u64DBGCTL = MSR_IA32_DEBUGCTL_LBR;
1897}
1898
1899
1900/**
1901 * Loads the guest (or nested-guest) debug state into the VMCB and programs the
1902 * necessary intercepts accordingly.
1903 *
1904 * @param pVCpu The cross context virtual CPU structure.
1905 * @param pVmcb Pointer to the VM control block.
1906 * @param pCtx Pointer to the guest-CPU context.
1907 *
1908 * @remarks No-long-jump zone!!!
1909 * @remarks Requires EFLAGS to be up-to-date in the VMCB!
1910 */
1911static void hmR0SvmLoadSharedDebugState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
1912{
1913 bool fInterceptMovDRx = false;
1914
1915 /*
1916 * Anyone single stepping on the host side? If so, we'll have to use the
1917 * trap flag in the guest EFLAGS since AMD-V doesn't have a trap flag on
1918 * the VMM level like the VT-x implementations does.
1919 */
1920 bool const fStepping = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
1921 if (fStepping)
1922 {
1923 pVCpu->hm.s.fClearTrapFlag = true;
1924 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1925 fInterceptMovDRx = true; /* Need clean DR6, no guest mess. */
1926 }
1927
1928 if ( fStepping
1929 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
1930 {
1931 /*
1932 * Use the combined guest and host DRx values found in the hypervisor
1933 * register set because the debugger has breakpoints active or someone
1934 * is single stepping on the host side.
1935 *
1936 * Note! DBGF expects a clean DR6 state before executing guest code.
1937 */
1938#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1939 if ( CPUMIsGuestInLongModeEx(pCtx)
1940 && !CPUMIsHyperDebugStateActivePending(pVCpu))
1941 {
1942 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1943 Assert(!CPUMIsGuestDebugStateActivePending(pVCpu));
1944 Assert(CPUMIsHyperDebugStateActivePending(pVCpu));
1945 }
1946 else
1947#endif
1948 if (!CPUMIsHyperDebugStateActive(pVCpu))
1949 {
1950 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1951 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1952 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1953 }
1954
1955 /* Update DR6 & DR7. (The other DRx values are handled by CPUM one way or the other.) */
1956 if ( pVmcb->guest.u64DR6 != X86_DR6_INIT_VAL
1957 || pVmcb->guest.u64DR7 != CPUMGetHyperDR7(pVCpu))
1958 {
1959 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1960 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
1961 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1962 pVCpu->hm.s.fUsingHyperDR7 = true;
1963 }
1964
1965 /** @todo If we cared, we could optimize to allow the guest to read registers
1966 * with the same values. */
1967 fInterceptMovDRx = true;
1968 Log5(("hmR0SvmLoadSharedDebugState: Loaded hyper DRx\n"));
1969 }
1970 else
1971 {
1972 /*
1973 * Update DR6, DR7 with the guest values if necessary.
1974 */
1975 if ( pVmcb->guest.u64DR7 != pCtx->dr[7]
1976 || pVmcb->guest.u64DR6 != pCtx->dr[6])
1977 {
1978 pVmcb->guest.u64DR7 = pCtx->dr[7];
1979 pVmcb->guest.u64DR6 = pCtx->dr[6];
1980 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1981 pVCpu->hm.s.fUsingHyperDR7 = false;
1982 }
1983
1984 /*
1985 * If the guest has enabled debug registers, we need to load them prior to
1986 * executing guest code so they'll trigger at the right time.
1987 */
1988 if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
1989 {
1990#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1991 if ( CPUMIsGuestInLongModeEx(pCtx)
1992 && !CPUMIsGuestDebugStateActivePending(pVCpu))
1993 {
1994 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
1995 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1996 Assert(!CPUMIsHyperDebugStateActivePending(pVCpu));
1997 Assert(CPUMIsGuestDebugStateActivePending(pVCpu));
1998 }
1999 else
2000#endif
2001 if (!CPUMIsGuestDebugStateActive(pVCpu))
2002 {
2003 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
2004 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
2005 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
2006 Assert(CPUMIsGuestDebugStateActive(pVCpu));
2007 }
2008 Log5(("hmR0SvmLoadSharedDebugState: Loaded guest DRx\n"));
2009 }
2010 /*
2011 * If no debugging enabled, we'll lazy load DR0-3. We don't need to
2012 * intercept #DB as DR6 is updated in the VMCB.
2013 *
2014 * Note! If we cared and dared, we could skip intercepting \#DB here.
2015 * However, \#DB shouldn't be performance critical, so we'll play safe
2016 * and keep the code similar to the VT-x code and always intercept it.
2017 */
2018#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
2019 else if ( !CPUMIsGuestDebugStateActivePending(pVCpu)
2020 && !CPUMIsGuestDebugStateActive(pVCpu))
2021#else
2022 else if (!CPUMIsGuestDebugStateActive(pVCpu))
2023#endif
2024 {
2025 fInterceptMovDRx = true;
2026 }
2027 }
2028
2029 Assert(pVmcb->ctrl.u32InterceptXcpt & RT_BIT_32(X86_XCPT_DB));
2030 if (fInterceptMovDRx)
2031 {
2032 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
2033 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
2034 {
2035 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
2036 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
2037 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2038 }
2039 }
2040 else
2041 {
2042 if ( pVmcb->ctrl.u16InterceptRdDRx
2043 || pVmcb->ctrl.u16InterceptWrDRx)
2044 {
2045 pVmcb->ctrl.u16InterceptRdDRx = 0;
2046 pVmcb->ctrl.u16InterceptWrDRx = 0;
2047 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2048 }
2049 }
2050 Log4(("hmR0SvmLoadSharedDebugState: DR6=%#RX64 DR7=%#RX64\n", pCtx->dr[6], pCtx->dr[7]));
2051}
2052
2053
2054#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2055/**
2056 * Loads the nested-guest APIC state (currently just the TPR).
2057 *
2058 * @param pVCpu The cross context virtual CPU structure.
2059 * @param pVmcbNstGst Pointer to the nested-guest VM control block.
2060 */
2061static void hmR0SvmLoadGuestApicStateNested(PVMCPU pVCpu, PSVMVMCB pVmcbNstGst)
2062{
2063 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_APIC_STATE))
2064 {
2065 Assert(pVmcbNstGst->ctrl.IntCtrl.n.u1VIntrMasking == 1); RT_NOREF(pVmcbNstGst);
2066 pVCpu->hm.s.svm.fSyncVTpr = false;
2067 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
2068 }
2069}
2070
2071
2072/**
2073 * Loads the nested-guest hardware virtualization state.
2074 *
2075 * @param pVCpu The cross context virtual CPU structure.
2076 * @param pVmcbNstGst Pointer to the nested-guest VM control block.
2077 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
2078 */
2079static void hmR0SvmLoadGuestHwvirtStateNested(PVMCPU pVCpu, PSVMVMCB pVmcbNstGst, PCCPUMCTX pCtx)
2080{
2081 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_HWVIRT))
2082 {
2083 /*
2084 * Ensure the nested-guest pause-filter counters don't exceed the outer guest values esp.
2085 * since SVM doesn't have a preemption timer.
2086 *
2087 * We do this here rather than in hmR0SvmSetupVmcbNested() as we may have been executing the
2088 * nested-guest in IEM incl. PAUSE instructions which would update the pause-filter counters
2089 * and may continue execution in SVM R0 without a nested-guest #VMEXIT in between.
2090 */
2091 PVM pVM = pVCpu->CTX_SUFF(pVM);
2092 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2093 uint16_t const uGuestPauseFilterCount = pVM->hm.s.svm.cPauseFilter;
2094 uint16_t const uGuestPauseFilterThreshold = pVM->hm.s.svm.cPauseFilterThresholdTicks;
2095 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_PAUSE))
2096 {
2097 pVmcbNstGstCtrl->u16PauseFilterCount = RT_MIN(pCtx->hwvirt.svm.cPauseFilter, uGuestPauseFilterCount);
2098 pVmcbNstGstCtrl->u16PauseFilterThreshold = RT_MIN(pCtx->hwvirt.svm.cPauseFilterThreshold, uGuestPauseFilterThreshold);
2099 pVmcbNstGstCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2100 }
2101 else
2102 {
2103 pVmcbNstGstCtrl->u16PauseFilterCount = uGuestPauseFilterCount;
2104 pVmcbNstGstCtrl->u16PauseFilterThreshold = uGuestPauseFilterThreshold;
2105 }
2106
2107 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_HWVIRT);
2108 }
2109}
2110#endif
2111
2112/**
2113 * Loads the guest APIC state (currently just the TPR).
2114 *
2115 * @returns VBox status code.
2116 * @param pVCpu The cross context virtual CPU structure.
2117 * @param pVmcb Pointer to the VM control block.
2118 * @param pCtx Pointer to the guest-CPU context.
2119 */
2120static int hmR0SvmLoadGuestApicState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
2121{
2122 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_APIC_STATE))
2123 return VINF_SUCCESS;
2124
2125 int rc = VINF_SUCCESS;
2126 PVM pVM = pVCpu->CTX_SUFF(pVM);
2127 if ( PDMHasApic(pVM)
2128 && APICIsEnabled(pVCpu))
2129 {
2130 bool fPendingIntr;
2131 uint8_t u8Tpr;
2132 rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
2133 AssertRCReturn(rc, rc);
2134
2135 /* Assume that we need to trap all TPR accesses and thus need not check on
2136 every #VMEXIT if we should update the TPR. */
2137 Assert(pVmcb->ctrl.IntCtrl.n.u1VIntrMasking);
2138 pVCpu->hm.s.svm.fSyncVTpr = false;
2139
2140 if (!pVM->hm.s.fTPRPatchingActive)
2141 {
2142 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
2143 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
2144
2145 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we can deliver the interrupt to the guest. */
2146 if (fPendingIntr)
2147 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
2148 else
2149 {
2150 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
2151 pVCpu->hm.s.svm.fSyncVTpr = true;
2152 }
2153
2154 pVmcb->ctrl.u32VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_INT_CTRL);
2155 }
2156 else
2157 {
2158 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
2159 pVmcb->guest.u64LSTAR = u8Tpr;
2160 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
2161
2162 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
2163 if (fPendingIntr)
2164 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
2165 else
2166 {
2167 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
2168 pVCpu->hm.s.svm.fSyncVTpr = true;
2169 }
2170 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
2171 }
2172 }
2173
2174 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
2175 return rc;
2176}
2177
2178
2179/**
2180 * Loads the exception interrupts required for guest (or nested-guest) execution in
2181 * the VMCB.
2182 *
2183 * @param pVCpu The cross context virtual CPU structure.
2184 * @param pVmcb Pointer to the VM control block.
2185 * @param pCtx Pointer to the guest-CPU context.
2186 */
2187static void hmR0SvmLoadGuestXcptIntercepts(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
2188{
2189 /* If we modify intercepts from here, please check & adjust hmR0SvmLoadGuestXcptInterceptsNested()
2190 if required. */
2191 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMM_GUEST_XCPT_INTERCEPTS))
2192 {
2193 /* Trap #UD for GIM provider (e.g. for hypercalls). */
2194 if (pVCpu->hm.s.fGIMTrapXcptUD)
2195 hmR0SvmSetXcptIntercept(pVmcb, X86_XCPT_UD);
2196 else
2197 hmR0SvmClearXcptIntercept(pVCpu, pCtx, pVmcb, X86_XCPT_UD);
2198
2199 /* Trap #BP for INT3 debug breakpoints set by the VM debugger. */
2200 if (pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
2201 hmR0SvmSetXcptIntercept(pVmcb, X86_XCPT_BP);
2202 else
2203 hmR0SvmClearXcptIntercept(pVCpu, pCtx, pVmcb, X86_XCPT_BP);
2204
2205 /* The remaining intercepts are handled elsewhere, e.g. in hmR0SvmLoadSharedCR0(). */
2206 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMM_GUEST_XCPT_INTERCEPTS);
2207 }
2208}
2209
2210
2211#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2212/**
2213 * Merges guest and nested-guest intercepts for executing the nested-guest using
2214 * hardware-assisted SVM.
2215 *
2216 * This merges the guest and nested-guest intercepts in a way that if the outer
2217 * guest intercept is set we need to intercept it in the nested-guest as
2218 * well.
2219 *
2220 * @param pVCpu The cross context virtual CPU structure.
2221 * @param pVmcbNstGst Pointer to the nested-guest VM control block.
2222 * @param pCtx Pointer to the nested-guest-CPU context.
2223 */
2224static void hmR0SvmMergeVmcbCtrlsNested(PVMCPU pVCpu, PCCPUMCTX pCtx)
2225{
2226 PVM pVM = pVCpu->CTX_SUFF(pVM);
2227 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
2228 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2229 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2230
2231 /* Merge the guest's CR intercepts into the nested-guest VMCB. */
2232 pVmcbNstGstCtrl->u16InterceptRdCRx |= pVmcb->ctrl.u16InterceptRdCRx;
2233 pVmcbNstGstCtrl->u16InterceptWrCRx |= pVmcb->ctrl.u16InterceptWrCRx;
2234
2235 /* Always intercept CR4 writes for tracking PGM mode changes. */
2236 pVmcbNstGstCtrl->u16InterceptWrCRx |= RT_BIT(4);
2237
2238 /* Without nested paging, intercept CR3 reads and writes as we load shadow page tables. */
2239 if (!pVM->hm.s.fNestedPaging)
2240 {
2241 pVmcbNstGstCtrl->u16InterceptRdCRx |= RT_BIT(3);
2242 pVmcbNstGstCtrl->u16InterceptWrCRx |= RT_BIT(3);
2243 }
2244
2245 /** @todo Figure out debugging with nested-guests, till then just intercept
2246 * all DR[0-15] accesses. */
2247 pVmcbNstGstCtrl->u16InterceptRdDRx |= 0xffff;
2248 pVmcbNstGstCtrl->u16InterceptWrDRx |= 0xffff;
2249
2250 /*
2251 * Merge the guest's exception intercepts into the nested-guest VMCB.
2252 *
2253 * - \#UD: Exclude these as the outer guest's GIM hypercalls are not applicable
2254 * while executing the nested-guest.
2255 *
2256 * - \#BP: Exclude breakpoints set by the VM debugger for the outer guest. This can
2257 * be tweaked later depending on how we wish to implement breakpoints.
2258 *
2259 * Warning!! This ASSUMES we only intercept \#UD for hypercall purposes and \#BP
2260 * for VM debugger breakpoints, see hmR0SvmLoadGuestXcptIntercepts.
2261 */
2262#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
2263 pVmcbNstGstCtrl->u32InterceptXcpt |= (pVmcb->ctrl.u32InterceptXcpt & ~( RT_BIT(X86_XCPT_UD)
2264 | RT_BIT(X86_XCPT_BP)));
2265#else
2266 pVmcbNstGstCtrl->u32InterceptXcpt |= pVmcb->ctrl.u32InterceptXcpt;
2267#endif
2268
2269 /*
2270 * Adjust intercepts while executing the nested-guest that differ from the
2271 * outer guest intercepts.
2272 *
2273 * - VINTR: Exclude the outer guest intercept as we don't need to cause VINTR #VMEXITs
2274 * that belong to the nested-guest to the outer guest.
2275 *
2276 * - VMMCALL: Exclude the outer guest intercept as when it's also not intercepted by
2277 * the nested-guest, the physical CPU raises a \#UD exception as expected.
2278 */
2279 pVmcbNstGstCtrl->u64InterceptCtrl |= (pVmcb->ctrl.u64InterceptCtrl & ~( SVM_CTRL_INTERCEPT_VINTR
2280 | SVM_CTRL_INTERCEPT_VMMCALL))
2281 | HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS;
2282
2283 Assert( (pVmcbNstGstCtrl->u64InterceptCtrl & HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS)
2284 == HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS);
2285
2286 /* Finally, update the VMCB clean bits. */
2287 pVmcbNstGstCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2288}
2289#endif
2290
2291
2292/**
2293 * Sets up the appropriate function to run guest code.
2294 *
2295 * @returns VBox status code.
2296 * @param pVCpu The cross context virtual CPU structure.
2297 *
2298 * @remarks No-long-jump zone!!!
2299 */
2300static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu)
2301{
2302 if (CPUMIsGuestInLongMode(pVCpu))
2303 {
2304#ifndef VBOX_ENABLE_64_BITS_GUESTS
2305 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
2306#endif
2307 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
2308#if HC_ARCH_BITS == 32
2309 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
2310 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
2311#else
2312 /* 64-bit host or hybrid host. */
2313 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
2314#endif
2315 }
2316 else
2317 {
2318 /* Guest is not in long mode, use the 32-bit handler. */
2319 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
2320 }
2321 return VINF_SUCCESS;
2322}
2323
2324
2325/**
2326 * Enters the AMD-V session.
2327 *
2328 * @returns VBox status code.
2329 * @param pVM The cross context VM structure.
2330 * @param pVCpu The cross context virtual CPU structure.
2331 * @param pCpu Pointer to the CPU info struct.
2332 */
2333VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2334{
2335 AssertPtr(pVM);
2336 AssertPtr(pVCpu);
2337 Assert(pVM->hm.s.svm.fSupported);
2338 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2339 NOREF(pVM); NOREF(pCpu);
2340
2341 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
2342 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
2343
2344 pVCpu->hm.s.fLeaveDone = false;
2345 return VINF_SUCCESS;
2346}
2347
2348
2349/**
2350 * Thread-context callback for AMD-V.
2351 *
2352 * @param enmEvent The thread-context event.
2353 * @param pVCpu The cross context virtual CPU structure.
2354 * @param fGlobalInit Whether global VT-x/AMD-V init. is used.
2355 * @thread EMT(pVCpu)
2356 */
2357VMMR0DECL(void) SVMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
2358{
2359 NOREF(fGlobalInit);
2360
2361 switch (enmEvent)
2362 {
2363 case RTTHREADCTXEVENT_OUT:
2364 {
2365 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2366 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
2367 VMCPU_ASSERT_EMT(pVCpu);
2368
2369 /* No longjmps (log-flush, locks) in this fragile context. */
2370 VMMRZCallRing3Disable(pVCpu);
2371
2372 if (!pVCpu->hm.s.fLeaveDone)
2373 {
2374 hmR0SvmLeave(pVCpu, false /* fImportState */);
2375 pVCpu->hm.s.fLeaveDone = true;
2376 }
2377
2378 /* Leave HM context, takes care of local init (term). */
2379 int rc = HMR0LeaveCpu(pVCpu);
2380 AssertRC(rc); NOREF(rc);
2381
2382 /* Restore longjmp state. */
2383 VMMRZCallRing3Enable(pVCpu);
2384 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
2385 break;
2386 }
2387
2388 case RTTHREADCTXEVENT_IN:
2389 {
2390 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2391 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
2392 VMCPU_ASSERT_EMT(pVCpu);
2393
2394 /* No longjmps (log-flush, locks) in this fragile context. */
2395 VMMRZCallRing3Disable(pVCpu);
2396
2397 /*
2398 * Initialize the bare minimum state required for HM. This takes care of
2399 * initializing AMD-V if necessary (onlined CPUs, local init etc.)
2400 */
2401 int rc = HMR0EnterCpu(pVCpu);
2402 AssertRC(rc); NOREF(rc);
2403 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
2404
2405 pVCpu->hm.s.fLeaveDone = false;
2406
2407 /* Restore longjmp state. */
2408 VMMRZCallRing3Enable(pVCpu);
2409 break;
2410 }
2411
2412 default:
2413 break;
2414 }
2415}
2416
2417
2418/**
2419 * Saves the host state.
2420 *
2421 * @returns VBox status code.
2422 * @param pVM The cross context VM structure.
2423 * @param pVCpu The cross context virtual CPU structure.
2424 *
2425 * @remarks No-long-jump zone!!!
2426 */
2427VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
2428{
2429 NOREF(pVM);
2430 NOREF(pVCpu);
2431 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
2432 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT);
2433 return VINF_SUCCESS;
2434}
2435
2436
2437/**
2438 * Loads the guest state into the VMCB.
2439 *
2440 * The CPU state will be loaded from these fields on every successful VM-entry.
2441 * Also sets up the appropriate VMRUN function to execute guest code based on
2442 * the guest CPU mode.
2443 *
2444 * @returns VBox status code.
2445 * @param pVM The cross context VM structure.
2446 * @param pVCpu The cross context virtual CPU structure.
2447 * @param pCtx Pointer to the guest-CPU context.
2448 *
2449 * @remarks No-long-jump zone!!!
2450 */
2451static int hmR0SvmLoadGuestState(PVM pVM, PVMCPU pVCpu, PCCPUMCTX pCtx)
2452{
2453 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
2454
2455 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
2456 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
2457
2458 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
2459
2460 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
2461 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
2462
2463 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
2464 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
2465
2466 pVmcb->guest.u64RIP = pCtx->rip;
2467 pVmcb->guest.u64RSP = pCtx->rsp;
2468 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
2469 pVmcb->guest.u64RAX = pCtx->rax;
2470
2471#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2472 if (pVmcb->ctrl.IntCtrl.n.u1VGifEnable)
2473 {
2474 Assert(pVM->hm.s.svm.u32Features & X86_CPUID_SVM_FEATURE_EDX_VGIF);
2475 pVmcb->ctrl.IntCtrl.n.u1VGif = pCtx->hwvirt.fGif;
2476 }
2477#endif
2478
2479 /* hmR0SvmLoadGuestApicState() must be called -after- hmR0SvmLoadGuestMsrs() as we
2480 may overwrite LSTAR MSR in the VMCB in the case of TPR patching. */
2481 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
2482 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
2483
2484 hmR0SvmLoadGuestXcptIntercepts(pVCpu, pVmcb, pCtx);
2485
2486 rc = hmR0SvmSetupVMRunHandler(pVCpu);
2487 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
2488
2489 /* Clear any unused and reserved bits. */
2490 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
2491 | HM_CHANGED_GUEST_RSP
2492 | HM_CHANGED_GUEST_RFLAGS
2493 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
2494 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
2495 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
2496 | HM_CHANGED_GUEST_HWVIRT /* Unused. */
2497 | HM_CHANGED_VMM_GUEST_LAZY_MSRS
2498 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
2499 | HM_CHANGED_SVM_RESERVED2
2500 | HM_CHANGED_SVM_RESERVED3
2501 | HM_CHANGED_SVM_RESERVED4);
2502
2503 /* All the guest state bits should be loaded except maybe the host context and/or shared host/guest bits. */
2504 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
2505 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
2506 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
2507
2508#ifdef VBOX_STRICT
2509 hmR0SvmLogState(pVCpu, pVmcb, pCtx, "hmR0SvmLoadGuestState", 0 /* fFlags */, 0 /* uVerbose */);
2510#endif
2511 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
2512 return rc;
2513}
2514
2515
2516#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2517/**
2518 * Merges the guest and nested-guest MSR permission bitmap.
2519 *
2520 * If the guest is intercepting an MSR we need to intercept it regardless of
2521 * whether the nested-guest is intercepting it or not.
2522 *
2523 * @param pHostCpu Pointer to the physical CPU HM info. struct.
2524 * @param pVCpu The cross context virtual CPU structure.
2525 * @param pCtx Pointer to the nested-guest-CPU context.
2526 */
2527static void hmR0SvmMergeMsrpmNested(PHMGLOBALCPUINFO pHostCpu, PVMCPU pVCpu, PCCPUMCTX pCtx)
2528{
2529 uint64_t const *pu64GstMsrpm = (uint64_t const *)pVCpu->hm.s.svm.pvMsrBitmap;
2530 uint64_t const *pu64NstGstMsrpm = (uint64_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
2531 uint64_t *pu64DstMsrpm = (uint64_t *)pHostCpu->n.svm.pvNstGstMsrpm;
2532
2533 /* MSRPM bytes from offset 0x1800 are reserved, so we stop merging there. */
2534 uint32_t const offRsvdQwords = 0x1800 >> 3;
2535 for (uint32_t i = 0; i < offRsvdQwords; i++)
2536 pu64DstMsrpm[i] = pu64NstGstMsrpm[i] | pu64GstMsrpm[i];
2537}
2538
2539
2540/**
2541 * Caches the nested-guest VMCB fields before we modify them for execution using
2542 * hardware-assisted SVM.
2543 *
2544 * @returns true if the VMCB was previously already cached, false otherwise.
2545 * @param pCtx Pointer to the guest-CPU context.
2546 *
2547 * @sa HMSvmNstGstVmExitNotify.
2548 */
2549static bool hmR0SvmCacheVmcbNested(PVMCPU pVCpu, PCCPUMCTX pCtx)
2550{
2551 /*
2552 * Cache the nested-guest programmed VMCB fields if we have not cached it yet.
2553 * Otherwise we risk re-caching the values we may have modified, see @bugref{7243#c44}.
2554 *
2555 * Nested-paging CR3 is not saved back into the VMCB on #VMEXIT, hence no need to
2556 * cache and restore it, see AMD spec. 15.25.4 "Nested Paging and VMRUN/#VMEXIT".
2557 */
2558 PSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
2559 bool const fWasCached = pVmcbNstGstCache->fCacheValid;
2560 if (!fWasCached)
2561 {
2562 PCSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2563 PCSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2564 pVmcbNstGstCache->u16InterceptRdCRx = pVmcbNstGstCtrl->u16InterceptRdCRx;
2565 pVmcbNstGstCache->u16InterceptWrCRx = pVmcbNstGstCtrl->u16InterceptWrCRx;
2566 pVmcbNstGstCache->u16InterceptRdDRx = pVmcbNstGstCtrl->u16InterceptRdDRx;
2567 pVmcbNstGstCache->u16InterceptWrDRx = pVmcbNstGstCtrl->u16InterceptWrDRx;
2568 pVmcbNstGstCache->u16PauseFilterThreshold = pVmcbNstGstCtrl->u16PauseFilterThreshold;
2569 pVmcbNstGstCache->u16PauseFilterCount = pVmcbNstGstCtrl->u16PauseFilterCount;
2570 pVmcbNstGstCache->u32InterceptXcpt = pVmcbNstGstCtrl->u32InterceptXcpt;
2571 pVmcbNstGstCache->u64InterceptCtrl = pVmcbNstGstCtrl->u64InterceptCtrl;
2572 pVmcbNstGstCache->u64TSCOffset = pVmcbNstGstCtrl->u64TSCOffset;
2573 pVmcbNstGstCache->fVIntrMasking = pVmcbNstGstCtrl->IntCtrl.n.u1VIntrMasking;
2574 pVmcbNstGstCache->fNestedPaging = pVmcbNstGstCtrl->NestedPagingCtrl.n.u1NestedPaging;
2575 pVmcbNstGstCache->fLbrVirt = pVmcbNstGstCtrl->LbrVirt.n.u1LbrVirt;
2576 pVmcbNstGstCache->fCacheValid = true;
2577 Log4(("hmR0SvmCacheVmcbNested: Cached VMCB fields\n"));
2578 }
2579
2580 return fWasCached;
2581}
2582
2583
2584/**
2585 * Sets up the nested-guest VMCB for execution using hardware-assisted SVM.
2586 *
2587 * This is done the first time we enter nested-guest execution using SVM R0
2588 * until the nested-guest \#VMEXIT (not to be confused with physical CPU
2589 * \#VMEXITs which may or may not cause a corresponding nested-guest \#VMEXIT).
2590 *
2591 * @param pVCpu The cross context virtual CPU structure.
2592 * @param pCtx Pointer to the nested-guest-CPU context.
2593 */
2594static void hmR0SvmSetupVmcbNested(PVMCPU pVCpu, PCCPUMCTX pCtx)
2595{
2596 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2597 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
2598
2599 /*
2600 * First cache the nested-guest VMCB fields we may potentially modify.
2601 */
2602 bool const fVmcbCached = hmR0SvmCacheVmcbNested(pVCpu, pCtx);
2603 if (!fVmcbCached)
2604 {
2605 /*
2606 * The IOPM of the nested-guest can be ignored because the the guest always
2607 * intercepts all IO port accesses. Thus, we'll swap to the guest IOPM rather
2608 * than the nested-guest IOPM and swap the field back on the #VMEXIT.
2609 */
2610 pVmcbNstGstCtrl->u64IOPMPhysAddr = g_HCPhysIOBitmap;
2611
2612 /*
2613 * Use the same nested-paging as the outer guest. We can't dynamically switch off
2614 * nested-paging suddenly while executing a VM (see assertion at the end of
2615 * Trap0eHandler() in PGMAllBth.h).
2616 */
2617 pVmcbNstGstCtrl->NestedPagingCtrl.n.u1NestedPaging = pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging;
2618
2619 /* Always enable V_INTR_MASKING as we do not want to allow access to the physical APIC TPR. */
2620 pVmcbNstGstCtrl->IntCtrl.n.u1VIntrMasking = 1;
2621
2622#ifdef DEBUG_ramshankar
2623 /* For debugging purposes - copy the LBR info. from outer guest VMCB. */
2624 pVmcbNstGstCtrl->LbrVirt.n.u1LbrVirt = pVmcb->ctrl.LbrVirt.n.u1LbrVirt;
2625#endif
2626
2627 /*
2628 * If we don't expose Virtualized-VMSAVE/VMLOAD feature to the outer guest, we
2629 * need to intercept VMSAVE/VMLOAD instructions executed by the nested-guest.
2630 */
2631 if (!pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.fSvmVirtVmsaveVmload)
2632 pVmcbNstGstCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_VMSAVE
2633 | SVM_CTRL_INTERCEPT_VMLOAD;
2634
2635 /*
2636 * If we don't expose Virtual GIF feature to the outer guest, we need to intercept
2637 * CLGI/STGI instructions executed by the nested-guest.
2638 */
2639 if (!pVCpu->CTX_SUFF(pVM)->cpum.ro.GuestFeatures.fSvmVGif)
2640 pVmcbNstGstCtrl->u64InterceptCtrl |= SVM_CTRL_INTERCEPT_CLGI
2641 | SVM_CTRL_INTERCEPT_STGI;
2642
2643 /* Merge the guest and nested-guest intercepts. */
2644 hmR0SvmMergeVmcbCtrlsNested(pVCpu, pCtx);
2645
2646 /* Update the VMCB clean bits. */
2647 pVmcbNstGstCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2648 }
2649 else
2650 {
2651 Assert(pVmcbNstGstCtrl->u64IOPMPhysAddr == g_HCPhysIOBitmap);
2652 Assert(RT_BOOL(pVmcbNstGstCtrl->NestedPagingCtrl.n.u1NestedPaging) == pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
2653 }
2654}
2655
2656
2657/**
2658 * Loads the nested-guest state into the VMCB.
2659 *
2660 * @returns VBox status code.
2661 * @param pVCpu The cross context virtual CPU structure.
2662 * @param pCtx Pointer to the guest-CPU context.
2663 *
2664 * @remarks No-long-jump zone!!!
2665 */
2666static int hmR0SvmLoadGuestStateNested(PVMCPU pVCpu, PCCPUMCTX pCtx)
2667{
2668 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
2669
2670 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
2671 Assert(pVmcbNstGst);
2672
2673 hmR0SvmSetupVmcbNested(pVCpu, pCtx);
2674
2675 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcbNstGst, pCtx);
2676 AssertRCReturn(rc, rc);
2677
2678 /*
2679 * We need to load the entire state (including FS, GS etc.) as we could be continuing
2680 * to execute the nested-guest at any point (not just immediately after VMRUN) and thus
2681 * the VMCB can possibly be out-of-sync with the actual nested-guest state if it was
2682 * executed in IEM.
2683 */
2684 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcbNstGst, pCtx);
2685 hmR0SvmLoadGuestMsrs(pVCpu, pVmcbNstGst, pCtx);
2686 hmR0SvmLoadGuestApicStateNested(pVCpu, pVmcbNstGst);
2687 hmR0SvmLoadGuestHwvirtStateNested(pVCpu, pVmcbNstGst, pCtx);
2688
2689 pVmcbNstGst->guest.u64RIP = pCtx->rip;
2690 pVmcbNstGst->guest.u64RSP = pCtx->rsp;
2691 pVmcbNstGst->guest.u64RFlags = pCtx->eflags.u32;
2692 pVmcbNstGst->guest.u64RAX = pCtx->rax;
2693
2694#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2695 Assert(!pVmcbNstGst->ctrl.IntCtrl.n.u1VGifEnable); /* Nested VGIF not supported yet. */
2696#endif
2697
2698 rc = hmR0SvmSetupVMRunHandler(pVCpu);
2699 AssertRCReturn(rc, rc);
2700
2701 /* Clear any unused and reserved bits. */
2702 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
2703 | HM_CHANGED_GUEST_RSP
2704 | HM_CHANGED_GUEST_RFLAGS
2705 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
2706 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
2707 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
2708 | HM_CHANGED_VMM_GUEST_XCPT_INTERCEPTS /* Unused. */
2709 | HM_CHANGED_VMM_GUEST_LAZY_MSRS
2710 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
2711 | HM_CHANGED_SVM_RESERVED2
2712 | HM_CHANGED_SVM_RESERVED3
2713 | HM_CHANGED_SVM_RESERVED4);
2714
2715 /* All the guest state bits should be loaded except maybe the host context and/or shared host/guest bits. */
2716 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
2717 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
2718 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
2719
2720#ifdef VBOX_STRICT
2721 hmR0SvmLogState(pVCpu, pVmcbNstGst, pCtx, "hmR0SvmLoadGuestStateNested", HMSVM_LOG_ALL, 0 /* uVerbose */);
2722#endif
2723 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
2724 return rc;
2725}
2726#endif /* VBOX_WITH_NESTED_HWVIRT_SVM */
2727
2728
2729/**
2730 * Loads the state shared between the host and guest (or nested-guest) into the
2731 * VMCB.
2732 *
2733 * @param pVCpu The cross context virtual CPU structure.
2734 * @param pVmcb Pointer to the VM control block.
2735 * @param pCtx Pointer to the guest-CPU context.
2736 *
2737 * @remarks No-long-jump zone!!!
2738 */
2739static void hmR0SvmLoadSharedState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCCPUMCTX pCtx)
2740{
2741 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2742 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2743
2744 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
2745 {
2746 hmR0SvmLoadSharedCR0(pVCpu, pVmcb, pCtx);
2747 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR0);
2748 }
2749
2750 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
2751 {
2752 /** @todo Figure out stepping with nested-guest. */
2753 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
2754 hmR0SvmLoadSharedDebugState(pVCpu, pVmcb, pCtx);
2755 else
2756 {
2757 pVmcb->guest.u64DR6 = pCtx->dr[6];
2758 pVmcb->guest.u64DR7 = pCtx->dr[7];
2759 Log4(("hmR0SvmLoadSharedState: DR6=%#RX64 DR7=%#RX64\n", pCtx->dr[6], pCtx->dr[7]));
2760 }
2761
2762 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_DEBUG);
2763 }
2764
2765 /* Unused on AMD-V (no lazy MSRs). */
2766 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMM_GUEST_LAZY_MSRS);
2767
2768 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
2769 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
2770}
2771
2772
2773/**
2774 * Worker for SVMR0ImportStateOnDemand.
2775 *
2776 * @param pVCpu The cross context virtual CPU structure.
2777 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
2778 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
2779 */
2780static void hmR0SvmImportGuestState(PVMCPU pVCpu, PCPUMCTX pCtx, uint64_t fWhat)
2781{
2782 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
2783 PCSVMVMCBSTATESAVE pVmcbGuest = &pVmcb->guest;
2784 PCSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
2785
2786 Log4(("hmR0SvmImportGuestState: fExtrn=%#RX64 fWhat=%#RX64\n", pCtx->fExtrn, fWhat));
2787
2788 /*
2789 * We disable interrupts to make the updating of the state and in particular
2790 * the fExtrn modification atomic wrt to preemption hooks.
2791 */
2792 RTCCUINTREG const fSavedFlags = ASMIntDisableFlags();
2793
2794 fWhat &= pCtx->fExtrn;
2795 if (fWhat & pCtx->fExtrn)
2796 {
2797#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2798 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
2799 {
2800 if ( !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
2801 && pVmcbCtrl->IntCtrl.n.u1VGifEnable)
2802 {
2803 /* We don't yet support passing VGIF feature to the guest. */
2804 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.svm.fVGif);
2805 pCtx->hwvirt.fGif = pVmcbCtrl->IntCtrl.n.u1VGif;
2806 }
2807 }
2808
2809 if (fWhat & CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ)
2810 {
2811 if ( !pVmcbCtrl->IntCtrl.n.u1VIrqPending
2812 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
2813 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
2814 }
2815#endif
2816
2817 if (fWhat & CPUMCTX_EXTRN_HM_SVM_INT_SHADOW)
2818 {
2819 if (pVmcbCtrl->IntShadow.n.u1IntShadow)
2820 EMSetInhibitInterruptsPC(pVCpu, pVmcbGuest->u64RIP);
2821 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2822 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2823 }
2824
2825 if (fWhat & CPUMCTX_EXTRN_RIP)
2826 pCtx->rip = pVmcbGuest->u64RIP;
2827
2828 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
2829 pCtx->eflags.u32 = pVmcbGuest->u64RFlags;
2830
2831 if (fWhat & CPUMCTX_EXTRN_RSP)
2832 pCtx->rsp = pVmcbGuest->u64RSP;
2833
2834 if (fWhat & CPUMCTX_EXTRN_RAX)
2835 pCtx->rax = pVmcbGuest->u64RAX;
2836
2837 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
2838 {
2839 if (fWhat & CPUMCTX_EXTRN_CS)
2840 {
2841 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, CS, cs);
2842 /*
2843 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
2844 * register (yet).
2845 */
2846 /** @todo SELM might need to be fixed as it too should not care about the
2847 * granularity bit. See @bugref{6785}. */
2848 if ( !pCtx->cs.Attr.n.u1Granularity
2849 && pCtx->cs.Attr.n.u1Present
2850 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
2851 {
2852 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
2853 pCtx->cs.Attr.n.u1Granularity = 1;
2854 }
2855 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, cs);
2856 }
2857 if (fWhat & CPUMCTX_EXTRN_SS)
2858 {
2859 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, SS, ss);
2860 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, ss);
2861 /*
2862 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
2863 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
2864 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
2865 * See AMD spec. 15.5.1 "Basic operation".
2866 */
2867 Assert(!(pVmcbGuest->u8CPL & ~0x3));
2868 uint8_t const uCpl = pVmcbGuest->u8CPL;
2869 if (pCtx->ss.Attr.n.u2Dpl != uCpl)
2870 pCtx->ss.Attr.n.u2Dpl = uCpl & 0x3;
2871 }
2872 if (fWhat & CPUMCTX_EXTRN_DS)
2873 {
2874 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, DS, ds);
2875 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, ds);
2876 }
2877 if (fWhat & CPUMCTX_EXTRN_ES)
2878 {
2879 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, ES, es);
2880 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, es);
2881 }
2882 if (fWhat & CPUMCTX_EXTRN_FS)
2883 {
2884 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, FS, fs);
2885 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, fs);
2886 }
2887 if (fWhat & CPUMCTX_EXTRN_GS)
2888 {
2889 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, GS, gs);
2890 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, gs);
2891 }
2892 }
2893
2894 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
2895 {
2896 if (fWhat & CPUMCTX_EXTRN_TR)
2897 {
2898 /*
2899 * Fixup TR attributes so it's compatible with Intel. Important when saved-states
2900 * are used between Intel and AMD, see @bugref{6208#c39}.
2901 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2902 */
2903 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, TR, tr);
2904 if (pCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2905 {
2906 if ( pCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2907 || CPUMIsGuestInLongModeEx(pCtx))
2908 pCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2909 else if (pCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2910 pCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2911 }
2912 }
2913
2914 if (fWhat & CPUMCTX_EXTRN_LDTR)
2915 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, LDTR, ldtr);
2916
2917 if (fWhat & CPUMCTX_EXTRN_GDTR)
2918 {
2919 pCtx->gdtr.cbGdt = pVmcbGuest->GDTR.u32Limit;
2920 pCtx->gdtr.pGdt = pVmcbGuest->GDTR.u64Base;
2921 }
2922
2923 if (fWhat & CPUMCTX_EXTRN_IDTR)
2924 {
2925 pCtx->idtr.cbIdt = pVmcbGuest->IDTR.u32Limit;
2926 pCtx->idtr.pIdt = pVmcbGuest->IDTR.u64Base;
2927 }
2928 }
2929
2930 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
2931 {
2932 pCtx->msrSTAR = pVmcbGuest->u64STAR;
2933 pCtx->msrLSTAR = pVmcbGuest->u64LSTAR;
2934 pCtx->msrCSTAR = pVmcbGuest->u64CSTAR;
2935 pCtx->msrSFMASK = pVmcbGuest->u64SFMASK;
2936 }
2937
2938 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
2939 {
2940 pCtx->SysEnter.cs = pVmcbGuest->u64SysEnterCS;
2941 pCtx->SysEnter.eip = pVmcbGuest->u64SysEnterEIP;
2942 pCtx->SysEnter.esp = pVmcbGuest->u64SysEnterESP;
2943 }
2944
2945 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
2946 pCtx->msrKERNELGSBASE = pVmcbGuest->u64KernelGSBase;
2947
2948 if (fWhat & CPUMCTX_EXTRN_DR_MASK)
2949 {
2950 if (fWhat & CPUMCTX_EXTRN_DR6)
2951 {
2952 if (!pVCpu->hm.s.fUsingHyperDR7)
2953 pCtx->dr[6] = pVmcbGuest->u64DR6;
2954 else
2955 CPUMSetHyperDR6(pVCpu, pVmcbGuest->u64DR6);
2956 }
2957
2958 if (fWhat & CPUMCTX_EXTRN_DR7)
2959 {
2960 if (!pVCpu->hm.s.fUsingHyperDR7)
2961 pCtx->dr[7] = pVmcbGuest->u64DR7;
2962 else
2963 Assert(pVmcbGuest->u64DR7 == CPUMGetHyperDR7(pVCpu));
2964 }
2965 }
2966
2967 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
2968 {
2969 if (fWhat & CPUMCTX_EXTRN_CR0)
2970 {
2971 /* We intercept changes to all CR0 bits except maybe TS & MP bits. */
2972 uint64_t const uCr0 = (pCtx->cr0 & ~(X86_CR0_TS | X86_CR0_MP))
2973 | (pVmcbGuest->u64CR0 & (X86_CR0_TS | X86_CR0_MP));
2974 VMMRZCallRing3Disable(pVCpu); /* CPUM has log statements and calls into PGM. */
2975 CPUMSetGuestCR0(pVCpu, uCr0);
2976 VMMRZCallRing3Enable(pVCpu);
2977 }
2978
2979 if (fWhat & CPUMCTX_EXTRN_CR2)
2980 pCtx->cr2 = pVmcbGuest->u64CR2;
2981
2982 if (fWhat & CPUMCTX_EXTRN_CR3)
2983 {
2984 if ( pVmcbCtrl->NestedPagingCtrl.n.u1NestedPaging
2985 && pCtx->cr3 != pVmcbGuest->u64CR3)
2986 {
2987 CPUMSetGuestCR3(pVCpu, pVmcbGuest->u64CR3);
2988 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
2989 }
2990 }
2991
2992 /* Changes to CR4 are always intercepted. */
2993 }
2994
2995 /* Update fExtrn. */
2996 pCtx->fExtrn &= ~fWhat;
2997
2998 /* If everything has been imported, clear the HM keeper bit. */
2999 if (!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL))
3000 {
3001 pCtx->fExtrn &= ~CPUMCTX_EXTRN_KEEPER_HM;
3002 Assert(!pCtx->fExtrn);
3003 }
3004 }
3005 else
3006 Assert(!pCtx->fExtrn || (pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL));
3007
3008 ASMSetFlags(fSavedFlags);
3009
3010 /*
3011 * Honor any pending CR3 updates.
3012 *
3013 * Consider this scenario: #VMEXIT -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp
3014 * -> hmR0SvmCallRing3Callback() -> VMMRZCallRing3Disable() -> hmR0SvmImportGuestState()
3015 * -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp -> continue with #VMEXIT
3016 * handling -> hmR0SvmImportGuestState() and here we are.
3017 *
3018 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be
3019 * up-to-date and thus any CR3-saves -before- the VM-exit (longjmp) would've postponed the CR3
3020 * update via the force-flag and cleared CR3 from fExtrn. Any SVM R0 VM-exit handler that requests
3021 * CR3 to be saved will end up here and we call PGMUpdateCR3().
3022 *
3023 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again,
3024 * and does not process force-flag like regular exits to ring-3 either, we cover for it here.
3025 */
3026 if ( VMMRZCallRing3IsEnabled(pVCpu)
3027 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
3028 {
3029 Assert(pCtx->cr3 == pVmcbGuest->u64CR3);
3030 PGMUpdateCR3(pVCpu, pCtx->cr3);
3031 }
3032}
3033
3034
3035/**
3036 * Saves the guest (or nested-guest) state from the VMCB into the guest-CPU
3037 * context.
3038 *
3039 * Currently there is no residual state left in the CPU that is not updated in the
3040 * VMCB.
3041 *
3042 * @returns VBox status code.
3043 * @param pVCpu The cross context virtual CPU structure.
3044 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context. The
3045 * data may be out-of-sync. Make sure to update the required
3046 * fields before using them.
3047 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
3048 */
3049VMMR0DECL(int) SVMR0ImportStateOnDemand(PVMCPU pVCpu, PCPUMCTX pCtx, uint64_t fWhat)
3050{
3051 hmR0SvmImportGuestState(pVCpu, pCtx, fWhat);
3052 return VINF_SUCCESS;
3053}
3054
3055
3056/**
3057 * Saves the guest (or nested-guest) state from the VMCB into the guest-CPU
3058 * context.
3059 *
3060 * Currently there is no residual state left in the CPU that is not updated in the
3061 * VMCB.
3062 *
3063 * @returns VBox status code.
3064 * @param pVCpu The cross context virtual CPU structure.
3065 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context. The
3066 * data may be out-of-sync. Make sure to update the required
3067 * fields before using them.
3068 * @param pVmcb Pointer to the VM control block.
3069 */
3070static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pCtx, PCSVMVMCB pVmcb)
3071{
3072 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3073
3074 /*
3075 * Always import the following:
3076 *
3077 * - RIP, RFLAGS, int. shadow, GIF: we need them when as we evaluate
3078 * injecting events before re-entering guest execution.
3079 *
3080 * - GPRS: Only RAX, RSP are in the VMCB. All the other GPRs are swapped
3081 * by the assembly switcher code. Import these two always just to simplify
3082 * assumptions on GPRs.
3083 *
3084 * - SREG: We load them all together so we have to save all of them.
3085 *
3086 * - KERNEL_GS_BASE, SYSCALL MSRS: We don't have a HM_CHANGED_GUEST flag
3087 * for it yet
3088 */
3089 /** @todo Extend HM_CHANGED_GUEST_xxx so that we avoid saving segment
3090 * registers, kernel GS base and other MSRs each time. */
3091 hmR0SvmImportGuestState(pVCpu, pCtx, CPUMCTX_EXTRN_RIP
3092 | CPUMCTX_EXTRN_SYSCALL_MSRS
3093 | CPUMCTX_EXTRN_KERNEL_GS_BASE
3094 | CPUMCTX_EXTRN_RFLAGS
3095 | CPUMCTX_EXTRN_RAX
3096 | CPUMCTX_EXTRN_SREG_MASK
3097 | CPUMCTX_EXTRN_RSP
3098 | CPUMCTX_EXTRN_HWVIRT
3099 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW
3100 | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ);
3101
3102#ifdef DEBUG_ramshankar
3103 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3104 {
3105 hmR0SvmImportGuestState(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
3106 hmR0SvmLogState(pVCpu, pVmcb, pCtx, "hmR0SvmSaveGuestStateNested", HMSVM_LOG_ALL & ~HMSVM_LOG_LBR, 0 /* uVerbose */);
3107 }
3108#else
3109 RT_NOREF(pVmcb);
3110#endif
3111}
3112
3113
3114/**
3115 * Does the necessary state syncing before returning to ring-3 for any reason
3116 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
3117 *
3118 * @param pVCpu The cross context virtual CPU structure.
3119 * @param fImportState Whether to import the guest state from the VMCB back
3120 * to the guest-CPU context.
3121 *
3122 * @remarks No-long-jmp zone!!!
3123 */
3124static void hmR0SvmLeave(PVMCPU pVCpu, bool fImportState)
3125{
3126 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3127 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3128 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3129
3130 /*
3131 * !!! IMPORTANT !!!
3132 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
3133 */
3134
3135 /* Save the guest state if necessary. */
3136 if (fImportState)
3137 hmR0SvmImportGuestState(pVCpu, &pVCpu->cpum.GstCtx, HMSVM_CPUMCTX_EXTRN_ALL);
3138
3139 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
3140 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3141
3142 /*
3143 * Restore host debug registers if necessary and resync on next R0 reentry.
3144 */
3145#ifdef VBOX_STRICT
3146 if (CPUMIsHyperDebugStateActive(pVCpu))
3147 {
3148 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb; /** @todo nested-guest. */
3149 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
3150 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
3151 }
3152#endif
3153 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3154
3155 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
3156 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
3157
3158 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
3159 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
3160 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
3161 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
3162 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3163
3164 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
3165}
3166
3167
3168/**
3169 * Leaves the AMD-V session.
3170 *
3171 * Only used while returning to ring-3 either due to longjump or exits to
3172 * ring-3.
3173 *
3174 * @returns VBox status code.
3175 * @param pVCpu The cross context virtual CPU structure.
3176 */
3177static int hmR0SvmLeaveSession(PVMCPU pVCpu)
3178{
3179 HM_DISABLE_PREEMPT();
3180 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3181 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3182
3183 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
3184 and done this from the SVMR0ThreadCtxCallback(). */
3185 if (!pVCpu->hm.s.fLeaveDone)
3186 {
3187 hmR0SvmLeave(pVCpu, true /* fImportState */);
3188 pVCpu->hm.s.fLeaveDone = true;
3189 }
3190
3191 /*
3192 * !!! IMPORTANT !!!
3193 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
3194 */
3195
3196 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3197 /* Deregister hook now that we've left HM context before re-enabling preemption. */
3198 VMMR0ThreadCtxHookDisable(pVCpu);
3199
3200 /* Leave HM context. This takes care of local init (term). */
3201 int rc = HMR0LeaveCpu(pVCpu);
3202
3203 HM_RESTORE_PREEMPT();
3204 return rc;
3205}
3206
3207
3208/**
3209 * Does the necessary state syncing before doing a longjmp to ring-3.
3210 *
3211 * @returns VBox status code.
3212 * @param pVCpu The cross context virtual CPU structure.
3213 *
3214 * @remarks No-long-jmp zone!!!
3215 */
3216static int hmR0SvmLongJmpToRing3(PVMCPU pVCpu)
3217{
3218 return hmR0SvmLeaveSession(pVCpu);
3219}
3220
3221
3222/**
3223 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
3224 * any remaining host state) before we longjump to ring-3 and possibly get
3225 * preempted.
3226 *
3227 * @param pVCpu The cross context virtual CPU structure.
3228 * @param enmOperation The operation causing the ring-3 longjump.
3229 * @param pvUser The user argument (pointer to the possibly
3230 * out-of-date guest-CPU context).
3231 */
3232static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
3233{
3234 RT_NOREF_PV(pvUser);
3235
3236 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
3237 {
3238 /*
3239 * !!! IMPORTANT !!!
3240 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
3241 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
3242 */
3243 VMMRZCallRing3RemoveNotification(pVCpu);
3244 VMMRZCallRing3Disable(pVCpu);
3245 HM_DISABLE_PREEMPT();
3246
3247 /* Restore host FPU state if necessary and resync on next R0 reentry. */
3248 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3249
3250 /* Restore host debug registers if necessary and resync on next R0 reentry. */
3251 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3252
3253 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
3254 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3255 VMMR0ThreadCtxHookDisable(pVCpu);
3256
3257 /* Leave HM context. This takes care of local init (term). */
3258 HMR0LeaveCpu(pVCpu);
3259
3260 HM_RESTORE_PREEMPT();
3261 return VINF_SUCCESS;
3262 }
3263
3264 Assert(pVCpu);
3265 Assert(pvUser);
3266 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3267 HMSVM_ASSERT_PREEMPT_SAFE();
3268
3269 VMMRZCallRing3Disable(pVCpu);
3270 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3271
3272 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
3273 int rc = hmR0SvmLongJmpToRing3(pVCpu);
3274 AssertRCReturn(rc, rc);
3275
3276 VMMRZCallRing3Enable(pVCpu);
3277 return VINF_SUCCESS;
3278}
3279
3280
3281/**
3282 * Take necessary actions before going back to ring-3.
3283 *
3284 * An action requires us to go back to ring-3. This function does the necessary
3285 * steps before we can safely return to ring-3. This is not the same as longjmps
3286 * to ring-3, this is voluntary.
3287 *
3288 * @returns VBox status code.
3289 * @param pVM The cross context VM structure.
3290 * @param pVCpu The cross context virtual CPU structure.
3291 * @param pCtx Pointer to the guest-CPU context.
3292 * @param rcExit The reason for exiting to ring-3. Can be
3293 * VINF_VMM_UNKNOWN_RING3_CALL.
3294 */
3295static int hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
3296{
3297 Assert(pVM);
3298 Assert(pVCpu);
3299 Assert(pCtx);
3300 HMSVM_ASSERT_PREEMPT_SAFE();
3301
3302 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
3303 VMMRZCallRing3Disable(pVCpu);
3304 Log4(("hmR0SvmExitToRing3: VCPU[%u]: rcExit=%d LocalFF=%#RX32 GlobalFF=%#RX32\n", pVCpu->idCpu, rcExit,
3305 pVCpu->fLocalForcedActions, pVM->fGlobalForcedActions));
3306
3307 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
3308 if (pVCpu->hm.s.Event.fPending)
3309 {
3310 hmR0SvmPendingEventToTrpmTrap(pVCpu);
3311 Assert(!pVCpu->hm.s.Event.fPending);
3312 }
3313
3314 /* Sync. the necessary state for going back to ring-3. */
3315 hmR0SvmLeaveSession(pVCpu);
3316 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3317
3318 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
3319 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
3320 | CPUM_CHANGED_LDTR
3321 | CPUM_CHANGED_GDTR
3322 | CPUM_CHANGED_IDTR
3323 | CPUM_CHANGED_TR
3324 | CPUM_CHANGED_HIDDEN_SEL_REGS);
3325 if ( pVM->hm.s.fNestedPaging
3326 && CPUMIsGuestPagingEnabledEx(pCtx))
3327 {
3328 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3329 }
3330
3331 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
3332 if (rcExit != VINF_EM_RAW_INTERRUPT)
3333 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
3334
3335 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
3336
3337 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
3338 VMMRZCallRing3RemoveNotification(pVCpu);
3339 VMMRZCallRing3Enable(pVCpu);
3340
3341 /*
3342 * If we're emulating an instruction, we shouldn't have any TRPM traps pending
3343 * and if we're injecting an event we should have a TRPM trap pending.
3344 */
3345 AssertReturnStmt(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu),
3346 pVCpu->hm.s.u32HMError = rcExit,
3347 VERR_SVM_IPE_5);
3348 AssertReturnStmt(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu),
3349 pVCpu->hm.s.u32HMError = rcExit,
3350 VERR_SVM_IPE_4);
3351
3352 return rcExit;
3353}
3354
3355
3356/**
3357 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
3358 * intercepts.
3359 *
3360 * @param pVM The cross context VM structure.
3361 * @param pVCpu The cross context virtual CPU structure.
3362 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
3363 * @param pVmcb Pointer to the VM control block.
3364 *
3365 * @remarks No-long-jump zone!!!
3366 */
3367static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb)
3368{
3369 /*
3370 * Avoid intercepting RDTSC/RDTSCP if we determined the host TSC (++) is stable
3371 * and in case of a nested-guest, if the nested-VMCB specifies it is not intercepting
3372 * RDTSC/RDTSCP as well.
3373 */
3374 bool fParavirtTsc;
3375 uint64_t uTscOffset;
3376 bool const fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
3377
3378 bool fIntercept;
3379 if (fCanUseRealTsc)
3380 fIntercept = hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3381 else
3382 {
3383 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3384 fIntercept = true;
3385 }
3386
3387 if (!fIntercept)
3388 {
3389 /* Apply the nested-guest VMCB's TSC offset over the guest TSC offset. */
3390 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3391 uTscOffset = HMSvmNstGstApplyTscOffset(pVCpu, uTscOffset);
3392
3393 /* Update the TSC offset in the VMCB and the relevant clean bits. */
3394 pVmcb->ctrl.u64TSCOffset = uTscOffset;
3395 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3396
3397 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
3398 }
3399 else
3400 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
3401
3402 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
3403 information before every VM-entry, hence we have nothing to do here at the moment. */
3404 if (fParavirtTsc)
3405 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
3406}
3407
3408
3409/**
3410 * Sets an event as a pending event to be injected into the guest.
3411 *
3412 * @param pVCpu The cross context virtual CPU structure.
3413 * @param pEvent Pointer to the SVM event.
3414 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
3415 * page-fault.
3416 *
3417 * @remarks Statistics counter assumes this is a guest event being reflected to
3418 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
3419 */
3420DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
3421{
3422 Assert(!pVCpu->hm.s.Event.fPending);
3423 Assert(pEvent->n.u1Valid);
3424
3425 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
3426 pVCpu->hm.s.Event.fPending = true;
3427 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
3428
3429 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
3430 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3431}
3432
3433
3434/**
3435 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
3436 *
3437 * @param pVCpu The cross context virtual CPU structure.
3438 */
3439DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3440{
3441 SVMEVENT Event;
3442 Event.u = 0;
3443 Event.n.u1Valid = 1;
3444 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3445 Event.n.u8Vector = X86_XCPT_UD;
3446 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3447}
3448
3449
3450/**
3451 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
3452 *
3453 * @param pVCpu The cross context virtual CPU structure.
3454 */
3455DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3456{
3457 SVMEVENT Event;
3458 Event.u = 0;
3459 Event.n.u1Valid = 1;
3460 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3461 Event.n.u8Vector = X86_XCPT_DB;
3462 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3463}
3464
3465
3466/**
3467 * Sets a page fault (\#PF) exception as pending-for-injection into the VM.
3468 *
3469 * @param pVCpu The cross context virtual CPU structure.
3470 * @param pCtx Pointer to the guest-CPU context.
3471 * @param u32ErrCode The error-code for the page-fault.
3472 * @param uFaultAddress The page fault address (CR2).
3473 *
3474 * @remarks This updates the guest CR2 with @a uFaultAddress!
3475 */
3476DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3477{
3478 SVMEVENT Event;
3479 Event.u = 0;
3480 Event.n.u1Valid = 1;
3481 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3482 Event.n.u8Vector = X86_XCPT_PF;
3483 Event.n.u1ErrorCodeValid = 1;
3484 Event.n.u32ErrorCode = u32ErrCode;
3485
3486 /* Update CR2 of the guest. */
3487 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR2);
3488 if (pCtx->cr2 != uFaultAddress)
3489 {
3490 pCtx->cr2 = uFaultAddress;
3491 /* The VMCB clean bit for CR2 will be updated while re-loading the guest state. */
3492 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3493 }
3494
3495 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3496}
3497
3498
3499/**
3500 * Sets a math-fault (\#MF) exception as pending-for-injection into the VM.
3501 *
3502 * @param pVCpu The cross context virtual CPU structure.
3503 */
3504DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3505{
3506 SVMEVENT Event;
3507 Event.u = 0;
3508 Event.n.u1Valid = 1;
3509 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3510 Event.n.u8Vector = X86_XCPT_MF;
3511 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3512}
3513
3514
3515/**
3516 * Sets a double fault (\#DF) exception as pending-for-injection into the VM.
3517 *
3518 * @param pVCpu The cross context virtual CPU structure.
3519 */
3520DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3521{
3522 SVMEVENT Event;
3523 Event.u = 0;
3524 Event.n.u1Valid = 1;
3525 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3526 Event.n.u8Vector = X86_XCPT_DF;
3527 Event.n.u1ErrorCodeValid = 1;
3528 Event.n.u32ErrorCode = 0;
3529 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3530}
3531
3532
3533/**
3534 * Injects an event into the guest upon VMRUN by updating the relevant field
3535 * in the VMCB.
3536 *
3537 * @param pVCpu The cross context virtual CPU structure.
3538 * @param pVmcb Pointer to the guest VM control block.
3539 * @param pEvent Pointer to the event.
3540 *
3541 * @remarks No-long-jump zone!!!
3542 * @remarks Requires CR0!
3543 */
3544DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PSVMEVENT pEvent)
3545{
3546 Assert(!pVmcb->ctrl.EventInject.n.u1Valid);
3547 pVmcb->ctrl.EventInject.u = pEvent->u;
3548 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
3549 RT_NOREF(pVCpu);
3550
3551 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
3552 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3553}
3554
3555
3556
3557/**
3558 * Converts any TRPM trap into a pending HM event. This is typically used when
3559 * entering from ring-3 (not longjmp returns).
3560 *
3561 * @param pVCpu The cross context virtual CPU structure.
3562 */
3563static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
3564{
3565 Assert(TRPMHasTrap(pVCpu));
3566 Assert(!pVCpu->hm.s.Event.fPending);
3567
3568 uint8_t uVector;
3569 TRPMEVENT enmTrpmEvent;
3570 RTGCUINT uErrCode;
3571 RTGCUINTPTR GCPtrFaultAddress;
3572 uint8_t cbInstr;
3573
3574 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
3575 AssertRC(rc);
3576
3577 SVMEVENT Event;
3578 Event.u = 0;
3579 Event.n.u1Valid = 1;
3580 Event.n.u8Vector = uVector;
3581
3582 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
3583 if (enmTrpmEvent == TRPM_TRAP)
3584 {
3585 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3586 switch (uVector)
3587 {
3588 case X86_XCPT_NMI:
3589 {
3590 Event.n.u3Type = SVM_EVENT_NMI;
3591 break;
3592 }
3593
3594 case X86_XCPT_PF:
3595 case X86_XCPT_DF:
3596 case X86_XCPT_TS:
3597 case X86_XCPT_NP:
3598 case X86_XCPT_SS:
3599 case X86_XCPT_GP:
3600 case X86_XCPT_AC:
3601 {
3602 Event.n.u1ErrorCodeValid = 1;
3603 Event.n.u32ErrorCode = uErrCode;
3604 break;
3605 }
3606 }
3607 }
3608 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
3609 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3610 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
3611 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
3612 else
3613 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
3614
3615 rc = TRPMResetTrap(pVCpu);
3616 AssertRC(rc);
3617
3618 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
3619 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
3620
3621 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
3622}
3623
3624
3625/**
3626 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
3627 * AMD-V to execute any instruction.
3628 *
3629 * @param pVCpu The cross context virtual CPU structure.
3630 */
3631static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
3632{
3633 Assert(pVCpu->hm.s.Event.fPending);
3634 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
3635
3636 SVMEVENT Event;
3637 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3638
3639 uint8_t uVector = Event.n.u8Vector;
3640 uint8_t uVectorType = Event.n.u3Type;
3641 TRPMEVENT enmTrapType = HMSvmEventToTrpmEventType(&Event);
3642
3643 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
3644
3645 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
3646 AssertRC(rc);
3647
3648 if (Event.n.u1ErrorCodeValid)
3649 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
3650
3651 if ( uVectorType == SVM_EVENT_EXCEPTION
3652 && uVector == X86_XCPT_PF)
3653 {
3654 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
3655 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
3656 }
3657 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
3658 {
3659 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
3660 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
3661 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
3662 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
3663 }
3664 pVCpu->hm.s.Event.fPending = false;
3665}
3666
3667
3668/**
3669 * Checks if the guest (or nested-guest) has an interrupt shadow active right
3670 * now.
3671 *
3672 * @returns @c true if the interrupt shadow is active, @c false otherwise.
3673 * @param pVCpu The cross context virtual CPU structure.
3674 * @param pCtx Pointer to the guest-CPU context.
3675 *
3676 * @remarks No-long-jump zone!!!
3677 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
3678 */
3679DECLINLINE(bool) hmR0SvmIsIntrShadowActive(PVMCPU pVCpu, PCCPUMCTX pCtx)
3680{
3681 /*
3682 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
3683 * inhibit interrupts or clear any existing interrupt-inhibition.
3684 */
3685 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3686 {
3687 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
3688 {
3689 /*
3690 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
3691 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
3692 */
3693 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3694 return false;
3695 }
3696 return true;
3697 }
3698 return false;
3699}
3700
3701
3702/**
3703 * Sets the virtual interrupt intercept control in the VMCB.
3704 *
3705 * @param pVCpu The cross context virtual CPU structure.
3706 * @param pVmcb Pointer to the VM control block.
3707 * @param pCtx Pointer to the guest-CPU context.
3708 */
3709DECLINLINE(void) hmR0SvmSetIntWindowExiting(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
3710{
3711 /*
3712 * When AVIC isn't supported, set up an interrupt window to cause a #VMEXIT when
3713 * the guest is ready to accept interrupts. At #VMEXIT, we then get the interrupt
3714 * from the APIC (updating ISR at the right time) and inject the interrupt.
3715 *
3716 * With AVIC is supported, we could make use of the asynchronously delivery without
3717 * #VMEXIT and we would be passing the AVIC page to SVM.
3718 *
3719 * In AMD-V, an interrupt window is achieved using a combination of
3720 * V_IRQ (an interrupt is pending), V_IGN_TPR (ignore TPR priorities) and the
3721 * VINTR intercept all being set.
3722 */
3723#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3724 /*
3725 * Currently we don't overlay interupt windows and if there's any V_IRQ pending
3726 * in the nested-guest VMCB, we avoid setting up any interrupt window on behalf
3727 * of the outer guest.
3728 */
3729 /** @todo Does this mean we end up prioritizing virtual interrupt
3730 * delivery/window over a physical interrupt (from the outer guest)
3731 * might be pending? */
3732 bool const fEnableIntWindow = !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
3733 if (!fEnableIntWindow)
3734 {
3735 Assert(CPUMIsGuestInSvmNestedHwVirtMode(pCtx)); RT_NOREF(pCtx);
3736 Log4(("Nested-guest V_IRQ already pending\n"));
3737 }
3738#else
3739 RT_NOREF2(pVCpu, pCtx);
3740 bool const fEnableIntWindow = true;
3741#endif
3742 if (fEnableIntWindow)
3743 {
3744 Assert(pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR);
3745 pVmcb->ctrl.IntCtrl.n.u1VIrqPending = 1;
3746 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INT_CTRL;
3747 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_VINTR);
3748 Log4(("Set VINTR intercept\n"));
3749 }
3750}
3751
3752
3753/**
3754 * Clears the virtual interrupt intercept control in the VMCB as
3755 * we are figured the guest is unable process any interrupts
3756 * at this point of time.
3757 *
3758 * @param pVCpu The cross context virtual CPU structure.
3759 * @param pVmcb Pointer to the VM control block.
3760 * @param pCtx Pointer to the guest-CPU context.
3761 */
3762DECLINLINE(void) hmR0SvmClearIntWindowExiting(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
3763{
3764 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
3765 if ( pVmcbCtrl->IntCtrl.n.u1VIrqPending
3766 || (pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR))
3767 {
3768 pVmcbCtrl->IntCtrl.n.u1VIrqPending = 0;
3769 pVmcbCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INT_CTRL;
3770 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_VINTR);
3771 Log4(("Cleared VINTR intercept\n"));
3772 }
3773}
3774
3775#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3776/**
3777 * Evaluates the event to be delivered to the nested-guest and sets it as the
3778 * pending event.
3779 *
3780 * @returns VBox strict status code.
3781 * @param pVCpu The cross context virtual CPU structure.
3782 * @param pCtx Pointer to the guest-CPU context.
3783 */
3784static VBOXSTRICTRC hmR0SvmEvaluatePendingEventNested(PVMCPU pVCpu, PCPUMCTX pCtx)
3785{
3786 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
3787 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_HWVIRT
3788 | CPUMCTX_EXTRN_RFLAGS
3789 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW
3790 | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ);
3791
3792 Assert(!pVCpu->hm.s.Event.fPending);
3793 Assert(pCtx->hwvirt.fGif);
3794 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
3795 Assert(pVmcb);
3796
3797 bool const fVirtualGif = CPUMGetSvmNstGstVGif(pCtx);
3798 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3799 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3800
3801 Log4Func(("fVirtualGif=%RTbool fBlockNmi=%RTbool fIntShadow=%RTbool fIntrPending=%RTbool fNmiPending=%RTbool\n",
3802 fVirtualGif, fBlockNmi, fIntShadow, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC),
3803 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)));
3804
3805 /** @todo SMI. SMIs take priority over NMIs. */
3806
3807 /*
3808 * Check if the guest can receive NMIs.
3809 * Nested NMIs are not allowed, see AMD spec. 8.1.4 "Masking External Interrupts".
3810 * NMIs take priority over maskable interrupts, see AMD spec. 8.5 "Priorities".
3811 */
3812 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)
3813 && !fBlockNmi)
3814 {
3815 if ( fVirtualGif
3816 && !fIntShadow)
3817 {
3818 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_NMI))
3819 {
3820 Log4(("Intercepting NMI -> #VMEXIT\n"));
3821 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
3822 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_NMI, 0, 0);
3823 }
3824
3825 Log4(("Setting NMI pending for injection\n"));
3826 SVMEVENT Event;
3827 Event.u = 0;
3828 Event.n.u1Valid = 1;
3829 Event.n.u8Vector = X86_XCPT_NMI;
3830 Event.n.u3Type = SVM_EVENT_NMI;
3831 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3832 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3833 }
3834 else if (!fVirtualGif)
3835 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3836 else
3837 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3838 }
3839 /*
3840 * Check if the nested-guest can receive external interrupts (generated by
3841 * the guest's PIC/APIC).
3842 *
3843 * External intercepts, NMI, SMI etc. from the physical CPU are -always- intercepted
3844 * when executing using hardware-assisted SVM, see HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS.
3845 *
3846 * External interrupts that are generated for the outer guest may be intercepted
3847 * depending on how the nested-guest VMCB was programmed by guest software.
3848 *
3849 * Physical interrupts always take priority over virtual interrupts,
3850 * see AMD spec. 15.21.4 "Injecting Virtual (INTR) Interrupts".
3851 */
3852 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3853 && !pVCpu->hm.s.fSingleInstruction)
3854 {
3855 if ( fVirtualGif
3856 && !fIntShadow
3857 && CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx))
3858 {
3859 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INTR))
3860 {
3861 Log4(("Intercepting INTR -> #VMEXIT\n"));
3862 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
3863 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_INTR, 0, 0);
3864 }
3865
3866 uint8_t u8Interrupt;
3867 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3868 if (RT_SUCCESS(rc))
3869 {
3870 Log4(("Setting external interrupt %#x pending for injection\n", u8Interrupt));
3871 SVMEVENT Event;
3872 Event.u = 0;
3873 Event.n.u1Valid = 1;
3874 Event.n.u8Vector = u8Interrupt;
3875 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3876 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3877 }
3878 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3879 {
3880 /*
3881 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3882 * updated eventually when the TPR is written by the guest.
3883 */
3884 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3885 }
3886 else
3887 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3888 }
3889 else if (!fVirtualGif)
3890 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3891 else
3892 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3893 }
3894
3895 return VINF_SUCCESS;
3896}
3897#endif
3898
3899/**
3900 * Evaluates the event to be delivered to the guest and sets it as the pending
3901 * event.
3902 *
3903 * @param pVCpu The cross context virtual CPU structure.
3904 * @param pCtx Pointer to the guest-CPU context.
3905 */
3906static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
3907{
3908 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
3909 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_HWVIRT
3910 | CPUMCTX_EXTRN_RFLAGS
3911 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW);
3912
3913 Assert(!pVCpu->hm.s.Event.fPending);
3914 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
3915 Assert(pVmcb);
3916
3917#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3918 bool const fGif = pCtx->hwvirt.fGif;
3919#else
3920 bool const fGif = true;
3921#endif
3922 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3923 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
3924 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3925
3926 Log4Func(("fGif=%RTbool fBlockNmi=%RTbool fBlockInt=%RTbool fIntShadow=%RTbool Intr. pending=%RTbool NMI pending=%RTbool\n",
3927 fGif, fBlockNmi, fBlockInt, fIntShadow,
3928 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC),
3929 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)));
3930
3931 /** @todo SMI. SMIs take priority over NMIs. */
3932
3933 /*
3934 * Check if the guest can receive NMIs.
3935 * Nested NMIs are not allowed, see AMD spec. 8.1.4 "Masking External Interrupts".
3936 * NMIs take priority over maskable interrupts, see AMD spec. 8.5 "Priorities".
3937 */
3938 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)
3939 && !fBlockNmi)
3940 {
3941 if ( fGif
3942 && !fIntShadow)
3943 {
3944 Log4(("Setting NMI pending for injection\n"));
3945 SVMEVENT Event;
3946 Event.u = 0;
3947 Event.n.u1Valid = 1;
3948 Event.n.u8Vector = X86_XCPT_NMI;
3949 Event.n.u3Type = SVM_EVENT_NMI;
3950 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3951 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3952 }
3953 else if (!fGif)
3954 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3955 else
3956 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3957 }
3958 /*
3959 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
3960 * a valid interrupt we -must- deliver the interrupt. We can no longer re-request it from the APIC.
3961 */
3962 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3963 && !pVCpu->hm.s.fSingleInstruction)
3964 {
3965 if ( fGif
3966 && !fBlockInt
3967 && !fIntShadow)
3968 {
3969 uint8_t u8Interrupt;
3970 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3971 if (RT_SUCCESS(rc))
3972 {
3973 Log4(("Setting external interrupt %#x pending for injection\n", u8Interrupt));
3974 SVMEVENT Event;
3975 Event.u = 0;
3976 Event.n.u1Valid = 1;
3977 Event.n.u8Vector = u8Interrupt;
3978 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3979 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3980 }
3981 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3982 {
3983 /*
3984 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3985 * updated eventually when the TPR is written by the guest.
3986 */
3987 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3988 }
3989 else
3990 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3991 }
3992 else if (!fGif)
3993 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3994 else
3995 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3996 }
3997}
3998
3999
4000/**
4001 * Injects any pending events into the guest (or nested-guest).
4002 *
4003 * @param pVCpu The cross context virtual CPU structure.
4004 * @param pCtx Pointer to the guest-CPU context.
4005 * @param pVmcb Pointer to the VM control block.
4006 *
4007 * @remarks Must only be called when we are guaranteed to enter
4008 * hardware-assisted SVM execution and not return to ring-3
4009 * prematurely.
4010 */
4011static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb)
4012{
4013 Assert(!TRPMHasTrap(pVCpu));
4014 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4015
4016 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
4017#ifdef VBOX_STRICT
4018 bool const fGif = pCtx->hwvirt.fGif;
4019 bool fAllowInt = fGif;
4020 if (fGif)
4021 {
4022 /*
4023 * For nested-guests we have no way to determine if we're injecting a physical or virtual
4024 * interrupt at this point. Hence the partial verification below.
4025 */
4026 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4027 fAllowInt = CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx) || CPUMCanSvmNstGstTakeVirtIntr(pVCpu, pCtx);
4028 else
4029 fAllowInt = RT_BOOL(pCtx->eflags.u32 & X86_EFL_IF);
4030 }
4031#endif
4032
4033 if (pVCpu->hm.s.Event.fPending)
4034 {
4035 SVMEVENT Event;
4036 Event.u = pVCpu->hm.s.Event.u64IntInfo;
4037 Assert(Event.n.u1Valid);
4038
4039 /*
4040 * Validate event injection pre-conditions.
4041 */
4042 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
4043 {
4044 Assert(fAllowInt);
4045 Assert(!fIntShadow);
4046 }
4047 else if (Event.n.u3Type == SVM_EVENT_NMI)
4048 {
4049 Assert(fGif);
4050 Assert(!fIntShadow);
4051 }
4052
4053 /*
4054 * Before injecting an NMI we must set VMCPU_FF_BLOCK_NMIS to prevent nested NMIs. We do this only
4055 * when we are surely going to inject the NMI as otherwise if we return to ring-3 prematurely we
4056 * could leave NMIs blocked indefinitely upon re-entry into SVM R0.
4057 *
4058 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set
4059 * the VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
4060 */
4061 if ( Event.n.u3Type == SVM_EVENT_NMI
4062 && Event.n.u8Vector == X86_XCPT_NMI
4063 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4064 {
4065 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
4066 }
4067
4068 /*
4069 * Inject it (update VMCB for injection by the hardware).
4070 */
4071 Log4(("Injecting pending HM event\n"));
4072 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, &Event);
4073 pVCpu->hm.s.Event.fPending = false;
4074
4075 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
4076 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
4077 else
4078 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
4079 }
4080 else
4081 Assert(pVmcb->ctrl.EventInject.n.u1Valid == 0);
4082
4083 /*
4084 * We could have injected an NMI through IEM and continue guest execution using
4085 * hardware-assisted SVM. In which case, we would not have any events pending (above)
4086 * but we still need to intercept IRET in order to eventually clear NMI inhibition.
4087 */
4088 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4089 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_IRET);
4090
4091 /*
4092 * Update the guest interrupt shadow in the guest (or nested-guest) VMCB.
4093 *
4094 * For nested-guests: We need to update it too for the scenario where IEM executes
4095 * the nested-guest but execution later continues here with an interrupt shadow active.
4096 */
4097 pVmcb->ctrl.IntShadow.n.u1IntShadow = fIntShadow;
4098}
4099
4100
4101/**
4102 * Reports world-switch error and dumps some useful debug info.
4103 *
4104 * @param pVM The cross context VM structure.
4105 * @param pVCpu The cross context virtual CPU structure.
4106 * @param rcVMRun The return code from VMRUN (or
4107 * VERR_SVM_INVALID_GUEST_STATE for invalid
4108 * guest-state).
4109 * @param pCtx Pointer to the guest-CPU context.
4110 */
4111static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
4112{
4113 NOREF(pCtx);
4114 HMSVM_ASSERT_PREEMPT_SAFE();
4115 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4116 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
4117
4118 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4119 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
4120 {
4121 hmR0DumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
4122#ifdef VBOX_STRICT
4123 Log4(("ctrl.u32VmcbCleanBits %#RX32\n", pVmcb->ctrl.u32VmcbCleanBits));
4124 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
4125 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
4126 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
4127 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
4128 Log4(("ctrl.u32InterceptXcpt %#x\n", pVmcb->ctrl.u32InterceptXcpt));
4129 Log4(("ctrl.u64InterceptCtrl %#RX64\n", pVmcb->ctrl.u64InterceptCtrl));
4130 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
4131 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
4132 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
4133
4134 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
4135 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
4136 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
4137
4138 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
4139 Log4(("ctrl.IntCtrl.u1VIrqPending %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqPending));
4140 Log4(("ctrl.IntCtrl.u1VGif %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGif));
4141 Log4(("ctrl.IntCtrl.u6Reserved0 %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
4142 Log4(("ctrl.IntCtrl.u4VIntrPrio %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIntrPrio));
4143 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
4144 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
4145 Log4(("ctrl.IntCtrl.u1VIntrMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIntrMasking));
4146 Log4(("ctrl.IntCtrl.u1VGifEnable %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGifEnable));
4147 Log4(("ctrl.IntCtrl.u5Reserved1 %#x\n", pVmcb->ctrl.IntCtrl.n.u5Reserved));
4148 Log4(("ctrl.IntCtrl.u8VIntrVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIntrVector));
4149 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
4150
4151 Log4(("ctrl.IntShadow.u1IntShadow %#x\n", pVmcb->ctrl.IntShadow.n.u1IntShadow));
4152 Log4(("ctrl.IntShadow.u1GuestIntMask %#x\n", pVmcb->ctrl.IntShadow.n.u1GuestIntMask));
4153 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
4154 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
4155 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
4156 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
4157 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
4158 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
4159 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
4160 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
4161 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
4162 Log4(("ctrl.NestedPagingCtrl.u1NestedPaging %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1NestedPaging));
4163 Log4(("ctrl.NestedPagingCtrl.u1Sev %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1Sev));
4164 Log4(("ctrl.NestedPagingCtrl.u1SevEs %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1SevEs));
4165 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
4166 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
4167 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
4168 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
4169 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
4170 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
4171
4172 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
4173
4174 Log4(("ctrl.LbrVirt.u1LbrVirt %#x\n", pVmcb->ctrl.LbrVirt.n.u1LbrVirt));
4175 Log4(("ctrl.LbrVirt.u1VirtVmsaveVmload %#x\n", pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload));
4176
4177 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
4178 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
4179 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
4180 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
4181 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
4182 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
4183 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
4184 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
4185 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
4186 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
4187 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
4188 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
4189 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
4190 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
4191 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
4192 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
4193 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
4194 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
4195 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
4196 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
4197
4198 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
4199 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
4200
4201 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
4202 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
4203 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
4204 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
4205
4206 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
4207 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
4208
4209 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
4210 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
4211 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
4212 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
4213
4214 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
4215 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
4216 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
4217 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
4218 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
4219 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
4220 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
4221
4222 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
4223 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
4224 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
4225 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
4226
4227 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
4228 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
4229 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
4230
4231 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
4232 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
4233 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
4234 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
4235 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
4236 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
4237 Log4(("guest.u64PAT %#RX64\n", pVmcb->guest.u64PAT));
4238 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
4239 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
4240 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
4241 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
4242 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
4243#endif /* VBOX_STRICT */
4244 }
4245 else
4246 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
4247
4248 NOREF(pVmcb);
4249}
4250
4251
4252/**
4253 * Check per-VM and per-VCPU force flag actions that require us to go back to
4254 * ring-3 for one reason or another.
4255 *
4256 * @returns VBox status code (information status code included).
4257 * @retval VINF_SUCCESS if we don't have any actions that require going back to
4258 * ring-3.
4259 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
4260 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
4261 * interrupts)
4262 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
4263 * all EMTs to be in ring-3.
4264 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
4265 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
4266 * to the EM loop.
4267 *
4268 * @param pVM The cross context VM structure.
4269 * @param pVCpu The cross context virtual CPU structure.
4270 * @param pCtx Pointer to the guest-CPU context.
4271 */
4272static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4273{
4274 Assert(VMMRZCallRing3IsEnabled(pVCpu));
4275 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
4276 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
4277
4278 /* Could happen as a result of longjump. */
4279 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
4280 {
4281 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CR3));
4282 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
4283 }
4284
4285 /* Update pending interrupts into the APIC's IRR. */
4286 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
4287 APICUpdatePendingInterrupts(pVCpu);
4288
4289 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
4290 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
4291 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
4292 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
4293 {
4294 /* Pending PGM C3 sync. */
4295 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
4296 {
4297 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
4298 if (rc != VINF_SUCCESS)
4299 {
4300 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
4301 return rc;
4302 }
4303 }
4304
4305 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
4306 /* -XXX- what was that about single stepping? */
4307 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
4308 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4309 {
4310 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4311 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
4312 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
4313 return rc;
4314 }
4315
4316 /* Pending VM request packets, such as hardware interrupts. */
4317 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
4318 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
4319 {
4320 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
4321 return VINF_EM_PENDING_REQUEST;
4322 }
4323
4324 /* Pending PGM pool flushes. */
4325 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
4326 {
4327 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
4328 return VINF_PGM_POOL_FLUSH_PENDING;
4329 }
4330
4331 /* Pending DMA requests. */
4332 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
4333 {
4334 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
4335 return VINF_EM_RAW_TO_R3;
4336 }
4337 }
4338
4339 return VINF_SUCCESS;
4340}
4341
4342
4343#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4344/**
4345 * Does the preparations before executing nested-guest code in AMD-V.
4346 *
4347 * @returns VBox status code (informational status codes included).
4348 * @retval VINF_SUCCESS if we can proceed with running the guest.
4349 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4350 *
4351 * @param pVM The cross context VM structure.
4352 * @param pVCpu The cross context virtual CPU structure.
4353 * @param pCtx Pointer to the nested-guest-CPU context.
4354 * @param pSvmTransient Pointer to the SVM transient structure.
4355 *
4356 * @remarks Same caveats regarding longjumps as hmR0SvmPreRunGuest applies.
4357 * @sa hmR0SvmPreRunGuest.
4358 */
4359static int hmR0SvmPreRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4360{
4361 HMSVM_ASSERT_PREEMPT_SAFE();
4362 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4363
4364#ifdef VBOX_WITH_NESTED_HWVIRT_SVM_ONLY_IN_IEM
4365 Log2(("hmR0SvmPreRunGuest: Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
4366 return VINF_EM_RESCHEDULE_REM;
4367#endif
4368
4369 /* Check force flag actions that might require us to go back to ring-3. */
4370 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4371 if (rc != VINF_SUCCESS)
4372 return rc;
4373
4374 if (TRPMHasTrap(pVCpu))
4375 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4376 else if (!pVCpu->hm.s.Event.fPending)
4377 {
4378 VBOXSTRICTRC rcStrict = hmR0SvmEvaluatePendingEventNested(pVCpu, pCtx);
4379 if ( rcStrict != VINF_SUCCESS
4380 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4381 return VBOXSTRICTRC_VAL(rcStrict);
4382 }
4383
4384 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4385
4386 /*
4387 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4388 * Just do it in software, see @bugref{8411}.
4389 * NB: If we could continue a task switch exit we wouldn't need to do this.
4390 */
4391 if (RT_UNLIKELY( !pVM->hm.s.svm.u32Features
4392 && pVCpu->hm.s.Event.fPending
4393 && SVM_EVENT_GET_TYPE(pVCpu->hm.s.Event.u64IntInfo) == SVM_EVENT_NMI))
4394 {
4395 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4396 }
4397
4398#ifdef HMSVM_SYNC_FULL_NESTED_GUEST_STATE
4399 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4400#endif
4401
4402 /*
4403 * Load the nested-guest state.
4404 */
4405 rc = hmR0SvmLoadGuestStateNested(pVCpu, pCtx);
4406 AssertRCReturn(rc, rc);
4407 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull); /** @todo Get new STAM counter for this? */
4408
4409 /* Ensure we've cached (and hopefully modified) the VMCB for execution using hardware-assisted SVM. */
4410 Assert(pVCpu->hm.s.svm.NstGstVmcbCache.fCacheValid);
4411
4412 /*
4413 * No longjmps to ring-3 from this point on!!!
4414 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4415 * This also disables flushing of the R0-logger instance (if any).
4416 */
4417 VMMRZCallRing3Disable(pVCpu);
4418
4419 /*
4420 * We disable interrupts so that we don't miss any interrupts that would flag
4421 * preemption (IPI/timers etc.) when thread-context hooks aren't used and we've
4422 * been running with preemption disabled for a while. Since this is purly to aid
4423 * the RTThreadPreemptIsPending code, it doesn't matter that it may temporarily
4424 * reenable and disable interrupt on NT.
4425 *
4426 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4427 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4428 *
4429 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4430 * executing guest code.
4431 */
4432 pSvmTransient->fEFlags = ASMIntDisableFlags();
4433 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4434 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4435 {
4436 ASMSetFlags(pSvmTransient->fEFlags);
4437 VMMRZCallRing3Enable(pVCpu);
4438 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4439 return VINF_EM_RAW_TO_R3;
4440 }
4441 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4442 {
4443 ASMSetFlags(pSvmTransient->fEFlags);
4444 VMMRZCallRing3Enable(pVCpu);
4445 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4446 return VINF_EM_RAW_INTERRUPT;
4447 }
4448 return VINF_SUCCESS;
4449}
4450#endif
4451
4452
4453/**
4454 * Does the preparations before executing guest code in AMD-V.
4455 *
4456 * This may cause longjmps to ring-3 and may even result in rescheduling to the
4457 * recompiler. We must be cautious what we do here regarding committing
4458 * guest-state information into the VMCB assuming we assuredly execute the guest
4459 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
4460 * clearing the common-state (TRPM/forceflags), we must undo those changes so
4461 * that the recompiler can (and should) use them when it resumes guest
4462 * execution. Otherwise such operations must be done when we can no longer
4463 * exit to ring-3.
4464 *
4465 * @returns VBox status code (informational status codes included).
4466 * @retval VINF_SUCCESS if we can proceed with running the guest.
4467 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4468 *
4469 * @param pVM The cross context VM structure.
4470 * @param pVCpu The cross context virtual CPU structure.
4471 * @param pCtx Pointer to the guest-CPU context.
4472 * @param pSvmTransient Pointer to the SVM transient structure.
4473 */
4474static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4475{
4476 HMSVM_ASSERT_PREEMPT_SAFE();
4477 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4478
4479 /* Check force flag actions that might require us to go back to ring-3. */
4480 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4481 if (rc != VINF_SUCCESS)
4482 return rc;
4483
4484 if (TRPMHasTrap(pVCpu))
4485 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4486 else if (!pVCpu->hm.s.Event.fPending)
4487 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
4488
4489 /*
4490 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4491 * Just do it in software, see @bugref{8411}.
4492 * NB: If we could continue a task switch exit we wouldn't need to do this.
4493 */
4494 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
4495 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
4496 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4497
4498#ifdef HMSVM_SYNC_FULL_GUEST_STATE
4499 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4500#endif
4501
4502 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
4503 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
4504 AssertRCReturn(rc, rc);
4505 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
4506
4507 /*
4508 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
4509 * so we can update it on the way back if the guest changed the TPR.
4510 */
4511 if (pVCpu->hm.s.svm.fSyncVTpr)
4512 {
4513 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4514 if (pVM->hm.s.fTPRPatchingActive)
4515 pSvmTransient->u8GuestTpr = pVmcb->guest.u64LSTAR;
4516 else
4517 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
4518 }
4519
4520 /*
4521 * No longjmps to ring-3 from this point on!!!
4522 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4523 * This also disables flushing of the R0-logger instance (if any).
4524 */
4525 VMMRZCallRing3Disable(pVCpu);
4526
4527 /*
4528 * We disable interrupts so that we don't miss any interrupts that would flag
4529 * preemption (IPI/timers etc.) when thread-context hooks aren't used and we've
4530 * been running with preemption disabled for a while. Since this is purly to aid
4531 * the RTThreadPreemptIsPending code, it doesn't matter that it may temporarily
4532 * reenable and disable interrupt on NT.
4533 *
4534 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4535 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4536 *
4537 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4538 * executing guest code.
4539 */
4540 pSvmTransient->fEFlags = ASMIntDisableFlags();
4541 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4542 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4543 {
4544 ASMSetFlags(pSvmTransient->fEFlags);
4545 VMMRZCallRing3Enable(pVCpu);
4546 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4547 return VINF_EM_RAW_TO_R3;
4548 }
4549 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4550 {
4551 ASMSetFlags(pSvmTransient->fEFlags);
4552 VMMRZCallRing3Enable(pVCpu);
4553 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4554 return VINF_EM_RAW_INTERRUPT;
4555 }
4556
4557 return VINF_SUCCESS;
4558}
4559
4560
4561/**
4562 * Prepares to run guest (or nested-guest) code in AMD-V and we've committed to
4563 * doing so.
4564 *
4565 * This means there is no backing out to ring-3 or anywhere else at this point.
4566 *
4567 * @param pVCpu The cross context virtual CPU structure.
4568 * @param pCtx Pointer to the guest-CPU context.
4569 * @param pSvmTransient Pointer to the SVM transient structure.
4570 *
4571 * @remarks Called with preemption disabled.
4572 * @remarks No-long-jump zone!!!
4573 */
4574static void hmR0SvmPreRunGuestCommitted(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4575{
4576 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4577 Assert(VMMR0IsLogFlushDisabled(pVCpu));
4578 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4579
4580 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4581 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
4582
4583 PVM pVM = pVCpu->CTX_SUFF(pVM);
4584 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4585
4586 hmR0SvmInjectPendingEvent(pVCpu, pCtx, pVmcb);
4587
4588 if (!CPUMIsGuestFPUStateActive(pVCpu))
4589 {
4590 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4591 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
4592 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4593 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
4594 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4595 }
4596
4597 /* Load the state shared between host and guest (FPU, debug). */
4598 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
4599 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
4600
4601 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
4602 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
4603
4604 PHMGLOBALCPUINFO pHostCpu = hmR0GetCurrentCpu();
4605 RTCPUID const idHostCpu = pHostCpu->idCpu;
4606 bool const fMigratedHostCpu = idHostCpu != pVCpu->hm.s.idLastCpu;
4607
4608 /* Setup TSC offsetting. */
4609 if ( pSvmTransient->fUpdateTscOffsetting
4610 || fMigratedHostCpu)
4611 {
4612 hmR0SvmUpdateTscOffsetting(pVM, pVCpu, pCtx, pVmcb);
4613 pSvmTransient->fUpdateTscOffsetting = false;
4614 }
4615
4616 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
4617 if (fMigratedHostCpu)
4618 pVmcb->ctrl.u32VmcbCleanBits = 0;
4619
4620 /* Store status of the shared guest-host state at the time of VMRUN. */
4621#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4622 if (CPUMIsGuestInLongModeEx(pCtx))
4623 {
4624 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
4625 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
4626 }
4627 else
4628#endif
4629 {
4630 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
4631 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
4632 }
4633
4634#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4635 uint8_t *pbMsrBitmap;
4636 if (!pSvmTransient->fIsNestedGuest)
4637 pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4638 else
4639 {
4640 hmR0SvmMergeMsrpmNested(pHostCpu, pVCpu, pCtx);
4641
4642 /* Update the nested-guest VMCB with the newly merged MSRPM (clean bits updated below). */
4643 pVmcb->ctrl.u64MSRPMPhysAddr = pHostCpu->n.svm.HCPhysNstGstMsrpm;
4644 pbMsrBitmap = (uint8_t *)pHostCpu->n.svm.pvNstGstMsrpm;
4645 }
4646#else
4647 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4648#endif
4649
4650 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
4651 /* Flush the appropriate tagged-TLB entries. */
4652 hmR0SvmFlushTaggedTlb(pVCpu, pCtx, pVmcb, pHostCpu);
4653 Assert(pVCpu->hm.s.idLastCpu == idHostCpu);
4654
4655 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
4656
4657 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
4658 to start executing. */
4659
4660 /*
4661 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
4662 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
4663 *
4664 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
4665 */
4666 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
4667 && !(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSCP))
4668 {
4669 uint64_t const uGuestTscAux = CPUMGetGuestTscAux(pVCpu);
4670 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
4671 if (uGuestTscAux != pVCpu->hm.s.u64HostTscAux)
4672 ASMWrMsr(MSR_K8_TSC_AUX, uGuestTscAux);
4673 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
4674 pSvmTransient->fRestoreTscAuxMsr = true;
4675 }
4676 else
4677 {
4678 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
4679 pSvmTransient->fRestoreTscAuxMsr = false;
4680 }
4681 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
4682
4683 /*
4684 * If VMCB Clean bits isn't supported by the CPU or exposed to the guest in the
4685 * nested virtualization case, mark all state-bits as dirty indicating to the
4686 * CPU to re-load from VMCB.
4687 */
4688 bool const fSupportsVmcbCleanBits = hmR0SvmSupportsVmcbCleanBits(pVCpu, pCtx);
4689 if (!fSupportsVmcbCleanBits)
4690 pVmcb->ctrl.u32VmcbCleanBits = 0;
4691}
4692
4693
4694/**
4695 * Wrapper for running the guest code in AMD-V.
4696 *
4697 * @returns VBox strict status code.
4698 * @param pVM The cross context VM structure.
4699 * @param pVCpu The cross context virtual CPU structure.
4700 * @param pCtx Pointer to the guest-CPU context.
4701 *
4702 * @remarks No-long-jump zone!!!
4703 */
4704DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4705{
4706 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
4707 pCtx->fExtrn |= HMSVM_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
4708
4709 /*
4710 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4711 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4712 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4713 */
4714#ifdef VBOX_WITH_KERNEL_USING_XMM
4715 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4716 pVCpu->hm.s.svm.pfnVMRun);
4717#else
4718 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4719#endif
4720}
4721
4722
4723#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4724/**
4725 * Wrapper for running the nested-guest code in AMD-V.
4726 *
4727 * @returns VBox strict status code.
4728 * @param pVM The cross context VM structure.
4729 * @param pVCpu The cross context virtual CPU structure.
4730 * @param pCtx Pointer to the guest-CPU context.
4731 *
4732 * @remarks No-long-jump zone!!!
4733 */
4734DECLINLINE(int) hmR0SvmRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4735{
4736 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
4737 pCtx->fExtrn |= HMSVM_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
4738
4739 /*
4740 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4741 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4742 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4743 */
4744#ifdef VBOX_WITH_KERNEL_USING_XMM
4745 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4746 pVCpu->hm.s.svm.pfnVMRun);
4747#else
4748 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4749#endif
4750}
4751
4752
4753/**
4754 * Undoes the TSC offset applied for an SVM nested-guest and returns the TSC
4755 * value for the guest.
4756 *
4757 * @returns The TSC offset after undoing any nested-guest TSC offset.
4758 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
4759 * @param uTicks The nested-guest TSC.
4760 *
4761 * @note If you make any changes to this function, please check if
4762 * hmR0SvmNstGstUndoTscOffset() needs adjusting.
4763 *
4764 * @sa HMSvmNstGstApplyTscOffset().
4765 */
4766DECLINLINE(uint64_t) hmR0SvmNstGstUndoTscOffset(PVMCPU pVCpu, uint64_t uTicks)
4767{
4768 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
4769 Assert(pVmcbNstGstCache->fCacheValid);
4770 return uTicks - pVmcbNstGstCache->u64TSCOffset;
4771}
4772#endif
4773
4774/**
4775 * Performs some essential restoration of state after running guest (or
4776 * nested-guest) code in AMD-V.
4777 *
4778 * @param pVCpu The cross context virtual CPU structure.
4779 * @param pCtx Pointer to the guest-CPU context. The data maybe
4780 * out-of-sync. Make sure to update the required fields
4781 * before using them.
4782 * @param pSvmTransient Pointer to the SVM transient structure.
4783 * @param rcVMRun Return code of VMRUN.
4784 *
4785 * @remarks Called with interrupts disabled.
4786 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
4787 * unconditionally when it is safe to do so.
4788 */
4789static void hmR0SvmPostRunGuest(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
4790{
4791 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4792
4793 uint64_t const uHostTsc = ASMReadTSC(); /* Read the TSC as soon as possible. */
4794 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
4795 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
4796
4797 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4798 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
4799
4800 /* TSC read must be done early for maximum accuracy. */
4801 if (!(pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSC))
4802 {
4803 if (!pSvmTransient->fIsNestedGuest)
4804 TMCpuTickSetLastSeen(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4805#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4806 else
4807 {
4808 /* The nested-guest VMCB TSC offset shall eventually be restored on #VMEXIT via HMSvmNstGstVmExitNotify(). */
4809 uint64_t const uGstTsc = hmR0SvmNstGstUndoTscOffset(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4810 TMCpuTickSetLastSeen(pVCpu, uGstTsc);
4811 }
4812#endif
4813 }
4814
4815 if (pSvmTransient->fRestoreTscAuxMsr)
4816 {
4817 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
4818 CPUMSetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
4819 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
4820 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
4821 }
4822
4823 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
4824 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
4825 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4826
4827 Assert(!(ASMGetFlags() & X86_EFL_IF));
4828 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
4829 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
4830
4831 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
4832 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
4833 {
4834 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
4835 return;
4836 }
4837
4838 pSvmTransient->u64ExitCode = pVmcbCtrl->u64ExitCode; /* Save the #VMEXIT reason. */
4839 pVmcbCtrl->u32VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
4840 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
4841 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
4842
4843 hmR0SvmSaveGuestState(pVCpu, pCtx, pVmcb); /* Save the guest state from the VMCB to the guest-CPU context. */
4844
4845 if ( pSvmTransient->u64ExitCode != SVM_EXIT_INVALID
4846 && pVCpu->hm.s.svm.fSyncVTpr)
4847 {
4848 Assert(!pSvmTransient->fIsNestedGuest);
4849 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
4850 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive
4851 && (pVmcb->guest.u64LSTAR & 0xff) != pSvmTransient->u8GuestTpr)
4852 {
4853 int rc = APICSetTpr(pVCpu, pVmcb->guest.u64LSTAR & 0xff);
4854 AssertRC(rc);
4855 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4856 }
4857 /* Sync TPR when we aren't intercepting CR8 writes. */
4858 else if (pSvmTransient->u8GuestTpr != pVmcbCtrl->IntCtrl.n.u8VTPR)
4859 {
4860 int rc = APICSetTpr(pVCpu, pVmcbCtrl->IntCtrl.n.u8VTPR << 4);
4861 AssertRC(rc);
4862 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4863 }
4864 }
4865
4866 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
4867 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_SVM, pSvmTransient->u64ExitCode & EMEXIT_F_TYPE_MASK),
4868 pCtx->cs.u64Base + pCtx->rip, uHostTsc);
4869}
4870
4871
4872/**
4873 * Runs the guest code using AMD-V.
4874 *
4875 * @returns VBox status code.
4876 * @param pVM The cross context VM structure.
4877 * @param pVCpu The cross context virtual CPU structure.
4878 * @param pCtx Pointer to the guest-CPU context.
4879 * @param pcLoops Pointer to the number of executed loops.
4880 */
4881static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4882{
4883 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4884 Assert(pcLoops);
4885 Assert(*pcLoops <= cMaxResumeLoops);
4886
4887 SVMTRANSIENT SvmTransient;
4888 RT_ZERO(SvmTransient);
4889 SvmTransient.fUpdateTscOffsetting = true;
4890 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4891
4892 int rc = VERR_INTERNAL_ERROR_5;
4893 for (;;)
4894 {
4895 Assert(!HMR0SuspendPending());
4896 HMSVM_ASSERT_CPU_SAFE();
4897
4898 /* Preparatory work for running guest code, this may force us to return
4899 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4900 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4901 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4902 if (rc != VINF_SUCCESS)
4903 break;
4904
4905 /*
4906 * No longjmps to ring-3 from this point on!!!
4907 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4908 * This also disables flushing of the R0-logger instance (if any).
4909 */
4910 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4911 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4912
4913 /* Restore any residual host-state and save any bits shared between host
4914 and guest into the guest-CPU state. Re-enables interrupts! */
4915 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4916
4917 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4918 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4919 {
4920 if (rc == VINF_SUCCESS)
4921 rc = VERR_SVM_INVALID_GUEST_STATE;
4922 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4923 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4924 break;
4925 }
4926
4927 /* Handle the #VMEXIT. */
4928 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4929 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4930 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4931 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4932 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4933 if (rc != VINF_SUCCESS)
4934 break;
4935 if (++(*pcLoops) >= cMaxResumeLoops)
4936 {
4937 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4938 rc = VINF_EM_RAW_INTERRUPT;
4939 break;
4940 }
4941 }
4942
4943 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4944 return rc;
4945}
4946
4947
4948/**
4949 * Runs the guest code using AMD-V in single step mode.
4950 *
4951 * @returns VBox status code.
4952 * @param pVM The cross context VM structure.
4953 * @param pVCpu The cross context virtual CPU structure.
4954 * @param pCtx Pointer to the guest-CPU context.
4955 * @param pcLoops Pointer to the number of executed loops.
4956 */
4957static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4958{
4959 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4960 Assert(pcLoops);
4961 Assert(*pcLoops <= cMaxResumeLoops);
4962
4963 SVMTRANSIENT SvmTransient;
4964 RT_ZERO(SvmTransient);
4965 SvmTransient.fUpdateTscOffsetting = true;
4966 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4967
4968 uint16_t uCsStart = pCtx->cs.Sel;
4969 uint64_t uRipStart = pCtx->rip;
4970
4971 int rc = VERR_INTERNAL_ERROR_5;
4972 for (;;)
4973 {
4974 Assert(!HMR0SuspendPending());
4975 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
4976 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
4977 (unsigned)RTMpCpuId(), *pcLoops));
4978
4979 /* Preparatory work for running guest code, this may force us to return
4980 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4981 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4982 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4983 if (rc != VINF_SUCCESS)
4984 break;
4985
4986 /*
4987 * No longjmps to ring-3 from this point on!!!
4988 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4989 * This also disables flushing of the R0-logger instance (if any).
4990 */
4991 VMMRZCallRing3Disable(pVCpu);
4992 VMMRZCallRing3RemoveNotification(pVCpu);
4993 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4994
4995 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4996
4997 /*
4998 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
4999 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
5000 */
5001 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
5002 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
5003 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
5004 {
5005 if (rc == VINF_SUCCESS)
5006 rc = VERR_SVM_INVALID_GUEST_STATE;
5007 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
5008 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
5009 return rc;
5010 }
5011
5012 /* Handle the #VMEXIT. */
5013 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
5014 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
5015 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
5016 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
5017 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
5018 if (rc != VINF_SUCCESS)
5019 break;
5020 if (++(*pcLoops) >= cMaxResumeLoops)
5021 {
5022 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
5023 rc = VINF_EM_RAW_INTERRUPT;
5024 break;
5025 }
5026
5027 /*
5028 * Did the RIP change, if so, consider it a single step.
5029 * Otherwise, make sure one of the TFs gets set.
5030 */
5031 if ( pCtx->rip != uRipStart
5032 || pCtx->cs.Sel != uCsStart)
5033 {
5034 rc = VINF_EM_DBG_STEPPED;
5035 break;
5036 }
5037 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
5038 }
5039
5040 /*
5041 * Clear the X86_EFL_TF if necessary.
5042 */
5043 if (pVCpu->hm.s.fClearTrapFlag)
5044 {
5045 pVCpu->hm.s.fClearTrapFlag = false;
5046 pCtx->eflags.Bits.u1TF = 0;
5047 }
5048
5049 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
5050 return rc;
5051}
5052
5053#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5054/**
5055 * Runs the nested-guest code using AMD-V.
5056 *
5057 * @returns VBox status code.
5058 * @param pVM The cross context VM structure.
5059 * @param pVCpu The cross context virtual CPU structure.
5060 * @param pCtx Pointer to the guest-CPU context.
5061 * @param pcLoops Pointer to the number of executed loops. If we're switching
5062 * from the guest-code execution loop to this nested-guest
5063 * execution loop pass the remainder value, else pass 0.
5064 */
5065static int hmR0SvmRunGuestCodeNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
5066{
5067 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5068 Assert(pcLoops);
5069 Assert(*pcLoops <= pVM->hm.s.cMaxResumeLoops);
5070
5071 SVMTRANSIENT SvmTransient;
5072 RT_ZERO(SvmTransient);
5073 SvmTransient.fUpdateTscOffsetting = true;
5074 SvmTransient.pVmcb = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5075 SvmTransient.fIsNestedGuest = true;
5076
5077 int rc = VERR_INTERNAL_ERROR_4;
5078 for (;;)
5079 {
5080 Assert(!HMR0SuspendPending());
5081 HMSVM_ASSERT_CPU_SAFE();
5082
5083 /* Preparatory work for running nested-guest code, this may force us to return
5084 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
5085 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
5086 rc = hmR0SvmPreRunGuestNested(pVM, pVCpu, pCtx, &SvmTransient);
5087 if ( rc != VINF_SUCCESS
5088 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5089 {
5090 break;
5091 }
5092
5093 /*
5094 * No longjmps to ring-3 from this point on!!!
5095 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
5096 * This also disables flushing of the R0-logger instance (if any).
5097 */
5098 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
5099
5100 rc = hmR0SvmRunGuestNested(pVM, pVCpu, pCtx);
5101
5102 /* Restore any residual host-state and save any bits shared between host
5103 and guest into the guest-CPU state. Re-enables interrupts! */
5104 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
5105
5106 if (RT_LIKELY( rc == VINF_SUCCESS
5107 && SvmTransient.u64ExitCode != SVM_EXIT_INVALID))
5108 { /* extremely likely */ }
5109 else
5110 {
5111 /* VMRUN failed, shouldn't really happen, Guru. */
5112 if (rc != VINF_SUCCESS)
5113 break;
5114
5115 /* Invalid nested-guest state. Cause a #VMEXIT but assert on strict builds. */
5116 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
5117 AssertMsgFailed(("Invalid nested-guest state. rc=%Rrc u64ExitCode=%#RX64\n", rc, SvmTransient.u64ExitCode));
5118 rc = VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_INVALID, 0, 0));
5119 break;
5120 }
5121
5122 /* Handle the #VMEXIT. */
5123 HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
5124 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
5125 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pCtx->hwvirt.svm.CTX_SUFF(pVmcb));
5126 rc = hmR0SvmHandleExitNested(pVCpu, pCtx, &SvmTransient);
5127 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
5128 if ( rc != VINF_SUCCESS
5129 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5130 break;
5131 if (++(*pcLoops) >= pVM->hm.s.cMaxResumeLoops)
5132 {
5133 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
5134 rc = VINF_EM_RAW_INTERRUPT;
5135 break;
5136 }
5137
5138 /** @todo handle single-stepping */
5139 }
5140
5141 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
5142 return rc;
5143}
5144#endif
5145
5146
5147/**
5148 * Runs the guest code using AMD-V.
5149 *
5150 * @returns Strict VBox status code.
5151 * @param pVM The cross context VM structure.
5152 * @param pVCpu The cross context virtual CPU structure.
5153 * @param pCtx Pointer to the guest-CPU context.
5154 */
5155VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5156{
5157 Assert(VMMRZCallRing3IsEnabled(pVCpu));
5158 HMSVM_ASSERT_PREEMPT_SAFE();
5159 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
5160
5161 uint32_t cLoops = 0;
5162 int rc;
5163#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5164 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5165#endif
5166 {
5167 if (!pVCpu->hm.s.fSingleInstruction)
5168 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx, &cLoops);
5169 else
5170 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx, &cLoops);
5171 }
5172#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5173 else
5174 {
5175 rc = VINF_SVM_VMRUN;
5176 }
5177
5178 /* Re-check the nested-guest condition here as we may be transitioning from the normal
5179 execution loop into the nested-guest, hence this is not placed in the 'else' part above. */
5180 if (rc == VINF_SVM_VMRUN)
5181 {
5182 rc = hmR0SvmRunGuestCodeNested(pVM, pVCpu, pCtx, &cLoops);
5183 if (rc == VINF_SVM_VMEXIT)
5184 rc = VINF_SUCCESS;
5185 }
5186#endif
5187
5188 /* Fixup error codes. */
5189 if (rc == VERR_EM_INTERPRETER)
5190 rc = VINF_EM_RAW_EMULATE_INSTR;
5191 else if (rc == VINF_EM_RESET)
5192 rc = VINF_EM_TRIPLE_FAULT;
5193
5194 /* Prepare to return to ring-3. This will remove longjmp notifications. */
5195 rc = hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
5196 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
5197 return rc;
5198}
5199
5200
5201#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5202/**
5203 * Determines whether an IOIO intercept is active for the nested-guest or not.
5204 *
5205 * @param pvIoBitmap Pointer to the nested-guest IO bitmap.
5206 * @param pIoExitInfo Pointer to the SVMIOIOEXITINFO.
5207 */
5208static bool hmR0SvmIsIoInterceptActive(void *pvIoBitmap, PSVMIOIOEXITINFO pIoExitInfo)
5209{
5210 const uint16_t u16Port = pIoExitInfo->n.u16Port;
5211 const SVMIOIOTYPE enmIoType = (SVMIOIOTYPE)pIoExitInfo->n.u1Type;
5212 const uint8_t cbReg = (pIoExitInfo->u >> SVM_IOIO_OP_SIZE_SHIFT) & 7;
5213 const uint8_t cAddrSizeBits = ((pIoExitInfo->u >> SVM_IOIO_ADDR_SIZE_SHIFT) & 7) << 4;
5214 const uint8_t iEffSeg = pIoExitInfo->n.u3Seg;
5215 const bool fRep = pIoExitInfo->n.u1Rep;
5216 const bool fStrIo = pIoExitInfo->n.u1Str;
5217
5218 return HMSvmIsIOInterceptActive(pvIoBitmap, u16Port, enmIoType, cbReg, cAddrSizeBits, iEffSeg, fRep, fStrIo,
5219 NULL /* pIoExitInfo */);
5220}
5221
5222
5223/**
5224 * Handles a nested-guest \#VMEXIT (for all EXITCODE values except
5225 * SVM_EXIT_INVALID).
5226 *
5227 * @returns VBox status code (informational status codes included).
5228 * @param pVCpu The cross context virtual CPU structure.
5229 * @param pCtx Pointer to the guest-CPU context.
5230 * @param pSvmTransient Pointer to the SVM transient structure.
5231 */
5232static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5233{
5234 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5235 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5236 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5237
5238 /** @todo Use IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK instead of
5239 * HMSVM_CPUMCTX_EXTRN_ALL below. See todo in
5240 * HMSvmNstGstVmExitNotify(). */
5241#define NST_GST_VMEXIT_CALL_RET(a_pVCpu, a_pCtx, a_uExitCode, a_uExitInfo1, a_uExitInfo2) \
5242 do { \
5243 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL); \
5244 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit((a_pVCpu), (a_uExitCode), (a_uExitInfo1), (a_uExitInfo2))); \
5245 } while (0)
5246
5247 /*
5248 * For all the #VMEXITs here we primarily figure out if the #VMEXIT is expected
5249 * by the nested-guest. If it isn't, it should be handled by the (outer) guest.
5250 */
5251 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5252 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
5253 uint64_t const uExitCode = pVmcbNstGstCtrl->u64ExitCode;
5254 uint64_t const uExitInfo1 = pVmcbNstGstCtrl->u64ExitInfo1;
5255 uint64_t const uExitInfo2 = pVmcbNstGstCtrl->u64ExitInfo2;
5256
5257 Assert(uExitCode == pVmcbNstGstCtrl->u64ExitCode);
5258 switch (uExitCode)
5259 {
5260 case SVM_EXIT_CPUID:
5261 {
5262 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CPUID))
5263 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5264 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
5265 }
5266
5267 case SVM_EXIT_RDTSC:
5268 {
5269 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDTSC))
5270 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5271 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5272 }
5273
5274 case SVM_EXIT_RDTSCP:
5275 {
5276 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDTSCP))
5277 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5278 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5279 }
5280
5281 case SVM_EXIT_MONITOR:
5282 {
5283 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MONITOR))
5284 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5285 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5286 }
5287
5288 case SVM_EXIT_MWAIT:
5289 {
5290 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MWAIT))
5291 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5292 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5293 }
5294
5295 case SVM_EXIT_HLT:
5296 {
5297 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_HLT))
5298 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5299 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5300 }
5301
5302 case SVM_EXIT_MSR:
5303 {
5304 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MSR_PROT))
5305 {
5306 uint32_t const idMsr = pCtx->ecx;
5307 uint16_t offMsrpm;
5308 uint8_t uMsrpmBit;
5309 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
5310 if (RT_SUCCESS(rc))
5311 {
5312 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
5313 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
5314
5315 uint8_t const *pbMsrBitmap = (uint8_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
5316 pbMsrBitmap += offMsrpm;
5317 bool const fInterceptRead = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit));
5318 bool const fInterceptWrite = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
5319
5320 if ( (fInterceptWrite && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
5321 || (fInterceptRead && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_READ))
5322 {
5323 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5324 }
5325 }
5326 else
5327 {
5328 /*
5329 * MSRs not covered by the MSRPM automatically cause an #VMEXIT.
5330 * See AMD-V spec. "15.11 MSR Intercepts".
5331 */
5332 Assert(rc == VERR_OUT_OF_RANGE);
5333 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5334 }
5335 }
5336 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5337 }
5338
5339 case SVM_EXIT_IOIO:
5340 {
5341 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_IOIO_PROT))
5342 {
5343 void *pvIoBitmap = pCtx->hwvirt.svm.CTX_SUFF(pvIoBitmap);
5344 SVMIOIOEXITINFO IoExitInfo;
5345 IoExitInfo.u = pVmcbNstGst->ctrl.u64ExitInfo1;
5346 bool const fIntercept = hmR0SvmIsIoInterceptActive(pvIoBitmap, &IoExitInfo);
5347 if (fIntercept)
5348 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5349 }
5350 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5351 }
5352
5353 case SVM_EXIT_XCPT_PF:
5354 {
5355 PVM pVM = pVCpu->CTX_SUFF(pVM);
5356 if (pVM->hm.s.fNestedPaging)
5357 {
5358 uint32_t const u32ErrCode = pVmcbNstGstCtrl->u64ExitInfo1;
5359 uint64_t const uFaultAddress = pVmcbNstGstCtrl->u64ExitInfo2;
5360
5361 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
5362 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_PF))
5363 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, u32ErrCode, uFaultAddress);
5364
5365 /* If the nested-guest is not intercepting #PFs, forward the #PF to the guest. */
5366 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR2);
5367 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5368 return VINF_SUCCESS;
5369 }
5370 return hmR0SvmExitXcptPF(pVCpu, pCtx,pSvmTransient);
5371 }
5372
5373 case SVM_EXIT_XCPT_UD:
5374 {
5375 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_UD))
5376 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5377 hmR0SvmSetPendingXcptUD(pVCpu);
5378 return VINF_SUCCESS;
5379 }
5380
5381 case SVM_EXIT_XCPT_MF:
5382 {
5383 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_MF))
5384 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5385 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5386 }
5387
5388 case SVM_EXIT_XCPT_DB:
5389 {
5390 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_DB))
5391 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5392 return hmR0SvmNestedExitXcptDB(pVCpu, pCtx, pSvmTransient);
5393 }
5394
5395 case SVM_EXIT_XCPT_AC:
5396 {
5397 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_AC))
5398 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5399 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5400 }
5401
5402 case SVM_EXIT_XCPT_BP:
5403 {
5404 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_BP))
5405 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5406 return hmR0SvmNestedExitXcptBP(pVCpu, pCtx, pSvmTransient);
5407 }
5408
5409 case SVM_EXIT_READ_CR0:
5410 case SVM_EXIT_READ_CR3:
5411 case SVM_EXIT_READ_CR4:
5412 {
5413 uint8_t const uCr = uExitCode - SVM_EXIT_READ_CR0;
5414 if (HMIsGuestSvmReadCRxInterceptSet(pVCpu, uCr))
5415 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5416 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5417 }
5418
5419 case SVM_EXIT_CR0_SEL_WRITE:
5420 {
5421 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CR0_SEL_WRITE))
5422 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5423 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5424 }
5425
5426 case SVM_EXIT_WRITE_CR0:
5427 case SVM_EXIT_WRITE_CR3:
5428 case SVM_EXIT_WRITE_CR4:
5429 case SVM_EXIT_WRITE_CR8: /** @todo Shouldn't writes to CR8 go to V_TPR instead since we run with V_INTR_MASKING set? */
5430 {
5431 uint8_t const uCr = uExitCode - SVM_EXIT_WRITE_CR0;
5432 Log4(("hmR0SvmHandleExitNested: Write CR%u: uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", uCr, uExitInfo1, uExitInfo2));
5433
5434 if (HMIsGuestSvmWriteCRxInterceptSet(pVCpu, uCr))
5435 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5436 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5437 }
5438
5439 case SVM_EXIT_PAUSE:
5440 {
5441 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_PAUSE))
5442 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5443 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5444 }
5445
5446 case SVM_EXIT_VINTR:
5447 {
5448 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VINTR))
5449 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5450 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5451 }
5452
5453 case SVM_EXIT_INTR:
5454 case SVM_EXIT_NMI:
5455 case SVM_EXIT_SMI:
5456 case SVM_EXIT_XCPT_NMI: /* Should not occur, SVM_EXIT_NMI is used instead. */
5457 {
5458 /*
5459 * We shouldn't direct physical interrupts, NMIs, SMIs to the nested-guest.
5460 *
5461 * Although we don't intercept SMIs, the nested-guest might. Therefore, we
5462 * might get an SMI #VMEXIT here so simply ignore rather than causing a
5463 * corresponding nested-guest #VMEXIT.
5464 */
5465 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5466 }
5467
5468 case SVM_EXIT_FERR_FREEZE:
5469 {
5470 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_FERR_FREEZE))
5471 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5472 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5473 }
5474
5475 case SVM_EXIT_INVLPG:
5476 {
5477 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVLPG))
5478 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5479 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5480 }
5481
5482 case SVM_EXIT_WBINVD:
5483 {
5484 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_WBINVD))
5485 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5486 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5487 }
5488
5489 case SVM_EXIT_INVD:
5490 {
5491 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVD))
5492 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5493 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5494 }
5495
5496 case SVM_EXIT_RDPMC:
5497 {
5498 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDPMC))
5499 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5500 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5501 }
5502
5503 default:
5504 {
5505 switch (uExitCode)
5506 {
5507 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5508 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5509 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5510 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5511 {
5512 uint8_t const uDr = uExitCode - SVM_EXIT_READ_DR0;
5513 if (HMIsGuestSvmReadDRxInterceptSet(pVCpu, uDr))
5514 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5515 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5516 }
5517
5518 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5519 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5520 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5521 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5522 {
5523 uint8_t const uDr = uExitCode - SVM_EXIT_WRITE_DR0;
5524 if (HMIsGuestSvmWriteDRxInterceptSet(pVCpu, uDr))
5525 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5526 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5527 }
5528
5529 case SVM_EXIT_XCPT_0: /* #DE */
5530 /* SVM_EXIT_XCPT_1: */ /* #DB - Handled above. */
5531 /* SVM_EXIT_XCPT_2: */ /* #NMI - Handled above. */
5532 /* SVM_EXIT_XCPT_3: */ /* #BP - Handled above. */
5533 case SVM_EXIT_XCPT_4: /* #OF */
5534 case SVM_EXIT_XCPT_5: /* #BR */
5535 /* SVM_EXIT_XCPT_6: */ /* #UD - Handled above. */
5536 case SVM_EXIT_XCPT_7: /* #NM */
5537 case SVM_EXIT_XCPT_8: /* #DF */
5538 case SVM_EXIT_XCPT_9: /* #CO_SEG_OVERRUN */
5539 case SVM_EXIT_XCPT_10: /* #TS */
5540 case SVM_EXIT_XCPT_11: /* #NP */
5541 case SVM_EXIT_XCPT_12: /* #SS */
5542 case SVM_EXIT_XCPT_13: /* #GP */
5543 /* SVM_EXIT_XCPT_14: */ /* #PF - Handled above. */
5544 case SVM_EXIT_XCPT_15: /* Reserved. */
5545 /* SVM_EXIT_XCPT_16: */ /* #MF - Handled above. */
5546 /* SVM_EXIT_XCPT_17: */ /* #AC - Handled above. */
5547 case SVM_EXIT_XCPT_18: /* #MC */
5548 case SVM_EXIT_XCPT_19: /* #XF */
5549 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5550 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5551 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5552 {
5553 uint8_t const uVector = uExitCode - SVM_EXIT_XCPT_0;
5554 if (HMIsGuestSvmXcptInterceptSet(pVCpu, uVector))
5555 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5556 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5557 }
5558
5559 case SVM_EXIT_XSETBV:
5560 {
5561 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_XSETBV))
5562 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5563 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5564 }
5565
5566 case SVM_EXIT_TASK_SWITCH:
5567 {
5568 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_TASK_SWITCH))
5569 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5570 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5571 }
5572
5573 case SVM_EXIT_IRET:
5574 {
5575 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_IRET))
5576 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5577 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5578 }
5579
5580 case SVM_EXIT_SHUTDOWN:
5581 {
5582 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_SHUTDOWN))
5583 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5584 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5585 }
5586
5587 case SVM_EXIT_VMMCALL:
5588 {
5589 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMMCALL))
5590 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5591 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5592 }
5593
5594 case SVM_EXIT_CLGI:
5595 {
5596 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CLGI))
5597 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5598 return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5599 }
5600
5601 case SVM_EXIT_STGI:
5602 {
5603 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_STGI))
5604 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5605 return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5606 }
5607
5608 case SVM_EXIT_VMLOAD:
5609 {
5610 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMLOAD))
5611 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5612 return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5613 }
5614
5615 case SVM_EXIT_VMSAVE:
5616 {
5617 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMSAVE))
5618 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5619 return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5620 }
5621
5622 case SVM_EXIT_INVLPGA:
5623 {
5624 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVLPGA))
5625 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5626 return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5627 }
5628
5629 case SVM_EXIT_VMRUN:
5630 {
5631 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMRUN))
5632 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5633 return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5634 }
5635
5636 case SVM_EXIT_RSM:
5637 {
5638 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RSM))
5639 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5640 hmR0SvmSetPendingXcptUD(pVCpu);
5641 return VINF_SUCCESS;
5642 }
5643
5644 case SVM_EXIT_SKINIT:
5645 {
5646 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_SKINIT))
5647 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5648 hmR0SvmSetPendingXcptUD(pVCpu);
5649 return VINF_SUCCESS;
5650 }
5651
5652 case SVM_EXIT_NPF:
5653 {
5654 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5655 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
5656 }
5657
5658 case SVM_EXIT_INIT: /* We shouldn't get INIT signals while executing a nested-guest. */
5659 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5660
5661 default:
5662 {
5663 AssertMsgFailed(("hmR0SvmHandleExitNested: Unknown exit code %#x\n", pSvmTransient->u64ExitCode));
5664 pVCpu->hm.s.u32HMError = pSvmTransient->u64ExitCode;
5665 return VERR_SVM_UNKNOWN_EXIT;
5666 }
5667 }
5668 }
5669 }
5670 /* not reached */
5671
5672#undef NST_GST_VMEXIT_CALL_RET
5673}
5674#endif
5675
5676
5677/**
5678 * Handles a guest \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
5679 *
5680 * @returns VBox status code (informational status codes included).
5681 * @param pVCpu The cross context virtual CPU structure.
5682 * @param pCtx Pointer to the guest-CPU context.
5683 * @param pSvmTransient Pointer to the SVM transient structure.
5684 */
5685static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5686{
5687 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5688 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5689
5690#ifdef DEBUG_ramshankar
5691# define VMEXIT_CALL_RET(a_fDbg, a_CallExpr) \
5692 do { \
5693 if ((a_fDbg) == 1) \
5694 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL); \
5695 int rc = a_CallExpr; \
5696 /* if ((a_fDbg) == 1) */ \
5697 /* HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST); */ \
5698 return rc; \
5699 } while (0)
5700#else
5701# define VMEXIT_CALL_RET(a_fDbg, a_CallExpr) return a_CallExpr
5702#endif
5703
5704 /*
5705 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs
5706 * for most guests under normal workloads (for some definition of "normal").
5707 */
5708 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
5709 switch (uExitCode)
5710 {
5711 case SVM_EXIT_NPF: VMEXIT_CALL_RET(0, hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient));
5712 case SVM_EXIT_IOIO: VMEXIT_CALL_RET(0, hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient));
5713 case SVM_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient));
5714 case SVM_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient));
5715 case SVM_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient));
5716 case SVM_EXIT_XCPT_PF: VMEXIT_CALL_RET(0, hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient));
5717 case SVM_EXIT_MSR: VMEXIT_CALL_RET(0, hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient));
5718 case SVM_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient));
5719 case SVM_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient));
5720 case SVM_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient));
5721
5722 case SVM_EXIT_XCPT_NMI: /* Should not occur, SVM_EXIT_NMI is used instead. */
5723 case SVM_EXIT_INTR:
5724 case SVM_EXIT_NMI: VMEXIT_CALL_RET(0, hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient));
5725
5726 case SVM_EXIT_READ_CR0:
5727 case SVM_EXIT_READ_CR3:
5728 case SVM_EXIT_READ_CR4: VMEXIT_CALL_RET(0, hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient));
5729
5730 case SVM_EXIT_CR0_SEL_WRITE:
5731 case SVM_EXIT_WRITE_CR0:
5732 case SVM_EXIT_WRITE_CR3:
5733 case SVM_EXIT_WRITE_CR4:
5734 case SVM_EXIT_WRITE_CR8: VMEXIT_CALL_RET(0, hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient));
5735
5736 case SVM_EXIT_VINTR: VMEXIT_CALL_RET(0, hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient));
5737 case SVM_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient));
5738 case SVM_EXIT_VMMCALL: VMEXIT_CALL_RET(0, hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient));
5739 case SVM_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient));
5740 case SVM_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient));
5741 case SVM_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient));
5742 case SVM_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient));
5743 case SVM_EXIT_IRET: VMEXIT_CALL_RET(0, hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient));
5744 case SVM_EXIT_XCPT_UD: VMEXIT_CALL_RET(0, hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient));
5745 case SVM_EXIT_XCPT_MF: VMEXIT_CALL_RET(0, hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient));
5746 case SVM_EXIT_XCPT_DB: VMEXIT_CALL_RET(0, hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient));
5747 case SVM_EXIT_XCPT_AC: VMEXIT_CALL_RET(0, hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient));
5748 case SVM_EXIT_XCPT_BP: VMEXIT_CALL_RET(0, hmR0SvmExitXcptBP(pVCpu, pCtx, pSvmTransient));
5749 case SVM_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient));
5750 case SVM_EXIT_FERR_FREEZE: VMEXIT_CALL_RET(0, hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient));
5751
5752 default:
5753 {
5754 switch (pSvmTransient->u64ExitCode)
5755 {
5756 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5757 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5758 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5759 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5760 VMEXIT_CALL_RET(0, hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient));
5761
5762 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5763 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5764 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5765 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5766 VMEXIT_CALL_RET(0, hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient));
5767
5768 case SVM_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient));
5769 case SVM_EXIT_SHUTDOWN: VMEXIT_CALL_RET(0, hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient));
5770
5771 case SVM_EXIT_SMI:
5772 case SVM_EXIT_INIT:
5773 {
5774 /*
5775 * We don't intercept SMIs. As for INIT signals, it really shouldn't ever happen here.
5776 * If it ever does, we want to know about it so log the exit code and bail.
5777 */
5778 VMEXIT_CALL_RET(0, hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient));
5779 }
5780
5781#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5782 case SVM_EXIT_CLGI: VMEXIT_CALL_RET(0, hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient));
5783 case SVM_EXIT_STGI: VMEXIT_CALL_RET(0, hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient));
5784 case SVM_EXIT_VMLOAD: VMEXIT_CALL_RET(0, hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient));
5785 case SVM_EXIT_VMSAVE: VMEXIT_CALL_RET(0, hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient));
5786 case SVM_EXIT_INVLPGA: VMEXIT_CALL_RET(0, hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient));
5787 case SVM_EXIT_VMRUN: VMEXIT_CALL_RET(0, hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient));
5788#else
5789 case SVM_EXIT_CLGI:
5790 case SVM_EXIT_STGI:
5791 case SVM_EXIT_VMLOAD:
5792 case SVM_EXIT_VMSAVE:
5793 case SVM_EXIT_INVLPGA:
5794 case SVM_EXIT_VMRUN:
5795#endif
5796 case SVM_EXIT_RSM:
5797 case SVM_EXIT_SKINIT:
5798 {
5799 hmR0SvmSetPendingXcptUD(pVCpu);
5800 return VINF_SUCCESS;
5801 }
5802
5803#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5804 case SVM_EXIT_XCPT_DE:
5805 /* SVM_EXIT_XCPT_DB: */ /* Handled above. */
5806 /* SVM_EXIT_XCPT_NMI: */ /* Handled above. */
5807 /* SVM_EXIT_XCPT_BP: */ /* Handled above. */
5808 case SVM_EXIT_XCPT_OF:
5809 case SVM_EXIT_XCPT_BR:
5810 /* SVM_EXIT_XCPT_UD: */ /* Handled above. */
5811 case SVM_EXIT_XCPT_NM:
5812 case SVM_EXIT_XCPT_DF:
5813 case SVM_EXIT_XCPT_CO_SEG_OVERRUN:
5814 case SVM_EXIT_XCPT_TS:
5815 case SVM_EXIT_XCPT_NP:
5816 case SVM_EXIT_XCPT_SS:
5817 case SVM_EXIT_XCPT_GP:
5818 /* SVM_EXIT_XCPT_PF: */
5819 case SVM_EXIT_XCPT_15: /* Reserved. */
5820 /* SVM_EXIT_XCPT_MF: */ /* Handled above. */
5821 /* SVM_EXIT_XCPT_AC: */ /* Handled above. */
5822 case SVM_EXIT_XCPT_MC:
5823 case SVM_EXIT_XCPT_XF:
5824 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5825 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5826 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5827 VMEXIT_CALL_RET(0, hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient));
5828#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
5829
5830 default:
5831 {
5832 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#RX64\n", uExitCode));
5833 pVCpu->hm.s.u32HMError = uExitCode;
5834 return VERR_SVM_UNKNOWN_EXIT;
5835 }
5836 }
5837 }
5838 }
5839 /* not reached */
5840#undef VMEXIT_CALL_RET
5841}
5842
5843
5844#ifdef DEBUG
5845/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
5846# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
5847 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
5848
5849# define HMSVM_ASSERT_PREEMPT_CPUID() \
5850 do \
5851 { \
5852 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
5853 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
5854 } while (0)
5855
5856# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
5857 do { \
5858 AssertPtr(pVCpu); \
5859 AssertPtr(pCtx); \
5860 AssertPtr(pSvmTransient); \
5861 Assert(ASMIntAreEnabled()); \
5862 HMSVM_ASSERT_PREEMPT_SAFE(); \
5863 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
5864 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)); \
5865 HMSVM_ASSERT_PREEMPT_SAFE(); \
5866 if (VMMR0IsLogFlushDisabled(pVCpu)) \
5867 HMSVM_ASSERT_PREEMPT_CPUID(); \
5868 } while (0)
5869#else /* Release builds */
5870# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
5871#endif
5872
5873
5874/**
5875 * Worker for hmR0SvmInterpretInvlpg().
5876 *
5877 * @return VBox status code.
5878 * @param pVCpu The cross context virtual CPU structure.
5879 * @param pCpu Pointer to the disassembler state.
5880 * @param pCtx The guest CPU context.
5881 */
5882static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
5883{
5884 DISQPVPARAMVAL Param1;
5885 RTGCPTR GCPtrPage;
5886
5887 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
5888 if (RT_FAILURE(rc))
5889 return VERR_EM_INTERPRETER;
5890
5891 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
5892 || Param1.type == DISQPV_TYPE_ADDRESS)
5893 {
5894 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
5895 return VERR_EM_INTERPRETER;
5896
5897 GCPtrPage = Param1.val.val64;
5898 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
5899 rc = VBOXSTRICTRC_VAL(rc2);
5900 }
5901 else
5902 {
5903 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
5904 rc = VERR_EM_INTERPRETER;
5905 }
5906
5907 return rc;
5908}
5909
5910
5911/**
5912 * Interprets INVLPG.
5913 *
5914 * @returns VBox status code.
5915 * @retval VINF_* Scheduling instructions.
5916 * @retval VERR_EM_INTERPRETER Something we can't cope with.
5917 * @retval VERR_* Fatal errors.
5918 *
5919 * @param pVM The cross context VM structure.
5920 * @param pVCpu The cross context virtual CPU structure.
5921 * @param pCtx The guest CPU context.
5922 *
5923 * @remarks Updates the RIP if the instruction was executed successfully.
5924 */
5925static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5926{
5927 /* Only allow 32 & 64 bit code. */
5928 if (CPUMGetGuestCodeBits(pVCpu) != 16)
5929 {
5930 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5931 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
5932 if ( RT_SUCCESS(rc)
5933 && pDis->pCurInstr->uOpcode == OP_INVLPG)
5934 {
5935 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
5936 if (RT_SUCCESS(rc))
5937 pCtx->rip += pDis->cbInstr;
5938 return rc;
5939 }
5940 else
5941 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5942 }
5943 return VERR_EM_INTERPRETER;
5944}
5945
5946
5947#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
5948/**
5949 * Gets the IEM exception flags for the specified SVM event.
5950 *
5951 * @returns The IEM exception flags.
5952 * @param pEvent Pointer to the SVM event.
5953 *
5954 * @remarks This function currently only constructs flags required for
5955 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g. error-code
5956 * and CR2 aspects of an exception are not included).
5957 */
5958static uint32_t hmR0SvmGetIemXcptFlags(PCSVMEVENT pEvent)
5959{
5960 uint8_t const uEventType = pEvent->n.u3Type;
5961 uint32_t fIemXcptFlags;
5962 switch (uEventType)
5963 {
5964 case SVM_EVENT_EXCEPTION:
5965 /*
5966 * Only INT3 and INTO instructions can raise #BP and #OF exceptions.
5967 * See AMD spec. Table 8-1. "Interrupt Vector Source and Cause".
5968 */
5969 if (pEvent->n.u8Vector == X86_XCPT_BP)
5970 {
5971 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_BP_INSTR;
5972 break;
5973 }
5974 if (pEvent->n.u8Vector == X86_XCPT_OF)
5975 {
5976 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_OF_INSTR;
5977 break;
5978 }
5979 /** @todo How do we distinguish ICEBP \#DB from the regular one? */
5980 RT_FALL_THRU();
5981 case SVM_EVENT_NMI:
5982 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
5983 break;
5984
5985 case SVM_EVENT_EXTERNAL_IRQ:
5986 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
5987 break;
5988
5989 case SVM_EVENT_SOFTWARE_INT:
5990 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
5991 break;
5992
5993 default:
5994 fIemXcptFlags = 0;
5995 AssertMsgFailed(("Unexpected event type! uEventType=%#x uVector=%#x", uEventType, pEvent->n.u8Vector));
5996 break;
5997 }
5998 return fIemXcptFlags;
5999}
6000
6001#else
6002/**
6003 * Determines if an exception is a contributory exception.
6004 *
6005 * Contributory exceptions are ones which can cause double-faults unless the
6006 * original exception was a benign exception. Page-fault is intentionally not
6007 * included here as it's a conditional contributory exception.
6008 *
6009 * @returns @c true if the exception is contributory, @c false otherwise.
6010 * @param uVector The exception vector.
6011 */
6012DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
6013{
6014 switch (uVector)
6015 {
6016 case X86_XCPT_GP:
6017 case X86_XCPT_SS:
6018 case X86_XCPT_NP:
6019 case X86_XCPT_TS:
6020 case X86_XCPT_DE:
6021 return true;
6022 default:
6023 break;
6024 }
6025 return false;
6026}
6027#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
6028
6029
6030/**
6031 * Handle a condition that occurred while delivering an event through the guest
6032 * IDT.
6033 *
6034 * @returns VBox status code (informational error codes included).
6035 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
6036 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
6037 * continue execution of the guest which will delivery the \#DF.
6038 * @retval VINF_EM_RESET if we detected a triple-fault condition.
6039 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
6040 *
6041 * @param pVCpu The cross context virtual CPU structure.
6042 * @param pCtx Pointer to the guest-CPU context.
6043 * @param pSvmTransient Pointer to the SVM transient structure.
6044 *
6045 * @remarks No-long-jump zone!!!
6046 */
6047static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6048{
6049 int rc = VINF_SUCCESS;
6050 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6051 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR2);
6052
6053 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
6054 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
6055 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
6056
6057 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
6058 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
6059 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
6060 {
6061#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
6062 IEMXCPTRAISE enmRaise;
6063 IEMXCPTRAISEINFO fRaiseInfo;
6064 bool const fExitIsHwXcpt = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31;
6065 uint8_t const uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
6066 if (fExitIsHwXcpt)
6067 {
6068 uint8_t const uExitVector = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0;
6069 uint32_t const fIdtVectorFlags = hmR0SvmGetIemXcptFlags(&pVmcb->ctrl.ExitIntInfo);
6070 uint32_t const fExitVectorFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6071 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
6072 }
6073 else
6074 {
6075 /*
6076 * If delivery of an event caused a #VMEXIT that is not an exception (e.g. #NPF) then we
6077 * end up here.
6078 *
6079 * If the event was:
6080 * - a software interrupt, we can re-execute the instruction which will regenerate
6081 * the event.
6082 * - an NMI, we need to clear NMI blocking and re-inject the NMI.
6083 * - a hardware exception or external interrupt, we re-inject it.
6084 */
6085 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
6086 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_SOFTWARE_INT)
6087 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
6088 else
6089 enmRaise = IEMXCPTRAISE_PREV_EVENT;
6090 }
6091
6092 switch (enmRaise)
6093 {
6094 case IEMXCPTRAISE_CURRENT_XCPT:
6095 case IEMXCPTRAISE_PREV_EVENT:
6096 {
6097 /* For software interrupts, we shall re-execute the instruction. */
6098 if (!(fRaiseInfo & IEMXCPTRAISEINFO_SOFT_INT_XCPT))
6099 {
6100 RTGCUINTPTR GCPtrFaultAddress = 0;
6101
6102 /* If we are re-injecting an NMI, clear NMI blocking. */
6103 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6104 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6105
6106 /* Determine a vectoring #PF condition, see comment in hmR0SvmExitXcptPF(). */
6107 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
6108 {
6109 pSvmTransient->fVectoringPF = true;
6110 Log4(("IDT: Pending vectoring #PF due to delivery of Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6111 }
6112 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION
6113 && uIdtVector == X86_XCPT_PF)
6114 {
6115 /*
6116 * If the previous exception was a #PF, we need to recover the CR2 value.
6117 * This can't happen with shadow paging.
6118 */
6119 GCPtrFaultAddress = pCtx->cr2;
6120 }
6121
6122 /*
6123 * Without nested paging, when uExitVector is #PF, CR2 value will be updated from the VMCB's
6124 * exit info. fields, if it's a guest #PF, see hmR0SvmExitXcptPF().
6125 */
6126 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6127 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6128 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, GCPtrFaultAddress);
6129
6130 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32 GCPtrFaultAddress=%#RX64\n",
6131 pVmcb->ctrl.ExitIntInfo.u, RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid),
6132 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, GCPtrFaultAddress));
6133 }
6134 break;
6135 }
6136
6137 case IEMXCPTRAISE_REEXEC_INSTR:
6138 {
6139 Assert(rc == VINF_SUCCESS);
6140 break;
6141 }
6142
6143 case IEMXCPTRAISE_DOUBLE_FAULT:
6144 {
6145 /*
6146 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
6147 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
6148 */
6149 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
6150 {
6151 Log4(("IDT: Pending vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
6152 pSvmTransient->fVectoringDoublePF = true;
6153 Assert(rc == VINF_SUCCESS);
6154 }
6155 else
6156 {
6157 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6158 hmR0SvmSetPendingXcptDF(pVCpu);
6159 rc = VINF_HM_DOUBLE_FAULT;
6160 }
6161 break;
6162 }
6163
6164 case IEMXCPTRAISE_TRIPLE_FAULT:
6165 {
6166 rc = VINF_EM_RESET;
6167 break;
6168 }
6169
6170 case IEMXCPTRAISE_CPU_HANG:
6171 {
6172 rc = VERR_EM_GUEST_CPU_HANG;
6173 break;
6174 }
6175
6176 default:
6177 {
6178 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
6179 rc = VERR_SVM_IPE_2;
6180 break;
6181 }
6182 }
6183#else
6184 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
6185
6186 typedef enum
6187 {
6188 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
6189 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
6190 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
6191 SVMREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
6192 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
6193 } SVMREFLECTXCPT;
6194
6195 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
6196 bool fReflectingNmi = false;
6197 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
6198 {
6199 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6200 {
6201 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6202
6203#ifdef VBOX_STRICT
6204 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
6205 && uExitVector == X86_XCPT_PF)
6206 {
6207 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
6208 }
6209#endif
6210
6211 if ( uIdtVector == X86_XCPT_BP
6212 || uIdtVector == X86_XCPT_OF)
6213 {
6214 /* Ignore INT3/INTO, just re-execute. See @bugref{8357}. */
6215 }
6216 else if ( uExitVector == X86_XCPT_PF
6217 && uIdtVector == X86_XCPT_PF)
6218 {
6219 pSvmTransient->fVectoringDoublePF = true;
6220 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
6221 }
6222 else if ( uExitVector == X86_XCPT_AC
6223 && uIdtVector == X86_XCPT_AC)
6224 {
6225 enmReflect = SVMREFLECTXCPT_HANG;
6226 Log4(("IDT: Nested #AC - Bad guest\n"));
6227 }
6228 else if ( (pVmcb->ctrl.u32InterceptXcpt & HMSVM_CONTRIBUTORY_XCPT_MASK)
6229 && hmR0SvmIsContributoryXcpt(uExitVector)
6230 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
6231 || uIdtVector == X86_XCPT_PF))
6232 {
6233 enmReflect = SVMREFLECTXCPT_DF;
6234 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
6235 uIdtVector, uExitVector));
6236 }
6237 else if (uIdtVector == X86_XCPT_DF)
6238 {
6239 enmReflect = SVMREFLECTXCPT_TF;
6240 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
6241 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
6242 }
6243 else
6244 enmReflect = SVMREFLECTXCPT_XCPT;
6245 }
6246 else
6247 {
6248 /*
6249 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
6250 * exception to the guest after handling the #VMEXIT.
6251 */
6252 enmReflect = SVMREFLECTXCPT_XCPT;
6253 }
6254 }
6255 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
6256 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6257 {
6258 enmReflect = SVMREFLECTXCPT_XCPT;
6259 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
6260
6261 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6262 {
6263 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6264 if (uExitVector == X86_XCPT_PF)
6265 {
6266 pSvmTransient->fVectoringPF = true;
6267 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6268 }
6269 }
6270 }
6271 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
6272
6273 switch (enmReflect)
6274 {
6275 case SVMREFLECTXCPT_XCPT:
6276 {
6277 /* If we are re-injecting the NMI, clear NMI blocking. */
6278 if (fReflectingNmi)
6279 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6280
6281 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6282 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6283 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
6284
6285 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
6286 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
6287 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
6288 break;
6289 }
6290
6291 case SVMREFLECTXCPT_DF:
6292 {
6293 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6294 hmR0SvmSetPendingXcptDF(pVCpu);
6295 rc = VINF_HM_DOUBLE_FAULT;
6296 break;
6297 }
6298
6299 case SVMREFLECTXCPT_TF:
6300 {
6301 rc = VINF_EM_RESET;
6302 break;
6303 }
6304
6305 case SVMREFLECTXCPT_HANG:
6306 {
6307 rc = VERR_EM_GUEST_CPU_HANG;
6308 break;
6309 }
6310
6311 default:
6312 Assert(rc == VINF_SUCCESS);
6313 break;
6314 }
6315#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
6316 }
6317 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
6318 NOREF(pCtx);
6319 return rc;
6320}
6321
6322
6323/**
6324 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
6325 * supported, otherwise advances the RIP by the number of bytes specified in
6326 * @a cb.
6327 *
6328 * @param pVCpu The cross context virtual CPU structure.
6329 * @param pCtx Pointer to the guest-CPU context.
6330 * @param cb RIP increment value in bytes.
6331 *
6332 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
6333 * when NRIP_SAVE is supported by the CPU, otherwise use
6334 * hmR0SvmAdvanceRipDumb!
6335 */
6336DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6337{
6338 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6339 if (fSupportsNextRipSave)
6340 {
6341 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6342 Assert(pVmcb);
6343 Assert(pVmcb->ctrl.u64NextRIP);
6344 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
6345 AssertRelease(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb); /* temporary, remove later */
6346 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6347 }
6348 else
6349 pCtx->rip += cb;
6350
6351 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6352}
6353
6354
6355/**
6356 * Gets the length of the current instruction if the CPU supports the NRIP_SAVE
6357 * feature. Otherwise, returns the value in @a cbLikely.
6358 *
6359 * @param pVCpu The cross context virtual CPU structure.
6360 * @param pCtx Pointer to the guest-CPU context.
6361 * @param cbLikely The likely instruction length.
6362 */
6363DECLINLINE(uint8_t) hmR0SvmGetInstrLengthHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint8_t cbLikely)
6364{
6365 Assert(cbLikely <= 15); /* See Intel spec. 2.3.11 "AVX Instruction Length" */
6366 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6367 if (fSupportsNextRipSave)
6368 {
6369 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6370 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6371 Assert(cbInstr == cbLikely);
6372 return cbInstr;
6373 }
6374 return cbLikely;
6375}
6376
6377
6378/**
6379 * Advances the guest RIP by the number of bytes specified in @a cb. This does
6380 * not make use of any hardware features to determine the instruction length.
6381 *
6382 * @param pVCpu The cross context virtual CPU structure.
6383 * @param pCtx Pointer to the guest-CPU context.
6384 * @param cb RIP increment value in bytes.
6385 */
6386DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6387{
6388 pCtx->rip += cb;
6389 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6390}
6391#undef HMSVM_UPDATE_INTR_SHADOW
6392
6393
6394/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6395/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6396/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6397
6398/** @name \#VMEXIT handlers.
6399 * @{
6400 */
6401
6402/**
6403 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
6404 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
6405 */
6406HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6407{
6408 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6409
6410 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
6411 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
6412 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
6413 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
6414
6415 /*
6416 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
6417 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
6418 * interrupt it is until the host actually take the interrupt.
6419 *
6420 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
6421 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
6422 */
6423 return VINF_EM_RAW_INTERRUPT;
6424}
6425
6426
6427/**
6428 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
6429 */
6430HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6431{
6432 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6433
6434 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6435 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
6436 int rc = VINF_SUCCESS;
6437 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6438 return rc;
6439}
6440
6441
6442/**
6443 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
6444 */
6445HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6446{
6447 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6448
6449 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6450 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
6451 int rc = VINF_SUCCESS;
6452 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6453 return rc;
6454}
6455
6456
6457/**
6458 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
6459 */
6460HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6461{
6462 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6463
6464 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS);
6465 VBOXSTRICTRC rcStrict;
6466 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
6467 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
6468 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
6469 if (!pExitRec)
6470 {
6471 PVM pVM = pVCpu->CTX_SUFF(pVM);
6472 rcStrict = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6473 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
6474 {
6475 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6476 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6477 }
6478 else
6479 {
6480 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
6481 rcStrict = VERR_EM_INTERPRETER;
6482 }
6483 }
6484 else
6485 {
6486 /*
6487 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
6488 */
6489 Assert(pCtx == &pVCpu->cpum.GstCtx);
6490 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6491
6492 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
6493 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
6494
6495 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
6496
6497 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
6498 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
6499 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
6500 }
6501 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
6502 return VBOXSTRICTRC_TODO(rcStrict);
6503}
6504
6505
6506/**
6507 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
6508 */
6509HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6510{
6511 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6512 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6513 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 2));
6514 if (rcStrict == VINF_SUCCESS)
6515 pSvmTransient->fUpdateTscOffsetting = true;
6516 else if (rcStrict == VINF_IEM_RAISED_XCPT)
6517 rcStrict = VINF_SUCCESS;
6518 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6519 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
6520 return VBOXSTRICTRC_TODO(rcStrict);
6521}
6522
6523
6524/**
6525 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
6526 */
6527HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6528{
6529 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6530 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3));
6531 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6532 if (rcStrict == VINF_SUCCESS)
6533 pSvmTransient->fUpdateTscOffsetting = true;
6534 else if (rcStrict == VINF_IEM_RAISED_XCPT)
6535 rcStrict = VINF_SUCCESS;
6536 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6537 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
6538 return VBOXSTRICTRC_TODO(rcStrict);
6539}
6540
6541
6542/**
6543 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
6544 */
6545HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6546{
6547 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6548 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6549 | CPUMCTX_EXTRN_CR4
6550 | CPUMCTX_EXTRN_SS);
6551
6552 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6553 if (RT_LIKELY(rc == VINF_SUCCESS))
6554 {
6555 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6556 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6557 }
6558 else
6559 {
6560 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
6561 rc = VERR_EM_INTERPRETER;
6562 }
6563 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
6564 return rc;
6565}
6566
6567
6568/**
6569 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
6570 */
6571HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6572{
6573 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6574 PVM pVM = pVCpu->CTX_SUFF(pVM);
6575 Assert(!pVM->hm.s.fNestedPaging);
6576 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
6577
6578 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6579 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6580 if ( fSupportsDecodeAssists
6581 && fSupportsNextRipSave)
6582 {
6583 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6584 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6585 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6586 RTGCPTR const GCPtrPage = pVmcb->ctrl.u64ExitInfo1;
6587 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, cbInstr, GCPtrPage);
6588 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6589 return VBOXSTRICTRC_VAL(rcStrict);
6590 }
6591
6592 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6593 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
6594 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
6595 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6596 return rc;
6597}
6598
6599
6600/**
6601 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
6602 */
6603HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6604{
6605 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6606
6607 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
6608 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
6609 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6610 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
6611 if (rc != VINF_SUCCESS)
6612 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
6613 return rc;
6614}
6615
6616
6617/**
6618 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
6619 */
6620HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6621{
6622 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6623 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6624 | CPUMCTX_EXTRN_SS);
6625
6626 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6627 if (RT_LIKELY(rc == VINF_SUCCESS))
6628 {
6629 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6630 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6631 }
6632 else
6633 {
6634 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
6635 rc = VERR_EM_INTERPRETER;
6636 }
6637 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
6638 return rc;
6639}
6640
6641
6642/**
6643 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
6644 */
6645HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6646{
6647 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6648 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6649 | CPUMCTX_EXTRN_SS);
6650
6651 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6652 int rc = VBOXSTRICTRC_VAL(rc2);
6653 if ( rc == VINF_EM_HALT
6654 || rc == VINF_SUCCESS)
6655 {
6656 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6657
6658 if ( rc == VINF_EM_HALT
6659 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
6660 {
6661 rc = VINF_SUCCESS;
6662 }
6663 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6664 }
6665 else
6666 {
6667 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
6668 rc = VERR_EM_INTERPRETER;
6669 }
6670 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
6671 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
6672 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
6673 return rc;
6674}
6675
6676
6677/**
6678 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
6679 * \#VMEXIT.
6680 */
6681HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6682{
6683 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6684 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6685 return VINF_EM_RESET;
6686}
6687
6688
6689/**
6690 * \#VMEXIT handler for unexpected exits. Conditional \#VMEXIT.
6691 */
6692HMSVM_EXIT_DECL hmR0SvmExitUnexpected(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6693{
6694 RT_NOREF(pCtx);
6695 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6696 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6697 AssertMsgFailed(("hmR0SvmExitUnexpected: ExitCode=%#RX64 uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", pSvmTransient->u64ExitCode,
6698 pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2));
6699 RT_NOREF(pVmcb);
6700 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6701 return VERR_SVM_UNEXPECTED_EXIT;
6702}
6703
6704
6705/**
6706 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
6707 */
6708HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6709{
6710 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6711
6712 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6713 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
6714
6715 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6716 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6717 if ( fSupportsDecodeAssists
6718 && fSupportsNextRipSave)
6719 {
6720 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6721 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6722 if (fMovCRx)
6723 {
6724 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6725 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6726 uint8_t const iCrReg = pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0;
6727 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6728 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
6729 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6730 return VBOXSTRICTRC_VAL(rcStrict);
6731 }
6732 /* else: SMSW instruction, fall back below to IEM for this. */
6733 }
6734
6735 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6736 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6737 int rc = VBOXSTRICTRC_VAL(rc2);
6738 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
6739 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
6740 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
6741 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6742 return rc;
6743}
6744
6745
6746/**
6747 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
6748 */
6749HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6750{
6751 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6752
6753 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
6754 uint8_t const iCrReg = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0);
6755 Assert(iCrReg <= 15);
6756
6757 VBOXSTRICTRC rcStrict = VERR_SVM_IPE_5;
6758 bool fDecodedInstr = false;
6759 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6760 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6761 if ( fSupportsDecodeAssists
6762 && fSupportsNextRipSave)
6763 {
6764 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6765 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6766 if (fMovCRx)
6767 {
6768 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6769 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6770 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6771 Log4(("hmR0SvmExitWriteCRx: Mov CR%u w/ iGReg=%#x\n", iCrReg, iGReg));
6772 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
6773 fDecodedInstr = true;
6774 }
6775 /* else: LMSW or CLTS instruction, fall back below to IEM for this. */
6776 }
6777
6778 if (!fDecodedInstr)
6779 {
6780 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6781 Log4(("hmR0SvmExitWriteCRx: iCrReg=%#x\n", iCrReg));
6782 rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
6783 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
6784 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
6785 rcStrict = VERR_EM_INTERPRETER;
6786 }
6787
6788 if (rcStrict == VINF_SUCCESS)
6789 {
6790 switch (iCrReg)
6791 {
6792 case 0: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0); break;
6793 case 2: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2); break;
6794 case 3: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3); break;
6795 case 4: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4); break;
6796 case 8: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE); break;
6797 default:
6798 {
6799 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
6800 pSvmTransient->u64ExitCode, iCrReg));
6801 break;
6802 }
6803 }
6804 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6805 }
6806 else
6807 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
6808 return VBOXSTRICTRC_TODO(rcStrict);
6809}
6810
6811
6812/**
6813 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
6814 * \#VMEXIT.
6815 */
6816HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6817{
6818 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6819 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6820 | CPUMCTX_EXTRN_RFLAGS
6821 | CPUMCTX_EXTRN_SS
6822 | CPUMCTX_EXTRN_ALL_MSRS);
6823
6824 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6825 PVM pVM = pVCpu->CTX_SUFF(pVM);
6826
6827 int rc;
6828 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
6829 {
6830 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
6831 Log4(("MSR Write: idMsr=%#RX32\n", pCtx->ecx));
6832
6833 /* Handle TPR patching; intercepted LSTAR write. */
6834 if ( pVM->hm.s.fTPRPatchingActive
6835 && pCtx->ecx == MSR_K8_LSTAR)
6836 {
6837 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
6838 {
6839 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
6840 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
6841 AssertRC(rc2);
6842 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6843 }
6844 rc = VINF_SUCCESS;
6845 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6846 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6847 return rc;
6848 }
6849
6850 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6851 if (fSupportsNextRipSave)
6852 {
6853 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6854 if (RT_LIKELY(rc == VINF_SUCCESS))
6855 {
6856 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6857 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6858 }
6859 else
6860 AssertMsg( rc == VERR_EM_INTERPRETER
6861 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
6862 }
6863 else
6864 {
6865 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6866 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
6867 if (RT_LIKELY(rc == VINF_SUCCESS))
6868 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
6869 else
6870 AssertMsg( rc == VERR_EM_INTERPRETER
6871 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6872 }
6873
6874 if (rc == VINF_SUCCESS)
6875 {
6876 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
6877 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
6878 && pCtx->ecx <= MSR_IA32_X2APIC_END)
6879 {
6880 /*
6881 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
6882 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
6883 * EMInterpretWrmsr() changes it.
6884 */
6885 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6886 }
6887 else
6888 {
6889 switch (pCtx->ecx)
6890 {
6891 case MSR_K6_EFER: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR); break;
6892 case MSR_IA32_TSC: pSvmTransient->fUpdateTscOffsetting = true; break;
6893 case MSR_K8_FS_BASE:
6894 case MSR_K8_GS_BASE: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS); break;
6895 case MSR_IA32_SYSENTER_CS: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
6896 case MSR_IA32_SYSENTER_EIP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
6897 case MSR_IA32_SYSENTER_ESP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
6898 }
6899 }
6900 }
6901 }
6902 else
6903 {
6904 /* MSR Read access. */
6905 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
6906 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
6907 Log4(("MSR Read: idMsr=%#RX32\n", pCtx->ecx));
6908
6909 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6910 if (fSupportsNextRipSave)
6911 {
6912 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6913 if (RT_LIKELY(rc == VINF_SUCCESS))
6914 {
6915 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6916 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6917 }
6918 else
6919 AssertMsg( rc == VERR_EM_INTERPRETER
6920 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
6921 }
6922 else
6923 {
6924 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6925 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
6926 if (RT_UNLIKELY(rc != VINF_SUCCESS))
6927 {
6928 AssertMsg( rc == VERR_EM_INTERPRETER
6929 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6930 }
6931 /* RIP updated by EMInterpretInstruction(). */
6932 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6933 }
6934 }
6935
6936 /* RIP has been updated by EMInterpret[Rd|Wr]msr() or EMInterpretInstruction(). */
6937 return rc;
6938}
6939
6940
6941/**
6942 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
6943 */
6944HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6945{
6946 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6947 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6948
6949 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
6950
6951 /** @todo Stepping with nested-guest. */
6952 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
6953 {
6954 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
6955 if (pSvmTransient->fWasGuestDebugStateActive)
6956 {
6957 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
6958 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6959 return VERR_SVM_UNEXPECTED_EXIT;
6960 }
6961
6962 /*
6963 * Lazy DR0-3 loading.
6964 */
6965 if (!pSvmTransient->fWasHyperDebugStateActive)
6966 {
6967 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
6968 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
6969
6970 /* Don't intercept DRx read and writes. */
6971 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
6972 pVmcb->ctrl.u16InterceptRdDRx = 0;
6973 pVmcb->ctrl.u16InterceptWrDRx = 0;
6974 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
6975
6976 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
6977 VMMRZCallRing3Disable(pVCpu);
6978 HM_DISABLE_PREEMPT();
6979
6980 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
6981 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
6982 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
6983
6984 HM_RESTORE_PREEMPT();
6985 VMMRZCallRing3Enable(pVCpu);
6986
6987 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
6988 return VINF_SUCCESS;
6989 }
6990 }
6991
6992 /*
6993 * Interpret the read/writing of DRx.
6994 */
6995 /** @todo Decode assist. */
6996 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6997 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
6998 if (RT_LIKELY(rc == VINF_SUCCESS))
6999 {
7000 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
7001 /** @todo CPUM should set this flag! */
7002 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
7003 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7004 }
7005 else
7006 Assert(rc == VERR_EM_INTERPRETER);
7007 return VBOXSTRICTRC_TODO(rc);
7008}
7009
7010
7011/**
7012 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
7013 */
7014HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7015{
7016 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7017 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
7018 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
7019 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
7020 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
7021 return rc;
7022}
7023
7024
7025/**
7026 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
7027 */
7028HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7029{
7030 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7031 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
7032
7033 /** @todo decode assists... */
7034 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
7035 if (rcStrict == VINF_IEM_RAISED_XCPT)
7036 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7037
7038 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
7039 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
7040 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
7041
7042 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
7043 return VBOXSTRICTRC_TODO(rcStrict);
7044}
7045
7046
7047/**
7048 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
7049 */
7050HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7051{
7052 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7053 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK);
7054
7055 /* I/O operation lookup arrays. */
7056 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
7057 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
7058 the result (in AL/AX/EAX). */
7059 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
7060
7061 PVM pVM = pVCpu->CTX_SUFF(pVM);
7062 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7063
7064 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
7065 SVMIOIOEXITINFO IoExitInfo;
7066 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
7067 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
7068 uint32_t cbValue = s_aIOSize[uIOWidth];
7069 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
7070
7071 if (RT_UNLIKELY(!cbValue))
7072 {
7073 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
7074 return VERR_EM_INTERPRETER;
7075 }
7076
7077 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS);
7078 VBOXSTRICTRC rcStrict;
7079 PCEMEXITREC pExitRec = NULL;
7080 if ( !pVCpu->hm.s.fSingleInstruction
7081 && !pVCpu->cpum.GstCtx.eflags.Bits.u1TF)
7082 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
7083 !IoExitInfo.n.u1Str
7084 ? IoExitInfo.n.u1Type == SVM_IOIO_READ
7085 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
7086 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
7087 : IoExitInfo.n.u1Type == SVM_IOIO_READ
7088 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
7089 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
7090 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
7091 if (!pExitRec)
7092 {
7093 bool fUpdateRipAlready = false;
7094 if (IoExitInfo.n.u1Str)
7095 {
7096 /* INS/OUTS - I/O String instruction. */
7097 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
7098 * in EXITINFO1? Investigate once this thing is up and running. */
7099 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
7100 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
7101 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
7102 static IEMMODE const s_aenmAddrMode[8] =
7103 {
7104 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
7105 };
7106 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
7107 if (enmAddrMode != (IEMMODE)-1)
7108 {
7109 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
7110 if (cbInstr <= 15 && cbInstr >= 1)
7111 {
7112 Assert(cbInstr >= 1U + IoExitInfo.n.u1Rep);
7113 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
7114 {
7115 /* Don't know exactly how to detect whether u3Seg is valid, currently
7116 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
7117 2384 Opterons when only checking NRIP. */
7118 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
7119 if ( fSupportsNextRipSave
7120 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
7121 {
7122 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1Rep,
7123 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3Seg, cbInstr, IoExitInfo.n.u1Rep));
7124 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7125 IoExitInfo.n.u3Seg, true /*fIoChecked*/);
7126 }
7127 else if (cbInstr == 1U + IoExitInfo.n.u1Rep)
7128 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7129 X86_SREG_DS, true /*fIoChecked*/);
7130 else
7131 rcStrict = IEMExecOne(pVCpu);
7132 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
7133 }
7134 else
7135 {
7136 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3Seg));
7137 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7138 true /*fIoChecked*/);
7139 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
7140 }
7141 }
7142 else
7143 {
7144 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
7145 rcStrict = IEMExecOne(pVCpu);
7146 }
7147 }
7148 else
7149 {
7150 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
7151 rcStrict = IEMExecOne(pVCpu);
7152 }
7153 fUpdateRipAlready = true;
7154 }
7155 else
7156 {
7157 /* IN/OUT - I/O instruction. */
7158 Assert(!IoExitInfo.n.u1Rep);
7159
7160 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
7161 {
7162 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
7163 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
7164 }
7165 else
7166 {
7167 uint32_t u32Val = 0;
7168 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
7169 if (IOM_SUCCESS(rcStrict))
7170 {
7171 /* Save result of I/O IN instr. in AL/AX/EAX. */
7172 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
7173 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
7174 }
7175 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7176 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
7177
7178 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
7179 }
7180 }
7181
7182 if (IOM_SUCCESS(rcStrict))
7183 {
7184 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
7185 if (!fUpdateRipAlready)
7186 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
7187
7188 /*
7189 * If any I/O breakpoints are armed, we need to check if one triggered
7190 * and take appropriate action.
7191 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
7192 */
7193 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
7194 * execution engines about whether hyper BPs and such are pending. */
7195 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_DR7);
7196 uint32_t const uDr7 = pCtx->dr[7];
7197 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
7198 && X86_DR7_ANY_RW_IO(uDr7)
7199 && (pCtx->cr4 & X86_CR4_DE))
7200 || DBGFBpIsHwIoArmed(pVM)))
7201 {
7202 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
7203 VMMRZCallRing3Disable(pVCpu);
7204 HM_DISABLE_PREEMPT();
7205
7206 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
7207 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
7208
7209 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
7210 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
7211 {
7212 /* Raise #DB. */
7213 pVmcb->guest.u64DR6 = pCtx->dr[6];
7214 pVmcb->guest.u64DR7 = pCtx->dr[7];
7215 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7216 hmR0SvmSetPendingXcptDB(pVCpu);
7217 }
7218 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
7219 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
7220 else if ( rcStrict2 != VINF_SUCCESS
7221 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
7222 rcStrict = rcStrict2;
7223 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
7224
7225 HM_RESTORE_PREEMPT();
7226 VMMRZCallRing3Enable(pVCpu);
7227 }
7228
7229 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
7230 }
7231
7232#ifdef VBOX_STRICT
7233 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7234 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
7235 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
7236 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
7237 else
7238 {
7239 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
7240 * statuses, that the VMM device and some others may return. See
7241 * IOM_SUCCESS() for guidance. */
7242 AssertMsg( RT_FAILURE(rcStrict)
7243 || rcStrict == VINF_SUCCESS
7244 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
7245 || rcStrict == VINF_EM_DBG_BREAKPOINT
7246 || rcStrict == VINF_EM_RAW_GUEST_TRAP
7247 || rcStrict == VINF_EM_RAW_TO_R3
7248 || rcStrict == VINF_TRPM_XCPT_DISPATCHED
7249 || rcStrict == VINF_EM_TRIPLE_FAULT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
7250 }
7251#endif
7252 }
7253 else
7254 {
7255 /*
7256 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
7257 */
7258 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
7259 STAM_COUNTER_INC(!IoExitInfo.n.u1Str
7260 ? IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
7261 : IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
7262 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
7263 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, IoExitInfo.n.u1Rep ? "REP " : "",
7264 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? "OUT" : "IN", IoExitInfo.n.u1Str ? "S" : "", IoExitInfo.n.u16Port, uIOWidth));
7265
7266 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
7267 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7268
7269 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
7270 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
7271 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
7272 }
7273 return VBOXSTRICTRC_TODO(rcStrict);
7274}
7275
7276
7277/**
7278 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
7279 */
7280HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7281{
7282 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7283 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7284 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7285
7286 PVM pVM = pVCpu->CTX_SUFF(pVM);
7287 Assert(pVM->hm.s.fNestedPaging);
7288
7289 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
7290 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7291 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
7292 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1; /* Note! High bits in EXITINFO1 may contain additional info and are
7293 thus intentionally not copied into u32ErrCode. */
7294
7295 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
7296
7297 /*
7298 * TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions.
7299 */
7300 if ( pVM->hm.s.fTprPatchingAllowed
7301 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == XAPIC_OFF_TPR
7302 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
7303 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
7304 && !CPUMIsGuestInLongModeEx(pCtx)
7305 && !CPUMGetGuestCPL(pVCpu)
7306 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7307 {
7308 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7309 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7310
7311 if (GCPhysFaultAddr == GCPhysApicBase + XAPIC_OFF_TPR)
7312 {
7313 /* Only attempt to patch the instruction once. */
7314 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7315 if (!pPatch)
7316 return VINF_EM_HM_PATCH_TPR_INSTR;
7317 }
7318 }
7319
7320 /*
7321 * Determine the nested paging mode.
7322 */
7323 PGMMODE enmNestedPagingMode;
7324#if HC_ARCH_BITS == 32
7325 if (CPUMIsGuestInLongModeEx(pCtx))
7326 enmNestedPagingMode = PGMMODE_AMD64_NX;
7327 else
7328#endif
7329 enmNestedPagingMode = PGMGetHostMode(pVM);
7330
7331 /*
7332 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
7333 */
7334 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
7335 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
7336 {
7337 /* If event delivery causes an MMIO #NPF, go back to instruction emulation as
7338 otherwise injecting the original pending event would most likely cause the same MMIO #NPF. */
7339 if (pVCpu->hm.s.Event.fPending)
7340 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7341
7342 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS);
7343 VBOXSTRICTRC rcStrict;
7344 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
7345 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
7346 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
7347 if (!pExitRec)
7348 {
7349
7350 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
7351 u32ErrCode);
7352
7353 /*
7354 * If we succeed, resume guest execution.
7355 * If we fail in interpreting the instruction because we couldn't get the guest physical address
7356 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
7357 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
7358 * weird case. See @bugref{6043}.
7359 */
7360 if ( rcStrict == VINF_SUCCESS
7361 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
7362 || rcStrict == VERR_PAGE_NOT_PRESENT)
7363 {
7364 /* Successfully handled MMIO operation. */
7365 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
7366 rcStrict = VINF_SUCCESS;
7367 }
7368 }
7369 else
7370 {
7371 /*
7372 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
7373 */
7374 Assert(pCtx == &pVCpu->cpum.GstCtx);
7375 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
7376 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
7377 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhysFaultAddr));
7378
7379 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
7380 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7381
7382 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
7383 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
7384 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
7385 }
7386 return VBOXSTRICTRC_TODO(rcStrict);
7387 }
7388
7389 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
7390 int rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
7391 TRPMResetTrap(pVCpu);
7392
7393 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
7394
7395 /*
7396 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
7397 */
7398 if ( rc == VINF_SUCCESS
7399 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7400 || rc == VERR_PAGE_NOT_PRESENT)
7401 {
7402 /* We've successfully synced our shadow page tables. */
7403 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7404 rc = VINF_SUCCESS;
7405 }
7406
7407 return rc;
7408}
7409
7410
7411/**
7412 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
7413 * \#VMEXIT.
7414 */
7415HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7416{
7417 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7418 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7419
7420 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7421 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7422 hmR0SvmClearIntWindowExiting(pVCpu, pVmcb, pCtx);
7423
7424 /* Deliver the pending interrupt via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7425 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
7426 return VINF_SUCCESS;
7427}
7428
7429
7430/**
7431 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
7432 * \#VMEXIT.
7433 */
7434HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7435{
7436 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7437 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7438
7439#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
7440 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7441#endif
7442
7443 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
7444 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
7445 {
7446 /*
7447 * AMD-V provides us with the exception which caused the TS; we collect
7448 * the information in the call to hmR0SvmCheckExitDueToEventDelivery.
7449 */
7450 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
7451 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7452 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7453 }
7454
7455 /** @todo Emulate task switch someday, currently just going back to ring-3 for
7456 * emulation. */
7457 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7458 return VERR_EM_INTERPRETER;
7459}
7460
7461
7462/**
7463 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7464 */
7465HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7466{
7467 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7468 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7469
7470 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
7471
7472 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTprPatchingAllowed)
7473 {
7474 int rc = hmSvmEmulateMovTpr(pVCpu, pCtx);
7475 if (rc != VERR_NOT_FOUND)
7476 {
7477 Log4(("hmR0SvmExitVmmCall: hmSvmEmulateMovTpr returns %Rrc\n", rc));
7478 return rc;
7479 }
7480 }
7481
7482 if (EMAreHypercallInstructionsEnabled(pVCpu))
7483 {
7484 VBOXSTRICTRC rcStrict = GIMHypercall(pVCpu, pCtx);
7485 if (RT_SUCCESS(rcStrict))
7486 {
7487 /* Only update the RIP if we're continuing guest execution and not in the case
7488 of say VINF_GIM_R3_HYPERCALL. */
7489 if (rcStrict == VINF_SUCCESS)
7490 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
7491
7492 return VBOXSTRICTRC_VAL(rcStrict);
7493 }
7494 else
7495 Log4(("hmR0SvmExitVmmCall: GIMHypercall returns %Rrc -> #UD\n", VBOXSTRICTRC_VAL(rcStrict)));
7496 }
7497
7498 hmR0SvmSetPendingXcptUD(pVCpu);
7499 return VINF_SUCCESS;
7500}
7501
7502
7503/**
7504 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7505 */
7506HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7507{
7508 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7509 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
7510 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
7511 /** @todo The guest has likely hit a contended spinlock. We might want to
7512 * poke a schedule different guest VCPU. */
7513 return VINF_EM_RAW_INTERRUPT;
7514}
7515
7516
7517/**
7518 * \#VMEXIT handler for FERR intercept (SVM_EXIT_FERR_FREEZE). Conditional
7519 * \#VMEXIT.
7520 */
7521HMSVM_EXIT_DECL hmR0SvmExitFerrFreeze(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7522{
7523 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7524 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0);
7525 Assert(!(pCtx->cr0 & X86_CR0_NE));
7526
7527 Log4(("hmR0SvmExitFerrFreeze: Raising IRQ 13 in response to #FERR\n"));
7528 return PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7529}
7530
7531
7532/**
7533 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
7534 */
7535HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7536{
7537 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7538
7539 /* Clear NMI blocking. */
7540 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
7541 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
7542
7543 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7544 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7545 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_IRET);
7546
7547 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7548 return VINF_SUCCESS;
7549}
7550
7551
7552/**
7553 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_XCPT_14).
7554 * Conditional \#VMEXIT.
7555 */
7556HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7557{
7558 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7559 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7560 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7561
7562 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7563 PVM pVM = pVCpu->CTX_SUFF(pVM);
7564 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7565 uint32_t uErrCode = pVmcb->ctrl.u64ExitInfo1;
7566 uint64_t const uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7567
7568#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
7569 if (pVM->hm.s.fNestedPaging)
7570 {
7571 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7572 if ( !pSvmTransient->fVectoringDoublePF
7573 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
7574 {
7575 /* A genuine guest #PF, reflect it to the guest. */
7576 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, uErrCode, uFaultAddress);
7577 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RX64 ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
7578 uFaultAddress, uErrCode));
7579 }
7580 else
7581 {
7582 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7583 hmR0SvmSetPendingXcptDF(pVCpu);
7584 Log4(("Pending #DF due to vectoring #PF. NP\n"));
7585 }
7586 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7587 return VINF_SUCCESS;
7588 }
7589#endif
7590
7591 Assert(!pVM->hm.s.fNestedPaging);
7592
7593 /*
7594 * TPR patching shortcut for APIC TPR reads and writes; only applicable to 32-bit guests.
7595 */
7596 if ( pVM->hm.s.fTprPatchingAllowed
7597 && (uFaultAddress & 0xfff) == XAPIC_OFF_TPR
7598 && !(uErrCode & X86_TRAP_PF_P) /* Not present. */
7599 && !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7600 && !CPUMIsGuestInLongModeEx(pCtx)
7601 && !CPUMGetGuestCPL(pVCpu)
7602 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7603 {
7604 RTGCPHYS GCPhysApicBase;
7605 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7606 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7607
7608 /* Check if the page at the fault-address is the APIC base. */
7609 RTGCPHYS GCPhysPage;
7610 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
7611 if ( rc2 == VINF_SUCCESS
7612 && GCPhysPage == GCPhysApicBase)
7613 {
7614 /* Only attempt to patch the instruction once. */
7615 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7616 if (!pPatch)
7617 return VINF_EM_HM_PATCH_TPR_INSTR;
7618 }
7619 }
7620
7621 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 uErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7622 pCtx->rip, uErrCode, pCtx->cr3));
7623
7624 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
7625 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
7626 if (pSvmTransient->fVectoringPF)
7627 {
7628 Assert(pVCpu->hm.s.Event.fPending);
7629 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7630 }
7631
7632 TRPMAssertXcptPF(pVCpu, uFaultAddress, uErrCode);
7633 int rc = PGMTrap0eHandler(pVCpu, uErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7634
7635 Log4(("#PF: rc=%Rrc\n", rc));
7636
7637 if (rc == VINF_SUCCESS)
7638 {
7639 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7640 TRPMResetTrap(pVCpu);
7641 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7642 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7643 return rc;
7644 }
7645
7646 if (rc == VINF_EM_RAW_GUEST_TRAP)
7647 {
7648 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7649
7650 /*
7651 * If a nested-guest delivers a #PF and that causes a #PF which is -not- a shadow #PF,
7652 * we should simply forward the #PF to the guest and is up to the nested-hypervisor to
7653 * determine whether it is a nested-shadow #PF or a #DF, see @bugref{7243#c121}.
7654 */
7655 if ( !pSvmTransient->fVectoringDoublePF
7656 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
7657 {
7658 /* It's a guest (or nested-guest) page fault and needs to be reflected. */
7659 uErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7660 TRPMResetTrap(pVCpu);
7661
7662#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7663 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
7664 if ( CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7665 && HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_PF))
7666 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_XCPT_PF, uErrCode, uFaultAddress));
7667#endif
7668
7669 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, uErrCode, uFaultAddress);
7670 }
7671 else
7672 {
7673 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7674 TRPMResetTrap(pVCpu);
7675 hmR0SvmSetPendingXcptDF(pVCpu);
7676 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
7677 }
7678
7679 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7680 return VINF_SUCCESS;
7681 }
7682
7683 TRPMResetTrap(pVCpu);
7684 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7685 return rc;
7686}
7687
7688
7689/**
7690 * \#VMEXIT handler for undefined opcode (SVM_EXIT_XCPT_6).
7691 * Conditional \#VMEXIT.
7692 */
7693HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7694{
7695 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7696 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7697
7698 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7699 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7700 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7701
7702 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
7703 if (pVCpu->hm.s.fGIMTrapXcptUD)
7704 {
7705 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7706 uint8_t cbInstr = 0;
7707 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
7708 if (rcStrict == VINF_SUCCESS)
7709 {
7710 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
7711 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
7712 rc = VINF_SUCCESS;
7713 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7714 }
7715 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
7716 rc = VINF_SUCCESS;
7717 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
7718 rc = VINF_GIM_R3_HYPERCALL;
7719 else
7720 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
7721 }
7722
7723 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
7724 if (RT_FAILURE(rc))
7725 {
7726 hmR0SvmSetPendingXcptUD(pVCpu);
7727 rc = VINF_SUCCESS;
7728 }
7729
7730 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
7731 return rc;
7732}
7733
7734
7735/**
7736 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_XCPT_16).
7737 * Conditional \#VMEXIT.
7738 */
7739HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7740{
7741 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7742 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7743
7744 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7745 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7746 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7747
7748 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
7749
7750 if (!(pCtx->cr0 & X86_CR0_NE))
7751 {
7752 PVM pVM = pVCpu->CTX_SUFF(pVM);
7753 PDISSTATE pDis = &pVCpu->hm.s.DisState;
7754 unsigned cbOp;
7755 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
7756 if (RT_SUCCESS(rc))
7757 {
7758 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
7759 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7760 if (RT_SUCCESS(rc))
7761 pCtx->rip += cbOp;
7762 }
7763 else
7764 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
7765 return rc;
7766 }
7767
7768 hmR0SvmSetPendingXcptMF(pVCpu);
7769 return VINF_SUCCESS;
7770}
7771
7772
7773/**
7774 * \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1). Conditional
7775 * \#VMEXIT.
7776 */
7777HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7778{
7779 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7780 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7781 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7782
7783 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
7784 {
7785 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7786 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7787 }
7788
7789 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
7790
7791 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
7792 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
7793 PVM pVM = pVCpu->CTX_SUFF(pVM);
7794 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7795 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
7796 if (rc == VINF_EM_RAW_GUEST_TRAP)
7797 {
7798 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
7799 if (CPUMIsHyperDebugStateActive(pVCpu))
7800 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
7801
7802 /* Reflect the exception back to the guest. */
7803 hmR0SvmSetPendingXcptDB(pVCpu);
7804 rc = VINF_SUCCESS;
7805 }
7806
7807 /*
7808 * Update DR6.
7809 */
7810 if (CPUMIsHyperDebugStateActive(pVCpu))
7811 {
7812 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
7813 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
7814 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7815 }
7816 else
7817 {
7818 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
7819 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
7820 }
7821
7822 return rc;
7823}
7824
7825
7826/**
7827 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_XCPT_17).
7828 * Conditional \#VMEXIT.
7829 */
7830HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7831{
7832 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7833 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7834
7835 SVMEVENT Event;
7836 Event.u = 0;
7837 Event.n.u1Valid = 1;
7838 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7839 Event.n.u8Vector = X86_XCPT_AC;
7840 Event.n.u1ErrorCodeValid = 1;
7841 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7842 return VINF_SUCCESS;
7843}
7844
7845
7846/**
7847 * \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7848 * Conditional \#VMEXIT.
7849 */
7850HMSVM_EXIT_DECL hmR0SvmExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7851{
7852 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7853 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7854 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7855
7856 int rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
7857 if (rc == VINF_EM_RAW_GUEST_TRAP)
7858 {
7859 SVMEVENT Event;
7860 Event.u = 0;
7861 Event.n.u1Valid = 1;
7862 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7863 Event.n.u8Vector = X86_XCPT_BP;
7864 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7865 }
7866
7867 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
7868 return rc;
7869}
7870
7871
7872#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT_SVM)
7873/**
7874 * \#VMEXIT handler for generic exceptions. Conditional \#VMEXIT.
7875 */
7876HMSVM_EXIT_DECL hmR0SvmExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7877{
7878 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7879 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7880
7881 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7882 uint8_t const uVector = pVmcb->ctrl.u64ExitCode - SVM_EXIT_XCPT_0;
7883 uint32_t const uErrCode = pVmcb->ctrl.u64ExitInfo1;
7884 Assert(pSvmTransient->u64ExitCode == pVmcb->ctrl.u64ExitCode);
7885 Assert(uVector <= X86_XCPT_LAST);
7886 Log4(("hmR0SvmExitXcptGeneric: uVector=%#x uErrCode=%u\n", uVector, uErrCode));
7887
7888 SVMEVENT Event;
7889 Event.u = 0;
7890 Event.n.u1Valid = 1;
7891 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7892 Event.n.u8Vector = uVector;
7893 switch (uVector)
7894 {
7895 /* Shouldn't be here for reflecting #PFs (among other things, the fault address isn't passed along). */
7896 case X86_XCPT_PF: AssertMsgFailed(("hmR0SvmExitXcptGeneric: Unexpected exception")); return VERR_SVM_IPE_5;
7897 case X86_XCPT_DF:
7898 case X86_XCPT_TS:
7899 case X86_XCPT_NP:
7900 case X86_XCPT_SS:
7901 case X86_XCPT_GP:
7902 case X86_XCPT_AC:
7903 {
7904 Event.n.u1ErrorCodeValid = 1;
7905 Event.n.u32ErrorCode = uErrCode;
7906 break;
7907 }
7908 }
7909
7910 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7911 return VINF_SUCCESS;
7912}
7913#endif
7914
7915#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7916/**
7917 * \#VMEXIT handler for CLGI (SVM_EXIT_CLGI). Conditional \#VMEXIT.
7918 */
7919HMSVM_EXIT_DECL hmR0SvmExitClgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7920{
7921 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7922 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK
7923 | CPUMCTX_EXTRN_HWVIRT);
7924
7925#ifdef VBOX_STRICT
7926 PCSVMVMCB pVmcbTmp = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7927 Assert(pVmcbTmp);
7928 Assert(!pVmcbTmp->ctrl.IntCtrl.n.u1VGifEnable);
7929 RT_NOREF(pVmcbTmp);
7930#endif
7931
7932 /** @todo Stat. */
7933 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClgi); */
7934 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7935 VBOXSTRICTRC rcStrict = IEMExecDecodedClgi(pVCpu, cbInstr);
7936 return VBOXSTRICTRC_VAL(rcStrict);
7937}
7938
7939
7940/**
7941 * \#VMEXIT handler for STGI (SVM_EXIT_STGI). Conditional \#VMEXIT.
7942 */
7943HMSVM_EXIT_DECL hmR0SvmExitStgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7944{
7945 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7946 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK
7947 | CPUMCTX_EXTRN_HWVIRT);
7948
7949 /*
7950 * When VGIF is not used we always intercept STGI instructions. When VGIF is used,
7951 * we only intercept STGI when events are pending for GIF to become 1.
7952 */
7953 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7954 if (pVmcb->ctrl.IntCtrl.n.u1VGifEnable)
7955 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_STGI);
7956
7957 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7958 VBOXSTRICTRC rcStrict = IEMExecDecodedStgi(pVCpu, cbInstr);
7959 return VBOXSTRICTRC_VAL(rcStrict);
7960}
7961
7962
7963/**
7964 * \#VMEXIT handler for VMLOAD (SVM_EXIT_VMLOAD). Conditional \#VMEXIT.
7965 */
7966HMSVM_EXIT_DECL hmR0SvmExitVmload(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7967{
7968 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7969 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK
7970 | CPUMCTX_EXTRN_FS
7971 | CPUMCTX_EXTRN_GS
7972 | CPUMCTX_EXTRN_TR
7973 | CPUMCTX_EXTRN_LDTR
7974 | CPUMCTX_EXTRN_KERNEL_GS_BASE
7975 | CPUMCTX_EXTRN_SYSCALL_MSRS
7976 | CPUMCTX_EXTRN_SYSENTER_MSRS);
7977
7978#ifdef VBOX_STRICT
7979 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7980 Assert(pVmcb);
7981 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
7982 RT_NOREF(pVmcb);
7983#endif
7984
7985 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7986 VBOXSTRICTRC rcStrict = IEMExecDecodedVmload(pVCpu, cbInstr);
7987 if (rcStrict == VINF_SUCCESS)
7988 {
7989 /* We skip flagging changes made to LSTAR, STAR, SFMASK and other MSRs as they are always re-loaded. */
7990 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS
7991 | HM_CHANGED_GUEST_TR
7992 | HM_CHANGED_GUEST_LDTR
7993 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
7994 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
7995 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
7996 }
7997 return VBOXSTRICTRC_VAL(rcStrict);
7998}
7999
8000
8001/**
8002 * \#VMEXIT handler for VMSAVE (SVM_EXIT_VMSAVE). Conditional \#VMEXIT.
8003 */
8004HMSVM_EXIT_DECL hmR0SvmExitVmsave(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8005{
8006 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8007 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
8008
8009#ifdef VBOX_STRICT
8010 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
8011 Assert(pVmcb);
8012 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
8013 RT_NOREF(pVmcb);
8014#endif
8015
8016 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8017 VBOXSTRICTRC rcStrict = IEMExecDecodedVmsave(pVCpu, cbInstr);
8018 return VBOXSTRICTRC_VAL(rcStrict);
8019}
8020
8021
8022/**
8023 * \#VMEXIT handler for INVLPGA (SVM_EXIT_INVLPGA). Conditional \#VMEXIT.
8024 */
8025HMSVM_EXIT_DECL hmR0SvmExitInvlpga(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8026{
8027 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8028 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
8029
8030 /** @todo Stat. */
8031 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpga); */
8032 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8033 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpga(pVCpu, cbInstr);
8034 return VBOXSTRICTRC_VAL(rcStrict);
8035}
8036
8037
8038/**
8039 * \#VMEXIT handler for STGI (SVM_EXIT_VMRUN). Conditional \#VMEXIT.
8040 */
8041HMSVM_EXIT_DECL hmR0SvmExitVmrun(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8042{
8043 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8044 /** @todo Only save and reload what VMRUN changes (e.g. skip LDTR, TR etc). */
8045 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
8046
8047 VBOXSTRICTRC rcStrict;
8048 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8049 rcStrict = IEMExecDecodedVmrun(pVCpu, cbInstr);
8050 Log4(("IEMExecDecodedVmrun: returned %d\n", VBOXSTRICTRC_VAL(rcStrict)));
8051 if (rcStrict == VINF_SUCCESS)
8052 {
8053 rcStrict = VINF_SVM_VMRUN;
8054 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
8055 }
8056 return VBOXSTRICTRC_VAL(rcStrict);
8057}
8058
8059
8060/**
8061 * Nested-guest \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1).
8062 * Unconditional \#VMEXIT.
8063 */
8064HMSVM_EXIT_DECL hmR0SvmNestedExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8065{
8066 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8067 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
8068
8069 if (pVCpu->hm.s.Event.fPending)
8070 {
8071 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
8072 return VINF_EM_RAW_INJECT_TRPM_EVENT;
8073 }
8074
8075 hmR0SvmSetPendingXcptDB(pVCpu);
8076 return VINF_SUCCESS;
8077}
8078
8079
8080/**
8081 * Nested-guest \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
8082 * Conditional \#VMEXIT.
8083 */
8084HMSVM_EXIT_DECL hmR0SvmNestedExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8085{
8086 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8087 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
8088
8089 SVMEVENT Event;
8090 Event.u = 0;
8091 Event.n.u1Valid = 1;
8092 Event.n.u3Type = SVM_EVENT_EXCEPTION;
8093 Event.n.u8Vector = X86_XCPT_BP;
8094 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
8095 return VINF_SUCCESS;
8096}
8097
8098#endif /* VBOX_WITH_NESTED_HWVIRT_SVM */
8099
8100
8101/** @} */
8102
Note: See TracBrowser for help on using the repository browser.

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