VirtualBox

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

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

VMM/HMSVMR0: Nested Hw.virt: Sync VMCPU_FF_INTERRUPT_NESTED_GUEST while returning from executing the nested-guest.

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