VirtualBox

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

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

VMM/HMSVMR0: nit.

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