VirtualBox

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

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

VMM/HMSVMR0: Fallback to IEMExecOne() on certain VM-exits on CPUs that do not provide the instruction length.
Fixes setting HM_CHANGED_XXX flags on VINF_IEM_RAISED_XCPT on some VM-exits.
Fixes an incorrect assertion in hmR0SvmCallRing3Callback().

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