VirtualBox

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

Last change on this file since 86776 was 86730, checked in by vboxsync, 4 years ago

VMM/DBGF: Move the DBGFRZ* part into VMMAll as the trap handlers will be required to work in Ring-3 before long to be able to support the IEM execute in Ring-3 and NEM cases, bugref:9837

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette