VirtualBox

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

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

EM,HM,IEM: Replaced EMInterpretWrmsr with IEMExecDecodedWrmsr.

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