VirtualBox

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

Last change on this file since 69046 was 69046, checked in by vboxsync, 8 years ago

Global: replace fall-through comments with RT_FALL_THRU().
bugref:8192: gcc warnings

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

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