VirtualBox

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

Last change on this file since 71906 was 71906, checked in by vboxsync, 7 years ago

VMM/HMSVMR0: Clean up VMCB initialization.

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