VirtualBox

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

Last change on this file since 87390 was 87387, checked in by vboxsync, 4 years ago

Moved the hmR0SvmVmRun* prototypes to HMInternal.h.

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

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