VirtualBox

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

Last change on this file since 82968 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

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

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