VirtualBox

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

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

VMM: Nested Hw.virt: Avoid calling ASM helpers for modifying the MSR bitmaps.

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