VirtualBox

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

Last change on this file since 72886 was 72886, checked in by vboxsync, 6 years ago

VMM/HMR0: Import the guest-state (incl. keeper bits) on the ring-3 callback triggered by ring-0 assertions.

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

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