VirtualBox

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

Last change on this file since 79532 was 79532, checked in by vboxsync, 5 years ago

VMM/HMSVMR0: Nested SVM: bugref:7243 Doxygen burn fix.

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