VirtualBox

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

Last change on this file since 91513 was 91308, checked in by vboxsync, 3 years ago

VMM/CPUM: Comments/todos for some big CPUMCTX members. bugref:10093

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

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