VirtualBox

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

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

VMM: Fix HMSvmEventToTrpmEventType to convert #BP and #OF to TRPM_SOFTWARE_INT.

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