VirtualBox

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

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

VMM/HMSVMR0: Temporarily enable full guest sync to try diagnose nested SVM breakage.

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