VirtualBox

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

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

VMM: Kicking out 32-bit host support - SVM. bugref:9511

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

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