VirtualBox

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

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

VMM/HMSVMR0: Remove confusing HMSVM_SYNC_FULL_NESTED_GUEST_STATE option. Figure out if it's needed later.

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