VirtualBox

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

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

SVM: Emulate intercepted IRET to avoid injecting a pending NMI too early (see bugref:6208).

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