VirtualBox

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

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

VMM/HMSVMR0: Build fix (defined but not used function).

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