VirtualBox

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

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

VMM/HM: Fixes to MSRPM bit accesses. Implemented merging of guest and nested-guest MSRPMs. Other nits and cleanups.

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

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