VirtualBox

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

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

VMM/HMSVMR0: Dead code.

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

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