VirtualBox

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

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

VMM/HMSVMR0: Check single-step debugging following the #UD patch & execute operation for KVM hypercalls.

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

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