VirtualBox

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

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

EM,HM,NEM,TRPM: Renamed some EMEXIT_XXXX stuff to shorten things down a bit. Added missing HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST) after EMHistoryExec in the VT-x code. Prepped the SVM code for CPUID, IO and MMIO exit optimizations. bugref:9198

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 325.3 KB
Line 
1/* $Id: HMSVMR0.cpp 72655 2018-06-22 10:05:53Z 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 if (pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL)
2788 {
2789 fWhat &= pCtx->fExtrn;
2790
2791#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
2792 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
2793 {
2794 if ( !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
2795 && pVmcbCtrl->IntCtrl.n.u1VGifEnable)
2796 {
2797 /* We don't yet support passing VGIF feature to the guest. */
2798 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.svm.fVGif);
2799 pCtx->hwvirt.fGif = pVmcbCtrl->IntCtrl.n.u1VGif;
2800 }
2801 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_HWVIRT);
2802 }
2803
2804 if (fWhat & CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ)
2805 {
2806 if ( !pVmcbCtrl->IntCtrl.n.u1VIrqPending
2807 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
2808 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
2809 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ);
2810 }
2811#else
2812 ASMAtomicUoAndU64(&pCtx->fExtrn, ~(CPUMCTX_EXTRN_HWVIRT | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ));
2813#endif
2814
2815 if (fWhat & CPUMCTX_EXTRN_HM_SVM_INT_SHADOW)
2816 {
2817 if (pVmcbCtrl->IntShadow.n.u1IntShadow)
2818 EMSetInhibitInterruptsPC(pVCpu, pVmcbGuest->u64RIP);
2819 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2820 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2821 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_HM_SVM_INT_SHADOW);
2822 }
2823
2824 if (fWhat & CPUMCTX_EXTRN_RIP)
2825 {
2826 pCtx->rip = pVmcbGuest->u64RIP;
2827 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_RIP);
2828 }
2829
2830 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
2831 {
2832 pCtx->eflags.u32 = pVmcbGuest->u64RFlags;
2833 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_RFLAGS);
2834 }
2835
2836 if (fWhat & CPUMCTX_EXTRN_RSP)
2837 {
2838 pCtx->rsp = pVmcbGuest->u64RSP;
2839 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_RSP);
2840 }
2841
2842 if (fWhat & CPUMCTX_EXTRN_RAX)
2843 {
2844 pCtx->rax = pVmcbGuest->u64RAX;
2845 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_RAX);
2846 }
2847
2848 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
2849 {
2850 if (fWhat & CPUMCTX_EXTRN_CS)
2851 {
2852 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, CS, cs);
2853 /*
2854 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
2855 * register (yet).
2856 */
2857 /** @todo SELM might need to be fixed as it too should not care about the
2858 * granularity bit. See @bugref{6785}. */
2859 if ( !pCtx->cs.Attr.n.u1Granularity
2860 && pCtx->cs.Attr.n.u1Present
2861 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
2862 {
2863 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
2864 pCtx->cs.Attr.n.u1Granularity = 1;
2865 }
2866 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, cs);
2867 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_CS);
2868 }
2869 if (fWhat & CPUMCTX_EXTRN_SS)
2870 {
2871 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, SS, ss);
2872 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, ss);
2873 /*
2874 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
2875 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
2876 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
2877 * See AMD spec. 15.5.1 "Basic operation".
2878 */
2879 Assert(!(pVmcbGuest->u8CPL & ~0x3));
2880 uint8_t const uCpl = pVmcbGuest->u8CPL;
2881 if (pCtx->ss.Attr.n.u2Dpl != uCpl)
2882 pCtx->ss.Attr.n.u2Dpl = uCpl & 0x3;
2883 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_SS);
2884 }
2885 if (fWhat & CPUMCTX_EXTRN_DS)
2886 {
2887 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, DS, ds);
2888 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, ds);
2889 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_DS);
2890 }
2891 if (fWhat & CPUMCTX_EXTRN_ES)
2892 {
2893 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, ES, es);
2894 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, es);
2895 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_ES);
2896 }
2897 if (fWhat & CPUMCTX_EXTRN_FS)
2898 {
2899 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, FS, fs);
2900 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, fs);
2901 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_FS);
2902 }
2903 if (fWhat & CPUMCTX_EXTRN_GS)
2904 {
2905 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, GS, gs);
2906 HMSVM_ASSERT_SEG_GRANULARITY(pCtx, gs);
2907 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_GS);
2908 }
2909 }
2910
2911 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
2912 {
2913 if (fWhat & CPUMCTX_EXTRN_TR)
2914 {
2915 /*
2916 * Fixup TR attributes so it's compatible with Intel. Important when saved-states
2917 * are used between Intel and AMD, see @bugref{6208#c39}.
2918 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2919 */
2920 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, TR, tr);
2921 if (pCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2922 {
2923 if ( pCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2924 || CPUMIsGuestInLongModeEx(pCtx))
2925 pCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2926 else if (pCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2927 pCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2928 }
2929 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_TR);
2930 }
2931
2932 if (fWhat & CPUMCTX_EXTRN_LDTR)
2933 {
2934 HMSVM_SEG_REG_COPY_FROM_VMCB(pCtx, pVmcbGuest, LDTR, ldtr);
2935 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_LDTR);
2936 }
2937
2938 if (fWhat & CPUMCTX_EXTRN_GDTR)
2939 {
2940 pCtx->gdtr.cbGdt = pVmcbGuest->GDTR.u32Limit;
2941 pCtx->gdtr.pGdt = pVmcbGuest->GDTR.u64Base;
2942 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_GDTR);
2943 }
2944
2945 if (fWhat & CPUMCTX_EXTRN_IDTR)
2946 {
2947 pCtx->idtr.cbIdt = pVmcbGuest->IDTR.u32Limit;
2948 pCtx->idtr.pIdt = pVmcbGuest->IDTR.u64Base;
2949 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_IDTR);
2950 }
2951 }
2952
2953 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
2954 {
2955 pCtx->msrSTAR = pVmcbGuest->u64STAR;
2956 pCtx->msrLSTAR = pVmcbGuest->u64LSTAR;
2957 pCtx->msrCSTAR = pVmcbGuest->u64CSTAR;
2958 pCtx->msrSFMASK = pVmcbGuest->u64SFMASK;
2959 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_SYSCALL_MSRS);
2960 }
2961
2962 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
2963 {
2964 pCtx->SysEnter.cs = pVmcbGuest->u64SysEnterCS;
2965 pCtx->SysEnter.eip = pVmcbGuest->u64SysEnterEIP;
2966 pCtx->SysEnter.esp = pVmcbGuest->u64SysEnterESP;
2967 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_SYSENTER_MSRS);
2968 }
2969
2970 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
2971 {
2972 pCtx->msrKERNELGSBASE = pVmcbGuest->u64KernelGSBase;
2973 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_KERNEL_GS_BASE);
2974 }
2975
2976 if (fWhat & CPUMCTX_EXTRN_DR_MASK)
2977 {
2978 if (fWhat & CPUMCTX_EXTRN_DR6)
2979 {
2980 if (!pVCpu->hm.s.fUsingHyperDR7)
2981 pCtx->dr[6] = pVmcbGuest->u64DR6;
2982 else
2983 CPUMSetHyperDR6(pVCpu, pVmcbGuest->u64DR6);
2984 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_DR6);
2985 }
2986
2987 if (fWhat & CPUMCTX_EXTRN_DR7)
2988 {
2989 if (!pVCpu->hm.s.fUsingHyperDR7)
2990 pCtx->dr[7] = pVmcbGuest->u64DR7;
2991 else
2992 Assert(pVmcbGuest->u64DR7 == CPUMGetHyperDR7(pVCpu));
2993 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_DR7);
2994 }
2995 }
2996
2997 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
2998 {
2999 if (fWhat & CPUMCTX_EXTRN_CR0)
3000 {
3001 /* We intercept changes to all CR0 bits except maybe TS & MP bits. */
3002 uint64_t const uCr0 = (pCtx->cr0 & ~(X86_CR0_TS | X86_CR0_MP))
3003 | (pVmcbGuest->u64CR0 & (X86_CR0_TS | X86_CR0_MP));
3004 CPUMSetGuestCR0(pVCpu, uCr0);
3005 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_CR0);
3006 }
3007
3008 if (fWhat & CPUMCTX_EXTRN_CR2)
3009 {
3010 pCtx->cr2 = pVmcbGuest->u64CR2;
3011 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_CR2);
3012 }
3013
3014 if (fWhat & CPUMCTX_EXTRN_CR3)
3015 {
3016 if ( pVmcbCtrl->NestedPagingCtrl.n.u1NestedPaging
3017 && pCtx->cr3 != pVmcbGuest->u64CR3)
3018 {
3019 CPUMSetGuestCR3(pVCpu, pVmcbGuest->u64CR3);
3020 if (VMMRZCallRing3IsEnabled(pVCpu))
3021 {
3022 Log4(("hmR0SvmImportGuestState: Calling PGMUpdateCR3\n"));
3023 PGMUpdateCR3(pVCpu, pVmcbGuest->u64CR3);
3024 }
3025 else
3026 {
3027 Log4(("hmR0SvmImportGuestState: Setting VMCPU_FF_HM_UPDATE_CR3\n"));
3028 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
3029 }
3030 }
3031 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_CR3);
3032 }
3033
3034 /* Changes to CR4 are always intercepted. */
3035 }
3036
3037 /* If everything has been imported, clear the HM keeper bit. */
3038 if (!(pCtx->fExtrn & HMSVM_CPUMCTX_EXTRN_ALL))
3039 {
3040 ASMAtomicUoAndU64(&pCtx->fExtrn, ~CPUMCTX_EXTRN_KEEPER_HM);
3041 Assert(!pCtx->fExtrn);
3042 }
3043 }
3044 else
3045 Assert(!pCtx->fExtrn);
3046
3047 /*
3048 * Honor any pending CR3 updates.
3049 *
3050 * Consider this scenario: #VMEXIT -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp
3051 * -> hmR0SvmCallRing3Callback() -> VMMRZCallRing3Disable() -> hmR0SvmImportGuestState()
3052 * -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp -> continue with #VMEXIT
3053 * handling -> hmR0SvmImportGuestState() and here we are.
3054 *
3055 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be
3056 * up-to-date and thus any CR3-saves -before- the VM-exit (longjmp) would've postponed the CR3
3057 * update via the force-flag and cleared CR3 from fExtrn. Any SVM R0 VM-exit handler that requests
3058 * CR3 to be saved will end up here and we call PGMUpdateCR3().
3059 *
3060 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again,
3061 * and does not process force-flag like regular exits to ring-3 either, we cover for it here.
3062 */
3063 if ( VMMRZCallRing3IsEnabled(pVCpu)
3064 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
3065 {
3066 Assert(pCtx->cr3 == pVmcbGuest->u64CR3);
3067 PGMUpdateCR3(pVCpu, pCtx->cr3);
3068 }
3069}
3070
3071
3072/**
3073 * Saves the guest (or nested-guest) state from the VMCB into the guest-CPU
3074 * context.
3075 *
3076 * Currently there is no residual state left in the CPU that is not updated in the
3077 * VMCB.
3078 *
3079 * @returns VBox status code.
3080 * @param pVCpu The cross context virtual CPU structure.
3081 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context. The
3082 * data may be out-of-sync. Make sure to update the required
3083 * fields before using them.
3084 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
3085 */
3086VMMR0DECL(int) SVMR0ImportStateOnDemand(PVMCPU pVCpu, PCPUMCTX pCtx, uint64_t fWhat)
3087{
3088 hmR0SvmImportGuestState(pVCpu, pCtx, fWhat);
3089 return VINF_SUCCESS;
3090}
3091
3092
3093/**
3094 * Saves the guest (or nested-guest) state from the VMCB into the guest-CPU
3095 * context.
3096 *
3097 * Currently there is no residual state left in the CPU that is not updated in the
3098 * VMCB.
3099 *
3100 * @returns VBox status code.
3101 * @param pVCpu The cross context virtual CPU structure.
3102 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context. The
3103 * data may be out-of-sync. Make sure to update the required
3104 * fields before using them.
3105 * @param pVmcb Pointer to the VM control block.
3106 */
3107static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pCtx, PCSVMVMCB pVmcb)
3108{
3109 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3110
3111 /*
3112 * Always import the following:
3113 *
3114 * - RIP, RFLAGS, int. shadow, GIF: we need them when as we evaluate
3115 * injecting events before re-entering guest execution.
3116 *
3117 * - GPRS: Only RAX, RSP are in the VMCB. All the other GPRs are swapped
3118 * by the assembly switcher code. Import these two always just to simplify
3119 * assumptions on GPRs.
3120 *
3121 * - SREG: We load them all together so we have to save all of them.
3122 *
3123 * - KERNEL_GS_BASE, SYSCALL MSRS: We don't have a HM_CHANGED_GUEST flag
3124 * for it yet
3125 */
3126 /** @todo Extend HM_CHANGED_GUEST_xxx so that we avoid saving segment
3127 * registers, kernel GS base and other MSRs each time. */
3128 hmR0SvmImportGuestState(pVCpu, pCtx, CPUMCTX_EXTRN_RIP
3129 | CPUMCTX_EXTRN_SYSCALL_MSRS
3130 | CPUMCTX_EXTRN_KERNEL_GS_BASE
3131 | CPUMCTX_EXTRN_RFLAGS
3132 | CPUMCTX_EXTRN_RAX
3133 | CPUMCTX_EXTRN_SREG_MASK
3134 | CPUMCTX_EXTRN_RSP
3135 | CPUMCTX_EXTRN_HWVIRT
3136 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW
3137 | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ);
3138
3139#ifdef DEBUG_ramshankar
3140 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3141 {
3142 hmR0SvmImportGuestState(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
3143 hmR0SvmLogState(pVCpu, pVmcb, pCtx, "hmR0SvmSaveGuestStateNested", HMSVM_LOG_ALL & ~HMSVM_LOG_LBR, 0 /* uVerbose */);
3144 }
3145#else
3146 RT_NOREF(pVmcb);
3147#endif
3148}
3149
3150
3151/**
3152 * Does the necessary state syncing before returning to ring-3 for any reason
3153 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
3154 *
3155 * @param pVCpu The cross context virtual CPU structure.
3156 * @param fImportState Whether to import the guest state from the VMCB back
3157 * to the guest-CPU context.
3158 *
3159 * @remarks No-long-jmp zone!!!
3160 */
3161static void hmR0SvmLeave(PVMCPU pVCpu, bool fImportState)
3162{
3163 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3164 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3165 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3166
3167 /*
3168 * !!! IMPORTANT !!!
3169 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
3170 */
3171
3172 /* Save the guest state if necessary. */
3173 if (fImportState)
3174 hmR0SvmImportGuestState(pVCpu, &pVCpu->cpum.GstCtx, HMSVM_CPUMCTX_EXTRN_ALL);
3175
3176 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
3177 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3178
3179 /*
3180 * Restore host debug registers if necessary and resync on next R0 reentry.
3181 */
3182#ifdef VBOX_STRICT
3183 if (CPUMIsHyperDebugStateActive(pVCpu))
3184 {
3185 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb; /** @todo nested-guest. */
3186 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
3187 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
3188 }
3189#endif
3190 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3191
3192 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
3193 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
3194
3195 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
3196 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
3197 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
3198 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
3199 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3200
3201 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
3202}
3203
3204
3205/**
3206 * Leaves the AMD-V session.
3207 *
3208 * Only used while returning to ring-3 either due to longjump or exits to
3209 * ring-3.
3210 *
3211 * @returns VBox status code.
3212 * @param pVCpu The cross context virtual CPU structure.
3213 */
3214static int hmR0SvmLeaveSession(PVMCPU pVCpu)
3215{
3216 HM_DISABLE_PREEMPT();
3217 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3218 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3219
3220 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
3221 and done this from the SVMR0ThreadCtxCallback(). */
3222 if (!pVCpu->hm.s.fLeaveDone)
3223 {
3224 hmR0SvmLeave(pVCpu, true /* fImportState */);
3225 pVCpu->hm.s.fLeaveDone = true;
3226 }
3227
3228 /*
3229 * !!! IMPORTANT !!!
3230 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
3231 */
3232
3233 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3234 /* Deregister hook now that we've left HM context before re-enabling preemption. */
3235 VMMR0ThreadCtxHookDisable(pVCpu);
3236
3237 /* Leave HM context. This takes care of local init (term). */
3238 int rc = HMR0LeaveCpu(pVCpu);
3239
3240 HM_RESTORE_PREEMPT();
3241 return rc;
3242}
3243
3244
3245/**
3246 * Does the necessary state syncing before doing a longjmp to ring-3.
3247 *
3248 * @returns VBox status code.
3249 * @param pVCpu The cross context virtual CPU structure.
3250 *
3251 * @remarks No-long-jmp zone!!!
3252 */
3253static int hmR0SvmLongJmpToRing3(PVMCPU pVCpu)
3254{
3255 return hmR0SvmLeaveSession(pVCpu);
3256}
3257
3258
3259/**
3260 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
3261 * any remaining host state) before we longjump to ring-3 and possibly get
3262 * preempted.
3263 *
3264 * @param pVCpu The cross context virtual CPU structure.
3265 * @param enmOperation The operation causing the ring-3 longjump.
3266 * @param pvUser The user argument (pointer to the possibly
3267 * out-of-date guest-CPU context).
3268 */
3269static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
3270{
3271 RT_NOREF_PV(pvUser);
3272
3273 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
3274 {
3275 /*
3276 * !!! IMPORTANT !!!
3277 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
3278 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
3279 */
3280 VMMRZCallRing3RemoveNotification(pVCpu);
3281 VMMRZCallRing3Disable(pVCpu);
3282 HM_DISABLE_PREEMPT();
3283
3284 /* Restore host FPU state if necessary and resync on next R0 reentry. */
3285 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
3286
3287 /* Restore host debug registers if necessary and resync on next R0 reentry. */
3288 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
3289
3290 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
3291 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
3292 VMMR0ThreadCtxHookDisable(pVCpu);
3293
3294 /* Leave HM context. This takes care of local init (term). */
3295 HMR0LeaveCpu(pVCpu);
3296
3297 HM_RESTORE_PREEMPT();
3298 return VINF_SUCCESS;
3299 }
3300
3301 Assert(pVCpu);
3302 Assert(pvUser);
3303 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3304 HMSVM_ASSERT_PREEMPT_SAFE();
3305
3306 VMMRZCallRing3Disable(pVCpu);
3307 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3308
3309 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
3310 int rc = hmR0SvmLongJmpToRing3(pVCpu);
3311 AssertRCReturn(rc, rc);
3312
3313 VMMRZCallRing3Enable(pVCpu);
3314 return VINF_SUCCESS;
3315}
3316
3317
3318/**
3319 * Take necessary actions before going back to ring-3.
3320 *
3321 * An action requires us to go back to ring-3. This function does the necessary
3322 * steps before we can safely return to ring-3. This is not the same as longjmps
3323 * to ring-3, this is voluntary.
3324 *
3325 * @returns VBox status code.
3326 * @param pVM The cross context VM structure.
3327 * @param pVCpu The cross context virtual CPU structure.
3328 * @param pCtx Pointer to the guest-CPU context.
3329 * @param rcExit The reason for exiting to ring-3. Can be
3330 * VINF_VMM_UNKNOWN_RING3_CALL.
3331 */
3332static int hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
3333{
3334 Assert(pVM);
3335 Assert(pVCpu);
3336 Assert(pCtx);
3337 HMSVM_ASSERT_PREEMPT_SAFE();
3338
3339 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
3340 VMMRZCallRing3Disable(pVCpu);
3341 Log4(("hmR0SvmExitToRing3: VCPU[%u]: rcExit=%d LocalFF=%#RX32 GlobalFF=%#RX32\n", pVCpu->idCpu, rcExit,
3342 pVCpu->fLocalForcedActions, pVM->fGlobalForcedActions));
3343
3344 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
3345 if (pVCpu->hm.s.Event.fPending)
3346 {
3347 hmR0SvmPendingEventToTrpmTrap(pVCpu);
3348 Assert(!pVCpu->hm.s.Event.fPending);
3349 }
3350
3351 /* Sync. the necessary state for going back to ring-3. */
3352 hmR0SvmLeaveSession(pVCpu);
3353 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
3354
3355 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
3356 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
3357 | CPUM_CHANGED_LDTR
3358 | CPUM_CHANGED_GDTR
3359 | CPUM_CHANGED_IDTR
3360 | CPUM_CHANGED_TR
3361 | CPUM_CHANGED_HIDDEN_SEL_REGS);
3362 if ( pVM->hm.s.fNestedPaging
3363 && CPUMIsGuestPagingEnabledEx(pCtx))
3364 {
3365 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3366 }
3367
3368 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
3369 if (rcExit != VINF_EM_RAW_INTERRUPT)
3370 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
3371
3372 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
3373
3374 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
3375 VMMRZCallRing3RemoveNotification(pVCpu);
3376 VMMRZCallRing3Enable(pVCpu);
3377
3378 /*
3379 * If we're emulating an instruction, we shouldn't have any TRPM traps pending
3380 * and if we're injecting an event we should have a TRPM trap pending.
3381 */
3382 AssertReturnStmt(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu),
3383 pVCpu->hm.s.u32HMError = rcExit,
3384 VERR_SVM_IPE_5);
3385 AssertReturnStmt(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu),
3386 pVCpu->hm.s.u32HMError = rcExit,
3387 VERR_SVM_IPE_4);
3388
3389 return rcExit;
3390}
3391
3392
3393/**
3394 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
3395 * intercepts.
3396 *
3397 * @param pVM The cross context VM structure.
3398 * @param pVCpu The cross context virtual CPU structure.
3399 * @param pCtx Pointer to the guest-CPU or nested-guest-CPU context.
3400 * @param pVmcb Pointer to the VM control block.
3401 *
3402 * @remarks No-long-jump zone!!!
3403 */
3404static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb)
3405{
3406 /*
3407 * Avoid intercepting RDTSC/RDTSCP if we determined the host TSC (++) is stable
3408 * and in case of a nested-guest, if the nested-VMCB specifies it is not intercepting
3409 * RDTSC/RDTSCP as well.
3410 */
3411 bool fParavirtTsc;
3412 uint64_t uTscOffset;
3413 bool const fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
3414
3415 bool fIntercept;
3416 if (fCanUseRealTsc)
3417 fIntercept = hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3418 else
3419 {
3420 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_RDTSC | SVM_CTRL_INTERCEPT_RDTSCP);
3421 fIntercept = true;
3422 }
3423
3424 if (!fIntercept)
3425 {
3426 /* Apply the nested-guest VMCB's TSC offset over the guest TSC offset. */
3427 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
3428 uTscOffset = HMSvmNstGstApplyTscOffset(pVCpu, uTscOffset);
3429
3430 /* Update the TSC offset in the VMCB and the relevant clean bits. */
3431 pVmcb->ctrl.u64TSCOffset = uTscOffset;
3432 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3433
3434 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
3435 }
3436 else
3437 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
3438
3439 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
3440 information before every VM-entry, hence we have nothing to do here at the moment. */
3441 if (fParavirtTsc)
3442 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
3443}
3444
3445
3446/**
3447 * Sets an event as a pending event to be injected into the guest.
3448 *
3449 * @param pVCpu The cross context virtual CPU structure.
3450 * @param pEvent Pointer to the SVM event.
3451 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
3452 * page-fault.
3453 *
3454 * @remarks Statistics counter assumes this is a guest event being reflected to
3455 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
3456 */
3457DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
3458{
3459 Assert(!pVCpu->hm.s.Event.fPending);
3460 Assert(pEvent->n.u1Valid);
3461
3462 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
3463 pVCpu->hm.s.Event.fPending = true;
3464 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
3465
3466 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
3467 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3468}
3469
3470
3471/**
3472 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
3473 *
3474 * @param pVCpu The cross context virtual CPU structure.
3475 */
3476DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
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_UD;
3483 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3484}
3485
3486
3487/**
3488 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
3489 *
3490 * @param pVCpu The cross context virtual CPU structure.
3491 */
3492DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3493{
3494 SVMEVENT Event;
3495 Event.u = 0;
3496 Event.n.u1Valid = 1;
3497 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3498 Event.n.u8Vector = X86_XCPT_DB;
3499 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3500}
3501
3502
3503/**
3504 * Sets a page fault (\#PF) exception as pending-for-injection into the VM.
3505 *
3506 * @param pVCpu The cross context virtual CPU structure.
3507 * @param pCtx Pointer to the guest-CPU context.
3508 * @param u32ErrCode The error-code for the page-fault.
3509 * @param uFaultAddress The page fault address (CR2).
3510 *
3511 * @remarks This updates the guest CR2 with @a uFaultAddress!
3512 */
3513DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3514{
3515 SVMEVENT Event;
3516 Event.u = 0;
3517 Event.n.u1Valid = 1;
3518 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3519 Event.n.u8Vector = X86_XCPT_PF;
3520 Event.n.u1ErrorCodeValid = 1;
3521 Event.n.u32ErrorCode = u32ErrCode;
3522
3523 /* Update CR2 of the guest. */
3524 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR2);
3525 if (pCtx->cr2 != uFaultAddress)
3526 {
3527 pCtx->cr2 = uFaultAddress;
3528 /* The VMCB clean bit for CR2 will be updated while re-loading the guest state. */
3529 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3530 }
3531
3532 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3533}
3534
3535
3536/**
3537 * Sets a math-fault (\#MF) exception as pending-for-injection into the VM.
3538 *
3539 * @param pVCpu The cross context virtual CPU structure.
3540 */
3541DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3542{
3543 SVMEVENT Event;
3544 Event.u = 0;
3545 Event.n.u1Valid = 1;
3546 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3547 Event.n.u8Vector = X86_XCPT_MF;
3548 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3549}
3550
3551
3552/**
3553 * Sets a double fault (\#DF) exception as pending-for-injection into the VM.
3554 *
3555 * @param pVCpu The cross context virtual CPU structure.
3556 */
3557DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3558{
3559 SVMEVENT Event;
3560 Event.u = 0;
3561 Event.n.u1Valid = 1;
3562 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3563 Event.n.u8Vector = X86_XCPT_DF;
3564 Event.n.u1ErrorCodeValid = 1;
3565 Event.n.u32ErrorCode = 0;
3566 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3567}
3568
3569
3570/**
3571 * Injects an event into the guest upon VMRUN by updating the relevant field
3572 * in the VMCB.
3573 *
3574 * @param pVCpu The cross context virtual CPU structure.
3575 * @param pVmcb Pointer to the guest VM control block.
3576 * @param pEvent Pointer to the event.
3577 *
3578 * @remarks No-long-jump zone!!!
3579 * @remarks Requires CR0!
3580 */
3581DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PSVMEVENT pEvent)
3582{
3583 Assert(!pVmcb->ctrl.EventInject.n.u1Valid);
3584 pVmcb->ctrl.EventInject.u = pEvent->u;
3585 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
3586 RT_NOREF(pVCpu);
3587
3588 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
3589 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
3590}
3591
3592
3593
3594/**
3595 * Converts any TRPM trap into a pending HM event. This is typically used when
3596 * entering from ring-3 (not longjmp returns).
3597 *
3598 * @param pVCpu The cross context virtual CPU structure.
3599 */
3600static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
3601{
3602 Assert(TRPMHasTrap(pVCpu));
3603 Assert(!pVCpu->hm.s.Event.fPending);
3604
3605 uint8_t uVector;
3606 TRPMEVENT enmTrpmEvent;
3607 RTGCUINT uErrCode;
3608 RTGCUINTPTR GCPtrFaultAddress;
3609 uint8_t cbInstr;
3610
3611 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
3612 AssertRC(rc);
3613
3614 SVMEVENT Event;
3615 Event.u = 0;
3616 Event.n.u1Valid = 1;
3617 Event.n.u8Vector = uVector;
3618
3619 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
3620 if (enmTrpmEvent == TRPM_TRAP)
3621 {
3622 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3623 switch (uVector)
3624 {
3625 case X86_XCPT_NMI:
3626 {
3627 Event.n.u3Type = SVM_EVENT_NMI;
3628 break;
3629 }
3630
3631 case X86_XCPT_PF:
3632 case X86_XCPT_DF:
3633 case X86_XCPT_TS:
3634 case X86_XCPT_NP:
3635 case X86_XCPT_SS:
3636 case X86_XCPT_GP:
3637 case X86_XCPT_AC:
3638 {
3639 Event.n.u1ErrorCodeValid = 1;
3640 Event.n.u32ErrorCode = uErrCode;
3641 break;
3642 }
3643 }
3644 }
3645 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
3646 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3647 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
3648 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
3649 else
3650 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
3651
3652 rc = TRPMResetTrap(pVCpu);
3653 AssertRC(rc);
3654
3655 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
3656 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
3657
3658 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
3659}
3660
3661
3662/**
3663 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
3664 * AMD-V to execute any instruction.
3665 *
3666 * @param pVCpu The cross context virtual CPU structure.
3667 */
3668static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
3669{
3670 Assert(pVCpu->hm.s.Event.fPending);
3671 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
3672
3673 SVMEVENT Event;
3674 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3675
3676 uint8_t uVector = Event.n.u8Vector;
3677 uint8_t uVectorType = Event.n.u3Type;
3678 TRPMEVENT enmTrapType = HMSvmEventToTrpmEventType(&Event);
3679
3680 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
3681
3682 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
3683 AssertRC(rc);
3684
3685 if (Event.n.u1ErrorCodeValid)
3686 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
3687
3688 if ( uVectorType == SVM_EVENT_EXCEPTION
3689 && uVector == X86_XCPT_PF)
3690 {
3691 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
3692 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
3693 }
3694 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
3695 {
3696 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
3697 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
3698 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
3699 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
3700 }
3701 pVCpu->hm.s.Event.fPending = false;
3702}
3703
3704
3705/**
3706 * Checks if the guest (or nested-guest) has an interrupt shadow active right
3707 * now.
3708 *
3709 * @returns @c true if the interrupt shadow is active, @c false otherwise.
3710 * @param pVCpu The cross context virtual CPU structure.
3711 * @param pCtx Pointer to the guest-CPU context.
3712 *
3713 * @remarks No-long-jump zone!!!
3714 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
3715 */
3716DECLINLINE(bool) hmR0SvmIsIntrShadowActive(PVMCPU pVCpu, PCCPUMCTX pCtx)
3717{
3718 /*
3719 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
3720 * inhibit interrupts or clear any existing interrupt-inhibition.
3721 */
3722 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3723 {
3724 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
3725 {
3726 /*
3727 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
3728 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
3729 */
3730 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3731 return false;
3732 }
3733 return true;
3734 }
3735 return false;
3736}
3737
3738
3739/**
3740 * Sets the virtual interrupt intercept control in the VMCB.
3741 *
3742 * @param pVCpu The cross context virtual CPU structure.
3743 * @param pVmcb Pointer to the VM control block.
3744 * @param pCtx Pointer to the guest-CPU context.
3745 */
3746DECLINLINE(void) hmR0SvmSetIntWindowExiting(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
3747{
3748 /*
3749 * When AVIC isn't supported, set up an interrupt window to cause a #VMEXIT when
3750 * the guest is ready to accept interrupts. At #VMEXIT, we then get the interrupt
3751 * from the APIC (updating ISR at the right time) and inject the interrupt.
3752 *
3753 * With AVIC is supported, we could make use of the asynchronously delivery without
3754 * #VMEXIT and we would be passing the AVIC page to SVM.
3755 *
3756 * In AMD-V, an interrupt window is achieved using a combination of
3757 * V_IRQ (an interrupt is pending), V_IGN_TPR (ignore TPR priorities) and the
3758 * VINTR intercept all being set.
3759 */
3760#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3761 /*
3762 * Currently we don't overlay interupt windows and if there's any V_IRQ pending
3763 * in the nested-guest VMCB, we avoid setting up any interrupt window on behalf
3764 * of the outer guest.
3765 */
3766 /** @todo Does this mean we end up prioritizing virtual interrupt
3767 * delivery/window over a physical interrupt (from the outer guest)
3768 * might be pending? */
3769 bool const fEnableIntWindow = !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST);
3770 if (!fEnableIntWindow)
3771 {
3772 Assert(CPUMIsGuestInSvmNestedHwVirtMode(pCtx)); RT_NOREF(pCtx);
3773 Log4(("Nested-guest V_IRQ already pending\n"));
3774 }
3775#else
3776 RT_NOREF2(pVCpu, pCtx);
3777 bool const fEnableIntWindow = true;
3778#endif
3779 if (fEnableIntWindow)
3780 {
3781 Assert(pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR);
3782 pVmcb->ctrl.IntCtrl.n.u1VIrqPending = 1;
3783 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INT_CTRL;
3784 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_VINTR);
3785 Log4(("Set VINTR intercept\n"));
3786 }
3787}
3788
3789
3790/**
3791 * Clears the virtual interrupt intercept control in the VMCB as
3792 * we are figured the guest is unable process any interrupts
3793 * at this point of time.
3794 *
3795 * @param pVCpu The cross context virtual CPU structure.
3796 * @param pVmcb Pointer to the VM control block.
3797 * @param pCtx Pointer to the guest-CPU context.
3798 */
3799DECLINLINE(void) hmR0SvmClearIntWindowExiting(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
3800{
3801 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
3802 if ( pVmcbCtrl->IntCtrl.n.u1VIrqPending
3803 || (pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR))
3804 {
3805 pVmcbCtrl->IntCtrl.n.u1VIrqPending = 0;
3806 pVmcbCtrl->u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INT_CTRL;
3807 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_VINTR);
3808 Log4(("Cleared VINTR intercept\n"));
3809 }
3810}
3811
3812#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3813/**
3814 * Evaluates the event to be delivered to the nested-guest and sets it as the
3815 * pending event.
3816 *
3817 * @returns VBox strict status code.
3818 * @param pVCpu The cross context virtual CPU structure.
3819 * @param pCtx Pointer to the guest-CPU context.
3820 */
3821static VBOXSTRICTRC hmR0SvmEvaluatePendingEventNested(PVMCPU pVCpu, PCPUMCTX pCtx)
3822{
3823 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
3824 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_HWVIRT
3825 | CPUMCTX_EXTRN_RFLAGS
3826 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW
3827 | CPUMCTX_EXTRN_HM_SVM_HWVIRT_VIRQ);
3828
3829 Assert(!pVCpu->hm.s.Event.fPending);
3830 Assert(pCtx->hwvirt.fGif);
3831 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
3832 Assert(pVmcb);
3833
3834 bool const fVirtualGif = CPUMGetSvmNstGstVGif(pCtx);
3835 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3836 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3837
3838 Log4Func(("fVirtualGif=%RTbool fBlockNmi=%RTbool fIntShadow=%RTbool fIntrPending=%RTbool fNmiPending=%RTbool\n",
3839 fVirtualGif, fBlockNmi, fIntShadow, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC),
3840 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)));
3841
3842 /** @todo SMI. SMIs take priority over NMIs. */
3843
3844 /*
3845 * Check if the guest can receive NMIs.
3846 * Nested NMIs are not allowed, see AMD spec. 8.1.4 "Masking External Interrupts".
3847 * NMIs take priority over maskable interrupts, see AMD spec. 8.5 "Priorities".
3848 */
3849 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)
3850 && !fBlockNmi)
3851 {
3852 if ( fVirtualGif
3853 && !fIntShadow)
3854 {
3855 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_NMI))
3856 {
3857 Log4(("Intercepting NMI -> #VMEXIT\n"));
3858 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
3859 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_NMI, 0, 0);
3860 }
3861
3862 Log4(("Setting NMI pending for injection\n"));
3863 SVMEVENT Event;
3864 Event.u = 0;
3865 Event.n.u1Valid = 1;
3866 Event.n.u8Vector = X86_XCPT_NMI;
3867 Event.n.u3Type = SVM_EVENT_NMI;
3868 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3869 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3870 }
3871 else if (!fVirtualGif)
3872 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3873 else
3874 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3875 }
3876 /*
3877 * Check if the nested-guest can receive external interrupts (generated by
3878 * the guest's PIC/APIC).
3879 *
3880 * External intercepts, NMI, SMI etc. from the physical CPU are -always- intercepted
3881 * when executing using hardware-assisted SVM, see HMSVM_MANDATORY_GUEST_CTRL_INTERCEPTS.
3882 *
3883 * External interrupts that are generated for the outer guest may be intercepted
3884 * depending on how the nested-guest VMCB was programmed by guest software.
3885 *
3886 * Physical interrupts always take priority over virtual interrupts,
3887 * see AMD spec. 15.21.4 "Injecting Virtual (INTR) Interrupts".
3888 */
3889 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
3890 && !pVCpu->hm.s.fSingleInstruction)
3891 {
3892 if ( fVirtualGif
3893 && !fIntShadow
3894 && CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx))
3895 {
3896 if (CPUMIsGuestSvmCtrlInterceptSet(pVCpu, pCtx, SVM_CTRL_INTERCEPT_INTR))
3897 {
3898 Log4(("Intercepting INTR -> #VMEXIT\n"));
3899 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK);
3900 return IEMExecSvmVmexit(pVCpu, SVM_EXIT_INTR, 0, 0);
3901 }
3902
3903 uint8_t u8Interrupt;
3904 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
3905 if (RT_SUCCESS(rc))
3906 {
3907 Log4(("Setting external interrupt %#x pending for injection\n", u8Interrupt));
3908 SVMEVENT Event;
3909 Event.u = 0;
3910 Event.n.u1Valid = 1;
3911 Event.n.u8Vector = u8Interrupt;
3912 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
3913 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3914 }
3915 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
3916 {
3917 /*
3918 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
3919 * updated eventually when the TPR is written by the guest.
3920 */
3921 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
3922 }
3923 else
3924 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
3925 }
3926 else if (!fVirtualGif)
3927 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3928 else
3929 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3930 }
3931
3932 return VINF_SUCCESS;
3933}
3934#endif
3935
3936/**
3937 * Evaluates the event to be delivered to the guest and sets it as the pending
3938 * event.
3939 *
3940 * @param pVCpu The cross context virtual CPU structure.
3941 * @param pCtx Pointer to the guest-CPU context.
3942 */
3943static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
3944{
3945 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
3946 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_HWVIRT
3947 | CPUMCTX_EXTRN_RFLAGS
3948 | CPUMCTX_EXTRN_HM_SVM_INT_SHADOW);
3949
3950 Assert(!pVCpu->hm.s.Event.fPending);
3951 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
3952 Assert(pVmcb);
3953
3954#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
3955 bool const fGif = pCtx->hwvirt.fGif;
3956#else
3957 bool const fGif = true;
3958#endif
3959 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
3960 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
3961 bool const fBlockNmi = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS);
3962
3963 Log4Func(("fGif=%RTbool fBlockNmi=%RTbool fBlockInt=%RTbool fIntShadow=%RTbool Intr. pending=%RTbool NMI pending=%RTbool\n",
3964 fGif, fBlockNmi, fBlockInt, fIntShadow,
3965 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC),
3966 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)));
3967
3968 /** @todo SMI. SMIs take priority over NMIs. */
3969
3970 /*
3971 * Check if the guest can receive NMIs.
3972 * Nested NMIs are not allowed, see AMD spec. 8.1.4 "Masking External Interrupts".
3973 * NMIs take priority over maskable interrupts, see AMD spec. 8.5 "Priorities".
3974 */
3975 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)
3976 && !fBlockNmi)
3977 {
3978 if ( fGif
3979 && !fIntShadow)
3980 {
3981 Log4(("Setting NMI pending for injection\n"));
3982 SVMEVENT Event;
3983 Event.u = 0;
3984 Event.n.u1Valid = 1;
3985 Event.n.u8Vector = X86_XCPT_NMI;
3986 Event.n.u3Type = SVM_EVENT_NMI;
3987 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3988 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
3989 }
3990 else if (!fGif)
3991 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
3992 else
3993 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
3994 }
3995 /*
3996 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
3997 * a valid interrupt we -must- deliver the interrupt. We can no longer re-request it from the APIC.
3998 */
3999 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
4000 && !pVCpu->hm.s.fSingleInstruction)
4001 {
4002 if ( fGif
4003 && !fBlockInt
4004 && !fIntShadow)
4005 {
4006 uint8_t u8Interrupt;
4007 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
4008 if (RT_SUCCESS(rc))
4009 {
4010 Log4(("Setting external interrupt %#x pending for injection\n", u8Interrupt));
4011 SVMEVENT Event;
4012 Event.u = 0;
4013 Event.n.u1Valid = 1;
4014 Event.n.u8Vector = u8Interrupt;
4015 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
4016 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
4017 }
4018 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
4019 {
4020 /*
4021 * AMD-V has no TPR thresholding feature. TPR and the force-flag will be
4022 * updated eventually when the TPR is written by the guest.
4023 */
4024 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
4025 }
4026 else
4027 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
4028 }
4029 else if (!fGif)
4030 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_STGI);
4031 else
4032 hmR0SvmSetIntWindowExiting(pVCpu, pVmcb, pCtx);
4033 }
4034}
4035
4036
4037/**
4038 * Injects any pending events into the guest (or nested-guest).
4039 *
4040 * @param pVCpu The cross context virtual CPU structure.
4041 * @param pCtx Pointer to the guest-CPU context.
4042 * @param pVmcb Pointer to the VM control block.
4043 *
4044 * @remarks Must only be called when we are guaranteed to enter
4045 * hardware-assisted SVM execution and not return to ring-3
4046 * prematurely.
4047 */
4048static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMVMCB pVmcb)
4049{
4050 Assert(!TRPMHasTrap(pVCpu));
4051 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4052
4053 bool const fIntShadow = hmR0SvmIsIntrShadowActive(pVCpu, pCtx);
4054#ifdef VBOX_STRICT
4055 bool const fGif = pCtx->hwvirt.fGif;
4056 bool fAllowInt = fGif;
4057 if (fGif)
4058 {
4059 /*
4060 * For nested-guests we have no way to determine if we're injecting a physical or virtual
4061 * interrupt at this point. Hence the partial verification below.
4062 */
4063 if (CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4064 fAllowInt = CPUMCanSvmNstGstTakePhysIntr(pVCpu, pCtx) || CPUMCanSvmNstGstTakeVirtIntr(pVCpu, pCtx);
4065 else
4066 fAllowInt = RT_BOOL(pCtx->eflags.u32 & X86_EFL_IF);
4067 }
4068#endif
4069
4070 if (pVCpu->hm.s.Event.fPending)
4071 {
4072 SVMEVENT Event;
4073 Event.u = pVCpu->hm.s.Event.u64IntInfo;
4074 Assert(Event.n.u1Valid);
4075
4076 /*
4077 * Validate event injection pre-conditions.
4078 */
4079 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
4080 {
4081 Assert(fAllowInt);
4082 Assert(!fIntShadow);
4083 }
4084 else if (Event.n.u3Type == SVM_EVENT_NMI)
4085 {
4086 Assert(fGif);
4087 Assert(!fIntShadow);
4088 }
4089
4090 /*
4091 * Before injecting an NMI we must set VMCPU_FF_BLOCK_NMIS to prevent nested NMIs. We do this only
4092 * when we are surely going to inject the NMI as otherwise if we return to ring-3 prematurely we
4093 * could leave NMIs blocked indefinitely upon re-entry into SVM R0.
4094 *
4095 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set
4096 * the VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
4097 */
4098 if ( Event.n.u3Type == SVM_EVENT_NMI
4099 && Event.n.u8Vector == X86_XCPT_NMI
4100 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4101 {
4102 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
4103 }
4104
4105 /*
4106 * Inject it (update VMCB for injection by the hardware).
4107 */
4108 Log4(("Injecting pending HM event\n"));
4109 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, &Event);
4110 pVCpu->hm.s.Event.fPending = false;
4111
4112 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
4113 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
4114 else
4115 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
4116 }
4117 else
4118 Assert(pVmcb->ctrl.EventInject.n.u1Valid == 0);
4119
4120 /*
4121 * We could have injected an NMI through IEM and continue guest execution using
4122 * hardware-assisted SVM. In which case, we would not have any events pending (above)
4123 * but we still need to intercept IRET in order to eventually clear NMI inhibition.
4124 */
4125 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
4126 hmR0SvmSetCtrlIntercept(pVmcb, SVM_CTRL_INTERCEPT_IRET);
4127
4128 /*
4129 * Update the guest interrupt shadow in the guest (or nested-guest) VMCB.
4130 *
4131 * For nested-guests: We need to update it too for the scenario where IEM executes
4132 * the nested-guest but execution later continues here with an interrupt shadow active.
4133 */
4134 pVmcb->ctrl.IntShadow.n.u1IntShadow = fIntShadow;
4135}
4136
4137
4138/**
4139 * Reports world-switch error and dumps some useful debug info.
4140 *
4141 * @param pVM The cross context VM structure.
4142 * @param pVCpu The cross context virtual CPU structure.
4143 * @param rcVMRun The return code from VMRUN (or
4144 * VERR_SVM_INVALID_GUEST_STATE for invalid
4145 * guest-state).
4146 * @param pCtx Pointer to the guest-CPU context.
4147 */
4148static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
4149{
4150 NOREF(pCtx);
4151 HMSVM_ASSERT_PREEMPT_SAFE();
4152 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4153 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
4154
4155 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4156 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
4157 {
4158 hmR0DumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
4159#ifdef VBOX_STRICT
4160 Log4(("ctrl.u32VmcbCleanBits %#RX32\n", pVmcb->ctrl.u32VmcbCleanBits));
4161 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
4162 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
4163 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
4164 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
4165 Log4(("ctrl.u32InterceptXcpt %#x\n", pVmcb->ctrl.u32InterceptXcpt));
4166 Log4(("ctrl.u64InterceptCtrl %#RX64\n", pVmcb->ctrl.u64InterceptCtrl));
4167 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
4168 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
4169 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
4170
4171 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
4172 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
4173 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
4174
4175 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
4176 Log4(("ctrl.IntCtrl.u1VIrqPending %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqPending));
4177 Log4(("ctrl.IntCtrl.u1VGif %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGif));
4178 Log4(("ctrl.IntCtrl.u6Reserved0 %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
4179 Log4(("ctrl.IntCtrl.u4VIntrPrio %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIntrPrio));
4180 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
4181 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
4182 Log4(("ctrl.IntCtrl.u1VIntrMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIntrMasking));
4183 Log4(("ctrl.IntCtrl.u1VGifEnable %#x\n", pVmcb->ctrl.IntCtrl.n.u1VGifEnable));
4184 Log4(("ctrl.IntCtrl.u5Reserved1 %#x\n", pVmcb->ctrl.IntCtrl.n.u5Reserved));
4185 Log4(("ctrl.IntCtrl.u8VIntrVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIntrVector));
4186 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
4187
4188 Log4(("ctrl.IntShadow.u1IntShadow %#x\n", pVmcb->ctrl.IntShadow.n.u1IntShadow));
4189 Log4(("ctrl.IntShadow.u1GuestIntMask %#x\n", pVmcb->ctrl.IntShadow.n.u1GuestIntMask));
4190 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
4191 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
4192 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
4193 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
4194 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
4195 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
4196 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
4197 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
4198 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
4199 Log4(("ctrl.NestedPagingCtrl.u1NestedPaging %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1NestedPaging));
4200 Log4(("ctrl.NestedPagingCtrl.u1Sev %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1Sev));
4201 Log4(("ctrl.NestedPagingCtrl.u1SevEs %#x\n", pVmcb->ctrl.NestedPagingCtrl.n.u1SevEs));
4202 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
4203 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
4204 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
4205 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
4206 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
4207 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
4208
4209 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
4210
4211 Log4(("ctrl.LbrVirt.u1LbrVirt %#x\n", pVmcb->ctrl.LbrVirt.n.u1LbrVirt));
4212 Log4(("ctrl.LbrVirt.u1VirtVmsaveVmload %#x\n", pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload));
4213
4214 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
4215 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
4216 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
4217 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
4218 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
4219 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
4220 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
4221 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
4222 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
4223 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
4224 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
4225 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
4226 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
4227 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
4228 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
4229 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
4230 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
4231 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
4232 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
4233 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
4234
4235 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
4236 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
4237
4238 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
4239 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
4240 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
4241 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
4242
4243 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
4244 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
4245
4246 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
4247 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
4248 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
4249 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
4250
4251 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
4252 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
4253 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
4254 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
4255 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
4256 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
4257 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
4258
4259 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
4260 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
4261 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
4262 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
4263
4264 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
4265 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
4266 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
4267
4268 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
4269 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
4270 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
4271 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
4272 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
4273 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
4274 Log4(("guest.u64PAT %#RX64\n", pVmcb->guest.u64PAT));
4275 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
4276 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
4277 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
4278 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
4279 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
4280#endif /* VBOX_STRICT */
4281 }
4282 else
4283 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
4284
4285 NOREF(pVmcb);
4286}
4287
4288
4289/**
4290 * Check per-VM and per-VCPU force flag actions that require us to go back to
4291 * ring-3 for one reason or another.
4292 *
4293 * @returns VBox status code (information status code included).
4294 * @retval VINF_SUCCESS if we don't have any actions that require going back to
4295 * ring-3.
4296 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
4297 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
4298 * interrupts)
4299 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
4300 * all EMTs to be in ring-3.
4301 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
4302 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
4303 * to the EM loop.
4304 *
4305 * @param pVM The cross context VM structure.
4306 * @param pVCpu The cross context virtual CPU structure.
4307 * @param pCtx Pointer to the guest-CPU context.
4308 */
4309static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4310{
4311 Assert(VMMRZCallRing3IsEnabled(pVCpu));
4312 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
4313 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
4314
4315 /* Could happen as a result of longjump. */
4316 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
4317 {
4318 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CR3));
4319 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
4320 }
4321
4322 /* Update pending interrupts into the APIC's IRR. */
4323 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
4324 APICUpdatePendingInterrupts(pVCpu);
4325
4326 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
4327 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
4328 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
4329 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
4330 {
4331 /* Pending PGM C3 sync. */
4332 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
4333 {
4334 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
4335 if (rc != VINF_SUCCESS)
4336 {
4337 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
4338 return rc;
4339 }
4340 }
4341
4342 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
4343 /* -XXX- what was that about single stepping? */
4344 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
4345 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4346 {
4347 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4348 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
4349 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
4350 return rc;
4351 }
4352
4353 /* Pending VM request packets, such as hardware interrupts. */
4354 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
4355 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
4356 {
4357 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
4358 return VINF_EM_PENDING_REQUEST;
4359 }
4360
4361 /* Pending PGM pool flushes. */
4362 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
4363 {
4364 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
4365 return VINF_PGM_POOL_FLUSH_PENDING;
4366 }
4367
4368 /* Pending DMA requests. */
4369 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
4370 {
4371 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
4372 return VINF_EM_RAW_TO_R3;
4373 }
4374 }
4375
4376 return VINF_SUCCESS;
4377}
4378
4379
4380#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4381/**
4382 * Does the preparations before executing nested-guest code in AMD-V.
4383 *
4384 * @returns VBox status code (informational status codes included).
4385 * @retval VINF_SUCCESS if we can proceed with running the guest.
4386 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4387 *
4388 * @param pVM The cross context VM structure.
4389 * @param pVCpu The cross context virtual CPU structure.
4390 * @param pCtx Pointer to the nested-guest-CPU context.
4391 * @param pSvmTransient Pointer to the SVM transient structure.
4392 *
4393 * @remarks Same caveats regarding longjumps as hmR0SvmPreRunGuest applies.
4394 * @sa hmR0SvmPreRunGuest.
4395 */
4396static int hmR0SvmPreRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4397{
4398 HMSVM_ASSERT_PREEMPT_SAFE();
4399 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4400
4401#ifdef VBOX_WITH_NESTED_HWVIRT_SVM_ONLY_IN_IEM
4402 Log2(("hmR0SvmPreRunGuest: Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
4403 return VINF_EM_RESCHEDULE_REM;
4404#endif
4405
4406 /* Check force flag actions that might require us to go back to ring-3. */
4407 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4408 if (rc != VINF_SUCCESS)
4409 return rc;
4410
4411 if (TRPMHasTrap(pVCpu))
4412 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4413 else if (!pVCpu->hm.s.Event.fPending)
4414 {
4415 VBOXSTRICTRC rcStrict = hmR0SvmEvaluatePendingEventNested(pVCpu, pCtx);
4416 if ( rcStrict != VINF_SUCCESS
4417 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
4418 return VBOXSTRICTRC_VAL(rcStrict);
4419 }
4420
4421 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
4422
4423 /*
4424 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4425 * Just do it in software, see @bugref{8411}.
4426 * NB: If we could continue a task switch exit we wouldn't need to do this.
4427 */
4428 if (RT_UNLIKELY( !pVM->hm.s.svm.u32Features
4429 && pVCpu->hm.s.Event.fPending
4430 && SVM_EVENT_GET_TYPE(pVCpu->hm.s.Event.u64IntInfo) == SVM_EVENT_NMI))
4431 {
4432 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4433 }
4434
4435#ifdef HMSVM_SYNC_FULL_NESTED_GUEST_STATE
4436 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4437#endif
4438
4439 /*
4440 * Load the nested-guest state.
4441 */
4442 rc = hmR0SvmLoadGuestStateNested(pVCpu, pCtx);
4443 AssertRCReturn(rc, rc);
4444 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull); /** @todo Get new STAM counter for this? */
4445
4446 /* Ensure we've cached (and hopefully modified) the VMCB for execution using hardware-assisted SVM. */
4447 Assert(pVCpu->hm.s.svm.NstGstVmcbCache.fCacheValid);
4448
4449 /*
4450 * No longjmps to ring-3 from this point on!!!
4451 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4452 * This also disables flushing of the R0-logger instance (if any).
4453 */
4454 VMMRZCallRing3Disable(pVCpu);
4455
4456 /*
4457 * We disable interrupts so that we don't miss any interrupts that would flag
4458 * preemption (IPI/timers etc.) when thread-context hooks aren't used and we've
4459 * been running with preemption disabled for a while. Since this is purly to aid
4460 * the RTThreadPreemptIsPending code, it doesn't matter that it may temporarily
4461 * reenable and disable interrupt on NT.
4462 *
4463 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4464 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4465 *
4466 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4467 * executing guest code.
4468 */
4469 pSvmTransient->fEFlags = ASMIntDisableFlags();
4470 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4471 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4472 {
4473 ASMSetFlags(pSvmTransient->fEFlags);
4474 VMMRZCallRing3Enable(pVCpu);
4475 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4476 return VINF_EM_RAW_TO_R3;
4477 }
4478 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4479 {
4480 ASMSetFlags(pSvmTransient->fEFlags);
4481 VMMRZCallRing3Enable(pVCpu);
4482 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4483 return VINF_EM_RAW_INTERRUPT;
4484 }
4485 return VINF_SUCCESS;
4486}
4487#endif
4488
4489
4490/**
4491 * Does the preparations before executing guest code in AMD-V.
4492 *
4493 * This may cause longjmps to ring-3 and may even result in rescheduling to the
4494 * recompiler. We must be cautious what we do here regarding committing
4495 * guest-state information into the VMCB assuming we assuredly execute the guest
4496 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
4497 * clearing the common-state (TRPM/forceflags), we must undo those changes so
4498 * that the recompiler can (and should) use them when it resumes guest
4499 * execution. Otherwise such operations must be done when we can no longer
4500 * exit to ring-3.
4501 *
4502 * @returns VBox status code (informational status codes included).
4503 * @retval VINF_SUCCESS if we can proceed with running the guest.
4504 * @retval VINF_* scheduling changes, we have to go back to ring-3.
4505 *
4506 * @param pVM The cross context VM structure.
4507 * @param pVCpu The cross context virtual CPU structure.
4508 * @param pCtx Pointer to the guest-CPU context.
4509 * @param pSvmTransient Pointer to the SVM transient structure.
4510 */
4511static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4512{
4513 HMSVM_ASSERT_PREEMPT_SAFE();
4514 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
4515
4516 /* Check force flag actions that might require us to go back to ring-3. */
4517 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
4518 if (rc != VINF_SUCCESS)
4519 return rc;
4520
4521 if (TRPMHasTrap(pVCpu))
4522 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
4523 else if (!pVCpu->hm.s.Event.fPending)
4524 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
4525
4526 /*
4527 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
4528 * Just do it in software, see @bugref{8411}.
4529 * NB: If we could continue a task switch exit we wouldn't need to do this.
4530 */
4531 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
4532 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
4533 return VINF_EM_RAW_INJECT_TRPM_EVENT;
4534
4535#ifdef HMSVM_SYNC_FULL_GUEST_STATE
4536 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4537#endif
4538
4539 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
4540 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
4541 AssertRCReturn(rc, rc);
4542 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
4543
4544 /*
4545 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
4546 * so we can update it on the way back if the guest changed the TPR.
4547 */
4548 if (pVCpu->hm.s.svm.fSyncVTpr)
4549 {
4550 PCSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
4551 if (pVM->hm.s.fTPRPatchingActive)
4552 pSvmTransient->u8GuestTpr = pVmcb->guest.u64LSTAR;
4553 else
4554 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
4555 }
4556
4557 /*
4558 * No longjmps to ring-3 from this point on!!!
4559 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4560 * This also disables flushing of the R0-logger instance (if any).
4561 */
4562 VMMRZCallRing3Disable(pVCpu);
4563
4564 /*
4565 * We disable interrupts so that we don't miss any interrupts that would flag
4566 * preemption (IPI/timers etc.) when thread-context hooks aren't used and we've
4567 * been running with preemption disabled for a while. Since this is purly to aid
4568 * the RTThreadPreemptIsPending code, it doesn't matter that it may temporarily
4569 * reenable and disable interrupt on NT.
4570 *
4571 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
4572 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
4573 *
4574 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
4575 * executing guest code.
4576 */
4577 pSvmTransient->fEFlags = ASMIntDisableFlags();
4578 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4579 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4580 {
4581 ASMSetFlags(pSvmTransient->fEFlags);
4582 VMMRZCallRing3Enable(pVCpu);
4583 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
4584 return VINF_EM_RAW_TO_R3;
4585 }
4586 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
4587 {
4588 ASMSetFlags(pSvmTransient->fEFlags);
4589 VMMRZCallRing3Enable(pVCpu);
4590 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
4591 return VINF_EM_RAW_INTERRUPT;
4592 }
4593
4594 return VINF_SUCCESS;
4595}
4596
4597
4598/**
4599 * Prepares to run guest (or nested-guest) code in AMD-V and we've committed to
4600 * doing so.
4601 *
4602 * This means there is no backing out to ring-3 or anywhere else at this point.
4603 *
4604 * @param pVCpu The cross context virtual CPU structure.
4605 * @param pCtx Pointer to the guest-CPU context.
4606 * @param pSvmTransient Pointer to the SVM transient structure.
4607 *
4608 * @remarks Called with preemption disabled.
4609 * @remarks No-long-jump zone!!!
4610 */
4611static void hmR0SvmPreRunGuestCommitted(PVMCPU pVCpu, PCCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4612{
4613 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4614 Assert(VMMR0IsLogFlushDisabled(pVCpu));
4615 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4616
4617 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4618 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
4619
4620 PVM pVM = pVCpu->CTX_SUFF(pVM);
4621 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4622
4623 hmR0SvmInjectPendingEvent(pVCpu, pCtx, pVmcb);
4624
4625 if (!CPUMIsGuestFPUStateActive(pVCpu))
4626 {
4627 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4628 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
4629 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
4630 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
4631 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4632 }
4633
4634 /* Load the state shared between host and guest (FPU, debug). */
4635 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
4636 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
4637
4638 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
4639 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
4640
4641 PHMGLOBALCPUINFO pHostCpu = hmR0GetCurrentCpu();
4642 RTCPUID const idHostCpu = pHostCpu->idCpu;
4643 bool const fMigratedHostCpu = idHostCpu != pVCpu->hm.s.idLastCpu;
4644
4645 /* Setup TSC offsetting. */
4646 if ( pSvmTransient->fUpdateTscOffsetting
4647 || fMigratedHostCpu)
4648 {
4649 hmR0SvmUpdateTscOffsetting(pVM, pVCpu, pCtx, pVmcb);
4650 pSvmTransient->fUpdateTscOffsetting = false;
4651 }
4652
4653 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
4654 if (fMigratedHostCpu)
4655 pVmcb->ctrl.u32VmcbCleanBits = 0;
4656
4657 /* Store status of the shared guest-host state at the time of VMRUN. */
4658#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4659 if (CPUMIsGuestInLongModeEx(pCtx))
4660 {
4661 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
4662 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
4663 }
4664 else
4665#endif
4666 {
4667 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
4668 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
4669 }
4670
4671#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4672 uint8_t *pbMsrBitmap;
4673 if (!pSvmTransient->fIsNestedGuest)
4674 pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4675 else
4676 {
4677 hmR0SvmMergeMsrpmNested(pHostCpu, pVCpu, pCtx);
4678
4679 /* Update the nested-guest VMCB with the newly merged MSRPM (clean bits updated below). */
4680 pVmcb->ctrl.u64MSRPMPhysAddr = pHostCpu->n.svm.HCPhysNstGstMsrpm;
4681 pbMsrBitmap = (uint8_t *)pHostCpu->n.svm.pvNstGstMsrpm;
4682 }
4683#else
4684 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
4685#endif
4686
4687 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
4688 /* Flush the appropriate tagged-TLB entries. */
4689 hmR0SvmFlushTaggedTlb(pVCpu, pCtx, pVmcb, pHostCpu);
4690 Assert(pVCpu->hm.s.idLastCpu == idHostCpu);
4691
4692 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
4693
4694 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
4695 to start executing. */
4696
4697 /*
4698 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
4699 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
4700 *
4701 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
4702 */
4703 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
4704 && !(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSCP))
4705 {
4706 uint64_t const uGuestTscAux = CPUMGetGuestTscAux(pVCpu);
4707 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
4708 if (uGuestTscAux != pVCpu->hm.s.u64HostTscAux)
4709 ASMWrMsr(MSR_K8_TSC_AUX, uGuestTscAux);
4710 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
4711 pSvmTransient->fRestoreTscAuxMsr = true;
4712 }
4713 else
4714 {
4715 hmR0SvmSetMsrPermission(pCtx, pbMsrBitmap, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
4716 pSvmTransient->fRestoreTscAuxMsr = false;
4717 }
4718 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
4719
4720 /*
4721 * If VMCB Clean bits isn't supported by the CPU or exposed to the guest in the
4722 * nested virtualization case, mark all state-bits as dirty indicating to the
4723 * CPU to re-load from VMCB.
4724 */
4725 bool const fSupportsVmcbCleanBits = hmR0SvmSupportsVmcbCleanBits(pVCpu, pCtx);
4726 if (!fSupportsVmcbCleanBits)
4727 pVmcb->ctrl.u32VmcbCleanBits = 0;
4728}
4729
4730
4731/**
4732 * Wrapper for running the guest code in AMD-V.
4733 *
4734 * @returns VBox strict status code.
4735 * @param pVM The cross context VM structure.
4736 * @param pVCpu The cross context virtual CPU structure.
4737 * @param pCtx Pointer to the guest-CPU context.
4738 *
4739 * @remarks No-long-jump zone!!!
4740 */
4741DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4742{
4743 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
4744 pCtx->fExtrn |= HMSVM_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
4745
4746 /*
4747 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4748 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4749 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4750 */
4751#ifdef VBOX_WITH_KERNEL_USING_XMM
4752 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4753 pVCpu->hm.s.svm.pfnVMRun);
4754#else
4755 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4756#endif
4757}
4758
4759
4760#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4761/**
4762 * Wrapper for running the nested-guest code in AMD-V.
4763 *
4764 * @returns VBox strict status code.
4765 * @param pVM The cross context VM structure.
4766 * @param pVCpu The cross context virtual CPU structure.
4767 * @param pCtx Pointer to the guest-CPU context.
4768 *
4769 * @remarks No-long-jump zone!!!
4770 */
4771DECLINLINE(int) hmR0SvmRunGuestNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4772{
4773 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
4774 pCtx->fExtrn |= HMSVM_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
4775
4776 /*
4777 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4778 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4779 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4780 */
4781#ifdef VBOX_WITH_KERNEL_USING_XMM
4782 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
4783 pVCpu->hm.s.svm.pfnVMRun);
4784#else
4785 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pCtx->hwvirt.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
4786#endif
4787}
4788
4789
4790/**
4791 * Undoes the TSC offset applied for an SVM nested-guest and returns the TSC
4792 * value for the guest.
4793 *
4794 * @returns The TSC offset after undoing any nested-guest TSC offset.
4795 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
4796 * @param uTicks The nested-guest TSC.
4797 *
4798 * @note If you make any changes to this function, please check if
4799 * hmR0SvmNstGstUndoTscOffset() needs adjusting.
4800 *
4801 * @sa HMSvmNstGstApplyTscOffset().
4802 */
4803DECLINLINE(uint64_t) hmR0SvmNstGstUndoTscOffset(PVMCPU pVCpu, uint64_t uTicks)
4804{
4805 PCSVMNESTEDVMCBCACHE pVmcbNstGstCache = &pVCpu->hm.s.svm.NstGstVmcbCache;
4806 Assert(pVmcbNstGstCache->fCacheValid);
4807 return uTicks - pVmcbNstGstCache->u64TSCOffset;
4808}
4809#endif
4810
4811/**
4812 * Performs some essential restoration of state after running guest (or
4813 * nested-guest) code in AMD-V.
4814 *
4815 * @param pVCpu The cross context virtual CPU structure.
4816 * @param pCtx Pointer to the guest-CPU context. The data maybe
4817 * out-of-sync. Make sure to update the required fields
4818 * before using them.
4819 * @param pSvmTransient Pointer to the SVM transient structure.
4820 * @param rcVMRun Return code of VMRUN.
4821 *
4822 * @remarks Called with interrupts disabled.
4823 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
4824 * unconditionally when it is safe to do so.
4825 */
4826static void hmR0SvmPostRunGuest(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
4827{
4828 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
4829
4830 uint64_t const uHostTsc = ASMReadTSC(); /* Read the TSC as soon as possible. */
4831 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
4832 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
4833
4834 PSVMVMCB pVmcb = pSvmTransient->pVmcb;
4835 PSVMVMCBCTRL pVmcbCtrl = &pVmcb->ctrl;
4836
4837 /* TSC read must be done early for maximum accuracy. */
4838 if (!(pVmcbCtrl->u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSC))
4839 {
4840 if (!pSvmTransient->fIsNestedGuest)
4841 TMCpuTickSetLastSeen(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4842#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
4843 else
4844 {
4845 /* The nested-guest VMCB TSC offset shall eventually be restored on #VMEXIT via HMSvmNstGstVmExitNotify(). */
4846 uint64_t const uGstTsc = hmR0SvmNstGstUndoTscOffset(pVCpu, uHostTsc + pVmcbCtrl->u64TSCOffset);
4847 TMCpuTickSetLastSeen(pVCpu, uGstTsc);
4848 }
4849#endif
4850 }
4851
4852 if (pSvmTransient->fRestoreTscAuxMsr)
4853 {
4854 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
4855 CPUMSetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
4856 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
4857 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
4858 }
4859
4860 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
4861 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
4862 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
4863
4864 Assert(!(ASMGetFlags() & X86_EFL_IF));
4865 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
4866 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
4867
4868 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
4869 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
4870 {
4871 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
4872 return;
4873 }
4874
4875 pSvmTransient->u64ExitCode = pVmcbCtrl->u64ExitCode; /* Save the #VMEXIT reason. */
4876 pVmcbCtrl->u32VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
4877 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
4878 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
4879
4880 hmR0SvmSaveGuestState(pVCpu, pCtx, pVmcb); /* Save the guest state from the VMCB to the guest-CPU context. */
4881
4882 if ( pSvmTransient->u64ExitCode != SVM_EXIT_INVALID
4883 && pVCpu->hm.s.svm.fSyncVTpr)
4884 {
4885 Assert(!pSvmTransient->fIsNestedGuest);
4886 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
4887 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive
4888 && (pVmcb->guest.u64LSTAR & 0xff) != pSvmTransient->u8GuestTpr)
4889 {
4890 int rc = APICSetTpr(pVCpu, pVmcb->guest.u64LSTAR & 0xff);
4891 AssertRC(rc);
4892 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4893 }
4894 /* Sync TPR when we aren't intercepting CR8 writes. */
4895 else if (pSvmTransient->u8GuestTpr != pVmcbCtrl->IntCtrl.n.u8VTPR)
4896 {
4897 int rc = APICSetTpr(pVCpu, pVmcbCtrl->IntCtrl.n.u8VTPR << 4);
4898 AssertRC(rc);
4899 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
4900 }
4901 }
4902
4903 HMSVM_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
4904 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_SVM, pSvmTransient->u64ExitCode & EMEXIT_F_TYPE_MASK),
4905 pCtx->cs.u64Base + pCtx->rip, uHostTsc);
4906}
4907
4908
4909/**
4910 * Runs the guest code using AMD-V.
4911 *
4912 * @returns VBox status code.
4913 * @param pVM The cross context VM structure.
4914 * @param pVCpu The cross context virtual CPU structure.
4915 * @param pCtx Pointer to the guest-CPU context.
4916 * @param pcLoops Pointer to the number of executed loops.
4917 */
4918static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4919{
4920 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4921 Assert(pcLoops);
4922 Assert(*pcLoops <= cMaxResumeLoops);
4923
4924 SVMTRANSIENT SvmTransient;
4925 RT_ZERO(SvmTransient);
4926 SvmTransient.fUpdateTscOffsetting = true;
4927 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
4928
4929 int rc = VERR_INTERNAL_ERROR_5;
4930 for (;;)
4931 {
4932 Assert(!HMR0SuspendPending());
4933 HMSVM_ASSERT_CPU_SAFE();
4934
4935 /* Preparatory work for running guest code, this may force us to return
4936 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
4937 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
4938 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
4939 if (rc != VINF_SUCCESS)
4940 break;
4941
4942 /*
4943 * No longjmps to ring-3 from this point on!!!
4944 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
4945 * This also disables flushing of the R0-logger instance (if any).
4946 */
4947 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
4948 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
4949
4950 /* Restore any residual host-state and save any bits shared between host
4951 and guest into the guest-CPU state. Re-enables interrupts! */
4952 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
4953
4954 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
4955 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
4956 {
4957 if (rc == VINF_SUCCESS)
4958 rc = VERR_SVM_INVALID_GUEST_STATE;
4959 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
4960 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
4961 break;
4962 }
4963
4964 /* Handle the #VMEXIT. */
4965 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
4966 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
4967 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
4968 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
4969 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
4970 if (rc != VINF_SUCCESS)
4971 break;
4972 if (++(*pcLoops) >= cMaxResumeLoops)
4973 {
4974 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
4975 rc = VINF_EM_RAW_INTERRUPT;
4976 break;
4977 }
4978 }
4979
4980 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
4981 return rc;
4982}
4983
4984
4985/**
4986 * Runs the guest code using AMD-V in single step mode.
4987 *
4988 * @returns VBox status code.
4989 * @param pVM The cross context VM structure.
4990 * @param pVCpu The cross context virtual CPU structure.
4991 * @param pCtx Pointer to the guest-CPU context.
4992 * @param pcLoops Pointer to the number of executed loops.
4993 */
4994static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
4995{
4996 uint32_t const cMaxResumeLoops = pVM->hm.s.cMaxResumeLoops;
4997 Assert(pcLoops);
4998 Assert(*pcLoops <= cMaxResumeLoops);
4999
5000 SVMTRANSIENT SvmTransient;
5001 RT_ZERO(SvmTransient);
5002 SvmTransient.fUpdateTscOffsetting = true;
5003 SvmTransient.pVmcb = pVCpu->hm.s.svm.pVmcb;
5004
5005 uint16_t uCsStart = pCtx->cs.Sel;
5006 uint64_t uRipStart = pCtx->rip;
5007
5008 int rc = VERR_INTERNAL_ERROR_5;
5009 for (;;)
5010 {
5011 Assert(!HMR0SuspendPending());
5012 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
5013 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
5014 (unsigned)RTMpCpuId(), *pcLoops));
5015
5016 /* Preparatory work for running guest code, this may force us to return
5017 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
5018 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
5019 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
5020 if (rc != VINF_SUCCESS)
5021 break;
5022
5023 /*
5024 * No longjmps to ring-3 from this point on!!!
5025 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
5026 * This also disables flushing of the R0-logger instance (if any).
5027 */
5028 VMMRZCallRing3Disable(pVCpu);
5029 VMMRZCallRing3RemoveNotification(pVCpu);
5030 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
5031
5032 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
5033
5034 /*
5035 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
5036 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
5037 */
5038 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
5039 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
5040 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
5041 {
5042 if (rc == VINF_SUCCESS)
5043 rc = VERR_SVM_INVALID_GUEST_STATE;
5044 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
5045 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
5046 return rc;
5047 }
5048
5049 /* Handle the #VMEXIT. */
5050 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
5051 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
5052 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pVCpu->hm.s.svm.pVmcb);
5053 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
5054 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
5055 if (rc != VINF_SUCCESS)
5056 break;
5057 if (++(*pcLoops) >= cMaxResumeLoops)
5058 {
5059 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
5060 rc = VINF_EM_RAW_INTERRUPT;
5061 break;
5062 }
5063
5064 /*
5065 * Did the RIP change, if so, consider it a single step.
5066 * Otherwise, make sure one of the TFs gets set.
5067 */
5068 if ( pCtx->rip != uRipStart
5069 || pCtx->cs.Sel != uCsStart)
5070 {
5071 rc = VINF_EM_DBG_STEPPED;
5072 break;
5073 }
5074 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
5075 }
5076
5077 /*
5078 * Clear the X86_EFL_TF if necessary.
5079 */
5080 if (pVCpu->hm.s.fClearTrapFlag)
5081 {
5082 pVCpu->hm.s.fClearTrapFlag = false;
5083 pCtx->eflags.Bits.u1TF = 0;
5084 }
5085
5086 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
5087 return rc;
5088}
5089
5090#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5091/**
5092 * Runs the nested-guest code using AMD-V.
5093 *
5094 * @returns VBox status code.
5095 * @param pVM The cross context VM structure.
5096 * @param pVCpu The cross context virtual CPU structure.
5097 * @param pCtx Pointer to the guest-CPU context.
5098 * @param pcLoops Pointer to the number of executed loops. If we're switching
5099 * from the guest-code execution loop to this nested-guest
5100 * execution loop pass the remainder value, else pass 0.
5101 */
5102static int hmR0SvmRunGuestCodeNested(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t *pcLoops)
5103{
5104 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5105 Assert(pcLoops);
5106 Assert(*pcLoops <= pVM->hm.s.cMaxResumeLoops);
5107
5108 SVMTRANSIENT SvmTransient;
5109 RT_ZERO(SvmTransient);
5110 SvmTransient.fUpdateTscOffsetting = true;
5111 SvmTransient.pVmcb = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5112 SvmTransient.fIsNestedGuest = true;
5113
5114 int rc = VERR_INTERNAL_ERROR_4;
5115 for (;;)
5116 {
5117 Assert(!HMR0SuspendPending());
5118 HMSVM_ASSERT_CPU_SAFE();
5119
5120 /* Preparatory work for running nested-guest code, this may force us to return
5121 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
5122 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
5123 rc = hmR0SvmPreRunGuestNested(pVM, pVCpu, pCtx, &SvmTransient);
5124 if ( rc != VINF_SUCCESS
5125 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5126 {
5127 break;
5128 }
5129
5130 /*
5131 * No longjmps to ring-3 from this point on!!!
5132 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
5133 * This also disables flushing of the R0-logger instance (if any).
5134 */
5135 hmR0SvmPreRunGuestCommitted(pVCpu, pCtx, &SvmTransient);
5136
5137 rc = hmR0SvmRunGuestNested(pVM, pVCpu, pCtx);
5138
5139 /* Restore any residual host-state and save any bits shared between host
5140 and guest into the guest-CPU state. Re-enables interrupts! */
5141 hmR0SvmPostRunGuest(pVCpu, pCtx, &SvmTransient, rc);
5142
5143 if (RT_LIKELY( rc == VINF_SUCCESS
5144 && SvmTransient.u64ExitCode != SVM_EXIT_INVALID))
5145 { /* extremely likely */ }
5146 else
5147 {
5148 /* VMRUN failed, shouldn't really happen, Guru. */
5149 if (rc != VINF_SUCCESS)
5150 break;
5151
5152 /* Invalid nested-guest state. Cause a #VMEXIT but assert on strict builds. */
5153 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
5154 AssertMsgFailed(("Invalid nested-guest state. rc=%Rrc u64ExitCode=%#RX64\n", rc, SvmTransient.u64ExitCode));
5155 rc = VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_INVALID, 0, 0));
5156 break;
5157 }
5158
5159 /* Handle the #VMEXIT. */
5160 HMSVM_NESTED_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
5161 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
5162 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, pCtx->hwvirt.svm.CTX_SUFF(pVmcb));
5163 rc = hmR0SvmHandleExitNested(pVCpu, pCtx, &SvmTransient);
5164 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
5165 if ( rc != VINF_SUCCESS
5166 || !CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5167 break;
5168 if (++(*pcLoops) >= pVM->hm.s.cMaxResumeLoops)
5169 {
5170 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
5171 rc = VINF_EM_RAW_INTERRUPT;
5172 break;
5173 }
5174
5175 /** @todo handle single-stepping */
5176 }
5177
5178 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
5179 return rc;
5180}
5181#endif
5182
5183
5184/**
5185 * Runs the guest code using AMD-V.
5186 *
5187 * @returns Strict VBox status code.
5188 * @param pVM The cross context VM structure.
5189 * @param pVCpu The cross context virtual CPU structure.
5190 * @param pCtx Pointer to the guest-CPU context.
5191 */
5192VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5193{
5194 Assert(VMMRZCallRing3IsEnabled(pVCpu));
5195 HMSVM_ASSERT_PREEMPT_SAFE();
5196 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
5197
5198 uint32_t cLoops = 0;
5199 int rc;
5200#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5201 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
5202#endif
5203 {
5204 if (!pVCpu->hm.s.fSingleInstruction)
5205 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx, &cLoops);
5206 else
5207 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx, &cLoops);
5208 }
5209#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5210 else
5211 {
5212 rc = VINF_SVM_VMRUN;
5213 }
5214
5215 /* Re-check the nested-guest condition here as we may be transitioning from the normal
5216 execution loop into the nested-guest, hence this is not placed in the 'else' part above. */
5217 if (rc == VINF_SVM_VMRUN)
5218 {
5219 rc = hmR0SvmRunGuestCodeNested(pVM, pVCpu, pCtx, &cLoops);
5220 if (rc == VINF_SVM_VMEXIT)
5221 rc = VINF_SUCCESS;
5222 }
5223#endif
5224
5225 /* Fixup error codes. */
5226 if (rc == VERR_EM_INTERPRETER)
5227 rc = VINF_EM_RAW_EMULATE_INSTR;
5228 else if (rc == VINF_EM_RESET)
5229 rc = VINF_EM_TRIPLE_FAULT;
5230
5231 /* Prepare to return to ring-3. This will remove longjmp notifications. */
5232 rc = hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
5233 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
5234 return rc;
5235}
5236
5237
5238#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5239/**
5240 * Determines whether an IOIO intercept is active for the nested-guest or not.
5241 *
5242 * @param pvIoBitmap Pointer to the nested-guest IO bitmap.
5243 * @param pIoExitInfo Pointer to the SVMIOIOEXITINFO.
5244 */
5245static bool hmR0SvmIsIoInterceptActive(void *pvIoBitmap, PSVMIOIOEXITINFO pIoExitInfo)
5246{
5247 const uint16_t u16Port = pIoExitInfo->n.u16Port;
5248 const SVMIOIOTYPE enmIoType = (SVMIOIOTYPE)pIoExitInfo->n.u1Type;
5249 const uint8_t cbReg = (pIoExitInfo->u >> SVM_IOIO_OP_SIZE_SHIFT) & 7;
5250 const uint8_t cAddrSizeBits = ((pIoExitInfo->u >> SVM_IOIO_ADDR_SIZE_SHIFT) & 7) << 4;
5251 const uint8_t iEffSeg = pIoExitInfo->n.u3Seg;
5252 const bool fRep = pIoExitInfo->n.u1Rep;
5253 const bool fStrIo = pIoExitInfo->n.u1Str;
5254
5255 return HMSvmIsIOInterceptActive(pvIoBitmap, u16Port, enmIoType, cbReg, cAddrSizeBits, iEffSeg, fRep, fStrIo,
5256 NULL /* pIoExitInfo */);
5257}
5258
5259
5260/**
5261 * Handles a nested-guest \#VMEXIT (for all EXITCODE values except
5262 * SVM_EXIT_INVALID).
5263 *
5264 * @returns VBox status code (informational status codes included).
5265 * @param pVCpu The cross context virtual CPU structure.
5266 * @param pCtx Pointer to the guest-CPU context.
5267 * @param pSvmTransient Pointer to the SVM transient structure.
5268 */
5269static int hmR0SvmHandleExitNested(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5270{
5271 HMSVM_ASSERT_IN_NESTED_GUEST(pCtx);
5272 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5273 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5274
5275 /** @todo Use IEM_CPUMCTX_EXTRN_SVM_VMEXIT_MASK instead of
5276 * HMSVM_CPUMCTX_EXTRN_ALL below. See todo in
5277 * HMSvmNstGstVmExitNotify(). */
5278#define NST_GST_VMEXIT_CALL_RET(a_pVCpu, a_pCtx, a_uExitCode, a_uExitInfo1, a_uExitInfo2) \
5279 do { \
5280 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL); \
5281 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit((a_pVCpu), (a_uExitCode), (a_uExitInfo1), (a_uExitInfo2))); \
5282 } while (0)
5283
5284 /*
5285 * For all the #VMEXITs here we primarily figure out if the #VMEXIT is expected
5286 * by the nested-guest. If it isn't, it should be handled by the (outer) guest.
5287 */
5288 PSVMVMCB pVmcbNstGst = pCtx->hwvirt.svm.CTX_SUFF(pVmcb);
5289 PSVMVMCBCTRL pVmcbNstGstCtrl = &pVmcbNstGst->ctrl;
5290 uint64_t const uExitCode = pVmcbNstGstCtrl->u64ExitCode;
5291 uint64_t const uExitInfo1 = pVmcbNstGstCtrl->u64ExitInfo1;
5292 uint64_t const uExitInfo2 = pVmcbNstGstCtrl->u64ExitInfo2;
5293
5294 Assert(uExitCode == pVmcbNstGstCtrl->u64ExitCode);
5295 switch (uExitCode)
5296 {
5297 case SVM_EXIT_CPUID:
5298 {
5299 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CPUID))
5300 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5301 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
5302 }
5303
5304 case SVM_EXIT_RDTSC:
5305 {
5306 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDTSC))
5307 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5308 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
5309 }
5310
5311 case SVM_EXIT_RDTSCP:
5312 {
5313 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDTSCP))
5314 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5315 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
5316 }
5317
5318 case SVM_EXIT_MONITOR:
5319 {
5320 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MONITOR))
5321 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5322 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
5323 }
5324
5325 case SVM_EXIT_MWAIT:
5326 {
5327 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MWAIT))
5328 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5329 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
5330 }
5331
5332 case SVM_EXIT_HLT:
5333 {
5334 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_HLT))
5335 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5336 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
5337 }
5338
5339 case SVM_EXIT_MSR:
5340 {
5341 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_MSR_PROT))
5342 {
5343 uint32_t const idMsr = pCtx->ecx;
5344 uint16_t offMsrpm;
5345 uint8_t uMsrpmBit;
5346 int rc = HMSvmGetMsrpmOffsetAndBit(idMsr, &offMsrpm, &uMsrpmBit);
5347 if (RT_SUCCESS(rc))
5348 {
5349 Assert(uMsrpmBit == 0 || uMsrpmBit == 2 || uMsrpmBit == 4 || uMsrpmBit == 6);
5350 Assert(offMsrpm < SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT);
5351
5352 uint8_t const *pbMsrBitmap = (uint8_t const *)pCtx->hwvirt.svm.CTX_SUFF(pvMsrBitmap);
5353 pbMsrBitmap += offMsrpm;
5354 bool const fInterceptRead = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit));
5355 bool const fInterceptWrite = RT_BOOL(*pbMsrBitmap & RT_BIT(uMsrpmBit + 1));
5356
5357 if ( (fInterceptWrite && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
5358 || (fInterceptRead && pVmcbNstGstCtrl->u64ExitInfo1 == SVM_EXIT1_MSR_READ))
5359 {
5360 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5361 }
5362 }
5363 else
5364 {
5365 /*
5366 * MSRs not covered by the MSRPM automatically cause an #VMEXIT.
5367 * See AMD-V spec. "15.11 MSR Intercepts".
5368 */
5369 Assert(rc == VERR_OUT_OF_RANGE);
5370 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5371 }
5372 }
5373 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
5374 }
5375
5376 case SVM_EXIT_IOIO:
5377 {
5378 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_IOIO_PROT))
5379 {
5380 void *pvIoBitmap = pCtx->hwvirt.svm.CTX_SUFF(pvIoBitmap);
5381 SVMIOIOEXITINFO IoExitInfo;
5382 IoExitInfo.u = pVmcbNstGst->ctrl.u64ExitInfo1;
5383 bool const fIntercept = hmR0SvmIsIoInterceptActive(pvIoBitmap, &IoExitInfo);
5384 if (fIntercept)
5385 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5386 }
5387 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
5388 }
5389
5390 case SVM_EXIT_XCPT_PF:
5391 {
5392 PVM pVM = pVCpu->CTX_SUFF(pVM);
5393 if (pVM->hm.s.fNestedPaging)
5394 {
5395 uint32_t const u32ErrCode = pVmcbNstGstCtrl->u64ExitInfo1;
5396 uint64_t const uFaultAddress = pVmcbNstGstCtrl->u64ExitInfo2;
5397
5398 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
5399 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_PF))
5400 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, u32ErrCode, uFaultAddress);
5401
5402 /* If the nested-guest is not intercepting #PFs, forward the #PF to the guest. */
5403 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR2);
5404 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5405 return VINF_SUCCESS;
5406 }
5407 return hmR0SvmExitXcptPF(pVCpu, pCtx,pSvmTransient);
5408 }
5409
5410 case SVM_EXIT_XCPT_UD:
5411 {
5412 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_UD))
5413 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5414 hmR0SvmSetPendingXcptUD(pVCpu);
5415 return VINF_SUCCESS;
5416 }
5417
5418 case SVM_EXIT_XCPT_MF:
5419 {
5420 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_MF))
5421 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5422 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
5423 }
5424
5425 case SVM_EXIT_XCPT_DB:
5426 {
5427 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_DB))
5428 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5429 return hmR0SvmNestedExitXcptDB(pVCpu, pCtx, pSvmTransient);
5430 }
5431
5432 case SVM_EXIT_XCPT_AC:
5433 {
5434 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_AC))
5435 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5436 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
5437 }
5438
5439 case SVM_EXIT_XCPT_BP:
5440 {
5441 if (HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_BP))
5442 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5443 return hmR0SvmNestedExitXcptBP(pVCpu, pCtx, pSvmTransient);
5444 }
5445
5446 case SVM_EXIT_READ_CR0:
5447 case SVM_EXIT_READ_CR3:
5448 case SVM_EXIT_READ_CR4:
5449 {
5450 uint8_t const uCr = uExitCode - SVM_EXIT_READ_CR0;
5451 if (HMIsGuestSvmReadCRxInterceptSet(pVCpu, uCr))
5452 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5453 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
5454 }
5455
5456 case SVM_EXIT_CR0_SEL_WRITE:
5457 {
5458 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CR0_SEL_WRITE))
5459 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5460 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5461 }
5462
5463 case SVM_EXIT_WRITE_CR0:
5464 case SVM_EXIT_WRITE_CR3:
5465 case SVM_EXIT_WRITE_CR4:
5466 case SVM_EXIT_WRITE_CR8: /** @todo Shouldn't writes to CR8 go to V_TPR instead since we run with V_INTR_MASKING set? */
5467 {
5468 uint8_t const uCr = uExitCode - SVM_EXIT_WRITE_CR0;
5469 Log4(("hmR0SvmHandleExitNested: Write CR%u: uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", uCr, uExitInfo1, uExitInfo2));
5470
5471 if (HMIsGuestSvmWriteCRxInterceptSet(pVCpu, uCr))
5472 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5473 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
5474 }
5475
5476 case SVM_EXIT_PAUSE:
5477 {
5478 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_PAUSE))
5479 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5480 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
5481 }
5482
5483 case SVM_EXIT_VINTR:
5484 {
5485 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VINTR))
5486 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5487 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5488 }
5489
5490 case SVM_EXIT_INTR:
5491 case SVM_EXIT_NMI:
5492 case SVM_EXIT_SMI:
5493 case SVM_EXIT_XCPT_NMI: /* Should not occur, SVM_EXIT_NMI is used instead. */
5494 {
5495 /*
5496 * We shouldn't direct physical interrupts, NMIs, SMIs to the nested-guest.
5497 *
5498 * Although we don't intercept SMIs, the nested-guest might. Therefore, we
5499 * might get an SMI #VMEXIT here so simply ignore rather than causing a
5500 * corresponding nested-guest #VMEXIT.
5501 */
5502 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
5503 }
5504
5505 case SVM_EXIT_FERR_FREEZE:
5506 {
5507 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_FERR_FREEZE))
5508 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5509 return hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient);
5510 }
5511
5512 case SVM_EXIT_INVLPG:
5513 {
5514 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVLPG))
5515 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5516 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
5517 }
5518
5519 case SVM_EXIT_WBINVD:
5520 {
5521 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_WBINVD))
5522 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5523 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
5524 }
5525
5526 case SVM_EXIT_INVD:
5527 {
5528 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVD))
5529 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5530 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
5531 }
5532
5533 case SVM_EXIT_RDPMC:
5534 {
5535 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RDPMC))
5536 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5537 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
5538 }
5539
5540 default:
5541 {
5542 switch (uExitCode)
5543 {
5544 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5545 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5546 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5547 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5548 {
5549 uint8_t const uDr = uExitCode - SVM_EXIT_READ_DR0;
5550 if (HMIsGuestSvmReadDRxInterceptSet(pVCpu, uDr))
5551 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5552 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
5553 }
5554
5555 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5556 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5557 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5558 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5559 {
5560 uint8_t const uDr = uExitCode - SVM_EXIT_WRITE_DR0;
5561 if (HMIsGuestSvmWriteDRxInterceptSet(pVCpu, uDr))
5562 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5563 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
5564 }
5565
5566 case SVM_EXIT_XCPT_0: /* #DE */
5567 /* SVM_EXIT_XCPT_1: */ /* #DB - Handled above. */
5568 /* SVM_EXIT_XCPT_2: */ /* #NMI - Handled above. */
5569 /* SVM_EXIT_XCPT_3: */ /* #BP - Handled above. */
5570 case SVM_EXIT_XCPT_4: /* #OF */
5571 case SVM_EXIT_XCPT_5: /* #BR */
5572 /* SVM_EXIT_XCPT_6: */ /* #UD - Handled above. */
5573 case SVM_EXIT_XCPT_7: /* #NM */
5574 case SVM_EXIT_XCPT_8: /* #DF */
5575 case SVM_EXIT_XCPT_9: /* #CO_SEG_OVERRUN */
5576 case SVM_EXIT_XCPT_10: /* #TS */
5577 case SVM_EXIT_XCPT_11: /* #NP */
5578 case SVM_EXIT_XCPT_12: /* #SS */
5579 case SVM_EXIT_XCPT_13: /* #GP */
5580 /* SVM_EXIT_XCPT_14: */ /* #PF - Handled above. */
5581 case SVM_EXIT_XCPT_15: /* Reserved. */
5582 /* SVM_EXIT_XCPT_16: */ /* #MF - Handled above. */
5583 /* SVM_EXIT_XCPT_17: */ /* #AC - Handled above. */
5584 case SVM_EXIT_XCPT_18: /* #MC */
5585 case SVM_EXIT_XCPT_19: /* #XF */
5586 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5587 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5588 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5589 {
5590 uint8_t const uVector = uExitCode - SVM_EXIT_XCPT_0;
5591 if (HMIsGuestSvmXcptInterceptSet(pVCpu, uVector))
5592 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5593 return hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient);
5594 }
5595
5596 case SVM_EXIT_XSETBV:
5597 {
5598 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_XSETBV))
5599 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5600 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
5601 }
5602
5603 case SVM_EXIT_TASK_SWITCH:
5604 {
5605 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_TASK_SWITCH))
5606 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5607 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
5608 }
5609
5610 case SVM_EXIT_IRET:
5611 {
5612 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_IRET))
5613 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5614 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
5615 }
5616
5617 case SVM_EXIT_SHUTDOWN:
5618 {
5619 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_SHUTDOWN))
5620 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5621 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
5622 }
5623
5624 case SVM_EXIT_VMMCALL:
5625 {
5626 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMMCALL))
5627 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5628 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
5629 }
5630
5631 case SVM_EXIT_CLGI:
5632 {
5633 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_CLGI))
5634 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5635 return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
5636 }
5637
5638 case SVM_EXIT_STGI:
5639 {
5640 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_STGI))
5641 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5642 return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
5643 }
5644
5645 case SVM_EXIT_VMLOAD:
5646 {
5647 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMLOAD))
5648 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5649 return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
5650 }
5651
5652 case SVM_EXIT_VMSAVE:
5653 {
5654 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMSAVE))
5655 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5656 return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
5657 }
5658
5659 case SVM_EXIT_INVLPGA:
5660 {
5661 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_INVLPGA))
5662 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5663 return hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient);
5664 }
5665
5666 case SVM_EXIT_VMRUN:
5667 {
5668 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_VMRUN))
5669 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5670 return hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient);
5671 }
5672
5673 case SVM_EXIT_RSM:
5674 {
5675 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_RSM))
5676 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5677 hmR0SvmSetPendingXcptUD(pVCpu);
5678 return VINF_SUCCESS;
5679 }
5680
5681 case SVM_EXIT_SKINIT:
5682 {
5683 if (HMIsGuestSvmCtrlInterceptSet(pVCpu, SVM_CTRL_INTERCEPT_SKINIT))
5684 NST_GST_VMEXIT_CALL_RET(pVCpu, pCtx, uExitCode, uExitInfo1, uExitInfo2);
5685 hmR0SvmSetPendingXcptUD(pVCpu);
5686 return VINF_SUCCESS;
5687 }
5688
5689 case SVM_EXIT_NPF:
5690 {
5691 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5692 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
5693 }
5694
5695 case SVM_EXIT_INIT: /* We shouldn't get INIT signals while executing a nested-guest. */
5696 return hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient);
5697
5698 default:
5699 {
5700 AssertMsgFailed(("hmR0SvmHandleExitNested: Unknown exit code %#x\n", pSvmTransient->u64ExitCode));
5701 pVCpu->hm.s.u32HMError = pSvmTransient->u64ExitCode;
5702 return VERR_SVM_UNKNOWN_EXIT;
5703 }
5704 }
5705 }
5706 }
5707 /* not reached */
5708
5709#undef NST_GST_VMEXIT_CALL_RET
5710}
5711#endif
5712
5713
5714/**
5715 * Handles a guest \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
5716 *
5717 * @returns VBox status code (informational status codes included).
5718 * @param pVCpu The cross context virtual CPU structure.
5719 * @param pCtx Pointer to the guest-CPU context.
5720 * @param pSvmTransient Pointer to the SVM transient structure.
5721 */
5722static int hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5723{
5724 Assert(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID);
5725 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
5726
5727#ifdef DEBUG_ramshankar
5728# define VMEXIT_CALL_RET(a_fDbg, a_CallExpr) \
5729 do { \
5730 if ((a_fDbg) == 1) \
5731 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL); \
5732 int rc = a_CallExpr; \
5733 /* if ((a_fDbg) == 1) */ \
5734 /* HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST); */ \
5735 return rc; \
5736 } while (0)
5737#else
5738# define VMEXIT_CALL_RET(a_fDbg, a_CallExpr) return a_CallExpr
5739#endif
5740
5741 /*
5742 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs
5743 * for most guests under normal workloads (for some definition of "normal").
5744 */
5745 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
5746 switch (uExitCode)
5747 {
5748 case SVM_EXIT_NPF: VMEXIT_CALL_RET(0, hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient));
5749 case SVM_EXIT_IOIO: VMEXIT_CALL_RET(0, hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient));
5750 case SVM_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient));
5751 case SVM_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient));
5752 case SVM_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient));
5753 case SVM_EXIT_XCPT_PF: VMEXIT_CALL_RET(0, hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient));
5754 case SVM_EXIT_MSR: VMEXIT_CALL_RET(0, hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient));
5755 case SVM_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient));
5756 case SVM_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient));
5757 case SVM_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient));
5758
5759 case SVM_EXIT_XCPT_NMI: /* Should not occur, SVM_EXIT_NMI is used instead. */
5760 case SVM_EXIT_INTR:
5761 case SVM_EXIT_NMI: VMEXIT_CALL_RET(0, hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient));
5762
5763 case SVM_EXIT_READ_CR0:
5764 case SVM_EXIT_READ_CR3:
5765 case SVM_EXIT_READ_CR4: VMEXIT_CALL_RET(0, hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient));
5766
5767 case SVM_EXIT_CR0_SEL_WRITE:
5768 case SVM_EXIT_WRITE_CR0:
5769 case SVM_EXIT_WRITE_CR3:
5770 case SVM_EXIT_WRITE_CR4:
5771 case SVM_EXIT_WRITE_CR8: VMEXIT_CALL_RET(0, hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient));
5772
5773 case SVM_EXIT_VINTR: VMEXIT_CALL_RET(0, hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient));
5774 case SVM_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient));
5775 case SVM_EXIT_VMMCALL: VMEXIT_CALL_RET(0, hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient));
5776 case SVM_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient));
5777 case SVM_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient));
5778 case SVM_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient));
5779 case SVM_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient));
5780 case SVM_EXIT_IRET: VMEXIT_CALL_RET(0, hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient));
5781 case SVM_EXIT_XCPT_UD: VMEXIT_CALL_RET(0, hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient));
5782 case SVM_EXIT_XCPT_MF: VMEXIT_CALL_RET(0, hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient));
5783 case SVM_EXIT_XCPT_DB: VMEXIT_CALL_RET(0, hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient));
5784 case SVM_EXIT_XCPT_AC: VMEXIT_CALL_RET(0, hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient));
5785 case SVM_EXIT_XCPT_BP: VMEXIT_CALL_RET(0, hmR0SvmExitXcptBP(pVCpu, pCtx, pSvmTransient));
5786 case SVM_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient));
5787 case SVM_EXIT_FERR_FREEZE: VMEXIT_CALL_RET(0, hmR0SvmExitFerrFreeze(pVCpu, pCtx, pSvmTransient));
5788
5789 default:
5790 {
5791 switch (pSvmTransient->u64ExitCode)
5792 {
5793 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
5794 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
5795 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
5796 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
5797 VMEXIT_CALL_RET(0, hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient));
5798
5799 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
5800 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
5801 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
5802 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
5803 VMEXIT_CALL_RET(0, hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient));
5804
5805 case SVM_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient));
5806 case SVM_EXIT_SHUTDOWN: VMEXIT_CALL_RET(0, hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient));
5807
5808 case SVM_EXIT_SMI:
5809 case SVM_EXIT_INIT:
5810 {
5811 /*
5812 * We don't intercept SMIs. As for INIT signals, it really shouldn't ever happen here.
5813 * If it ever does, we want to know about it so log the exit code and bail.
5814 */
5815 VMEXIT_CALL_RET(0, hmR0SvmExitUnexpected(pVCpu, pCtx, pSvmTransient));
5816 }
5817
5818#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
5819 case SVM_EXIT_CLGI: VMEXIT_CALL_RET(0, hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient));
5820 case SVM_EXIT_STGI: VMEXIT_CALL_RET(0, hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient));
5821 case SVM_EXIT_VMLOAD: VMEXIT_CALL_RET(0, hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient));
5822 case SVM_EXIT_VMSAVE: VMEXIT_CALL_RET(0, hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient));
5823 case SVM_EXIT_INVLPGA: VMEXIT_CALL_RET(0, hmR0SvmExitInvlpga(pVCpu, pCtx, pSvmTransient));
5824 case SVM_EXIT_VMRUN: VMEXIT_CALL_RET(0, hmR0SvmExitVmrun(pVCpu, pCtx, pSvmTransient));
5825#else
5826 case SVM_EXIT_CLGI:
5827 case SVM_EXIT_STGI:
5828 case SVM_EXIT_VMLOAD:
5829 case SVM_EXIT_VMSAVE:
5830 case SVM_EXIT_INVLPGA:
5831 case SVM_EXIT_VMRUN:
5832#endif
5833 case SVM_EXIT_RSM:
5834 case SVM_EXIT_SKINIT:
5835 {
5836 hmR0SvmSetPendingXcptUD(pVCpu);
5837 return VINF_SUCCESS;
5838 }
5839
5840#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5841 case SVM_EXIT_XCPT_DE:
5842 /* SVM_EXIT_XCPT_DB: */ /* Handled above. */
5843 /* SVM_EXIT_XCPT_NMI: */ /* Handled above. */
5844 /* SVM_EXIT_XCPT_BP: */ /* Handled above. */
5845 case SVM_EXIT_XCPT_OF:
5846 case SVM_EXIT_XCPT_BR:
5847 /* SVM_EXIT_XCPT_UD: */ /* Handled above. */
5848 case SVM_EXIT_XCPT_NM:
5849 case SVM_EXIT_XCPT_DF:
5850 case SVM_EXIT_XCPT_CO_SEG_OVERRUN:
5851 case SVM_EXIT_XCPT_TS:
5852 case SVM_EXIT_XCPT_NP:
5853 case SVM_EXIT_XCPT_SS:
5854 case SVM_EXIT_XCPT_GP:
5855 /* SVM_EXIT_XCPT_PF: */
5856 case SVM_EXIT_XCPT_15: /* Reserved. */
5857 /* SVM_EXIT_XCPT_MF: */ /* Handled above. */
5858 /* SVM_EXIT_XCPT_AC: */ /* Handled above. */
5859 case SVM_EXIT_XCPT_MC:
5860 case SVM_EXIT_XCPT_XF:
5861 case SVM_EXIT_XCPT_20: case SVM_EXIT_XCPT_21: case SVM_EXIT_XCPT_22: case SVM_EXIT_XCPT_23:
5862 case SVM_EXIT_XCPT_24: case SVM_EXIT_XCPT_25: case SVM_EXIT_XCPT_26: case SVM_EXIT_XCPT_27:
5863 case SVM_EXIT_XCPT_28: case SVM_EXIT_XCPT_29: case SVM_EXIT_XCPT_30: case SVM_EXIT_XCPT_31:
5864 VMEXIT_CALL_RET(0, hmR0SvmExitXcptGeneric(pVCpu, pCtx, pSvmTransient));
5865#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
5866
5867 default:
5868 {
5869 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#RX64\n", uExitCode));
5870 pVCpu->hm.s.u32HMError = uExitCode;
5871 return VERR_SVM_UNKNOWN_EXIT;
5872 }
5873 }
5874 }
5875 }
5876 /* not reached */
5877#undef VMEXIT_CALL_RET
5878}
5879
5880
5881#ifdef DEBUG
5882/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
5883# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
5884 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
5885
5886# define HMSVM_ASSERT_PREEMPT_CPUID() \
5887 do \
5888 { \
5889 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
5890 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
5891 } while (0)
5892
5893# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
5894 do { \
5895 AssertPtr(pVCpu); \
5896 AssertPtr(pCtx); \
5897 AssertPtr(pSvmTransient); \
5898 Assert(ASMIntAreEnabled()); \
5899 HMSVM_ASSERT_PREEMPT_SAFE(); \
5900 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
5901 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)); \
5902 HMSVM_ASSERT_PREEMPT_SAFE(); \
5903 if (VMMR0IsLogFlushDisabled(pVCpu)) \
5904 HMSVM_ASSERT_PREEMPT_CPUID(); \
5905 } while (0)
5906#else /* Release builds */
5907# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
5908#endif
5909
5910
5911/**
5912 * Worker for hmR0SvmInterpretInvlpg().
5913 *
5914 * @return VBox status code.
5915 * @param pVCpu The cross context virtual CPU structure.
5916 * @param pCpu Pointer to the disassembler state.
5917 * @param pCtx The guest CPU context.
5918 */
5919static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
5920{
5921 DISQPVPARAMVAL Param1;
5922 RTGCPTR GCPtrPage;
5923
5924 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
5925 if (RT_FAILURE(rc))
5926 return VERR_EM_INTERPRETER;
5927
5928 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
5929 || Param1.type == DISQPV_TYPE_ADDRESS)
5930 {
5931 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
5932 return VERR_EM_INTERPRETER;
5933
5934 GCPtrPage = Param1.val.val64;
5935 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
5936 rc = VBOXSTRICTRC_VAL(rc2);
5937 }
5938 else
5939 {
5940 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
5941 rc = VERR_EM_INTERPRETER;
5942 }
5943
5944 return rc;
5945}
5946
5947
5948/**
5949 * Interprets INVLPG.
5950 *
5951 * @returns VBox status code.
5952 * @retval VINF_* Scheduling instructions.
5953 * @retval VERR_EM_INTERPRETER Something we can't cope with.
5954 * @retval VERR_* Fatal errors.
5955 *
5956 * @param pVM The cross context VM structure.
5957 * @param pVCpu The cross context virtual CPU structure.
5958 * @param pCtx The guest CPU context.
5959 *
5960 * @remarks Updates the RIP if the instruction was executed successfully.
5961 */
5962static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5963{
5964 /* Only allow 32 & 64 bit code. */
5965 if (CPUMGetGuestCodeBits(pVCpu) != 16)
5966 {
5967 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5968 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
5969 if ( RT_SUCCESS(rc)
5970 && pDis->pCurInstr->uOpcode == OP_INVLPG)
5971 {
5972 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
5973 if (RT_SUCCESS(rc))
5974 pCtx->rip += pDis->cbInstr;
5975 return rc;
5976 }
5977 else
5978 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5979 }
5980 return VERR_EM_INTERPRETER;
5981}
5982
5983
5984#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
5985/**
5986 * Gets the IEM exception flags for the specified SVM event.
5987 *
5988 * @returns The IEM exception flags.
5989 * @param pEvent Pointer to the SVM event.
5990 *
5991 * @remarks This function currently only constructs flags required for
5992 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g. error-code
5993 * and CR2 aspects of an exception are not included).
5994 */
5995static uint32_t hmR0SvmGetIemXcptFlags(PCSVMEVENT pEvent)
5996{
5997 uint8_t const uEventType = pEvent->n.u3Type;
5998 uint32_t fIemXcptFlags;
5999 switch (uEventType)
6000 {
6001 case SVM_EVENT_EXCEPTION:
6002 /*
6003 * Only INT3 and INTO instructions can raise #BP and #OF exceptions.
6004 * See AMD spec. Table 8-1. "Interrupt Vector Source and Cause".
6005 */
6006 if (pEvent->n.u8Vector == X86_XCPT_BP)
6007 {
6008 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_BP_INSTR;
6009 break;
6010 }
6011 if (pEvent->n.u8Vector == X86_XCPT_OF)
6012 {
6013 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_OF_INSTR;
6014 break;
6015 }
6016 /** @todo How do we distinguish ICEBP \#DB from the regular one? */
6017 RT_FALL_THRU();
6018 case SVM_EVENT_NMI:
6019 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6020 break;
6021
6022 case SVM_EVENT_EXTERNAL_IRQ:
6023 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
6024 break;
6025
6026 case SVM_EVENT_SOFTWARE_INT:
6027 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6028 break;
6029
6030 default:
6031 fIemXcptFlags = 0;
6032 AssertMsgFailed(("Unexpected event type! uEventType=%#x uVector=%#x", uEventType, pEvent->n.u8Vector));
6033 break;
6034 }
6035 return fIemXcptFlags;
6036}
6037
6038#else
6039/**
6040 * Determines if an exception is a contributory exception.
6041 *
6042 * Contributory exceptions are ones which can cause double-faults unless the
6043 * original exception was a benign exception. Page-fault is intentionally not
6044 * included here as it's a conditional contributory exception.
6045 *
6046 * @returns @c true if the exception is contributory, @c false otherwise.
6047 * @param uVector The exception vector.
6048 */
6049DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
6050{
6051 switch (uVector)
6052 {
6053 case X86_XCPT_GP:
6054 case X86_XCPT_SS:
6055 case X86_XCPT_NP:
6056 case X86_XCPT_TS:
6057 case X86_XCPT_DE:
6058 return true;
6059 default:
6060 break;
6061 }
6062 return false;
6063}
6064#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
6065
6066
6067/**
6068 * Handle a condition that occurred while delivering an event through the guest
6069 * IDT.
6070 *
6071 * @returns VBox status code (informational error codes included).
6072 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
6073 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
6074 * continue execution of the guest which will delivery the \#DF.
6075 * @retval VINF_EM_RESET if we detected a triple-fault condition.
6076 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
6077 *
6078 * @param pVCpu The cross context virtual CPU structure.
6079 * @param pCtx Pointer to the guest-CPU context.
6080 * @param pSvmTransient Pointer to the SVM transient structure.
6081 *
6082 * @remarks No-long-jump zone!!!
6083 */
6084static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6085{
6086 int rc = VINF_SUCCESS;
6087 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6088 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR2);
6089
6090 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
6091 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
6092 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
6093
6094 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
6095 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
6096 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
6097 {
6098#ifdef HMSVM_USE_IEM_EVENT_REFLECTION
6099 IEMXCPTRAISE enmRaise;
6100 IEMXCPTRAISEINFO fRaiseInfo;
6101 bool const fExitIsHwXcpt = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31;
6102 uint8_t const uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
6103 if (fExitIsHwXcpt)
6104 {
6105 uint8_t const uExitVector = pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0;
6106 uint32_t const fIdtVectorFlags = hmR0SvmGetIemXcptFlags(&pVmcb->ctrl.ExitIntInfo);
6107 uint32_t const fExitVectorFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6108 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
6109 }
6110 else
6111 {
6112 /*
6113 * If delivery of an event caused a #VMEXIT that is not an exception (e.g. #NPF) then we
6114 * end up here.
6115 *
6116 * If the event was:
6117 * - a software interrupt, we can re-execute the instruction which will regenerate
6118 * the event.
6119 * - an NMI, we need to clear NMI blocking and re-inject the NMI.
6120 * - a hardware exception or external interrupt, we re-inject it.
6121 */
6122 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
6123 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_SOFTWARE_INT)
6124 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
6125 else
6126 enmRaise = IEMXCPTRAISE_PREV_EVENT;
6127 }
6128
6129 switch (enmRaise)
6130 {
6131 case IEMXCPTRAISE_CURRENT_XCPT:
6132 case IEMXCPTRAISE_PREV_EVENT:
6133 {
6134 /* For software interrupts, we shall re-execute the instruction. */
6135 if (!(fRaiseInfo & IEMXCPTRAISEINFO_SOFT_INT_XCPT))
6136 {
6137 RTGCUINTPTR GCPtrFaultAddress = 0;
6138
6139 /* If we are re-injecting an NMI, clear NMI blocking. */
6140 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6141 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6142
6143 /* Determine a vectoring #PF condition, see comment in hmR0SvmExitXcptPF(). */
6144 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
6145 {
6146 pSvmTransient->fVectoringPF = true;
6147 Log4(("IDT: Pending vectoring #PF due to delivery of Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6148 }
6149 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION
6150 && uIdtVector == X86_XCPT_PF)
6151 {
6152 /*
6153 * If the previous exception was a #PF, we need to recover the CR2 value.
6154 * This can't happen with shadow paging.
6155 */
6156 GCPtrFaultAddress = pCtx->cr2;
6157 }
6158
6159 /*
6160 * Without nested paging, when uExitVector is #PF, CR2 value will be updated from the VMCB's
6161 * exit info. fields, if it's a guest #PF, see hmR0SvmExitXcptPF().
6162 */
6163 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6164 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6165 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, GCPtrFaultAddress);
6166
6167 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32 GCPtrFaultAddress=%#RX64\n",
6168 pVmcb->ctrl.ExitIntInfo.u, RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid),
6169 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, GCPtrFaultAddress));
6170 }
6171 break;
6172 }
6173
6174 case IEMXCPTRAISE_REEXEC_INSTR:
6175 {
6176 Assert(rc == VINF_SUCCESS);
6177 break;
6178 }
6179
6180 case IEMXCPTRAISE_DOUBLE_FAULT:
6181 {
6182 /*
6183 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
6184 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
6185 */
6186 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
6187 {
6188 Log4(("IDT: Pending vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
6189 pSvmTransient->fVectoringDoublePF = true;
6190 Assert(rc == VINF_SUCCESS);
6191 }
6192 else
6193 {
6194 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6195 hmR0SvmSetPendingXcptDF(pVCpu);
6196 rc = VINF_HM_DOUBLE_FAULT;
6197 }
6198 break;
6199 }
6200
6201 case IEMXCPTRAISE_TRIPLE_FAULT:
6202 {
6203 rc = VINF_EM_RESET;
6204 break;
6205 }
6206
6207 case IEMXCPTRAISE_CPU_HANG:
6208 {
6209 rc = VERR_EM_GUEST_CPU_HANG;
6210 break;
6211 }
6212
6213 default:
6214 {
6215 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
6216 rc = VERR_SVM_IPE_2;
6217 break;
6218 }
6219 }
6220#else
6221 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
6222
6223 typedef enum
6224 {
6225 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
6226 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
6227 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
6228 SVMREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
6229 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
6230 } SVMREFLECTXCPT;
6231
6232 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
6233 bool fReflectingNmi = false;
6234 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
6235 {
6236 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6237 {
6238 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6239
6240#ifdef VBOX_STRICT
6241 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
6242 && uExitVector == X86_XCPT_PF)
6243 {
6244 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
6245 }
6246#endif
6247
6248 if ( uIdtVector == X86_XCPT_BP
6249 || uIdtVector == X86_XCPT_OF)
6250 {
6251 /* Ignore INT3/INTO, just re-execute. See @bugref{8357}. */
6252 }
6253 else if ( uExitVector == X86_XCPT_PF
6254 && uIdtVector == X86_XCPT_PF)
6255 {
6256 pSvmTransient->fVectoringDoublePF = true;
6257 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
6258 }
6259 else if ( uExitVector == X86_XCPT_AC
6260 && uIdtVector == X86_XCPT_AC)
6261 {
6262 enmReflect = SVMREFLECTXCPT_HANG;
6263 Log4(("IDT: Nested #AC - Bad guest\n"));
6264 }
6265 else if ( (pVmcb->ctrl.u32InterceptXcpt & HMSVM_CONTRIBUTORY_XCPT_MASK)
6266 && hmR0SvmIsContributoryXcpt(uExitVector)
6267 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
6268 || uIdtVector == X86_XCPT_PF))
6269 {
6270 enmReflect = SVMREFLECTXCPT_DF;
6271 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
6272 uIdtVector, uExitVector));
6273 }
6274 else if (uIdtVector == X86_XCPT_DF)
6275 {
6276 enmReflect = SVMREFLECTXCPT_TF;
6277 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
6278 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
6279 }
6280 else
6281 enmReflect = SVMREFLECTXCPT_XCPT;
6282 }
6283 else
6284 {
6285 /*
6286 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
6287 * exception to the guest after handling the #VMEXIT.
6288 */
6289 enmReflect = SVMREFLECTXCPT_XCPT;
6290 }
6291 }
6292 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
6293 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
6294 {
6295 enmReflect = SVMREFLECTXCPT_XCPT;
6296 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
6297
6298 if (pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0 <= SVM_EXIT_XCPT_31)
6299 {
6300 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_XCPT_0);
6301 if (uExitVector == X86_XCPT_PF)
6302 {
6303 pSvmTransient->fVectoringPF = true;
6304 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
6305 }
6306 }
6307 }
6308 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
6309
6310 switch (enmReflect)
6311 {
6312 case SVMREFLECTXCPT_XCPT:
6313 {
6314 /* If we are re-injecting the NMI, clear NMI blocking. */
6315 if (fReflectingNmi)
6316 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6317
6318 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
6319 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6320 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
6321
6322 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
6323 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
6324 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
6325 break;
6326 }
6327
6328 case SVMREFLECTXCPT_DF:
6329 {
6330 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6331 hmR0SvmSetPendingXcptDF(pVCpu);
6332 rc = VINF_HM_DOUBLE_FAULT;
6333 break;
6334 }
6335
6336 case SVMREFLECTXCPT_TF:
6337 {
6338 rc = VINF_EM_RESET;
6339 break;
6340 }
6341
6342 case SVMREFLECTXCPT_HANG:
6343 {
6344 rc = VERR_EM_GUEST_CPU_HANG;
6345 break;
6346 }
6347
6348 default:
6349 Assert(rc == VINF_SUCCESS);
6350 break;
6351 }
6352#endif /* HMSVM_USE_IEM_EVENT_REFLECTION */
6353 }
6354 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
6355 NOREF(pCtx);
6356 return rc;
6357}
6358
6359
6360/**
6361 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
6362 * supported, otherwise advances the RIP by the number of bytes specified in
6363 * @a cb.
6364 *
6365 * @param pVCpu The cross context virtual CPU structure.
6366 * @param pCtx Pointer to the guest-CPU context.
6367 * @param cb RIP increment value in bytes.
6368 *
6369 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
6370 * when NRIP_SAVE is supported by the CPU, otherwise use
6371 * hmR0SvmAdvanceRipDumb!
6372 */
6373DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6374{
6375 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6376 if (fSupportsNextRipSave)
6377 {
6378 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6379 Assert(pVmcb);
6380 Assert(pVmcb->ctrl.u64NextRIP);
6381 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
6382 AssertRelease(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb); /* temporary, remove later */
6383 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6384 }
6385 else
6386 pCtx->rip += cb;
6387
6388 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6389}
6390
6391
6392/**
6393 * Gets the length of the current instruction if the CPU supports the NRIP_SAVE
6394 * feature. Otherwise, returns the value in @a cbLikely.
6395 *
6396 * @param pVCpu The cross context virtual CPU structure.
6397 * @param pCtx Pointer to the guest-CPU context.
6398 * @param cbLikely The likely instruction length.
6399 */
6400DECLINLINE(uint8_t) hmR0SvmGetInstrLengthHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint8_t cbLikely)
6401{
6402 Assert(cbLikely <= 15); /* See Intel spec. 2.3.11 "AVX Instruction Length" */
6403 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6404 if (fSupportsNextRipSave)
6405 {
6406 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6407 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6408 Assert(cbInstr == cbLikely);
6409 return cbInstr;
6410 }
6411 return cbLikely;
6412}
6413
6414
6415/**
6416 * Advances the guest RIP by the number of bytes specified in @a cb. This does
6417 * not make use of any hardware features to determine the instruction length.
6418 *
6419 * @param pVCpu The cross context virtual CPU structure.
6420 * @param pCtx Pointer to the guest-CPU context.
6421 * @param cb RIP increment value in bytes.
6422 */
6423DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
6424{
6425 pCtx->rip += cb;
6426 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
6427}
6428#undef HMSVM_UPDATE_INTR_SHADOW
6429
6430
6431/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6432/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
6433/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
6434
6435/** @name \#VMEXIT handlers.
6436 * @{
6437 */
6438
6439/**
6440 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
6441 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
6442 */
6443HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6444{
6445 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6446
6447 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
6448 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
6449 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
6450 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
6451
6452 /*
6453 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
6454 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
6455 * interrupt it is until the host actually take the interrupt.
6456 *
6457 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
6458 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
6459 */
6460 return VINF_EM_RAW_INTERRUPT;
6461}
6462
6463
6464/**
6465 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
6466 */
6467HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6468{
6469 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6470
6471 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6472 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
6473 int rc = VINF_SUCCESS;
6474 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6475 return rc;
6476}
6477
6478
6479/**
6480 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
6481 */
6482HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6483{
6484 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6485
6486 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6487 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
6488 int rc = VINF_SUCCESS;
6489 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6490 return rc;
6491}
6492
6493
6494/**
6495 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
6496 */
6497HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6498{
6499 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6500
6501 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS);
6502 VBOXSTRICTRC rcStrict;
6503 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
6504 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
6505 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
6506 if (!pExitRec)
6507 {
6508 PVM pVM = pVCpu->CTX_SUFF(pVM);
6509 rcStrict = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6510 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
6511 {
6512 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6513 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6514 }
6515 else
6516 {
6517 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
6518 rcStrict = VERR_EM_INTERPRETER;
6519 }
6520 }
6521 else
6522 {
6523 /*
6524 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
6525 */
6526 Assert(pCtx == &pVCpu->cpum.GstCtx);
6527 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6528
6529 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
6530 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
6531
6532 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
6533
6534 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
6535 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
6536 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
6537 }
6538 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
6539 return VBOXSTRICTRC_TODO(rcStrict);
6540}
6541
6542
6543/**
6544 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
6545 */
6546HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6547{
6548 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6549 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6550 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 2));
6551 if (rcStrict == VINF_SUCCESS)
6552 pSvmTransient->fUpdateTscOffsetting = true;
6553 else if (rcStrict == VINF_IEM_RAISED_XCPT)
6554 rcStrict = VINF_SUCCESS;
6555 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6556 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
6557 return VBOXSTRICTRC_TODO(rcStrict);
6558}
6559
6560
6561/**
6562 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
6563 */
6564HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6565{
6566 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6567 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3));
6568 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6569 if (rcStrict == VINF_SUCCESS)
6570 pSvmTransient->fUpdateTscOffsetting = true;
6571 else if (rcStrict == VINF_IEM_RAISED_XCPT)
6572 rcStrict = VINF_SUCCESS;
6573 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6574 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
6575 return VBOXSTRICTRC_TODO(rcStrict);
6576}
6577
6578
6579/**
6580 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
6581 */
6582HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6583{
6584 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6585 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6586 | CPUMCTX_EXTRN_CR4
6587 | CPUMCTX_EXTRN_SS);
6588
6589 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6590 if (RT_LIKELY(rc == VINF_SUCCESS))
6591 {
6592 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6593 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6594 }
6595 else
6596 {
6597 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
6598 rc = VERR_EM_INTERPRETER;
6599 }
6600 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
6601 return rc;
6602}
6603
6604
6605/**
6606 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
6607 */
6608HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6609{
6610 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6611 PVM pVM = pVCpu->CTX_SUFF(pVM);
6612 Assert(!pVM->hm.s.fNestedPaging);
6613 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
6614
6615 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6616 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6617 if ( fSupportsDecodeAssists
6618 && fSupportsNextRipSave)
6619 {
6620 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6621 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6622 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6623 RTGCPTR const GCPtrPage = pVmcb->ctrl.u64ExitInfo1;
6624 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, cbInstr, GCPtrPage);
6625 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6626 return VBOXSTRICTRC_VAL(rcStrict);
6627 }
6628
6629 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6630 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
6631 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
6632 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6633 return rc;
6634}
6635
6636
6637/**
6638 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
6639 */
6640HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6641{
6642 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6643
6644 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
6645 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
6646 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6647 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
6648 if (rc != VINF_SUCCESS)
6649 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
6650 return rc;
6651}
6652
6653
6654/**
6655 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
6656 */
6657HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6658{
6659 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6660 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6661 | CPUMCTX_EXTRN_SS);
6662
6663 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6664 if (RT_LIKELY(rc == VINF_SUCCESS))
6665 {
6666 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6667 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6668 }
6669 else
6670 {
6671 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
6672 rc = VERR_EM_INTERPRETER;
6673 }
6674 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
6675 return rc;
6676}
6677
6678
6679/**
6680 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
6681 */
6682HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6683{
6684 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6685 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6686 | CPUMCTX_EXTRN_SS);
6687
6688 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
6689 int rc = VBOXSTRICTRC_VAL(rc2);
6690 if ( rc == VINF_EM_HALT
6691 || rc == VINF_SUCCESS)
6692 {
6693 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
6694
6695 if ( rc == VINF_EM_HALT
6696 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
6697 {
6698 rc = VINF_SUCCESS;
6699 }
6700 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6701 }
6702 else
6703 {
6704 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
6705 rc = VERR_EM_INTERPRETER;
6706 }
6707 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
6708 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
6709 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
6710 return rc;
6711}
6712
6713
6714/**
6715 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
6716 * \#VMEXIT.
6717 */
6718HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6719{
6720 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6721 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6722 return VINF_EM_RESET;
6723}
6724
6725
6726/**
6727 * \#VMEXIT handler for unexpected exits. Conditional \#VMEXIT.
6728 */
6729HMSVM_EXIT_DECL hmR0SvmExitUnexpected(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6730{
6731 RT_NOREF(pCtx);
6732 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6733 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6734 AssertMsgFailed(("hmR0SvmExitUnexpected: ExitCode=%#RX64 uExitInfo1=%#RX64 uExitInfo2=%#RX64\n", pSvmTransient->u64ExitCode,
6735 pVmcb->ctrl.u64ExitInfo1, pVmcb->ctrl.u64ExitInfo2));
6736 RT_NOREF(pVmcb);
6737 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6738 return VERR_SVM_UNEXPECTED_EXIT;
6739}
6740
6741
6742/**
6743 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
6744 */
6745HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6746{
6747 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6748
6749 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
6750 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
6751
6752 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6753 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6754 if ( fSupportsDecodeAssists
6755 && fSupportsNextRipSave)
6756 {
6757 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6758 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6759 if (fMovCRx)
6760 {
6761 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6762 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6763 uint8_t const iCrReg = pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0;
6764 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6765 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
6766 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6767 return VBOXSTRICTRC_VAL(rcStrict);
6768 }
6769 /* else: SMSW instruction, fall back below to IEM for this. */
6770 }
6771
6772 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6773 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
6774 int rc = VBOXSTRICTRC_VAL(rc2);
6775 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
6776 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
6777 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
6778 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6779 return rc;
6780}
6781
6782
6783/**
6784 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
6785 */
6786HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6787{
6788 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6789
6790 uint64_t const uExitCode = pSvmTransient->u64ExitCode;
6791 uint8_t const iCrReg = uExitCode == SVM_EXIT_CR0_SEL_WRITE ? 0 : (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0);
6792 Assert(iCrReg <= 15);
6793
6794 VBOXSTRICTRC rcStrict = VERR_SVM_IPE_5;
6795 bool fDecodedInstr = false;
6796 bool const fSupportsDecodeAssists = hmR0SvmSupportsDecodeAssists(pVCpu, pCtx);
6797 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6798 if ( fSupportsDecodeAssists
6799 && fSupportsNextRipSave)
6800 {
6801 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6802 bool const fMovCRx = RT_BOOL(pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_MASK);
6803 if (fMovCRx)
6804 {
6805 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6806 uint8_t const cbInstr = pVmcb->ctrl.u64NextRIP - pCtx->rip;
6807 uint8_t const iGReg = pVmcb->ctrl.u64ExitInfo1 & SVM_EXIT1_MOV_CRX_GPR_NUMBER;
6808 Log4(("hmR0SvmExitWriteCRx: Mov CR%u w/ iGReg=%#x\n", iCrReg, iGReg));
6809 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
6810 fDecodedInstr = true;
6811 }
6812 /* else: LMSW or CLTS instruction, fall back below to IEM for this. */
6813 }
6814
6815 if (!fDecodedInstr)
6816 {
6817 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
6818 Log4(("hmR0SvmExitWriteCRx: iCrReg=%#x\n", iCrReg));
6819 rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
6820 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
6821 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
6822 rcStrict = VERR_EM_INTERPRETER;
6823 }
6824
6825 if (rcStrict == VINF_SUCCESS)
6826 {
6827 switch (iCrReg)
6828 {
6829 case 0: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0); break;
6830 case 2: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2); break;
6831 case 3: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3); break;
6832 case 4: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4); break;
6833 case 8: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE); break;
6834 default:
6835 {
6836 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
6837 pSvmTransient->u64ExitCode, iCrReg));
6838 break;
6839 }
6840 }
6841 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
6842 }
6843 else
6844 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
6845 return VBOXSTRICTRC_TODO(rcStrict);
6846}
6847
6848
6849/**
6850 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
6851 * \#VMEXIT.
6852 */
6853HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6854{
6855 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6856 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0
6857 | CPUMCTX_EXTRN_RFLAGS
6858 | CPUMCTX_EXTRN_SS
6859 | CPUMCTX_EXTRN_ALL_MSRS);
6860
6861 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
6862 PVM pVM = pVCpu->CTX_SUFF(pVM);
6863
6864 int rc;
6865 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
6866 {
6867 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
6868 Log4(("MSR Write: idMsr=%#RX32\n", pCtx->ecx));
6869
6870 /* Handle TPR patching; intercepted LSTAR write. */
6871 if ( pVM->hm.s.fTPRPatchingActive
6872 && pCtx->ecx == MSR_K8_LSTAR)
6873 {
6874 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
6875 {
6876 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
6877 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
6878 AssertRC(rc2);
6879 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6880 }
6881 rc = VINF_SUCCESS;
6882 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
6883 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6884 return rc;
6885 }
6886
6887 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6888 if (fSupportsNextRipSave)
6889 {
6890 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6891 if (RT_LIKELY(rc == VINF_SUCCESS))
6892 {
6893 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6894 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6895 }
6896 else
6897 AssertMsg( rc == VERR_EM_INTERPRETER
6898 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
6899 }
6900 else
6901 {
6902 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6903 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
6904 if (RT_LIKELY(rc == VINF_SUCCESS))
6905 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
6906 else
6907 AssertMsg( rc == VERR_EM_INTERPRETER
6908 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6909 }
6910
6911 if (rc == VINF_SUCCESS)
6912 {
6913 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
6914 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
6915 && pCtx->ecx <= MSR_IA32_X2APIC_END)
6916 {
6917 /*
6918 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
6919 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
6920 * EMInterpretWrmsr() changes it.
6921 */
6922 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
6923 }
6924 else
6925 {
6926 switch (pCtx->ecx)
6927 {
6928 case MSR_K6_EFER: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR); break;
6929 case MSR_IA32_TSC: pSvmTransient->fUpdateTscOffsetting = true; break;
6930 case MSR_K8_FS_BASE:
6931 case MSR_K8_GS_BASE: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS); break;
6932 case MSR_IA32_SYSENTER_CS: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
6933 case MSR_IA32_SYSENTER_EIP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
6934 case MSR_IA32_SYSENTER_ESP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
6935 }
6936 }
6937 }
6938 }
6939 else
6940 {
6941 /* MSR Read access. */
6942 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
6943 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
6944 Log4(("MSR Read: idMsr=%#RX32\n", pCtx->ecx));
6945
6946 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
6947 if (fSupportsNextRipSave)
6948 {
6949 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
6950 if (RT_LIKELY(rc == VINF_SUCCESS))
6951 {
6952 pCtx->rip = pVmcb->ctrl.u64NextRIP;
6953 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6954 }
6955 else
6956 AssertMsg( rc == VERR_EM_INTERPRETER
6957 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
6958 }
6959 else
6960 {
6961 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6962 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
6963 if (RT_UNLIKELY(rc != VINF_SUCCESS))
6964 {
6965 AssertMsg( rc == VERR_EM_INTERPRETER
6966 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
6967 }
6968 /* RIP updated by EMInterpretInstruction(). */
6969 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
6970 }
6971 }
6972
6973 /* RIP has been updated by EMInterpret[Rd|Wr]msr() or EMInterpretInstruction(). */
6974 return rc;
6975}
6976
6977
6978/**
6979 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
6980 */
6981HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
6982{
6983 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
6984 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
6985
6986 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
6987
6988 /** @todo Stepping with nested-guest. */
6989 if (!CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
6990 {
6991 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
6992 if (pSvmTransient->fWasGuestDebugStateActive)
6993 {
6994 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
6995 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
6996 return VERR_SVM_UNEXPECTED_EXIT;
6997 }
6998
6999 /*
7000 * Lazy DR0-3 loading.
7001 */
7002 if (!pSvmTransient->fWasHyperDebugStateActive)
7003 {
7004 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
7005 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
7006
7007 /* Don't intercept DRx read and writes. */
7008 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7009 pVmcb->ctrl.u16InterceptRdDRx = 0;
7010 pVmcb->ctrl.u16InterceptWrDRx = 0;
7011 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
7012
7013 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
7014 VMMRZCallRing3Disable(pVCpu);
7015 HM_DISABLE_PREEMPT();
7016
7017 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
7018 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
7019 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
7020
7021 HM_RESTORE_PREEMPT();
7022 VMMRZCallRing3Enable(pVCpu);
7023
7024 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
7025 return VINF_SUCCESS;
7026 }
7027 }
7028
7029 /*
7030 * Interpret the read/writing of DRx.
7031 */
7032 /** @todo Decode assist. */
7033 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
7034 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
7035 if (RT_LIKELY(rc == VINF_SUCCESS))
7036 {
7037 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
7038 /** @todo CPUM should set this flag! */
7039 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
7040 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7041 }
7042 else
7043 Assert(rc == VERR_EM_INTERPRETER);
7044 return VBOXSTRICTRC_TODO(rc);
7045}
7046
7047
7048/**
7049 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
7050 */
7051HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7052{
7053 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7054 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
7055 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
7056 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
7057 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
7058 return rc;
7059}
7060
7061
7062/**
7063 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
7064 */
7065HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7066{
7067 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7068 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
7069
7070 /** @todo decode assists... */
7071 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
7072 if (rcStrict == VINF_IEM_RAISED_XCPT)
7073 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7074
7075 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
7076 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
7077 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
7078
7079 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
7080 return VBOXSTRICTRC_TODO(rcStrict);
7081}
7082
7083
7084/**
7085 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
7086 */
7087HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7088{
7089 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7090 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK);
7091
7092 /* I/O operation lookup arrays. */
7093 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
7094 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
7095 the result (in AL/AX/EAX). */
7096 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
7097
7098 PVM pVM = pVCpu->CTX_SUFF(pVM);
7099 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7100
7101 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
7102 SVMIOIOEXITINFO IoExitInfo;
7103 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
7104 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
7105 uint32_t cbValue = s_aIOSize[uIOWidth];
7106 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
7107
7108 if (RT_UNLIKELY(!cbValue))
7109 {
7110 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
7111 return VERR_EM_INTERPRETER;
7112 }
7113
7114 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS);
7115 VBOXSTRICTRC rcStrict;
7116 PCEMEXITREC pExitRec = NULL;
7117 if ( !pVCpu->hm.s.fSingleInstruction
7118 && !pVCpu->cpum.GstCtx.eflags.Bits.u1TF)
7119 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
7120 !IoExitInfo.n.u1Str
7121 ? IoExitInfo.n.u1Type == SVM_IOIO_READ
7122 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
7123 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
7124 : IoExitInfo.n.u1Type == SVM_IOIO_READ
7125 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
7126 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
7127 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
7128 if (!pExitRec)
7129 {
7130 bool fUpdateRipAlready = false;
7131 if (IoExitInfo.n.u1Str)
7132 {
7133 /* INS/OUTS - I/O String instruction. */
7134 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
7135 * in EXITINFO1? Investigate once this thing is up and running. */
7136 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
7137 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
7138 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
7139 static IEMMODE const s_aenmAddrMode[8] =
7140 {
7141 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
7142 };
7143 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
7144 if (enmAddrMode != (IEMMODE)-1)
7145 {
7146 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
7147 if (cbInstr <= 15 && cbInstr >= 1)
7148 {
7149 Assert(cbInstr >= 1U + IoExitInfo.n.u1Rep);
7150 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
7151 {
7152 /* Don't know exactly how to detect whether u3Seg is valid, currently
7153 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
7154 2384 Opterons when only checking NRIP. */
7155 bool const fSupportsNextRipSave = hmR0SvmSupportsNextRipSave(pVCpu, pCtx);
7156 if ( fSupportsNextRipSave
7157 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
7158 {
7159 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1Rep,
7160 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3Seg, cbInstr, IoExitInfo.n.u1Rep));
7161 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7162 IoExitInfo.n.u3Seg, true /*fIoChecked*/);
7163 }
7164 else if (cbInstr == 1U + IoExitInfo.n.u1Rep)
7165 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7166 X86_SREG_DS, true /*fIoChecked*/);
7167 else
7168 rcStrict = IEMExecOne(pVCpu);
7169 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
7170 }
7171 else
7172 {
7173 AssertMsg(IoExitInfo.n.u3Seg == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3Seg));
7174 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1Rep, (uint8_t)cbInstr,
7175 true /*fIoChecked*/);
7176 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
7177 }
7178 }
7179 else
7180 {
7181 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
7182 rcStrict = IEMExecOne(pVCpu);
7183 }
7184 }
7185 else
7186 {
7187 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
7188 rcStrict = IEMExecOne(pVCpu);
7189 }
7190 fUpdateRipAlready = true;
7191 }
7192 else
7193 {
7194 /* IN/OUT - I/O instruction. */
7195 Assert(!IoExitInfo.n.u1Rep);
7196
7197 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
7198 {
7199 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
7200 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
7201 }
7202 else
7203 {
7204 uint32_t u32Val = 0;
7205 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
7206 if (IOM_SUCCESS(rcStrict))
7207 {
7208 /* Save result of I/O IN instr. in AL/AX/EAX. */
7209 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
7210 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
7211 }
7212 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7213 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
7214
7215 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
7216 }
7217 }
7218
7219 if (IOM_SUCCESS(rcStrict))
7220 {
7221 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
7222 if (!fUpdateRipAlready)
7223 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
7224
7225 /*
7226 * If any I/O breakpoints are armed, we need to check if one triggered
7227 * and take appropriate action.
7228 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
7229 */
7230 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
7231 * execution engines about whether hyper BPs and such are pending. */
7232 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_DR7);
7233 uint32_t const uDr7 = pCtx->dr[7];
7234 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
7235 && X86_DR7_ANY_RW_IO(uDr7)
7236 && (pCtx->cr4 & X86_CR4_DE))
7237 || DBGFBpIsHwIoArmed(pVM)))
7238 {
7239 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
7240 VMMRZCallRing3Disable(pVCpu);
7241 HM_DISABLE_PREEMPT();
7242
7243 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
7244 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
7245
7246 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
7247 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
7248 {
7249 /* Raise #DB. */
7250 pVmcb->guest.u64DR6 = pCtx->dr[6];
7251 pVmcb->guest.u64DR7 = pCtx->dr[7];
7252 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7253 hmR0SvmSetPendingXcptDB(pVCpu);
7254 }
7255 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
7256 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
7257 else if ( rcStrict2 != VINF_SUCCESS
7258 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
7259 rcStrict = rcStrict2;
7260 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
7261
7262 HM_RESTORE_PREEMPT();
7263 VMMRZCallRing3Enable(pVCpu);
7264 }
7265
7266 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
7267 }
7268
7269#ifdef VBOX_STRICT
7270 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
7271 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
7272 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
7273 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
7274 else
7275 {
7276 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
7277 * statuses, that the VMM device and some others may return. See
7278 * IOM_SUCCESS() for guidance. */
7279 AssertMsg( RT_FAILURE(rcStrict)
7280 || rcStrict == VINF_SUCCESS
7281 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
7282 || rcStrict == VINF_EM_DBG_BREAKPOINT
7283 || rcStrict == VINF_EM_RAW_GUEST_TRAP
7284 || rcStrict == VINF_EM_RAW_TO_R3
7285 || rcStrict == VINF_TRPM_XCPT_DISPATCHED
7286 || rcStrict == VINF_EM_TRIPLE_FAULT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
7287 }
7288#endif
7289 }
7290 else
7291 {
7292 /*
7293 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
7294 */
7295 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
7296 STAM_COUNTER_INC(!IoExitInfo.n.u1Str
7297 ? IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
7298 : IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
7299 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
7300 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, IoExitInfo.n.u1Rep ? "REP " : "",
7301 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? "OUT" : "IN", IoExitInfo.n.u1Str ? "S" : "", IoExitInfo.n.u16Port, uIOWidth));
7302
7303 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
7304 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7305
7306 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
7307 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
7308 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
7309 }
7310 return VBOXSTRICTRC_TODO(rcStrict);
7311}
7312
7313
7314/**
7315 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
7316 */
7317HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7318{
7319 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7320 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7321 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7322
7323 PVM pVM = pVCpu->CTX_SUFF(pVM);
7324 Assert(pVM->hm.s.fNestedPaging);
7325
7326 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
7327 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7328 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
7329 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1; /* Note! High bits in EXITINFO1 may contain additional info and are
7330 thus intentionally not copied into u32ErrCode. */
7331
7332 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
7333
7334 /*
7335 * TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions.
7336 */
7337 if ( pVM->hm.s.fTprPatchingAllowed
7338 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == XAPIC_OFF_TPR
7339 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
7340 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
7341 && !CPUMIsGuestInLongModeEx(pCtx)
7342 && !CPUMGetGuestCPL(pVCpu)
7343 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7344 {
7345 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7346 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7347
7348 if (GCPhysFaultAddr == GCPhysApicBase + XAPIC_OFF_TPR)
7349 {
7350 /* Only attempt to patch the instruction once. */
7351 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7352 if (!pPatch)
7353 return VINF_EM_HM_PATCH_TPR_INSTR;
7354 }
7355 }
7356
7357 /*
7358 * Determine the nested paging mode.
7359 */
7360 PGMMODE enmNestedPagingMode;
7361#if HC_ARCH_BITS == 32
7362 if (CPUMIsGuestInLongModeEx(pCtx))
7363 enmNestedPagingMode = PGMMODE_AMD64_NX;
7364 else
7365#endif
7366 enmNestedPagingMode = PGMGetHostMode(pVM);
7367
7368 /*
7369 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
7370 */
7371 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
7372 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
7373 {
7374 /* If event delivery causes an MMIO #NPF, go back to instruction emulation as
7375 otherwise injecting the original pending event would most likely cause the same MMIO #NPF. */
7376 if (pVCpu->hm.s.Event.fPending)
7377 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7378
7379 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS);
7380 VBOXSTRICTRC rcStrict;
7381 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
7382 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
7383 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
7384 if (!pExitRec)
7385 {
7386
7387 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
7388 u32ErrCode);
7389
7390 /*
7391 * If we succeed, resume guest execution.
7392 * If we fail in interpreting the instruction because we couldn't get the guest physical address
7393 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
7394 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
7395 * weird case. See @bugref{6043}.
7396 */
7397 if ( rcStrict == VINF_SUCCESS
7398 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
7399 || rcStrict == VERR_PAGE_NOT_PRESENT)
7400 {
7401 /* Successfully handled MMIO operation. */
7402 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_APIC_STATE);
7403 rcStrict = VINF_SUCCESS;
7404 }
7405 }
7406 else
7407 {
7408 /*
7409 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
7410 */
7411 Assert(pCtx == &pVCpu->cpum.GstCtx);
7412 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
7413 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
7414 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhysFaultAddr));
7415
7416 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
7417 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7418
7419 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
7420 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
7421 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
7422 }
7423 return VBOXSTRICTRC_TODO(rcStrict);
7424 }
7425
7426 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
7427 int rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
7428 TRPMResetTrap(pVCpu);
7429
7430 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
7431
7432 /*
7433 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
7434 */
7435 if ( rc == VINF_SUCCESS
7436 || rc == VERR_PAGE_TABLE_NOT_PRESENT
7437 || rc == VERR_PAGE_NOT_PRESENT)
7438 {
7439 /* We've successfully synced our shadow page tables. */
7440 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7441 rc = VINF_SUCCESS;
7442 }
7443
7444 return rc;
7445}
7446
7447
7448/**
7449 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
7450 * \#VMEXIT.
7451 */
7452HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7453{
7454 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7455 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7456
7457 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7458 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7459 hmR0SvmClearIntWindowExiting(pVCpu, pVmcb, pCtx);
7460
7461 /* Deliver the pending interrupt via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7462 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
7463 return VINF_SUCCESS;
7464}
7465
7466
7467/**
7468 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
7469 * \#VMEXIT.
7470 */
7471HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7472{
7473 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7474 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7475
7476#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
7477 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
7478#endif
7479
7480 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
7481 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
7482 {
7483 /*
7484 * AMD-V provides us with the exception which caused the TS; we collect
7485 * the information in the call to hmR0SvmCheckExitDueToEventDelivery.
7486 */
7487 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
7488 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7489 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7490 }
7491
7492 /** @todo Emulate task switch someday, currently just going back to ring-3 for
7493 * emulation. */
7494 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
7495 return VERR_EM_INTERPRETER;
7496}
7497
7498
7499/**
7500 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7501 */
7502HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7503{
7504 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7505 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7506
7507 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
7508
7509 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTprPatchingAllowed)
7510 {
7511 int rc = hmSvmEmulateMovTpr(pVCpu, pCtx);
7512 if (rc != VERR_NOT_FOUND)
7513 {
7514 Log4(("hmR0SvmExitVmmCall: hmSvmEmulateMovTpr returns %Rrc\n", rc));
7515 return rc;
7516 }
7517 }
7518
7519 if (EMAreHypercallInstructionsEnabled(pVCpu))
7520 {
7521 VBOXSTRICTRC rcStrict = GIMHypercall(pVCpu, pCtx);
7522 if (RT_SUCCESS(rcStrict))
7523 {
7524 /* Only update the RIP if we're continuing guest execution and not in the case
7525 of say VINF_GIM_R3_HYPERCALL. */
7526 if (rcStrict == VINF_SUCCESS)
7527 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
7528
7529 return VBOXSTRICTRC_VAL(rcStrict);
7530 }
7531 else
7532 Log4(("hmR0SvmExitVmmCall: GIMHypercall returns %Rrc -> #UD\n", VBOXSTRICTRC_VAL(rcStrict)));
7533 }
7534
7535 hmR0SvmSetPendingXcptUD(pVCpu);
7536 return VINF_SUCCESS;
7537}
7538
7539
7540/**
7541 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
7542 */
7543HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7544{
7545 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7546 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
7547 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
7548 /** @todo The guest has likely hit a contended spinlock. We might want to
7549 * poke a schedule different guest VCPU. */
7550 return VINF_EM_RAW_INTERRUPT;
7551}
7552
7553
7554/**
7555 * \#VMEXIT handler for FERR intercept (SVM_EXIT_FERR_FREEZE). Conditional
7556 * \#VMEXIT.
7557 */
7558HMSVM_EXIT_DECL hmR0SvmExitFerrFreeze(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7559{
7560 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7561 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, CPUMCTX_EXTRN_CR0);
7562 Assert(!(pCtx->cr0 & X86_CR0_NE));
7563
7564 Log4(("hmR0SvmExitFerrFreeze: Raising IRQ 13 in response to #FERR\n"));
7565 return PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7566}
7567
7568
7569/**
7570 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
7571 */
7572HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7573{
7574 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7575
7576 /* Clear NMI blocking. */
7577 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
7578 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
7579
7580 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
7581 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7582 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_IRET);
7583
7584 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
7585 return VINF_SUCCESS;
7586}
7587
7588
7589/**
7590 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_XCPT_14).
7591 * Conditional \#VMEXIT.
7592 */
7593HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7594{
7595 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7596 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7597 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7598
7599 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
7600 PVM pVM = pVCpu->CTX_SUFF(pVM);
7601 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7602 uint32_t uErrCode = pVmcb->ctrl.u64ExitInfo1;
7603 uint64_t const uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
7604
7605#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
7606 if (pVM->hm.s.fNestedPaging)
7607 {
7608 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7609 if ( !pSvmTransient->fVectoringDoublePF
7610 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
7611 {
7612 /* A genuine guest #PF, reflect it to the guest. */
7613 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, uErrCode, uFaultAddress);
7614 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RX64 ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
7615 uFaultAddress, uErrCode));
7616 }
7617 else
7618 {
7619 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7620 hmR0SvmSetPendingXcptDF(pVCpu);
7621 Log4(("Pending #DF due to vectoring #PF. NP\n"));
7622 }
7623 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7624 return VINF_SUCCESS;
7625 }
7626#endif
7627
7628 Assert(!pVM->hm.s.fNestedPaging);
7629
7630 /*
7631 * TPR patching shortcut for APIC TPR reads and writes; only applicable to 32-bit guests.
7632 */
7633 if ( pVM->hm.s.fTprPatchingAllowed
7634 && (uFaultAddress & 0xfff) == XAPIC_OFF_TPR
7635 && !(uErrCode & X86_TRAP_PF_P) /* Not present. */
7636 && !CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7637 && !CPUMIsGuestInLongModeEx(pCtx)
7638 && !CPUMGetGuestCPL(pVCpu)
7639 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
7640 {
7641 RTGCPHYS GCPhysApicBase;
7642 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
7643 GCPhysApicBase &= PAGE_BASE_GC_MASK;
7644
7645 /* Check if the page at the fault-address is the APIC base. */
7646 RTGCPHYS GCPhysPage;
7647 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
7648 if ( rc2 == VINF_SUCCESS
7649 && GCPhysPage == GCPhysApicBase)
7650 {
7651 /* Only attempt to patch the instruction once. */
7652 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
7653 if (!pPatch)
7654 return VINF_EM_HM_PATCH_TPR_INSTR;
7655 }
7656 }
7657
7658 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 uErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
7659 pCtx->rip, uErrCode, pCtx->cr3));
7660
7661 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
7662 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
7663 if (pSvmTransient->fVectoringPF)
7664 {
7665 Assert(pVCpu->hm.s.Event.fPending);
7666 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7667 }
7668
7669 TRPMAssertXcptPF(pVCpu, uFaultAddress, uErrCode);
7670 int rc = PGMTrap0eHandler(pVCpu, uErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
7671
7672 Log4(("#PF: rc=%Rrc\n", rc));
7673
7674 if (rc == VINF_SUCCESS)
7675 {
7676 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
7677 TRPMResetTrap(pVCpu);
7678 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
7679 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7680 return rc;
7681 }
7682
7683 if (rc == VINF_EM_RAW_GUEST_TRAP)
7684 {
7685 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
7686
7687 /*
7688 * If a nested-guest delivers a #PF and that causes a #PF which is -not- a shadow #PF,
7689 * we should simply forward the #PF to the guest and is up to the nested-hypervisor to
7690 * determine whether it is a nested-shadow #PF or a #DF, see @bugref{7243#c121}.
7691 */
7692 if ( !pSvmTransient->fVectoringDoublePF
7693 || CPUMIsGuestInSvmNestedHwVirtMode(pCtx))
7694 {
7695 /* It's a guest (or nested-guest) page fault and needs to be reflected. */
7696 uErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
7697 TRPMResetTrap(pVCpu);
7698
7699#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7700 /* If the nested-guest is intercepting #PFs, cause a #PF #VMEXIT. */
7701 if ( CPUMIsGuestInSvmNestedHwVirtMode(pCtx)
7702 && HMIsGuestSvmXcptInterceptSet(pVCpu, X86_XCPT_PF))
7703 return VBOXSTRICTRC_TODO(IEMExecSvmVmexit(pVCpu, SVM_EXIT_XCPT_PF, uErrCode, uFaultAddress));
7704#endif
7705
7706 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, uErrCode, uFaultAddress);
7707 }
7708 else
7709 {
7710 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
7711 TRPMResetTrap(pVCpu);
7712 hmR0SvmSetPendingXcptDF(pVCpu);
7713 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
7714 }
7715
7716 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
7717 return VINF_SUCCESS;
7718 }
7719
7720 TRPMResetTrap(pVCpu);
7721 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
7722 return rc;
7723}
7724
7725
7726/**
7727 * \#VMEXIT handler for undefined opcode (SVM_EXIT_XCPT_6).
7728 * Conditional \#VMEXIT.
7729 */
7730HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7731{
7732 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7733 HMSVM_ASSERT_NOT_IN_NESTED_GUEST(pCtx);
7734
7735 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7736 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7737 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7738
7739 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
7740 if (pVCpu->hm.s.fGIMTrapXcptUD)
7741 {
7742 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7743 uint8_t cbInstr = 0;
7744 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
7745 if (rcStrict == VINF_SUCCESS)
7746 {
7747 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
7748 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
7749 rc = VINF_SUCCESS;
7750 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
7751 }
7752 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
7753 rc = VINF_SUCCESS;
7754 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
7755 rc = VINF_GIM_R3_HYPERCALL;
7756 else
7757 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
7758 }
7759
7760 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
7761 if (RT_FAILURE(rc))
7762 {
7763 hmR0SvmSetPendingXcptUD(pVCpu);
7764 rc = VINF_SUCCESS;
7765 }
7766
7767 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
7768 return rc;
7769}
7770
7771
7772/**
7773 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_XCPT_16).
7774 * Conditional \#VMEXIT.
7775 */
7776HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7777{
7778 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7779 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7780
7781 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
7782 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7783 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid); NOREF(pVmcb);
7784
7785 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
7786
7787 if (!(pCtx->cr0 & X86_CR0_NE))
7788 {
7789 PVM pVM = pVCpu->CTX_SUFF(pVM);
7790 PDISSTATE pDis = &pVCpu->hm.s.DisState;
7791 unsigned cbOp;
7792 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
7793 if (RT_SUCCESS(rc))
7794 {
7795 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
7796 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13 /* u8Irq */, 1 /* u8Level */, 0 /* uTagSrc */);
7797 if (RT_SUCCESS(rc))
7798 pCtx->rip += cbOp;
7799 }
7800 else
7801 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
7802 return rc;
7803 }
7804
7805 hmR0SvmSetPendingXcptMF(pVCpu);
7806 return VINF_SUCCESS;
7807}
7808
7809
7810/**
7811 * \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1). Conditional
7812 * \#VMEXIT.
7813 */
7814HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7815{
7816 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7817 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7818 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7819
7820 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
7821 {
7822 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
7823 return VINF_EM_RAW_INJECT_TRPM_EVENT;
7824 }
7825
7826 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
7827
7828 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
7829 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
7830 PVM pVM = pVCpu->CTX_SUFF(pVM);
7831 PSVMVMCB pVmcb = pVCpu->hm.s.svm.pVmcb;
7832 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
7833 if (rc == VINF_EM_RAW_GUEST_TRAP)
7834 {
7835 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
7836 if (CPUMIsHyperDebugStateActive(pVCpu))
7837 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
7838
7839 /* Reflect the exception back to the guest. */
7840 hmR0SvmSetPendingXcptDB(pVCpu);
7841 rc = VINF_SUCCESS;
7842 }
7843
7844 /*
7845 * Update DR6.
7846 */
7847 if (CPUMIsHyperDebugStateActive(pVCpu))
7848 {
7849 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
7850 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
7851 pVmcb->ctrl.u32VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
7852 }
7853 else
7854 {
7855 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
7856 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
7857 }
7858
7859 return rc;
7860}
7861
7862
7863/**
7864 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_XCPT_17).
7865 * Conditional \#VMEXIT.
7866 */
7867HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7868{
7869 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7870 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7871
7872 SVMEVENT Event;
7873 Event.u = 0;
7874 Event.n.u1Valid = 1;
7875 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7876 Event.n.u8Vector = X86_XCPT_AC;
7877 Event.n.u1ErrorCodeValid = 1;
7878 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7879 return VINF_SUCCESS;
7880}
7881
7882
7883/**
7884 * \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
7885 * Conditional \#VMEXIT.
7886 */
7887HMSVM_EXIT_DECL hmR0SvmExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7888{
7889 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7890 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
7891 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7892
7893 int rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
7894 if (rc == VINF_EM_RAW_GUEST_TRAP)
7895 {
7896 SVMEVENT Event;
7897 Event.u = 0;
7898 Event.n.u1Valid = 1;
7899 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7900 Event.n.u8Vector = X86_XCPT_BP;
7901 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7902 }
7903
7904 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
7905 return rc;
7906}
7907
7908
7909#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(VBOX_WITH_NESTED_HWVIRT_SVM)
7910/**
7911 * \#VMEXIT handler for generic exceptions. Conditional \#VMEXIT.
7912 */
7913HMSVM_EXIT_DECL hmR0SvmExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7914{
7915 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7916 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
7917
7918 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7919 uint8_t const uVector = pVmcb->ctrl.u64ExitCode - SVM_EXIT_XCPT_0;
7920 uint32_t const uErrCode = pVmcb->ctrl.u64ExitInfo1;
7921 Assert(pSvmTransient->u64ExitCode == pVmcb->ctrl.u64ExitCode);
7922 Assert(uVector <= X86_XCPT_LAST);
7923 Log4(("hmR0SvmExitXcptGeneric: uVector=%#x uErrCode=%u\n", uVector, uErrCode));
7924
7925 SVMEVENT Event;
7926 Event.u = 0;
7927 Event.n.u1Valid = 1;
7928 Event.n.u3Type = SVM_EVENT_EXCEPTION;
7929 Event.n.u8Vector = uVector;
7930 switch (uVector)
7931 {
7932 /* Shouldn't be here for reflecting #PFs (among other things, the fault address isn't passed along). */
7933 case X86_XCPT_PF: AssertMsgFailed(("hmR0SvmExitXcptGeneric: Unexpected exception")); return VERR_SVM_IPE_5;
7934 case X86_XCPT_DF:
7935 case X86_XCPT_TS:
7936 case X86_XCPT_NP:
7937 case X86_XCPT_SS:
7938 case X86_XCPT_GP:
7939 case X86_XCPT_AC:
7940 {
7941 Event.n.u1ErrorCodeValid = 1;
7942 Event.n.u32ErrorCode = uErrCode;
7943 break;
7944 }
7945 }
7946
7947 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
7948 return VINF_SUCCESS;
7949}
7950#endif
7951
7952#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
7953/**
7954 * \#VMEXIT handler for CLGI (SVM_EXIT_CLGI). Conditional \#VMEXIT.
7955 */
7956HMSVM_EXIT_DECL hmR0SvmExitClgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7957{
7958 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7959 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK
7960 | CPUMCTX_EXTRN_HWVIRT);
7961
7962#ifdef VBOX_STRICT
7963 PCSVMVMCB pVmcbTmp = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7964 Assert(pVmcbTmp);
7965 Assert(!pVmcbTmp->ctrl.IntCtrl.n.u1VGifEnable);
7966 RT_NOREF(pVmcbTmp);
7967#endif
7968
7969 /** @todo Stat. */
7970 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClgi); */
7971 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7972 VBOXSTRICTRC rcStrict = IEMExecDecodedClgi(pVCpu, cbInstr);
7973 return VBOXSTRICTRC_VAL(rcStrict);
7974}
7975
7976
7977/**
7978 * \#VMEXIT handler for STGI (SVM_EXIT_STGI). Conditional \#VMEXIT.
7979 */
7980HMSVM_EXIT_DECL hmR0SvmExitStgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
7981{
7982 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
7983 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK
7984 | CPUMCTX_EXTRN_HWVIRT);
7985
7986 /*
7987 * When VGIF is not used we always intercept STGI instructions. When VGIF is used,
7988 * we only intercept STGI when events are pending for GIF to become 1.
7989 */
7990 PSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
7991 if (pVmcb->ctrl.IntCtrl.n.u1VGifEnable)
7992 hmR0SvmClearCtrlIntercept(pVCpu, pCtx, pVmcb, SVM_CTRL_INTERCEPT_STGI);
7993
7994 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
7995 VBOXSTRICTRC rcStrict = IEMExecDecodedStgi(pVCpu, cbInstr);
7996 return VBOXSTRICTRC_VAL(rcStrict);
7997}
7998
7999
8000/**
8001 * \#VMEXIT handler for VMLOAD (SVM_EXIT_VMLOAD). Conditional \#VMEXIT.
8002 */
8003HMSVM_EXIT_DECL hmR0SvmExitVmload(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8004{
8005 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8006 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK
8007 | CPUMCTX_EXTRN_FS
8008 | CPUMCTX_EXTRN_GS
8009 | CPUMCTX_EXTRN_TR
8010 | CPUMCTX_EXTRN_LDTR
8011 | CPUMCTX_EXTRN_KERNEL_GS_BASE
8012 | CPUMCTX_EXTRN_SYSCALL_MSRS
8013 | CPUMCTX_EXTRN_SYSENTER_MSRS);
8014
8015#ifdef VBOX_STRICT
8016 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
8017 Assert(pVmcb);
8018 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
8019 RT_NOREF(pVmcb);
8020#endif
8021
8022 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8023 VBOXSTRICTRC rcStrict = IEMExecDecodedVmload(pVCpu, cbInstr);
8024 if (rcStrict == VINF_SUCCESS)
8025 {
8026 /* We skip flagging changes made to LSTAR, STAR, SFMASK and other MSRs as they are always re-loaded. */
8027 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS
8028 | HM_CHANGED_GUEST_TR
8029 | HM_CHANGED_GUEST_LDTR
8030 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
8031 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
8032 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
8033 }
8034 return VBOXSTRICTRC_VAL(rcStrict);
8035}
8036
8037
8038/**
8039 * \#VMEXIT handler for VMSAVE (SVM_EXIT_VMSAVE). Conditional \#VMEXIT.
8040 */
8041HMSVM_EXIT_DECL hmR0SvmExitVmsave(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8042{
8043 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8044 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
8045
8046#ifdef VBOX_STRICT
8047 PCSVMVMCB pVmcb = hmR0SvmGetCurrentVmcb(pVCpu, pCtx);
8048 Assert(pVmcb);
8049 Assert(!pVmcb->ctrl.LbrVirt.n.u1VirtVmsaveVmload);
8050 RT_NOREF(pVmcb);
8051#endif
8052
8053 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8054 VBOXSTRICTRC rcStrict = IEMExecDecodedVmsave(pVCpu, cbInstr);
8055 return VBOXSTRICTRC_VAL(rcStrict);
8056}
8057
8058
8059/**
8060 * \#VMEXIT handler for INVLPGA (SVM_EXIT_INVLPGA). Conditional \#VMEXIT.
8061 */
8062HMSVM_EXIT_DECL hmR0SvmExitInvlpga(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8063{
8064 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8065 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, IEM_CPUMCTX_EXTRN_MUST_MASK);
8066
8067 /** @todo Stat. */
8068 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpga); */
8069 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8070 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpga(pVCpu, cbInstr);
8071 return VBOXSTRICTRC_VAL(rcStrict);
8072}
8073
8074
8075/**
8076 * \#VMEXIT handler for STGI (SVM_EXIT_VMRUN). Conditional \#VMEXIT.
8077 */
8078HMSVM_EXIT_DECL hmR0SvmExitVmrun(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8079{
8080 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8081 /** @todo Only save and reload what VMRUN changes (e.g. skip LDTR, TR etc). */
8082 HMSVM_CPUMCTX_IMPORT_STATE(pVCpu, pCtx, HMSVM_CPUMCTX_EXTRN_ALL);
8083
8084 VBOXSTRICTRC rcStrict;
8085 uint8_t const cbInstr = hmR0SvmGetInstrLengthHwAssist(pVCpu, pCtx, 3);
8086 rcStrict = IEMExecDecodedVmrun(pVCpu, cbInstr);
8087 Log4(("IEMExecDecodedVmrun: returned %d\n", VBOXSTRICTRC_VAL(rcStrict)));
8088 if (rcStrict == VINF_SUCCESS)
8089 {
8090 rcStrict = VINF_SVM_VMRUN;
8091 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
8092 }
8093 return VBOXSTRICTRC_VAL(rcStrict);
8094}
8095
8096
8097/**
8098 * Nested-guest \#VMEXIT handler for debug exceptions (SVM_EXIT_XCPT_1).
8099 * Unconditional \#VMEXIT.
8100 */
8101HMSVM_EXIT_DECL hmR0SvmNestedExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8102{
8103 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8104 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
8105
8106 if (pVCpu->hm.s.Event.fPending)
8107 {
8108 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
8109 return VINF_EM_RAW_INJECT_TRPM_EVENT;
8110 }
8111
8112 hmR0SvmSetPendingXcptDB(pVCpu);
8113 return VINF_SUCCESS;
8114}
8115
8116
8117/**
8118 * Nested-guest \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_XCPT_3).
8119 * Conditional \#VMEXIT.
8120 */
8121HMSVM_EXIT_DECL hmR0SvmNestedExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
8122{
8123 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
8124 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
8125
8126 SVMEVENT Event;
8127 Event.u = 0;
8128 Event.n.u1Valid = 1;
8129 Event.n.u3Type = SVM_EVENT_EXCEPTION;
8130 Event.n.u8Vector = X86_XCPT_BP;
8131 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
8132 return VINF_SUCCESS;
8133}
8134
8135#endif /* VBOX_WITH_NESTED_HWVIRT_SVM */
8136
8137
8138/** @} */
8139
Note: See TracBrowser for help on using the repository browser.

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