VirtualBox

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

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

VMM/HMSVMR0: Comment.

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

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