VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HMVMXR0.cpp@ 67783

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

VMM/HMVMXR0: Don't assert about error code for exceptions when in real-mode in hmR0VmxInjectEventVmcs.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 597.8 KB
Line 
1/* $Id: HMVMXR0.cpp 67783 2017-07-05 04:09:04Z vboxsync $ */
2/** @file
3 * HM VMX (Intel VT-x) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2012-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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/x86.h>
24#include <iprt/asm-amd64-x86.h>
25#include <iprt/thread.h>
26
27#include <VBox/vmm/pdmapi.h>
28#include <VBox/vmm/dbgf.h>
29#include <VBox/vmm/iem.h>
30#include <VBox/vmm/iom.h>
31#include <VBox/vmm/selm.h>
32#include <VBox/vmm/tm.h>
33#include <VBox/vmm/gim.h>
34#include <VBox/vmm/apic.h>
35#ifdef VBOX_WITH_REM
36# include <VBox/vmm/rem.h>
37#endif
38#include "HMInternal.h"
39#include <VBox/vmm/vm.h>
40#include "HMVMXR0.h"
41#include "dtrace/VBoxVMM.h"
42
43#define HMVMX_USE_IEM_EVENT_REFLECTION
44#ifdef DEBUG_ramshankar
45# define HMVMX_ALWAYS_SAVE_GUEST_RFLAGS
46# define HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE
47# define HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
48# define HMVMX_ALWAYS_CHECK_GUEST_STATE
49# define HMVMX_ALWAYS_TRAP_ALL_XCPTS
50# define HMVMX_ALWAYS_TRAP_PF
51# define HMVMX_ALWAYS_SWAP_FPU_STATE
52# define HMVMX_ALWAYS_FLUSH_TLB
53# define HMVMX_ALWAYS_SWAP_EFER
54#endif
55
56
57/*********************************************************************************************************************************
58* Defined Constants And Macros *
59*********************************************************************************************************************************/
60/** Use the function table. */
61#define HMVMX_USE_FUNCTION_TABLE
62
63/** Determine which tagged-TLB flush handler to use. */
64#define HMVMX_FLUSH_TAGGED_TLB_EPT_VPID 0
65#define HMVMX_FLUSH_TAGGED_TLB_EPT 1
66#define HMVMX_FLUSH_TAGGED_TLB_VPID 2
67#define HMVMX_FLUSH_TAGGED_TLB_NONE 3
68
69/** @name Updated-guest-state flags.
70 * @{ */
71#define HMVMX_UPDATED_GUEST_RIP RT_BIT(0)
72#define HMVMX_UPDATED_GUEST_RSP RT_BIT(1)
73#define HMVMX_UPDATED_GUEST_RFLAGS RT_BIT(2)
74#define HMVMX_UPDATED_GUEST_CR0 RT_BIT(3)
75#define HMVMX_UPDATED_GUEST_CR3 RT_BIT(4)
76#define HMVMX_UPDATED_GUEST_CR4 RT_BIT(5)
77#define HMVMX_UPDATED_GUEST_GDTR RT_BIT(6)
78#define HMVMX_UPDATED_GUEST_IDTR RT_BIT(7)
79#define HMVMX_UPDATED_GUEST_LDTR RT_BIT(8)
80#define HMVMX_UPDATED_GUEST_TR RT_BIT(9)
81#define HMVMX_UPDATED_GUEST_SEGMENT_REGS RT_BIT(10)
82#define HMVMX_UPDATED_GUEST_DR7 RT_BIT(11)
83#define HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR RT_BIT(12)
84#define HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR RT_BIT(13)
85#define HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR RT_BIT(14)
86#define HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS RT_BIT(15)
87#define HMVMX_UPDATED_GUEST_LAZY_MSRS RT_BIT(16)
88#define HMVMX_UPDATED_GUEST_ACTIVITY_STATE RT_BIT(17)
89#define HMVMX_UPDATED_GUEST_INTR_STATE RT_BIT(18)
90#define HMVMX_UPDATED_GUEST_APIC_STATE RT_BIT(19)
91#define HMVMX_UPDATED_GUEST_ALL ( HMVMX_UPDATED_GUEST_RIP \
92 | HMVMX_UPDATED_GUEST_RSP \
93 | HMVMX_UPDATED_GUEST_RFLAGS \
94 | HMVMX_UPDATED_GUEST_CR0 \
95 | HMVMX_UPDATED_GUEST_CR3 \
96 | HMVMX_UPDATED_GUEST_CR4 \
97 | HMVMX_UPDATED_GUEST_GDTR \
98 | HMVMX_UPDATED_GUEST_IDTR \
99 | HMVMX_UPDATED_GUEST_LDTR \
100 | HMVMX_UPDATED_GUEST_TR \
101 | HMVMX_UPDATED_GUEST_SEGMENT_REGS \
102 | HMVMX_UPDATED_GUEST_DR7 \
103 | HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR \
104 | HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR \
105 | HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR \
106 | HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS \
107 | HMVMX_UPDATED_GUEST_LAZY_MSRS \
108 | HMVMX_UPDATED_GUEST_ACTIVITY_STATE \
109 | HMVMX_UPDATED_GUEST_INTR_STATE \
110 | HMVMX_UPDATED_GUEST_APIC_STATE)
111/** @} */
112
113/** @name
114 * Flags to skip redundant reads of some common VMCS fields that are not part of
115 * the guest-CPU state but are in the transient structure.
116 */
117#define HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_INFO RT_BIT(0)
118#define HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_ERROR_CODE RT_BIT(1)
119#define HMVMX_UPDATED_TRANSIENT_EXIT_QUALIFICATION RT_BIT(2)
120#define HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_LEN RT_BIT(3)
121#define HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO RT_BIT(4)
122#define HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_ERROR_CODE RT_BIT(5)
123#define HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_INFO RT_BIT(6)
124/** @} */
125
126/** @name
127 * States of the VMCS.
128 *
129 * This does not reflect all possible VMCS states but currently only those
130 * needed for maintaining the VMCS consistently even when thread-context hooks
131 * are used. Maybe later this can be extended (i.e. Nested Virtualization).
132 */
133#define HMVMX_VMCS_STATE_CLEAR RT_BIT(0)
134#define HMVMX_VMCS_STATE_ACTIVE RT_BIT(1)
135#define HMVMX_VMCS_STATE_LAUNCHED RT_BIT(2)
136/** @} */
137
138/**
139 * Exception bitmap mask for real-mode guests (real-on-v86).
140 *
141 * We need to intercept all exceptions manually except:
142 * - \#NM, \#MF handled in hmR0VmxLoadSharedCR0().
143 * - \#AC and \#DB are always intercepted to prevent the CPU from deadlocking
144 * due to bugs in Intel CPUs.
145 * - \#PF need not be intercepted even in real-mode if we have Nested Paging
146 * support.
147 */
148#define HMVMX_REAL_MODE_XCPT_MASK ( RT_BIT(X86_XCPT_DE) /* always: | RT_BIT(X86_XCPT_DB) */ | RT_BIT(X86_XCPT_NMI) \
149 | RT_BIT(X86_XCPT_BP) | RT_BIT(X86_XCPT_OF) | RT_BIT(X86_XCPT_BR) \
150 | RT_BIT(X86_XCPT_UD) /* RT_BIT(X86_XCPT_NM) */ | RT_BIT(X86_XCPT_DF) \
151 | RT_BIT(X86_XCPT_CO_SEG_OVERRUN) | RT_BIT(X86_XCPT_TS) | RT_BIT(X86_XCPT_NP) \
152 | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_GP) /* RT_BIT(X86_XCPT_PF) */ \
153 /* RT_BIT(X86_XCPT_MF) always: | RT_BIT(X86_XCPT_AC) */ | RT_BIT(X86_XCPT_MC) \
154 | RT_BIT(X86_XCPT_XF))
155
156/**
157 * Exception bitmap mask for all contributory exceptions.
158 *
159 * Page fault is deliberately excluded here as it's conditional as to whether
160 * it's contributory or benign. Page faults are handled separately.
161 */
162#define HMVMX_CONTRIBUTORY_XCPT_MASK ( RT_BIT(X86_XCPT_GP) | RT_BIT(X86_XCPT_NP) | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_TS) \
163 | RT_BIT(X86_XCPT_DE))
164
165/** Maximum VM-instruction error number. */
166#define HMVMX_INSTR_ERROR_MAX 28
167
168/** Profiling macro. */
169#ifdef HM_PROFILE_EXIT_DISPATCH
170# define HMVMX_START_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitDispatch, ed)
171# define HMVMX_STOP_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitDispatch, ed)
172#else
173# define HMVMX_START_EXIT_DISPATCH_PROF() do { } while (0)
174# define HMVMX_STOP_EXIT_DISPATCH_PROF() do { } while (0)
175#endif
176
177/** Assert that preemption is disabled or covered by thread-context hooks. */
178#define HMVMX_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
179 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
180
181/** Assert that we haven't migrated CPUs when thread-context hooks are not
182 * used. */
183#define HMVMX_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
184 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
185 ("Illegal migration! Entered on CPU %u Current %u\n", \
186 pVCpu->hm.s.idEnteredCpu, RTMpCpuId())); \
187
188/** Helper macro for VM-exit handlers called unexpectedly. */
189#define HMVMX_RETURN_UNEXPECTED_EXIT() \
190 do { \
191 pVCpu->hm.s.u32HMError = pVmxTransient->uExitReason; \
192 return VERR_VMX_UNEXPECTED_EXIT; \
193 } while (0)
194
195
196/*********************************************************************************************************************************
197* Structures and Typedefs *
198*********************************************************************************************************************************/
199/**
200 * VMX transient state.
201 *
202 * A state structure for holding miscellaneous information across
203 * VMX non-root operation and restored after the transition.
204 */
205typedef struct VMXTRANSIENT
206{
207 /** The host's rflags/eflags. */
208 RTCCUINTREG fEFlags;
209#if HC_ARCH_BITS == 32
210 uint32_t u32Alignment0;
211#endif
212 /** The guest's TPR value used for TPR shadowing. */
213 uint8_t u8GuestTpr;
214 /** Alignment. */
215 uint8_t abAlignment0[7];
216
217 /** The basic VM-exit reason. */
218 uint16_t uExitReason;
219 /** Alignment. */
220 uint16_t u16Alignment0;
221 /** The VM-exit interruption error code. */
222 uint32_t uExitIntErrorCode;
223 /** The VM-exit exit code qualification. */
224 uint64_t uExitQualification;
225
226 /** The VM-exit interruption-information field. */
227 uint32_t uExitIntInfo;
228 /** The VM-exit instruction-length field. */
229 uint32_t cbInstr;
230 /** The VM-exit instruction-information field. */
231 union
232 {
233 /** Plain unsigned int representation. */
234 uint32_t u;
235 /** INS and OUTS information. */
236 struct
237 {
238 uint32_t u7Reserved0 : 7;
239 /** The address size; 0=16-bit, 1=32-bit, 2=64-bit, rest undefined. */
240 uint32_t u3AddrSize : 3;
241 uint32_t u5Reserved1 : 5;
242 /** The segment register (X86_SREG_XXX). */
243 uint32_t iSegReg : 3;
244 uint32_t uReserved2 : 14;
245 } StrIo;
246 } ExitInstrInfo;
247 /** Whether the VM-entry failed or not. */
248 bool fVMEntryFailed;
249 /** Alignment. */
250 uint8_t abAlignment1[3];
251
252 /** The VM-entry interruption-information field. */
253 uint32_t uEntryIntInfo;
254 /** The VM-entry exception error code field. */
255 uint32_t uEntryXcptErrorCode;
256 /** The VM-entry instruction length field. */
257 uint32_t cbEntryInstr;
258
259 /** IDT-vectoring information field. */
260 uint32_t uIdtVectoringInfo;
261 /** IDT-vectoring error code. */
262 uint32_t uIdtVectoringErrorCode;
263
264 /** Mask of currently read VMCS fields; HMVMX_UPDATED_TRANSIENT_*. */
265 uint32_t fVmcsFieldsRead;
266
267 /** Whether the guest FPU was active at the time of VM-exit. */
268 bool fWasGuestFPUStateActive;
269 /** Whether the guest debug state was active at the time of VM-exit. */
270 bool fWasGuestDebugStateActive;
271 /** Whether the hyper debug state was active at the time of VM-exit. */
272 bool fWasHyperDebugStateActive;
273 /** Whether TSC-offsetting should be setup before VM-entry. */
274 bool fUpdateTscOffsettingAndPreemptTimer;
275 /** Whether the VM-exit was caused by a page-fault during delivery of a
276 * contributory exception or a page-fault. */
277 bool fVectoringDoublePF;
278 /** Whether the VM-exit was caused by a page-fault during delivery of an
279 * external interrupt or NMI. */
280 bool fVectoringPF;
281} VMXTRANSIENT;
282AssertCompileMemberAlignment(VMXTRANSIENT, uExitReason, sizeof(uint64_t));
283AssertCompileMemberAlignment(VMXTRANSIENT, uExitIntInfo, sizeof(uint64_t));
284AssertCompileMemberAlignment(VMXTRANSIENT, uEntryIntInfo, sizeof(uint64_t));
285AssertCompileMemberAlignment(VMXTRANSIENT, fWasGuestFPUStateActive, sizeof(uint64_t));
286AssertCompileMemberSize(VMXTRANSIENT, ExitInstrInfo, sizeof(uint32_t));
287/** Pointer to VMX transient state. */
288typedef VMXTRANSIENT *PVMXTRANSIENT;
289
290
291/**
292 * MSR-bitmap read permissions.
293 */
294typedef enum VMXMSREXITREAD
295{
296 /** Reading this MSR causes a VM-exit. */
297 VMXMSREXIT_INTERCEPT_READ = 0xb,
298 /** Reading this MSR does not cause a VM-exit. */
299 VMXMSREXIT_PASSTHRU_READ
300} VMXMSREXITREAD;
301/** Pointer to MSR-bitmap read permissions. */
302typedef VMXMSREXITREAD* PVMXMSREXITREAD;
303
304/**
305 * MSR-bitmap write permissions.
306 */
307typedef enum VMXMSREXITWRITE
308{
309 /** Writing to this MSR causes a VM-exit. */
310 VMXMSREXIT_INTERCEPT_WRITE = 0xd,
311 /** Writing to this MSR does not cause a VM-exit. */
312 VMXMSREXIT_PASSTHRU_WRITE
313} VMXMSREXITWRITE;
314/** Pointer to MSR-bitmap write permissions. */
315typedef VMXMSREXITWRITE* PVMXMSREXITWRITE;
316
317
318/**
319 * VMX VM-exit handler.
320 *
321 * @returns Strict VBox status code (i.e. informational status codes too).
322 * @param pVCpu The cross context virtual CPU structure.
323 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
324 * out-of-sync. Make sure to update the required
325 * fields before using them.
326 * @param pVmxTransient Pointer to the VMX-transient structure.
327 */
328#ifndef HMVMX_USE_FUNCTION_TABLE
329typedef VBOXSTRICTRC FNVMXEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
330#else
331typedef DECLCALLBACK(VBOXSTRICTRC) FNVMXEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
332/** Pointer to VM-exit handler. */
333typedef FNVMXEXITHANDLER *PFNVMXEXITHANDLER;
334#endif
335
336/**
337 * VMX VM-exit handler, non-strict status code.
338 *
339 * This is generally the same as FNVMXEXITHANDLER, the NSRC bit is just FYI.
340 *
341 * @returns VBox status code, no informational status code returned.
342 * @param pVCpu The cross context virtual CPU structure.
343 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
344 * out-of-sync. Make sure to update the required
345 * fields before using them.
346 * @param pVmxTransient Pointer to the VMX-transient structure.
347 *
348 * @remarks This is not used on anything returning VERR_EM_INTERPRETER as the
349 * use of that status code will be replaced with VINF_EM_SOMETHING
350 * later when switching over to IEM.
351 */
352#ifndef HMVMX_USE_FUNCTION_TABLE
353typedef int FNVMXEXITHANDLERNSRC(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
354#else
355typedef FNVMXEXITHANDLER FNVMXEXITHANDLERNSRC;
356#endif
357
358
359/*********************************************************************************************************************************
360* Internal Functions *
361*********************************************************************************************************************************/
362static void hmR0VmxFlushEpt(PVMCPU pVCpu, VMXFLUSHEPT enmFlush);
363static void hmR0VmxFlushVpid(PVM pVM, PVMCPU pVCpu, VMXFLUSHVPID enmFlush, RTGCPTR GCPtr);
364static void hmR0VmxClearIntNmiWindowsVmcs(PVMCPU pVCpu);
365static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint64_t u64IntInfo, uint32_t cbInstr,
366 uint32_t u32ErrCode, RTGCUINTREG GCPtrFaultAddress,
367 bool fStepping, uint32_t *puIntState);
368#if HC_ARCH_BITS == 32
369static int hmR0VmxInitVmcsReadCache(PVM pVM, PVMCPU pVCpu);
370#endif
371#ifndef HMVMX_USE_FUNCTION_TABLE
372DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, uint32_t rcReason);
373# define HMVMX_EXIT_DECL DECLINLINE(VBOXSTRICTRC)
374# define HMVMX_EXIT_NSRC_DECL DECLINLINE(int)
375#else
376# define HMVMX_EXIT_DECL static DECLCALLBACK(VBOXSTRICTRC)
377# define HMVMX_EXIT_NSRC_DECL HMVMX_EXIT_DECL
378#endif
379
380
381/** @name VM-exit handlers.
382 * @{
383 */
384static FNVMXEXITHANDLER hmR0VmxExitXcptOrNmi;
385static FNVMXEXITHANDLER hmR0VmxExitExtInt;
386static FNVMXEXITHANDLER hmR0VmxExitTripleFault;
387static FNVMXEXITHANDLERNSRC hmR0VmxExitInitSignal;
388static FNVMXEXITHANDLERNSRC hmR0VmxExitSipi;
389static FNVMXEXITHANDLERNSRC hmR0VmxExitIoSmi;
390static FNVMXEXITHANDLERNSRC hmR0VmxExitSmi;
391static FNVMXEXITHANDLERNSRC hmR0VmxExitIntWindow;
392static FNVMXEXITHANDLERNSRC hmR0VmxExitNmiWindow;
393static FNVMXEXITHANDLER hmR0VmxExitTaskSwitch;
394static FNVMXEXITHANDLER hmR0VmxExitCpuid;
395static FNVMXEXITHANDLER hmR0VmxExitGetsec;
396static FNVMXEXITHANDLER hmR0VmxExitHlt;
397static FNVMXEXITHANDLERNSRC hmR0VmxExitInvd;
398static FNVMXEXITHANDLER hmR0VmxExitInvlpg;
399static FNVMXEXITHANDLER hmR0VmxExitRdpmc;
400static FNVMXEXITHANDLER hmR0VmxExitVmcall;
401static FNVMXEXITHANDLER hmR0VmxExitRdtsc;
402static FNVMXEXITHANDLERNSRC hmR0VmxExitRsm;
403static FNVMXEXITHANDLERNSRC hmR0VmxExitSetPendingXcptUD;
404static FNVMXEXITHANDLER hmR0VmxExitMovCRx;
405static FNVMXEXITHANDLER hmR0VmxExitMovDRx;
406static FNVMXEXITHANDLER hmR0VmxExitIoInstr;
407static FNVMXEXITHANDLER hmR0VmxExitRdmsr;
408static FNVMXEXITHANDLER hmR0VmxExitWrmsr;
409static FNVMXEXITHANDLERNSRC hmR0VmxExitErrInvalidGuestState;
410static FNVMXEXITHANDLERNSRC hmR0VmxExitErrMsrLoad;
411static FNVMXEXITHANDLERNSRC hmR0VmxExitErrUndefined;
412static FNVMXEXITHANDLER hmR0VmxExitMwait;
413static FNVMXEXITHANDLER hmR0VmxExitMtf;
414static FNVMXEXITHANDLER hmR0VmxExitMonitor;
415static FNVMXEXITHANDLER hmR0VmxExitPause;
416static FNVMXEXITHANDLERNSRC hmR0VmxExitErrMachineCheck;
417static FNVMXEXITHANDLERNSRC hmR0VmxExitTprBelowThreshold;
418static FNVMXEXITHANDLER hmR0VmxExitApicAccess;
419static FNVMXEXITHANDLER hmR0VmxExitXdtrAccess;
420static FNVMXEXITHANDLER hmR0VmxExitXdtrAccess;
421static FNVMXEXITHANDLER hmR0VmxExitEptViolation;
422static FNVMXEXITHANDLER hmR0VmxExitEptMisconfig;
423static FNVMXEXITHANDLER hmR0VmxExitRdtscp;
424static FNVMXEXITHANDLER hmR0VmxExitPreemptTimer;
425static FNVMXEXITHANDLERNSRC hmR0VmxExitWbinvd;
426static FNVMXEXITHANDLER hmR0VmxExitXsetbv;
427static FNVMXEXITHANDLER hmR0VmxExitRdrand;
428static FNVMXEXITHANDLER hmR0VmxExitInvpcid;
429/** @} */
430
431static int hmR0VmxExitXcptNM(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
432static int hmR0VmxExitXcptPF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
433static int hmR0VmxExitXcptMF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
434static int hmR0VmxExitXcptDB(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
435static int hmR0VmxExitXcptBP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
436static int hmR0VmxExitXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
437static int hmR0VmxExitXcptAC(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
438static int hmR0VmxExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
439static uint32_t hmR0VmxCheckGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
440
441
442/*********************************************************************************************************************************
443* Global Variables *
444*********************************************************************************************************************************/
445#ifdef HMVMX_USE_FUNCTION_TABLE
446
447/**
448 * VMX_EXIT dispatch table.
449 */
450static const PFNVMXEXITHANDLER g_apfnVMExitHandlers[VMX_EXIT_MAX + 1] =
451{
452 /* 00 VMX_EXIT_XCPT_OR_NMI */ hmR0VmxExitXcptOrNmi,
453 /* 01 VMX_EXIT_EXT_INT */ hmR0VmxExitExtInt,
454 /* 02 VMX_EXIT_TRIPLE_FAULT */ hmR0VmxExitTripleFault,
455 /* 03 VMX_EXIT_INIT_SIGNAL */ hmR0VmxExitInitSignal,
456 /* 04 VMX_EXIT_SIPI */ hmR0VmxExitSipi,
457 /* 05 VMX_EXIT_IO_SMI */ hmR0VmxExitIoSmi,
458 /* 06 VMX_EXIT_SMI */ hmR0VmxExitSmi,
459 /* 07 VMX_EXIT_INT_WINDOW */ hmR0VmxExitIntWindow,
460 /* 08 VMX_EXIT_NMI_WINDOW */ hmR0VmxExitNmiWindow,
461 /* 09 VMX_EXIT_TASK_SWITCH */ hmR0VmxExitTaskSwitch,
462 /* 10 VMX_EXIT_CPUID */ hmR0VmxExitCpuid,
463 /* 11 VMX_EXIT_GETSEC */ hmR0VmxExitGetsec,
464 /* 12 VMX_EXIT_HLT */ hmR0VmxExitHlt,
465 /* 13 VMX_EXIT_INVD */ hmR0VmxExitInvd,
466 /* 14 VMX_EXIT_INVLPG */ hmR0VmxExitInvlpg,
467 /* 15 VMX_EXIT_RDPMC */ hmR0VmxExitRdpmc,
468 /* 16 VMX_EXIT_RDTSC */ hmR0VmxExitRdtsc,
469 /* 17 VMX_EXIT_RSM */ hmR0VmxExitRsm,
470 /* 18 VMX_EXIT_VMCALL */ hmR0VmxExitVmcall,
471 /* 19 VMX_EXIT_VMCLEAR */ hmR0VmxExitSetPendingXcptUD,
472 /* 20 VMX_EXIT_VMLAUNCH */ hmR0VmxExitSetPendingXcptUD,
473 /* 21 VMX_EXIT_VMPTRLD */ hmR0VmxExitSetPendingXcptUD,
474 /* 22 VMX_EXIT_VMPTRST */ hmR0VmxExitSetPendingXcptUD,
475 /* 23 VMX_EXIT_VMREAD */ hmR0VmxExitSetPendingXcptUD,
476 /* 24 VMX_EXIT_VMRESUME */ hmR0VmxExitSetPendingXcptUD,
477 /* 25 VMX_EXIT_VMWRITE */ hmR0VmxExitSetPendingXcptUD,
478 /* 26 VMX_EXIT_VMXOFF */ hmR0VmxExitSetPendingXcptUD,
479 /* 27 VMX_EXIT_VMXON */ hmR0VmxExitSetPendingXcptUD,
480 /* 28 VMX_EXIT_MOV_CRX */ hmR0VmxExitMovCRx,
481 /* 29 VMX_EXIT_MOV_DRX */ hmR0VmxExitMovDRx,
482 /* 30 VMX_EXIT_IO_INSTR */ hmR0VmxExitIoInstr,
483 /* 31 VMX_EXIT_RDMSR */ hmR0VmxExitRdmsr,
484 /* 32 VMX_EXIT_WRMSR */ hmR0VmxExitWrmsr,
485 /* 33 VMX_EXIT_ERR_INVALID_GUEST_STATE */ hmR0VmxExitErrInvalidGuestState,
486 /* 34 VMX_EXIT_ERR_MSR_LOAD */ hmR0VmxExitErrMsrLoad,
487 /* 35 UNDEFINED */ hmR0VmxExitErrUndefined,
488 /* 36 VMX_EXIT_MWAIT */ hmR0VmxExitMwait,
489 /* 37 VMX_EXIT_MTF */ hmR0VmxExitMtf,
490 /* 38 UNDEFINED */ hmR0VmxExitErrUndefined,
491 /* 39 VMX_EXIT_MONITOR */ hmR0VmxExitMonitor,
492 /* 40 UNDEFINED */ hmR0VmxExitPause,
493 /* 41 VMX_EXIT_PAUSE */ hmR0VmxExitErrMachineCheck,
494 /* 42 VMX_EXIT_ERR_MACHINE_CHECK */ hmR0VmxExitErrUndefined,
495 /* 43 VMX_EXIT_TPR_BELOW_THRESHOLD */ hmR0VmxExitTprBelowThreshold,
496 /* 44 VMX_EXIT_APIC_ACCESS */ hmR0VmxExitApicAccess,
497 /* 45 UNDEFINED */ hmR0VmxExitErrUndefined,
498 /* 46 VMX_EXIT_XDTR_ACCESS */ hmR0VmxExitXdtrAccess,
499 /* 47 VMX_EXIT_TR_ACCESS */ hmR0VmxExitXdtrAccess,
500 /* 48 VMX_EXIT_EPT_VIOLATION */ hmR0VmxExitEptViolation,
501 /* 49 VMX_EXIT_EPT_MISCONFIG */ hmR0VmxExitEptMisconfig,
502 /* 50 VMX_EXIT_INVEPT */ hmR0VmxExitSetPendingXcptUD,
503 /* 51 VMX_EXIT_RDTSCP */ hmR0VmxExitRdtscp,
504 /* 52 VMX_EXIT_PREEMPT_TIMER */ hmR0VmxExitPreemptTimer,
505 /* 53 VMX_EXIT_INVVPID */ hmR0VmxExitSetPendingXcptUD,
506 /* 54 VMX_EXIT_WBINVD */ hmR0VmxExitWbinvd,
507 /* 55 VMX_EXIT_XSETBV */ hmR0VmxExitXsetbv,
508 /* 56 VMX_EXIT_APIC_WRITE */ hmR0VmxExitErrUndefined,
509 /* 57 VMX_EXIT_RDRAND */ hmR0VmxExitRdrand,
510 /* 58 VMX_EXIT_INVPCID */ hmR0VmxExitInvpcid,
511 /* 59 VMX_EXIT_VMFUNC */ hmR0VmxExitSetPendingXcptUD,
512 /* 60 VMX_EXIT_ENCLS */ hmR0VmxExitErrUndefined,
513 /* 61 VMX_EXIT_RDSEED */ hmR0VmxExitErrUndefined, /* only spurious exits, so undefined */
514 /* 62 VMX_EXIT_PML_FULL */ hmR0VmxExitErrUndefined,
515 /* 63 VMX_EXIT_XSAVES */ hmR0VmxExitSetPendingXcptUD,
516 /* 64 VMX_EXIT_XRSTORS */ hmR0VmxExitSetPendingXcptUD,
517};
518#endif /* HMVMX_USE_FUNCTION_TABLE */
519
520#ifdef VBOX_STRICT
521static const char * const g_apszVmxInstrErrors[HMVMX_INSTR_ERROR_MAX + 1] =
522{
523 /* 0 */ "(Not Used)",
524 /* 1 */ "VMCALL executed in VMX root operation.",
525 /* 2 */ "VMCLEAR with invalid physical address.",
526 /* 3 */ "VMCLEAR with VMXON pointer.",
527 /* 4 */ "VMLAUNCH with non-clear VMCS.",
528 /* 5 */ "VMRESUME with non-launched VMCS.",
529 /* 6 */ "VMRESUME after VMXOFF",
530 /* 7 */ "VM-entry with invalid control fields.",
531 /* 8 */ "VM-entry with invalid host state fields.",
532 /* 9 */ "VMPTRLD with invalid physical address.",
533 /* 10 */ "VMPTRLD with VMXON pointer.",
534 /* 11 */ "VMPTRLD with incorrect revision identifier.",
535 /* 12 */ "VMREAD/VMWRITE from/to unsupported VMCS component.",
536 /* 13 */ "VMWRITE to read-only VMCS component.",
537 /* 14 */ "(Not Used)",
538 /* 15 */ "VMXON executed in VMX root operation.",
539 /* 16 */ "VM-entry with invalid executive-VMCS pointer.",
540 /* 17 */ "VM-entry with non-launched executing VMCS.",
541 /* 18 */ "VM-entry with executive-VMCS pointer not VMXON pointer.",
542 /* 19 */ "VMCALL with non-clear VMCS.",
543 /* 20 */ "VMCALL with invalid VM-exit control fields.",
544 /* 21 */ "(Not Used)",
545 /* 22 */ "VMCALL with incorrect MSEG revision identifier.",
546 /* 23 */ "VMXOFF under dual monitor treatment of SMIs and SMM.",
547 /* 24 */ "VMCALL with invalid SMM-monitor features.",
548 /* 25 */ "VM-entry with invalid VM-execution control fields in executive VMCS.",
549 /* 26 */ "VM-entry with events blocked by MOV SS.",
550 /* 27 */ "(Not Used)",
551 /* 28 */ "Invalid operand to INVEPT/INVVPID."
552};
553#endif /* VBOX_STRICT */
554
555
556
557/**
558 * Updates the VM's last error record.
559 *
560 * If there was a VMX instruction error, reads the error data from the VMCS and
561 * updates VCPU's last error record as well.
562 *
563 * @param pVM The cross context VM structure.
564 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
565 * Can be NULL if @a rc is not VERR_VMX_UNABLE_TO_START_VM or
566 * VERR_VMX_INVALID_VMCS_FIELD.
567 * @param rc The error code.
568 */
569static void hmR0VmxUpdateErrorRecord(PVM pVM, PVMCPU pVCpu, int rc)
570{
571 AssertPtr(pVM);
572 if ( rc == VERR_VMX_INVALID_VMCS_FIELD
573 || rc == VERR_VMX_UNABLE_TO_START_VM)
574 {
575 AssertPtrReturnVoid(pVCpu);
576 VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
577 }
578 pVM->hm.s.lLastError = rc;
579}
580
581
582/**
583 * Reads the VM-entry interruption-information field from the VMCS into the VMX
584 * transient structure.
585 *
586 * @returns VBox status code.
587 * @param pVmxTransient Pointer to the VMX transient structure.
588 *
589 * @remarks No-long-jump zone!!!
590 */
591DECLINLINE(int) hmR0VmxReadEntryIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
592{
593 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &pVmxTransient->uEntryIntInfo);
594 AssertRCReturn(rc, rc);
595 return VINF_SUCCESS;
596}
597
598
599#ifdef VBOX_STRICT
600/**
601 * Reads the VM-entry exception error code field from the VMCS into
602 * the VMX transient structure.
603 *
604 * @returns VBox status code.
605 * @param pVmxTransient Pointer to the VMX transient structure.
606 *
607 * @remarks No-long-jump zone!!!
608 */
609DECLINLINE(int) hmR0VmxReadEntryXcptErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
610{
611 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &pVmxTransient->uEntryXcptErrorCode);
612 AssertRCReturn(rc, rc);
613 return VINF_SUCCESS;
614}
615#endif /* VBOX_STRICT */
616
617
618#ifdef VBOX_STRICT
619/**
620 * Reads the VM-entry exception error code field from the VMCS into
621 * the VMX transient structure.
622 *
623 * @returns VBox status code.
624 * @param pVmxTransient Pointer to the VMX transient structure.
625 *
626 * @remarks No-long-jump zone!!!
627 */
628DECLINLINE(int) hmR0VmxReadEntryInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
629{
630 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &pVmxTransient->cbEntryInstr);
631 AssertRCReturn(rc, rc);
632 return VINF_SUCCESS;
633}
634#endif /* VBOX_STRICT */
635
636
637/**
638 * Reads the VM-exit interruption-information field from the VMCS into the VMX
639 * transient structure.
640 *
641 * @returns VBox status code.
642 * @param pVmxTransient Pointer to the VMX transient structure.
643 */
644DECLINLINE(int) hmR0VmxReadExitIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
645{
646 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO))
647 {
648 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
649 AssertRCReturn(rc, rc);
650 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO;
651 }
652 return VINF_SUCCESS;
653}
654
655
656/**
657 * Reads the VM-exit interruption error code from the VMCS into the VMX
658 * transient structure.
659 *
660 * @returns VBox status code.
661 * @param pVmxTransient Pointer to the VMX transient structure.
662 */
663DECLINLINE(int) hmR0VmxReadExitIntErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
664{
665 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_ERROR_CODE))
666 {
667 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
668 AssertRCReturn(rc, rc);
669 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_ERROR_CODE;
670 }
671 return VINF_SUCCESS;
672}
673
674
675/**
676 * Reads the VM-exit instruction length field from the VMCS into the VMX
677 * transient structure.
678 *
679 * @returns VBox status code.
680 * @param pVmxTransient Pointer to the VMX transient structure.
681 */
682DECLINLINE(int) hmR0VmxReadExitInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
683{
684 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_LEN))
685 {
686 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbInstr);
687 AssertRCReturn(rc, rc);
688 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_LEN;
689 }
690 return VINF_SUCCESS;
691}
692
693
694/**
695 * Reads the VM-exit instruction-information field from the VMCS into
696 * the VMX transient structure.
697 *
698 * @returns VBox status code.
699 * @param pVmxTransient Pointer to the VMX transient structure.
700 */
701DECLINLINE(int) hmR0VmxReadExitInstrInfoVmcs(PVMXTRANSIENT pVmxTransient)
702{
703 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_INFO))
704 {
705 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
706 AssertRCReturn(rc, rc);
707 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_INFO;
708 }
709 return VINF_SUCCESS;
710}
711
712
713/**
714 * Reads the exit code qualification from the VMCS into the VMX transient
715 * structure.
716 *
717 * @returns VBox status code.
718 * @param pVCpu The cross context virtual CPU structure of the
719 * calling EMT. (Required for the VMCS cache case.)
720 * @param pVmxTransient Pointer to the VMX transient structure.
721 */
722DECLINLINE(int) hmR0VmxReadExitQualificationVmcs(PVMCPU pVCpu, PVMXTRANSIENT pVmxTransient)
723{
724 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_QUALIFICATION))
725 {
726 int rc = VMXReadVmcsGstN(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQualification); NOREF(pVCpu);
727 AssertRCReturn(rc, rc);
728 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_QUALIFICATION;
729 }
730 return VINF_SUCCESS;
731}
732
733
734/**
735 * Reads the IDT-vectoring information field from the VMCS into the VMX
736 * transient structure.
737 *
738 * @returns VBox status code.
739 * @param pVmxTransient Pointer to the VMX transient structure.
740 *
741 * @remarks No-long-jump zone!!!
742 */
743DECLINLINE(int) hmR0VmxReadIdtVectoringInfoVmcs(PVMXTRANSIENT pVmxTransient)
744{
745 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_INFO))
746 {
747 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_INFO, &pVmxTransient->uIdtVectoringInfo);
748 AssertRCReturn(rc, rc);
749 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_INFO;
750 }
751 return VINF_SUCCESS;
752}
753
754
755/**
756 * Reads the IDT-vectoring error code from the VMCS into the VMX
757 * transient structure.
758 *
759 * @returns VBox status code.
760 * @param pVmxTransient Pointer to the VMX transient structure.
761 */
762DECLINLINE(int) hmR0VmxReadIdtVectoringErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
763{
764 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_ERROR_CODE))
765 {
766 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
767 AssertRCReturn(rc, rc);
768 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_ERROR_CODE;
769 }
770 return VINF_SUCCESS;
771}
772
773
774/**
775 * Enters VMX root mode operation on the current CPU.
776 *
777 * @returns VBox status code.
778 * @param pVM The cross context VM structure. Can be
779 * NULL, after a resume.
780 * @param HCPhysCpuPage Physical address of the VMXON region.
781 * @param pvCpuPage Pointer to the VMXON region.
782 */
783static int hmR0VmxEnterRootMode(PVM pVM, RTHCPHYS HCPhysCpuPage, void *pvCpuPage)
784{
785 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
786 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
787 Assert(pvCpuPage);
788 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
789
790 if (pVM)
791 {
792 /* Write the VMCS revision dword to the VMXON region. */
793 *(uint32_t *)pvCpuPage = MSR_IA32_VMX_BASIC_INFO_VMCS_ID(pVM->hm.s.vmx.Msrs.u64BasicInfo);
794 }
795
796 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with CR4. */
797 RTCCUINTREG fEFlags = ASMIntDisableFlags();
798
799 /* Enable the VMX bit in CR4 if necessary. */
800 RTCCUINTREG uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
801
802 /* Enter VMX root mode. */
803 int rc = VMXEnable(HCPhysCpuPage);
804 if (RT_FAILURE(rc))
805 {
806 if (!(uOldCr4 & X86_CR4_VMXE))
807 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
808
809 if (pVM)
810 pVM->hm.s.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
811 }
812
813 /* Restore interrupts. */
814 ASMSetFlags(fEFlags);
815 return rc;
816}
817
818
819/**
820 * Exits VMX root mode operation on the current CPU.
821 *
822 * @returns VBox status code.
823 */
824static int hmR0VmxLeaveRootMode(void)
825{
826 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
827
828 /* Paranoid: Disable interrupts as, in theory, interrupts handlers might mess with CR4. */
829 RTCCUINTREG fEFlags = ASMIntDisableFlags();
830
831 /* If we're for some reason not in VMX root mode, then don't leave it. */
832 RTCCUINTREG uHostCR4 = ASMGetCR4();
833
834 int rc;
835 if (uHostCR4 & X86_CR4_VMXE)
836 {
837 /* Exit VMX root mode and clear the VMX bit in CR4. */
838 VMXDisable();
839 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
840 rc = VINF_SUCCESS;
841 }
842 else
843 rc = VERR_VMX_NOT_IN_VMX_ROOT_MODE;
844
845 /* Restore interrupts. */
846 ASMSetFlags(fEFlags);
847 return rc;
848}
849
850
851/**
852 * Allocates and maps one physically contiguous page. The allocated page is
853 * zero'd out. (Used by various VT-x structures).
854 *
855 * @returns IPRT status code.
856 * @param pMemObj Pointer to the ring-0 memory object.
857 * @param ppVirt Where to store the virtual address of the
858 * allocation.
859 * @param pHCPhys Where to store the physical address of the
860 * allocation.
861 */
862DECLINLINE(int) hmR0VmxPageAllocZ(PRTR0MEMOBJ pMemObj, PRTR0PTR ppVirt, PRTHCPHYS pHCPhys)
863{
864 AssertPtrReturn(pMemObj, VERR_INVALID_PARAMETER);
865 AssertPtrReturn(ppVirt, VERR_INVALID_PARAMETER);
866 AssertPtrReturn(pHCPhys, VERR_INVALID_PARAMETER);
867
868 int rc = RTR0MemObjAllocCont(pMemObj, PAGE_SIZE, false /* fExecutable */);
869 if (RT_FAILURE(rc))
870 return rc;
871 *ppVirt = RTR0MemObjAddress(*pMemObj);
872 *pHCPhys = RTR0MemObjGetPagePhysAddr(*pMemObj, 0 /* iPage */);
873 ASMMemZero32(*ppVirt, PAGE_SIZE);
874 return VINF_SUCCESS;
875}
876
877
878/**
879 * Frees and unmaps an allocated physical page.
880 *
881 * @param pMemObj Pointer to the ring-0 memory object.
882 * @param ppVirt Where to re-initialize the virtual address of
883 * allocation as 0.
884 * @param pHCPhys Where to re-initialize the physical address of the
885 * allocation as 0.
886 */
887DECLINLINE(void) hmR0VmxPageFree(PRTR0MEMOBJ pMemObj, PRTR0PTR ppVirt, PRTHCPHYS pHCPhys)
888{
889 AssertPtr(pMemObj);
890 AssertPtr(ppVirt);
891 AssertPtr(pHCPhys);
892 if (*pMemObj != NIL_RTR0MEMOBJ)
893 {
894 int rc = RTR0MemObjFree(*pMemObj, true /* fFreeMappings */);
895 AssertRC(rc);
896 *pMemObj = NIL_RTR0MEMOBJ;
897 *ppVirt = 0;
898 *pHCPhys = 0;
899 }
900}
901
902
903/**
904 * Worker function to free VT-x related structures.
905 *
906 * @returns IPRT status code.
907 * @param pVM The cross context VM structure.
908 */
909static void hmR0VmxStructsFree(PVM pVM)
910{
911 for (VMCPUID i = 0; i < pVM->cCpus; i++)
912 {
913 PVMCPU pVCpu = &pVM->aCpus[i];
914 AssertPtr(pVCpu);
915
916 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjHostMsr, &pVCpu->hm.s.vmx.pvHostMsr, &pVCpu->hm.s.vmx.HCPhysHostMsr);
917 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjGuestMsr, &pVCpu->hm.s.vmx.pvGuestMsr, &pVCpu->hm.s.vmx.HCPhysGuestMsr);
918
919 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
920 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjMsrBitmap, &pVCpu->hm.s.vmx.pvMsrBitmap, &pVCpu->hm.s.vmx.HCPhysMsrBitmap);
921
922 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjVmcs, &pVCpu->hm.s.vmx.pvVmcs, &pVCpu->hm.s.vmx.HCPhysVmcs);
923 }
924
925 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess, &pVM->hm.s.vmx.HCPhysApicAccess);
926#ifdef VBOX_WITH_CRASHDUMP_MAGIC
927 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjScratch, &pVM->hm.s.vmx.pbScratch, &pVM->hm.s.vmx.HCPhysScratch);
928#endif
929}
930
931
932/**
933 * Worker function to allocate VT-x related VM structures.
934 *
935 * @returns IPRT status code.
936 * @param pVM The cross context VM structure.
937 */
938static int hmR0VmxStructsAlloc(PVM pVM)
939{
940 /*
941 * Initialize members up-front so we can cleanup properly on allocation failure.
942 */
943#define VMXLOCAL_INIT_VM_MEMOBJ(a_Name, a_VirtPrefix) \
944 pVM->hm.s.vmx.hMemObj##a_Name = NIL_RTR0MEMOBJ; \
945 pVM->hm.s.vmx.a_VirtPrefix##a_Name = 0; \
946 pVM->hm.s.vmx.HCPhys##a_Name = 0;
947
948#define VMXLOCAL_INIT_VMCPU_MEMOBJ(a_Name, a_VirtPrefix) \
949 pVCpu->hm.s.vmx.hMemObj##a_Name = NIL_RTR0MEMOBJ; \
950 pVCpu->hm.s.vmx.a_VirtPrefix##a_Name = 0; \
951 pVCpu->hm.s.vmx.HCPhys##a_Name = 0;
952
953#ifdef VBOX_WITH_CRASHDUMP_MAGIC
954 VMXLOCAL_INIT_VM_MEMOBJ(Scratch, pv);
955#endif
956 VMXLOCAL_INIT_VM_MEMOBJ(ApicAccess, pb);
957
958 AssertCompile(sizeof(VMCPUID) == sizeof(pVM->cCpus));
959 for (VMCPUID i = 0; i < pVM->cCpus; i++)
960 {
961 PVMCPU pVCpu = &pVM->aCpus[i];
962 VMXLOCAL_INIT_VMCPU_MEMOBJ(Vmcs, pv);
963 VMXLOCAL_INIT_VMCPU_MEMOBJ(MsrBitmap, pv);
964 VMXLOCAL_INIT_VMCPU_MEMOBJ(GuestMsr, pv);
965 VMXLOCAL_INIT_VMCPU_MEMOBJ(HostMsr, pv);
966 }
967#undef VMXLOCAL_INIT_VMCPU_MEMOBJ
968#undef VMXLOCAL_INIT_VM_MEMOBJ
969
970 /* The VMCS size cannot be more than 4096 bytes. See Intel spec. Appendix A.1 "Basic VMX Information". */
971 AssertReturnStmt(MSR_IA32_VMX_BASIC_INFO_VMCS_SIZE(pVM->hm.s.vmx.Msrs.u64BasicInfo) <= PAGE_SIZE,
972 (&pVM->aCpus[0])->hm.s.u32HMError = VMX_UFC_INVALID_VMCS_SIZE,
973 VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO);
974
975 /*
976 * Allocate all the VT-x structures.
977 */
978 int rc = VINF_SUCCESS;
979#ifdef VBOX_WITH_CRASHDUMP_MAGIC
980 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjScratch, &pVM->hm.s.vmx.pbScratch, &pVM->hm.s.vmx.HCPhysScratch);
981 if (RT_FAILURE(rc))
982 goto cleanup;
983 strcpy((char *)pVM->hm.s.vmx.pbScratch, "SCRATCH Magic");
984 *(uint64_t *)(pVM->hm.s.vmx.pbScratch + 16) = UINT64_C(0xdeadbeefdeadbeef);
985#endif
986
987 /* Allocate the APIC-access page for trapping APIC accesses from the guest. */
988 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
989 {
990 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess,
991 &pVM->hm.s.vmx.HCPhysApicAccess);
992 if (RT_FAILURE(rc))
993 goto cleanup;
994 }
995
996 /*
997 * Initialize per-VCPU VT-x structures.
998 */
999 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1000 {
1001 PVMCPU pVCpu = &pVM->aCpus[i];
1002 AssertPtr(pVCpu);
1003
1004 /* Allocate the VM control structure (VMCS). */
1005 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjVmcs, &pVCpu->hm.s.vmx.pvVmcs, &pVCpu->hm.s.vmx.HCPhysVmcs);
1006 if (RT_FAILURE(rc))
1007 goto cleanup;
1008
1009 /* Get the allocated virtual-APIC page from the APIC device for transparent TPR accesses. */
1010 if ( PDMHasApic(pVM)
1011 && (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW))
1012 {
1013 rc = APICGetApicPageForCpu(pVCpu, &pVCpu->hm.s.vmx.HCPhysVirtApic, (PRTR0PTR)&pVCpu->hm.s.vmx.pbVirtApic,
1014 NULL /* pR3Ptr */, NULL /* pRCPtr */);
1015 if (RT_FAILURE(rc))
1016 goto cleanup;
1017 }
1018
1019 /*
1020 * Allocate the MSR-bitmap if supported by the CPU. The MSR-bitmap is for
1021 * transparent accesses of specific MSRs.
1022 *
1023 * If the condition for enabling MSR bitmaps changes here, don't forget to
1024 * update HMAreMsrBitmapsAvailable().
1025 */
1026 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1027 {
1028 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjMsrBitmap, &pVCpu->hm.s.vmx.pvMsrBitmap,
1029 &pVCpu->hm.s.vmx.HCPhysMsrBitmap);
1030 if (RT_FAILURE(rc))
1031 goto cleanup;
1032 ASMMemFill32(pVCpu->hm.s.vmx.pvMsrBitmap, PAGE_SIZE, UINT32_C(0xffffffff));
1033 }
1034
1035 /* Allocate the VM-entry MSR-load and VM-exit MSR-store page for the guest MSRs. */
1036 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjGuestMsr, &pVCpu->hm.s.vmx.pvGuestMsr, &pVCpu->hm.s.vmx.HCPhysGuestMsr);
1037 if (RT_FAILURE(rc))
1038 goto cleanup;
1039
1040 /* Allocate the VM-exit MSR-load page for the host MSRs. */
1041 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjHostMsr, &pVCpu->hm.s.vmx.pvHostMsr, &pVCpu->hm.s.vmx.HCPhysHostMsr);
1042 if (RT_FAILURE(rc))
1043 goto cleanup;
1044 }
1045
1046 return VINF_SUCCESS;
1047
1048cleanup:
1049 hmR0VmxStructsFree(pVM);
1050 return rc;
1051}
1052
1053
1054/**
1055 * Does global VT-x initialization (called during module initialization).
1056 *
1057 * @returns VBox status code.
1058 */
1059VMMR0DECL(int) VMXR0GlobalInit(void)
1060{
1061#ifdef HMVMX_USE_FUNCTION_TABLE
1062 AssertCompile(VMX_EXIT_MAX + 1 == RT_ELEMENTS(g_apfnVMExitHandlers));
1063# ifdef VBOX_STRICT
1064 for (unsigned i = 0; i < RT_ELEMENTS(g_apfnVMExitHandlers); i++)
1065 Assert(g_apfnVMExitHandlers[i]);
1066# endif
1067#endif
1068 return VINF_SUCCESS;
1069}
1070
1071
1072/**
1073 * Does global VT-x termination (called during module termination).
1074 */
1075VMMR0DECL(void) VMXR0GlobalTerm()
1076{
1077 /* Nothing to do currently. */
1078}
1079
1080
1081/**
1082 * Sets up and activates VT-x on the current CPU.
1083 *
1084 * @returns VBox status code.
1085 * @param pCpu Pointer to the global CPU info struct.
1086 * @param pVM The cross context VM structure. Can be
1087 * NULL after a host resume operation.
1088 * @param pvCpuPage Pointer to the VMXON region (can be NULL if @a
1089 * fEnabledByHost is @c true).
1090 * @param HCPhysCpuPage Physical address of the VMXON region (can be 0 if
1091 * @a fEnabledByHost is @c true).
1092 * @param fEnabledByHost Set if SUPR0EnableVTx() or similar was used to
1093 * enable VT-x on the host.
1094 * @param pvMsrs Opaque pointer to VMXMSRS struct.
1095 */
1096VMMR0DECL(int) VMXR0EnableCpu(PHMGLOBALCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
1097 void *pvMsrs)
1098{
1099 Assert(pCpu);
1100 Assert(pvMsrs);
1101 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1102
1103 /* Enable VT-x if it's not already enabled by the host. */
1104 if (!fEnabledByHost)
1105 {
1106 int rc = hmR0VmxEnterRootMode(pVM, HCPhysCpuPage, pvCpuPage);
1107 if (RT_FAILURE(rc))
1108 return rc;
1109 }
1110
1111 /*
1112 * Flush all EPT tagged-TLB entries (in case VirtualBox or any other hypervisor have been using EPTPs) so
1113 * we don't retain any stale guest-physical mappings which won't get invalidated when flushing by VPID.
1114 */
1115 PVMXMSRS pMsrs = (PVMXMSRS)pvMsrs;
1116 if (pMsrs->u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
1117 {
1118 hmR0VmxFlushEpt(NULL /* pVCpu */, VMXFLUSHEPT_ALL_CONTEXTS);
1119 pCpu->fFlushAsidBeforeUse = false;
1120 }
1121 else
1122 pCpu->fFlushAsidBeforeUse = true;
1123
1124 /* Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}. */
1125 ++pCpu->cTlbFlushes;
1126
1127 return VINF_SUCCESS;
1128}
1129
1130
1131/**
1132 * Deactivates VT-x on the current CPU.
1133 *
1134 * @returns VBox status code.
1135 * @param pCpu Pointer to the global CPU info struct.
1136 * @param pvCpuPage Pointer to the VMXON region.
1137 * @param HCPhysCpuPage Physical address of the VMXON region.
1138 *
1139 * @remarks This function should never be called when SUPR0EnableVTx() or
1140 * similar was used to enable VT-x on the host.
1141 */
1142VMMR0DECL(int) VMXR0DisableCpu(PHMGLOBALCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
1143{
1144 NOREF(pCpu);
1145 NOREF(pvCpuPage);
1146 NOREF(HCPhysCpuPage);
1147
1148 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1149 return hmR0VmxLeaveRootMode();
1150}
1151
1152
1153/**
1154 * Sets the permission bits for the specified MSR in the MSR bitmap.
1155 *
1156 * @param pVCpu The cross context virtual CPU structure.
1157 * @param uMsr The MSR value.
1158 * @param enmRead Whether reading this MSR causes a VM-exit.
1159 * @param enmWrite Whether writing this MSR causes a VM-exit.
1160 */
1161static void hmR0VmxSetMsrPermission(PVMCPU pVCpu, uint32_t uMsr, VMXMSREXITREAD enmRead, VMXMSREXITWRITE enmWrite)
1162{
1163 int32_t iBit;
1164 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.vmx.pvMsrBitmap;
1165
1166 /*
1167 * Layout:
1168 * 0x000 - 0x3ff - Low MSR read bits
1169 * 0x400 - 0x7ff - High MSR read bits
1170 * 0x800 - 0xbff - Low MSR write bits
1171 * 0xc00 - 0xfff - High MSR write bits
1172 */
1173 if (uMsr <= 0x00001FFF)
1174 iBit = uMsr;
1175 else if (uMsr - UINT32_C(0xC0000000) <= UINT32_C(0x00001FFF))
1176 {
1177 iBit = uMsr - UINT32_C(0xC0000000);
1178 pbMsrBitmap += 0x400;
1179 }
1180 else
1181 AssertMsgFailedReturnVoid(("hmR0VmxSetMsrPermission: Invalid MSR %#RX32\n", uMsr));
1182
1183 Assert(iBit <= 0x1fff);
1184 if (enmRead == VMXMSREXIT_INTERCEPT_READ)
1185 ASMBitSet(pbMsrBitmap, iBit);
1186 else
1187 ASMBitClear(pbMsrBitmap, iBit);
1188
1189 if (enmWrite == VMXMSREXIT_INTERCEPT_WRITE)
1190 ASMBitSet(pbMsrBitmap + 0x800, iBit);
1191 else
1192 ASMBitClear(pbMsrBitmap + 0x800, iBit);
1193}
1194
1195
1196#ifdef VBOX_STRICT
1197/**
1198 * Gets the permission bits for the specified MSR in the MSR bitmap.
1199 *
1200 * @returns VBox status code.
1201 * @retval VINF_SUCCESS if the specified MSR is found.
1202 * @retval VERR_NOT_FOUND if the specified MSR is not found.
1203 * @retval VERR_NOT_SUPPORTED if VT-x doesn't allow the MSR.
1204 *
1205 * @param pVCpu The cross context virtual CPU structure.
1206 * @param uMsr The MSR.
1207 * @param penmRead Where to store the read permissions.
1208 * @param penmWrite Where to store the write permissions.
1209 */
1210static int hmR0VmxGetMsrPermission(PVMCPU pVCpu, uint32_t uMsr, PVMXMSREXITREAD penmRead, PVMXMSREXITWRITE penmWrite)
1211{
1212 AssertPtrReturn(penmRead, VERR_INVALID_PARAMETER);
1213 AssertPtrReturn(penmWrite, VERR_INVALID_PARAMETER);
1214 int32_t iBit;
1215 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.vmx.pvMsrBitmap;
1216
1217 /* See hmR0VmxSetMsrPermission() for the layout. */
1218 if (uMsr <= 0x00001FFF)
1219 iBit = uMsr;
1220 else if ( uMsr >= 0xC0000000
1221 && uMsr <= 0xC0001FFF)
1222 {
1223 iBit = (uMsr - 0xC0000000);
1224 pbMsrBitmap += 0x400;
1225 }
1226 else
1227 AssertMsgFailedReturn(("hmR0VmxGetMsrPermission: Invalid MSR %#RX32\n", uMsr), VERR_NOT_SUPPORTED);
1228
1229 Assert(iBit <= 0x1fff);
1230 if (ASMBitTest(pbMsrBitmap, iBit))
1231 *penmRead = VMXMSREXIT_INTERCEPT_READ;
1232 else
1233 *penmRead = VMXMSREXIT_PASSTHRU_READ;
1234
1235 if (ASMBitTest(pbMsrBitmap + 0x800, iBit))
1236 *penmWrite = VMXMSREXIT_INTERCEPT_WRITE;
1237 else
1238 *penmWrite = VMXMSREXIT_PASSTHRU_WRITE;
1239 return VINF_SUCCESS;
1240}
1241#endif /* VBOX_STRICT */
1242
1243
1244/**
1245 * Updates the VMCS with the number of effective MSRs in the auto-load/store MSR
1246 * area.
1247 *
1248 * @returns VBox status code.
1249 * @param pVCpu The cross context virtual CPU structure.
1250 * @param cMsrs The number of MSRs.
1251 */
1252DECLINLINE(int) hmR0VmxSetAutoLoadStoreMsrCount(PVMCPU pVCpu, uint32_t cMsrs)
1253{
1254 /* Shouldn't ever happen but there -is- a number. We're well within the recommended 512. */
1255 uint32_t const cMaxSupportedMsrs = MSR_IA32_VMX_MISC_MAX_MSR(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.u64Misc);
1256 if (RT_UNLIKELY(cMsrs > cMaxSupportedMsrs))
1257 {
1258 LogRel(("CPU auto-load/store MSR count in VMCS exceeded cMsrs=%u Supported=%u.\n", cMsrs, cMaxSupportedMsrs));
1259 pVCpu->hm.s.u32HMError = VMX_UFC_INSUFFICIENT_GUEST_MSR_STORAGE;
1260 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
1261 }
1262
1263 /* Update number of guest MSRs to load/store across the world-switch. */
1264 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, cMsrs);
1265 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, cMsrs);
1266
1267 /* Update number of host MSRs to load after the world-switch. Identical to guest-MSR count as it's always paired. */
1268 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, cMsrs);
1269 AssertRCReturn(rc, rc);
1270
1271 /* Update the VCPU's copy of the MSR count. */
1272 pVCpu->hm.s.vmx.cMsrs = cMsrs;
1273
1274 return VINF_SUCCESS;
1275}
1276
1277
1278/**
1279 * Adds a new (or updates the value of an existing) guest/host MSR
1280 * pair to be swapped during the world-switch as part of the
1281 * auto-load/store MSR area in the VMCS.
1282 *
1283 * @returns VBox status code.
1284 * @param pVCpu The cross context virtual CPU structure.
1285 * @param uMsr The MSR.
1286 * @param uGuestMsrValue Value of the guest MSR.
1287 * @param fUpdateHostMsr Whether to update the value of the host MSR if
1288 * necessary.
1289 * @param pfAddedAndUpdated Where to store whether the MSR was added -and-
1290 * its value was updated. Optional, can be NULL.
1291 */
1292static int hmR0VmxAddAutoLoadStoreMsr(PVMCPU pVCpu, uint32_t uMsr, uint64_t uGuestMsrValue, bool fUpdateHostMsr,
1293 bool *pfAddedAndUpdated)
1294{
1295 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1296 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1297 uint32_t i;
1298 for (i = 0; i < cMsrs; i++)
1299 {
1300 if (pGuestMsr->u32Msr == uMsr)
1301 break;
1302 pGuestMsr++;
1303 }
1304
1305 bool fAdded = false;
1306 if (i == cMsrs)
1307 {
1308 ++cMsrs;
1309 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, cMsrs);
1310 AssertMsgRCReturn(rc, ("hmR0VmxAddAutoLoadStoreMsr: Insufficient space to add MSR %u\n", uMsr), rc);
1311
1312 /* Now that we're swapping MSRs during the world-switch, allow the guest to read/write them without causing VM-exits. */
1313 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1314 hmR0VmxSetMsrPermission(pVCpu, uMsr, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
1315
1316 fAdded = true;
1317 }
1318
1319 /* Update the MSR values in the auto-load/store MSR area. */
1320 pGuestMsr->u32Msr = uMsr;
1321 pGuestMsr->u64Value = uGuestMsrValue;
1322
1323 /* Create/update the MSR slot in the host MSR area. */
1324 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1325 pHostMsr += i;
1326 pHostMsr->u32Msr = uMsr;
1327
1328 /*
1329 * Update the host MSR only when requested by the caller AND when we're
1330 * adding it to the auto-load/store area. Otherwise, it would have been
1331 * updated by hmR0VmxSaveHostMsrs(). We do this for performance reasons.
1332 */
1333 bool fUpdatedMsrValue = false;
1334 if ( fAdded
1335 && fUpdateHostMsr)
1336 {
1337 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1338 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1339 pHostMsr->u64Value = ASMRdMsr(pHostMsr->u32Msr);
1340 fUpdatedMsrValue = true;
1341 }
1342
1343 if (pfAddedAndUpdated)
1344 *pfAddedAndUpdated = fUpdatedMsrValue;
1345 return VINF_SUCCESS;
1346}
1347
1348
1349/**
1350 * Removes a guest/host MSR pair to be swapped during the world-switch from the
1351 * auto-load/store MSR area in the VMCS.
1352 *
1353 * @returns VBox status code.
1354 * @param pVCpu The cross context virtual CPU structure.
1355 * @param uMsr The MSR.
1356 */
1357static int hmR0VmxRemoveAutoLoadStoreMsr(PVMCPU pVCpu, uint32_t uMsr)
1358{
1359 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1360 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1361 for (uint32_t i = 0; i < cMsrs; i++)
1362 {
1363 /* Find the MSR. */
1364 if (pGuestMsr->u32Msr == uMsr)
1365 {
1366 /* If it's the last MSR, simply reduce the count. */
1367 if (i == cMsrs - 1)
1368 {
1369 --cMsrs;
1370 break;
1371 }
1372
1373 /* Remove it by swapping the last MSR in place of it, and reducing the count. */
1374 PVMXAUTOMSR pLastGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1375 pLastGuestMsr += cMsrs - 1;
1376 pGuestMsr->u32Msr = pLastGuestMsr->u32Msr;
1377 pGuestMsr->u64Value = pLastGuestMsr->u64Value;
1378
1379 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1380 PVMXAUTOMSR pLastHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1381 pLastHostMsr += cMsrs - 1;
1382 pHostMsr->u32Msr = pLastHostMsr->u32Msr;
1383 pHostMsr->u64Value = pLastHostMsr->u64Value;
1384 --cMsrs;
1385 break;
1386 }
1387 pGuestMsr++;
1388 }
1389
1390 /* Update the VMCS if the count changed (meaning the MSR was found). */
1391 if (cMsrs != pVCpu->hm.s.vmx.cMsrs)
1392 {
1393 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, cMsrs);
1394 AssertRCReturn(rc, rc);
1395
1396 /* We're no longer swapping MSRs during the world-switch, intercept guest read/writes to them. */
1397 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1398 hmR0VmxSetMsrPermission(pVCpu, uMsr, VMXMSREXIT_INTERCEPT_READ, VMXMSREXIT_INTERCEPT_WRITE);
1399
1400 Log4(("Removed MSR %#RX32 new cMsrs=%u\n", uMsr, pVCpu->hm.s.vmx.cMsrs));
1401 return VINF_SUCCESS;
1402 }
1403
1404 return VERR_NOT_FOUND;
1405}
1406
1407
1408/**
1409 * Checks if the specified guest MSR is part of the auto-load/store area in
1410 * the VMCS.
1411 *
1412 * @returns true if found, false otherwise.
1413 * @param pVCpu The cross context virtual CPU structure.
1414 * @param uMsr The MSR to find.
1415 */
1416static bool hmR0VmxIsAutoLoadStoreGuestMsr(PVMCPU pVCpu, uint32_t uMsr)
1417{
1418 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1419 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1420
1421 for (uint32_t i = 0; i < cMsrs; i++, pGuestMsr++)
1422 {
1423 if (pGuestMsr->u32Msr == uMsr)
1424 return true;
1425 }
1426 return false;
1427}
1428
1429
1430/**
1431 * Updates the value of all host MSRs in the auto-load/store area in the VMCS.
1432 *
1433 * @param pVCpu The cross context virtual CPU structure.
1434 *
1435 * @remarks No-long-jump zone!!!
1436 */
1437static void hmR0VmxUpdateAutoLoadStoreHostMsrs(PVMCPU pVCpu)
1438{
1439 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1440 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1441 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1442 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1443
1444 for (uint32_t i = 0; i < cMsrs; i++, pHostMsr++, pGuestMsr++)
1445 {
1446 AssertReturnVoid(pHostMsr->u32Msr == pGuestMsr->u32Msr);
1447
1448 /*
1449 * Performance hack for the host EFER MSR. We use the cached value rather than re-read it.
1450 * Strict builds will catch mismatches in hmR0VmxCheckAutoLoadStoreMsrs(). See @bugref{7368}.
1451 */
1452 if (pHostMsr->u32Msr == MSR_K6_EFER)
1453 pHostMsr->u64Value = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostEfer;
1454 else
1455 pHostMsr->u64Value = ASMRdMsr(pHostMsr->u32Msr);
1456 }
1457
1458 pVCpu->hm.s.vmx.fUpdatedHostMsrs = true;
1459}
1460
1461
1462/**
1463 * Saves a set of host MSRs to allow read/write passthru access to the guest and
1464 * perform lazy restoration of the host MSRs while leaving VT-x.
1465 *
1466 * @param pVCpu The cross context virtual CPU structure.
1467 *
1468 * @remarks No-long-jump zone!!!
1469 */
1470static void hmR0VmxLazySaveHostMsrs(PVMCPU pVCpu)
1471{
1472 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1473
1474 /*
1475 * Note: If you're adding MSRs here, make sure to update the MSR-bitmap permissions in hmR0VmxSetupProcCtls().
1476 */
1477 if (!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST))
1478 {
1479 Assert(!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)); /* Guest MSRs better not be loaded now. */
1480#if HC_ARCH_BITS == 64
1481 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1482 {
1483 pVCpu->hm.s.vmx.u64HostLStarMsr = ASMRdMsr(MSR_K8_LSTAR);
1484 pVCpu->hm.s.vmx.u64HostStarMsr = ASMRdMsr(MSR_K6_STAR);
1485 pVCpu->hm.s.vmx.u64HostSFMaskMsr = ASMRdMsr(MSR_K8_SF_MASK);
1486 pVCpu->hm.s.vmx.u64HostKernelGSBaseMsr = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
1487 }
1488#endif
1489 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_SAVED_HOST;
1490 }
1491}
1492
1493
1494/**
1495 * Checks whether the MSR belongs to the set of guest MSRs that we restore
1496 * lazily while leaving VT-x.
1497 *
1498 * @returns true if it does, false otherwise.
1499 * @param pVCpu The cross context virtual CPU structure.
1500 * @param uMsr The MSR to check.
1501 */
1502static bool hmR0VmxIsLazyGuestMsr(PVMCPU pVCpu, uint32_t uMsr)
1503{
1504 NOREF(pVCpu);
1505#if HC_ARCH_BITS == 64
1506 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1507 {
1508 switch (uMsr)
1509 {
1510 case MSR_K8_LSTAR:
1511 case MSR_K6_STAR:
1512 case MSR_K8_SF_MASK:
1513 case MSR_K8_KERNEL_GS_BASE:
1514 return true;
1515 }
1516 }
1517#else
1518 RT_NOREF(pVCpu, uMsr);
1519#endif
1520 return false;
1521}
1522
1523
1524/**
1525 * Saves a set of guest MSRs back into the guest-CPU context.
1526 *
1527 * @param pVCpu The cross context virtual CPU structure.
1528 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1529 * out-of-sync. Make sure to update the required fields
1530 * before using them.
1531 *
1532 * @remarks No-long-jump zone!!!
1533 */
1534static void hmR0VmxLazySaveGuestMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1535{
1536 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1537 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1538
1539 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
1540 {
1541 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
1542#if HC_ARCH_BITS == 64
1543 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1544 {
1545 pMixedCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
1546 pMixedCtx->msrSTAR = ASMRdMsr(MSR_K6_STAR);
1547 pMixedCtx->msrSFMASK = ASMRdMsr(MSR_K8_SF_MASK);
1548 pMixedCtx->msrKERNELGSBASE = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
1549 }
1550#else
1551 NOREF(pMixedCtx);
1552#endif
1553 }
1554}
1555
1556
1557/**
1558 * Loads a set of guests MSRs to allow read/passthru to the guest.
1559 *
1560 * The name of this function is slightly confusing. This function does NOT
1561 * postpone loading, but loads the MSR right now. "hmR0VmxLazy" is simply a
1562 * common prefix for functions dealing with "lazy restoration" of the shared
1563 * MSRs.
1564 *
1565 * @param pVCpu The cross context virtual CPU structure.
1566 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1567 * out-of-sync. Make sure to update the required fields
1568 * before using them.
1569 *
1570 * @remarks No-long-jump zone!!!
1571 */
1572static void hmR0VmxLazyLoadGuestMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1573{
1574 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1575 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1576
1577 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
1578#if HC_ARCH_BITS == 64
1579 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1580 {
1581 /*
1582 * If the guest MSRs are not loaded -and- if all the guest MSRs are identical
1583 * to the MSRs on the CPU (which are the saved host MSRs, see assertion above) then
1584 * we can skip a few MSR writes.
1585 *
1586 * Otherwise, it implies either 1. they're not loaded, or 2. they're loaded but the
1587 * guest MSR values in the guest-CPU context might be different to what's currently
1588 * loaded in the CPU. In either case, we need to write the new guest MSR values to the
1589 * CPU, see @bugref{8728}.
1590 */
1591 if ( !(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
1592 && pMixedCtx->msrKERNELGSBASE == pVCpu->hm.s.vmx.u64HostKernelGSBaseMsr
1593 && pMixedCtx->msrLSTAR == pVCpu->hm.s.vmx.u64HostLStarMsr
1594 && pMixedCtx->msrSTAR == pVCpu->hm.s.vmx.u64HostStarMsr
1595 && pMixedCtx->msrSFMASK == pVCpu->hm.s.vmx.u64HostSFMaskMsr)
1596 {
1597#ifdef VBOX_STRICT
1598 Assert(ASMRdMsr(MSR_K8_KERNEL_GS_BASE) == pMixedCtx->msrKERNELGSBASE);
1599 Assert(ASMRdMsr(MSR_K8_LSTAR) == pMixedCtx->msrLSTAR);
1600 Assert(ASMRdMsr(MSR_K6_STAR) == pMixedCtx->msrSTAR);
1601 Assert(ASMRdMsr(MSR_K8_SF_MASK) == pMixedCtx->msrSFMASK);
1602#endif
1603 }
1604 else
1605 {
1606 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pMixedCtx->msrKERNELGSBASE);
1607 ASMWrMsr(MSR_K8_LSTAR, pMixedCtx->msrLSTAR);
1608 ASMWrMsr(MSR_K6_STAR, pMixedCtx->msrSTAR);
1609 ASMWrMsr(MSR_K8_SF_MASK, pMixedCtx->msrSFMASK);
1610 }
1611 }
1612#else
1613 RT_NOREF(pMixedCtx);
1614#endif
1615 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_LOADED_GUEST;
1616}
1617
1618
1619/**
1620 * Performs lazy restoration of the set of host MSRs if they were previously
1621 * loaded with guest MSR values.
1622 *
1623 * @param pVCpu The cross context virtual CPU structure.
1624 *
1625 * @remarks No-long-jump zone!!!
1626 * @remarks The guest MSRs should have been saved back into the guest-CPU
1627 * context by hmR0VmxSaveGuestLazyMsrs()!!!
1628 */
1629static void hmR0VmxLazyRestoreHostMsrs(PVMCPU pVCpu)
1630{
1631 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1632 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1633
1634 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
1635 {
1636 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
1637#if HC_ARCH_BITS == 64
1638 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1639 {
1640 ASMWrMsr(MSR_K8_LSTAR, pVCpu->hm.s.vmx.u64HostLStarMsr);
1641 ASMWrMsr(MSR_K6_STAR, pVCpu->hm.s.vmx.u64HostStarMsr);
1642 ASMWrMsr(MSR_K8_SF_MASK, pVCpu->hm.s.vmx.u64HostSFMaskMsr);
1643 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pVCpu->hm.s.vmx.u64HostKernelGSBaseMsr);
1644 }
1645#endif
1646 }
1647 pVCpu->hm.s.vmx.fLazyMsrs &= ~(VMX_LAZY_MSRS_LOADED_GUEST | VMX_LAZY_MSRS_SAVED_HOST);
1648}
1649
1650
1651/**
1652 * Verifies that our cached values of the VMCS controls are all
1653 * consistent with what's actually present in the VMCS.
1654 *
1655 * @returns VBox status code.
1656 * @param pVCpu The cross context virtual CPU structure.
1657 */
1658static int hmR0VmxCheckVmcsCtls(PVMCPU pVCpu)
1659{
1660 uint32_t u32Val;
1661 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
1662 AssertRCReturn(rc, rc);
1663 AssertMsgReturn(pVCpu->hm.s.vmx.u32EntryCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32EntryCtls, u32Val),
1664 VERR_VMX_ENTRY_CTLS_CACHE_INVALID);
1665
1666 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val);
1667 AssertRCReturn(rc, rc);
1668 AssertMsgReturn(pVCpu->hm.s.vmx.u32ExitCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32ExitCtls, u32Val),
1669 VERR_VMX_EXIT_CTLS_CACHE_INVALID);
1670
1671 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val);
1672 AssertRCReturn(rc, rc);
1673 AssertMsgReturn(pVCpu->hm.s.vmx.u32PinCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32PinCtls, u32Val),
1674 VERR_VMX_PIN_EXEC_CTLS_CACHE_INVALID);
1675
1676 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val);
1677 AssertRCReturn(rc, rc);
1678 AssertMsgReturn(pVCpu->hm.s.vmx.u32ProcCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32ProcCtls, u32Val),
1679 VERR_VMX_PROC_EXEC_CTLS_CACHE_INVALID);
1680
1681 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
1682 {
1683 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val);
1684 AssertRCReturn(rc, rc);
1685 AssertMsgReturn(pVCpu->hm.s.vmx.u32ProcCtls2 == u32Val,
1686 ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32ProcCtls2, u32Val),
1687 VERR_VMX_PROC_EXEC2_CTLS_CACHE_INVALID);
1688 }
1689
1690 return VINF_SUCCESS;
1691}
1692
1693
1694#ifdef VBOX_STRICT
1695/**
1696 * Verifies that our cached host EFER value has not changed
1697 * since we cached it.
1698 *
1699 * @param pVCpu The cross context virtual CPU structure.
1700 */
1701static void hmR0VmxCheckHostEferMsr(PVMCPU pVCpu)
1702{
1703 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1704
1705 if (pVCpu->hm.s.vmx.u32ExitCtls & VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR)
1706 {
1707 uint64_t u64Val;
1708 int rc = VMXReadVmcs64(VMX_VMCS64_HOST_EFER_FULL, &u64Val);
1709 AssertRC(rc);
1710
1711 uint64_t u64HostEferMsr = ASMRdMsr(MSR_K6_EFER);
1712 AssertMsgReturnVoid(u64HostEferMsr == u64Val, ("u64HostEferMsr=%#RX64 u64Val=%#RX64\n", u64HostEferMsr, u64Val));
1713 }
1714}
1715
1716
1717/**
1718 * Verifies whether the guest/host MSR pairs in the auto-load/store area in the
1719 * VMCS are correct.
1720 *
1721 * @param pVCpu The cross context virtual CPU structure.
1722 */
1723static void hmR0VmxCheckAutoLoadStoreMsrs(PVMCPU pVCpu)
1724{
1725 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1726
1727 /* Verify MSR counts in the VMCS are what we think it should be. */
1728 uint32_t cMsrs;
1729 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &cMsrs); AssertRC(rc);
1730 Assert(cMsrs == pVCpu->hm.s.vmx.cMsrs);
1731
1732 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &cMsrs); AssertRC(rc);
1733 Assert(cMsrs == pVCpu->hm.s.vmx.cMsrs);
1734
1735 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &cMsrs); AssertRC(rc);
1736 Assert(cMsrs == pVCpu->hm.s.vmx.cMsrs);
1737
1738 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1739 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1740 for (uint32_t i = 0; i < cMsrs; i++, pHostMsr++, pGuestMsr++)
1741 {
1742 /* Verify that the MSRs are paired properly and that the host MSR has the correct value. */
1743 AssertMsgReturnVoid(pHostMsr->u32Msr == pGuestMsr->u32Msr, ("HostMsr=%#RX32 GuestMsr=%#RX32 cMsrs=%u\n", pHostMsr->u32Msr,
1744 pGuestMsr->u32Msr, cMsrs));
1745
1746 uint64_t u64Msr = ASMRdMsr(pHostMsr->u32Msr);
1747 AssertMsgReturnVoid(pHostMsr->u64Value == u64Msr, ("u32Msr=%#RX32 VMCS Value=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
1748 pHostMsr->u32Msr, pHostMsr->u64Value, u64Msr, cMsrs));
1749
1750 /* Verify that the permissions are as expected in the MSR bitmap. */
1751 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1752 {
1753 VMXMSREXITREAD enmRead;
1754 VMXMSREXITWRITE enmWrite;
1755 rc = hmR0VmxGetMsrPermission(pVCpu, pGuestMsr->u32Msr, &enmRead, &enmWrite);
1756 AssertMsgReturnVoid(rc == VINF_SUCCESS, ("hmR0VmxGetMsrPermission! failed. rc=%Rrc\n", rc));
1757 if (pGuestMsr->u32Msr == MSR_K6_EFER)
1758 {
1759 AssertMsgReturnVoid(enmRead == VMXMSREXIT_INTERCEPT_READ, ("Passthru read for EFER!?\n"));
1760 AssertMsgReturnVoid(enmWrite == VMXMSREXIT_INTERCEPT_WRITE, ("Passthru write for EFER!?\n"));
1761 }
1762 else
1763 {
1764 AssertMsgReturnVoid(enmRead == VMXMSREXIT_PASSTHRU_READ, ("u32Msr=%#RX32 cMsrs=%u No passthru read!\n",
1765 pGuestMsr->u32Msr, cMsrs));
1766 AssertMsgReturnVoid(enmWrite == VMXMSREXIT_PASSTHRU_WRITE, ("u32Msr=%#RX32 cMsrs=%u No passthru write!\n",
1767 pGuestMsr->u32Msr, cMsrs));
1768 }
1769 }
1770 }
1771}
1772#endif /* VBOX_STRICT */
1773
1774
1775/**
1776 * Flushes the TLB using EPT.
1777 *
1778 * @returns VBox status code.
1779 * @param pVCpu The cross context virtual CPU structure of the calling
1780 * EMT. Can be NULL depending on @a enmFlush.
1781 * @param enmFlush Type of flush.
1782 *
1783 * @remarks Caller is responsible for making sure this function is called only
1784 * when NestedPaging is supported and providing @a enmFlush that is
1785 * supported by the CPU.
1786 * @remarks Can be called with interrupts disabled.
1787 */
1788static void hmR0VmxFlushEpt(PVMCPU pVCpu, VMXFLUSHEPT enmFlush)
1789{
1790 uint64_t au64Descriptor[2];
1791 if (enmFlush == VMXFLUSHEPT_ALL_CONTEXTS)
1792 au64Descriptor[0] = 0;
1793 else
1794 {
1795 Assert(pVCpu);
1796 au64Descriptor[0] = pVCpu->hm.s.vmx.HCPhysEPTP;
1797 }
1798 au64Descriptor[1] = 0; /* MBZ. Intel spec. 33.3 "VMX Instructions" */
1799
1800 int rc = VMXR0InvEPT(enmFlush, &au64Descriptor[0]);
1801 AssertMsg(rc == VINF_SUCCESS, ("VMXR0InvEPT %#x %RGv failed with %Rrc\n", enmFlush, pVCpu ? pVCpu->hm.s.vmx.HCPhysEPTP : 0,
1802 rc));
1803 if ( RT_SUCCESS(rc)
1804 && pVCpu)
1805 {
1806 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushNestedPaging);
1807 }
1808}
1809
1810
1811/**
1812 * Flushes the TLB using VPID.
1813 *
1814 * @returns VBox status code.
1815 * @param pVM The cross context VM structure.
1816 * @param pVCpu The cross context virtual CPU structure of the calling
1817 * EMT. Can be NULL depending on @a enmFlush.
1818 * @param enmFlush Type of flush.
1819 * @param GCPtr Virtual address of the page to flush (can be 0 depending
1820 * on @a enmFlush).
1821 *
1822 * @remarks Can be called with interrupts disabled.
1823 */
1824static void hmR0VmxFlushVpid(PVM pVM, PVMCPU pVCpu, VMXFLUSHVPID enmFlush, RTGCPTR GCPtr)
1825{
1826 NOREF(pVM);
1827 AssertPtr(pVM);
1828 Assert(pVM->hm.s.vmx.fVpid);
1829
1830 uint64_t au64Descriptor[2];
1831 if (enmFlush == VMXFLUSHVPID_ALL_CONTEXTS)
1832 {
1833 au64Descriptor[0] = 0;
1834 au64Descriptor[1] = 0;
1835 }
1836 else
1837 {
1838 AssertPtr(pVCpu);
1839 AssertMsg(pVCpu->hm.s.uCurrentAsid != 0, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
1840 AssertMsg(pVCpu->hm.s.uCurrentAsid <= UINT16_MAX, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
1841 au64Descriptor[0] = pVCpu->hm.s.uCurrentAsid;
1842 au64Descriptor[1] = GCPtr;
1843 }
1844
1845 int rc = VMXR0InvVPID(enmFlush, &au64Descriptor[0]); NOREF(rc);
1846 AssertMsg(rc == VINF_SUCCESS,
1847 ("VMXR0InvVPID %#x %u %RGv failed with %d\n", enmFlush, pVCpu ? pVCpu->hm.s.uCurrentAsid : 0, GCPtr, rc));
1848 if ( RT_SUCCESS(rc)
1849 && pVCpu)
1850 {
1851 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
1852 }
1853}
1854
1855
1856/**
1857 * Invalidates a guest page by guest virtual address. Only relevant for
1858 * EPT/VPID, otherwise there is nothing really to invalidate.
1859 *
1860 * @returns VBox status code.
1861 * @param pVM The cross context VM structure.
1862 * @param pVCpu The cross context virtual CPU structure.
1863 * @param GCVirt Guest virtual address of the page to invalidate.
1864 */
1865VMMR0DECL(int) VMXR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
1866{
1867 AssertPtr(pVM);
1868 AssertPtr(pVCpu);
1869 LogFlowFunc(("pVM=%p pVCpu=%p GCVirt=%RGv\n", pVM, pVCpu, GCVirt));
1870
1871 bool fFlushPending = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_FLUSH);
1872 if (!fFlushPending)
1873 {
1874 /*
1875 * We must invalidate the guest TLB entry in either case, we cannot ignore it even for the EPT case
1876 * See @bugref{6043} and @bugref{6177}.
1877 *
1878 * Set the VMCPU_FF_TLB_FLUSH force flag and flush before VM-entry in hmR0VmxFlushTLB*() as this
1879 * function maybe called in a loop with individual addresses.
1880 */
1881 if (pVM->hm.s.vmx.fVpid)
1882 {
1883 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
1884 {
1885 hmR0VmxFlushVpid(pVM, pVCpu, VMXFLUSHVPID_INDIV_ADDR, GCVirt);
1886 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
1887 }
1888 else
1889 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1890 }
1891 else if (pVM->hm.s.fNestedPaging)
1892 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1893 }
1894
1895 return VINF_SUCCESS;
1896}
1897
1898
1899/**
1900 * Invalidates a guest page by physical address. Only relevant for EPT/VPID,
1901 * otherwise there is nothing really to invalidate.
1902 *
1903 * @returns VBox status code.
1904 * @param pVM The cross context VM structure.
1905 * @param pVCpu The cross context virtual CPU structure.
1906 * @param GCPhys Guest physical address of the page to invalidate.
1907 */
1908VMMR0DECL(int) VMXR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
1909{
1910 NOREF(pVM); NOREF(GCPhys);
1911 LogFlowFunc(("%RGp\n", GCPhys));
1912
1913 /*
1914 * We cannot flush a page by guest-physical address. invvpid takes only a linear address while invept only flushes
1915 * by EPT not individual addresses. We update the force flag here and flush before the next VM-entry in hmR0VmxFlushTLB*().
1916 * This function might be called in a loop. This should cause a flush-by-EPT if EPT is in use. See @bugref{6568}.
1917 */
1918 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1919 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgPhys);
1920 return VINF_SUCCESS;
1921}
1922
1923
1924/**
1925 * Dummy placeholder for tagged-TLB flush handling before VM-entry. Used in the
1926 * case where neither EPT nor VPID is supported by the CPU.
1927 *
1928 * @param pVM The cross context VM structure.
1929 * @param pVCpu The cross context virtual CPU structure.
1930 * @param pCpu Pointer to the global HM struct.
1931 *
1932 * @remarks Called with interrupts disabled.
1933 */
1934static void hmR0VmxFlushTaggedTlbNone(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1935{
1936 AssertPtr(pVCpu);
1937 AssertPtr(pCpu);
1938 NOREF(pVM);
1939
1940 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
1941
1942 Assert(pCpu->idCpu != NIL_RTCPUID);
1943 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
1944 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1945 pVCpu->hm.s.fForceTLBFlush = false;
1946 return;
1947}
1948
1949
1950/**
1951 * Flushes the tagged-TLB entries for EPT+VPID CPUs as necessary.
1952 *
1953 * @param pVM The cross context VM structure.
1954 * @param pVCpu The cross context virtual CPU structure.
1955 * @param pCpu Pointer to the global HM CPU struct.
1956 * @remarks All references to "ASID" in this function pertains to "VPID" in
1957 * Intel's nomenclature. The reason is, to avoid confusion in compare
1958 * statements since the host-CPU copies are named "ASID".
1959 *
1960 * @remarks Called with interrupts disabled.
1961 */
1962static void hmR0VmxFlushTaggedTlbBoth(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1963{
1964#ifdef VBOX_WITH_STATISTICS
1965 bool fTlbFlushed = false;
1966# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { fTlbFlushed = true; } while (0)
1967# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { \
1968 if (!fTlbFlushed) \
1969 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch); \
1970 } while (0)
1971#else
1972# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { } while (0)
1973# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { } while (0)
1974#endif
1975
1976 AssertPtr(pVM);
1977 AssertPtr(pCpu);
1978 AssertPtr(pVCpu);
1979 Assert(pCpu->idCpu != NIL_RTCPUID);
1980
1981 AssertMsg(pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid,
1982 ("hmR0VmxFlushTaggedTlbBoth cannot be invoked unless NestedPaging & VPID are enabled."
1983 "fNestedPaging=%RTbool fVpid=%RTbool", pVM->hm.s.fNestedPaging, pVM->hm.s.vmx.fVpid));
1984
1985 /*
1986 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
1987 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB
1988 * or the host CPU is online after a suspend/resume, so we cannot reuse the current ASID anymore.
1989 */
1990 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
1991 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
1992 {
1993 ++pCpu->uCurrentAsid;
1994 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
1995 {
1996 pCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0. */
1997 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
1998 pCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
1999 }
2000
2001 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
2002 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
2003 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
2004
2005 /*
2006 * Flush by EPT when we get rescheduled to a new host CPU to ensure EPT-only tagged mappings are also
2007 * invalidated. We don't need to flush-by-VPID here as flushing by EPT covers it. See @bugref{6568}.
2008 */
2009 hmR0VmxFlushEpt(pVCpu, pVM->hm.s.vmx.enmFlushEpt);
2010 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2011 HMVMX_SET_TAGGED_TLB_FLUSHED();
2012 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH); /* Already flushed-by-EPT, skip doing it again below. */
2013 }
2014
2015 /* Check for explicit TLB flushes. */
2016 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2017 {
2018 /*
2019 * Changes to the EPT paging structure by VMM requires flushing by EPT as the CPU creates
2020 * guest-physical (only EPT-tagged) mappings while traversing the EPT tables when EPT is in use.
2021 * Flushing by VPID will only flush linear (only VPID-tagged) and combined (EPT+VPID tagged) mappings
2022 * but not guest-physical mappings.
2023 * See Intel spec. 28.3.2 "Creating and Using Cached Translation Information". See @bugref{6568}.
2024 */
2025 hmR0VmxFlushEpt(pVCpu, pVM->hm.s.vmx.enmFlushEpt);
2026 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2027 HMVMX_SET_TAGGED_TLB_FLUSHED();
2028 }
2029
2030 pVCpu->hm.s.fForceTLBFlush = false;
2031 HMVMX_UPDATE_FLUSH_SKIPPED_STAT();
2032
2033 Assert(pVCpu->hm.s.idLastCpu == pCpu->idCpu);
2034 Assert(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes);
2035 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
2036 ("Flush count mismatch for cpu %d (%u vs %u)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
2037 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
2038 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pCpu->idCpu,
2039 pCpu->uCurrentAsid, pCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
2040 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
2041 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
2042
2043 /* Update VMCS with the VPID. */
2044 int rc = VMXWriteVmcs32(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
2045 AssertRC(rc);
2046
2047#undef HMVMX_SET_TAGGED_TLB_FLUSHED
2048}
2049
2050
2051/**
2052 * Flushes the tagged-TLB entries for EPT CPUs as necessary.
2053 *
2054 * @returns VBox status code.
2055 * @param pVM The cross context VM structure.
2056 * @param pVCpu The cross context virtual CPU structure.
2057 * @param pCpu Pointer to the global HM CPU struct.
2058 *
2059 * @remarks Called with interrupts disabled.
2060 */
2061static void hmR0VmxFlushTaggedTlbEpt(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2062{
2063 AssertPtr(pVM);
2064 AssertPtr(pVCpu);
2065 AssertPtr(pCpu);
2066 Assert(pCpu->idCpu != NIL_RTCPUID);
2067 AssertMsg(pVM->hm.s.fNestedPaging, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with NestedPaging disabled."));
2068 AssertMsg(!pVM->hm.s.vmx.fVpid, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with VPID enabled."));
2069
2070 /*
2071 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
2072 * A change in the TLB flush count implies the host CPU is online after a suspend/resume.
2073 */
2074 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
2075 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
2076 {
2077 pVCpu->hm.s.fForceTLBFlush = true;
2078 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2079 }
2080
2081 /* Check for explicit TLB flushes. */
2082 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2083 {
2084 pVCpu->hm.s.fForceTLBFlush = true;
2085 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2086 }
2087
2088 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
2089 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
2090
2091 if (pVCpu->hm.s.fForceTLBFlush)
2092 {
2093 hmR0VmxFlushEpt(pVCpu, pVM->hm.s.vmx.enmFlushEpt);
2094 pVCpu->hm.s.fForceTLBFlush = false;
2095 }
2096}
2097
2098
2099/**
2100 * Flushes the tagged-TLB entries for VPID CPUs as necessary.
2101 *
2102 * @returns VBox status code.
2103 * @param pVM The cross context VM structure.
2104 * @param pVCpu The cross context virtual CPU structure.
2105 * @param pCpu Pointer to the global HM CPU struct.
2106 *
2107 * @remarks Called with interrupts disabled.
2108 */
2109static void hmR0VmxFlushTaggedTlbVpid(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2110{
2111 AssertPtr(pVM);
2112 AssertPtr(pVCpu);
2113 AssertPtr(pCpu);
2114 Assert(pCpu->idCpu != NIL_RTCPUID);
2115 AssertMsg(pVM->hm.s.vmx.fVpid, ("hmR0VmxFlushTlbVpid cannot be invoked with VPID disabled."));
2116 AssertMsg(!pVM->hm.s.fNestedPaging, ("hmR0VmxFlushTlbVpid cannot be invoked with NestedPaging enabled"));
2117
2118 /*
2119 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
2120 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB
2121 * or the host CPU is online after a suspend/resume, so we cannot reuse the current ASID anymore.
2122 */
2123 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
2124 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
2125 {
2126 pVCpu->hm.s.fForceTLBFlush = true;
2127 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2128 }
2129
2130 /* Check for explicit TLB flushes. */
2131 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2132 {
2133 /*
2134 * If we ever support VPID flush combinations other than ALL or SINGLE-context (see hmR0VmxSetupTaggedTlb())
2135 * we would need to explicitly flush in this case (add an fExplicitFlush = true here and change the
2136 * pCpu->fFlushAsidBeforeUse check below to include fExplicitFlush's too) - an obscure corner case.
2137 */
2138 pVCpu->hm.s.fForceTLBFlush = true;
2139 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2140 }
2141
2142 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
2143 if (pVCpu->hm.s.fForceTLBFlush)
2144 {
2145 ++pCpu->uCurrentAsid;
2146 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
2147 {
2148 pCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0 */
2149 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
2150 pCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
2151 }
2152
2153 pVCpu->hm.s.fForceTLBFlush = false;
2154 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
2155 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
2156 if (pCpu->fFlushAsidBeforeUse)
2157 {
2158 if (pVM->hm.s.vmx.enmFlushVpid == VMXFLUSHVPID_SINGLE_CONTEXT)
2159 hmR0VmxFlushVpid(pVM, pVCpu, VMXFLUSHVPID_SINGLE_CONTEXT, 0 /* GCPtr */);
2160 else if (pVM->hm.s.vmx.enmFlushVpid == VMXFLUSHVPID_ALL_CONTEXTS)
2161 {
2162 hmR0VmxFlushVpid(pVM, pVCpu, VMXFLUSHVPID_ALL_CONTEXTS, 0 /* GCPtr */);
2163 pCpu->fFlushAsidBeforeUse = false;
2164 }
2165 else
2166 {
2167 /* hmR0VmxSetupTaggedTlb() ensures we never get here. Paranoia. */
2168 AssertMsgFailed(("Unsupported VPID-flush context type.\n"));
2169 }
2170 }
2171 }
2172
2173 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
2174 ("Flush count mismatch for cpu %d (%u vs %u)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
2175 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
2176 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pCpu->idCpu,
2177 pCpu->uCurrentAsid, pCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
2178 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
2179 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
2180
2181 int rc = VMXWriteVmcs32(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
2182 AssertRC(rc);
2183}
2184
2185
2186/**
2187 * Flushes the guest TLB entry based on CPU capabilities.
2188 *
2189 * @param pVCpu The cross context virtual CPU structure.
2190 * @param pCpu Pointer to the global HM CPU struct.
2191 */
2192DECLINLINE(void) hmR0VmxFlushTaggedTlb(PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2193{
2194#ifdef HMVMX_ALWAYS_FLUSH_TLB
2195 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2196#endif
2197 PVM pVM = pVCpu->CTX_SUFF(pVM);
2198 switch (pVM->hm.s.vmx.uFlushTaggedTlb)
2199 {
2200 case HMVMX_FLUSH_TAGGED_TLB_EPT_VPID: hmR0VmxFlushTaggedTlbBoth(pVM, pVCpu, pCpu); break;
2201 case HMVMX_FLUSH_TAGGED_TLB_EPT: hmR0VmxFlushTaggedTlbEpt(pVM, pVCpu, pCpu); break;
2202 case HMVMX_FLUSH_TAGGED_TLB_VPID: hmR0VmxFlushTaggedTlbVpid(pVM, pVCpu, pCpu); break;
2203 case HMVMX_FLUSH_TAGGED_TLB_NONE: hmR0VmxFlushTaggedTlbNone(pVM, pVCpu, pCpu); break;
2204 default:
2205 AssertMsgFailed(("Invalid flush-tag function identifier\n"));
2206 break;
2207 }
2208
2209 /* Don't assert that VMCPU_FF_TLB_FLUSH should no longer be pending. It can be set by other EMTs. */
2210}
2211
2212
2213/**
2214 * Sets up the appropriate tagged TLB-flush level and handler for flushing guest
2215 * TLB entries from the host TLB before VM-entry.
2216 *
2217 * @returns VBox status code.
2218 * @param pVM The cross context VM structure.
2219 */
2220static int hmR0VmxSetupTaggedTlb(PVM pVM)
2221{
2222 /*
2223 * Determine optimal flush type for Nested Paging.
2224 * We cannot ignore EPT if no suitable flush-types is supported by the CPU as we've already setup unrestricted
2225 * guest execution (see hmR3InitFinalizeR0()).
2226 */
2227 if (pVM->hm.s.fNestedPaging)
2228 {
2229 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT)
2230 {
2231 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT)
2232 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_SINGLE_CONTEXT;
2233 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
2234 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_ALL_CONTEXTS;
2235 else
2236 {
2237 /* Shouldn't happen. EPT is supported but no suitable flush-types supported. */
2238 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2239 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_FLUSH_TYPE_UNSUPPORTED;
2240 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2241 }
2242
2243 /* Make sure the write-back cacheable memory type for EPT is supported. */
2244 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB)))
2245 {
2246 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2247 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_MEM_TYPE_NOT_WB;
2248 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2249 }
2250
2251 /* EPT requires a page-walk length of 4. */
2252 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4)))
2253 {
2254 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2255 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_PAGE_WALK_LENGTH_UNSUPPORTED;
2256 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2257 }
2258 }
2259 else
2260 {
2261 /* Shouldn't happen. EPT is supported but INVEPT instruction is not supported. */
2262 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2263 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_INVEPT_UNAVAILABLE;
2264 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2265 }
2266 }
2267
2268 /*
2269 * Determine optimal flush type for VPID.
2270 */
2271 if (pVM->hm.s.vmx.fVpid)
2272 {
2273 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID)
2274 {
2275 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT)
2276 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_SINGLE_CONTEXT;
2277 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS)
2278 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_ALL_CONTEXTS;
2279 else
2280 {
2281 /* Neither SINGLE nor ALL-context flush types for VPID is supported by the CPU. Ignore VPID capability. */
2282 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
2283 LogRel(("hmR0VmxSetupTaggedTlb: Only INDIV_ADDR supported. Ignoring VPID.\n"));
2284 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
2285 LogRel(("hmR0VmxSetupTaggedTlb: Only SINGLE_CONTEXT_RETAIN_GLOBALS supported. Ignoring VPID.\n"));
2286 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_NOT_SUPPORTED;
2287 pVM->hm.s.vmx.fVpid = false;
2288 }
2289 }
2290 else
2291 {
2292 /* Shouldn't happen. VPID is supported but INVVPID is not supported by the CPU. Ignore VPID capability. */
2293 Log4(("hmR0VmxSetupTaggedTlb: VPID supported without INVEPT support. Ignoring VPID.\n"));
2294 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_NOT_SUPPORTED;
2295 pVM->hm.s.vmx.fVpid = false;
2296 }
2297 }
2298
2299 /*
2300 * Setup the handler for flushing tagged-TLBs.
2301 */
2302 if (pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid)
2303 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_EPT_VPID;
2304 else if (pVM->hm.s.fNestedPaging)
2305 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_EPT;
2306 else if (pVM->hm.s.vmx.fVpid)
2307 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_VPID;
2308 else
2309 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_NONE;
2310 return VINF_SUCCESS;
2311}
2312
2313
2314/**
2315 * Sets up pin-based VM-execution controls in the VMCS.
2316 *
2317 * @returns VBox status code.
2318 * @param pVM The cross context VM structure.
2319 * @param pVCpu The cross context virtual CPU structure.
2320 */
2321static int hmR0VmxSetupPinCtls(PVM pVM, PVMCPU pVCpu)
2322{
2323 AssertPtr(pVM);
2324 AssertPtr(pVCpu);
2325
2326 uint32_t val = pVM->hm.s.vmx.Msrs.VmxPinCtls.n.disallowed0; /* Bits set here must always be set. */
2327 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1; /* Bits cleared here must always be cleared. */
2328
2329 val |= VMX_VMCS_CTRL_PIN_EXEC_EXT_INT_EXIT /* External interrupts cause a VM-exit. */
2330 | VMX_VMCS_CTRL_PIN_EXEC_NMI_EXIT; /* Non-maskable interrupts (NMIs) cause a VM-exit. */
2331
2332 if (pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI)
2333 val |= VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI; /* Use virtual NMIs and virtual-NMI blocking features. */
2334
2335 /* Enable the VMX preemption timer. */
2336 if (pVM->hm.s.vmx.fUsePreemptTimer)
2337 {
2338 Assert(pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_PREEMPT_TIMER);
2339 val |= VMX_VMCS_CTRL_PIN_EXEC_PREEMPT_TIMER;
2340 }
2341
2342#if 0
2343 /* Enable posted-interrupt processing. */
2344 if (pVM->hm.s.fPostedIntrs)
2345 {
2346 Assert(pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR);
2347 Assert(pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT);
2348 val |= VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR;
2349 }
2350#endif
2351
2352 if ((val & zap) != val)
2353 {
2354 LogRel(("hmR0VmxSetupPinCtls: Invalid pin-based VM-execution controls combo! cpu=%#RX64 val=%#RX64 zap=%#RX64\n",
2355 pVM->hm.s.vmx.Msrs.VmxPinCtls.n.disallowed0, val, zap));
2356 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PIN_EXEC;
2357 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2358 }
2359
2360 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, val);
2361 AssertRCReturn(rc, rc);
2362
2363 pVCpu->hm.s.vmx.u32PinCtls = val;
2364 return rc;
2365}
2366
2367
2368/**
2369 * Sets up processor-based VM-execution controls in the VMCS.
2370 *
2371 * @returns VBox status code.
2372 * @param pVM The cross context VM structure.
2373 * @param pVCpu The cross context virtual CPU structure.
2374 */
2375static int hmR0VmxSetupProcCtls(PVM pVM, PVMCPU pVCpu)
2376{
2377 AssertPtr(pVM);
2378 AssertPtr(pVCpu);
2379
2380 int rc = VERR_INTERNAL_ERROR_5;
2381 uint32_t val = pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0; /* Bits set here must be set in the VMCS. */
2382 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
2383
2384 val |= VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT /* HLT causes a VM-exit. */
2385 | VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING /* Use TSC-offsetting. */
2386 | VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT /* MOV DRx causes a VM-exit. */
2387 | VMX_VMCS_CTRL_PROC_EXEC_UNCOND_IO_EXIT /* All IO instructions cause a VM-exit. */
2388 | VMX_VMCS_CTRL_PROC_EXEC_RDPMC_EXIT /* RDPMC causes a VM-exit. */
2389 | VMX_VMCS_CTRL_PROC_EXEC_MONITOR_EXIT /* MONITOR causes a VM-exit. */
2390 | VMX_VMCS_CTRL_PROC_EXEC_MWAIT_EXIT; /* MWAIT causes a VM-exit. */
2391
2392 /* We toggle VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT later, check if it's not -always- needed to be set or clear. */
2393 if ( !(pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT)
2394 || (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0 & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT))
2395 {
2396 LogRel(("hmR0VmxSetupProcCtls: Unsupported VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT combo!"));
2397 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_MOV_DRX_EXIT;
2398 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2399 }
2400
2401 /* Without Nested Paging, INVLPG (also affects INVPCID) and MOV CR3 instructions should cause VM-exits. */
2402 if (!pVM->hm.s.fNestedPaging)
2403 {
2404 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest); /* Paranoia. */
2405 val |= VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT
2406 | VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT
2407 | VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT;
2408 }
2409
2410 /* Use TPR shadowing if supported by the CPU. */
2411 if ( PDMHasApic(pVM)
2412 && pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
2413 {
2414 Assert(pVCpu->hm.s.vmx.HCPhysVirtApic);
2415 Assert(!(pVCpu->hm.s.vmx.HCPhysVirtApic & 0xfff)); /* Bits 11:0 MBZ. */
2416 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, 0);
2417 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VAPIC_PAGEADDR_FULL, pVCpu->hm.s.vmx.HCPhysVirtApic);
2418 AssertRCReturn(rc, rc);
2419
2420 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW; /* CR8 reads from the Virtual-APIC page. */
2421 /* CR8 writes cause a VM-exit based on TPR threshold. */
2422 Assert(!(val & VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT));
2423 Assert(!(val & VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT));
2424 }
2425 else
2426 {
2427 /*
2428 * Some 32-bit CPUs do not support CR8 load/store exiting as MOV CR8 is invalid on 32-bit Intel CPUs.
2429 * Set this control only for 64-bit guests.
2430 */
2431 if (pVM->hm.s.fAllow64BitGuests)
2432 {
2433 val |= VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT /* CR8 reads cause a VM-exit. */
2434 | VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT; /* CR8 writes cause a VM-exit. */
2435 }
2436 }
2437
2438 /* Use MSR-bitmaps if supported by the CPU. */
2439 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
2440 {
2441 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS;
2442
2443 Assert(pVCpu->hm.s.vmx.HCPhysMsrBitmap);
2444 Assert(!(pVCpu->hm.s.vmx.HCPhysMsrBitmap & 0xfff)); /* Bits 11:0 MBZ. */
2445 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_MSR_BITMAP_FULL, pVCpu->hm.s.vmx.HCPhysMsrBitmap);
2446 AssertRCReturn(rc, rc);
2447
2448 /*
2449 * The guest can access the following MSRs (read, write) without causing VM-exits; they are loaded/stored
2450 * automatically using dedicated fields in the VMCS.
2451 */
2452 hmR0VmxSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_CS, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2453 hmR0VmxSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_ESP, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2454 hmR0VmxSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_EIP, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2455 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_GS_BASE, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2456 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_FS_BASE, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2457
2458#if HC_ARCH_BITS == 64
2459 /*
2460 * Set passthru permissions for the following MSRs (mandatory for VT-x) required for 64-bit guests.
2461 */
2462 if (pVM->hm.s.fAllow64BitGuests)
2463 {
2464 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_LSTAR, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2465 hmR0VmxSetMsrPermission(pVCpu, MSR_K6_STAR, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2466 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_SF_MASK, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2467 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2468 }
2469#endif
2470 /* Though MSR_IA32_PERF_GLOBAL_CTRL is saved/restored lazily, we want intercept reads/write to it for now. */
2471 }
2472
2473 /* Use the secondary processor-based VM-execution controls if supported by the CPU. */
2474 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
2475 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL;
2476
2477 if ((val & zap) != val)
2478 {
2479 LogRel(("hmR0VmxSetupProcCtls: Invalid processor-based VM-execution controls combo! cpu=%#RX64 val=%#RX64 zap=%#RX64\n",
2480 pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0, val, zap));
2481 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC;
2482 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2483 }
2484
2485 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, val);
2486 AssertRCReturn(rc, rc);
2487
2488 pVCpu->hm.s.vmx.u32ProcCtls = val;
2489
2490 /*
2491 * Secondary processor-based VM-execution controls.
2492 */
2493 if (RT_LIKELY(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL))
2494 {
2495 val = pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.disallowed0; /* Bits set here must be set in the VMCS. */
2496 zap = pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
2497
2498 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT)
2499 val |= VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT; /* WBINVD causes a VM-exit. */
2500
2501 if (pVM->hm.s.fNestedPaging)
2502 val |= VMX_VMCS_CTRL_PROC_EXEC2_EPT; /* Enable EPT. */
2503 else
2504 {
2505 /*
2506 * Without Nested Paging, INVPCID should cause a VM-exit. Enabling this bit causes the CPU to refer to
2507 * VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT when INVPCID is executed by the guest.
2508 * See Intel spec. 25.4 "Changes to instruction behaviour in VMX non-root operation".
2509 */
2510 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_INVPCID)
2511 val |= VMX_VMCS_CTRL_PROC_EXEC2_INVPCID;
2512 }
2513
2514 if (pVM->hm.s.vmx.fVpid)
2515 val |= VMX_VMCS_CTRL_PROC_EXEC2_VPID; /* Enable VPID. */
2516
2517 if (pVM->hm.s.vmx.fUnrestrictedGuest)
2518 val |= VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST; /* Enable Unrestricted Execution. */
2519
2520#if 0
2521 if (pVM->hm.s.fVirtApicRegs)
2522 {
2523 Assert(pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT);
2524 val |= VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT; /* Enable APIC-register virtualization. */
2525
2526 Assert(pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY);
2527 val |= VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY; /* Enable virtual-interrupt delivery. */
2528 }
2529#endif
2530
2531 /* Enable Virtual-APIC page accesses if supported by the CPU. This is essentially where the TPR shadow resides. */
2532 /** @todo VIRT_X2APIC support, it's mutually exclusive with this. So must be
2533 * done dynamically. */
2534 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
2535 {
2536 Assert(pVM->hm.s.vmx.HCPhysApicAccess);
2537 Assert(!(pVM->hm.s.vmx.HCPhysApicAccess & 0xfff)); /* Bits 11:0 MBZ. */
2538 val |= VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC; /* Virtualize APIC accesses. */
2539 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, pVM->hm.s.vmx.HCPhysApicAccess);
2540 AssertRCReturn(rc, rc);
2541 }
2542
2543 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP)
2544 val |= VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP; /* Enable RDTSCP support. */
2545
2546 if ( pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_PAUSE_LOOP_EXIT
2547 && pVM->hm.s.vmx.cPleGapTicks
2548 && pVM->hm.s.vmx.cPleWindowTicks)
2549 {
2550 val |= VMX_VMCS_CTRL_PROC_EXEC2_PAUSE_LOOP_EXIT; /* Enable pause-loop exiting. */
2551
2552 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, pVM->hm.s.vmx.cPleGapTicks);
2553 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, pVM->hm.s.vmx.cPleWindowTicks);
2554 AssertRCReturn(rc, rc);
2555 }
2556
2557 if ((val & zap) != val)
2558 {
2559 LogRel(("hmR0VmxSetupProcCtls: Invalid secondary processor-based VM-execution controls combo! "
2560 "cpu=%#RX64 val=%#RX64 zap=%#RX64\n", pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.disallowed0, val, zap));
2561 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC2;
2562 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2563 }
2564
2565 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, val);
2566 AssertRCReturn(rc, rc);
2567
2568 pVCpu->hm.s.vmx.u32ProcCtls2 = val;
2569 }
2570 else if (RT_UNLIKELY(pVM->hm.s.vmx.fUnrestrictedGuest))
2571 {
2572 LogRel(("hmR0VmxSetupProcCtls: Unrestricted Guest set as true when secondary processor-based VM-execution controls not "
2573 "available\n"));
2574 pVCpu->hm.s.u32HMError = VMX_UFC_INVALID_UX_COMBO;
2575 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2576 }
2577
2578 return VINF_SUCCESS;
2579}
2580
2581
2582/**
2583 * Sets up miscellaneous (everything other than Pin & Processor-based
2584 * VM-execution) control fields in the VMCS.
2585 *
2586 * @returns VBox status code.
2587 * @param pVM The cross context VM structure.
2588 * @param pVCpu The cross context virtual CPU structure.
2589 */
2590static int hmR0VmxSetupMiscCtls(PVM pVM, PVMCPU pVCpu)
2591{
2592 NOREF(pVM);
2593 AssertPtr(pVM);
2594 AssertPtr(pVCpu);
2595
2596 int rc = VERR_GENERAL_FAILURE;
2597
2598 /* All fields are zero-initialized during allocation; but don't remove the commented block below. */
2599#if 0
2600 /* All CR3 accesses cause VM-exits. Later we optimize CR3 accesses (see hmR0VmxLoadGuestCR3AndCR4())*/
2601 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_CR3_TARGET_COUNT, 0);
2602 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, 0);
2603
2604 /*
2605 * Set MASK & MATCH to 0. VMX checks if GuestPFErrCode & MASK == MATCH. If equal (in our case it always is)
2606 * and if the X86_XCPT_PF bit in the exception bitmap is set it causes a VM-exit, if clear doesn't cause an exit.
2607 * We thus use the exception bitmap to control it rather than use both.
2608 */
2609 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, 0);
2610 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, 0);
2611
2612 /** @todo Explore possibility of using IO-bitmaps. */
2613 /* All IO & IOIO instructions cause VM-exits. */
2614 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_IO_BITMAP_A_FULL, 0);
2615 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_IO_BITMAP_B_FULL, 0);
2616
2617 /* Initialize the MSR-bitmap area. */
2618 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, 0);
2619 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, 0);
2620 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, 0);
2621 AssertRCReturn(rc, rc);
2622#endif
2623
2624 /* Setup MSR auto-load/store area. */
2625 Assert(pVCpu->hm.s.vmx.HCPhysGuestMsr);
2626 Assert(!(pVCpu->hm.s.vmx.HCPhysGuestMsr & 0xf)); /* Lower 4 bits MBZ. */
2627 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL, pVCpu->hm.s.vmx.HCPhysGuestMsr);
2628 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL, pVCpu->hm.s.vmx.HCPhysGuestMsr);
2629 AssertRCReturn(rc, rc);
2630
2631 Assert(pVCpu->hm.s.vmx.HCPhysHostMsr);
2632 Assert(!(pVCpu->hm.s.vmx.HCPhysHostMsr & 0xf)); /* Lower 4 bits MBZ. */
2633 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL, pVCpu->hm.s.vmx.HCPhysHostMsr);
2634 AssertRCReturn(rc, rc);
2635
2636 /* Set VMCS link pointer. Reserved for future use, must be -1. Intel spec. 24.4 "Guest-State Area". */
2637 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, UINT64_C(0xffffffffffffffff));
2638 AssertRCReturn(rc, rc);
2639
2640 /* All fields are zero-initialized during allocation; but don't remove the commented block below. */
2641#if 0
2642 /* Setup debug controls */
2643 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, 0); /** @todo We don't support IA32_DEBUGCTL MSR. Should we? */
2644 rc |= VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, 0);
2645 AssertRCReturn(rc, rc);
2646#endif
2647
2648 return rc;
2649}
2650
2651
2652/**
2653 * Sets up the initial exception bitmap in the VMCS based on static conditions.
2654 *
2655 * We shall setup those exception intercepts that don't change during the
2656 * lifetime of the VM here. The rest are done dynamically while loading the
2657 * guest state.
2658 *
2659 * @returns VBox status code.
2660 * @param pVM The cross context VM structure.
2661 * @param pVCpu The cross context virtual CPU structure.
2662 */
2663static int hmR0VmxInitXcptBitmap(PVM pVM, PVMCPU pVCpu)
2664{
2665 AssertPtr(pVM);
2666 AssertPtr(pVCpu);
2667
2668 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
2669
2670 uint32_t u32XcptBitmap = 0;
2671
2672 /* Must always intercept #AC to prevent the guest from hanging the CPU. */
2673 u32XcptBitmap |= RT_BIT_32(X86_XCPT_AC);
2674
2675 /* Because we need to maintain the DR6 state even when intercepting DRx reads
2676 and writes, and because recursive #DBs can cause the CPU hang, we must always
2677 intercept #DB. */
2678 u32XcptBitmap |= RT_BIT_32(X86_XCPT_DB);
2679
2680 /* Without Nested Paging, #PF must cause a VM-exit so we can sync our shadow page tables. */
2681 if (!pVM->hm.s.fNestedPaging)
2682 u32XcptBitmap |= RT_BIT(X86_XCPT_PF);
2683
2684 pVCpu->hm.s.vmx.u32XcptBitmap = u32XcptBitmap;
2685 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
2686 AssertRCReturn(rc, rc);
2687 return rc;
2688}
2689
2690
2691/**
2692 * Sets up the initial guest-state mask. The guest-state mask is consulted
2693 * before reading guest-state fields from the VMCS as VMREADs can be expensive
2694 * for the nested virtualization case (as it would cause a VM-exit).
2695 *
2696 * @param pVCpu The cross context virtual CPU structure.
2697 */
2698static int hmR0VmxInitUpdatedGuestStateMask(PVMCPU pVCpu)
2699{
2700 /* Initially the guest-state is up-to-date as there is nothing in the VMCS. */
2701 HMVMXCPU_GST_RESET_TO(pVCpu, HMVMX_UPDATED_GUEST_ALL);
2702 return VINF_SUCCESS;
2703}
2704
2705
2706/**
2707 * Does per-VM VT-x initialization.
2708 *
2709 * @returns VBox status code.
2710 * @param pVM The cross context VM structure.
2711 */
2712VMMR0DECL(int) VMXR0InitVM(PVM pVM)
2713{
2714 LogFlowFunc(("pVM=%p\n", pVM));
2715
2716 int rc = hmR0VmxStructsAlloc(pVM);
2717 if (RT_FAILURE(rc))
2718 {
2719 LogRel(("VMXR0InitVM: hmR0VmxStructsAlloc failed! rc=%Rrc\n", rc));
2720 return rc;
2721 }
2722
2723 return VINF_SUCCESS;
2724}
2725
2726
2727/**
2728 * Does per-VM VT-x termination.
2729 *
2730 * @returns VBox status code.
2731 * @param pVM The cross context VM structure.
2732 */
2733VMMR0DECL(int) VMXR0TermVM(PVM pVM)
2734{
2735 LogFlowFunc(("pVM=%p\n", pVM));
2736
2737#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2738 if (pVM->hm.s.vmx.hMemObjScratch != NIL_RTR0MEMOBJ)
2739 ASMMemZero32(pVM->hm.s.vmx.pvScratch, PAGE_SIZE);
2740#endif
2741 hmR0VmxStructsFree(pVM);
2742 return VINF_SUCCESS;
2743}
2744
2745
2746/**
2747 * Sets up the VM for execution under VT-x.
2748 * This function is only called once per-VM during initialization.
2749 *
2750 * @returns VBox status code.
2751 * @param pVM The cross context VM structure.
2752 */
2753VMMR0DECL(int) VMXR0SetupVM(PVM pVM)
2754{
2755 AssertPtrReturn(pVM, VERR_INVALID_PARAMETER);
2756 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2757
2758 LogFlowFunc(("pVM=%p\n", pVM));
2759
2760 /*
2761 * Without UnrestrictedGuest, pRealModeTSS and pNonPagingModeEPTPageTable *must* always be allocated.
2762 * We no longer support the highly unlikely case of UnrestrictedGuest without pRealModeTSS. See hmR3InitFinalizeR0Intel().
2763 */
2764 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
2765 && ( !pVM->hm.s.vmx.pNonPagingModeEPTPageTable
2766 || !pVM->hm.s.vmx.pRealModeTSS))
2767 {
2768 LogRel(("VMXR0SetupVM: Invalid real-on-v86 state.\n"));
2769 return VERR_INTERNAL_ERROR;
2770 }
2771
2772 /* Initialize these always, see hmR3InitFinalizeR0().*/
2773 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NONE;
2774 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_NONE;
2775
2776 /* Setup the tagged-TLB flush handlers. */
2777 int rc = hmR0VmxSetupTaggedTlb(pVM);
2778 if (RT_FAILURE(rc))
2779 {
2780 LogRel(("VMXR0SetupVM: hmR0VmxSetupTaggedTlb failed! rc=%Rrc\n", rc));
2781 return rc;
2782 }
2783
2784 /* Check if we can use the VMCS controls for swapping the EFER MSR. */
2785 Assert(!pVM->hm.s.vmx.fSupportsVmcsEfer);
2786#if HC_ARCH_BITS == 64
2787 if ( (pVM->hm.s.vmx.Msrs.VmxEntry.n.allowed1 & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR)
2788 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR)
2789 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR))
2790 {
2791 pVM->hm.s.vmx.fSupportsVmcsEfer = true;
2792 }
2793#endif
2794
2795 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
2796 RTCCUINTREG uHostCR4 = ASMGetCR4();
2797 if (RT_UNLIKELY(!(uHostCR4 & X86_CR4_VMXE)))
2798 return VERR_VMX_NOT_IN_VMX_ROOT_MODE;
2799
2800 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2801 {
2802 PVMCPU pVCpu = &pVM->aCpus[i];
2803 AssertPtr(pVCpu);
2804 AssertPtr(pVCpu->hm.s.vmx.pvVmcs);
2805
2806 /* Log the VCPU pointers, useful for debugging SMP VMs. */
2807 Log4(("VMXR0SetupVM: pVCpu=%p idCpu=%RU32\n", pVCpu, pVCpu->idCpu));
2808
2809 /* Initialize the VM-exit history array with end-of-array markers (UINT16_MAX). */
2810 Assert(!pVCpu->hm.s.idxExitHistoryFree);
2811 HMCPU_EXIT_HISTORY_RESET(pVCpu);
2812
2813 /* Set revision dword at the beginning of the VMCS structure. */
2814 *(uint32_t *)pVCpu->hm.s.vmx.pvVmcs = MSR_IA32_VMX_BASIC_INFO_VMCS_ID(pVM->hm.s.vmx.Msrs.u64BasicInfo);
2815
2816 /* Initialize our VMCS region in memory, set the VMCS launch state to "clear". */
2817 rc = VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
2818 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: VMXClearVmcs failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2819 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2820
2821 /* Load this VMCS as the current VMCS. */
2822 rc = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
2823 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: VMXActivateVmcs failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2824 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2825
2826 rc = hmR0VmxSetupPinCtls(pVM, pVCpu);
2827 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxSetupPinCtls failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2828 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2829
2830 rc = hmR0VmxSetupProcCtls(pVM, pVCpu);
2831 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxSetupProcCtls failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2832 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2833
2834 rc = hmR0VmxSetupMiscCtls(pVM, pVCpu);
2835 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxSetupMiscCtls failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2836 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2837
2838 rc = hmR0VmxInitXcptBitmap(pVM, pVCpu);
2839 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxInitXcptBitmap failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2840 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2841
2842 rc = hmR0VmxInitUpdatedGuestStateMask(pVCpu);
2843 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxInitUpdatedGuestStateMask failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2844 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2845
2846#if HC_ARCH_BITS == 32
2847 rc = hmR0VmxInitVmcsReadCache(pVM, pVCpu);
2848 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxInitVmcsReadCache failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2849 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2850#endif
2851
2852 /* Re-sync the CPU's internal data into our VMCS memory region & reset the launch state to "clear". */
2853 rc = VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
2854 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: VMXClearVmcs(2) failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2855 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2856
2857 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
2858
2859 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc);
2860 }
2861
2862 return VINF_SUCCESS;
2863}
2864
2865
2866/**
2867 * Saves the host control registers (CR0, CR3, CR4) into the host-state area in
2868 * the VMCS.
2869 *
2870 * @returns VBox status code.
2871 * @param pVM The cross context VM structure.
2872 * @param pVCpu The cross context virtual CPU structure.
2873 */
2874DECLINLINE(int) hmR0VmxSaveHostControlRegs(PVM pVM, PVMCPU pVCpu)
2875{
2876 NOREF(pVM); NOREF(pVCpu);
2877
2878 RTCCUINTREG uReg = ASMGetCR0();
2879 int rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_CR0, uReg);
2880 AssertRCReturn(rc, rc);
2881
2882 uReg = ASMGetCR3();
2883 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_CR3, uReg);
2884 AssertRCReturn(rc, rc);
2885
2886 uReg = ASMGetCR4();
2887 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_CR4, uReg);
2888 AssertRCReturn(rc, rc);
2889 return rc;
2890}
2891
2892
2893#if HC_ARCH_BITS == 64
2894/**
2895 * Macro for adjusting host segment selectors to satisfy VT-x's VM-entry
2896 * requirements. See hmR0VmxSaveHostSegmentRegs().
2897 */
2898# define VMXLOCAL_ADJUST_HOST_SEG(seg, selValue) \
2899 if ((selValue) & (X86_SEL_RPL | X86_SEL_LDT)) \
2900 { \
2901 bool fValidSelector = true; \
2902 if ((selValue) & X86_SEL_LDT) \
2903 { \
2904 uint32_t uAttr = ASMGetSegAttr((selValue)); \
2905 fValidSelector = RT_BOOL(uAttr != UINT32_MAX && (uAttr & X86_DESC_P)); \
2906 } \
2907 if (fValidSelector) \
2908 { \
2909 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##seg; \
2910 pVCpu->hm.s.vmx.RestoreHost.uHostSel##seg = (selValue); \
2911 } \
2912 (selValue) = 0; \
2913 }
2914#endif
2915
2916
2917/**
2918 * Saves the host segment registers and GDTR, IDTR, (TR, GS and FS bases) into
2919 * the host-state area in the VMCS.
2920 *
2921 * @returns VBox status code.
2922 * @param pVM The cross context VM structure.
2923 * @param pVCpu The cross context virtual CPU structure.
2924 */
2925DECLINLINE(int) hmR0VmxSaveHostSegmentRegs(PVM pVM, PVMCPU pVCpu)
2926{
2927 int rc = VERR_INTERNAL_ERROR_5;
2928
2929#if HC_ARCH_BITS == 64
2930 /*
2931 * If we've executed guest code using VT-x, the host-state bits will be messed up. We
2932 * should -not- save the messed up state without restoring the original host-state. See @bugref{7240}.
2933 *
2934 * This apparently can happen (most likely the FPU changes), deal with it rather than asserting.
2935 * Was observed booting Solaris10u10 32-bit guest.
2936 */
2937 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
2938 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
2939 {
2940 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags,
2941 pVCpu->idCpu));
2942 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
2943 }
2944 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
2945#else
2946 RT_NOREF(pVCpu);
2947#endif
2948
2949 /*
2950 * Host DS, ES, FS and GS segment registers.
2951 */
2952#if HC_ARCH_BITS == 64
2953 RTSEL uSelDS = ASMGetDS();
2954 RTSEL uSelES = ASMGetES();
2955 RTSEL uSelFS = ASMGetFS();
2956 RTSEL uSelGS = ASMGetGS();
2957#else
2958 RTSEL uSelDS = 0;
2959 RTSEL uSelES = 0;
2960 RTSEL uSelFS = 0;
2961 RTSEL uSelGS = 0;
2962#endif
2963
2964 /*
2965 * Host CS and SS segment registers.
2966 */
2967 RTSEL uSelCS = ASMGetCS();
2968 RTSEL uSelSS = ASMGetSS();
2969
2970 /*
2971 * Host TR segment register.
2972 */
2973 RTSEL uSelTR = ASMGetTR();
2974
2975#if HC_ARCH_BITS == 64
2976 /*
2977 * Determine if the host segment registers are suitable for VT-x. Otherwise use zero to gain VM-entry and restore them
2978 * before we get preempted. See Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers".
2979 */
2980 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
2981 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
2982 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
2983 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
2984# undef VMXLOCAL_ADJUST_HOST_SEG
2985#endif
2986
2987 /* Verification based on Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers" */
2988 Assert(!(uSelCS & X86_SEL_RPL)); Assert(!(uSelCS & X86_SEL_LDT));
2989 Assert(!(uSelSS & X86_SEL_RPL)); Assert(!(uSelSS & X86_SEL_LDT));
2990 Assert(!(uSelDS & X86_SEL_RPL)); Assert(!(uSelDS & X86_SEL_LDT));
2991 Assert(!(uSelES & X86_SEL_RPL)); Assert(!(uSelES & X86_SEL_LDT));
2992 Assert(!(uSelFS & X86_SEL_RPL)); Assert(!(uSelFS & X86_SEL_LDT));
2993 Assert(!(uSelGS & X86_SEL_RPL)); Assert(!(uSelGS & X86_SEL_LDT));
2994 Assert(!(uSelTR & X86_SEL_RPL)); Assert(!(uSelTR & X86_SEL_LDT));
2995 Assert(uSelCS);
2996 Assert(uSelTR);
2997
2998 /* Assertion is right but we would not have updated u32ExitCtls yet. */
2999#if 0
3000 if (!(pVCpu->hm.s.vmx.u32ExitCtls & VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE))
3001 Assert(uSelSS != 0);
3002#endif
3003
3004 /* Write these host selector fields into the host-state area in the VMCS. */
3005 rc = VMXWriteVmcs32(VMX_VMCS16_HOST_CS_SEL, uSelCS);
3006 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_SS_SEL, uSelSS);
3007#if HC_ARCH_BITS == 64
3008 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_DS_SEL, uSelDS);
3009 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_ES_SEL, uSelES);
3010 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_FS_SEL, uSelFS);
3011 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_GS_SEL, uSelGS);
3012#else
3013 NOREF(uSelDS);
3014 NOREF(uSelES);
3015 NOREF(uSelFS);
3016 NOREF(uSelGS);
3017#endif
3018 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_TR_SEL, uSelTR);
3019 AssertRCReturn(rc, rc);
3020
3021 /*
3022 * Host GDTR and IDTR.
3023 */
3024 RTGDTR Gdtr;
3025 RTIDTR Idtr;
3026 RT_ZERO(Gdtr);
3027 RT_ZERO(Idtr);
3028 ASMGetGDTR(&Gdtr);
3029 ASMGetIDTR(&Idtr);
3030 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_GDTR_BASE, Gdtr.pGdt);
3031 rc |= VMXWriteVmcsHstN(VMX_VMCS_HOST_IDTR_BASE, Idtr.pIdt);
3032 AssertRCReturn(rc, rc);
3033
3034#if HC_ARCH_BITS == 64
3035 /*
3036 * Determine if we need to manually need to restore the GDTR and IDTR limits as VT-x zaps them to the
3037 * maximum limit (0xffff) on every VM-exit.
3038 */
3039 if (Gdtr.cbGdt != 0xffff)
3040 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDTR;
3041
3042 /*
3043 * IDT limit is effectively capped at 0xfff. (See Intel spec. 6.14.1 "64-Bit Mode IDT"
3044 * and Intel spec. 6.2 "Exception and Interrupt Vectors".) Therefore if the host has the limit as 0xfff, VT-x
3045 * bloating the limit to 0xffff shouldn't cause any different CPU behavior. However, several hosts either insists
3046 * on 0xfff being the limit (Windows Patch Guard) or uses the limit for other purposes (darwin puts the CPU ID in there
3047 * but botches sidt alignment in at least one consumer). So, we're only allowing IDTR.LIMIT to be left at 0xffff on
3048 * hosts where we are pretty sure it won't cause trouble.
3049 */
3050# if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
3051 if (Idtr.cbIdt < 0x0fff)
3052# else
3053 if (Idtr.cbIdt != 0xffff)
3054# endif
3055 {
3056 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_IDTR;
3057 AssertCompile(sizeof(Idtr) == sizeof(X86XDTR64));
3058 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostIdtr, &Idtr, sizeof(X86XDTR64));
3059 }
3060#endif
3061
3062 /*
3063 * Host TR base. Verify that TR selector doesn't point past the GDT. Masking off the TI and RPL bits
3064 * is effectively what the CPU does for "scaling by 8". TI is always 0 and RPL should be too in most cases.
3065 */
3066 AssertMsgReturn((uSelTR | X86_SEL_RPL_LDT) <= Gdtr.cbGdt,
3067 ("hmR0VmxSaveHostSegmentRegs: TR selector exceeds limit. TR=%RTsel cbGdt=%#x\n", uSelTR, Gdtr.cbGdt),
3068 VERR_VMX_INVALID_HOST_STATE);
3069
3070 PCX86DESCHC pDesc = (PCX86DESCHC)(Gdtr.pGdt + (uSelTR & X86_SEL_MASK));
3071#if HC_ARCH_BITS == 64
3072 uintptr_t uTRBase = X86DESC64_BASE(pDesc);
3073
3074 /*
3075 * VT-x unconditionally restores the TR limit to 0x67 and type to 11 (32-bit busy TSS) on all VM-exits.
3076 * The type is the same for 64-bit busy TSS[1]. The limit needs manual restoration if the host has something else.
3077 * Task switching is not supported in 64-bit mode[2], but the limit still matters as IOPM is supported in 64-bit mode.
3078 * Restoring the limit lazily while returning to ring-3 is safe because IOPM is not applicable in ring-0.
3079 *
3080 * [1] See Intel spec. 3.5 "System Descriptor Types".
3081 * [2] See Intel spec. 7.2.3 "TSS Descriptor in 64-bit mode".
3082 */
3083 Assert(pDesc->System.u4Type == 11);
3084 if ( pDesc->System.u16LimitLow != 0x67
3085 || pDesc->System.u4LimitHigh)
3086 {
3087 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_TR;
3088 /* If the host has made GDT read-only, we would need to temporarily toggle CR0.WP before writing the GDT. */
3089 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_READ_ONLY)
3090 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_READ_ONLY;
3091 pVCpu->hm.s.vmx.RestoreHost.uHostSelTR = uSelTR;
3092 }
3093
3094 /*
3095 * Store the GDTR as we need it when restoring the GDT and while restoring the TR.
3096 */
3097 if (pVCpu->hm.s.vmx.fRestoreHostFlags & (VMX_RESTORE_HOST_GDTR | VMX_RESTORE_HOST_SEL_TR))
3098 {
3099 AssertCompile(sizeof(Gdtr) == sizeof(X86XDTR64));
3100 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostGdtr, &Gdtr, sizeof(X86XDTR64));
3101 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_NEED_WRITABLE)
3102 {
3103 /* The GDT is read-only but the writable GDT is available. */
3104 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_NEED_WRITABLE;
3105 pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.cb = Gdtr.cbGdt;
3106 rc = SUPR0GetCurrentGdtRw(&pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.uAddr);
3107 AssertRCReturn(rc, rc);
3108 }
3109 }
3110#else
3111 NOREF(pVM);
3112 uintptr_t uTRBase = X86DESC_BASE(pDesc);
3113#endif
3114 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_TR_BASE, uTRBase);
3115 AssertRCReturn(rc, rc);
3116
3117 /*
3118 * Host FS base and GS base.
3119 */
3120#if HC_ARCH_BITS == 64
3121 uint64_t u64FSBase = ASMRdMsr(MSR_K8_FS_BASE);
3122 uint64_t u64GSBase = ASMRdMsr(MSR_K8_GS_BASE);
3123 rc = VMXWriteVmcs64(VMX_VMCS_HOST_FS_BASE, u64FSBase);
3124 rc |= VMXWriteVmcs64(VMX_VMCS_HOST_GS_BASE, u64GSBase);
3125 AssertRCReturn(rc, rc);
3126
3127 /* Store the base if we have to restore FS or GS manually as we need to restore the base as well. */
3128 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_FS)
3129 pVCpu->hm.s.vmx.RestoreHost.uHostFSBase = u64FSBase;
3130 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_GS)
3131 pVCpu->hm.s.vmx.RestoreHost.uHostGSBase = u64GSBase;
3132#endif
3133 return rc;
3134}
3135
3136
3137/**
3138 * Saves certain host MSRs in the VM-exit MSR-load area and some in the
3139 * host-state area of the VMCS. Theses MSRs will be automatically restored on
3140 * the host after every successful VM-exit.
3141 *
3142 * @returns VBox status code.
3143 * @param pVM The cross context VM structure.
3144 * @param pVCpu The cross context virtual CPU structure.
3145 *
3146 * @remarks No-long-jump zone!!!
3147 */
3148DECLINLINE(int) hmR0VmxSaveHostMsrs(PVM pVM, PVMCPU pVCpu)
3149{
3150 NOREF(pVM);
3151
3152 AssertPtr(pVCpu);
3153 AssertPtr(pVCpu->hm.s.vmx.pvHostMsr);
3154
3155 /*
3156 * Save MSRs that we restore lazily (due to preemption or transition to ring-3)
3157 * rather than swapping them on every VM-entry.
3158 */
3159 hmR0VmxLazySaveHostMsrs(pVCpu);
3160
3161 /*
3162 * Host Sysenter MSRs.
3163 */
3164 int rc = VMXWriteVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS));
3165#if HC_ARCH_BITS == 32
3166 rc |= VMXWriteVmcs32(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr_Low(MSR_IA32_SYSENTER_ESP));
3167 rc |= VMXWriteVmcs32(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr_Low(MSR_IA32_SYSENTER_EIP));
3168#else
3169 rc |= VMXWriteVmcs64(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP));
3170 rc |= VMXWriteVmcs64(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP));
3171#endif
3172 AssertRCReturn(rc, rc);
3173
3174 /*
3175 * Host EFER MSR.
3176 * If the CPU supports the newer VMCS controls for managing EFER, use it.
3177 * Otherwise it's done as part of auto-load/store MSR area in the VMCS, see hmR0VmxLoadGuestMsrs().
3178 */
3179 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
3180 {
3181 rc = VMXWriteVmcs64(VMX_VMCS64_HOST_EFER_FULL, pVM->hm.s.vmx.u64HostEfer);
3182 AssertRCReturn(rc, rc);
3183 }
3184
3185 /** @todo IA32_PERF_GLOBALCTRL, IA32_PAT also see
3186 * hmR0VmxLoadGuestExitCtls() !! */
3187
3188 return rc;
3189}
3190
3191
3192/**
3193 * Figures out if we need to swap the EFER MSR which is particularly expensive.
3194 *
3195 * We check all relevant bits. For now, that's everything besides LMA/LME, as
3196 * these two bits are handled by VM-entry, see hmR0VmxLoadGuestExitCtls() and
3197 * hmR0VMxLoadGuestEntryCtls().
3198 *
3199 * @returns true if we need to load guest EFER, false otherwise.
3200 * @param pVCpu The cross context virtual CPU structure.
3201 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3202 * out-of-sync. Make sure to update the required fields
3203 * before using them.
3204 *
3205 * @remarks Requires EFER, CR4.
3206 * @remarks No-long-jump zone!!!
3207 */
3208static bool hmR0VmxShouldSwapEferMsr(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3209{
3210#ifdef HMVMX_ALWAYS_SWAP_EFER
3211 return true;
3212#endif
3213
3214#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
3215 /* For 32-bit hosts running 64-bit guests, we always swap EFER in the world-switcher. Nothing to do here. */
3216 if (CPUMIsGuestInLongMode(pVCpu))
3217 return false;
3218#endif
3219
3220 PVM pVM = pVCpu->CTX_SUFF(pVM);
3221 uint64_t u64HostEfer = pVM->hm.s.vmx.u64HostEfer;
3222 uint64_t u64GuestEfer = pMixedCtx->msrEFER;
3223
3224 /*
3225 * For 64-bit guests, if EFER.SCE bit differs, we need to swap to ensure that the
3226 * guest's SYSCALL behaviour isn't screwed. See @bugref{7386}.
3227 */
3228 if ( CPUMIsGuestInLongMode(pVCpu)
3229 && (u64GuestEfer & MSR_K6_EFER_SCE) != (u64HostEfer & MSR_K6_EFER_SCE))
3230 {
3231 return true;
3232 }
3233
3234 /*
3235 * If the guest uses PAE and EFER.NXE bit differs, we need to swap EFER as it
3236 * affects guest paging. 64-bit paging implies CR4.PAE as well.
3237 * See Intel spec. 4.5 "IA-32e Paging" and Intel spec. 4.1.1 "Three Paging Modes".
3238 */
3239 if ( (pMixedCtx->cr4 & X86_CR4_PAE)
3240 && (pMixedCtx->cr0 & X86_CR0_PG)
3241 && (u64GuestEfer & MSR_K6_EFER_NXE) != (u64HostEfer & MSR_K6_EFER_NXE))
3242 {
3243 /* Assert that host is PAE capable. */
3244 Assert(pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_NX);
3245 return true;
3246 }
3247
3248 /** @todo Check the latest Intel spec. for any other bits,
3249 * like SMEP/SMAP? */
3250 return false;
3251}
3252
3253
3254/**
3255 * Sets up VM-entry controls in the VMCS. These controls can affect things done
3256 * on VM-exit; e.g. "load debug controls", see Intel spec. 24.8.1 "VM-entry
3257 * controls".
3258 *
3259 * @returns VBox status code.
3260 * @param pVCpu The cross context virtual CPU structure.
3261 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3262 * out-of-sync. Make sure to update the required fields
3263 * before using them.
3264 *
3265 * @remarks Requires EFER.
3266 * @remarks No-long-jump zone!!!
3267 */
3268DECLINLINE(int) hmR0VmxLoadGuestEntryCtls(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3269{
3270 int rc = VINF_SUCCESS;
3271 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_ENTRY_CTLS))
3272 {
3273 PVM pVM = pVCpu->CTX_SUFF(pVM);
3274 uint32_t val = pVM->hm.s.vmx.Msrs.VmxEntry.n.disallowed0; /* Bits set here must be set in the VMCS. */
3275 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxEntry.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3276
3277 /* Load debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x capable CPUs only supports the 1-setting of this bit. */
3278 val |= VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG;
3279
3280 /* Set if the guest is in long mode. This will set/clear the EFER.LMA bit on VM-entry. */
3281 if (CPUMIsGuestInLongModeEx(pMixedCtx))
3282 {
3283 val |= VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST;
3284 Log4(("Load[%RU32]: VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST\n", pVCpu->idCpu));
3285 }
3286 else
3287 Assert(!(val & VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST));
3288
3289 /* If the CPU supports the newer VMCS controls for managing guest/host EFER, use it. */
3290 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
3291 && hmR0VmxShouldSwapEferMsr(pVCpu, pMixedCtx))
3292 {
3293 val |= VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR;
3294 Log4(("Load[%RU32]: VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR\n", pVCpu->idCpu));
3295 }
3296
3297 /*
3298 * The following should -not- be set (since we're not in SMM mode):
3299 * - VMX_VMCS_CTRL_ENTRY_ENTRY_SMM
3300 * - VMX_VMCS_CTRL_ENTRY_DEACTIVATE_DUALMON
3301 */
3302
3303 /** @todo VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PERF_MSR,
3304 * VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PAT_MSR. */
3305
3306 if ((val & zap) != val)
3307 {
3308 LogRel(("hmR0VmxLoadGuestEntryCtls: Invalid VM-entry controls combo! cpu=%RX64 val=%RX64 zap=%RX64\n",
3309 pVM->hm.s.vmx.Msrs.VmxEntry.n.disallowed0, val, zap));
3310 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_ENTRY;
3311 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3312 }
3313
3314 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY, val);
3315 AssertRCReturn(rc, rc);
3316
3317 pVCpu->hm.s.vmx.u32EntryCtls = val;
3318 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_ENTRY_CTLS);
3319 }
3320 return rc;
3321}
3322
3323
3324/**
3325 * Sets up the VM-exit controls in the VMCS.
3326 *
3327 * @returns VBox status code.
3328 * @param pVCpu The cross context virtual CPU structure.
3329 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3330 * out-of-sync. Make sure to update the required fields
3331 * before using them.
3332 *
3333 * @remarks Requires EFER.
3334 */
3335DECLINLINE(int) hmR0VmxLoadGuestExitCtls(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3336{
3337 NOREF(pMixedCtx);
3338
3339 int rc = VINF_SUCCESS;
3340 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_EXIT_CTLS))
3341 {
3342 PVM pVM = pVCpu->CTX_SUFF(pVM);
3343 uint32_t val = pVM->hm.s.vmx.Msrs.VmxExit.n.disallowed0; /* Bits set here must be set in the VMCS. */
3344 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3345
3346 /* Save debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x CPUs only supported the 1-setting of this bit. */
3347 val |= VMX_VMCS_CTRL_EXIT_SAVE_DEBUG;
3348
3349 /*
3350 * Set the host long mode active (EFER.LMA) bit (which Intel calls "Host address-space size") if necessary.
3351 * On VM-exit, VT-x sets both the host EFER.LMA and EFER.LME bit to this value. See assertion in hmR0VmxSaveHostMsrs().
3352 */
3353#if HC_ARCH_BITS == 64
3354 val |= VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE;
3355 Log4(("Load[%RU32]: VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE\n", pVCpu->idCpu));
3356#else
3357 Assert( pVCpu->hm.s.vmx.pfnStartVM == VMXR0SwitcherStartVM64
3358 || pVCpu->hm.s.vmx.pfnStartVM == VMXR0StartVM32);
3359 /* Set the host address-space size based on the switcher, not guest state. See @bugref{8432}. */
3360 if (pVCpu->hm.s.vmx.pfnStartVM == VMXR0SwitcherStartVM64)
3361 {
3362 /* The switcher returns to long mode, EFER is managed by the switcher. */
3363 val |= VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE;
3364 Log4(("Load[%RU32]: VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE\n", pVCpu->idCpu));
3365 }
3366 else
3367 Assert(!(val & VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE));
3368#endif
3369
3370 /* If the newer VMCS fields for managing EFER exists, use it. */
3371 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
3372 && hmR0VmxShouldSwapEferMsr(pVCpu, pMixedCtx))
3373 {
3374 val |= VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR
3375 | VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR;
3376 Log4(("Load[%RU32]: VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR, VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR\n", pVCpu->idCpu));
3377 }
3378
3379 /* Don't acknowledge external interrupts on VM-exit. We want to let the host do that. */
3380 Assert(!(val & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT));
3381
3382 /** @todo VMX_VMCS_CTRL_EXIT_LOAD_PERF_MSR,
3383 * VMX_VMCS_CTRL_EXIT_SAVE_GUEST_PAT_MSR,
3384 * VMX_VMCS_CTRL_EXIT_LOAD_HOST_PAT_MSR. */
3385
3386 if ( pVM->hm.s.vmx.fUsePreemptTimer
3387 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_SAVE_VMX_PREEMPT_TIMER))
3388 val |= VMX_VMCS_CTRL_EXIT_SAVE_VMX_PREEMPT_TIMER;
3389
3390 if ((val & zap) != val)
3391 {
3392 LogRel(("hmR0VmxSetupProcCtls: Invalid VM-exit controls combo! cpu=%RX64 val=%RX64 zap=%RX64\n",
3393 pVM->hm.s.vmx.Msrs.VmxExit.n.disallowed0, val, zap));
3394 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_EXIT;
3395 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3396 }
3397
3398 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT, val);
3399 AssertRCReturn(rc, rc);
3400
3401 pVCpu->hm.s.vmx.u32ExitCtls = val;
3402 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_EXIT_CTLS);
3403 }
3404 return rc;
3405}
3406
3407
3408/**
3409 * Sets the TPR threshold in the VMCS.
3410 *
3411 * @returns VBox status code.
3412 * @param pVCpu The cross context virtual CPU structure.
3413 * @param u32TprThreshold The TPR threshold (task-priority class only).
3414 */
3415DECLINLINE(int) hmR0VmxApicSetTprThreshold(PVMCPU pVCpu, uint32_t u32TprThreshold)
3416{
3417 Assert(!(u32TprThreshold & 0xfffffff0)); /* Bits 31:4 MBZ. */
3418 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW); RT_NOREF_PV(pVCpu);
3419 return VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
3420}
3421
3422
3423/**
3424 * Loads the guest APIC and related state.
3425 *
3426 * @returns VBox status code.
3427 * @param pVCpu The cross context virtual CPU structure.
3428 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3429 * out-of-sync. Make sure to update the required fields
3430 * before using them.
3431 *
3432 * @remarks No-long-jump zone!!!
3433 */
3434DECLINLINE(int) hmR0VmxLoadGuestApicState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3435{
3436 NOREF(pMixedCtx);
3437
3438 int rc = VINF_SUCCESS;
3439 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE))
3440 {
3441 if ( PDMHasApic(pVCpu->CTX_SUFF(pVM))
3442 && APICIsEnabled(pVCpu))
3443 {
3444 /*
3445 * Setup TPR shadowing.
3446 */
3447 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
3448 {
3449 Assert(pVCpu->hm.s.vmx.HCPhysVirtApic);
3450
3451 bool fPendingIntr = false;
3452 uint8_t u8Tpr = 0;
3453 uint8_t u8PendingIntr = 0;
3454 rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
3455 AssertRCReturn(rc, rc);
3456
3457 /*
3458 * If there are interrupts pending but masked by the TPR, instruct VT-x to cause a TPR-below-threshold VM-exit
3459 * when the guest lowers its TPR below the priority of the pending interrupt so we can deliver the interrupt.
3460 * If there are no interrupts pending, set threshold to 0 to not cause any TPR-below-threshold VM-exits.
3461 */
3462 pVCpu->hm.s.vmx.pbVirtApic[XAPIC_OFF_TPR] = u8Tpr;
3463 uint32_t u32TprThreshold = 0;
3464 if (fPendingIntr)
3465 {
3466 /* Bits 3:0 of the TPR threshold field correspond to bits 7:4 of the TPR (which is the Task-Priority Class). */
3467 const uint8_t u8PendingPriority = u8PendingIntr >> 4;
3468 const uint8_t u8TprPriority = u8Tpr >> 4;
3469 if (u8PendingPriority <= u8TprPriority)
3470 u32TprThreshold = u8PendingPriority;
3471 }
3472
3473 rc = hmR0VmxApicSetTprThreshold(pVCpu, u32TprThreshold);
3474 AssertRCReturn(rc, rc);
3475 }
3476 }
3477 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
3478 }
3479
3480 return rc;
3481}
3482
3483
3484/**
3485 * Gets the guest's interruptibility-state ("interrupt shadow" as AMD calls it).
3486 *
3487 * @returns Guest's interruptibility-state.
3488 * @param pVCpu The cross context virtual CPU structure.
3489 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3490 * out-of-sync. Make sure to update the required fields
3491 * before using them.
3492 *
3493 * @remarks No-long-jump zone!!!
3494 */
3495DECLINLINE(uint32_t) hmR0VmxGetGuestIntrState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3496{
3497 /*
3498 * Check if we should inhibit interrupt delivery due to instructions like STI and MOV SS.
3499 */
3500 uint32_t uIntrState = 0;
3501 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3502 {
3503 /* If inhibition is active, RIP & RFLAGS should've been accessed (i.e. read previously from the VMCS or from ring-3). */
3504 AssertMsg(HMVMXCPU_GST_IS_SET(pVCpu, HMVMX_UPDATED_GUEST_RIP | HMVMX_UPDATED_GUEST_RFLAGS),
3505 ("%#x\n", HMVMXCPU_GST_VALUE(pVCpu)));
3506 if (pMixedCtx->rip == EMGetInhibitInterruptsPC(pVCpu))
3507 {
3508 if (pMixedCtx->eflags.Bits.u1IF)
3509 uIntrState = VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI;
3510 else
3511 uIntrState = VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS;
3512 }
3513 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3514 {
3515 /*
3516 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
3517 * VT-x, the flag's condition to be cleared is met and thus the cleared state is correct.
3518 */
3519 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3520 }
3521 }
3522
3523 /*
3524 * NMIs to the guest are blocked after an NMI is injected until the guest executes an IRET. We only
3525 * bother with virtual-NMI blocking when we have support for virtual NMIs in the CPU, otherwise
3526 * setting this would block host-NMIs and IRET will not clear the blocking.
3527 *
3528 * See Intel spec. 26.6.1 "Interruptibility state". See @bugref{7445}.
3529 */
3530 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS)
3531 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI))
3532 {
3533 uIntrState |= VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI;
3534 }
3535
3536 return uIntrState;
3537}
3538
3539
3540/**
3541 * Loads the guest's interruptibility-state into the guest-state area in the
3542 * VMCS.
3543 *
3544 * @returns VBox status code.
3545 * @param pVCpu The cross context virtual CPU structure.
3546 * @param uIntrState The interruptibility-state to set.
3547 */
3548static int hmR0VmxLoadGuestIntrState(PVMCPU pVCpu, uint32_t uIntrState)
3549{
3550 NOREF(pVCpu);
3551 AssertMsg(!(uIntrState & 0xfffffff0), ("%#x\n", uIntrState)); /* Bits 31:4 MBZ. */
3552 Assert((uIntrState & 0x3) != 0x3); /* Block-by-STI and MOV SS cannot be simultaneously set. */
3553 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, uIntrState);
3554 AssertRC(rc);
3555 return rc;
3556}
3557
3558
3559/**
3560 * Loads the exception intercepts required for guest execution in the VMCS.
3561 *
3562 * @returns VBox status code.
3563 * @param pVCpu The cross context virtual CPU structure.
3564 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3565 * out-of-sync. Make sure to update the required fields
3566 * before using them.
3567 */
3568static int hmR0VmxLoadGuestXcptIntercepts(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3569{
3570 NOREF(pMixedCtx);
3571 int rc = VINF_SUCCESS;
3572 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
3573 {
3574 /* The remaining exception intercepts are handled elsewhere, e.g. in hmR0VmxLoadSharedCR0(). */
3575 if (pVCpu->hm.s.fGIMTrapXcptUD)
3576 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_UD);
3577#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
3578 else
3579 pVCpu->hm.s.vmx.u32XcptBitmap &= ~RT_BIT(X86_XCPT_UD);
3580#endif
3581
3582 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_AC));
3583 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_DB));
3584
3585 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVCpu->hm.s.vmx.u32XcptBitmap);
3586 AssertRCReturn(rc, rc);
3587
3588 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
3589 Log4(("Load[%RU32]: VMX_VMCS32_CTRL_EXCEPTION_BITMAP=%#RX64 fContextUseFlags=%#RX32\n", pVCpu->idCpu,
3590 pVCpu->hm.s.vmx.u32XcptBitmap, HMCPU_CF_VALUE(pVCpu)));
3591 }
3592 return rc;
3593}
3594
3595
3596/**
3597 * Loads the guest's RIP into the guest-state area in the VMCS.
3598 *
3599 * @returns VBox status code.
3600 * @param pVCpu The cross context virtual CPU structure.
3601 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3602 * out-of-sync. Make sure to update the required fields
3603 * before using them.
3604 *
3605 * @remarks No-long-jump zone!!!
3606 */
3607static int hmR0VmxLoadGuestRip(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3608{
3609 int rc = VINF_SUCCESS;
3610 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RIP))
3611 {
3612 rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_RIP, pMixedCtx->rip);
3613 AssertRCReturn(rc, rc);
3614
3615 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP);
3616 Log4(("Load[%RU32]: VMX_VMCS_GUEST_RIP=%#RX64 fContextUseFlags=%#RX32\n", pVCpu->idCpu, pMixedCtx->rip,
3617 HMCPU_CF_VALUE(pVCpu)));
3618 }
3619 return rc;
3620}
3621
3622
3623/**
3624 * Loads the guest's RSP into the guest-state area in the VMCS.
3625 *
3626 * @returns VBox status code.
3627 * @param pVCpu The cross context virtual CPU structure.
3628 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3629 * out-of-sync. Make sure to update the required fields
3630 * before using them.
3631 *
3632 * @remarks No-long-jump zone!!!
3633 */
3634static int hmR0VmxLoadGuestRsp(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3635{
3636 int rc = VINF_SUCCESS;
3637 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RSP))
3638 {
3639 rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_RSP, pMixedCtx->rsp);
3640 AssertRCReturn(rc, rc);
3641
3642 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RSP);
3643 Log4(("Load[%RU32]: VMX_VMCS_GUEST_RSP=%#RX64\n", pVCpu->idCpu, pMixedCtx->rsp));
3644 }
3645 return rc;
3646}
3647
3648
3649/**
3650 * Loads the guest's RFLAGS into the guest-state area in the VMCS.
3651 *
3652 * @returns VBox status code.
3653 * @param pVCpu The cross context virtual CPU structure.
3654 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3655 * out-of-sync. Make sure to update the required fields
3656 * before using them.
3657 *
3658 * @remarks No-long-jump zone!!!
3659 */
3660static int hmR0VmxLoadGuestRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3661{
3662 int rc = VINF_SUCCESS;
3663 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RFLAGS))
3664 {
3665 /* Intel spec. 2.3.1 "System Flags and Fields in IA-32e Mode" claims the upper 32-bits of RFLAGS are reserved (MBZ).
3666 Let us assert it as such and use 32-bit VMWRITE. */
3667 Assert(!(pMixedCtx->rflags.u64 >> 32));
3668 X86EFLAGS Eflags = pMixedCtx->eflags;
3669 /** @todo r=bird: There shall be no need to OR in X86_EFL_1 here, nor
3670 * shall there be any reason for clearing bits 63:22, 15, 5 and 3.
3671 * These will never be cleared/set, unless some other part of the VMM
3672 * code is buggy - in which case we're better of finding and fixing
3673 * those bugs than hiding them. */
3674 Assert(Eflags.u32 & X86_EFL_RA1_MASK);
3675 Assert(!(Eflags.u32 & ~(X86_EFL_1 | X86_EFL_LIVE_MASK)));
3676 Eflags.u32 &= VMX_EFLAGS_RESERVED_0; /* Bits 22-31, 15, 5 & 3 MBZ. */
3677 Eflags.u32 |= VMX_EFLAGS_RESERVED_1; /* Bit 1 MB1. */
3678
3679 /*
3680 * If we're emulating real-mode using Virtual 8086 mode, save the real-mode eflags so we can restore them on VM-exit.
3681 * Modify the real-mode guest's eflags so that VT-x can run the real-mode guest code under Virtual 8086 mode.
3682 */
3683 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
3684 {
3685 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
3686 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
3687 pVCpu->hm.s.vmx.RealMode.Eflags.u32 = Eflags.u32; /* Save the original eflags of the real-mode guest. */
3688 Eflags.Bits.u1VM = 1; /* Set the Virtual 8086 mode bit. */
3689 Eflags.Bits.u2IOPL = 0; /* Change IOPL to 0, otherwise certain instructions won't fault. */
3690 }
3691
3692 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_RFLAGS, Eflags.u32);
3693 AssertRCReturn(rc, rc);
3694
3695 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RFLAGS);
3696 Log4(("Load[%RU32]: VMX_VMCS_GUEST_RFLAGS=%#RX32\n", pVCpu->idCpu, Eflags.u32));
3697 }
3698 return rc;
3699}
3700
3701
3702/**
3703 * Loads the guest RIP, RSP and RFLAGS into the guest-state area in the VMCS.
3704 *
3705 * @returns VBox status code.
3706 * @param pVCpu The cross context virtual CPU structure.
3707 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3708 * out-of-sync. Make sure to update the required fields
3709 * before using them.
3710 *
3711 * @remarks No-long-jump zone!!!
3712 */
3713DECLINLINE(int) hmR0VmxLoadGuestRipRspRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3714{
3715 int rc = hmR0VmxLoadGuestRip(pVCpu, pMixedCtx);
3716 rc |= hmR0VmxLoadGuestRsp(pVCpu, pMixedCtx);
3717 rc |= hmR0VmxLoadGuestRflags(pVCpu, pMixedCtx);
3718 AssertRCReturn(rc, rc);
3719 return rc;
3720}
3721
3722
3723/**
3724 * Loads the guest CR0 control register into the guest-state area in the VMCS.
3725 * CR0 is partially shared with the host and we have to consider the FPU bits.
3726 *
3727 * @returns VBox status code.
3728 * @param pVCpu The cross context virtual CPU structure.
3729 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3730 * out-of-sync. Make sure to update the required fields
3731 * before using them.
3732 *
3733 * @remarks No-long-jump zone!!!
3734 */
3735static int hmR0VmxLoadSharedCR0(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3736{
3737 /*
3738 * Guest CR0.
3739 * Guest FPU.
3740 */
3741 int rc = VINF_SUCCESS;
3742 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
3743 {
3744 Assert(!(pMixedCtx->cr0 >> 32));
3745 uint32_t u32GuestCR0 = pMixedCtx->cr0;
3746 PVM pVM = pVCpu->CTX_SUFF(pVM);
3747
3748 /* The guest's view (read access) of its CR0 is unblemished. */
3749 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR0_READ_SHADOW, u32GuestCR0);
3750 AssertRCReturn(rc, rc);
3751 Log4(("Load[%RU32]: VMX_VMCS_CTRL_CR0_READ_SHADOW=%#RX32\n", pVCpu->idCpu, u32GuestCR0));
3752
3753 /* Setup VT-x's view of the guest CR0. */
3754 /* Minimize VM-exits due to CR3 changes when we have NestedPaging. */
3755 if (pVM->hm.s.fNestedPaging)
3756 {
3757 if (CPUMIsGuestPagingEnabledEx(pMixedCtx))
3758 {
3759 /* The guest has paging enabled, let it access CR3 without causing a VM-exit if supported. */
3760 pVCpu->hm.s.vmx.u32ProcCtls &= ~( VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT
3761 | VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT);
3762 }
3763 else
3764 {
3765 /* The guest doesn't have paging enabled, make CR3 access cause a VM-exit to update our shadow. */
3766 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT
3767 | VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT;
3768 }
3769
3770 /* If we have unrestricted guest execution, we never have to intercept CR3 reads. */
3771 if (pVM->hm.s.vmx.fUnrestrictedGuest)
3772 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT;
3773
3774 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
3775 AssertRCReturn(rc, rc);
3776 }
3777 else
3778 u32GuestCR0 |= X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
3779
3780 /*
3781 * Guest FPU bits.
3782 * Intel spec. 23.8 "Restrictions on VMX operation" mentions that CR0.NE bit must always be set on the first
3783 * CPUs to support VT-x and no mention of with regards to UX in VM-entry checks.
3784 */
3785 u32GuestCR0 |= X86_CR0_NE;
3786 bool fInterceptNM = false;
3787 if (CPUMIsGuestFPUStateActive(pVCpu))
3788 {
3789 fInterceptNM = false; /* Guest FPU active, no need to VM-exit on #NM. */
3790 /* The guest should still get #NM exceptions when it expects it to, so we should not clear TS & MP bits here.
3791 We're only concerned about -us- not intercepting #NMs when the guest-FPU is active. Not the guest itself! */
3792 }
3793 else
3794 {
3795 fInterceptNM = true; /* Guest FPU inactive, VM-exit on #NM for lazy FPU loading. */
3796 u32GuestCR0 |= X86_CR0_TS /* Guest can task switch quickly and do lazy FPU syncing. */
3797 | X86_CR0_MP; /* FWAIT/WAIT should not ignore CR0.TS and should generate #NM. */
3798 }
3799
3800 /* Catch floating point exceptions if we need to report them to the guest in a different way. */
3801 bool fInterceptMF = false;
3802 if (!(pMixedCtx->cr0 & X86_CR0_NE))
3803 fInterceptMF = true;
3804
3805 /* Finally, intercept all exceptions as we cannot directly inject them in real-mode, see hmR0VmxInjectEventVmcs(). */
3806 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
3807 {
3808 Assert(PDMVmmDevHeapIsEnabled(pVM));
3809 Assert(pVM->hm.s.vmx.pRealModeTSS);
3810 pVCpu->hm.s.vmx.u32XcptBitmap |= HMVMX_REAL_MODE_XCPT_MASK;
3811 fInterceptNM = true;
3812 fInterceptMF = true;
3813 }
3814 else
3815 {
3816 /* For now, cleared here as mode-switches can happen outside HM/VT-x. See @bugref{7626#c11}. */
3817 pVCpu->hm.s.vmx.u32XcptBitmap &= ~HMVMX_REAL_MODE_XCPT_MASK;
3818 }
3819 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
3820
3821 if (fInterceptNM)
3822 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_NM);
3823 else
3824 pVCpu->hm.s.vmx.u32XcptBitmap &= ~RT_BIT(X86_XCPT_NM);
3825
3826 if (fInterceptMF)
3827 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_MF);
3828 else
3829 pVCpu->hm.s.vmx.u32XcptBitmap &= ~RT_BIT(X86_XCPT_MF);
3830
3831 /* Additional intercepts for debugging, define these yourself explicitly. */
3832#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
3833 pVCpu->hm.s.vmx.u32XcptBitmap |= 0
3834 | RT_BIT(X86_XCPT_BP)
3835 | RT_BIT(X86_XCPT_DE)
3836 | RT_BIT(X86_XCPT_NM)
3837 | RT_BIT(X86_XCPT_TS)
3838 | RT_BIT(X86_XCPT_UD)
3839 | RT_BIT(X86_XCPT_NP)
3840 | RT_BIT(X86_XCPT_SS)
3841 | RT_BIT(X86_XCPT_GP)
3842 | RT_BIT(X86_XCPT_PF)
3843 | RT_BIT(X86_XCPT_MF)
3844 ;
3845#elif defined(HMVMX_ALWAYS_TRAP_PF)
3846 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_PF);
3847#endif
3848
3849 Assert(pVM->hm.s.fNestedPaging || (pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT(X86_XCPT_PF)));
3850
3851 /* Set/clear the CR0 specific bits along with their exceptions (PE, PG, CD, NW). */
3852 uint32_t uSetCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
3853 uint32_t uZapCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
3854 if (pVM->hm.s.vmx.fUnrestrictedGuest) /* Exceptions for unrestricted-guests for fixed CR0 bits (PE, PG). */
3855 uSetCR0 &= ~(X86_CR0_PE | X86_CR0_PG);
3856 else
3857 Assert((uSetCR0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG));
3858
3859 u32GuestCR0 |= uSetCR0;
3860 u32GuestCR0 &= uZapCR0;
3861 u32GuestCR0 &= ~(X86_CR0_CD | X86_CR0_NW); /* Always enable caching. */
3862
3863 /* Write VT-x's view of the guest CR0 into the VMCS. */
3864 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_CR0, u32GuestCR0);
3865 AssertRCReturn(rc, rc);
3866 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR0=%#RX32 (uSetCR0=%#RX32 uZapCR0=%#RX32)\n", pVCpu->idCpu, u32GuestCR0, uSetCR0,
3867 uZapCR0));
3868
3869 /*
3870 * CR0 is shared between host and guest along with a CR0 read shadow. Therefore, certain bits must not be changed
3871 * by the guest because VT-x ignores saving/restoring them (namely CD, ET, NW) and for certain other bits
3872 * we want to be notified immediately of guest CR0 changes (e.g. PG to update our shadow page tables).
3873 */
3874 uint32_t u32CR0Mask = 0;
3875 u32CR0Mask = X86_CR0_PE
3876 | X86_CR0_NE
3877 | X86_CR0_WP
3878 | X86_CR0_PG
3879 | X86_CR0_ET /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.ET */
3880 | X86_CR0_CD /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.CD */
3881 | X86_CR0_NW; /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.NW */
3882
3883 /** @todo Avoid intercepting CR0.PE with unrestricted guests. Fix PGM
3884 * enmGuestMode to be in-sync with the current mode. See @bugref{6398}
3885 * and @bugref{6944}. */
3886#if 0
3887 if (pVM->hm.s.vmx.fUnrestrictedGuest)
3888 u32CR0Mask &= ~X86_CR0_PE;
3889#endif
3890 if (pVM->hm.s.fNestedPaging)
3891 u32CR0Mask &= ~X86_CR0_WP;
3892
3893 /* If the guest FPU state is active, don't need to VM-exit on writes to FPU related bits in CR0. */
3894 if (fInterceptNM)
3895 {
3896 u32CR0Mask |= X86_CR0_TS
3897 | X86_CR0_MP;
3898 }
3899
3900 /* Write the CR0 mask into the VMCS and update the VCPU's copy of the current CR0 mask. */
3901 pVCpu->hm.s.vmx.u32CR0Mask = u32CR0Mask;
3902 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR0_MASK, u32CR0Mask);
3903 AssertRCReturn(rc, rc);
3904 Log4(("Load[%RU32]: VMX_VMCS_CTRL_CR0_MASK=%#RX32\n", pVCpu->idCpu, u32CR0Mask));
3905
3906 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR0);
3907 }
3908 return rc;
3909}
3910
3911
3912/**
3913 * Loads the guest control registers (CR3, CR4) into the guest-state area
3914 * in the VMCS.
3915 *
3916 * @returns VBox strict status code.
3917 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
3918 * without unrestricted guest access and the VMMDev is not presently
3919 * mapped (e.g. EFI32).
3920 *
3921 * @param pVCpu The cross context virtual CPU structure.
3922 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3923 * out-of-sync. Make sure to update the required fields
3924 * before using them.
3925 *
3926 * @remarks No-long-jump zone!!!
3927 */
3928static VBOXSTRICTRC hmR0VmxLoadGuestCR3AndCR4(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3929{
3930 int rc = VINF_SUCCESS;
3931 PVM pVM = pVCpu->CTX_SUFF(pVM);
3932
3933 /*
3934 * Guest CR2.
3935 * It's always loaded in the assembler code. Nothing to do here.
3936 */
3937
3938 /*
3939 * Guest CR3.
3940 */
3941 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR3))
3942 {
3943 RTGCPHYS GCPhysGuestCR3 = NIL_RTGCPHYS;
3944 if (pVM->hm.s.fNestedPaging)
3945 {
3946 pVCpu->hm.s.vmx.HCPhysEPTP = PGMGetHyperCR3(pVCpu);
3947
3948 /* Validate. See Intel spec. 28.2.2 "EPT Translation Mechanism" and 24.6.11 "Extended-Page-Table Pointer (EPTP)" */
3949 Assert(pVCpu->hm.s.vmx.HCPhysEPTP);
3950 Assert(!(pVCpu->hm.s.vmx.HCPhysEPTP & UINT64_C(0xfff0000000000000)));
3951 Assert(!(pVCpu->hm.s.vmx.HCPhysEPTP & 0xfff));
3952
3953 /* VMX_EPT_MEMTYPE_WB support is already checked in hmR0VmxSetupTaggedTlb(). */
3954 pVCpu->hm.s.vmx.HCPhysEPTP |= VMX_EPT_MEMTYPE_WB
3955 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
3956
3957 /* Validate. See Intel spec. 26.2.1 "Checks on VMX Controls" */
3958 AssertMsg( ((pVCpu->hm.s.vmx.HCPhysEPTP >> 3) & 0x07) == 3 /* Bits 3:5 (EPT page walk length - 1) must be 3. */
3959 && ((pVCpu->hm.s.vmx.HCPhysEPTP >> 7) & 0x1f) == 0, /* Bits 7:11 MBZ. */
3960 ("EPTP %#RX64\n", pVCpu->hm.s.vmx.HCPhysEPTP));
3961 AssertMsg( !((pVCpu->hm.s.vmx.HCPhysEPTP >> 6) & 0x01) /* Bit 6 (EPT accessed & dirty bit). */
3962 || (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY),
3963 ("EPTP accessed/dirty bit not supported by CPU but set %#RX64\n", pVCpu->hm.s.vmx.HCPhysEPTP));
3964
3965 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, pVCpu->hm.s.vmx.HCPhysEPTP);
3966 AssertRCReturn(rc, rc);
3967 Log4(("Load[%RU32]: VMX_VMCS64_CTRL_EPTP_FULL=%#RX64\n", pVCpu->idCpu, pVCpu->hm.s.vmx.HCPhysEPTP));
3968
3969 if ( pVM->hm.s.vmx.fUnrestrictedGuest
3970 || CPUMIsGuestPagingEnabledEx(pMixedCtx))
3971 {
3972 /* If the guest is in PAE mode, pass the PDPEs to VT-x using the VMCS fields. */
3973 if (CPUMIsGuestInPAEModeEx(pMixedCtx))
3974 {
3975 rc = PGMGstGetPaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
3976 AssertRCReturn(rc, rc);
3977 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, pVCpu->hm.s.aPdpes[0].u);
3978 rc |= VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, pVCpu->hm.s.aPdpes[1].u);
3979 rc |= VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, pVCpu->hm.s.aPdpes[2].u);
3980 rc |= VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, pVCpu->hm.s.aPdpes[3].u);
3981 AssertRCReturn(rc, rc);
3982 }
3983
3984 /* The guest's view of its CR3 is unblemished with Nested Paging when the guest is using paging or we
3985 have Unrestricted Execution to handle the guest when it's not using paging. */
3986 GCPhysGuestCR3 = pMixedCtx->cr3;
3987 }
3988 else
3989 {
3990 /*
3991 * The guest is not using paging, but the CPU (VT-x) has to. While the guest thinks it accesses physical memory
3992 * directly, we use our identity-mapped page table to map guest-linear to guest-physical addresses.
3993 * EPT takes care of translating it to host-physical addresses.
3994 */
3995 RTGCPHYS GCPhys;
3996 Assert(pVM->hm.s.vmx.pNonPagingModeEPTPageTable);
3997
3998 /* We obtain it here every time as the guest could have relocated this PCI region. */
3999 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
4000 if (RT_SUCCESS(rc))
4001 { /* likely */ }
4002 else if (rc == VERR_PDM_DEV_HEAP_R3_TO_GCPHYS)
4003 {
4004 Log4(("Load[%RU32]: VERR_PDM_DEV_HEAP_R3_TO_GCPHYS -> VINF_EM_RESCHEDULE_REM\n", pVCpu->idCpu));
4005 return VINF_EM_RESCHEDULE_REM; /* We cannot execute now, switch to REM/IEM till the guest maps in VMMDev. */
4006 }
4007 else
4008 AssertMsgFailedReturn(("%Rrc\n", rc), rc);
4009
4010 GCPhysGuestCR3 = GCPhys;
4011 }
4012
4013 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR3=%#RGp (GstN)\n", pVCpu->idCpu, GCPhysGuestCR3));
4014 rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_CR3, GCPhysGuestCR3);
4015 }
4016 else
4017 {
4018 /* Non-nested paging case, just use the hypervisor's CR3. */
4019 RTHCPHYS HCPhysGuestCR3 = PGMGetHyperCR3(pVCpu);
4020
4021 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR3=%#RHv (HstN)\n", pVCpu->idCpu, HCPhysGuestCR3));
4022 rc = VMXWriteVmcsHstN(VMX_VMCS_GUEST_CR3, HCPhysGuestCR3);
4023 }
4024 AssertRCReturn(rc, rc);
4025
4026 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR3);
4027 }
4028
4029 /*
4030 * Guest CR4.
4031 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
4032 */
4033 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR4))
4034 {
4035 Assert(!(pMixedCtx->cr4 >> 32));
4036 uint32_t u32GuestCR4 = pMixedCtx->cr4;
4037
4038 /* The guest's view of its CR4 is unblemished. */
4039 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR4_READ_SHADOW, u32GuestCR4);
4040 AssertRCReturn(rc, rc);
4041 Log4(("Load[%RU32]: VMX_VMCS_CTRL_CR4_READ_SHADOW=%#RX32\n", pVCpu->idCpu, u32GuestCR4));
4042
4043 /* Setup VT-x's view of the guest CR4. */
4044 /*
4045 * If we're emulating real-mode using virtual-8086 mode, we want to redirect software interrupts to the 8086 program
4046 * interrupt handler. Clear the VME bit (the interrupt redirection bitmap is already all 0, see hmR3InitFinalizeR0())
4047 * See Intel spec. 20.2 "Software Interrupt Handling Methods While in Virtual-8086 Mode".
4048 */
4049 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4050 {
4051 Assert(pVM->hm.s.vmx.pRealModeTSS);
4052 Assert(PDMVmmDevHeapIsEnabled(pVM));
4053 u32GuestCR4 &= ~X86_CR4_VME;
4054 }
4055
4056 if (pVM->hm.s.fNestedPaging)
4057 {
4058 if ( !CPUMIsGuestPagingEnabledEx(pMixedCtx)
4059 && !pVM->hm.s.vmx.fUnrestrictedGuest)
4060 {
4061 /* We use 4 MB pages in our identity mapping page table when the guest doesn't have paging. */
4062 u32GuestCR4 |= X86_CR4_PSE;
4063 /* Our identity mapping is a 32-bit page directory. */
4064 u32GuestCR4 &= ~X86_CR4_PAE;
4065 }
4066 /* else use guest CR4.*/
4067 }
4068 else
4069 {
4070 /*
4071 * The shadow paging modes and guest paging modes are different, the shadow is in accordance with the host
4072 * paging mode and thus we need to adjust VT-x's view of CR4 depending on our shadow page tables.
4073 */
4074 switch (pVCpu->hm.s.enmShadowMode)
4075 {
4076 case PGMMODE_REAL: /* Real-mode. */
4077 case PGMMODE_PROTECTED: /* Protected mode without paging. */
4078 case PGMMODE_32_BIT: /* 32-bit paging. */
4079 {
4080 u32GuestCR4 &= ~X86_CR4_PAE;
4081 break;
4082 }
4083
4084 case PGMMODE_PAE: /* PAE paging. */
4085 case PGMMODE_PAE_NX: /* PAE paging with NX. */
4086 {
4087 u32GuestCR4 |= X86_CR4_PAE;
4088 break;
4089 }
4090
4091 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
4092 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
4093#ifdef VBOX_ENABLE_64_BITS_GUESTS
4094 break;
4095#endif
4096 default:
4097 AssertFailed();
4098 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
4099 }
4100 }
4101
4102 /* We need to set and clear the CR4 specific bits here (mainly the X86_CR4_VMXE bit). */
4103 uint64_t uSetCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
4104 uint64_t uZapCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
4105 u32GuestCR4 |= uSetCR4;
4106 u32GuestCR4 &= uZapCR4;
4107
4108 /* Write VT-x's view of the guest CR4 into the VMCS. */
4109 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR4=%#RX32 (Set=%#RX32 Zap=%#RX32)\n", pVCpu->idCpu, u32GuestCR4, uSetCR4, uZapCR4));
4110 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_CR4, u32GuestCR4);
4111 AssertRCReturn(rc, rc);
4112
4113 /* Setup CR4 mask. CR4 flags owned by the host, if the guest attempts to change them, that would cause a VM-exit. */
4114 uint32_t u32CR4Mask = X86_CR4_VME
4115 | X86_CR4_PAE
4116 | X86_CR4_PGE
4117 | X86_CR4_PSE
4118 | X86_CR4_VMXE;
4119 if (pVM->cpum.ro.HostFeatures.fXSaveRstor)
4120 u32CR4Mask |= X86_CR4_OSXSAVE;
4121 pVCpu->hm.s.vmx.u32CR4Mask = u32CR4Mask;
4122 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR4_MASK, u32CR4Mask);
4123 AssertRCReturn(rc, rc);
4124
4125 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
4126 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pMixedCtx->cr4 & X86_CR4_OSXSAVE) && pMixedCtx->aXcr[0] != ASMGetXcr0();
4127
4128 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR4);
4129 }
4130 return rc;
4131}
4132
4133
4134/**
4135 * Loads the guest debug registers into the guest-state area in the VMCS.
4136 *
4137 * This also sets up whether \#DB and MOV DRx accesses cause VM-exits.
4138 *
4139 * The guest debug bits are partially shared with the host (e.g. DR6, DR0-3).
4140 *
4141 * @returns VBox status code.
4142 * @param pVCpu The cross context virtual CPU structure.
4143 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4144 * out-of-sync. Make sure to update the required fields
4145 * before using them.
4146 *
4147 * @remarks No-long-jump zone!!!
4148 */
4149static int hmR0VmxLoadSharedDebugState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4150{
4151 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
4152 return VINF_SUCCESS;
4153
4154#ifdef VBOX_STRICT
4155 /* Validate. Intel spec. 26.3.1.1 "Checks on Guest Controls Registers, Debug Registers, MSRs" */
4156 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG)
4157 {
4158 /* Validate. Intel spec. 17.2 "Debug Registers", recompiler paranoia checks. */
4159 Assert((pMixedCtx->dr[7] & (X86_DR7_MBZ_MASK | X86_DR7_RAZ_MASK)) == 0); /* Bits 63:32, 15, 14, 12, 11 are reserved. */
4160 Assert((pMixedCtx->dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK); /* Bit 10 is reserved (RA1). */
4161 }
4162#endif
4163
4164 int rc;
4165 PVM pVM = pVCpu->CTX_SUFF(pVM);
4166 bool fSteppingDB = false;
4167 bool fInterceptMovDRx = false;
4168 if (pVCpu->hm.s.fSingleInstruction)
4169 {
4170 /* If the CPU supports the monitor trap flag, use it for single stepping in DBGF and avoid intercepting #DB. */
4171 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG)
4172 {
4173 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG;
4174 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
4175 AssertRCReturn(rc, rc);
4176 Assert(fSteppingDB == false);
4177 }
4178 else
4179 {
4180 pMixedCtx->eflags.u32 |= X86_EFL_TF;
4181 pVCpu->hm.s.fClearTrapFlag = true;
4182 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RFLAGS);
4183 fSteppingDB = true;
4184 }
4185 }
4186
4187 if ( fSteppingDB
4188 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
4189 {
4190 /*
4191 * Use the combined guest and host DRx values found in the hypervisor
4192 * register set because the debugger has breakpoints active or someone
4193 * is single stepping on the host side without a monitor trap flag.
4194 *
4195 * Note! DBGF expects a clean DR6 state before executing guest code.
4196 */
4197#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4198 if ( CPUMIsGuestInLongModeEx(pMixedCtx)
4199 && !CPUMIsHyperDebugStateActivePending(pVCpu))
4200 {
4201 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
4202 Assert(CPUMIsHyperDebugStateActivePending(pVCpu));
4203 Assert(!CPUMIsGuestDebugStateActivePending(pVCpu));
4204 }
4205 else
4206#endif
4207 if (!CPUMIsHyperDebugStateActive(pVCpu))
4208 {
4209 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
4210 Assert(CPUMIsHyperDebugStateActive(pVCpu));
4211 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
4212 }
4213
4214 /* Update DR7. (The other DRx values are handled by CPUM one way or the other.) */
4215 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_DR7, (uint32_t)CPUMGetHyperDR7(pVCpu));
4216 AssertRCReturn(rc, rc);
4217
4218 pVCpu->hm.s.fUsingHyperDR7 = true;
4219 fInterceptMovDRx = true;
4220 }
4221 else
4222 {
4223 /*
4224 * If the guest has enabled debug registers, we need to load them prior to
4225 * executing guest code so they'll trigger at the right time.
4226 */
4227 if (pMixedCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
4228 {
4229#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4230 if ( CPUMIsGuestInLongModeEx(pMixedCtx)
4231 && !CPUMIsGuestDebugStateActivePending(pVCpu))
4232 {
4233 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
4234 Assert(CPUMIsGuestDebugStateActivePending(pVCpu));
4235 Assert(!CPUMIsHyperDebugStateActivePending(pVCpu));
4236 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
4237 }
4238 else
4239#endif
4240 if (!CPUMIsGuestDebugStateActive(pVCpu))
4241 {
4242 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
4243 Assert(CPUMIsGuestDebugStateActive(pVCpu));
4244 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
4245 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
4246 }
4247 Assert(!fInterceptMovDRx);
4248 }
4249 /*
4250 * If no debugging enabled, we'll lazy load DR0-3. Unlike on AMD-V, we
4251 * must intercept #DB in order to maintain a correct DR6 guest value, and
4252 * because we need to intercept it to prevent nested #DBs from hanging the
4253 * CPU, we end up always having to intercept it. See hmR0VmxInitXcptBitmap.
4254 */
4255#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4256 else if ( !CPUMIsGuestDebugStateActivePending(pVCpu)
4257 && !CPUMIsGuestDebugStateActive(pVCpu))
4258#else
4259 else if (!CPUMIsGuestDebugStateActive(pVCpu))
4260#endif
4261 {
4262 fInterceptMovDRx = true;
4263 }
4264
4265 /* Update guest DR7. */
4266 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_DR7, pMixedCtx->dr[7]);
4267 AssertRCReturn(rc, rc);
4268
4269 pVCpu->hm.s.fUsingHyperDR7 = false;
4270 }
4271
4272 /*
4273 * Update the processor-based VM-execution controls regarding intercepting MOV DRx instructions.
4274 */
4275 if (fInterceptMovDRx)
4276 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT;
4277 else
4278 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT;
4279 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
4280 AssertRCReturn(rc, rc);
4281
4282 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_DEBUG);
4283 return VINF_SUCCESS;
4284}
4285
4286
4287#ifdef VBOX_STRICT
4288/**
4289 * Strict function to validate segment registers.
4290 *
4291 * @remarks ASSUMES CR0 is up to date.
4292 */
4293static void hmR0VmxValidateSegmentRegs(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4294{
4295 /* Validate segment registers. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers". */
4296 /* NOTE: The reason we check for attribute value 0 and not just the unusable bit here is because hmR0VmxWriteSegmentReg()
4297 * only updates the VMCS' copy of the value with the unusable bit and doesn't change the guest-context value. */
4298 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
4299 && ( !CPUMIsGuestInRealModeEx(pCtx)
4300 && !CPUMIsGuestInV86ModeEx(pCtx)))
4301 {
4302 /* Protected mode checks */
4303 /* CS */
4304 Assert(pCtx->cs.Attr.n.u1Present);
4305 Assert(!(pCtx->cs.Attr.u & 0xf00));
4306 Assert(!(pCtx->cs.Attr.u & 0xfffe0000));
4307 Assert( (pCtx->cs.u32Limit & 0xfff) == 0xfff
4308 || !(pCtx->cs.Attr.n.u1Granularity));
4309 Assert( !(pCtx->cs.u32Limit & 0xfff00000)
4310 || (pCtx->cs.Attr.n.u1Granularity));
4311 /* CS cannot be loaded with NULL in protected mode. */
4312 Assert(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE)); /** @todo is this really true even for 64-bit CS? */
4313 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
4314 Assert(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl);
4315 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
4316 Assert(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl);
4317 else
4318 AssertMsgFailed(("Invalid CS Type %#x\n", pCtx->cs.Attr.n.u2Dpl));
4319 /* SS */
4320 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
4321 Assert(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL));
4322 if ( !(pCtx->cr0 & X86_CR0_PE)
4323 || pCtx->cs.Attr.n.u4Type == 3)
4324 {
4325 Assert(!pCtx->ss.Attr.n.u2Dpl);
4326 }
4327 if (pCtx->ss.Attr.u && !(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
4328 {
4329 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
4330 Assert(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7);
4331 Assert(pCtx->ss.Attr.n.u1Present);
4332 Assert(!(pCtx->ss.Attr.u & 0xf00));
4333 Assert(!(pCtx->ss.Attr.u & 0xfffe0000));
4334 Assert( (pCtx->ss.u32Limit & 0xfff) == 0xfff
4335 || !(pCtx->ss.Attr.n.u1Granularity));
4336 Assert( !(pCtx->ss.u32Limit & 0xfff00000)
4337 || (pCtx->ss.Attr.n.u1Granularity));
4338 }
4339 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxWriteSegmentReg(). */
4340 if (pCtx->ds.Attr.u && !(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
4341 {
4342 Assert(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4343 Assert(pCtx->ds.Attr.n.u1Present);
4344 Assert(pCtx->ds.Attr.n.u4Type > 11 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL));
4345 Assert(!(pCtx->ds.Attr.u & 0xf00));
4346 Assert(!(pCtx->ds.Attr.u & 0xfffe0000));
4347 Assert( (pCtx->ds.u32Limit & 0xfff) == 0xfff
4348 || !(pCtx->ds.Attr.n.u1Granularity));
4349 Assert( !(pCtx->ds.u32Limit & 0xfff00000)
4350 || (pCtx->ds.Attr.n.u1Granularity));
4351 Assert( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4352 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ));
4353 }
4354 if (pCtx->es.Attr.u && !(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
4355 {
4356 Assert(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4357 Assert(pCtx->es.Attr.n.u1Present);
4358 Assert(pCtx->es.Attr.n.u4Type > 11 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL));
4359 Assert(!(pCtx->es.Attr.u & 0xf00));
4360 Assert(!(pCtx->es.Attr.u & 0xfffe0000));
4361 Assert( (pCtx->es.u32Limit & 0xfff) == 0xfff
4362 || !(pCtx->es.Attr.n.u1Granularity));
4363 Assert( !(pCtx->es.u32Limit & 0xfff00000)
4364 || (pCtx->es.Attr.n.u1Granularity));
4365 Assert( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4366 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ));
4367 }
4368 if (pCtx->fs.Attr.u && !(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
4369 {
4370 Assert(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4371 Assert(pCtx->fs.Attr.n.u1Present);
4372 Assert(pCtx->fs.Attr.n.u4Type > 11 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL));
4373 Assert(!(pCtx->fs.Attr.u & 0xf00));
4374 Assert(!(pCtx->fs.Attr.u & 0xfffe0000));
4375 Assert( (pCtx->fs.u32Limit & 0xfff) == 0xfff
4376 || !(pCtx->fs.Attr.n.u1Granularity));
4377 Assert( !(pCtx->fs.u32Limit & 0xfff00000)
4378 || (pCtx->fs.Attr.n.u1Granularity));
4379 Assert( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4380 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ));
4381 }
4382 if (pCtx->gs.Attr.u && !(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
4383 {
4384 Assert(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4385 Assert(pCtx->gs.Attr.n.u1Present);
4386 Assert(pCtx->gs.Attr.n.u4Type > 11 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL));
4387 Assert(!(pCtx->gs.Attr.u & 0xf00));
4388 Assert(!(pCtx->gs.Attr.u & 0xfffe0000));
4389 Assert( (pCtx->gs.u32Limit & 0xfff) == 0xfff
4390 || !(pCtx->gs.Attr.n.u1Granularity));
4391 Assert( !(pCtx->gs.u32Limit & 0xfff00000)
4392 || (pCtx->gs.Attr.n.u1Granularity));
4393 Assert( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4394 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ));
4395 }
4396 /* 64-bit capable CPUs. */
4397# if HC_ARCH_BITS == 64
4398 Assert(!(pCtx->cs.u64Base >> 32));
4399 Assert(!pCtx->ss.Attr.u || !(pCtx->ss.u64Base >> 32));
4400 Assert(!pCtx->ds.Attr.u || !(pCtx->ds.u64Base >> 32));
4401 Assert(!pCtx->es.Attr.u || !(pCtx->es.u64Base >> 32));
4402# endif
4403 }
4404 else if ( CPUMIsGuestInV86ModeEx(pCtx)
4405 || ( CPUMIsGuestInRealModeEx(pCtx)
4406 && !pVM->hm.s.vmx.fUnrestrictedGuest))
4407 {
4408 /* Real and v86 mode checks. */
4409 /* hmR0VmxWriteSegmentReg() writes the modified in VMCS. We want what we're feeding to VT-x. */
4410 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
4411 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4412 {
4413 u32CSAttr = 0xf3; u32SSAttr = 0xf3; u32DSAttr = 0xf3; u32ESAttr = 0xf3; u32FSAttr = 0xf3; u32GSAttr = 0xf3;
4414 }
4415 else
4416 {
4417 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u; u32DSAttr = pCtx->ds.Attr.u;
4418 u32ESAttr = pCtx->es.Attr.u; u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
4419 }
4420
4421 /* CS */
4422 AssertMsg((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), ("CS base %#x %#x\n", pCtx->cs.u64Base, pCtx->cs.Sel));
4423 Assert(pCtx->cs.u32Limit == 0xffff);
4424 Assert(u32CSAttr == 0xf3);
4425 /* SS */
4426 Assert(pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4);
4427 Assert(pCtx->ss.u32Limit == 0xffff);
4428 Assert(u32SSAttr == 0xf3);
4429 /* DS */
4430 Assert(pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4);
4431 Assert(pCtx->ds.u32Limit == 0xffff);
4432 Assert(u32DSAttr == 0xf3);
4433 /* ES */
4434 Assert(pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4);
4435 Assert(pCtx->es.u32Limit == 0xffff);
4436 Assert(u32ESAttr == 0xf3);
4437 /* FS */
4438 Assert(pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4);
4439 Assert(pCtx->fs.u32Limit == 0xffff);
4440 Assert(u32FSAttr == 0xf3);
4441 /* GS */
4442 Assert(pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4);
4443 Assert(pCtx->gs.u32Limit == 0xffff);
4444 Assert(u32GSAttr == 0xf3);
4445 /* 64-bit capable CPUs. */
4446# if HC_ARCH_BITS == 64
4447 Assert(!(pCtx->cs.u64Base >> 32));
4448 Assert(!u32SSAttr || !(pCtx->ss.u64Base >> 32));
4449 Assert(!u32DSAttr || !(pCtx->ds.u64Base >> 32));
4450 Assert(!u32ESAttr || !(pCtx->es.u64Base >> 32));
4451# endif
4452 }
4453}
4454#endif /* VBOX_STRICT */
4455
4456
4457/**
4458 * Writes a guest segment register into the guest-state area in the VMCS.
4459 *
4460 * @returns VBox status code.
4461 * @param pVCpu The cross context virtual CPU structure.
4462 * @param idxSel Index of the selector in the VMCS.
4463 * @param idxLimit Index of the segment limit in the VMCS.
4464 * @param idxBase Index of the segment base in the VMCS.
4465 * @param idxAccess Index of the access rights of the segment in the VMCS.
4466 * @param pSelReg Pointer to the segment selector.
4467 *
4468 * @remarks No-long-jump zone!!!
4469 */
4470static int hmR0VmxWriteSegmentReg(PVMCPU pVCpu, uint32_t idxSel, uint32_t idxLimit, uint32_t idxBase,
4471 uint32_t idxAccess, PCPUMSELREG pSelReg)
4472{
4473 int rc = VMXWriteVmcs32(idxSel, pSelReg->Sel); /* 16-bit guest selector field. */
4474 rc |= VMXWriteVmcs32(idxLimit, pSelReg->u32Limit); /* 32-bit guest segment limit field. */
4475 rc |= VMXWriteVmcsGstN(idxBase, pSelReg->u64Base); /* Natural width guest segment base field.*/
4476 AssertRCReturn(rc, rc);
4477
4478 uint32_t u32Access = pSelReg->Attr.u;
4479 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4480 {
4481 /* VT-x requires our real-using-v86 mode hack to override the segment access-right bits. */
4482 u32Access = 0xf3;
4483 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
4484 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
4485 }
4486 else
4487 {
4488 /*
4489 * The way to differentiate between whether this is really a null selector or was just a selector loaded with 0 in
4490 * real-mode is using the segment attributes. A selector loaded in real-mode with the value 0 is valid and usable in
4491 * protected-mode and we should -not- mark it as an unusable segment. Both the recompiler & VT-x ensures NULL selectors
4492 * loaded in protected-mode have their attribute as 0.
4493 */
4494 if (!u32Access)
4495 u32Access = X86DESCATTR_UNUSABLE;
4496 }
4497
4498 /* Validate segment access rights. Refer to Intel spec. "26.3.1.2 Checks on Guest Segment Registers". */
4499 AssertMsg((u32Access & X86DESCATTR_UNUSABLE) || (u32Access & X86_SEL_TYPE_ACCESSED),
4500 ("Access bit not set for usable segment. idx=%#x sel=%#x attr %#x\n", idxBase, pSelReg, pSelReg->Attr.u));
4501
4502 rc = VMXWriteVmcs32(idxAccess, u32Access); /* 32-bit guest segment access-rights field. */
4503 AssertRCReturn(rc, rc);
4504 return rc;
4505}
4506
4507
4508/**
4509 * Loads the guest segment registers, GDTR, IDTR, LDTR, (TR, FS and GS bases)
4510 * into the guest-state area in the VMCS.
4511 *
4512 * @returns VBox status code.
4513 * @param pVCpu The cross context virtual CPU structure.
4514 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4515 * out-of-sync. Make sure to update the required fields
4516 * before using them.
4517 *
4518 * @remarks ASSUMES pMixedCtx->cr0 is up to date (strict builds validation).
4519 * @remarks No-long-jump zone!!!
4520 */
4521static int hmR0VmxLoadGuestSegmentRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4522{
4523 int rc = VERR_INTERNAL_ERROR_5;
4524 PVM pVM = pVCpu->CTX_SUFF(pVM);
4525
4526 /*
4527 * Guest Segment registers: CS, SS, DS, ES, FS, GS.
4528 */
4529 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS))
4530 {
4531 /* Save the segment attributes for real-on-v86 mode hack, so we can restore them on VM-exit. */
4532 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4533 {
4534 pVCpu->hm.s.vmx.RealMode.AttrCS.u = pMixedCtx->cs.Attr.u;
4535 pVCpu->hm.s.vmx.RealMode.AttrSS.u = pMixedCtx->ss.Attr.u;
4536 pVCpu->hm.s.vmx.RealMode.AttrDS.u = pMixedCtx->ds.Attr.u;
4537 pVCpu->hm.s.vmx.RealMode.AttrES.u = pMixedCtx->es.Attr.u;
4538 pVCpu->hm.s.vmx.RealMode.AttrFS.u = pMixedCtx->fs.Attr.u;
4539 pVCpu->hm.s.vmx.RealMode.AttrGS.u = pMixedCtx->gs.Attr.u;
4540 }
4541
4542#ifdef VBOX_WITH_REM
4543 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
4544 {
4545 Assert(pVM->hm.s.vmx.pRealModeTSS);
4546 AssertCompile(PGMMODE_REAL < PGMMODE_PROTECTED);
4547 if ( pVCpu->hm.s.vmx.fWasInRealMode
4548 && PGMGetGuestMode(pVCpu) >= PGMMODE_PROTECTED)
4549 {
4550 /* Signal that the recompiler must flush its code-cache as the guest -may- rewrite code it will later execute
4551 in real-mode (e.g. OpenBSD 4.0) */
4552 REMFlushTBs(pVM);
4553 Log4(("Load[%RU32]: Switch to protected mode detected!\n", pVCpu->idCpu));
4554 pVCpu->hm.s.vmx.fWasInRealMode = false;
4555 }
4556 }
4557#endif
4558 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_CS_SEL, VMX_VMCS32_GUEST_CS_LIMIT, VMX_VMCS_GUEST_CS_BASE,
4559 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS, &pMixedCtx->cs);
4560 AssertRCReturn(rc, rc);
4561 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_SS_SEL, VMX_VMCS32_GUEST_SS_LIMIT, VMX_VMCS_GUEST_SS_BASE,
4562 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS, &pMixedCtx->ss);
4563 AssertRCReturn(rc, rc);
4564 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_DS_SEL, VMX_VMCS32_GUEST_DS_LIMIT, VMX_VMCS_GUEST_DS_BASE,
4565 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS, &pMixedCtx->ds);
4566 AssertRCReturn(rc, rc);
4567 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_ES_SEL, VMX_VMCS32_GUEST_ES_LIMIT, VMX_VMCS_GUEST_ES_BASE,
4568 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS, &pMixedCtx->es);
4569 AssertRCReturn(rc, rc);
4570 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_FS_SEL, VMX_VMCS32_GUEST_FS_LIMIT, VMX_VMCS_GUEST_FS_BASE,
4571 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS, &pMixedCtx->fs);
4572 AssertRCReturn(rc, rc);
4573 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_GS_SEL, VMX_VMCS32_GUEST_GS_LIMIT, VMX_VMCS_GUEST_GS_BASE,
4574 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS, &pMixedCtx->gs);
4575 AssertRCReturn(rc, rc);
4576
4577#ifdef VBOX_STRICT
4578 /* Validate. */
4579 hmR0VmxValidateSegmentRegs(pVM, pVCpu, pMixedCtx);
4580#endif
4581
4582 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS);
4583 Log4(("Load[%RU32]: CS=%#RX16 Base=%#RX64 Limit=%#RX32 Attr=%#RX32\n", pVCpu->idCpu, pMixedCtx->cs.Sel,
4584 pMixedCtx->cs.u64Base, pMixedCtx->cs.u32Limit, pMixedCtx->cs.Attr.u));
4585 }
4586
4587 /*
4588 * Guest TR.
4589 */
4590 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_TR))
4591 {
4592 /*
4593 * Real-mode emulation using virtual-8086 mode with CR4.VME. Interrupt redirection is achieved
4594 * using the interrupt redirection bitmap (all bits cleared to let the guest handle INT-n's) in the TSS.
4595 * See hmR3InitFinalizeR0() to see how pRealModeTSS is setup.
4596 */
4597 uint16_t u16Sel = 0;
4598 uint32_t u32Limit = 0;
4599 uint64_t u64Base = 0;
4600 uint32_t u32AccessRights = 0;
4601
4602 if (!pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4603 {
4604 u16Sel = pMixedCtx->tr.Sel;
4605 u32Limit = pMixedCtx->tr.u32Limit;
4606 u64Base = pMixedCtx->tr.u64Base;
4607 u32AccessRights = pMixedCtx->tr.Attr.u;
4608 }
4609 else
4610 {
4611 Assert(pVM->hm.s.vmx.pRealModeTSS);
4612 Assert(PDMVmmDevHeapIsEnabled(pVM)); /* Guaranteed by HMR3CanExecuteGuest() -XXX- what about inner loop changes? */
4613
4614 /* We obtain it here every time as PCI regions could be reconfigured in the guest, changing the VMMDev base. */
4615 RTGCPHYS GCPhys;
4616 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
4617 AssertRCReturn(rc, rc);
4618
4619 X86DESCATTR DescAttr;
4620 DescAttr.u = 0;
4621 DescAttr.n.u1Present = 1;
4622 DescAttr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
4623
4624 u16Sel = 0;
4625 u32Limit = HM_VTX_TSS_SIZE;
4626 u64Base = GCPhys; /* in real-mode phys = virt. */
4627 u32AccessRights = DescAttr.u;
4628 }
4629
4630 /* Validate. */
4631 Assert(!(u16Sel & RT_BIT(2)));
4632 AssertMsg( (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY
4633 || (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("TSS is not busy!? %#x\n", u32AccessRights));
4634 AssertMsg(!(u32AccessRights & X86DESCATTR_UNUSABLE), ("TR unusable bit is not clear!? %#x\n", u32AccessRights));
4635 Assert(!(u32AccessRights & RT_BIT(4))); /* System MBZ.*/
4636 Assert(u32AccessRights & RT_BIT(7)); /* Present MB1.*/
4637 Assert(!(u32AccessRights & 0xf00)); /* 11:8 MBZ. */
4638 Assert(!(u32AccessRights & 0xfffe0000)); /* 31:17 MBZ. */
4639 Assert( (u32Limit & 0xfff) == 0xfff
4640 || !(u32AccessRights & RT_BIT(15))); /* Granularity MBZ. */
4641 Assert( !(pMixedCtx->tr.u32Limit & 0xfff00000)
4642 || (u32AccessRights & RT_BIT(15))); /* Granularity MB1. */
4643
4644 rc = VMXWriteVmcs32(VMX_VMCS16_GUEST_TR_SEL, u16Sel);
4645 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, u32Limit);
4646 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_TR_BASE, u64Base);
4647 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, u32AccessRights);
4648 AssertRCReturn(rc, rc);
4649
4650 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_TR);
4651 Log4(("Load[%RU32]: VMX_VMCS_GUEST_TR_BASE=%#RX64\n", pVCpu->idCpu, u64Base));
4652 }
4653
4654 /*
4655 * Guest GDTR.
4656 */
4657 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_GDTR))
4658 {
4659 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, pMixedCtx->gdtr.cbGdt);
4660 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_GDTR_BASE, pMixedCtx->gdtr.pGdt);
4661 AssertRCReturn(rc, rc);
4662
4663 /* Validate. */
4664 Assert(!(pMixedCtx->gdtr.cbGdt & 0xffff0000)); /* Bits 31:16 MBZ. */
4665
4666 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_GDTR);
4667 Log4(("Load[%RU32]: VMX_VMCS_GUEST_GDTR_BASE=%#RX64\n", pVCpu->idCpu, pMixedCtx->gdtr.pGdt));
4668 }
4669
4670 /*
4671 * Guest LDTR.
4672 */
4673 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LDTR))
4674 {
4675 /* The unusable bit is specific to VT-x, if it's a null selector mark it as an unusable segment. */
4676 uint32_t u32Access = 0;
4677 if (!pMixedCtx->ldtr.Attr.u)
4678 u32Access = X86DESCATTR_UNUSABLE;
4679 else
4680 u32Access = pMixedCtx->ldtr.Attr.u;
4681
4682 rc = VMXWriteVmcs32(VMX_VMCS16_GUEST_LDTR_SEL, pMixedCtx->ldtr.Sel);
4683 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, pMixedCtx->ldtr.u32Limit);
4684 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_LDTR_BASE, pMixedCtx->ldtr.u64Base);
4685 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, u32Access);
4686 AssertRCReturn(rc, rc);
4687
4688 /* Validate. */
4689 if (!(u32Access & X86DESCATTR_UNUSABLE))
4690 {
4691 Assert(!(pMixedCtx->ldtr.Sel & RT_BIT(2))); /* TI MBZ. */
4692 Assert(pMixedCtx->ldtr.Attr.n.u4Type == 2); /* Type MB2 (LDT). */
4693 Assert(!pMixedCtx->ldtr.Attr.n.u1DescType); /* System MBZ. */
4694 Assert(pMixedCtx->ldtr.Attr.n.u1Present == 1); /* Present MB1. */
4695 Assert(!pMixedCtx->ldtr.Attr.n.u4LimitHigh); /* 11:8 MBZ. */
4696 Assert(!(pMixedCtx->ldtr.Attr.u & 0xfffe0000)); /* 31:17 MBZ. */
4697 Assert( (pMixedCtx->ldtr.u32Limit & 0xfff) == 0xfff
4698 || !pMixedCtx->ldtr.Attr.n.u1Granularity); /* Granularity MBZ. */
4699 Assert( !(pMixedCtx->ldtr.u32Limit & 0xfff00000)
4700 || pMixedCtx->ldtr.Attr.n.u1Granularity); /* Granularity MB1. */
4701 }
4702
4703 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LDTR);
4704 Log4(("Load[%RU32]: VMX_VMCS_GUEST_LDTR_BASE=%#RX64\n", pVCpu->idCpu, pMixedCtx->ldtr.u64Base));
4705 }
4706
4707 /*
4708 * Guest IDTR.
4709 */
4710 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_IDTR))
4711 {
4712 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, pMixedCtx->idtr.cbIdt);
4713 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_IDTR_BASE, pMixedCtx->idtr.pIdt);
4714 AssertRCReturn(rc, rc);
4715
4716 /* Validate. */
4717 Assert(!(pMixedCtx->idtr.cbIdt & 0xffff0000)); /* Bits 31:16 MBZ. */
4718
4719 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_IDTR);
4720 Log4(("Load[%RU32]: VMX_VMCS_GUEST_IDTR_BASE=%#RX64\n", pVCpu->idCpu, pMixedCtx->idtr.pIdt));
4721 }
4722
4723 return VINF_SUCCESS;
4724}
4725
4726
4727/**
4728 * Loads certain guest MSRs into the VM-entry MSR-load and VM-exit MSR-store
4729 * areas.
4730 *
4731 * These MSRs will automatically be loaded to the host CPU on every successful
4732 * VM-entry and stored from the host CPU on every successful VM-exit. This also
4733 * creates/updates MSR slots for the host MSRs. The actual host MSR values are
4734 * -not- updated here for performance reasons. See hmR0VmxSaveHostMsrs().
4735 *
4736 * Also loads the sysenter MSRs into the guest-state area in the VMCS.
4737 *
4738 * @returns VBox status code.
4739 * @param pVCpu The cross context virtual CPU structure.
4740 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4741 * out-of-sync. Make sure to update the required fields
4742 * before using them.
4743 *
4744 * @remarks No-long-jump zone!!!
4745 */
4746static int hmR0VmxLoadGuestMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4747{
4748 AssertPtr(pVCpu);
4749 AssertPtr(pVCpu->hm.s.vmx.pvGuestMsr);
4750
4751 /*
4752 * MSRs that we use the auto-load/store MSR area in the VMCS.
4753 */
4754 PVM pVM = pVCpu->CTX_SUFF(pVM);
4755 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS))
4756 {
4757 /* For 64-bit hosts, we load/restore them lazily, see hmR0VmxLazyLoadGuestMsrs(). */
4758#if HC_ARCH_BITS == 32
4759 if (pVM->hm.s.fAllow64BitGuests)
4760 {
4761 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_LSTAR, pMixedCtx->msrLSTAR, false, NULL);
4762 rc |= hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K6_STAR, pMixedCtx->msrSTAR, false, NULL);
4763 rc |= hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_SF_MASK, pMixedCtx->msrSFMASK, false, NULL);
4764 rc |= hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_KERNEL_GS_BASE, pMixedCtx->msrKERNELGSBASE, false, NULL);
4765 AssertRCReturn(rc, rc);
4766# ifdef LOG_ENABLED
4767 PVMXAUTOMSR pMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
4768 for (uint32_t i = 0; i < pVCpu->hm.s.vmx.cMsrs; i++, pMsr++)
4769 {
4770 Log4(("Load[%RU32]: MSR[%RU32]: u32Msr=%#RX32 u64Value=%#RX64\n", pVCpu->idCpu, i, pMsr->u32Msr,
4771 pMsr->u64Value));
4772 }
4773# endif
4774 }
4775#endif
4776 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
4777 }
4778
4779 /*
4780 * Guest Sysenter MSRs.
4781 * These flags are only set when MSR-bitmaps are not supported by the CPU and we cause
4782 * VM-exits on WRMSRs for these MSRs.
4783 */
4784 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR))
4785 {
4786 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, pMixedCtx->SysEnter.cs); AssertRCReturn(rc, rc);
4787 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR);
4788 }
4789
4790 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR))
4791 {
4792 int rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_SYSENTER_EIP, pMixedCtx->SysEnter.eip); AssertRCReturn(rc, rc);
4793 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
4794 }
4795
4796 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR))
4797 {
4798 int rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_SYSENTER_ESP, pMixedCtx->SysEnter.esp); AssertRCReturn(rc, rc);
4799 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
4800 }
4801
4802 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_EFER_MSR))
4803 {
4804 if (hmR0VmxShouldSwapEferMsr(pVCpu, pMixedCtx))
4805 {
4806 /*
4807 * If the CPU supports VMCS controls for swapping EFER, use it. Otherwise, we have no option
4808 * but to use the auto-load store MSR area in the VMCS for swapping EFER. See @bugref{7368}.
4809 */
4810 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
4811 {
4812 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_EFER_FULL, pMixedCtx->msrEFER);
4813 AssertRCReturn(rc,rc);
4814 Log4(("Load[%RU32]: VMX_VMCS64_GUEST_EFER_FULL=%#RX64\n", pVCpu->idCpu, pMixedCtx->msrEFER));
4815 }
4816 else
4817 {
4818 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K6_EFER, pMixedCtx->msrEFER, false /* fUpdateHostMsr */,
4819 NULL /* pfAddedAndUpdated */);
4820 AssertRCReturn(rc, rc);
4821
4822 /* We need to intercept reads too, see @bugref{7386#c16}. */
4823 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
4824 hmR0VmxSetMsrPermission(pVCpu, MSR_K6_EFER, VMXMSREXIT_INTERCEPT_READ, VMXMSREXIT_INTERCEPT_WRITE);
4825 Log4(("Load[%RU32]: MSR[--]: u32Msr=%#RX32 u64Value=%#RX64 cMsrs=%u\n", pVCpu->idCpu, MSR_K6_EFER,
4826 pMixedCtx->msrEFER, pVCpu->hm.s.vmx.cMsrs));
4827 }
4828 }
4829 else if (!pVM->hm.s.vmx.fSupportsVmcsEfer)
4830 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, MSR_K6_EFER);
4831 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
4832 }
4833
4834 return VINF_SUCCESS;
4835}
4836
4837
4838/**
4839 * Loads the guest activity state into the guest-state area in the VMCS.
4840 *
4841 * @returns VBox status code.
4842 * @param pVCpu The cross context virtual CPU structure.
4843 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4844 * out-of-sync. Make sure to update the required fields
4845 * before using them.
4846 *
4847 * @remarks No-long-jump zone!!!
4848 */
4849static int hmR0VmxLoadGuestActivityState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4850{
4851 NOREF(pMixedCtx);
4852 /** @todo See if we can make use of other states, e.g.
4853 * VMX_VMCS_GUEST_ACTIVITY_SHUTDOWN or HLT. */
4854 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_ACTIVITY_STATE))
4855 {
4856 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, VMX_VMCS_GUEST_ACTIVITY_ACTIVE);
4857 AssertRCReturn(rc, rc);
4858
4859 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_GUEST_ACTIVITY_STATE);
4860 }
4861 return VINF_SUCCESS;
4862}
4863
4864
4865#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
4866/**
4867 * Check if guest state allows safe use of 32-bit switcher again.
4868 *
4869 * Segment bases and protected mode structures must be 32-bit addressable
4870 * because the 32-bit switcher will ignore high dword when writing these VMCS
4871 * fields. See @bugref{8432} for details.
4872 *
4873 * @returns true if safe, false if must continue to use the 64-bit switcher.
4874 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4875 * out-of-sync. Make sure to update the required fields
4876 * before using them.
4877 *
4878 * @remarks No-long-jump zone!!!
4879 */
4880static bool hmR0VmxIs32BitSwitcherSafe(PCPUMCTX pMixedCtx)
4881{
4882 if (pMixedCtx->gdtr.pGdt & UINT64_C(0xffffffff00000000))
4883 return false;
4884 if (pMixedCtx->idtr.pIdt & UINT64_C(0xffffffff00000000))
4885 return false;
4886 if (pMixedCtx->ldtr.u64Base & UINT64_C(0xffffffff00000000))
4887 return false;
4888 if (pMixedCtx->tr.u64Base & UINT64_C(0xffffffff00000000))
4889 return false;
4890 if (pMixedCtx->es.u64Base & UINT64_C(0xffffffff00000000))
4891 return false;
4892 if (pMixedCtx->cs.u64Base & UINT64_C(0xffffffff00000000))
4893 return false;
4894 if (pMixedCtx->ss.u64Base & UINT64_C(0xffffffff00000000))
4895 return false;
4896 if (pMixedCtx->ds.u64Base & UINT64_C(0xffffffff00000000))
4897 return false;
4898 if (pMixedCtx->fs.u64Base & UINT64_C(0xffffffff00000000))
4899 return false;
4900 if (pMixedCtx->gs.u64Base & UINT64_C(0xffffffff00000000))
4901 return false;
4902 /* All good, bases are 32-bit. */
4903 return true;
4904}
4905#endif
4906
4907
4908/**
4909 * Sets up the appropriate function to run guest code.
4910 *
4911 * @returns VBox status code.
4912 * @param pVCpu The cross context virtual CPU structure.
4913 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4914 * out-of-sync. Make sure to update the required fields
4915 * before using them.
4916 *
4917 * @remarks No-long-jump zone!!!
4918 */
4919static int hmR0VmxSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4920{
4921 if (CPUMIsGuestInLongModeEx(pMixedCtx))
4922 {
4923#ifndef VBOX_ENABLE_64_BITS_GUESTS
4924 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
4925#endif
4926 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
4927#if HC_ARCH_BITS == 32
4928 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
4929 if (pVCpu->hm.s.vmx.pfnStartVM != VMXR0SwitcherStartVM64)
4930 {
4931 if (pVCpu->hm.s.vmx.pfnStartVM != NULL) /* Very first entry would have saved host-state already, ignore it. */
4932 {
4933 /* Currently, all mode changes sends us back to ring-3, so these should be set. See @bugref{6944}. */
4934 AssertMsg(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_VMX_EXIT_CTLS
4935 | HM_CHANGED_VMX_ENTRY_CTLS
4936 | HM_CHANGED_GUEST_EFER_MSR), ("flags=%#x\n", HMCPU_CF_VALUE(pVCpu)));
4937 }
4938 pVCpu->hm.s.vmx.pfnStartVM = VMXR0SwitcherStartVM64;
4939
4940 /* Mark that we've switched to 64-bit handler, we can't safely switch back to 32-bit for
4941 the rest of the VM run (until VM reset). See @bugref{8432#c7}. */
4942 pVCpu->hm.s.vmx.fSwitchedTo64on32 = true;
4943 Log4(("Load[%RU32]: hmR0VmxSetupVMRunHandler: selected 64-bit switcher\n", pVCpu->idCpu));
4944 }
4945#else
4946 /* 64-bit host. */
4947 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM64;
4948#endif
4949 }
4950 else
4951 {
4952 /* Guest is not in long mode, use the 32-bit handler. */
4953#if HC_ARCH_BITS == 32
4954 if ( pVCpu->hm.s.vmx.pfnStartVM != VMXR0StartVM32
4955 && !pVCpu->hm.s.vmx.fSwitchedTo64on32 /* If set, guest mode change does not imply switcher change. */
4956 && pVCpu->hm.s.vmx.pfnStartVM != NULL) /* Very first entry would have saved host-state already, ignore it. */
4957 {
4958 /* Currently, all mode changes sends us back to ring-3, so these should be set. See @bugref{6944}. */
4959 AssertMsg(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_VMX_EXIT_CTLS
4960 | HM_CHANGED_VMX_ENTRY_CTLS
4961 | HM_CHANGED_GUEST_EFER_MSR), ("flags=%#x\n", HMCPU_CF_VALUE(pVCpu)));
4962 }
4963# ifdef VBOX_ENABLE_64_BITS_GUESTS
4964 /*
4965 * Keep using the 64-bit switcher even though we're in 32-bit because of bad Intel design, see @bugref{8432#c7}.
4966 * If real-on-v86 mode is active, clear the 64-bit switcher flag because now we know the guest is in a sane
4967 * state where it's safe to use the 32-bit switcher. Otherwise check the guest state if it's safe to use
4968 * the much faster 32-bit switcher again.
4969 */
4970 if (!pVCpu->hm.s.vmx.fSwitchedTo64on32)
4971 {
4972 if (pVCpu->hm.s.vmx.pfnStartVM != VMXR0StartVM32)
4973 Log4(("Load[%RU32]: hmR0VmxSetupVMRunHandler: selected 32-bit switcher\n", pVCpu->idCpu));
4974 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4975 }
4976 else
4977 {
4978 Assert(pVCpu->hm.s.vmx.pfnStartVM == VMXR0SwitcherStartVM64);
4979 if ( pVCpu->hm.s.vmx.RealMode.fRealOnV86Active
4980 || hmR0VmxIs32BitSwitcherSafe(pMixedCtx))
4981 {
4982 pVCpu->hm.s.vmx.fSwitchedTo64on32 = false;
4983 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4984 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR
4985 | HM_CHANGED_VMX_ENTRY_CTLS
4986 | HM_CHANGED_VMX_EXIT_CTLS
4987 | HM_CHANGED_HOST_CONTEXT);
4988 Log4(("Load[%RU32]: hmR0VmxSetupVMRunHandler: selected 32-bit switcher (safe)\n", pVCpu->idCpu));
4989 }
4990 }
4991# else
4992 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4993# endif
4994#else
4995 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4996#endif
4997 }
4998 Assert(pVCpu->hm.s.vmx.pfnStartVM);
4999 return VINF_SUCCESS;
5000}
5001
5002
5003/**
5004 * Wrapper for running the guest code in VT-x.
5005 *
5006 * @returns VBox status code, no informational status codes.
5007 * @param pVM The cross context VM structure.
5008 * @param pVCpu The cross context virtual CPU structure.
5009 * @param pCtx Pointer to the guest-CPU context.
5010 *
5011 * @remarks No-long-jump zone!!!
5012 */
5013DECLINLINE(int) hmR0VmxRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
5014{
5015 /*
5016 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
5017 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
5018 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
5019 */
5020 bool const fResumeVM = RT_BOOL(pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_LAUNCHED);
5021 /** @todo Add stats for resume vs launch. */
5022#ifdef VBOX_WITH_KERNEL_USING_XMM
5023 int rc = hmR0VMXStartVMWrapXMM(fResumeVM, pCtx, &pVCpu->hm.s.vmx.VMCSCache, pVM, pVCpu, pVCpu->hm.s.vmx.pfnStartVM);
5024#else
5025 int rc = pVCpu->hm.s.vmx.pfnStartVM(fResumeVM, pCtx, &pVCpu->hm.s.vmx.VMCSCache, pVM, pVCpu);
5026#endif
5027 AssertMsg(rc <= VINF_SUCCESS, ("%Rrc\n", rc));
5028 return rc;
5029}
5030
5031
5032/**
5033 * Reports world-switch error and dumps some useful debug info.
5034 *
5035 * @param pVM The cross context VM structure.
5036 * @param pVCpu The cross context virtual CPU structure.
5037 * @param rcVMRun The return code from VMLAUNCH/VMRESUME.
5038 * @param pCtx Pointer to the guest-CPU context.
5039 * @param pVmxTransient Pointer to the VMX transient structure (only
5040 * exitReason updated).
5041 */
5042static void hmR0VmxReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx, PVMXTRANSIENT pVmxTransient)
5043{
5044 Assert(pVM);
5045 Assert(pVCpu);
5046 Assert(pCtx);
5047 Assert(pVmxTransient);
5048 HMVMX_ASSERT_PREEMPT_SAFE();
5049
5050 Log4(("VM-entry failure: %Rrc\n", rcVMRun));
5051 switch (rcVMRun)
5052 {
5053 case VERR_VMX_INVALID_VMXON_PTR:
5054 AssertFailed();
5055 break;
5056 case VINF_SUCCESS: /* VMLAUNCH/VMRESUME succeeded but VM-entry failed... yeah, true story. */
5057 case VERR_VMX_UNABLE_TO_START_VM: /* VMLAUNCH/VMRESUME itself failed. */
5058 {
5059 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &pVCpu->hm.s.vmx.LastError.u32ExitReason);
5060 rc |= VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
5061 rc |= hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
5062 AssertRC(rc);
5063
5064 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
5065 /* LastError.idCurrentCpu was already updated in hmR0VmxPreRunGuestCommitted().
5066 Cannot do it here as we may have been long preempted. */
5067
5068#ifdef VBOX_STRICT
5069 Log4(("uExitReason %#RX32 (VmxTransient %#RX16)\n", pVCpu->hm.s.vmx.LastError.u32ExitReason,
5070 pVmxTransient->uExitReason));
5071 Log4(("Exit Qualification %#RX64\n", pVmxTransient->uExitQualification));
5072 Log4(("InstrError %#RX32\n", pVCpu->hm.s.vmx.LastError.u32InstrError));
5073 if (pVCpu->hm.s.vmx.LastError.u32InstrError <= HMVMX_INSTR_ERROR_MAX)
5074 Log4(("InstrError Desc. \"%s\"\n", g_apszVmxInstrErrors[pVCpu->hm.s.vmx.LastError.u32InstrError]));
5075 else
5076 Log4(("InstrError Desc. Range exceeded %u\n", HMVMX_INSTR_ERROR_MAX));
5077 Log4(("Entered host CPU %u\n", pVCpu->hm.s.vmx.LastError.idEnteredCpu));
5078 Log4(("Current host CPU %u\n", pVCpu->hm.s.vmx.LastError.idCurrentCpu));
5079
5080 /* VMX control bits. */
5081 uint32_t u32Val;
5082 uint64_t u64Val;
5083 RTHCUINTREG uHCReg;
5084 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val); AssertRC(rc);
5085 Log4(("VMX_VMCS32_CTRL_PIN_EXEC %#RX32\n", u32Val));
5086 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val); AssertRC(rc);
5087 Log4(("VMX_VMCS32_CTRL_PROC_EXEC %#RX32\n", u32Val));
5088 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
5089 {
5090 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val); AssertRC(rc);
5091 Log4(("VMX_VMCS32_CTRL_PROC_EXEC2 %#RX32\n", u32Val));
5092 }
5093 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val); AssertRC(rc);
5094 Log4(("VMX_VMCS32_CTRL_ENTRY %#RX32\n", u32Val));
5095 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val); AssertRC(rc);
5096 Log4(("VMX_VMCS32_CTRL_EXIT %#RX32\n", u32Val));
5097 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_CR3_TARGET_COUNT, &u32Val); AssertRC(rc);
5098 Log4(("VMX_VMCS32_CTRL_CR3_TARGET_COUNT %#RX32\n", u32Val));
5099 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32Val); AssertRC(rc);
5100 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", u32Val));
5101 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &u32Val); AssertRC(rc);
5102 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", u32Val));
5103 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &u32Val); AssertRC(rc);
5104 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %u\n", u32Val));
5105 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, &u32Val); AssertRC(rc);
5106 Log4(("VMX_VMCS32_CTRL_TPR_THRESHOLD %u\n", u32Val));
5107 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &u32Val); AssertRC(rc);
5108 Log4(("VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT %u (guest MSRs)\n", u32Val));
5109 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &u32Val); AssertRC(rc);
5110 Log4(("VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT %u (host MSRs)\n", u32Val));
5111 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &u32Val); AssertRC(rc);
5112 Log4(("VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT %u (guest MSRs)\n", u32Val));
5113 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, &u32Val); AssertRC(rc);
5114 Log4(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP %#RX32\n", u32Val));
5115 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, &u32Val); AssertRC(rc);
5116 Log4(("VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK %#RX32\n", u32Val));
5117 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, &u32Val); AssertRC(rc);
5118 Log4(("VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH %#RX32\n", u32Val));
5119 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_MASK, &uHCReg); AssertRC(rc);
5120 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RHr\n", uHCReg));
5121 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_READ_SHADOW, &uHCReg); AssertRC(rc);
5122 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
5123 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_MASK, &uHCReg); AssertRC(rc);
5124 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RHr\n", uHCReg));
5125 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_READ_SHADOW, &uHCReg); AssertRC(rc);
5126 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
5127 if (pVM->hm.s.fNestedPaging)
5128 {
5129 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
5130 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
5131 }
5132
5133 /* Guest bits. */
5134 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RIP, &u64Val); AssertRC(rc);
5135 Log4(("Old Guest Rip %#RX64 New %#RX64\n", pCtx->rip, u64Val));
5136 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RSP, &u64Val); AssertRC(rc);
5137 Log4(("Old Guest Rsp %#RX64 New %#RX64\n", pCtx->rsp, u64Val));
5138 rc = VMXReadVmcs32(VMX_VMCS_GUEST_RFLAGS, &u32Val); AssertRC(rc);
5139 Log4(("Old Guest Rflags %#RX32 New %#RX32\n", pCtx->eflags.u32, u32Val));
5140 if (pVM->hm.s.vmx.fVpid)
5141 {
5142 rc = VMXReadVmcs32(VMX_VMCS16_VPID, &u32Val); AssertRC(rc);
5143 Log4(("VMX_VMCS16_VPID %u\n", u32Val));
5144 }
5145
5146 /* Host bits. */
5147 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_CR0, &uHCReg); AssertRC(rc);
5148 Log4(("Host CR0 %#RHr\n", uHCReg));
5149 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_CR3, &uHCReg); AssertRC(rc);
5150 Log4(("Host CR3 %#RHr\n", uHCReg));
5151 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_CR4, &uHCReg); AssertRC(rc);
5152 Log4(("Host CR4 %#RHr\n", uHCReg));
5153
5154 RTGDTR HostGdtr;
5155 PCX86DESCHC pDesc;
5156 ASMGetGDTR(&HostGdtr);
5157 rc = VMXReadVmcs32(VMX_VMCS16_HOST_CS_SEL, &u32Val); AssertRC(rc);
5158 Log4(("Host CS %#08x\n", u32Val));
5159 if (u32Val < HostGdtr.cbGdt)
5160 {
5161 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5162 hmR0DumpDescriptor(pDesc, u32Val, "CS: ");
5163 }
5164
5165 rc = VMXReadVmcs32(VMX_VMCS16_HOST_DS_SEL, &u32Val); AssertRC(rc);
5166 Log4(("Host DS %#08x\n", u32Val));
5167 if (u32Val < HostGdtr.cbGdt)
5168 {
5169 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5170 hmR0DumpDescriptor(pDesc, u32Val, "DS: ");
5171 }
5172
5173 rc = VMXReadVmcs32(VMX_VMCS16_HOST_ES_SEL, &u32Val); AssertRC(rc);
5174 Log4(("Host ES %#08x\n", u32Val));
5175 if (u32Val < HostGdtr.cbGdt)
5176 {
5177 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5178 hmR0DumpDescriptor(pDesc, u32Val, "ES: ");
5179 }
5180
5181 rc = VMXReadVmcs32(VMX_VMCS16_HOST_FS_SEL, &u32Val); AssertRC(rc);
5182 Log4(("Host FS %#08x\n", u32Val));
5183 if (u32Val < HostGdtr.cbGdt)
5184 {
5185 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5186 hmR0DumpDescriptor(pDesc, u32Val, "FS: ");
5187 }
5188
5189 rc = VMXReadVmcs32(VMX_VMCS16_HOST_GS_SEL, &u32Val); AssertRC(rc);
5190 Log4(("Host GS %#08x\n", u32Val));
5191 if (u32Val < HostGdtr.cbGdt)
5192 {
5193 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5194 hmR0DumpDescriptor(pDesc, u32Val, "GS: ");
5195 }
5196
5197 rc = VMXReadVmcs32(VMX_VMCS16_HOST_SS_SEL, &u32Val); AssertRC(rc);
5198 Log4(("Host SS %#08x\n", u32Val));
5199 if (u32Val < HostGdtr.cbGdt)
5200 {
5201 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5202 hmR0DumpDescriptor(pDesc, u32Val, "SS: ");
5203 }
5204
5205 rc = VMXReadVmcs32(VMX_VMCS16_HOST_TR_SEL, &u32Val); AssertRC(rc);
5206 Log4(("Host TR %#08x\n", u32Val));
5207 if (u32Val < HostGdtr.cbGdt)
5208 {
5209 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5210 hmR0DumpDescriptor(pDesc, u32Val, "TR: ");
5211 }
5212
5213 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_TR_BASE, &uHCReg); AssertRC(rc);
5214 Log4(("Host TR Base %#RHv\n", uHCReg));
5215 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_GDTR_BASE, &uHCReg); AssertRC(rc);
5216 Log4(("Host GDTR Base %#RHv\n", uHCReg));
5217 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_IDTR_BASE, &uHCReg); AssertRC(rc);
5218 Log4(("Host IDTR Base %#RHv\n", uHCReg));
5219 rc = VMXReadVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, &u32Val); AssertRC(rc);
5220 Log4(("Host SYSENTER CS %#08x\n", u32Val));
5221 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_SYSENTER_EIP, &uHCReg); AssertRC(rc);
5222 Log4(("Host SYSENTER EIP %#RHv\n", uHCReg));
5223 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_SYSENTER_ESP, &uHCReg); AssertRC(rc);
5224 Log4(("Host SYSENTER ESP %#RHv\n", uHCReg));
5225 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_RSP, &uHCReg); AssertRC(rc);
5226 Log4(("Host RSP %#RHv\n", uHCReg));
5227 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_RIP, &uHCReg); AssertRC(rc);
5228 Log4(("Host RIP %#RHv\n", uHCReg));
5229# if HC_ARCH_BITS == 64
5230 Log4(("MSR_K6_EFER = %#RX64\n", ASMRdMsr(MSR_K6_EFER)));
5231 Log4(("MSR_K8_CSTAR = %#RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
5232 Log4(("MSR_K8_LSTAR = %#RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
5233 Log4(("MSR_K6_STAR = %#RX64\n", ASMRdMsr(MSR_K6_STAR)));
5234 Log4(("MSR_K8_SF_MASK = %#RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
5235 Log4(("MSR_K8_KERNEL_GS_BASE = %#RX64\n", ASMRdMsr(MSR_K8_KERNEL_GS_BASE)));
5236# endif
5237#endif /* VBOX_STRICT */
5238 break;
5239 }
5240
5241 default:
5242 /* Impossible */
5243 AssertMsgFailed(("hmR0VmxReportWorldSwitchError %Rrc (%#x)\n", rcVMRun, rcVMRun));
5244 break;
5245 }
5246 NOREF(pVM); NOREF(pCtx);
5247}
5248
5249
5250#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
5251#ifndef VMX_USE_CACHED_VMCS_ACCESSES
5252# error "VMX_USE_CACHED_VMCS_ACCESSES not defined when it should be!"
5253#endif
5254#ifdef VBOX_STRICT
5255static bool hmR0VmxIsValidWriteField(uint32_t idxField)
5256{
5257 switch (idxField)
5258 {
5259 case VMX_VMCS_GUEST_RIP:
5260 case VMX_VMCS_GUEST_RSP:
5261 case VMX_VMCS_GUEST_SYSENTER_EIP:
5262 case VMX_VMCS_GUEST_SYSENTER_ESP:
5263 case VMX_VMCS_GUEST_GDTR_BASE:
5264 case VMX_VMCS_GUEST_IDTR_BASE:
5265 case VMX_VMCS_GUEST_CS_BASE:
5266 case VMX_VMCS_GUEST_DS_BASE:
5267 case VMX_VMCS_GUEST_ES_BASE:
5268 case VMX_VMCS_GUEST_FS_BASE:
5269 case VMX_VMCS_GUEST_GS_BASE:
5270 case VMX_VMCS_GUEST_SS_BASE:
5271 case VMX_VMCS_GUEST_LDTR_BASE:
5272 case VMX_VMCS_GUEST_TR_BASE:
5273 case VMX_VMCS_GUEST_CR3:
5274 return true;
5275 }
5276 return false;
5277}
5278
5279static bool hmR0VmxIsValidReadField(uint32_t idxField)
5280{
5281 switch (idxField)
5282 {
5283 /* Read-only fields. */
5284 case VMX_VMCS_RO_EXIT_QUALIFICATION:
5285 return true;
5286 }
5287 /* Remaining readable fields should also be writable. */
5288 return hmR0VmxIsValidWriteField(idxField);
5289}
5290#endif /* VBOX_STRICT */
5291
5292
5293/**
5294 * Executes the specified handler in 64-bit mode.
5295 *
5296 * @returns VBox status code (no informational status codes).
5297 * @param pVM The cross context VM structure.
5298 * @param pVCpu The cross context virtual CPU structure.
5299 * @param pCtx Pointer to the guest CPU context.
5300 * @param enmOp The operation to perform.
5301 * @param cParams Number of parameters.
5302 * @param paParam Array of 32-bit parameters.
5303 */
5304VMMR0DECL(int) VMXR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp,
5305 uint32_t cParams, uint32_t *paParam)
5306{
5307 NOREF(pCtx);
5308
5309 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
5310 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
5311 Assert(pVCpu->hm.s.vmx.VMCSCache.Write.cValidEntries <= RT_ELEMENTS(pVCpu->hm.s.vmx.VMCSCache.Write.aField));
5312 Assert(pVCpu->hm.s.vmx.VMCSCache.Read.cValidEntries <= RT_ELEMENTS(pVCpu->hm.s.vmx.VMCSCache.Read.aField));
5313
5314#ifdef VBOX_STRICT
5315 for (uint32_t i = 0; i < pVCpu->hm.s.vmx.VMCSCache.Write.cValidEntries; i++)
5316 Assert(hmR0VmxIsValidWriteField(pVCpu->hm.s.vmx.VMCSCache.Write.aField[i]));
5317
5318 for (uint32_t i = 0; i <pVCpu->hm.s.vmx.VMCSCache.Read.cValidEntries; i++)
5319 Assert(hmR0VmxIsValidReadField(pVCpu->hm.s.vmx.VMCSCache.Read.aField[i]));
5320#endif
5321
5322 /* Disable interrupts. */
5323 RTCCUINTREG fOldEFlags = ASMIntDisableFlags();
5324
5325#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
5326 RTCPUID idHostCpu = RTMpCpuId();
5327 CPUMR0SetLApic(pVCpu, idHostCpu);
5328#endif
5329
5330 PHMGLOBALCPUINFO pCpu = hmR0GetCurrentCpu();
5331 RTHCPHYS HCPhysCpuPage = pCpu->HCPhysMemObj;
5332
5333 /* Clear VMCS. Marking it inactive, clearing implementation-specific data and writing VMCS data back to memory. */
5334 VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
5335 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
5336
5337 /* Leave VMX Root Mode. */
5338 VMXDisable();
5339
5340 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
5341
5342 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
5343 CPUMSetHyperEIP(pVCpu, enmOp);
5344 for (int i = (int)cParams - 1; i >= 0; i--)
5345 CPUMPushHyper(pVCpu, paParam[i]);
5346
5347 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
5348
5349 /* Call the switcher. */
5350 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
5351 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
5352
5353 /** @todo replace with hmR0VmxEnterRootMode() and hmR0VmxLeaveRootMode(). */
5354 /* Make sure the VMX instructions don't cause #UD faults. */
5355 SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
5356
5357 /* Re-enter VMX Root Mode */
5358 int rc2 = VMXEnable(HCPhysCpuPage);
5359 if (RT_FAILURE(rc2))
5360 {
5361 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
5362 ASMSetFlags(fOldEFlags);
5363 pVM->hm.s.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
5364 return rc2;
5365 }
5366
5367 rc2 = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
5368 AssertRC(rc2);
5369 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_ACTIVE;
5370 Assert(!(ASMGetFlags() & X86_EFL_IF));
5371 ASMSetFlags(fOldEFlags);
5372 return rc;
5373}
5374
5375
5376/**
5377 * Prepares for and executes VMLAUNCH (64-bit guests) for 32-bit hosts
5378 * supporting 64-bit guests.
5379 *
5380 * @returns VBox status code.
5381 * @param fResume Whether to VMLAUNCH or VMRESUME.
5382 * @param pCtx Pointer to the guest-CPU context.
5383 * @param pCache Pointer to the VMCS cache.
5384 * @param pVM The cross context VM structure.
5385 * @param pVCpu The cross context virtual CPU structure.
5386 */
5387DECLASM(int) VMXR0SwitcherStartVM64(RTHCUINT fResume, PCPUMCTX pCtx, PVMCSCACHE pCache, PVM pVM, PVMCPU pVCpu)
5388{
5389 NOREF(fResume);
5390
5391 PHMGLOBALCPUINFO pCpu = hmR0GetCurrentCpu();
5392 RTHCPHYS HCPhysCpuPage = pCpu->HCPhysMemObj;
5393
5394#ifdef VBOX_WITH_CRASHDUMP_MAGIC
5395 pCache->uPos = 1;
5396 pCache->interPD = PGMGetInterPaeCR3(pVM);
5397 pCache->pSwitcher = (uint64_t)pVM->hm.s.pfnHost32ToGuest64R0;
5398#endif
5399
5400#if defined(DEBUG) && defined(VMX_USE_CACHED_VMCS_ACCESSES)
5401 pCache->TestIn.HCPhysCpuPage = 0;
5402 pCache->TestIn.HCPhysVmcs = 0;
5403 pCache->TestIn.pCache = 0;
5404 pCache->TestOut.HCPhysVmcs = 0;
5405 pCache->TestOut.pCache = 0;
5406 pCache->TestOut.pCtx = 0;
5407 pCache->TestOut.eflags = 0;
5408#else
5409 NOREF(pCache);
5410#endif
5411
5412 uint32_t aParam[10];
5413 aParam[0] = RT_LO_U32(HCPhysCpuPage); /* Param 1: VMXON physical address - Lo. */
5414 aParam[1] = RT_HI_U32(HCPhysCpuPage); /* Param 1: VMXON physical address - Hi. */
5415 aParam[2] = RT_LO_U32(pVCpu->hm.s.vmx.HCPhysVmcs); /* Param 2: VMCS physical address - Lo. */
5416 aParam[3] = RT_HI_U32(pVCpu->hm.s.vmx.HCPhysVmcs); /* Param 2: VMCS physical address - Hi. */
5417 aParam[4] = VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hm.s.vmx.VMCSCache);
5418 aParam[5] = 0;
5419 aParam[6] = VM_RC_ADDR(pVM, pVM);
5420 aParam[7] = 0;
5421 aParam[8] = VM_RC_ADDR(pVM, pVCpu);
5422 aParam[9] = 0;
5423
5424#ifdef VBOX_WITH_CRASHDUMP_MAGIC
5425 pCtx->dr[4] = pVM->hm.s.vmx.pScratchPhys + 16 + 8;
5426 *(uint32_t *)(pVM->hm.s.vmx.pScratch + 16 + 8) = 1;
5427#endif
5428 int rc = VMXR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_VMXRCStartVM64, RT_ELEMENTS(aParam), &aParam[0]);
5429
5430#ifdef VBOX_WITH_CRASHDUMP_MAGIC
5431 Assert(*(uint32_t *)(pVM->hm.s.vmx.pScratch + 16 + 8) == 5);
5432 Assert(pCtx->dr[4] == 10);
5433 *(uint32_t *)(pVM->hm.s.vmx.pScratch + 16 + 8) = 0xff;
5434#endif
5435
5436#if defined(DEBUG) && defined(VMX_USE_CACHED_VMCS_ACCESSES)
5437 AssertMsg(pCache->TestIn.HCPhysCpuPage == HCPhysCpuPage, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysCpuPage, HCPhysCpuPage));
5438 AssertMsg(pCache->TestIn.HCPhysVmcs == pVCpu->hm.s.vmx.HCPhysVmcs, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysVmcs,
5439 pVCpu->hm.s.vmx.HCPhysVmcs));
5440 AssertMsg(pCache->TestIn.HCPhysVmcs == pCache->TestOut.HCPhysVmcs, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysVmcs,
5441 pCache->TestOut.HCPhysVmcs));
5442 AssertMsg(pCache->TestIn.pCache == pCache->TestOut.pCache, ("%RGv vs %RGv\n", pCache->TestIn.pCache,
5443 pCache->TestOut.pCache));
5444 AssertMsg(pCache->TestIn.pCache == VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hm.s.vmx.VMCSCache),
5445 ("%RGv vs %RGv\n", pCache->TestIn.pCache, VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hm.s.vmx.VMCSCache)));
5446 AssertMsg(pCache->TestIn.pCtx == pCache->TestOut.pCtx, ("%RGv vs %RGv\n", pCache->TestIn.pCtx,
5447 pCache->TestOut.pCtx));
5448 Assert(!(pCache->TestOut.eflags & X86_EFL_IF));
5449#endif
5450 return rc;
5451}
5452
5453
5454/**
5455 * Initialize the VMCS-Read cache.
5456 *
5457 * The VMCS cache is used for 32-bit hosts running 64-bit guests (except 32-bit
5458 * Darwin which runs with 64-bit paging in 32-bit mode) for 64-bit fields that
5459 * cannot be accessed in 32-bit mode. Some 64-bit fields -can- be accessed
5460 * (those that have a 32-bit FULL & HIGH part).
5461 *
5462 * @returns VBox status code.
5463 * @param pVM The cross context VM structure.
5464 * @param pVCpu The cross context virtual CPU structure.
5465 */
5466static int hmR0VmxInitVmcsReadCache(PVM pVM, PVMCPU pVCpu)
5467{
5468#define VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, idxField) \
5469{ \
5470 Assert(pCache->Read.aField[idxField##_CACHE_IDX] == 0); \
5471 pCache->Read.aField[idxField##_CACHE_IDX] = idxField; \
5472 pCache->Read.aFieldVal[idxField##_CACHE_IDX] = 0; \
5473 ++cReadFields; \
5474}
5475
5476 AssertPtr(pVM);
5477 AssertPtr(pVCpu);
5478 PVMCSCACHE pCache = &pVCpu->hm.s.vmx.VMCSCache;
5479 uint32_t cReadFields = 0;
5480
5481 /*
5482 * Don't remove the #if 0'd fields in this code. They're listed here for consistency
5483 * and serve to indicate exceptions to the rules.
5484 */
5485
5486 /* Guest-natural selector base fields. */
5487#if 0
5488 /* These are 32-bit in practice. See Intel spec. 2.5 "Control Registers". */
5489 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR0);
5490 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR4);
5491#endif
5492 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_ES_BASE);
5493 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CS_BASE);
5494 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_SS_BASE);
5495 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_DS_BASE);
5496 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_FS_BASE);
5497 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_GS_BASE);
5498 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_LDTR_BASE);
5499 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_TR_BASE);
5500 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_GDTR_BASE);
5501 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_IDTR_BASE);
5502 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_RSP);
5503 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_RIP);
5504#if 0
5505 /* Unused natural width guest-state fields. */
5506 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS);
5507 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR3); /* Handled in Nested Paging case */
5508#endif
5509 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_SYSENTER_ESP);
5510 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_SYSENTER_EIP);
5511
5512 /* 64-bit guest-state fields; unused as we use two 32-bit VMREADs for these 64-bit fields (using "FULL" and "HIGH" fields). */
5513#if 0
5514 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL);
5515 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_DEBUGCTL_FULL);
5516 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PAT_FULL);
5517 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_EFER_FULL);
5518 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL);
5519 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE0_FULL);
5520 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE1_FULL);
5521 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE2_FULL);
5522 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE3_FULL);
5523#endif
5524
5525 /* Natural width guest-state fields. */
5526 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_RO_EXIT_QUALIFICATION);
5527#if 0
5528 /* Currently unused field. */
5529 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_RO_EXIT_GUEST_LINEAR_ADDR);
5530#endif
5531
5532 if (pVM->hm.s.fNestedPaging)
5533 {
5534 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR3);
5535 AssertMsg(cReadFields == VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX, ("cReadFields=%u expected %u\n", cReadFields,
5536 VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX));
5537 pCache->Read.cValidEntries = VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX;
5538 }
5539 else
5540 {
5541 AssertMsg(cReadFields == VMX_VMCS_MAX_CACHE_IDX, ("cReadFields=%u expected %u\n", cReadFields, VMX_VMCS_MAX_CACHE_IDX));
5542 pCache->Read.cValidEntries = VMX_VMCS_MAX_CACHE_IDX;
5543 }
5544
5545#undef VMXLOCAL_INIT_READ_CACHE_FIELD
5546 return VINF_SUCCESS;
5547}
5548
5549
5550/**
5551 * Writes a field into the VMCS. This can either directly invoke a VMWRITE or
5552 * queue up the VMWRITE by using the VMCS write cache (on 32-bit hosts, except
5553 * darwin, running 64-bit guests).
5554 *
5555 * @returns VBox status code.
5556 * @param pVCpu The cross context virtual CPU structure.
5557 * @param idxField The VMCS field encoding.
5558 * @param u64Val 16, 32 or 64-bit value.
5559 */
5560VMMR0DECL(int) VMXWriteVmcs64Ex(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
5561{
5562 int rc;
5563 switch (idxField)
5564 {
5565 /*
5566 * These fields consists of a "FULL" and a "HIGH" part which can be written to individually.
5567 */
5568 /* 64-bit Control fields. */
5569 case VMX_VMCS64_CTRL_IO_BITMAP_A_FULL:
5570 case VMX_VMCS64_CTRL_IO_BITMAP_B_FULL:
5571 case VMX_VMCS64_CTRL_MSR_BITMAP_FULL:
5572 case VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL:
5573 case VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL:
5574 case VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL:
5575 case VMX_VMCS64_CTRL_EXEC_VMCS_PTR_FULL:
5576 case VMX_VMCS64_CTRL_TSC_OFFSET_FULL:
5577 case VMX_VMCS64_CTRL_VAPIC_PAGEADDR_FULL:
5578 case VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL:
5579 case VMX_VMCS64_CTRL_VMFUNC_CTRLS_FULL:
5580 case VMX_VMCS64_CTRL_EPTP_FULL:
5581 case VMX_VMCS64_CTRL_EPTP_LIST_FULL:
5582 /* 64-bit Guest-state fields. */
5583 case VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL:
5584 case VMX_VMCS64_GUEST_DEBUGCTL_FULL:
5585 case VMX_VMCS64_GUEST_PAT_FULL:
5586 case VMX_VMCS64_GUEST_EFER_FULL:
5587 case VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL:
5588 case VMX_VMCS64_GUEST_PDPTE0_FULL:
5589 case VMX_VMCS64_GUEST_PDPTE1_FULL:
5590 case VMX_VMCS64_GUEST_PDPTE2_FULL:
5591 case VMX_VMCS64_GUEST_PDPTE3_FULL:
5592 /* 64-bit Host-state fields. */
5593 case VMX_VMCS64_HOST_PAT_FULL:
5594 case VMX_VMCS64_HOST_EFER_FULL:
5595 case VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_FULL:
5596 {
5597 rc = VMXWriteVmcs32(idxField, RT_LO_U32(u64Val));
5598 rc |= VMXWriteVmcs32(idxField + 1, RT_HI_U32(u64Val));
5599 break;
5600 }
5601
5602 /*
5603 * These fields do not have high and low parts. Queue up the VMWRITE by using the VMCS write-cache (for 64-bit
5604 * values). When we switch the host to 64-bit mode for running 64-bit guests, these VMWRITEs get executed then.
5605 */
5606 /* Natural-width Guest-state fields. */
5607 case VMX_VMCS_GUEST_CR3:
5608 case VMX_VMCS_GUEST_ES_BASE:
5609 case VMX_VMCS_GUEST_CS_BASE:
5610 case VMX_VMCS_GUEST_SS_BASE:
5611 case VMX_VMCS_GUEST_DS_BASE:
5612 case VMX_VMCS_GUEST_FS_BASE:
5613 case VMX_VMCS_GUEST_GS_BASE:
5614 case VMX_VMCS_GUEST_LDTR_BASE:
5615 case VMX_VMCS_GUEST_TR_BASE:
5616 case VMX_VMCS_GUEST_GDTR_BASE:
5617 case VMX_VMCS_GUEST_IDTR_BASE:
5618 case VMX_VMCS_GUEST_RSP:
5619 case VMX_VMCS_GUEST_RIP:
5620 case VMX_VMCS_GUEST_SYSENTER_ESP:
5621 case VMX_VMCS_GUEST_SYSENTER_EIP:
5622 {
5623 if (!(RT_HI_U32(u64Val)))
5624 {
5625 /* If this field is 64-bit, VT-x will zero out the top bits. */
5626 rc = VMXWriteVmcs32(idxField, RT_LO_U32(u64Val));
5627 }
5628 else
5629 {
5630 /* Assert that only the 32->64 switcher case should ever come here. */
5631 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests);
5632 rc = VMXWriteCachedVmcsEx(pVCpu, idxField, u64Val);
5633 }
5634 break;
5635 }
5636
5637 default:
5638 {
5639 AssertMsgFailed(("VMXWriteVmcs64Ex: Invalid field %#RX32 (pVCpu=%p u64Val=%#RX64)\n", idxField, pVCpu, u64Val));
5640 rc = VERR_INVALID_PARAMETER;
5641 break;
5642 }
5643 }
5644 AssertRCReturn(rc, rc);
5645 return rc;
5646}
5647
5648
5649/**
5650 * Queue up a VMWRITE by using the VMCS write cache.
5651 * This is only used on 32-bit hosts (except darwin) for 64-bit guests.
5652 *
5653 * @param pVCpu The cross context virtual CPU structure.
5654 * @param idxField The VMCS field encoding.
5655 * @param u64Val 16, 32 or 64-bit value.
5656 */
5657VMMR0DECL(int) VMXWriteCachedVmcsEx(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
5658{
5659 AssertPtr(pVCpu);
5660 PVMCSCACHE pCache = &pVCpu->hm.s.vmx.VMCSCache;
5661
5662 AssertMsgReturn(pCache->Write.cValidEntries < VMCSCACHE_MAX_ENTRY - 1,
5663 ("entries=%u\n", pCache->Write.cValidEntries), VERR_ACCESS_DENIED);
5664
5665 /* Make sure there are no duplicates. */
5666 for (uint32_t i = 0; i < pCache->Write.cValidEntries; i++)
5667 {
5668 if (pCache->Write.aField[i] == idxField)
5669 {
5670 pCache->Write.aFieldVal[i] = u64Val;
5671 return VINF_SUCCESS;
5672 }
5673 }
5674
5675 pCache->Write.aField[pCache->Write.cValidEntries] = idxField;
5676 pCache->Write.aFieldVal[pCache->Write.cValidEntries] = u64Val;
5677 pCache->Write.cValidEntries++;
5678 return VINF_SUCCESS;
5679}
5680#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
5681
5682
5683/**
5684 * Sets up the usage of TSC-offsetting and updates the VMCS.
5685 *
5686 * If offsetting is not possible, cause VM-exits on RDTSC(P)s. Also sets up the
5687 * VMX preemption timer.
5688 *
5689 * @returns VBox status code.
5690 * @param pVM The cross context VM structure.
5691 * @param pVCpu The cross context virtual CPU structure.
5692 *
5693 * @remarks No-long-jump zone!!!
5694 */
5695static void hmR0VmxUpdateTscOffsettingAndPreemptTimer(PVM pVM, PVMCPU pVCpu)
5696{
5697 int rc;
5698 bool fOffsettedTsc;
5699 bool fParavirtTsc;
5700 if (pVM->hm.s.vmx.fUsePreemptTimer)
5701 {
5702 uint64_t cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVM, pVCpu, &pVCpu->hm.s.vmx.u64TSCOffset,
5703 &fOffsettedTsc, &fParavirtTsc);
5704
5705 /* Make sure the returned values have sane upper and lower boundaries. */
5706 uint64_t u64CpuHz = SUPGetCpuHzFromGipBySetIndex(g_pSUPGlobalInfoPage, pVCpu->iHostCpuSet);
5707 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64th of a second */
5708 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 2048); /* 1/2048th of a second */
5709 cTicksToDeadline >>= pVM->hm.s.vmx.cPreemptTimerShift;
5710
5711 uint32_t cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
5712 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_PREEMPT_TIMER_VALUE, cPreemptionTickCount); AssertRC(rc);
5713 }
5714 else
5715 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &pVCpu->hm.s.vmx.u64TSCOffset, &fParavirtTsc);
5716
5717 /** @todo later optimize this to be done elsewhere and not before every
5718 * VM-entry. */
5719 if (fParavirtTsc)
5720 {
5721 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
5722 information before every VM-entry, hence disable it for performance sake. */
5723#if 0
5724 rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
5725 AssertRC(rc);
5726#endif
5727 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
5728 }
5729
5730 if (fOffsettedTsc && RT_LIKELY(!pVCpu->hm.s.fDebugWantRdTscExit))
5731 {
5732 /* Note: VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT takes precedence over TSC_OFFSET, applies to RDTSCP too. */
5733 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, pVCpu->hm.s.vmx.u64TSCOffset); AssertRC(rc);
5734
5735 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT;
5736 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls); AssertRC(rc);
5737 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
5738 }
5739 else
5740 {
5741 /* We can't use TSC-offsetting (non-fixed TSC, warp drive active etc.), VM-exit on RDTSC(P). */
5742 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT;
5743 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls); AssertRC(rc);
5744 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
5745 }
5746}
5747
5748
5749#ifdef HMVMX_USE_IEM_EVENT_REFLECTION
5750/**
5751 * Gets the IEM exception flags for the specified vector and IDT vectoring /
5752 * VM-exit interruption info type.
5753 *
5754 * @returns The IEM exception flags.
5755 * @param uVector The event vector.
5756 * @param uVmxVectorType The VMX event type.
5757 *
5758 * @remarks This function currently only constructs flags required for
5759 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g, error-code
5760 * and CR2 aspects of an exception are not included).
5761 */
5762static uint32_t hmR0VmxGetIemXcptFlags(uint8_t uVector, uint32_t uVmxVectorType)
5763{
5764 uint32_t fIemXcptFlags;
5765 switch (uVmxVectorType)
5766 {
5767 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
5768 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
5769 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
5770 break;
5771
5772 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
5773 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
5774 break;
5775
5776 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
5777 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_ICEBP_INSTR;
5778 break;
5779
5780 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT:
5781 {
5782 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
5783 if (uVector == X86_XCPT_BP)
5784 fIemXcptFlags |= IEM_XCPT_FLAGS_BP_INSTR;
5785 else if (uVector == X86_XCPT_OF)
5786 fIemXcptFlags |= IEM_XCPT_FLAGS_OF_INSTR;
5787 else
5788 {
5789 fIemXcptFlags = 0;
5790 AssertMsgFailed(("Unexpected vector for software int. uVector=%#x", uVector));
5791 }
5792 break;
5793 }
5794
5795 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
5796 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
5797 break;
5798
5799 default:
5800 fIemXcptFlags = 0;
5801 AssertMsgFailed(("Unexpected vector type! uVmxVectorType=%#x uVector=%#x", uVmxVectorType, uVector));
5802 break;
5803 }
5804 return fIemXcptFlags;
5805}
5806
5807#else
5808/**
5809 * Determines if an exception is a contributory exception.
5810 *
5811 * Contributory exceptions are ones which can cause double-faults unless the
5812 * original exception was a benign exception. Page-fault is intentionally not
5813 * included here as it's a conditional contributory exception.
5814 *
5815 * @returns true if the exception is contributory, false otherwise.
5816 * @param uVector The exception vector.
5817 */
5818DECLINLINE(bool) hmR0VmxIsContributoryXcpt(const uint32_t uVector)
5819{
5820 switch (uVector)
5821 {
5822 case X86_XCPT_GP:
5823 case X86_XCPT_SS:
5824 case X86_XCPT_NP:
5825 case X86_XCPT_TS:
5826 case X86_XCPT_DE:
5827 return true;
5828 default:
5829 break;
5830 }
5831 return false;
5832}
5833#endif /* HMVMX_USE_IEM_EVENT_REFLECTION */
5834
5835
5836/**
5837 * Sets an event as a pending event to be injected into the guest.
5838 *
5839 * @param pVCpu The cross context virtual CPU structure.
5840 * @param u32IntInfo The VM-entry interruption-information field.
5841 * @param cbInstr The VM-entry instruction length in bytes (for software
5842 * interrupts, exceptions and privileged software
5843 * exceptions).
5844 * @param u32ErrCode The VM-entry exception error code.
5845 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
5846 * page-fault.
5847 *
5848 * @remarks Statistics counter assumes this is a guest event being injected or
5849 * re-injected into the guest, i.e. 'StatInjectPendingReflect' is
5850 * always incremented.
5851 */
5852DECLINLINE(void) hmR0VmxSetPendingEvent(PVMCPU pVCpu, uint32_t u32IntInfo, uint32_t cbInstr, uint32_t u32ErrCode,
5853 RTGCUINTPTR GCPtrFaultAddress)
5854{
5855 Assert(!pVCpu->hm.s.Event.fPending);
5856 pVCpu->hm.s.Event.fPending = true;
5857 pVCpu->hm.s.Event.u64IntInfo = u32IntInfo;
5858 pVCpu->hm.s.Event.u32ErrCode = u32ErrCode;
5859 pVCpu->hm.s.Event.cbInstr = cbInstr;
5860 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
5861}
5862
5863
5864/**
5865 * Sets a double-fault (\#DF) exception as pending-for-injection into the VM.
5866 *
5867 * @param pVCpu The cross context virtual CPU structure.
5868 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
5869 * out-of-sync. Make sure to update the required fields
5870 * before using them.
5871 */
5872DECLINLINE(void) hmR0VmxSetPendingXcptDF(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
5873{
5874 NOREF(pMixedCtx);
5875 uint32_t u32IntInfo = X86_XCPT_DF | VMX_EXIT_INTERRUPTION_INFO_VALID;
5876 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
5877 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
5878 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
5879}
5880
5881
5882/**
5883 * Handle a condition that occurred while delivering an event through the guest
5884 * IDT.
5885 *
5886 * @returns Strict VBox status code (i.e. informational status codes too).
5887 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
5888 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
5889 * to continue execution of the guest which will delivery the \#DF.
5890 * @retval VINF_EM_RESET if we detected a triple-fault condition.
5891 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
5892 *
5893 * @param pVCpu The cross context virtual CPU structure.
5894 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
5895 * out-of-sync. Make sure to update the required fields
5896 * before using them.
5897 * @param pVmxTransient Pointer to the VMX transient structure.
5898 *
5899 * @remarks No-long-jump zone!!!
5900 */
5901static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
5902{
5903 uint32_t const uExitVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo);
5904
5905 int rc2 = hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient); AssertRCReturn(rc2, rc2);
5906 rc2 = hmR0VmxReadExitIntInfoVmcs(pVmxTransient); AssertRCReturn(rc2, rc2);
5907
5908 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
5909 if (VMX_IDT_VECTORING_INFO_VALID(pVmxTransient->uIdtVectoringInfo))
5910 {
5911 uint32_t const uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo);
5912 uint32_t const uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo);
5913#ifdef HMVMX_USE_IEM_EVENT_REFLECTION
5914 /*
5915 * If the event was a software interrupt (generated with INT n) or a software exception (generated
5916 * by INT3/INTO) or a privileged software exception (generated by INT1), we can handle the VM-exit
5917 * and continue guest execution which will re-execute the instruction rather than re-injecting the
5918 * exception, as that can cause premature trips to ring-3 before injection and involve TRPM which
5919 * currently has no way of storing that these exceptions were caused by these instructions
5920 * (ICEBP's #DB poses the problem).
5921 */
5922 IEMXCPTRAISE enmRaise;
5923 IEMXCPTRAISEINFO fRaiseInfo;
5924 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
5925 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
5926 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
5927 {
5928 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
5929 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
5930 }
5931 else if (VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo))
5932 {
5933 uint32_t const uExitVectorType = VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uExitIntInfo);
5934 uint32_t const fIdtVectorFlags = hmR0VmxGetIemXcptFlags(uIdtVector, uIdtVectorType);
5935 uint32_t const fExitVectorFlags = hmR0VmxGetIemXcptFlags(uExitVector, uExitVectorType);
5936 /** @todo Make AssertMsgReturn as just AssertMsg later. */
5937 AssertMsgReturn(uExitVectorType == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT,
5938 ("hmR0VmxCheckExitDueToEventDelivery: Unexpected VM-exit interruption info. %#x!\n",
5939 uExitVectorType), VERR_VMX_IPE_5);
5940 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
5941
5942 /* Determine a vectoring #PF condition, see comment in hmR0VmxExitXcptPF(). */
5943 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
5944 {
5945 pVmxTransient->fVectoringPF = true;
5946 enmRaise = IEMXCPTRAISE_PREV_EVENT;
5947 }
5948 }
5949 else
5950 {
5951 /*
5952 * If an exception or hardware interrupt delivery caused an EPT violation/misconfig or APIC access
5953 * VM-exit, then the VM-exit interruption-information will not be valid and we end up here.
5954 * It is sufficient to reflect the original event to the guest after handling the VM-exit.
5955 */
5956 Assert( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
5957 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
5958 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT);
5959 enmRaise = IEMXCPTRAISE_PREV_EVENT;
5960 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
5961 }
5962
5963 /*
5964 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig
5965 * etc.) occurred while delivering the NMI, we need to clear the block-by-NMI field in the guest
5966 * interruptibility-state before re-delivering the NMI after handling the VM-exit. Otherwise the
5967 * subsequent VM-entry would fail.
5968 *
5969 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception". See @bugref{7445}.
5970 */
5971 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS)
5972 && uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
5973 && ( enmRaise == IEMXCPTRAISE_PREV_EVENT
5974 || (fRaiseInfo & IEMXCPTRAISEINFO_NMI_PF))
5975 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI))
5976 {
5977 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5978 }
5979
5980 switch (enmRaise)
5981 {
5982 case IEMXCPTRAISE_CURRENT_XCPT:
5983 {
5984 Log4(("IDT: vcpu[%RU32] Pending secondary xcpt: uIdtVectoringInfo=%#RX64 uExitIntInfo=%#RX64\n", pVCpu->idCpu,
5985 pVmxTransient->uIdtVectoringInfo, pVmxTransient->uExitIntInfo));
5986 Assert(rcStrict == VINF_SUCCESS);
5987 break;
5988 }
5989
5990 case IEMXCPTRAISE_PREV_EVENT:
5991 {
5992 uint32_t u32ErrCode;
5993 if (VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uIdtVectoringInfo))
5994 {
5995 rc2 = hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
5996 AssertRCReturn(rc2, rc2);
5997 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
5998 }
5999 else
6000 u32ErrCode = 0;
6001
6002 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF, see hmR0VmxExitXcptPF(). */
6003 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6004 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
6005 0 /* cbInstr */, u32ErrCode, pMixedCtx->cr2);
6006
6007 Log4(("IDT: vcpu[%RU32] Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
6008 pVCpu->hm.s.Event.u32ErrCode));
6009 Assert(rcStrict == VINF_SUCCESS);
6010 break;
6011 }
6012
6013 case IEMXCPTRAISE_REEXEC_INSTR:
6014 Assert(rcStrict == VINF_SUCCESS);
6015 break;
6016
6017 case IEMXCPTRAISE_DOUBLE_FAULT:
6018 {
6019 /*
6020 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
6021 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
6022 */
6023 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
6024 {
6025 pVmxTransient->fVectoringDoublePF = true;
6026 Log4(("IDT: vcpu[%RU32] Vectoring double #PF %#RX64 cr2=%#RX64\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
6027 pMixedCtx->cr2));
6028 rcStrict = VINF_SUCCESS;
6029 }
6030 else
6031 {
6032 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6033 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
6034 Log4(("IDT: vcpu[%RU32] Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->idCpu,
6035 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
6036 rcStrict = VINF_HM_DOUBLE_FAULT;
6037 }
6038 break;
6039 }
6040
6041 case IEMXCPTRAISE_TRIPLE_FAULT:
6042 {
6043 Log4(("IDT: vcpu[%RU32] Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", pVCpu->idCpu, uIdtVector,
6044 uExitVector));
6045 rcStrict = VINF_EM_RESET;
6046 break;
6047 }
6048
6049 case IEMXCPTRAISE_CPU_HANG:
6050 {
6051 Log4(("IDT: vcpu[%RU32] Bad guest! Entering CPU hang. fRaiseInfo=%#x\n", pVCpu->idCpu, fRaiseInfo));
6052 rcStrict = VERR_EM_GUEST_CPU_HANG;
6053 break;
6054 }
6055
6056 default:
6057 {
6058 AssertMsgFailed(("IDT: vcpu[%RU32] Unexpected/invalid value! enmRaise=%#x\n", pVCpu->idCpu, enmRaise));
6059 rcStrict = VERR_VMX_IPE_2;
6060 break;
6061 }
6062 }
6063#else
6064 typedef enum
6065 {
6066 VMXREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
6067 VMXREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
6068 VMXREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
6069 VMXREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
6070 VMXREFLECTXCPT_NONE /* Nothing to reflect. */
6071 } VMXREFLECTXCPT;
6072
6073 /* See Intel spec. 30.7.1.1 "Reflecting Exceptions to Guest Software". */
6074 VMXREFLECTXCPT enmReflect = VMXREFLECTXCPT_NONE;
6075 if (VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo))
6076 {
6077 if (uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT)
6078 {
6079 enmReflect = VMXREFLECTXCPT_XCPT;
6080#ifdef VBOX_STRICT
6081 if ( hmR0VmxIsContributoryXcpt(uIdtVector)
6082 && uExitVector == X86_XCPT_PF)
6083 {
6084 Log4(("IDT: vcpu[%RU32] Contributory #PF uCR2=%#RX64\n", pVCpu->idCpu, pMixedCtx->cr2));
6085 }
6086#endif
6087 if ( uExitVector == X86_XCPT_PF
6088 && uIdtVector == X86_XCPT_PF)
6089 {
6090 pVmxTransient->fVectoringDoublePF = true;
6091 Log4(("IDT: vcpu[%RU32] Vectoring Double #PF uCR2=%#RX64\n", pVCpu->idCpu, pMixedCtx->cr2));
6092 }
6093 else if ( uExitVector == X86_XCPT_AC
6094 && uIdtVector == X86_XCPT_AC)
6095 {
6096 enmReflect = VMXREFLECTXCPT_HANG;
6097 Log4(("IDT: Nested #AC - Bad guest\n"));
6098 }
6099 else if ( (pVCpu->hm.s.vmx.u32XcptBitmap & HMVMX_CONTRIBUTORY_XCPT_MASK)
6100 && hmR0VmxIsContributoryXcpt(uExitVector)
6101 && ( hmR0VmxIsContributoryXcpt(uIdtVector)
6102 || uIdtVector == X86_XCPT_PF))
6103 {
6104 enmReflect = VMXREFLECTXCPT_DF;
6105 }
6106 else if (uIdtVector == X86_XCPT_DF)
6107 enmReflect = VMXREFLECTXCPT_TF;
6108 }
6109 else if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT
6110 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI)
6111 {
6112 /*
6113 * Ignore software interrupts (INT n), software exceptions (#BP, #OF) and
6114 * privileged software exception (#DB from ICEBP) as they reoccur when restarting the instruction.
6115 */
6116 enmReflect = VMXREFLECTXCPT_XCPT;
6117
6118 if (uExitVector == X86_XCPT_PF)
6119 {
6120 pVmxTransient->fVectoringPF = true;
6121 Log4(("IDT: vcpu[%RU32] Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pVCpu->idCpu, pMixedCtx->cr2));
6122 }
6123 }
6124 }
6125 else if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
6126 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT
6127 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI)
6128 {
6129 /*
6130 * If event delivery caused an EPT violation/misconfig or APIC access VM-exit, then the VM-exit
6131 * interruption-information will not be valid as it's not an exception and we end up here. In such cases,
6132 * it is sufficient to reflect the original exception to the guest after handling the VM-exit.
6133 */
6134 enmReflect = VMXREFLECTXCPT_XCPT;
6135 }
6136
6137 /*
6138 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig etc.) occurred
6139 * while delivering the NMI, we need to clear the block-by-NMI field in the guest interruptibility-state before
6140 * re-delivering the NMI after handling the VM-exit. Otherwise the subsequent VM-entry would fail.
6141 *
6142 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception". See @bugref{7445}.
6143 */
6144 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
6145 && enmReflect == VMXREFLECTXCPT_XCPT
6146 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI)
6147 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6148 {
6149 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6150 }
6151
6152 switch (enmReflect)
6153 {
6154 case VMXREFLECTXCPT_XCPT:
6155 {
6156 Assert( uIdtVectorType != VMX_IDT_VECTORING_INFO_TYPE_SW_INT
6157 && uIdtVectorType != VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
6158 && uIdtVectorType != VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT);
6159
6160 uint32_t u32ErrCode = 0;
6161 if (VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uIdtVectoringInfo))
6162 {
6163 rc2 = hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
6164 AssertRCReturn(rc2, rc2);
6165 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
6166 }
6167
6168 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF. See hmR0VmxExitXcptPF(). */
6169 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6170 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
6171 0 /* cbInstr */, u32ErrCode, pMixedCtx->cr2);
6172 rcStrict = VINF_SUCCESS;
6173 Log4(("IDT: vcpu[%RU32] Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->idCpu,
6174 pVCpu->hm.s.Event.u64IntInfo, pVCpu->hm.s.Event.u32ErrCode));
6175
6176 break;
6177 }
6178
6179 case VMXREFLECTXCPT_DF:
6180 {
6181 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
6182 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
6183 rcStrict = VINF_HM_DOUBLE_FAULT;
6184 Log4(("IDT: vcpu[%RU32] Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->idCpu,
6185 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
6186
6187 break;
6188 }
6189
6190 case VMXREFLECTXCPT_TF:
6191 {
6192 rcStrict = VINF_EM_RESET;
6193 Log4(("IDT: vcpu[%RU32] Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", pVCpu->idCpu, uIdtVector,
6194 uExitVector));
6195 break;
6196 }
6197
6198 case VMXREFLECTXCPT_HANG:
6199 {
6200 rcStrict = VERR_EM_GUEST_CPU_HANG;
6201 break;
6202 }
6203
6204 default:
6205 Assert(rcStrict == VINF_SUCCESS);
6206 break;
6207 }
6208#endif /* HMVMX_USE_IEM_EVENT_REFLECTION */
6209 }
6210 else if ( VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo)
6211 && VMX_EXIT_INTERRUPTION_INFO_NMI_UNBLOCK_IRET(pVmxTransient->uExitIntInfo)
6212 && uExitVector != X86_XCPT_DF
6213 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI))
6214 {
6215 /*
6216 * Execution of IRET caused this fault when NMI blocking was in effect (i.e we're in the guest NMI handler).
6217 * We need to set the block-by-NMI field so that NMIs remain blocked until the IRET execution is restarted.
6218 * See Intel spec. 30.7.1.2 "Resuming guest software after handling an exception".
6219 */
6220 if (!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6221 {
6222 Log4(("hmR0VmxCheckExitDueToEventDelivery: vcpu[%RU32] Setting VMCPU_FF_BLOCK_NMIS. Valid=%RTbool uExitReason=%u\n",
6223 pVCpu->idCpu, VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo), pVmxTransient->uExitReason));
6224 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
6225 }
6226 }
6227
6228 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
6229 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
6230 return rcStrict;
6231}
6232
6233
6234/**
6235 * Saves the guest's CR0 register from the VMCS into the guest-CPU context.
6236 *
6237 * @returns VBox status code.
6238 * @param pVCpu The cross context virtual CPU structure.
6239 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6240 * out-of-sync. Make sure to update the required fields
6241 * before using them.
6242 *
6243 * @remarks No-long-jump zone!!!
6244 */
6245static int hmR0VmxSaveGuestCR0(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6246{
6247 NOREF(pMixedCtx);
6248
6249 /*
6250 * While in the middle of saving guest-CR0, we could get preempted and re-invoked from the preemption hook,
6251 * see hmR0VmxLeave(). Safer to just make this code non-preemptible.
6252 */
6253 VMMRZCallRing3Disable(pVCpu);
6254 HM_DISABLE_PREEMPT();
6255
6256 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0))
6257 {
6258#ifndef DEBUG_bird /** @todo this triggers running bs3-cpu-generated-1.img with --debug-command-line
6259 * and 'dbgc-init' containing:
6260 * sxe "xcpt_de"
6261 * sxe "xcpt_bp"
6262 * sxi "xcpt_gp"
6263 * sxi "xcpt_ss"
6264 * sxi "xcpt_np"
6265 */
6266 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
6267#endif
6268 uint32_t uVal = 0;
6269 uint32_t uShadow = 0;
6270 int rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR0, &uVal);
6271 rc |= VMXReadVmcs32(VMX_VMCS_CTRL_CR0_READ_SHADOW, &uShadow);
6272 AssertRCReturn(rc, rc);
6273
6274 uVal = (uShadow & pVCpu->hm.s.vmx.u32CR0Mask) | (uVal & ~pVCpu->hm.s.vmx.u32CR0Mask);
6275 CPUMSetGuestCR0(pVCpu, uVal);
6276 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0);
6277 }
6278
6279 HM_RESTORE_PREEMPT();
6280 VMMRZCallRing3Enable(pVCpu);
6281 return VINF_SUCCESS;
6282}
6283
6284
6285/**
6286 * Saves the guest's CR4 register from the VMCS into the guest-CPU context.
6287 *
6288 * @returns VBox status code.
6289 * @param pVCpu The cross context virtual CPU structure.
6290 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6291 * out-of-sync. Make sure to update the required fields
6292 * before using them.
6293 *
6294 * @remarks No-long-jump zone!!!
6295 */
6296static int hmR0VmxSaveGuestCR4(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6297{
6298 NOREF(pMixedCtx);
6299
6300 int rc = VINF_SUCCESS;
6301 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR4))
6302 {
6303 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR4));
6304 uint32_t uVal = 0;
6305 uint32_t uShadow = 0;
6306 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR4, &uVal);
6307 rc |= VMXReadVmcs32(VMX_VMCS_CTRL_CR4_READ_SHADOW, &uShadow);
6308 AssertRCReturn(rc, rc);
6309
6310 uVal = (uShadow & pVCpu->hm.s.vmx.u32CR4Mask) | (uVal & ~pVCpu->hm.s.vmx.u32CR4Mask);
6311 CPUMSetGuestCR4(pVCpu, uVal);
6312 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR4);
6313 }
6314 return rc;
6315}
6316
6317
6318/**
6319 * Saves the guest's RIP register from the VMCS into the guest-CPU context.
6320 *
6321 * @returns VBox status code.
6322 * @param pVCpu The cross context virtual CPU structure.
6323 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6324 * out-of-sync. Make sure to update the required fields
6325 * before using them.
6326 *
6327 * @remarks No-long-jump zone!!!
6328 */
6329static int hmR0VmxSaveGuestRip(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6330{
6331 int rc = VINF_SUCCESS;
6332 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RIP))
6333 {
6334 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RIP));
6335 uint64_t u64Val = 0;
6336 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RIP, &u64Val);
6337 AssertRCReturn(rc, rc);
6338
6339 pMixedCtx->rip = u64Val;
6340 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RIP);
6341 }
6342 return rc;
6343}
6344
6345
6346/**
6347 * Saves the guest's RSP register from the VMCS into the guest-CPU context.
6348 *
6349 * @returns VBox status code.
6350 * @param pVCpu The cross context virtual CPU structure.
6351 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6352 * out-of-sync. Make sure to update the required fields
6353 * before using them.
6354 *
6355 * @remarks No-long-jump zone!!!
6356 */
6357static int hmR0VmxSaveGuestRsp(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6358{
6359 int rc = VINF_SUCCESS;
6360 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RSP))
6361 {
6362 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RSP));
6363 uint64_t u64Val = 0;
6364 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RSP, &u64Val);
6365 AssertRCReturn(rc, rc);
6366
6367 pMixedCtx->rsp = u64Val;
6368 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RSP);
6369 }
6370 return rc;
6371}
6372
6373
6374/**
6375 * Saves the guest's RFLAGS from the VMCS into the guest-CPU context.
6376 *
6377 * @returns VBox status code.
6378 * @param pVCpu The cross context virtual CPU structure.
6379 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6380 * out-of-sync. Make sure to update the required fields
6381 * before using them.
6382 *
6383 * @remarks No-long-jump zone!!!
6384 */
6385static int hmR0VmxSaveGuestRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6386{
6387 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS))
6388 {
6389 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RFLAGS));
6390 uint32_t uVal = 0;
6391 int rc = VMXReadVmcs32(VMX_VMCS_GUEST_RFLAGS, &uVal);
6392 AssertRCReturn(rc, rc);
6393
6394 pMixedCtx->eflags.u32 = uVal;
6395 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active) /* Undo our real-on-v86-mode changes to eflags if necessary. */
6396 {
6397 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
6398 Log4(("Saving real-mode EFLAGS VT-x view=%#RX32\n", pMixedCtx->eflags.u32));
6399
6400 pMixedCtx->eflags.Bits.u1VM = 0;
6401 pMixedCtx->eflags.Bits.u2IOPL = pVCpu->hm.s.vmx.RealMode.Eflags.Bits.u2IOPL;
6402 }
6403
6404 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS);
6405 }
6406 return VINF_SUCCESS;
6407}
6408
6409
6410/**
6411 * Wrapper for saving the guest's RIP, RSP and RFLAGS from the VMCS into the
6412 * guest-CPU context.
6413 */
6414DECLINLINE(int) hmR0VmxSaveGuestRipRspRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6415{
6416 int rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
6417 rc |= hmR0VmxSaveGuestRsp(pVCpu, pMixedCtx);
6418 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
6419 return rc;
6420}
6421
6422
6423/**
6424 * Saves the guest's interruptibility-state ("interrupt shadow" as AMD calls it)
6425 * from the guest-state area in the VMCS.
6426 *
6427 * @param pVCpu The cross context virtual CPU structure.
6428 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6429 * out-of-sync. Make sure to update the required fields
6430 * before using them.
6431 *
6432 * @remarks No-long-jump zone!!!
6433 */
6434static void hmR0VmxSaveGuestIntrState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6435{
6436 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_INTR_STATE))
6437 {
6438 uint32_t uIntrState = 0;
6439 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &uIntrState);
6440 AssertRC(rc);
6441
6442 if (!uIntrState)
6443 {
6444 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
6445 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
6446
6447 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6448 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6449 }
6450 else
6451 {
6452 if (uIntrState & ( VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS
6453 | VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI))
6454 {
6455 rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
6456 AssertRC(rc);
6457 rc = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx); /* for hmR0VmxGetGuestIntrState(). */
6458 AssertRC(rc);
6459
6460 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
6461 Assert(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
6462 }
6463 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
6464 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
6465
6466 if (uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI)
6467 {
6468 if (!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6469 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
6470 }
6471 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6472 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6473 }
6474
6475 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_INTR_STATE);
6476 }
6477}
6478
6479
6480/**
6481 * Saves the guest's activity state.
6482 *
6483 * @returns VBox status code.
6484 * @param pVCpu The cross context virtual CPU structure.
6485 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6486 * out-of-sync. Make sure to update the required fields
6487 * before using them.
6488 *
6489 * @remarks No-long-jump zone!!!
6490 */
6491static int hmR0VmxSaveGuestActivityState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6492{
6493 NOREF(pMixedCtx);
6494 /* Nothing to do for now until we make use of different guest-CPU activity state. Just update the flag. */
6495 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_ACTIVITY_STATE);
6496 return VINF_SUCCESS;
6497}
6498
6499
6500/**
6501 * Saves the guest SYSENTER MSRs (SYSENTER_CS, SYSENTER_EIP, SYSENTER_ESP) from
6502 * the current VMCS into the guest-CPU context.
6503 *
6504 * @returns VBox status code.
6505 * @param pVCpu The cross context virtual CPU structure.
6506 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6507 * out-of-sync. Make sure to update the required fields
6508 * before using them.
6509 *
6510 * @remarks No-long-jump zone!!!
6511 */
6512static int hmR0VmxSaveGuestSysenterMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6513{
6514 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR))
6515 {
6516 Assert(!HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR));
6517 uint32_t u32Val = 0;
6518 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, &u32Val); AssertRCReturn(rc, rc);
6519 pMixedCtx->SysEnter.cs = u32Val;
6520 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR);
6521 }
6522
6523 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR))
6524 {
6525 Assert(!HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR));
6526 uint64_t u64Val = 0;
6527 int rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_SYSENTER_EIP, &u64Val); AssertRCReturn(rc, rc);
6528 pMixedCtx->SysEnter.eip = u64Val;
6529 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR);
6530 }
6531 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR))
6532 {
6533 Assert(!HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR));
6534 uint64_t u64Val = 0;
6535 int rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_SYSENTER_ESP, &u64Val); AssertRCReturn(rc, rc);
6536 pMixedCtx->SysEnter.esp = u64Val;
6537 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR);
6538 }
6539 return VINF_SUCCESS;
6540}
6541
6542
6543/**
6544 * Saves the set of guest MSRs (that we restore lazily while leaving VT-x) from
6545 * the CPU back into the guest-CPU context.
6546 *
6547 * @returns VBox status code.
6548 * @param pVCpu The cross context virtual CPU structure.
6549 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6550 * out-of-sync. Make sure to update the required fields
6551 * before using them.
6552 *
6553 * @remarks No-long-jump zone!!!
6554 */
6555static int hmR0VmxSaveGuestLazyMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6556{
6557 /* Since this can be called from our preemption hook it's safer to make the guest-MSRs update non-preemptible. */
6558 VMMRZCallRing3Disable(pVCpu);
6559 HM_DISABLE_PREEMPT();
6560
6561 /* Doing the check here ensures we don't overwrite already-saved guest MSRs from a preemption hook. */
6562 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LAZY_MSRS))
6563 {
6564 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS));
6565 hmR0VmxLazySaveGuestMsrs(pVCpu, pMixedCtx);
6566 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LAZY_MSRS);
6567 }
6568
6569 HM_RESTORE_PREEMPT();
6570 VMMRZCallRing3Enable(pVCpu);
6571
6572 return VINF_SUCCESS;
6573}
6574
6575
6576/**
6577 * Saves the auto load/store'd guest MSRs from the current VMCS into
6578 * the guest-CPU context.
6579 *
6580 * @returns VBox status code.
6581 * @param pVCpu The cross context virtual CPU structure.
6582 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6583 * out-of-sync. Make sure to update the required fields
6584 * before using them.
6585 *
6586 * @remarks No-long-jump zone!!!
6587 */
6588static int hmR0VmxSaveGuestAutoLoadStoreMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6589{
6590 if (HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS))
6591 return VINF_SUCCESS;
6592
6593 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS));
6594 PVMXAUTOMSR pMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
6595 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
6596 Log4(("hmR0VmxSaveGuestAutoLoadStoreMsrs: cMsrs=%u\n", cMsrs));
6597 for (uint32_t i = 0; i < cMsrs; i++, pMsr++)
6598 {
6599 switch (pMsr->u32Msr)
6600 {
6601 case MSR_K8_TSC_AUX: CPUMR0SetGuestTscAux(pVCpu, pMsr->u64Value); break;
6602 case MSR_K8_LSTAR: pMixedCtx->msrLSTAR = pMsr->u64Value; break;
6603 case MSR_K6_STAR: pMixedCtx->msrSTAR = pMsr->u64Value; break;
6604 case MSR_K8_SF_MASK: pMixedCtx->msrSFMASK = pMsr->u64Value; break;
6605 case MSR_K8_KERNEL_GS_BASE: pMixedCtx->msrKERNELGSBASE = pMsr->u64Value; break;
6606 case MSR_K6_EFER: /* Nothing to do here since we intercept writes, see hmR0VmxLoadGuestMsrs(). */
6607 break;
6608
6609 default:
6610 {
6611 AssertMsgFailed(("Unexpected MSR in auto-load/store area. uMsr=%#RX32 cMsrs=%u\n", pMsr->u32Msr, cMsrs));
6612 pVCpu->hm.s.u32HMError = pMsr->u32Msr;
6613 return VERR_HM_UNEXPECTED_LD_ST_MSR;
6614 }
6615 }
6616 }
6617
6618 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS);
6619 return VINF_SUCCESS;
6620}
6621
6622
6623/**
6624 * Saves the guest control registers from the current VMCS into the guest-CPU
6625 * context.
6626 *
6627 * @returns VBox status code.
6628 * @param pVCpu The cross context virtual CPU structure.
6629 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6630 * out-of-sync. Make sure to update the required fields
6631 * before using them.
6632 *
6633 * @remarks No-long-jump zone!!!
6634 */
6635static int hmR0VmxSaveGuestControlRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6636{
6637 /* Guest CR0. Guest FPU. */
6638 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6639 AssertRCReturn(rc, rc);
6640
6641 /* Guest CR4. */
6642 rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
6643 AssertRCReturn(rc, rc);
6644
6645 /* Guest CR2 - updated always during the world-switch or in #PF. */
6646 /* Guest CR3. Only changes with Nested Paging. This must be done -after- saving CR0 and CR4 from the guest! */
6647 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR3))
6648 {
6649 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR3));
6650 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0));
6651 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR4));
6652
6653 PVM pVM = pVCpu->CTX_SUFF(pVM);
6654 if ( pVM->hm.s.vmx.fUnrestrictedGuest
6655 || ( pVM->hm.s.fNestedPaging
6656 && CPUMIsGuestPagingEnabledEx(pMixedCtx)))
6657 {
6658 uint64_t u64Val = 0;
6659 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_CR3, &u64Val);
6660 if (pMixedCtx->cr3 != u64Val)
6661 {
6662 CPUMSetGuestCR3(pVCpu, u64Val);
6663 if (VMMRZCallRing3IsEnabled(pVCpu))
6664 {
6665 PGMUpdateCR3(pVCpu, u64Val);
6666 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
6667 }
6668 else
6669 {
6670 /* Set the force flag to inform PGM about it when necessary. It is cleared by PGMUpdateCR3().*/
6671 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
6672 }
6673 }
6674
6675 /* If the guest is in PAE mode, sync back the PDPE's into the guest state. */
6676 if (CPUMIsGuestInPAEModeEx(pMixedCtx)) /* Reads CR0, CR4 and EFER MSR (EFER is always up-to-date). */
6677 {
6678 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &pVCpu->hm.s.aPdpes[0].u);
6679 rc |= VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &pVCpu->hm.s.aPdpes[1].u);
6680 rc |= VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &pVCpu->hm.s.aPdpes[2].u);
6681 rc |= VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &pVCpu->hm.s.aPdpes[3].u);
6682 AssertRCReturn(rc, rc);
6683
6684 if (VMMRZCallRing3IsEnabled(pVCpu))
6685 {
6686 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
6687 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
6688 }
6689 else
6690 {
6691 /* Set the force flag to inform PGM about it when necessary. It is cleared by PGMGstUpdatePaePdpes(). */
6692 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES);
6693 }
6694 }
6695 }
6696
6697 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR3);
6698 }
6699
6700 /*
6701 * Consider this scenario: VM-exit -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp -> hmR0VmxCallRing3Callback()
6702 * -> VMMRZCallRing3Disable() -> hmR0VmxSaveGuestState() -> Set VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp
6703 * -> continue with VM-exit handling -> hmR0VmxSaveGuestControlRegs() and here we are.
6704 *
6705 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be up-to-date and thus
6706 * if any CR3-saves -before- the VM-exit (longjmp) postponed the CR3 update via the force-flag, any VM-exit handler that
6707 * calls into PGM when it re-saves CR3 will end up here and we call PGMUpdateCR3(). This is why the code below should
6708 * -NOT- check if HMVMX_UPDATED_GUEST_CR3 is already set or not!
6709 *
6710 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again. We cover for it here.
6711 */
6712 if (VMMRZCallRing3IsEnabled(pVCpu))
6713 {
6714 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
6715 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
6716
6717 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
6718 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
6719
6720 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
6721 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
6722 }
6723
6724 return rc;
6725}
6726
6727
6728/**
6729 * Reads a guest segment register from the current VMCS into the guest-CPU
6730 * context.
6731 *
6732 * @returns VBox status code.
6733 * @param pVCpu The cross context virtual CPU structure.
6734 * @param idxSel Index of the selector in the VMCS.
6735 * @param idxLimit Index of the segment limit in the VMCS.
6736 * @param idxBase Index of the segment base in the VMCS.
6737 * @param idxAccess Index of the access rights of the segment in the VMCS.
6738 * @param pSelReg Pointer to the segment selector.
6739 *
6740 * @remarks No-long-jump zone!!!
6741 * @remarks Never call this function directly!!! Use the VMXLOCAL_READ_SEG()
6742 * macro as that takes care of whether to read from the VMCS cache or
6743 * not.
6744 */
6745DECLINLINE(int) hmR0VmxReadSegmentReg(PVMCPU pVCpu, uint32_t idxSel, uint32_t idxLimit, uint32_t idxBase, uint32_t idxAccess,
6746 PCPUMSELREG pSelReg)
6747{
6748 NOREF(pVCpu);
6749
6750 uint32_t u32Val = 0;
6751 int rc = VMXReadVmcs32(idxSel, &u32Val);
6752 AssertRCReturn(rc, rc);
6753 pSelReg->Sel = (uint16_t)u32Val;
6754 pSelReg->ValidSel = (uint16_t)u32Val;
6755 pSelReg->fFlags = CPUMSELREG_FLAGS_VALID;
6756
6757 rc = VMXReadVmcs32(idxLimit, &u32Val);
6758 AssertRCReturn(rc, rc);
6759 pSelReg->u32Limit = u32Val;
6760
6761 uint64_t u64Val = 0;
6762 rc = VMXReadVmcsGstNByIdxVal(idxBase, &u64Val);
6763 AssertRCReturn(rc, rc);
6764 pSelReg->u64Base = u64Val;
6765
6766 rc = VMXReadVmcs32(idxAccess, &u32Val);
6767 AssertRCReturn(rc, rc);
6768 pSelReg->Attr.u = u32Val;
6769
6770 /*
6771 * If VT-x marks the segment as unusable, most other bits remain undefined:
6772 * - For CS the L, D and G bits have meaning.
6773 * - For SS the DPL has meaning (it -is- the CPL for Intel and VBox).
6774 * - For the remaining data segments no bits are defined.
6775 *
6776 * The present bit and the unusable bit has been observed to be set at the
6777 * same time (the selector was supposed to be invalid as we started executing
6778 * a V8086 interrupt in ring-0).
6779 *
6780 * What should be important for the rest of the VBox code, is that the P bit is
6781 * cleared. Some of the other VBox code recognizes the unusable bit, but
6782 * AMD-V certainly don't, and REM doesn't really either. So, to be on the
6783 * safe side here, we'll strip off P and other bits we don't care about. If
6784 * any code breaks because Attr.u != 0 when Sel < 4, it should be fixed.
6785 *
6786 * See Intel spec. 27.3.2 "Saving Segment Registers and Descriptor-Table Registers".
6787 */
6788 if (pSelReg->Attr.u & X86DESCATTR_UNUSABLE)
6789 {
6790 Assert(idxSel != VMX_VMCS16_GUEST_TR_SEL); /* TR is the only selector that can never be unusable. */
6791
6792 /* Masking off: X86DESCATTR_P, X86DESCATTR_LIMIT_HIGH, and X86DESCATTR_AVL. The latter two are really irrelevant. */
6793 pSelReg->Attr.u &= X86DESCATTR_UNUSABLE | X86DESCATTR_L | X86DESCATTR_D | X86DESCATTR_G
6794 | X86DESCATTR_DPL | X86DESCATTR_TYPE | X86DESCATTR_DT;
6795
6796 Log4(("hmR0VmxReadSegmentReg: Unusable idxSel=%#x attr=%#x -> %#x\n", idxSel, u32Val, pSelReg->Attr.u));
6797#ifdef DEBUG_bird
6798 AssertMsg((u32Val & ~X86DESCATTR_P) == pSelReg->Attr.u,
6799 ("%#x: %#x != %#x (sel=%#x base=%#llx limit=%#x)\n",
6800 idxSel, u32Val, pSelReg->Attr.u, pSelReg->Sel, pSelReg->u64Base, pSelReg->u32Limit));
6801#endif
6802 }
6803 return VINF_SUCCESS;
6804}
6805
6806
6807#ifdef VMX_USE_CACHED_VMCS_ACCESSES
6808# define VMXLOCAL_READ_SEG(Sel, CtxSel) \
6809 hmR0VmxReadSegmentReg(pVCpu, VMX_VMCS16_GUEST_##Sel##_SEL, VMX_VMCS32_GUEST_##Sel##_LIMIT, \
6810 VMX_VMCS_GUEST_##Sel##_BASE_CACHE_IDX, VMX_VMCS32_GUEST_##Sel##_ACCESS_RIGHTS, &pMixedCtx->CtxSel)
6811#else
6812# define VMXLOCAL_READ_SEG(Sel, CtxSel) \
6813 hmR0VmxReadSegmentReg(pVCpu, VMX_VMCS16_GUEST_##Sel##_SEL, VMX_VMCS32_GUEST_##Sel##_LIMIT, \
6814 VMX_VMCS_GUEST_##Sel##_BASE, VMX_VMCS32_GUEST_##Sel##_ACCESS_RIGHTS, &pMixedCtx->CtxSel)
6815#endif
6816
6817
6818/**
6819 * Saves the guest segment registers from the current VMCS into the guest-CPU
6820 * context.
6821 *
6822 * @returns VBox status code.
6823 * @param pVCpu The cross context virtual CPU structure.
6824 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6825 * out-of-sync. Make sure to update the required fields
6826 * before using them.
6827 *
6828 * @remarks No-long-jump zone!!!
6829 */
6830static int hmR0VmxSaveGuestSegmentRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6831{
6832 /* Guest segment registers. */
6833 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SEGMENT_REGS))
6834 {
6835 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS));
6836 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6837 AssertRCReturn(rc, rc);
6838
6839 rc = VMXLOCAL_READ_SEG(CS, cs);
6840 rc |= VMXLOCAL_READ_SEG(SS, ss);
6841 rc |= VMXLOCAL_READ_SEG(DS, ds);
6842 rc |= VMXLOCAL_READ_SEG(ES, es);
6843 rc |= VMXLOCAL_READ_SEG(FS, fs);
6844 rc |= VMXLOCAL_READ_SEG(GS, gs);
6845 AssertRCReturn(rc, rc);
6846
6847 /* Restore segment attributes for real-on-v86 mode hack. */
6848 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
6849 {
6850 pMixedCtx->cs.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrCS.u;
6851 pMixedCtx->ss.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrSS.u;
6852 pMixedCtx->ds.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrDS.u;
6853 pMixedCtx->es.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrES.u;
6854 pMixedCtx->fs.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrFS.u;
6855 pMixedCtx->gs.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrGS.u;
6856 }
6857 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SEGMENT_REGS);
6858 }
6859
6860 return VINF_SUCCESS;
6861}
6862
6863
6864/**
6865 * Saves the guest descriptor table registers and task register from the current
6866 * VMCS into the guest-CPU context.
6867 *
6868 * @returns VBox status code.
6869 * @param pVCpu The cross context virtual CPU structure.
6870 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6871 * out-of-sync. Make sure to update the required fields
6872 * before using them.
6873 *
6874 * @remarks No-long-jump zone!!!
6875 */
6876static int hmR0VmxSaveGuestTableRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6877{
6878 int rc = VINF_SUCCESS;
6879
6880 /* Guest LDTR. */
6881 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LDTR))
6882 {
6883 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LDTR));
6884 rc = VMXLOCAL_READ_SEG(LDTR, ldtr);
6885 AssertRCReturn(rc, rc);
6886 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LDTR);
6887 }
6888
6889 /* Guest GDTR. */
6890 uint64_t u64Val = 0;
6891 uint32_t u32Val = 0;
6892 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_GDTR))
6893 {
6894 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_GDTR));
6895 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
6896 rc |= VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val); AssertRCReturn(rc, rc);
6897 pMixedCtx->gdtr.pGdt = u64Val;
6898 pMixedCtx->gdtr.cbGdt = u32Val;
6899 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_GDTR);
6900 }
6901
6902 /* Guest IDTR. */
6903 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_IDTR))
6904 {
6905 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_IDTR));
6906 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
6907 rc |= VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val); AssertRCReturn(rc, rc);
6908 pMixedCtx->idtr.pIdt = u64Val;
6909 pMixedCtx->idtr.cbIdt = u32Val;
6910 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_IDTR);
6911 }
6912
6913 /* Guest TR. */
6914 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_TR))
6915 {
6916 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_TR));
6917 rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6918 AssertRCReturn(rc, rc);
6919
6920 /* For real-mode emulation using virtual-8086 mode we have the fake TSS (pRealModeTSS) in TR, don't save the fake one. */
6921 if (!pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
6922 {
6923 rc = VMXLOCAL_READ_SEG(TR, tr);
6924 AssertRCReturn(rc, rc);
6925 }
6926 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_TR);
6927 }
6928 return rc;
6929}
6930
6931#undef VMXLOCAL_READ_SEG
6932
6933
6934/**
6935 * Saves the guest debug-register DR7 from the current VMCS into the guest-CPU
6936 * context.
6937 *
6938 * @returns VBox status code.
6939 * @param pVCpu The cross context virtual CPU structure.
6940 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6941 * out-of-sync. Make sure to update the required fields
6942 * before using them.
6943 *
6944 * @remarks No-long-jump zone!!!
6945 */
6946static int hmR0VmxSaveGuestDR7(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6947{
6948 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_DR7))
6949 {
6950 if (!pVCpu->hm.s.fUsingHyperDR7)
6951 {
6952 /* Upper 32-bits are always zero. See Intel spec. 2.7.3 "Loading and Storing Debug Registers". */
6953 uint32_t u32Val;
6954 int rc = VMXReadVmcs32(VMX_VMCS_GUEST_DR7, &u32Val); AssertRCReturn(rc, rc);
6955 pMixedCtx->dr[7] = u32Val;
6956 }
6957
6958 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_DR7);
6959 }
6960 return VINF_SUCCESS;
6961}
6962
6963
6964/**
6965 * Saves the guest APIC state from the current VMCS into the guest-CPU context.
6966 *
6967 * @returns VBox status code.
6968 * @param pVCpu The cross context virtual CPU structure.
6969 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6970 * out-of-sync. Make sure to update the required fields
6971 * before using them.
6972 *
6973 * @remarks No-long-jump zone!!!
6974 */
6975static int hmR0VmxSaveGuestApicState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6976{
6977 NOREF(pMixedCtx);
6978
6979 /* Updating TPR is already done in hmR0VmxPostRunGuest(). Just update the flag. */
6980 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_APIC_STATE);
6981 return VINF_SUCCESS;
6982}
6983
6984
6985/**
6986 * Saves the entire guest state from the currently active VMCS into the
6987 * guest-CPU context.
6988 *
6989 * This essentially VMREADs all guest-data.
6990 *
6991 * @returns VBox status code.
6992 * @param pVCpu The cross context virtual CPU structure.
6993 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
6994 * out-of-sync. Make sure to update the required fields
6995 * before using them.
6996 */
6997static int hmR0VmxSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6998{
6999 Assert(pVCpu);
7000 Assert(pMixedCtx);
7001
7002 if (HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL)
7003 return VINF_SUCCESS;
7004
7005 /* Though we can longjmp to ring-3 due to log-flushes here and get recalled
7006 again on the ring-3 callback path, there is no real need to. */
7007 if (VMMRZCallRing3IsEnabled(pVCpu))
7008 VMMR0LogFlushDisable(pVCpu);
7009 else
7010 Assert(VMMR0IsLogFlushDisabled(pVCpu));
7011 Log4Func(("vcpu[%RU32]\n", pVCpu->idCpu));
7012
7013 int rc = hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
7014 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestRipRspRflags failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7015
7016 rc = hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
7017 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestControlRegs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7018
7019 rc = hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
7020 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestSegmentRegs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7021
7022 rc = hmR0VmxSaveGuestTableRegs(pVCpu, pMixedCtx);
7023 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestTableRegs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7024
7025 rc = hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
7026 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestDR7 failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7027
7028 rc = hmR0VmxSaveGuestSysenterMsrs(pVCpu, pMixedCtx);
7029 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestSysenterMsrs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7030
7031 rc = hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
7032 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestLazyMsrs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7033
7034 rc = hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
7035 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestAutoLoadStoreMsrs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7036
7037 rc = hmR0VmxSaveGuestActivityState(pVCpu, pMixedCtx);
7038 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestActivityState failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7039
7040 rc = hmR0VmxSaveGuestApicState(pVCpu, pMixedCtx);
7041 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestApicState failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
7042
7043 AssertMsg(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL,
7044 ("Missed guest state bits while saving state; missing %RX32 (got %RX32, want %RX32) - check log for any previous errors!\n",
7045 HMVMX_UPDATED_GUEST_ALL ^ HMVMXCPU_GST_VALUE(pVCpu), HMVMXCPU_GST_VALUE(pVCpu), HMVMX_UPDATED_GUEST_ALL));
7046
7047 if (VMMRZCallRing3IsEnabled(pVCpu))
7048 VMMR0LogFlushEnable(pVCpu);
7049
7050 return VINF_SUCCESS;
7051}
7052
7053
7054/**
7055 * Saves basic guest registers needed for IEM instruction execution.
7056 *
7057 * @returns VBox status code (OR-able).
7058 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
7059 * @param pMixedCtx Pointer to the CPU context of the guest.
7060 * @param fMemory Whether the instruction being executed operates on
7061 * memory or not. Only CR0 is synced up if clear.
7062 * @param fNeedRsp Need RSP (any instruction working on GPRs or stack).
7063 */
7064static int hmR0VmxSaveGuestRegsForIemExec(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fMemory, bool fNeedRsp)
7065{
7066 /*
7067 * We assume all general purpose registers other than RSP are available.
7068 *
7069 * - RIP is a must, as it will be incremented or otherwise changed.
7070 * - RFLAGS are always required to figure the CPL.
7071 * - RSP isn't always required, however it's a GPR, so frequently required.
7072 * - SS and CS are the only segment register needed if IEM doesn't do memory
7073 * access (CPL + 16/32/64-bit mode), but we can only get all segment registers.
7074 * - CR0 is always required by IEM for the CPL, while CR3 and CR4 will only
7075 * be required for memory accesses.
7076 *
7077 * Note! Before IEM dispatches an exception, it will call us to sync in everything.
7078 */
7079 int rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
7080 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
7081 if (fNeedRsp)
7082 rc |= hmR0VmxSaveGuestRsp(pVCpu, pMixedCtx);
7083 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
7084 if (!fMemory)
7085 rc |= hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
7086 else
7087 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
7088 AssertRCReturn(rc, rc);
7089 return rc;
7090}
7091
7092
7093/**
7094 * Ensures that we've got a complete basic guest-context.
7095 *
7096 * This excludes the FPU, SSE, AVX, and similar extended state. The interface
7097 * is for the interpreter.
7098 *
7099 * @returns VBox status code.
7100 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
7101 * @param pMixedCtx Pointer to the guest-CPU context which may have data
7102 * needing to be synced in.
7103 * @thread EMT(pVCpu)
7104 */
7105VMMR0_INT_DECL(int) HMR0EnsureCompleteBasicContext(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7106{
7107 /* Note! Since this is only applicable to VT-x, the implementation is placed
7108 in the VT-x part of the sources instead of the generic stuff. */
7109 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported)
7110 {
7111 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
7112 /*
7113 * For now, imply that the caller might change everything too. Do this after
7114 * saving the guest state so as to not trigger assertions.
7115 */
7116 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7117 return rc;
7118 }
7119 return VINF_SUCCESS;
7120}
7121
7122
7123/**
7124 * Check per-VM and per-VCPU force flag actions that require us to go back to
7125 * ring-3 for one reason or another.
7126 *
7127 * @returns Strict VBox status code (i.e. informational status codes too)
7128 * @retval VINF_SUCCESS if we don't have any actions that require going back to
7129 * ring-3.
7130 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
7131 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
7132 * interrupts)
7133 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
7134 * all EMTs to be in ring-3.
7135 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
7136 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
7137 * to the EM loop.
7138 *
7139 * @param pVM The cross context VM structure.
7140 * @param pVCpu The cross context virtual CPU structure.
7141 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7142 * out-of-sync. Make sure to update the required fields
7143 * before using them.
7144 * @param fStepping Running in hmR0VmxRunGuestCodeStep().
7145 */
7146static VBOXSTRICTRC hmR0VmxCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fStepping)
7147{
7148 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7149
7150 /*
7151 * Anything pending? Should be more likely than not if we're doing a good job.
7152 */
7153 if ( !fStepping
7154 ? !VM_FF_IS_PENDING(pVM, VM_FF_HP_R0_PRE_HM_MASK)
7155 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HP_R0_PRE_HM_MASK)
7156 : !VM_FF_IS_PENDING(pVM, VM_FF_HP_R0_PRE_HM_STEP_MASK)
7157 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
7158 return VINF_SUCCESS;
7159
7160 /* We need the control registers now, make sure the guest-CPU context is updated. */
7161 int rc3 = hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
7162 AssertRCReturn(rc3, rc3);
7163
7164 /* Pending HM CR3 sync. */
7165 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
7166 {
7167 int rc2 = PGMUpdateCR3(pVCpu, pMixedCtx->cr3);
7168 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
7169 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
7170 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
7171 }
7172
7173 /* Pending HM PAE PDPEs. */
7174 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
7175 {
7176 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
7177 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
7178 }
7179
7180 /* Pending PGM C3 sync. */
7181 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
7182 {
7183 VBOXSTRICTRC rcStrict2 = PGMSyncCR3(pVCpu, pMixedCtx->cr0, pMixedCtx->cr3, pMixedCtx->cr4,
7184 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
7185 if (rcStrict2 != VINF_SUCCESS)
7186 {
7187 AssertRC(VBOXSTRICTRC_VAL(rcStrict2));
7188 Log4(("hmR0VmxCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc2=%d\n", VBOXSTRICTRC_VAL(rcStrict2)));
7189 return rcStrict2;
7190 }
7191 }
7192
7193 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
7194 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
7195 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
7196 {
7197 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
7198 int rc2 = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
7199 Log4(("hmR0VmxCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc2));
7200 return rc2;
7201 }
7202
7203 /* Pending VM request packets, such as hardware interrupts. */
7204 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
7205 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
7206 {
7207 Log4(("hmR0VmxCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
7208 return VINF_EM_PENDING_REQUEST;
7209 }
7210
7211 /* Pending PGM pool flushes. */
7212 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
7213 {
7214 Log4(("hmR0VmxCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
7215 return VINF_PGM_POOL_FLUSH_PENDING;
7216 }
7217
7218 /* Pending DMA requests. */
7219 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
7220 {
7221 Log4(("hmR0VmxCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
7222 return VINF_EM_RAW_TO_R3;
7223 }
7224
7225 return VINF_SUCCESS;
7226}
7227
7228
7229/**
7230 * Converts any TRPM trap into a pending HM event. This is typically used when
7231 * entering from ring-3 (not longjmp returns).
7232 *
7233 * @param pVCpu The cross context virtual CPU structure.
7234 */
7235static void hmR0VmxTrpmTrapToPendingEvent(PVMCPU pVCpu)
7236{
7237 Assert(TRPMHasTrap(pVCpu));
7238 Assert(!pVCpu->hm.s.Event.fPending);
7239
7240 uint8_t uVector;
7241 TRPMEVENT enmTrpmEvent;
7242 RTGCUINT uErrCode;
7243 RTGCUINTPTR GCPtrFaultAddress;
7244 uint8_t cbInstr;
7245
7246 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
7247 AssertRC(rc);
7248
7249 /* Refer Intel spec. 24.8.3 "VM-entry Controls for Event Injection" for the format of u32IntInfo. */
7250 uint32_t u32IntInfo = uVector | VMX_EXIT_INTERRUPTION_INFO_VALID;
7251 if (enmTrpmEvent == TRPM_TRAP)
7252 {
7253 switch (uVector)
7254 {
7255 case X86_XCPT_NMI:
7256 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7257 break;
7258
7259 case X86_XCPT_BP:
7260 case X86_XCPT_OF:
7261 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7262 break;
7263
7264 case X86_XCPT_PF:
7265 case X86_XCPT_DF:
7266 case X86_XCPT_TS:
7267 case X86_XCPT_NP:
7268 case X86_XCPT_SS:
7269 case X86_XCPT_GP:
7270 case X86_XCPT_AC:
7271 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
7272 /* fall thru */
7273 default:
7274 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7275 break;
7276 }
7277 }
7278 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
7279 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7280 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
7281 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7282 else
7283 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
7284
7285 rc = TRPMResetTrap(pVCpu);
7286 AssertRC(rc);
7287 Log4(("TRPM->HM event: u32IntInfo=%#RX32 enmTrpmEvent=%d cbInstr=%u uErrCode=%#RX32 GCPtrFaultAddress=%#RGv\n",
7288 u32IntInfo, enmTrpmEvent, cbInstr, uErrCode, GCPtrFaultAddress));
7289
7290 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, uErrCode, GCPtrFaultAddress);
7291}
7292
7293
7294/**
7295 * Converts the pending HM event into a TRPM trap.
7296 *
7297 * @param pVCpu The cross context virtual CPU structure.
7298 */
7299static void hmR0VmxPendingEventToTrpmTrap(PVMCPU pVCpu)
7300{
7301 Assert(pVCpu->hm.s.Event.fPending);
7302
7303 uint32_t uVectorType = VMX_IDT_VECTORING_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
7304 uint32_t uVector = VMX_IDT_VECTORING_INFO_VECTOR(pVCpu->hm.s.Event.u64IntInfo);
7305 bool fErrorCodeValid = VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVCpu->hm.s.Event.u64IntInfo);
7306 uint32_t uErrorCode = pVCpu->hm.s.Event.u32ErrCode;
7307
7308 /* If a trap was already pending, we did something wrong! */
7309 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
7310
7311 TRPMEVENT enmTrapType;
7312 switch (uVectorType)
7313 {
7314 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
7315 enmTrapType = TRPM_HARDWARE_INT;
7316 break;
7317
7318 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
7319 enmTrapType = TRPM_SOFTWARE_INT;
7320 break;
7321
7322 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
7323 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
7324 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT: /* #BP and #OF */
7325 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
7326 enmTrapType = TRPM_TRAP;
7327 break;
7328
7329 default:
7330 AssertMsgFailed(("Invalid trap type %#x\n", uVectorType));
7331 enmTrapType = TRPM_32BIT_HACK;
7332 break;
7333 }
7334
7335 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, enmTrapType));
7336
7337 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
7338 AssertRC(rc);
7339
7340 if (fErrorCodeValid)
7341 TRPMSetErrorCode(pVCpu, uErrorCode);
7342
7343 if ( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
7344 && uVector == X86_XCPT_PF)
7345 {
7346 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
7347 }
7348 else if ( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
7349 || uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
7350 || uVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
7351 {
7352 AssertMsg( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
7353 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
7354 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
7355 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
7356 }
7357
7358 /* Clear any pending events from the VMCS. */
7359 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0); AssertRC(rc);
7360 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, 0); AssertRC(rc);
7361
7362 /* We're now done converting the pending event. */
7363 pVCpu->hm.s.Event.fPending = false;
7364}
7365
7366
7367/**
7368 * Does the necessary state syncing before returning to ring-3 for any reason
7369 * (longjmp, preemption, voluntary exits to ring-3) from VT-x.
7370 *
7371 * @returns VBox status code.
7372 * @param pVCpu The cross context virtual CPU structure.
7373 * @param pMixedCtx Pointer to the guest-CPU context. The data may
7374 * be out-of-sync. Make sure to update the required
7375 * fields before using them.
7376 * @param fSaveGuestState Whether to save the guest state or not.
7377 *
7378 * @remarks No-long-jmp zone!!!
7379 */
7380static int hmR0VmxLeave(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fSaveGuestState)
7381{
7382 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7383 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7384
7385 RTCPUID idCpu = RTMpCpuId();
7386 Log4Func(("HostCpuId=%u\n", idCpu));
7387
7388 /*
7389 * !!! IMPORTANT !!!
7390 * If you modify code here, check whether hmR0VmxCallRing3Callback() needs to be updated too.
7391 */
7392
7393 /* Save the guest state if necessary. */
7394 if ( fSaveGuestState
7395 && HMVMXCPU_GST_VALUE(pVCpu) != HMVMX_UPDATED_GUEST_ALL)
7396 {
7397 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
7398 AssertRCReturn(rc, rc);
7399 Assert(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL);
7400 }
7401
7402 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
7403 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu))
7404 {
7405 /* We shouldn't reload CR0 without saving it first. */
7406 if (!fSaveGuestState)
7407 {
7408 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
7409 AssertRCReturn(rc, rc);
7410 }
7411 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
7412 }
7413
7414 /* Restore host debug registers if necessary and resync on next R0 reentry. */
7415#ifdef VBOX_STRICT
7416 if (CPUMIsHyperDebugStateActive(pVCpu))
7417 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT);
7418#endif
7419 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */))
7420 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
7421 Assert(!CPUMIsGuestDebugStateActive(pVCpu) && !CPUMIsGuestDebugStateActivePending(pVCpu));
7422 Assert(!CPUMIsHyperDebugStateActive(pVCpu) && !CPUMIsHyperDebugStateActivePending(pVCpu));
7423
7424#if HC_ARCH_BITS == 64
7425 /* Restore host-state bits that VT-x only restores partially. */
7426 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7427 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7428 {
7429 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags, idCpu));
7430 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7431 }
7432 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7433#endif
7434
7435 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7436 if (pVCpu->hm.s.vmx.fLazyMsrs)
7437 {
7438 /* We shouldn't reload the guest MSRs without saving it first. */
7439 if (!fSaveGuestState)
7440 {
7441 int rc = hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
7442 AssertRCReturn(rc, rc);
7443 }
7444 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LAZY_MSRS));
7445 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7446 Assert(!pVCpu->hm.s.vmx.fLazyMsrs);
7447 }
7448
7449 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7450 pVCpu->hm.s.vmx.fUpdatedHostMsrs = false;
7451
7452 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
7453 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
7454 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
7455 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
7456 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitIO);
7457 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitMovCRx);
7458 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitXcptNmi);
7459 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
7460
7461 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
7462
7463 /** @todo This partially defeats the purpose of having preemption hooks.
7464 * The problem is, deregistering the hooks should be moved to a place that
7465 * lasts until the EMT is about to be destroyed not everytime while leaving HM
7466 * context.
7467 */
7468 if (pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_ACTIVE)
7469 {
7470 int rc = VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
7471 AssertRCReturn(rc, rc);
7472
7473 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
7474 Log4Func(("Cleared Vmcs. HostCpuId=%u\n", idCpu));
7475 }
7476 Assert(!(pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_LAUNCHED));
7477 NOREF(idCpu);
7478
7479 return VINF_SUCCESS;
7480}
7481
7482
7483/**
7484 * Leaves the VT-x session.
7485 *
7486 * @returns VBox status code.
7487 * @param pVCpu The cross context virtual CPU structure.
7488 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7489 * out-of-sync. Make sure to update the required fields
7490 * before using them.
7491 *
7492 * @remarks No-long-jmp zone!!!
7493 */
7494DECLINLINE(int) hmR0VmxLeaveSession(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7495{
7496 HM_DISABLE_PREEMPT();
7497 HMVMX_ASSERT_CPU_SAFE();
7498 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7499 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7500
7501 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
7502 and done this from the VMXR0ThreadCtxCallback(). */
7503 if (!pVCpu->hm.s.fLeaveDone)
7504 {
7505 int rc2 = hmR0VmxLeave(pVCpu, pMixedCtx, true /* fSaveGuestState */);
7506 AssertRCReturnStmt(rc2, HM_RESTORE_PREEMPT(), rc2);
7507 pVCpu->hm.s.fLeaveDone = true;
7508 }
7509 Assert(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL);
7510
7511 /*
7512 * !!! IMPORTANT !!!
7513 * If you modify code here, make sure to check whether hmR0VmxCallRing3Callback() needs to be updated too.
7514 */
7515
7516 /* Deregister hook now that we've left HM context before re-enabling preemption. */
7517 /** @todo Deregistering here means we need to VMCLEAR always
7518 * (longjmp/exit-to-r3) in VT-x which is not efficient. */
7519 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
7520 VMMR0ThreadCtxHookDisable(pVCpu);
7521
7522 /* Leave HM context. This takes care of local init (term). */
7523 int rc = HMR0LeaveCpu(pVCpu);
7524
7525 HM_RESTORE_PREEMPT();
7526 return rc;
7527}
7528
7529
7530/**
7531 * Does the necessary state syncing before doing a longjmp to ring-3.
7532 *
7533 * @returns VBox status code.
7534 * @param pVCpu The cross context virtual CPU structure.
7535 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7536 * out-of-sync. Make sure to update the required fields
7537 * before using them.
7538 *
7539 * @remarks No-long-jmp zone!!!
7540 */
7541DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7542{
7543 return hmR0VmxLeaveSession(pVCpu, pMixedCtx);
7544}
7545
7546
7547/**
7548 * Take necessary actions before going back to ring-3.
7549 *
7550 * An action requires us to go back to ring-3. This function does the necessary
7551 * steps before we can safely return to ring-3. This is not the same as longjmps
7552 * to ring-3, this is voluntary and prepares the guest so it may continue
7553 * executing outside HM (recompiler/IEM).
7554 *
7555 * @returns VBox status code.
7556 * @param pVM The cross context VM structure.
7557 * @param pVCpu The cross context virtual CPU structure.
7558 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7559 * out-of-sync. Make sure to update the required fields
7560 * before using them.
7561 * @param rcExit The reason for exiting to ring-3. Can be
7562 * VINF_VMM_UNKNOWN_RING3_CALL.
7563 */
7564static int hmR0VmxExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, VBOXSTRICTRC rcExit)
7565{
7566 Assert(pVM);
7567 Assert(pVCpu);
7568 Assert(pMixedCtx);
7569 HMVMX_ASSERT_PREEMPT_SAFE();
7570
7571 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
7572 {
7573 VMXGetActivatedVmcs(&pVCpu->hm.s.vmx.LastError.u64VMCSPhys);
7574 pVCpu->hm.s.vmx.LastError.u32VMCSRevision = *(uint32_t *)pVCpu->hm.s.vmx.pvVmcs;
7575 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
7576 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
7577 }
7578
7579 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
7580 VMMRZCallRing3Disable(pVCpu);
7581 Log4(("hmR0VmxExitToRing3: pVCpu=%p idCpu=%RU32 rcExit=%d\n", pVCpu, pVCpu->idCpu, VBOXSTRICTRC_VAL(rcExit)));
7582
7583 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
7584 if (pVCpu->hm.s.Event.fPending)
7585 {
7586 hmR0VmxPendingEventToTrpmTrap(pVCpu);
7587 Assert(!pVCpu->hm.s.Event.fPending);
7588 }
7589
7590 /* Clear interrupt-window and NMI-window controls as we re-evaluate it when we return from ring-3. */
7591 hmR0VmxClearIntNmiWindowsVmcs(pVCpu);
7592
7593 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
7594 and if we're injecting an event we should have a TRPM trap pending. */
7595 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
7596#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a tripple fault in progress. */
7597 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
7598#endif
7599
7600 /* Save guest state and restore host state bits. */
7601 int rc = hmR0VmxLeaveSession(pVCpu, pMixedCtx);
7602 AssertRCReturn(rc, rc);
7603 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
7604 /* Thread-context hooks are unregistered at this point!!! */
7605
7606 /* Sync recompiler state. */
7607 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
7608 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
7609 | CPUM_CHANGED_LDTR
7610 | CPUM_CHANGED_GDTR
7611 | CPUM_CHANGED_IDTR
7612 | CPUM_CHANGED_TR
7613 | CPUM_CHANGED_HIDDEN_SEL_REGS);
7614 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0));
7615 if ( pVM->hm.s.fNestedPaging
7616 && CPUMIsGuestPagingEnabledEx(pMixedCtx))
7617 {
7618 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
7619 }
7620
7621 Assert(!pVCpu->hm.s.fClearTrapFlag);
7622
7623 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
7624 if (rcExit != VINF_EM_RAW_INTERRUPT)
7625 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7626
7627 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
7628
7629 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
7630 VMMRZCallRing3RemoveNotification(pVCpu);
7631 VMMRZCallRing3Enable(pVCpu);
7632
7633 return rc;
7634}
7635
7636
7637/**
7638 * VMMRZCallRing3() callback wrapper which saves the guest state before we
7639 * longjump to ring-3 and possibly get preempted.
7640 *
7641 * @returns VBox status code.
7642 * @param pVCpu The cross context virtual CPU structure.
7643 * @param enmOperation The operation causing the ring-3 longjump.
7644 * @param pvUser Opaque pointer to the guest-CPU context. The data
7645 * may be out-of-sync. Make sure to update the required
7646 * fields before using them.
7647 */
7648static DECLCALLBACK(int) hmR0VmxCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
7649{
7650 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
7651 {
7652 /*
7653 * !!! IMPORTANT !!!
7654 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
7655 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
7656 */
7657 VMMRZCallRing3RemoveNotification(pVCpu);
7658 VMMRZCallRing3Disable(pVCpu);
7659 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
7660 RTThreadPreemptDisable(&PreemptState);
7661
7662 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
7663 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
7664
7665#if HC_ARCH_BITS == 64
7666 /* Restore host-state bits that VT-x only restores partially. */
7667 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7668 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7669 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7670 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7671#endif
7672 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7673 if (pVCpu->hm.s.vmx.fLazyMsrs)
7674 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7675
7676 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7677 pVCpu->hm.s.vmx.fUpdatedHostMsrs = false;
7678 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
7679 if (pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_ACTIVE)
7680 {
7681 VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
7682 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
7683 }
7684
7685 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
7686 VMMR0ThreadCtxHookDisable(pVCpu);
7687 HMR0LeaveCpu(pVCpu);
7688 RTThreadPreemptRestore(&PreemptState);
7689 return VINF_SUCCESS;
7690 }
7691
7692 Assert(pVCpu);
7693 Assert(pvUser);
7694 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7695 HMVMX_ASSERT_PREEMPT_SAFE();
7696
7697 VMMRZCallRing3Disable(pVCpu);
7698 Assert(VMMR0IsLogFlushDisabled(pVCpu));
7699
7700 Log4(("hmR0VmxCallRing3Callback->hmR0VmxLongJmpToRing3 pVCpu=%p idCpu=%RU32 enmOperation=%d\n", pVCpu, pVCpu->idCpu,
7701 enmOperation));
7702
7703 int rc = hmR0VmxLongJmpToRing3(pVCpu, (PCPUMCTX)pvUser);
7704 AssertRCReturn(rc, rc);
7705
7706 VMMRZCallRing3Enable(pVCpu);
7707 return VINF_SUCCESS;
7708}
7709
7710
7711/**
7712 * Sets the interrupt-window exiting control in the VMCS which instructs VT-x to
7713 * cause a VM-exit as soon as the guest is in a state to receive interrupts.
7714 *
7715 * @param pVCpu The cross context virtual CPU structure.
7716 */
7717DECLINLINE(void) hmR0VmxSetIntWindowExitVmcs(PVMCPU pVCpu)
7718{
7719 if (RT_LIKELY(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT))
7720 {
7721 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT))
7722 {
7723 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT;
7724 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7725 AssertRC(rc);
7726 Log4(("Setup interrupt-window exiting\n"));
7727 }
7728 } /* else we will deliver interrupts whenever the guest exits next and is in a state to receive events. */
7729}
7730
7731
7732/**
7733 * Clears the interrupt-window exiting control in the VMCS.
7734 *
7735 * @param pVCpu The cross context virtual CPU structure.
7736 */
7737DECLINLINE(void) hmR0VmxClearIntWindowExitVmcs(PVMCPU pVCpu)
7738{
7739 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT);
7740 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT;
7741 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7742 AssertRC(rc);
7743 Log4(("Cleared interrupt-window exiting\n"));
7744}
7745
7746
7747/**
7748 * Sets the NMI-window exiting control in the VMCS which instructs VT-x to
7749 * cause a VM-exit as soon as the guest is in a state to receive NMIs.
7750 *
7751 * @param pVCpu The cross context virtual CPU structure.
7752 */
7753DECLINLINE(void) hmR0VmxSetNmiWindowExitVmcs(PVMCPU pVCpu)
7754{
7755 if (RT_LIKELY(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT))
7756 {
7757 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT))
7758 {
7759 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT;
7760 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7761 AssertRC(rc);
7762 Log4(("Setup NMI-window exiting\n"));
7763 }
7764 } /* else we will deliver NMIs whenever we VM-exit next, even possibly nesting NMIs. Can't be helped on ancient CPUs. */
7765}
7766
7767
7768/**
7769 * Clears the NMI-window exiting control in the VMCS.
7770 *
7771 * @param pVCpu The cross context virtual CPU structure.
7772 */
7773DECLINLINE(void) hmR0VmxClearNmiWindowExitVmcs(PVMCPU pVCpu)
7774{
7775 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT);
7776 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT;
7777 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7778 AssertRC(rc);
7779 Log4(("Cleared NMI-window exiting\n"));
7780}
7781
7782
7783/**
7784 * Evaluates the event to be delivered to the guest and sets it as the pending
7785 * event.
7786 *
7787 * @returns The VT-x guest-interruptibility state.
7788 * @param pVCpu The cross context virtual CPU structure.
7789 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7790 * out-of-sync. Make sure to update the required fields
7791 * before using them.
7792 */
7793static uint32_t hmR0VmxEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7794{
7795 /* Get the current interruptibility-state of the guest and then figure out what can be injected. */
7796 uint32_t const uIntrState = hmR0VmxGetGuestIntrState(pVCpu, pMixedCtx);
7797 bool const fBlockMovSS = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS);
7798 bool const fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
7799 bool const fBlockNmi = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI);
7800
7801 Assert(!fBlockSti || HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS));
7802 Assert(!(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
7803 Assert(!fBlockSti || pMixedCtx->eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
7804 Assert(!TRPMHasTrap(pVCpu));
7805
7806 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
7807 APICUpdatePendingInterrupts(pVCpu);
7808
7809 /*
7810 * Toggling of interrupt force-flags here is safe since we update TRPM on premature exits
7811 * to ring-3 before executing guest code, see hmR0VmxExitToRing3(). We must NOT restore these force-flags.
7812 */
7813 /** @todo SMI. SMIs take priority over NMIs. */
7814 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts. */
7815 {
7816 /* On some CPUs block-by-STI also blocks NMIs. See Intel spec. 26.3.1.5 "Checks On Guest Non-Register State". */
7817 if ( !pVCpu->hm.s.Event.fPending
7818 && !fBlockNmi
7819 && !fBlockSti
7820 && !fBlockMovSS)
7821 {
7822 Log4(("Pending NMI vcpu[%RU32]\n", pVCpu->idCpu));
7823 uint32_t u32IntInfo = X86_XCPT_NMI | VMX_EXIT_INTERRUPTION_INFO_VALID;
7824 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7825
7826 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7827 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
7828 }
7829 else
7830 hmR0VmxSetNmiWindowExitVmcs(pVCpu);
7831 }
7832 /*
7833 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
7834 * a valid interrupt we must- deliver the interrupt. We can no longer re-request it from the APIC.
7835 */
7836 else if ( VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC))
7837 && !pVCpu->hm.s.fSingleInstruction)
7838 {
7839 Assert(!DBGFIsStepping(pVCpu));
7840 int rc = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
7841 AssertRC(rc);
7842 bool const fBlockInt = !(pMixedCtx->eflags.u32 & X86_EFL_IF);
7843 if ( !pVCpu->hm.s.Event.fPending
7844 && !fBlockInt
7845 && !fBlockSti
7846 && !fBlockMovSS)
7847 {
7848 uint8_t u8Interrupt;
7849 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
7850 if (RT_SUCCESS(rc))
7851 {
7852 Log4(("Pending interrupt vcpu[%RU32] u8Interrupt=%#x \n", pVCpu->idCpu, u8Interrupt));
7853 uint32_t u32IntInfo = u8Interrupt | VMX_EXIT_INTERRUPTION_INFO_VALID;
7854 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7855
7856 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrfaultAddress */);
7857 }
7858 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
7859 {
7860 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
7861 hmR0VmxApicSetTprThreshold(pVCpu, u8Interrupt >> 4);
7862 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
7863
7864 /*
7865 * If the CPU doesn't have TPR shadowing, we will always get a VM-exit on TPR changes and
7866 * APICSetTpr() will end up setting the VMCPU_FF_INTERRUPT_APIC if required, so there is no
7867 * need to re-set this force-flag here.
7868 */
7869 }
7870 else
7871 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
7872 }
7873 else
7874 hmR0VmxSetIntWindowExitVmcs(pVCpu);
7875 }
7876
7877 return uIntrState;
7878}
7879
7880
7881/**
7882 * Sets a pending-debug exception to be delivered to the guest if the guest is
7883 * single-stepping in the VMCS.
7884 *
7885 * @param pVCpu The cross context virtual CPU structure.
7886 */
7887DECLINLINE(void) hmR0VmxSetPendingDebugXcptVmcs(PVMCPU pVCpu)
7888{
7889 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS)); NOREF(pVCpu);
7890 int rc = VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, VMX_VMCS_GUEST_DEBUG_EXCEPTIONS_BS);
7891 AssertRC(rc);
7892}
7893
7894
7895/**
7896 * Injects any pending events into the guest if the guest is in a state to
7897 * receive them.
7898 *
7899 * @returns Strict VBox status code (i.e. informational status codes too).
7900 * @param pVCpu The cross context virtual CPU structure.
7901 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7902 * out-of-sync. Make sure to update the required fields
7903 * before using them.
7904 * @param uIntrState The VT-x guest-interruptibility state.
7905 * @param fStepping Running in hmR0VmxRunGuestCodeStep() and we should
7906 * return VINF_EM_DBG_STEPPED if the event was
7907 * dispatched directly.
7908 */
7909static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t uIntrState, bool fStepping)
7910{
7911 HMVMX_ASSERT_PREEMPT_SAFE();
7912 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7913
7914 bool fBlockMovSS = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS);
7915 bool fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
7916
7917 Assert(!fBlockSti || HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS));
7918 Assert(!(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
7919 Assert(!fBlockSti || pMixedCtx->eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
7920 Assert(!TRPMHasTrap(pVCpu));
7921
7922 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
7923 if (pVCpu->hm.s.Event.fPending)
7924 {
7925 /*
7926 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
7927 * pending even while injecting an event and in this case, we want a VM-exit as soon as
7928 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
7929 *
7930 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
7931 */
7932 uint32_t const uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
7933#ifdef VBOX_STRICT
7934 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
7935 {
7936 bool const fBlockInt = !(pMixedCtx->eflags.u32 & X86_EFL_IF);
7937 Assert(!fBlockInt);
7938 Assert(!fBlockSti);
7939 Assert(!fBlockMovSS);
7940 }
7941 else if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
7942 {
7943 bool const fBlockNmi = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI);
7944 Assert(!fBlockSti);
7945 Assert(!fBlockMovSS);
7946 Assert(!fBlockNmi);
7947 }
7948#endif
7949 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#x\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
7950 (uint8_t)uIntType));
7951 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pMixedCtx, pVCpu->hm.s.Event.u64IntInfo, pVCpu->hm.s.Event.cbInstr,
7952 pVCpu->hm.s.Event.u32ErrCode, pVCpu->hm.s.Event.GCPtrFaultAddress,
7953 fStepping, &uIntrState);
7954 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
7955
7956 /* Update the interruptibility-state as it could have been changed by
7957 hmR0VmxInjectEventVmcs() (e.g. real-on-v86 guest injecting software interrupts) */
7958 fBlockMovSS = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS);
7959 fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
7960
7961 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
7962 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
7963 else
7964 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
7965 }
7966
7967 /* Deliver pending debug exception if the guest is single-stepping. Evaluate and set the BS bit. */
7968 if ( fBlockSti
7969 || fBlockMovSS)
7970 {
7971 if (!pVCpu->hm.s.fSingleInstruction)
7972 {
7973 /*
7974 * The pending-debug exceptions field is cleared on all VM-exits except VMX_EXIT_TPR_BELOW_THRESHOLD,
7975 * VMX_EXIT_MTF, VMX_EXIT_APIC_WRITE and VMX_EXIT_VIRTUALIZED_EOI.
7976 * See Intel spec. 27.3.4 "Saving Non-Register State".
7977 */
7978 Assert(!DBGFIsStepping(pVCpu));
7979 int rc2 = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
7980 AssertRCReturn(rc2, rc2);
7981 if (pMixedCtx->eflags.Bits.u1TF)
7982 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
7983 }
7984 else if (pMixedCtx->eflags.Bits.u1TF)
7985 {
7986 /*
7987 * We are single-stepping in the hypervisor debugger using EFLAGS.TF. Clear interrupt inhibition as setting the
7988 * BS bit would mean delivering a #DB to the guest upon VM-entry when it shouldn't be.
7989 */
7990 Assert(!(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG));
7991 uIntrState = 0;
7992 }
7993 }
7994
7995 /*
7996 * There's no need to clear the VM-entry interruption-information field here if we're not injecting anything.
7997 * VT-x clears the valid bit on every VM-exit. See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
7998 */
7999 int rc2 = hmR0VmxLoadGuestIntrState(pVCpu, uIntrState);
8000 AssertRC(rc2);
8001
8002 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
8003 NOREF(fBlockMovSS); NOREF(fBlockSti);
8004 return rcStrict;
8005}
8006
8007
8008/**
8009 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
8010 *
8011 * @param pVCpu The cross context virtual CPU structure.
8012 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8013 * out-of-sync. Make sure to update the required fields
8014 * before using them.
8015 */
8016DECLINLINE(void) hmR0VmxSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
8017{
8018 NOREF(pMixedCtx);
8019 uint32_t u32IntInfo = X86_XCPT_UD | VMX_EXIT_INTERRUPTION_INFO_VALID;
8020 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
8021}
8022
8023
8024/**
8025 * Injects a double-fault (\#DF) exception into the VM.
8026 *
8027 * @returns Strict VBox status code (i.e. informational status codes too).
8028 * @param pVCpu The cross context virtual CPU structure.
8029 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8030 * out-of-sync. Make sure to update the required fields
8031 * before using them.
8032 * @param fStepping Whether we're running in hmR0VmxRunGuestCodeStep()
8033 * and should return VINF_EM_DBG_STEPPED if the event
8034 * is injected directly (register modified by us, not
8035 * by hardware on VM-entry).
8036 * @param puIntrState Pointer to the current guest interruptibility-state.
8037 * This interruptibility-state will be updated if
8038 * necessary. This cannot not be NULL.
8039 */
8040DECLINLINE(VBOXSTRICTRC) hmR0VmxInjectXcptDF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fStepping, uint32_t *puIntrState)
8041{
8042 uint32_t u32IntInfo = X86_XCPT_DF | VMX_EXIT_INTERRUPTION_INFO_VALID;
8043 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8044 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
8045 return hmR0VmxInjectEventVmcs(pVCpu, pMixedCtx, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */,
8046 fStepping, puIntrState);
8047}
8048
8049
8050/**
8051 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
8052 *
8053 * @param pVCpu The cross context virtual CPU structure.
8054 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8055 * out-of-sync. Make sure to update the required fields
8056 * before using them.
8057 */
8058DECLINLINE(void) hmR0VmxSetPendingXcptDB(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
8059{
8060 NOREF(pMixedCtx);
8061 uint32_t u32IntInfo = X86_XCPT_DB | VMX_EXIT_INTERRUPTION_INFO_VALID;
8062 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8063 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
8064}
8065
8066
8067/**
8068 * Sets an overflow (\#OF) exception as pending-for-injection into the VM.
8069 *
8070 * @param pVCpu The cross context virtual CPU structure.
8071 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8072 * out-of-sync. Make sure to update the required fields
8073 * before using them.
8074 * @param cbInstr The value of RIP that is to be pushed on the guest
8075 * stack.
8076 */
8077DECLINLINE(void) hmR0VmxSetPendingXcptOF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t cbInstr)
8078{
8079 NOREF(pMixedCtx);
8080 uint32_t u32IntInfo = X86_XCPT_OF | VMX_EXIT_INTERRUPTION_INFO_VALID;
8081 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8082 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
8083}
8084
8085
8086/**
8087 * Injects a general-protection (\#GP) fault into the VM.
8088 *
8089 * @returns Strict VBox status code (i.e. informational status codes too).
8090 * @param pVCpu The cross context virtual CPU structure.
8091 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8092 * out-of-sync. Make sure to update the required fields
8093 * before using them.
8094 * @param fErrorCodeValid Whether the error code is valid (depends on the CPU
8095 * mode, i.e. in real-mode it's not valid).
8096 * @param u32ErrorCode The error code associated with the \#GP.
8097 * @param fStepping Whether we're running in
8098 * hmR0VmxRunGuestCodeStep() and should return
8099 * VINF_EM_DBG_STEPPED if the event is injected
8100 * directly (register modified by us, not by
8101 * hardware on VM-entry).
8102 * @param puIntrState Pointer to the current guest interruptibility-state.
8103 * This interruptibility-state will be updated if
8104 * necessary. This cannot not be NULL.
8105 */
8106DECLINLINE(VBOXSTRICTRC) hmR0VmxInjectXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fErrorCodeValid, uint32_t u32ErrorCode,
8107 bool fStepping, uint32_t *puIntrState)
8108{
8109 uint32_t u32IntInfo = X86_XCPT_GP | VMX_EXIT_INTERRUPTION_INFO_VALID;
8110 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8111 if (fErrorCodeValid)
8112 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
8113 return hmR0VmxInjectEventVmcs(pVCpu, pMixedCtx, u32IntInfo, 0 /* cbInstr */, u32ErrorCode, 0 /* GCPtrFaultAddress */,
8114 fStepping, puIntrState);
8115}
8116
8117
8118#if 0 /* unused */
8119/**
8120 * Sets a general-protection (\#GP) exception as pending-for-injection into the
8121 * VM.
8122 *
8123 * @param pVCpu The cross context virtual CPU structure.
8124 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8125 * out-of-sync. Make sure to update the required fields
8126 * before using them.
8127 * @param u32ErrorCode The error code associated with the \#GP.
8128 */
8129DECLINLINE(void) hmR0VmxSetPendingXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t u32ErrorCode)
8130{
8131 NOREF(pMixedCtx);
8132 uint32_t u32IntInfo = X86_XCPT_GP | VMX_EXIT_INTERRUPTION_INFO_VALID;
8133 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8134 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
8135 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrorCode, 0 /* GCPtrFaultAddress */);
8136}
8137#endif /* unused */
8138
8139
8140/**
8141 * Sets a software interrupt (INTn) as pending-for-injection into the VM.
8142 *
8143 * @param pVCpu The cross context virtual CPU structure.
8144 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8145 * out-of-sync. Make sure to update the required fields
8146 * before using them.
8147 * @param uVector The software interrupt vector number.
8148 * @param cbInstr The value of RIP that is to be pushed on the guest
8149 * stack.
8150 */
8151DECLINLINE(void) hmR0VmxSetPendingIntN(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint16_t uVector, uint32_t cbInstr)
8152{
8153 NOREF(pMixedCtx);
8154 uint32_t u32IntInfo = uVector | VMX_EXIT_INTERRUPTION_INFO_VALID;
8155 if ( uVector == X86_XCPT_BP
8156 || uVector == X86_XCPT_OF)
8157 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8158 else
8159 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
8160 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
8161}
8162
8163
8164/**
8165 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
8166 * stack.
8167 *
8168 * @returns Strict VBox status code (i.e. informational status codes too).
8169 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
8170 * @param pVM The cross context VM structure.
8171 * @param pMixedCtx Pointer to the guest-CPU context.
8172 * @param uValue The value to push to the guest stack.
8173 */
8174DECLINLINE(VBOXSTRICTRC) hmR0VmxRealModeGuestStackPush(PVM pVM, PCPUMCTX pMixedCtx, uint16_t uValue)
8175{
8176 /*
8177 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
8178 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
8179 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
8180 */
8181 if (pMixedCtx->sp == 1)
8182 return VINF_EM_RESET;
8183 pMixedCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
8184 int rc = PGMPhysSimpleWriteGCPhys(pVM, pMixedCtx->ss.u64Base + pMixedCtx->sp, &uValue, sizeof(uint16_t));
8185 AssertRC(rc);
8186 return rc;
8187}
8188
8189
8190/**
8191 * Injects an event into the guest upon VM-entry by updating the relevant fields
8192 * in the VM-entry area in the VMCS.
8193 *
8194 * @returns Strict VBox status code (i.e. informational status codes too).
8195 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
8196 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
8197 *
8198 * @param pVCpu The cross context virtual CPU structure.
8199 * @param pMixedCtx Pointer to the guest-CPU context. The data may
8200 * be out-of-sync. Make sure to update the required
8201 * fields before using them.
8202 * @param u64IntInfo The VM-entry interruption-information field.
8203 * @param cbInstr The VM-entry instruction length in bytes (for
8204 * software interrupts, exceptions and privileged
8205 * software exceptions).
8206 * @param u32ErrCode The VM-entry exception error code.
8207 * @param GCPtrFaultAddress The page-fault address for \#PF exceptions.
8208 * @param puIntrState Pointer to the current guest interruptibility-state.
8209 * This interruptibility-state will be updated if
8210 * necessary. This cannot not be NULL.
8211 * @param fStepping Whether we're running in
8212 * hmR0VmxRunGuestCodeStep() and should return
8213 * VINF_EM_DBG_STEPPED if the event is injected
8214 * directly (register modified by us, not by
8215 * hardware on VM-entry).
8216 *
8217 * @remarks Requires CR0!
8218 */
8219static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint64_t u64IntInfo, uint32_t cbInstr,
8220 uint32_t u32ErrCode, RTGCUINTREG GCPtrFaultAddress, bool fStepping,
8221 uint32_t *puIntrState)
8222{
8223 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
8224 AssertMsg(u64IntInfo >> 32 == 0, ("%#RX64\n", u64IntInfo));
8225 Assert(puIntrState);
8226 uint32_t u32IntInfo = (uint32_t)u64IntInfo;
8227
8228 uint32_t const uVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(u32IntInfo);
8229 uint32_t const uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(u32IntInfo);
8230
8231#ifdef VBOX_STRICT
8232 /* Validate the error-code-valid bit for hardware exceptions. */
8233 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT)
8234 {
8235 switch (uVector)
8236 {
8237 case X86_XCPT_PF:
8238 case X86_XCPT_DF:
8239 case X86_XCPT_TS:
8240 case X86_XCPT_NP:
8241 case X86_XCPT_SS:
8242 case X86_XCPT_GP:
8243 case X86_XCPT_AC:
8244 /* No error codes for exceptions in real-mode. See Intel spec. 20.1.4 "Interrupt and Exception Handling" */
8245 if (!CPUMIsGuestInRealModeEx(pMixedCtx))
8246 AssertMsg(VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(u32IntInfo),
8247 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
8248 /* fall thru */
8249 default:
8250 break;
8251 }
8252 }
8253#endif
8254
8255 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
8256 Assert( uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI
8257 || !(*puIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS));
8258
8259 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
8260
8261 /* We require CR0 to check if the guest is in real-mode. */
8262 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
8263 AssertRCReturn(rc, rc);
8264
8265 /*
8266 * Hardware interrupts & exceptions cannot be delivered through the software interrupt redirection bitmap to the real
8267 * mode task in virtual-8086 mode. We must jump to the interrupt handler in the (real-mode) guest.
8268 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode" for interrupt & exception classes.
8269 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8270 */
8271 if (CPUMIsGuestInRealModeEx(pMixedCtx))
8272 {
8273 PVM pVM = pVCpu->CTX_SUFF(pVM);
8274 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
8275 {
8276 Assert(PDMVmmDevHeapIsEnabled(pVM));
8277 Assert(pVM->hm.s.vmx.pRealModeTSS);
8278
8279 /* We require RIP, RSP, RFLAGS, CS, IDTR. Save the required ones from the VMCS. */
8280 rc = hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
8281 rc |= hmR0VmxSaveGuestTableRegs(pVCpu, pMixedCtx);
8282 rc |= hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
8283 AssertRCReturn(rc, rc);
8284 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RIP));
8285
8286 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8287 size_t const cbIdtEntry = sizeof(X86IDTR16);
8288 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pMixedCtx->idtr.cbIdt)
8289 {
8290 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8291 if (uVector == X86_XCPT_DF)
8292 return VINF_EM_RESET;
8293
8294 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault. */
8295 if (uVector == X86_XCPT_GP)
8296 return hmR0VmxInjectXcptDF(pVCpu, pMixedCtx, fStepping, puIntrState);
8297
8298 /* If we're injecting an interrupt/exception with no valid IDT entry, inject a general-protection fault. */
8299 /* No error codes for exceptions in real-mode. See Intel spec. 20.1.4 "Interrupt and Exception Handling" */
8300 return hmR0VmxInjectXcptGP(pVCpu, pMixedCtx, false /* fErrCodeValid */, 0 /* u32ErrCode */,
8301 fStepping, puIntrState);
8302 }
8303
8304 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8305 uint16_t uGuestIp = pMixedCtx->ip;
8306 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT)
8307 {
8308 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8309 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8310 uGuestIp = pMixedCtx->ip + (uint16_t)cbInstr;
8311 }
8312 else if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT)
8313 uGuestIp = pMixedCtx->ip + (uint16_t)cbInstr;
8314
8315 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8316 X86IDTR16 IdtEntry;
8317 RTGCPHYS GCPhysIdtEntry = (RTGCPHYS)pMixedCtx->idtr.pIdt + uVector * cbIdtEntry;
8318 rc = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8319 AssertRCReturn(rc, rc);
8320
8321 /* Construct the stack frame for the interrupt/exception handler. */
8322 VBOXSTRICTRC rcStrict;
8323 rcStrict = hmR0VmxRealModeGuestStackPush(pVM, pMixedCtx, pMixedCtx->eflags.u32);
8324 if (rcStrict == VINF_SUCCESS)
8325 rcStrict = hmR0VmxRealModeGuestStackPush(pVM, pMixedCtx, pMixedCtx->cs.Sel);
8326 if (rcStrict == VINF_SUCCESS)
8327 rcStrict = hmR0VmxRealModeGuestStackPush(pVM, pMixedCtx, uGuestIp);
8328
8329 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8330 if (rcStrict == VINF_SUCCESS)
8331 {
8332 pMixedCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8333 pMixedCtx->rip = IdtEntry.offSel;
8334 pMixedCtx->cs.Sel = IdtEntry.uSel;
8335 pMixedCtx->cs.ValidSel = IdtEntry.uSel;
8336 pMixedCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8337 if ( uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT
8338 && uVector == X86_XCPT_PF)
8339 pMixedCtx->cr2 = GCPtrFaultAddress;
8340
8341 /* If any other guest-state bits are changed here, make sure to update
8342 hmR0VmxPreRunGuestCommitted() when thread-context hooks are used. */
8343 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS
8344 | HM_CHANGED_GUEST_RIP
8345 | HM_CHANGED_GUEST_RFLAGS
8346 | HM_CHANGED_GUEST_RSP);
8347
8348 /* We're clearing interrupts, which means no block-by-STI interrupt-inhibition. */
8349 if (*puIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
8350 {
8351 Assert( uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI
8352 && uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT);
8353 Log4(("Clearing inhibition due to STI.\n"));
8354 *puIntrState &= ~VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI;
8355 }
8356 Log4(("Injecting real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8357 u32IntInfo, u32ErrCode, cbInstr, pMixedCtx->eflags.u, pMixedCtx->cs.Sel, pMixedCtx->eip));
8358
8359 /* The event has been truly dispatched. Mark it as no longer pending so we don't attempt to 'undo'
8360 it, if we are returning to ring-3 before executing guest code. */
8361 pVCpu->hm.s.Event.fPending = false;
8362
8363 /* Make hmR0VmxPreRunGuest return if we're stepping since we've changed cs:rip. */
8364 if (fStepping)
8365 rcStrict = VINF_EM_DBG_STEPPED;
8366 }
8367 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8368 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8369 return rcStrict;
8370 }
8371
8372 /*
8373 * For unrestricted execution enabled CPUs running real-mode guests, we must not set the deliver-error-code bit.
8374 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8375 */
8376 u32IntInfo &= ~VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
8377 }
8378
8379 /* Validate. */
8380 Assert(VMX_EXIT_INTERRUPTION_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
8381 Assert(!VMX_EXIT_INTERRUPTION_INFO_NMI_UNBLOCK_IRET(u32IntInfo)); /* Bit 12 MBZ. */
8382 Assert(!(u32IntInfo & 0x7ffff000)); /* Bits 30:12 MBZ. */
8383
8384 /* Inject. */
8385 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
8386 if (VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(u32IntInfo))
8387 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
8388 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
8389
8390 if ( VMX_EXIT_INTERRUPTION_INFO_TYPE(u32IntInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT
8391 && uVector == X86_XCPT_PF)
8392 pMixedCtx->cr2 = GCPtrFaultAddress;
8393
8394 Log4(("Injecting vcpu[%RU32] u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x pMixedCtx->uCR2=%#RX64\n", pVCpu->idCpu,
8395 u32IntInfo, u32ErrCode, cbInstr, pMixedCtx->cr2));
8396
8397 AssertRCReturn(rc, rc);
8398 return VINF_SUCCESS;
8399}
8400
8401
8402/**
8403 * Clears the interrupt-window exiting control in the VMCS and if necessary
8404 * clears the current event in the VMCS as well.
8405 *
8406 * @returns VBox status code.
8407 * @param pVCpu The cross context virtual CPU structure.
8408 *
8409 * @remarks Use this function only to clear events that have not yet been
8410 * delivered to the guest but are injected in the VMCS!
8411 * @remarks No-long-jump zone!!!
8412 */
8413static void hmR0VmxClearIntNmiWindowsVmcs(PVMCPU pVCpu)
8414{
8415 Log4Func(("vcpu[%d]\n", pVCpu->idCpu));
8416
8417 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT)
8418 hmR0VmxClearIntWindowExitVmcs(pVCpu);
8419
8420 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT)
8421 hmR0VmxClearNmiWindowExitVmcs(pVCpu);
8422}
8423
8424
8425/**
8426 * Enters the VT-x session.
8427 *
8428 * @returns VBox status code.
8429 * @param pVM The cross context VM structure.
8430 * @param pVCpu The cross context virtual CPU structure.
8431 * @param pCpu Pointer to the CPU info struct.
8432 */
8433VMMR0DECL(int) VMXR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
8434{
8435 AssertPtr(pVM);
8436 AssertPtr(pVCpu);
8437 Assert(pVM->hm.s.vmx.fSupported);
8438 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8439 NOREF(pCpu); NOREF(pVM);
8440
8441 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
8442 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
8443
8444#ifdef VBOX_STRICT
8445 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
8446 RTCCUINTREG uHostCR4 = ASMGetCR4();
8447 if (!(uHostCR4 & X86_CR4_VMXE))
8448 {
8449 LogRel(("VMXR0Enter: X86_CR4_VMXE bit in CR4 is not set!\n"));
8450 return VERR_VMX_X86_CR4_VMXE_CLEARED;
8451 }
8452#endif
8453
8454 /*
8455 * Load the VCPU's VMCS as the current (and active) one.
8456 */
8457 Assert(pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_CLEAR);
8458 int rc = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
8459 if (RT_FAILURE(rc))
8460 return rc;
8461
8462 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_ACTIVE;
8463 pVCpu->hm.s.fLeaveDone = false;
8464 Log4Func(("Activated Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8465
8466 return VINF_SUCCESS;
8467}
8468
8469
8470/**
8471 * The thread-context callback (only on platforms which support it).
8472 *
8473 * @param enmEvent The thread-context event.
8474 * @param pVCpu The cross context virtual CPU structure.
8475 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
8476 * @thread EMT(pVCpu)
8477 */
8478VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
8479{
8480 NOREF(fGlobalInit);
8481
8482 switch (enmEvent)
8483 {
8484 case RTTHREADCTXEVENT_OUT:
8485 {
8486 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8487 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8488 VMCPU_ASSERT_EMT(pVCpu);
8489
8490 PCPUMCTX pMixedCtx = CPUMQueryGuestCtxPtr(pVCpu);
8491
8492 /* No longjmps (logger flushes, locks) in this fragile context. */
8493 VMMRZCallRing3Disable(pVCpu);
8494 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
8495
8496 /*
8497 * Restore host-state (FPU, debug etc.)
8498 */
8499 if (!pVCpu->hm.s.fLeaveDone)
8500 {
8501 /* Do -not- save guest-state here as we might already be in the middle of saving it (esp. bad if we are
8502 holding the PGM lock while saving the guest state (see hmR0VmxSaveGuestControlRegs()). */
8503 hmR0VmxLeave(pVCpu, pMixedCtx, false /* fSaveGuestState */);
8504 pVCpu->hm.s.fLeaveDone = true;
8505 }
8506
8507 /* Leave HM context, takes care of local init (term). */
8508 int rc = HMR0LeaveCpu(pVCpu);
8509 AssertRC(rc); NOREF(rc);
8510
8511 /* Restore longjmp state. */
8512 VMMRZCallRing3Enable(pVCpu);
8513 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
8514 break;
8515 }
8516
8517 case RTTHREADCTXEVENT_IN:
8518 {
8519 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8520 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8521 VMCPU_ASSERT_EMT(pVCpu);
8522
8523 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
8524 VMMRZCallRing3Disable(pVCpu);
8525 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
8526
8527 /* Initialize the bare minimum state required for HM. This takes care of
8528 initializing VT-x if necessary (onlined CPUs, local init etc.) */
8529 int rc = HMR0EnterCpu(pVCpu);
8530 AssertRC(rc);
8531 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
8532
8533 /* Load the active VMCS as the current one. */
8534 if (pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_CLEAR)
8535 {
8536 rc = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
8537 AssertRC(rc); NOREF(rc);
8538 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_ACTIVE;
8539 Log4Func(("Resumed: Activated Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8540 }
8541 pVCpu->hm.s.fLeaveDone = false;
8542
8543 /* Restore longjmp state. */
8544 VMMRZCallRing3Enable(pVCpu);
8545 break;
8546 }
8547
8548 default:
8549 break;
8550 }
8551}
8552
8553
8554/**
8555 * Saves the host state in the VMCS host-state.
8556 * Sets up the VM-exit MSR-load area.
8557 *
8558 * The CPU state will be loaded from these fields on every successful VM-exit.
8559 *
8560 * @returns VBox status code.
8561 * @param pVM The cross context VM structure.
8562 * @param pVCpu The cross context virtual CPU structure.
8563 *
8564 * @remarks No-long-jump zone!!!
8565 */
8566static int hmR0VmxSaveHostState(PVM pVM, PVMCPU pVCpu)
8567{
8568 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8569
8570 int rc = VINF_SUCCESS;
8571 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_CONTEXT))
8572 {
8573 rc = hmR0VmxSaveHostControlRegs(pVM, pVCpu);
8574 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveHostControlRegisters failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8575
8576 rc = hmR0VmxSaveHostSegmentRegs(pVM, pVCpu);
8577 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveHostSegmentRegisters failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8578
8579 rc = hmR0VmxSaveHostMsrs(pVM, pVCpu);
8580 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveHostMsrs failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8581
8582 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT);
8583 }
8584 return rc;
8585}
8586
8587
8588/**
8589 * Saves the host state in the VMCS host-state.
8590 *
8591 * @returns VBox status code.
8592 * @param pVM The cross context VM structure.
8593 * @param pVCpu The cross context virtual CPU structure.
8594 *
8595 * @remarks No-long-jump zone!!!
8596 */
8597VMMR0DECL(int) VMXR0SaveHostState(PVM pVM, PVMCPU pVCpu)
8598{
8599 AssertPtr(pVM);
8600 AssertPtr(pVCpu);
8601
8602 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
8603
8604 /* Save the host state here while entering HM context. When thread-context hooks are used, we might get preempted
8605 and have to resave the host state but most of the time we won't be, so do it here before we disable interrupts. */
8606 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8607 return hmR0VmxSaveHostState(pVM, pVCpu);
8608}
8609
8610
8611/**
8612 * Loads the guest state into the VMCS guest-state area.
8613 *
8614 * The will typically be done before VM-entry when the guest-CPU state and the
8615 * VMCS state may potentially be out of sync.
8616 *
8617 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
8618 * VM-entry controls.
8619 * Sets up the appropriate VMX non-root function to execute guest code based on
8620 * the guest CPU mode.
8621 *
8622 * @returns VBox strict status code.
8623 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
8624 * without unrestricted guest access and the VMMDev is not presently
8625 * mapped (e.g. EFI32).
8626 *
8627 * @param pVM The cross context VM structure.
8628 * @param pVCpu The cross context virtual CPU structure.
8629 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8630 * out-of-sync. Make sure to update the required fields
8631 * before using them.
8632 *
8633 * @remarks No-long-jump zone!!!
8634 */
8635static VBOXSTRICTRC hmR0VmxLoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx)
8636{
8637 AssertPtr(pVM);
8638 AssertPtr(pVCpu);
8639 AssertPtr(pMixedCtx);
8640 HMVMX_ASSERT_PREEMPT_SAFE();
8641
8642 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
8643
8644 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
8645
8646 /* Determine real-on-v86 mode. */
8647 pVCpu->hm.s.vmx.RealMode.fRealOnV86Active = false;
8648 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
8649 && CPUMIsGuestInRealModeEx(pMixedCtx))
8650 {
8651 pVCpu->hm.s.vmx.RealMode.fRealOnV86Active = true;
8652 }
8653
8654 /*
8655 * Load the guest-state into the VMCS.
8656 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
8657 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
8658 */
8659 int rc = hmR0VmxSetupVMRunHandler(pVCpu, pMixedCtx);
8660 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8661
8662 /* This needs to be done after hmR0VmxSetupVMRunHandler() as changing pfnStartVM may require VM-entry control updates. */
8663 rc = hmR0VmxLoadGuestEntryCtls(pVCpu, pMixedCtx);
8664 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestEntryCtls! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8665
8666 /* This needs to be done after hmR0VmxSetupVMRunHandler() as changing pfnStartVM may require VM-exit control updates. */
8667 rc = hmR0VmxLoadGuestExitCtls(pVCpu, pMixedCtx);
8668 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSetupExitCtls failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8669
8670 rc = hmR0VmxLoadGuestActivityState(pVCpu, pMixedCtx);
8671 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestActivityState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8672
8673 VBOXSTRICTRC rcStrict = hmR0VmxLoadGuestCR3AndCR4(pVCpu, pMixedCtx);
8674 if (rcStrict == VINF_SUCCESS)
8675 { /* likely */ }
8676 else
8677 {
8678 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
8679 return rcStrict;
8680 }
8681
8682 /* Assumes pMixedCtx->cr0 is up-to-date (strict builds require CR0 for segment register validation checks). */
8683 rc = hmR0VmxLoadGuestSegmentRegs(pVCpu, pMixedCtx);
8684 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestSegmentRegs: rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8685
8686 /* This needs to be done after hmR0VmxLoadGuestEntryCtls() and hmR0VmxLoadGuestExitCtls() as it may alter controls if we
8687 determine we don't have to swap EFER after all. */
8688 rc = hmR0VmxLoadGuestMsrs(pVCpu, pMixedCtx);
8689 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestMsrs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8690
8691 rc = hmR0VmxLoadGuestApicState(pVCpu, pMixedCtx);
8692 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8693
8694 rc = hmR0VmxLoadGuestXcptIntercepts(pVCpu, pMixedCtx);
8695 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestXcptIntercepts! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8696
8697 /*
8698 * Loading Rflags here is fine, even though Rflags.TF might depend on guest debug state (which is not loaded here).
8699 * It is re-evaluated and updated if necessary in hmR0VmxLoadSharedState().
8700 */
8701 rc = hmR0VmxLoadGuestRipRspRflags(pVCpu, pMixedCtx);
8702 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestRipRspRflags! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8703
8704 /* Clear any unused and reserved bits. */
8705 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR2);
8706
8707 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
8708 return rc;
8709}
8710
8711
8712/**
8713 * Loads the state shared between the host and guest into the VMCS.
8714 *
8715 * @param pVM The cross context VM structure.
8716 * @param pVCpu The cross context virtual CPU structure.
8717 * @param pCtx Pointer to the guest-CPU context.
8718 *
8719 * @remarks No-long-jump zone!!!
8720 */
8721static void hmR0VmxLoadSharedState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
8722{
8723 NOREF(pVM);
8724
8725 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8726 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8727
8728 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
8729 {
8730 int rc = hmR0VmxLoadSharedCR0(pVCpu, pCtx);
8731 AssertRC(rc);
8732 }
8733
8734 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
8735 {
8736 int rc = hmR0VmxLoadSharedDebugState(pVCpu, pCtx);
8737 AssertRC(rc);
8738
8739 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
8740 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RFLAGS))
8741 {
8742 rc = hmR0VmxLoadGuestRflags(pVCpu, pCtx);
8743 AssertRC(rc);
8744 }
8745 }
8746
8747 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS))
8748 {
8749 hmR0VmxLazyLoadGuestMsrs(pVCpu, pCtx);
8750 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
8751 }
8752
8753 /* Loading CR0, debug state might have changed intercepts, update VMCS. */
8754 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
8755 {
8756 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_AC));
8757 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_DB));
8758 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVCpu->hm.s.vmx.u32XcptBitmap);
8759 AssertRC(rc);
8760 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
8761 }
8762
8763 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
8764 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8765}
8766
8767
8768/**
8769 * Worker for loading the guest-state bits in the inner VT-x execution loop.
8770 *
8771 * @returns Strict VBox status code (i.e. informational status codes too).
8772 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
8773 * without unrestricted guest access and the VMMDev is not presently
8774 * mapped (e.g. EFI32).
8775 *
8776 * @param pVM The cross context VM structure.
8777 * @param pVCpu The cross context virtual CPU structure.
8778 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8779 * out-of-sync. Make sure to update the required fields
8780 * before using them.
8781 *
8782 * @remarks No-long-jump zone!!!
8783 */
8784static VBOXSTRICTRC hmR0VmxLoadGuestStateOptimal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx)
8785{
8786 HMVMX_ASSERT_PREEMPT_SAFE();
8787 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8788 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8789
8790 Log5(("LoadFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8791#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
8792 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
8793#endif
8794
8795 /*
8796 * RIP is what changes the most often and hence if it's the only bit needing to be
8797 * updated, we shall handle it early for performance reasons.
8798 */
8799 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
8800 if (HMCPU_CF_IS_SET_ONLY(pVCpu, HM_CHANGED_GUEST_RIP))
8801 {
8802 rcStrict = hmR0VmxLoadGuestRip(pVCpu, pMixedCtx);
8803 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8804 { /* likely */}
8805 else
8806 {
8807 AssertMsgFailedReturn(("hmR0VmxLoadGuestStateOptimal: hmR0VmxLoadGuestRip failed! rc=%Rrc\n",
8808 VBOXSTRICTRC_VAL(rcStrict)), rcStrict);
8809 }
8810 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadMinimal);
8811 }
8812 else if (HMCPU_CF_VALUE(pVCpu))
8813 {
8814 rcStrict = hmR0VmxLoadGuestState(pVM, pVCpu, pMixedCtx);
8815 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8816 { /* likely */}
8817 else
8818 {
8819 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM,
8820 ("hmR0VmxLoadGuestStateOptimal: hmR0VmxLoadGuestState failed! rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8821 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8822 return rcStrict;
8823 }
8824 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
8825 }
8826
8827 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
8828 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
8829 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
8830 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8831 return rcStrict;
8832}
8833
8834
8835/**
8836 * Does the preparations before executing guest code in VT-x.
8837 *
8838 * This may cause longjmps to ring-3 and may even result in rescheduling to the
8839 * recompiler/IEM. We must be cautious what we do here regarding committing
8840 * guest-state information into the VMCS assuming we assuredly execute the
8841 * guest in VT-x mode.
8842 *
8843 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
8844 * the common-state (TRPM/forceflags), we must undo those changes so that the
8845 * recompiler/IEM can (and should) use them when it resumes guest execution.
8846 * Otherwise such operations must be done when we can no longer exit to ring-3.
8847 *
8848 * @returns Strict VBox status code (i.e. informational status codes too).
8849 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
8850 * have been disabled.
8851 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
8852 * double-fault into the guest.
8853 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
8854 * dispatched directly.
8855 * @retval VINF_* scheduling changes, we have to go back to ring-3.
8856 *
8857 * @param pVM The cross context VM structure.
8858 * @param pVCpu The cross context virtual CPU structure.
8859 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8860 * out-of-sync. Make sure to update the required fields
8861 * before using them.
8862 * @param pVmxTransient Pointer to the VMX transient structure.
8863 * @param fStepping Set if called from hmR0VmxRunGuestCodeStep(). Makes
8864 * us ignore some of the reasons for returning to
8865 * ring-3, and return VINF_EM_DBG_STEPPED if event
8866 * dispatching took place.
8867 */
8868static VBOXSTRICTRC hmR0VmxPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, bool fStepping)
8869{
8870 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8871
8872#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
8873 PGMRZDynMapFlushAutoSet(pVCpu);
8874#endif
8875
8876 /* Check force flag actions that might require us to go back to ring-3. */
8877 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVM, pVCpu, pMixedCtx, fStepping);
8878 if (rcStrict == VINF_SUCCESS)
8879 { /* FFs doesn't get set all the time. */ }
8880 else
8881 return rcStrict;
8882
8883#ifndef IEM_VERIFICATION_MODE_FULL
8884 /*
8885 * Setup the virtualized-APIC accesses.
8886 *
8887 * Note! This can cause a longjumps to R3 due to the acquisition of the PGM lock
8888 * in both PGMHandlerPhysicalReset() and IOMMMIOMapMMIOHCPage(), see @bugref{8721}.
8889 *
8890 * This is the reason we do it here and not in hmR0VmxLoadGuestState().
8891 */
8892 if ( !pVCpu->hm.s.vmx.u64MsrApicBase
8893 && (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
8894 && PDMHasApic(pVM))
8895 {
8896 uint64_t const u64MsrApicBase = APICGetBaseMsrNoCheck(pVCpu);
8897 Assert(u64MsrApicBase);
8898 Assert(pVM->hm.s.vmx.HCPhysApicAccess);
8899
8900 RTGCPHYS const GCPhysApicBase = u64MsrApicBase & PAGE_BASE_GC_MASK;
8901
8902 /* Unalias any existing mapping. */
8903 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
8904 AssertRCReturn(rc, rc);
8905
8906 /* Map the HC APIC-access page in place of the MMIO page, also updates the shadow page tables if necessary. */
8907 Log4(("hmR0VmxPreRunGuest: VCPU%u: Mapped HC APIC-access page at %#RGp\n", pVCpu->idCpu, GCPhysApicBase));
8908 rc = IOMMMIOMapMMIOHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hm.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
8909 AssertRCReturn(rc, rc);
8910
8911 /* Update the per-VCPU cache of the APIC base MSR. */
8912 pVCpu->hm.s.vmx.u64MsrApicBase = u64MsrApicBase;
8913 }
8914#endif /* !IEM_VERIFICATION_MODE_FULL */
8915
8916 if (TRPMHasTrap(pVCpu))
8917 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
8918 uint32_t uIntrState = hmR0VmxEvaluatePendingEvent(pVCpu, pMixedCtx);
8919
8920 /*
8921 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus needs to be done with
8922 * longjmps or interrupts + preemption enabled. Event injection might also result in triple-faulting the VM.
8923 */
8924 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pMixedCtx, uIntrState, fStepping);
8925 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8926 { /* likely */ }
8927 else
8928 {
8929 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8930 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8931 return rcStrict;
8932 }
8933
8934 /*
8935 * No longjmps to ring-3 from this point on!!!
8936 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
8937 * This also disables flushing of the R0-logger instance (if any).
8938 */
8939 VMMRZCallRing3Disable(pVCpu);
8940
8941 /*
8942 * Load the guest state bits.
8943 *
8944 * We cannot perform longjmps while loading the guest state because we do not preserve the
8945 * host/guest state (although the VMCS will be preserved) across longjmps which can cause
8946 * CPU migration.
8947 *
8948 * If we are injecting events to a real-on-v86 mode guest, we will have to update
8949 * RIP and some segment registers, i.e. hmR0VmxInjectPendingEvent()->hmR0VmxInjectEventVmcs().
8950 * Hence, loading of the guest state needs to be done -after- injection of events.
8951 */
8952 rcStrict = hmR0VmxLoadGuestStateOptimal(pVM, pVCpu, pMixedCtx);
8953 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8954 { /* likely */ }
8955 else
8956 {
8957 VMMRZCallRing3Enable(pVCpu);
8958 return rcStrict;
8959 }
8960
8961 /*
8962 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
8963 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
8964 *
8965 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
8966 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
8967 *
8968 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
8969 * executing guest code.
8970 */
8971 pVmxTransient->fEFlags = ASMIntDisableFlags();
8972
8973 if ( ( !VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
8974 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
8975 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
8976 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
8977 {
8978 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
8979 {
8980 pVCpu->hm.s.Event.fPending = false;
8981
8982 /*
8983 * We've injected any pending events. This is really the point of no return (to ring-3).
8984 *
8985 * Note! The caller expects to continue with interrupts & longjmps disabled on successful
8986 * returns from this function, so don't enable them here.
8987 */
8988 return VINF_SUCCESS;
8989 }
8990
8991 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
8992 rcStrict = VINF_EM_RAW_INTERRUPT;
8993 }
8994 else
8995 {
8996 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
8997 rcStrict = VINF_EM_RAW_TO_R3;
8998 }
8999
9000 ASMSetFlags(pVmxTransient->fEFlags);
9001 VMMRZCallRing3Enable(pVCpu);
9002
9003 return rcStrict;
9004}
9005
9006
9007/**
9008 * Prepares to run guest code in VT-x and we've committed to doing so. This
9009 * means there is no backing out to ring-3 or anywhere else at this
9010 * point.
9011 *
9012 * @param pVM The cross context VM structure.
9013 * @param pVCpu The cross context virtual CPU structure.
9014 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
9015 * out-of-sync. Make sure to update the required fields
9016 * before using them.
9017 * @param pVmxTransient Pointer to the VMX transient structure.
9018 *
9019 * @remarks Called with preemption disabled.
9020 * @remarks No-long-jump zone!!!
9021 */
9022static void hmR0VmxPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
9023{
9024 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9025 Assert(VMMR0IsLogFlushDisabled(pVCpu));
9026 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9027
9028 /*
9029 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
9030 */
9031 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
9032 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
9033
9034#ifdef HMVMX_ALWAYS_SWAP_FPU_STATE
9035 if (!CPUMIsGuestFPUStateActive(pVCpu))
9036 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
9037 HMCPU_CF_SET(pVCpu, HM_CHANGED_HOST_CONTEXT);
9038 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9039#endif
9040
9041 if ( pVCpu->hm.s.fPreloadGuestFpu
9042 && !CPUMIsGuestFPUStateActive(pVCpu))
9043 {
9044 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
9045 HMCPU_CF_SET(pVCpu, HM_CHANGED_HOST_CONTEXT);
9046 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0));
9047 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9048 }
9049
9050 /*
9051 * Lazy-update of the host MSRs values in the auto-load/store MSR area.
9052 */
9053 if ( !pVCpu->hm.s.vmx.fUpdatedHostMsrs
9054 && pVCpu->hm.s.vmx.cMsrs > 0)
9055 {
9056 hmR0VmxUpdateAutoLoadStoreHostMsrs(pVCpu);
9057 }
9058
9059 /*
9060 * Load the host state bits as we may've been preempted (only happens when
9061 * thread-context hooks are used or when hmR0VmxSetupVMRunHandler() changes pfnStartVM).
9062 * Note that the 64-on-32 switcher saves the (64-bit) host state into the VMCS and
9063 * if we change the switcher back to 32-bit, we *must* save the 32-bit host state here.
9064 * See @bugref{8432}.
9065 */
9066 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_CONTEXT))
9067 {
9068 int rc = hmR0VmxSaveHostState(pVM, pVCpu);
9069 AssertRC(rc);
9070 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreemptSaveHostState);
9071 }
9072 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_CONTEXT));
9073
9074 /*
9075 * Load the state shared between host and guest (FPU, debug, lazy MSRs).
9076 */
9077 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
9078 hmR0VmxLoadSharedState(pVM, pVCpu, pMixedCtx);
9079 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
9080
9081 /* Store status of the shared guest-host state at the time of VM-entry. */
9082#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
9083 if (CPUMIsGuestInLongModeEx(pMixedCtx))
9084 {
9085 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
9086 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
9087 }
9088 else
9089#endif
9090 {
9091 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
9092 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
9093 }
9094 pVmxTransient->fWasGuestFPUStateActive = CPUMIsGuestFPUStateActive(pVCpu);
9095
9096 /*
9097 * Cache the TPR-shadow for checking on every VM-exit if it might have changed.
9098 */
9099 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
9100 pVmxTransient->u8GuestTpr = pVCpu->hm.s.vmx.pbVirtApic[XAPIC_OFF_TPR];
9101
9102 PHMGLOBALCPUINFO pCpu = hmR0GetCurrentCpu();
9103 RTCPUID idCurrentCpu = pCpu->idCpu;
9104 if ( pVmxTransient->fUpdateTscOffsettingAndPreemptTimer
9105 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
9106 {
9107 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVM, pVCpu);
9108 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = false;
9109 }
9110
9111 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
9112 hmR0VmxFlushTaggedTlb(pVCpu, pCpu); /* Invalidate the appropriate guest entries from the TLB. */
9113 Assert(idCurrentCpu == pVCpu->hm.s.idLastCpu);
9114 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Update the error reporting info. with the current host CPU. */
9115
9116 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
9117
9118 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
9119 to start executing. */
9120
9121 /*
9122 * Load the TSC_AUX MSR when we are not intercepting RDTSCP.
9123 */
9124 if (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP)
9125 {
9126 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT))
9127 {
9128 bool fMsrUpdated;
9129 int rc2 = hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
9130 AssertRC(rc2);
9131 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS));
9132
9133 rc2 = hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_TSC_AUX, CPUMR0GetGuestTscAux(pVCpu), true /* fUpdateHostMsr */,
9134 &fMsrUpdated);
9135 AssertRC(rc2);
9136 Assert(fMsrUpdated || pVCpu->hm.s.vmx.fUpdatedHostMsrs);
9137
9138 /* Finally, mark that all host MSR values are updated so we don't redo it without leaving VT-x. See @bugref{6956}. */
9139 pVCpu->hm.s.vmx.fUpdatedHostMsrs = true;
9140 }
9141 else
9142 {
9143 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, MSR_K8_TSC_AUX);
9144 Assert(!pVCpu->hm.s.vmx.cMsrs || pVCpu->hm.s.vmx.fUpdatedHostMsrs);
9145 }
9146 }
9147
9148#ifdef VBOX_STRICT
9149 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu);
9150 hmR0VmxCheckHostEferMsr(pVCpu);
9151 AssertRC(hmR0VmxCheckVmcsCtls(pVCpu));
9152#endif
9153#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
9154 uint32_t uInvalidReason = hmR0VmxCheckGuestState(pVM, pVCpu, pMixedCtx);
9155 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
9156 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
9157#endif
9158}
9159
9160
9161/**
9162 * Performs some essential restoration of state after running guest code in
9163 * VT-x.
9164 *
9165 * @param pVM The cross context VM structure.
9166 * @param pVCpu The cross context virtual CPU structure.
9167 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
9168 * out-of-sync. Make sure to update the required fields
9169 * before using them.
9170 * @param pVmxTransient Pointer to the VMX transient structure.
9171 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
9172 *
9173 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
9174 *
9175 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
9176 * unconditionally when it is safe to do so.
9177 */
9178static void hmR0VmxPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, int rcVMRun)
9179{
9180 NOREF(pVM);
9181
9182 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9183
9184 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
9185 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
9186 HMVMXCPU_GST_RESET_TO(pVCpu, 0); /* Exits/longjmps to ring-3 requires saving the guest state. */
9187 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
9188 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
9189 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
9190
9191 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT))
9192 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVCpu->hm.s.vmx.u64TSCOffset);
9193
9194 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
9195 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
9196 Assert(!ASMIntAreEnabled());
9197 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
9198
9199#ifdef HMVMX_ALWAYS_SWAP_FPU_STATE
9200 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVM, pVCpu))
9201 {
9202 hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
9203 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9204 }
9205#endif
9206
9207#if HC_ARCH_BITS == 64
9208 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Host state messed up by VT-x, we must restore. */
9209#endif
9210#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
9211 /* The 64-on-32 switcher maintains uVmcsState on its own and we need to leave it alone here. */
9212 if (pVCpu->hm.s.vmx.pfnStartVM != VMXR0SwitcherStartVM64)
9213 pVCpu->hm.s.vmx.uVmcsState |= HMVMX_VMCS_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
9214#else
9215 pVCpu->hm.s.vmx.uVmcsState |= HMVMX_VMCS_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
9216#endif
9217#ifdef VBOX_STRICT
9218 hmR0VmxCheckHostEferMsr(pVCpu); /* Verify that VMRUN/VMLAUNCH didn't modify host EFER. */
9219#endif
9220 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
9221 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
9222
9223 /* Save the basic VM-exit reason. Refer Intel spec. 24.9.1 "Basic VM-exit Information". */
9224 uint32_t uExitReason;
9225 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
9226 rc |= hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
9227 AssertRC(rc);
9228 pVmxTransient->uExitReason = (uint16_t)VMX_EXIT_REASON_BASIC(uExitReason);
9229 pVmxTransient->fVMEntryFailed = VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uEntryIntInfo);
9230
9231 /* If the VMLAUNCH/VMRESUME failed, we can bail out early. This does -not- cover VMX_EXIT_ERR_*. */
9232 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
9233 {
9234 Log4(("VM-entry failure: pVCpu=%p idCpu=%RU32 rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", pVCpu, pVCpu->idCpu, rcVMRun,
9235 pVmxTransient->fVMEntryFailed));
9236 return;
9237 }
9238
9239 /*
9240 * Update the VM-exit history array here even if the VM-entry failed due to:
9241 * - Invalid guest state.
9242 * - MSR loading.
9243 * - Machine-check event.
9244 *
9245 * In any of the above cases we will still have a "valid" VM-exit reason
9246 * despite @a fVMEntryFailed being false.
9247 *
9248 * See Intel spec. 26.7 "VM-Entry failures during or after loading guest state".
9249 */
9250 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmxTransient->uExitReason);
9251
9252 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
9253 {
9254 /** @todo We can optimize this by only syncing with our force-flags when
9255 * really needed and keeping the VMCS state as it is for most
9256 * VM-exits. */
9257 /* Update the guest interruptibility-state from the VMCS. */
9258 hmR0VmxSaveGuestIntrState(pVCpu, pMixedCtx);
9259
9260#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
9261 rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
9262 AssertRC(rc);
9263#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
9264 rc = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
9265 AssertRC(rc);
9266#endif
9267
9268 /*
9269 * Sync the TPR shadow with our APIC state.
9270 */
9271 if ( (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
9272 && pVmxTransient->u8GuestTpr != pVCpu->hm.s.vmx.pbVirtApic[XAPIC_OFF_TPR])
9273 {
9274 rc = APICSetTpr(pVCpu, pVCpu->hm.s.vmx.pbVirtApic[XAPIC_OFF_TPR]);
9275 AssertRC(rc);
9276 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
9277 }
9278 }
9279}
9280
9281
9282/**
9283 * Runs the guest code using VT-x the normal way.
9284 *
9285 * @returns VBox status code.
9286 * @param pVM The cross context VM structure.
9287 * @param pVCpu The cross context virtual CPU structure.
9288 * @param pCtx Pointer to the guest-CPU context.
9289 *
9290 * @note Mostly the same as hmR0VmxRunGuestCodeStep().
9291 */
9292static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
9293{
9294 VMXTRANSIENT VmxTransient;
9295 VmxTransient.fUpdateTscOffsettingAndPreemptTimer = true;
9296 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
9297 uint32_t cLoops = 0;
9298
9299 for (;; cLoops++)
9300 {
9301 Assert(!HMR0SuspendPending());
9302 HMVMX_ASSERT_CPU_SAFE();
9303
9304 /* Preparatory work for running guest code, this may force us to return
9305 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
9306 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
9307 rcStrict = hmR0VmxPreRunGuest(pVM, pVCpu, pCtx, &VmxTransient, false /* fStepping */);
9308 if (rcStrict != VINF_SUCCESS)
9309 break;
9310
9311 hmR0VmxPreRunGuestCommitted(pVM, pVCpu, pCtx, &VmxTransient);
9312 int rcRun = hmR0VmxRunGuest(pVM, pVCpu, pCtx);
9313 /* The guest-CPU context is now outdated, 'pCtx' is to be treated as 'pMixedCtx' from this point on!!! */
9314
9315 /* Restore any residual host-state and save any bits shared between host
9316 and guest into the guest-CPU state. Re-enables interrupts! */
9317 hmR0VmxPostRunGuest(pVM, pVCpu, pCtx, &VmxTransient, rcRun);
9318
9319 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
9320 if (RT_SUCCESS(rcRun))
9321 { /* very likely */ }
9322 else
9323 {
9324 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
9325 hmR0VmxReportWorldSwitchError(pVM, pVCpu, rcRun, pCtx, &VmxTransient);
9326 return rcRun;
9327 }
9328
9329 /* Profile the VM-exit. */
9330 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
9331 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
9332 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
9333 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
9334 HMVMX_START_EXIT_DISPATCH_PROF();
9335
9336 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, pCtx, VmxTransient.uExitReason);
9337
9338 /* Handle the VM-exit. */
9339#ifdef HMVMX_USE_FUNCTION_TABLE
9340 rcStrict = g_apfnVMExitHandlers[VmxTransient.uExitReason](pVCpu, pCtx, &VmxTransient);
9341#else
9342 rcStrict = hmR0VmxHandleExit(pVCpu, pCtx, &VmxTransient, VmxTransient.uExitReason);
9343#endif
9344 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
9345 if (rcStrict == VINF_SUCCESS)
9346 {
9347 if (cLoops <= pVM->hm.s.cMaxResumeLoops)
9348 continue; /* likely */
9349 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
9350 rcStrict = VINF_EM_RAW_INTERRUPT;
9351 }
9352 break;
9353 }
9354
9355 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
9356 return rcStrict;
9357}
9358
9359
9360
9361/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
9362 * probes.
9363 *
9364 * The following few functions and associated structure contains the bloat
9365 * necessary for providing detailed debug events and dtrace probes as well as
9366 * reliable host side single stepping. This works on the principle of
9367 * "subclassing" the normal execution loop and workers. We replace the loop
9368 * method completely and override selected helpers to add necessary adjustments
9369 * to their core operation.
9370 *
9371 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
9372 * any performance for debug and analysis features.
9373 *
9374 * @{
9375 */
9376
9377/**
9378 * Transient per-VCPU debug state of VMCS and related info. we save/restore in
9379 * the debug run loop.
9380 */
9381typedef struct VMXRUNDBGSTATE
9382{
9383 /** The RIP we started executing at. This is for detecting that we stepped. */
9384 uint64_t uRipStart;
9385 /** The CS we started executing with. */
9386 uint16_t uCsStart;
9387
9388 /** Whether we've actually modified the 1st execution control field. */
9389 bool fModifiedProcCtls : 1;
9390 /** Whether we've actually modified the 2nd execution control field. */
9391 bool fModifiedProcCtls2 : 1;
9392 /** Whether we've actually modified the exception bitmap. */
9393 bool fModifiedXcptBitmap : 1;
9394
9395 /** We desire the modified the CR0 mask to be cleared. */
9396 bool fClearCr0Mask : 1;
9397 /** We desire the modified the CR4 mask to be cleared. */
9398 bool fClearCr4Mask : 1;
9399 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
9400 uint32_t fCpe1Extra;
9401 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
9402 uint32_t fCpe1Unwanted;
9403 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
9404 uint32_t fCpe2Extra;
9405 /** Extra stuff we need in VMX_VMCS32_CTRL_EXCEPTION_BITMAP. */
9406 uint32_t bmXcptExtra;
9407 /** The sequence number of the Dtrace provider settings the state was
9408 * configured against. */
9409 uint32_t uDtraceSettingsSeqNo;
9410 /** VM-exits to check (one bit per VM-exit). */
9411 uint32_t bmExitsToCheck[3];
9412
9413 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
9414 uint32_t fProcCtlsInitial;
9415 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
9416 uint32_t fProcCtls2Initial;
9417 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
9418 uint32_t bmXcptInitial;
9419} VMXRUNDBGSTATE;
9420AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
9421typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
9422
9423
9424/**
9425 * Initializes the VMXRUNDBGSTATE structure.
9426 *
9427 * @param pVCpu The cross context virtual CPU structure of the
9428 * calling EMT.
9429 * @param pCtx The CPU register context to go with @a pVCpu.
9430 * @param pDbgState The structure to initialize.
9431 */
9432DECLINLINE(void) hmR0VmxRunDebugStateInit(PVMCPU pVCpu, PCCPUMCTX pCtx, PVMXRUNDBGSTATE pDbgState)
9433{
9434 pDbgState->uRipStart = pCtx->rip;
9435 pDbgState->uCsStart = pCtx->cs.Sel;
9436
9437 pDbgState->fModifiedProcCtls = false;
9438 pDbgState->fModifiedProcCtls2 = false;
9439 pDbgState->fModifiedXcptBitmap = false;
9440 pDbgState->fClearCr0Mask = false;
9441 pDbgState->fClearCr4Mask = false;
9442 pDbgState->fCpe1Extra = 0;
9443 pDbgState->fCpe1Unwanted = 0;
9444 pDbgState->fCpe2Extra = 0;
9445 pDbgState->bmXcptExtra = 0;
9446 pDbgState->fProcCtlsInitial = pVCpu->hm.s.vmx.u32ProcCtls;
9447 pDbgState->fProcCtls2Initial = pVCpu->hm.s.vmx.u32ProcCtls2;
9448 pDbgState->bmXcptInitial = pVCpu->hm.s.vmx.u32XcptBitmap;
9449}
9450
9451
9452/**
9453 * Updates the VMSC fields with changes requested by @a pDbgState.
9454 *
9455 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
9456 * immediately before executing guest code, i.e. when interrupts are disabled.
9457 * We don't check status codes here as we cannot easily assert or return in the
9458 * latter case.
9459 *
9460 * @param pVCpu The cross context virtual CPU structure.
9461 * @param pDbgState The debug state.
9462 */
9463DECLINLINE(void) hmR0VmxPreRunGuestDebugStateApply(PVMCPU pVCpu, PVMXRUNDBGSTATE pDbgState)
9464{
9465 /*
9466 * Ensure desired flags in VMCS control fields are set.
9467 * (Ignoring write failure here, as we're committed and it's just debug extras.)
9468 *
9469 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
9470 * there should be no stale data in pCtx at this point.
9471 */
9472 if ( (pVCpu->hm.s.vmx.u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
9473 || (pVCpu->hm.s.vmx.u32ProcCtls & pDbgState->fCpe1Unwanted))
9474 {
9475 pVCpu->hm.s.vmx.u32ProcCtls |= pDbgState->fCpe1Extra;
9476 pVCpu->hm.s.vmx.u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
9477 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
9478 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVCpu->hm.s.vmx.u32ProcCtls));
9479 pDbgState->fModifiedProcCtls = true;
9480 }
9481
9482 if ((pVCpu->hm.s.vmx.u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
9483 {
9484 pVCpu->hm.s.vmx.u32ProcCtls2 |= pDbgState->fCpe2Extra;
9485 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVCpu->hm.s.vmx.u32ProcCtls2);
9486 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVCpu->hm.s.vmx.u32ProcCtls2));
9487 pDbgState->fModifiedProcCtls2 = true;
9488 }
9489
9490 if ((pVCpu->hm.s.vmx.u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
9491 {
9492 pVCpu->hm.s.vmx.u32XcptBitmap |= pDbgState->bmXcptExtra;
9493 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVCpu->hm.s.vmx.u32XcptBitmap);
9494 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVCpu->hm.s.vmx.u32XcptBitmap));
9495 pDbgState->fModifiedXcptBitmap = true;
9496 }
9497
9498 if (pDbgState->fClearCr0Mask && pVCpu->hm.s.vmx.u32CR0Mask != 0)
9499 {
9500 pVCpu->hm.s.vmx.u32CR0Mask = 0;
9501 VMXWriteVmcs32(VMX_VMCS_CTRL_CR0_MASK, 0);
9502 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS_CTRL_CR0_MASK: 0\n"));
9503 }
9504
9505 if (pDbgState->fClearCr4Mask && pVCpu->hm.s.vmx.u32CR4Mask != 0)
9506 {
9507 pVCpu->hm.s.vmx.u32CR4Mask = 0;
9508 VMXWriteVmcs32(VMX_VMCS_CTRL_CR4_MASK, 0);
9509 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS_CTRL_CR4_MASK: 0\n"));
9510 }
9511}
9512
9513
9514DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugStateRevert(PVMCPU pVCpu, PVMXRUNDBGSTATE pDbgState, VBOXSTRICTRC rcStrict)
9515{
9516 /*
9517 * Restore VM-exit control settings as we may not reenter this function the
9518 * next time around.
9519 */
9520 /* We reload the initial value, trigger what we can of recalculations the
9521 next time around. From the looks of things, that's all that's required atm. */
9522 if (pDbgState->fModifiedProcCtls)
9523 {
9524 if (!(pDbgState->fProcCtlsInitial & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
9525 pDbgState->fProcCtlsInitial |= VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
9526 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
9527 AssertRCReturn(rc2, rc2);
9528 pVCpu->hm.s.vmx.u32ProcCtls = pDbgState->fProcCtlsInitial;
9529 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0 | HM_CHANGED_GUEST_DEBUG);
9530 }
9531
9532 /* We're currently the only ones messing with this one, so just restore the
9533 cached value and reload the field. */
9534 if ( pDbgState->fModifiedProcCtls2
9535 && pVCpu->hm.s.vmx.u32ProcCtls2 != pDbgState->fProcCtls2Initial)
9536 {
9537 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
9538 AssertRCReturn(rc2, rc2);
9539 pVCpu->hm.s.vmx.u32ProcCtls2 = pDbgState->fProcCtls2Initial;
9540 }
9541
9542 /* If we've modified the exception bitmap, we restore it and trigger
9543 reloading and partial recalculation the next time around. */
9544 if (pDbgState->fModifiedXcptBitmap)
9545 {
9546 pVCpu->hm.s.vmx.u32XcptBitmap = pDbgState->bmXcptInitial;
9547 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS | HM_CHANGED_GUEST_CR0);
9548 }
9549
9550 /* We assume hmR0VmxLoadSharedCR0 will recalculate and load the CR0 mask. */
9551 if (pDbgState->fClearCr0Mask)
9552 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9553
9554 /* We assume hmR0VmxLoadGuestCR3AndCR4 will recalculate and load the CR4 mask. */
9555 if (pDbgState->fClearCr4Mask)
9556 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
9557
9558 return rcStrict;
9559}
9560
9561
9562/**
9563 * Configures VM-exit controls for current DBGF and DTrace settings.
9564 *
9565 * This updates @a pDbgState and the VMCS execution control fields to reflect
9566 * the necessary VM-exits demanded by DBGF and DTrace.
9567 *
9568 * @param pVM The cross context VM structure.
9569 * @param pVCpu The cross context virtual CPU structure.
9570 * @param pCtx Pointer to the guest-CPU context.
9571 * @param pDbgState The debug state.
9572 * @param pVmxTransient Pointer to the VMX transient structure. May update
9573 * fUpdateTscOffsettingAndPreemptTimer.
9574 */
9575static void hmR0VmxPreRunGuestDebugStateUpdate(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx,
9576 PVMXRUNDBGSTATE pDbgState, PVMXTRANSIENT pVmxTransient)
9577{
9578 /*
9579 * Take down the dtrace serial number so we can spot changes.
9580 */
9581 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
9582 ASMCompilerBarrier();
9583
9584 /*
9585 * We'll rebuild most of the middle block of data members (holding the
9586 * current settings) as we go along here, so start by clearing it all.
9587 */
9588 pDbgState->bmXcptExtra = 0;
9589 pDbgState->fCpe1Extra = 0;
9590 pDbgState->fCpe1Unwanted = 0;
9591 pDbgState->fCpe2Extra = 0;
9592 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
9593 pDbgState->bmExitsToCheck[i] = 0;
9594
9595 /*
9596 * Software interrupts (INT XXh) - no idea how to trigger these...
9597 */
9598 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
9599 || VBOXVMM_INT_SOFTWARE_ENABLED())
9600 {
9601 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
9602 }
9603
9604 /*
9605 * INT3 breakpoints - triggered by #BP exceptions.
9606 */
9607 if (pVM->dbgf.ro.cEnabledInt3Breakpoints > 0)
9608 pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
9609
9610 /*
9611 * Exception bitmap and XCPT events+probes.
9612 */
9613 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
9614 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
9615 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
9616
9617 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
9618 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
9619 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
9620 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
9621 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
9622 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
9623 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
9624 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
9625 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
9626 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
9627 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
9628 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
9629 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
9630 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
9631 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
9632 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
9633 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
9634 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
9635
9636 if (pDbgState->bmXcptExtra)
9637 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
9638
9639 /*
9640 * Process events and probes for VM-exits, making sure we get the wanted VM-exits.
9641 *
9642 * Note! This is the reverse of waft hmR0VmxHandleExitDtraceEvents does.
9643 * So, when adding/changing/removing please don't forget to update it.
9644 *
9645 * Some of the macros are picking up local variables to save horizontal space,
9646 * (being able to see it in a table is the lesser evil here).
9647 */
9648#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
9649 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
9650 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
9651#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
9652 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9653 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9654 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9655 } else do { } while (0)
9656#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
9657 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9658 { \
9659 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
9660 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9661 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9662 } else do { } while (0)
9663#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
9664 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9665 { \
9666 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
9667 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9668 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9669 } else do { } while (0)
9670#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
9671 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9672 { \
9673 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
9674 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9675 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9676 } else do { } while (0)
9677
9678 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
9679 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
9680 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
9681 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
9682 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
9683
9684 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
9685 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
9686 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
9687 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
9688 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT); /* paranoia */
9689 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
9690 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
9691 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
9692 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT);
9693 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
9694 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_VMCS_CTRL_PROC_EXEC_RDPMC_EXIT);
9695 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
9696 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT);
9697 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
9698 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
9699 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
9700 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
9701 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
9702 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
9703 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
9704 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
9705 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
9706 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
9707 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
9708 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
9709 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
9710 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
9711 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
9712 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
9713 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
9714 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
9715 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
9716 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
9717 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
9718 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
9719 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
9720
9721 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
9722 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
9723 {
9724 int rc2 = hmR0VmxSaveGuestCR0(pVCpu, pCtx);
9725 rc2 |= hmR0VmxSaveGuestCR4(pVCpu, pCtx);
9726 rc2 |= hmR0VmxSaveGuestApicState(pVCpu, pCtx);
9727 AssertRC(rc2);
9728
9729#if 0 /** @todo fix me */
9730 pDbgState->fClearCr0Mask = true;
9731 pDbgState->fClearCr4Mask = true;
9732#endif
9733 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
9734 pDbgState->fCpe1Extra |= VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT | VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT;
9735 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
9736 pDbgState->fCpe1Extra |= VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT | VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT;
9737 pDbgState->fCpe1Unwanted |= VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW; /* risky? */
9738 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
9739 require clearing here and in the loop if we start using it. */
9740 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
9741 }
9742 else
9743 {
9744 if (pDbgState->fClearCr0Mask)
9745 {
9746 pDbgState->fClearCr0Mask = false;
9747 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9748 }
9749 if (pDbgState->fClearCr4Mask)
9750 {
9751 pDbgState->fClearCr4Mask = false;
9752 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
9753 }
9754 }
9755 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
9756 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
9757
9758 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
9759 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
9760 {
9761 /** @todo later, need to fix handler as it assumes this won't usually happen. */
9762 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
9763 }
9764 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
9765 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
9766
9767 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS); /* risky clearing this? */
9768 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
9769 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS);
9770 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
9771 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_VMCS_CTRL_PROC_EXEC_MWAIT_EXIT); /* paranoia */
9772 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
9773 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_VMCS_CTRL_PROC_EXEC_MONITOR_EXIT); /* paranoia */
9774 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
9775#if 0 /** @todo too slow, fix handler. */
9776 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_VMCS_CTRL_PROC_EXEC_PAUSE_EXIT);
9777#endif
9778 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
9779
9780 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
9781 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
9782 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
9783 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
9784 {
9785 pDbgState->fCpe2Extra |= VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT;
9786 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XDTR_ACCESS);
9787 }
9788 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_XDTR_ACCESS);
9789 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_XDTR_ACCESS);
9790 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_XDTR_ACCESS);
9791 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_XDTR_ACCESS);
9792
9793 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
9794 || IS_EITHER_ENABLED(pVM, INSTR_STR)
9795 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
9796 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
9797 {
9798 pDbgState->fCpe2Extra |= VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT;
9799 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_TR_ACCESS);
9800 }
9801 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_TR_ACCESS);
9802 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_TR_ACCESS);
9803 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_TR_ACCESS);
9804 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_TR_ACCESS);
9805
9806 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
9807 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
9808 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT);
9809 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
9810 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
9811 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
9812 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT);
9813 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
9814 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
9815 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
9816 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT);
9817 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
9818 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT);
9819 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
9820 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
9821 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
9822 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_VMCS_CTRL_PROC_EXEC2_RDSEED_EXIT);
9823 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
9824 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
9825 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
9826 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
9827 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
9828
9829#undef IS_EITHER_ENABLED
9830#undef SET_ONLY_XBM_IF_EITHER_EN
9831#undef SET_CPE1_XBM_IF_EITHER_EN
9832#undef SET_CPEU_XBM_IF_EITHER_EN
9833#undef SET_CPE2_XBM_IF_EITHER_EN
9834
9835 /*
9836 * Sanitize the control stuff.
9837 */
9838 pDbgState->fCpe2Extra &= pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1;
9839 if (pDbgState->fCpe2Extra)
9840 pDbgState->fCpe1Extra |= VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL;
9841 pDbgState->fCpe1Extra &= pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1;
9842 pDbgState->fCpe1Unwanted &= ~pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0;
9843 if (pVCpu->hm.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT))
9844 {
9845 pVCpu->hm.s.fDebugWantRdTscExit ^= true;
9846 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
9847 }
9848
9849 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
9850 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
9851 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
9852 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
9853}
9854
9855
9856/**
9857 * Fires off DBGF events and dtrace probes for a VM-exit, when it's
9858 * appropriate.
9859 *
9860 * The caller has checked the VM-exit against the
9861 * VMXRUNDBGSTATE::bmExitsToCheck bitmap. The caller has checked for NMIs
9862 * already, so we don't have to do that either.
9863 *
9864 * @returns Strict VBox status code (i.e. informational status codes too).
9865 * @param pVM The cross context VM structure.
9866 * @param pVCpu The cross context virtual CPU structure.
9867 * @param pMixedCtx Pointer to the guest-CPU context.
9868 * @param pVmxTransient Pointer to the VMX-transient structure.
9869 * @param uExitReason The VM-exit reason.
9870 *
9871 * @remarks The name of this function is displayed by dtrace, so keep it short
9872 * and to the point. No longer than 33 chars long, please.
9873 */
9874static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx,
9875 PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
9876{
9877 /*
9878 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
9879 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
9880 *
9881 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
9882 * does. Must add/change/remove both places. Same ordering, please.
9883 *
9884 * Added/removed events must also be reflected in the next section
9885 * where we dispatch dtrace events.
9886 */
9887 bool fDtrace1 = false;
9888 bool fDtrace2 = false;
9889 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
9890 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
9891 uint32_t uEventArg = 0;
9892#define SET_EXIT(a_EventSubName) \
9893 do { \
9894 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
9895 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
9896 } while (0)
9897#define SET_BOTH(a_EventSubName) \
9898 do { \
9899 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
9900 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
9901 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
9902 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
9903 } while (0)
9904 switch (uExitReason)
9905 {
9906 case VMX_EXIT_MTF:
9907 return hmR0VmxExitMtf(pVCpu, pMixedCtx, pVmxTransient);
9908
9909 case VMX_EXIT_XCPT_OR_NMI:
9910 {
9911 uint8_t const idxVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo);
9912 switch (VMX_EXIT_INTERRUPTION_INFO_TYPE(pVmxTransient->uExitIntInfo))
9913 {
9914 case VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT:
9915 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT:
9916 case VMX_EXIT_INTERRUPTION_INFO_TYPE_PRIV_SW_XCPT:
9917 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
9918 {
9919 if (VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uExitIntInfo))
9920 {
9921 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
9922 uEventArg = pVmxTransient->uExitIntErrorCode;
9923 }
9924 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
9925 switch (enmEvent1)
9926 {
9927 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
9928 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
9929 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
9930 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
9931 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
9932 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
9933 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
9934 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
9935 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
9936 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
9937 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
9938 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
9939 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
9940 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
9941 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
9942 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
9943 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
9944 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
9945 default: break;
9946 }
9947 }
9948 else
9949 AssertFailed();
9950 break;
9951
9952 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT:
9953 uEventArg = idxVector;
9954 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
9955 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
9956 break;
9957 }
9958 break;
9959 }
9960
9961 case VMX_EXIT_TRIPLE_FAULT:
9962 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
9963 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
9964 break;
9965 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
9966 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
9967 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
9968 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
9969 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
9970
9971 /* Instruction specific VM-exits: */
9972 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
9973 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
9974 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
9975 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
9976 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
9977 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
9978 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
9979 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
9980 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
9981 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
9982 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
9983 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
9984 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
9985 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
9986 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
9987 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
9988 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
9989 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
9990 case VMX_EXIT_MOV_CRX:
9991 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
9992/** @todo r=bird: I feel these macros aren't very descriptive and needs to be at least 30 chars longer! ;-)
9993* Sensible abbreviations strongly recommended here because even with 130 columns this stuff get too wide! */
9994 if ( VMX_EXIT_QUALIFICATION_CRX_ACCESS(pVmxTransient->uExitQualification)
9995 == VMX_EXIT_QUALIFICATION_CRX_ACCESS_READ)
9996 SET_BOTH(CRX_READ);
9997 else
9998 SET_BOTH(CRX_WRITE);
9999 uEventArg = VMX_EXIT_QUALIFICATION_CRX_REGISTER(pVmxTransient->uExitQualification);
10000 break;
10001 case VMX_EXIT_MOV_DRX:
10002 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
10003 if ( VMX_EXIT_QUALIFICATION_DRX_DIRECTION(pVmxTransient->uExitQualification)
10004 == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_READ)
10005 SET_BOTH(DRX_READ);
10006 else
10007 SET_BOTH(DRX_WRITE);
10008 uEventArg = VMX_EXIT_QUALIFICATION_DRX_REGISTER(pVmxTransient->uExitQualification);
10009 break;
10010 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
10011 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
10012 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
10013 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
10014 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
10015 case VMX_EXIT_XDTR_ACCESS:
10016 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
10017 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_XDTR_INSINFO_INSTR_ID))
10018 {
10019 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
10020 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
10021 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
10022 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
10023 }
10024 break;
10025
10026 case VMX_EXIT_TR_ACCESS:
10027 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
10028 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_YYTR_INSINFO_INSTR_ID))
10029 {
10030 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
10031 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
10032 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
10033 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
10034 }
10035 break;
10036
10037 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
10038 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
10039 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
10040 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
10041 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
10042 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
10043 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
10044 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
10045 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
10046 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
10047 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
10048
10049 /* Events that aren't relevant at this point. */
10050 case VMX_EXIT_EXT_INT:
10051 case VMX_EXIT_INT_WINDOW:
10052 case VMX_EXIT_NMI_WINDOW:
10053 case VMX_EXIT_TPR_BELOW_THRESHOLD:
10054 case VMX_EXIT_PREEMPT_TIMER:
10055 case VMX_EXIT_IO_INSTR:
10056 break;
10057
10058 /* Errors and unexpected events. */
10059 case VMX_EXIT_INIT_SIGNAL:
10060 case VMX_EXIT_SIPI:
10061 case VMX_EXIT_IO_SMI:
10062 case VMX_EXIT_SMI:
10063 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
10064 case VMX_EXIT_ERR_MSR_LOAD:
10065 case VMX_EXIT_ERR_MACHINE_CHECK:
10066 break;
10067
10068 default:
10069 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
10070 break;
10071 }
10072#undef SET_BOTH
10073#undef SET_EXIT
10074
10075 /*
10076 * Dtrace tracepoints go first. We do them here at once so we don't
10077 * have to copy the guest state saving and stuff a few dozen times.
10078 * Down side is that we've got to repeat the switch, though this time
10079 * we use enmEvent since the probes are a subset of what DBGF does.
10080 */
10081 if (fDtrace1 || fDtrace2)
10082 {
10083 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
10084 hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
10085 switch (enmEvent1)
10086 {
10087 /** @todo consider which extra parameters would be helpful for each probe. */
10088 case DBGFEVENT_END: break;
10089 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pMixedCtx); break;
10090 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pMixedCtx, pMixedCtx->dr[6]); break;
10091 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pMixedCtx); break;
10092 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pMixedCtx); break;
10093 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pMixedCtx); break;
10094 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pMixedCtx); break;
10095 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pMixedCtx); break;
10096 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pMixedCtx); break;
10097 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pMixedCtx, uEventArg); break;
10098 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pMixedCtx, uEventArg); break;
10099 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pMixedCtx, uEventArg); break;
10100 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pMixedCtx, uEventArg); break;
10101 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pMixedCtx, uEventArg, pMixedCtx->cr2); break;
10102 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pMixedCtx); break;
10103 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pMixedCtx); break;
10104 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pMixedCtx); break;
10105 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pMixedCtx); break;
10106 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pMixedCtx, uEventArg); break;
10107 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10108 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pMixedCtx, pMixedCtx->eax, pMixedCtx->ecx); break;
10109 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pMixedCtx); break;
10110 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pMixedCtx); break;
10111 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pMixedCtx); break;
10112 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pMixedCtx); break;
10113 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pMixedCtx); break;
10114 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pMixedCtx); break;
10115 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pMixedCtx); break;
10116 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10117 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10118 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10119 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10120 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pMixedCtx, pMixedCtx->ecx); break;
10121 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pMixedCtx, pMixedCtx->ecx,
10122 RT_MAKE_U64(pMixedCtx->eax, pMixedCtx->edx)); break;
10123 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pMixedCtx); break;
10124 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pMixedCtx); break;
10125 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pMixedCtx); break;
10126 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pMixedCtx); break;
10127 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pMixedCtx); break;
10128 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pMixedCtx); break;
10129 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pMixedCtx); break;
10130 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pMixedCtx); break;
10131 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pMixedCtx); break;
10132 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pMixedCtx); break;
10133 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pMixedCtx); break;
10134 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pMixedCtx); break;
10135 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pMixedCtx); break;
10136 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pMixedCtx); break;
10137 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pMixedCtx); break;
10138 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pMixedCtx); break;
10139 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pMixedCtx); break;
10140 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pMixedCtx); break;
10141 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pMixedCtx); break;
10142 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pMixedCtx); break;
10143 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pMixedCtx); break;
10144 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pMixedCtx); break;
10145 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pMixedCtx); break;
10146 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pMixedCtx); break;
10147 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pMixedCtx); break;
10148 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pMixedCtx); break;
10149 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pMixedCtx); break;
10150 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pMixedCtx); break;
10151 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pMixedCtx); break;
10152 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pMixedCtx); break;
10153 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pMixedCtx); break;
10154 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pMixedCtx); break;
10155 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
10156 }
10157 switch (enmEvent2)
10158 {
10159 /** @todo consider which extra parameters would be helpful for each probe. */
10160 case DBGFEVENT_END: break;
10161 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pMixedCtx); break;
10162 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pMixedCtx, pMixedCtx->eax, pMixedCtx->ecx); break;
10163 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pMixedCtx); break;
10164 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pMixedCtx); break;
10165 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pMixedCtx); break;
10166 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pMixedCtx); break;
10167 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pMixedCtx); break;
10168 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pMixedCtx); break;
10169 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pMixedCtx); break;
10170 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10171 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10172 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10173 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
10174 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pMixedCtx, pMixedCtx->ecx); break;
10175 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pMixedCtx, pMixedCtx->ecx,
10176 RT_MAKE_U64(pMixedCtx->eax, pMixedCtx->edx)); break;
10177 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pMixedCtx); break;
10178 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pMixedCtx); break;
10179 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pMixedCtx); break;
10180 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pMixedCtx); break;
10181 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pMixedCtx); break;
10182 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pMixedCtx); break;
10183 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pMixedCtx); break;
10184 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pMixedCtx); break;
10185 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pMixedCtx); break;
10186 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pMixedCtx); break;
10187 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pMixedCtx); break;
10188 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pMixedCtx); break;
10189 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pMixedCtx); break;
10190 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pMixedCtx); break;
10191 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pMixedCtx); break;
10192 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pMixedCtx); break;
10193 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pMixedCtx); break;
10194 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pMixedCtx); break;
10195 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pMixedCtx); break;
10196 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pMixedCtx); break;
10197 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pMixedCtx); break;
10198 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pMixedCtx); break;
10199 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pMixedCtx); break;
10200 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pMixedCtx); break;
10201 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pMixedCtx); break;
10202 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pMixedCtx); break;
10203 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pMixedCtx); break;
10204 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pMixedCtx); break;
10205 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pMixedCtx); break;
10206 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pMixedCtx); break;
10207 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pMixedCtx); break;
10208 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pMixedCtx); break;
10209 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pMixedCtx); break;
10210 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pMixedCtx); break;
10211 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pMixedCtx); break;
10212 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pMixedCtx); break;
10213 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
10214 }
10215 }
10216
10217 /*
10218 * Fire of the DBGF event, if enabled (our check here is just a quick one,
10219 * the DBGF call will do a full check).
10220 *
10221 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
10222 * Note! If we have to events, we prioritize the first, i.e. the instruction
10223 * one, in order to avoid event nesting.
10224 */
10225 if ( enmEvent1 != DBGFEVENT_END
10226 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
10227 {
10228 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArg(pVM, pVCpu, enmEvent1, uEventArg, DBGFEVENTCTX_HM);
10229 if (rcStrict != VINF_SUCCESS)
10230 return rcStrict;
10231 }
10232 else if ( enmEvent2 != DBGFEVENT_END
10233 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
10234 {
10235 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArg(pVM, pVCpu, enmEvent2, uEventArg, DBGFEVENTCTX_HM);
10236 if (rcStrict != VINF_SUCCESS)
10237 return rcStrict;
10238 }
10239
10240 return VINF_SUCCESS;
10241}
10242
10243
10244/**
10245 * Single-stepping VM-exit filtering.
10246 *
10247 * This is preprocessing the VM-exits and deciding whether we've gotten far
10248 * enough to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit
10249 * handling is performed.
10250 *
10251 * @returns Strict VBox status code (i.e. informational status codes too).
10252 * @param pVM The cross context VM structure.
10253 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
10254 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
10255 * out-of-sync. Make sure to update the required
10256 * fields before using them.
10257 * @param pVmxTransient Pointer to the VMX-transient structure.
10258 * @param uExitReason The VM-exit reason.
10259 * @param pDbgState The debug state.
10260 */
10261DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient,
10262 uint32_t uExitReason, PVMXRUNDBGSTATE pDbgState)
10263{
10264 /*
10265 * Expensive (saves context) generic dtrace VM-exit probe.
10266 */
10267 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
10268 { /* more likely */ }
10269 else
10270 {
10271 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
10272 hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
10273 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, pMixedCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQualification);
10274 }
10275
10276 /*
10277 * Check for host NMI, just to get that out of the way.
10278 */
10279 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
10280 { /* normally likely */ }
10281 else
10282 {
10283 int rc2 = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
10284 AssertRCReturn(rc2, rc2);
10285 uint32_t uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(pVmxTransient->uExitIntInfo);
10286 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
10287 return hmR0VmxExitXcptOrNmi(pVCpu, pMixedCtx, pVmxTransient);
10288 }
10289
10290 /*
10291 * Check for single stepping event if we're stepping.
10292 */
10293 if (pVCpu->hm.s.fSingleInstruction)
10294 {
10295 switch (uExitReason)
10296 {
10297 case VMX_EXIT_MTF:
10298 return hmR0VmxExitMtf(pVCpu, pMixedCtx, pVmxTransient);
10299
10300 /* Various events: */
10301 case VMX_EXIT_XCPT_OR_NMI:
10302 case VMX_EXIT_EXT_INT:
10303 case VMX_EXIT_TRIPLE_FAULT:
10304 case VMX_EXIT_INT_WINDOW:
10305 case VMX_EXIT_NMI_WINDOW:
10306 case VMX_EXIT_TASK_SWITCH:
10307 case VMX_EXIT_TPR_BELOW_THRESHOLD:
10308 case VMX_EXIT_APIC_ACCESS:
10309 case VMX_EXIT_EPT_VIOLATION:
10310 case VMX_EXIT_EPT_MISCONFIG:
10311 case VMX_EXIT_PREEMPT_TIMER:
10312
10313 /* Instruction specific VM-exits: */
10314 case VMX_EXIT_CPUID:
10315 case VMX_EXIT_GETSEC:
10316 case VMX_EXIT_HLT:
10317 case VMX_EXIT_INVD:
10318 case VMX_EXIT_INVLPG:
10319 case VMX_EXIT_RDPMC:
10320 case VMX_EXIT_RDTSC:
10321 case VMX_EXIT_RSM:
10322 case VMX_EXIT_VMCALL:
10323 case VMX_EXIT_VMCLEAR:
10324 case VMX_EXIT_VMLAUNCH:
10325 case VMX_EXIT_VMPTRLD:
10326 case VMX_EXIT_VMPTRST:
10327 case VMX_EXIT_VMREAD:
10328 case VMX_EXIT_VMRESUME:
10329 case VMX_EXIT_VMWRITE:
10330 case VMX_EXIT_VMXOFF:
10331 case VMX_EXIT_VMXON:
10332 case VMX_EXIT_MOV_CRX:
10333 case VMX_EXIT_MOV_DRX:
10334 case VMX_EXIT_IO_INSTR:
10335 case VMX_EXIT_RDMSR:
10336 case VMX_EXIT_WRMSR:
10337 case VMX_EXIT_MWAIT:
10338 case VMX_EXIT_MONITOR:
10339 case VMX_EXIT_PAUSE:
10340 case VMX_EXIT_XDTR_ACCESS:
10341 case VMX_EXIT_TR_ACCESS:
10342 case VMX_EXIT_INVEPT:
10343 case VMX_EXIT_RDTSCP:
10344 case VMX_EXIT_INVVPID:
10345 case VMX_EXIT_WBINVD:
10346 case VMX_EXIT_XSETBV:
10347 case VMX_EXIT_RDRAND:
10348 case VMX_EXIT_INVPCID:
10349 case VMX_EXIT_VMFUNC:
10350 case VMX_EXIT_RDSEED:
10351 case VMX_EXIT_XSAVES:
10352 case VMX_EXIT_XRSTORS:
10353 {
10354 int rc2 = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
10355 rc2 |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
10356 AssertRCReturn(rc2, rc2);
10357 if ( pMixedCtx->rip != pDbgState->uRipStart
10358 || pMixedCtx->cs.Sel != pDbgState->uCsStart)
10359 return VINF_EM_DBG_STEPPED;
10360 break;
10361 }
10362
10363 /* Errors and unexpected events: */
10364 case VMX_EXIT_INIT_SIGNAL:
10365 case VMX_EXIT_SIPI:
10366 case VMX_EXIT_IO_SMI:
10367 case VMX_EXIT_SMI:
10368 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
10369 case VMX_EXIT_ERR_MSR_LOAD:
10370 case VMX_EXIT_ERR_MACHINE_CHECK:
10371 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
10372 break;
10373
10374 default:
10375 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
10376 break;
10377 }
10378 }
10379
10380 /*
10381 * Check for debugger event breakpoints and dtrace probes.
10382 */
10383 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
10384 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
10385 {
10386 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVM, pVCpu, pMixedCtx, pVmxTransient, uExitReason);
10387 if (rcStrict != VINF_SUCCESS)
10388 return rcStrict;
10389 }
10390
10391 /*
10392 * Normal processing.
10393 */
10394#ifdef HMVMX_USE_FUNCTION_TABLE
10395 return g_apfnVMExitHandlers[uExitReason](pVCpu, pMixedCtx, pVmxTransient);
10396#else
10397 return hmR0VmxHandleExit(pVCpu, pMixedCtx, pVmxTransient, uExitReason);
10398#endif
10399}
10400
10401
10402/**
10403 * Single steps guest code using VT-x.
10404 *
10405 * @returns Strict VBox status code (i.e. informational status codes too).
10406 * @param pVM The cross context VM structure.
10407 * @param pVCpu The cross context virtual CPU structure.
10408 * @param pCtx Pointer to the guest-CPU context.
10409 *
10410 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
10411 */
10412static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
10413{
10414 VMXTRANSIENT VmxTransient;
10415 VmxTransient.fUpdateTscOffsettingAndPreemptTimer = true;
10416
10417 /* Set HMCPU indicators. */
10418 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
10419 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
10420 pVCpu->hm.s.fDebugWantRdTscExit = false;
10421 pVCpu->hm.s.fUsingDebugLoop = true;
10422
10423 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
10424 VMXRUNDBGSTATE DbgState;
10425 hmR0VmxRunDebugStateInit(pVCpu, pCtx, &DbgState);
10426 hmR0VmxPreRunGuestDebugStateUpdate(pVM, pVCpu, pCtx, &DbgState, &VmxTransient);
10427
10428 /*
10429 * The loop.
10430 */
10431 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10432 for (uint32_t cLoops = 0; ; cLoops++)
10433 {
10434 Assert(!HMR0SuspendPending());
10435 HMVMX_ASSERT_CPU_SAFE();
10436 bool fStepping = pVCpu->hm.s.fSingleInstruction;
10437
10438 /*
10439 * Preparatory work for running guest code, this may force us to return
10440 * to ring-3. This bugger disables interrupts on VINF_SUCCESS!
10441 */
10442 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10443 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &DbgState); /* Set up execute controls the next to can respond to. */
10444 rcStrict = hmR0VmxPreRunGuest(pVM, pVCpu, pCtx, &VmxTransient, fStepping);
10445 if (rcStrict != VINF_SUCCESS)
10446 break;
10447
10448 hmR0VmxPreRunGuestCommitted(pVM, pVCpu, pCtx, &VmxTransient);
10449 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &DbgState); /* Override any obnoxious code in the above two calls. */
10450
10451 /*
10452 * Now we can run the guest code.
10453 */
10454 int rcRun = hmR0VmxRunGuest(pVM, pVCpu, pCtx);
10455
10456 /* The guest-CPU context is now outdated, 'pCtx' is to be treated as 'pMixedCtx' from this point on!!! */
10457
10458 /*
10459 * Restore any residual host-state and save any bits shared between host
10460 * and guest into the guest-CPU state. Re-enables interrupts!
10461 */
10462 hmR0VmxPostRunGuest(pVM, pVCpu, pCtx, &VmxTransient, rcRun);
10463
10464 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
10465 if (RT_SUCCESS(rcRun))
10466 { /* very likely */ }
10467 else
10468 {
10469 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
10470 hmR0VmxReportWorldSwitchError(pVM, pVCpu, rcRun, pCtx, &VmxTransient);
10471 return rcRun;
10472 }
10473
10474 /* Profile the VM-exit. */
10475 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10476 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10477 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10478 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
10479 HMVMX_START_EXIT_DISPATCH_PROF();
10480
10481 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, pCtx, VmxTransient.uExitReason);
10482
10483 /*
10484 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
10485 */
10486 rcStrict = hmR0VmxRunDebugHandleExit(pVM, pVCpu, pCtx, &VmxTransient, VmxTransient.uExitReason, &DbgState);
10487 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
10488 if (rcStrict != VINF_SUCCESS)
10489 break;
10490 if (cLoops > pVM->hm.s.cMaxResumeLoops)
10491 {
10492 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10493 rcStrict = VINF_EM_RAW_INTERRUPT;
10494 break;
10495 }
10496
10497 /*
10498 * Stepping: Did the RIP change, if so, consider it a single step.
10499 * Otherwise, make sure one of the TFs gets set.
10500 */
10501 if (fStepping)
10502 {
10503 int rc2 = hmR0VmxSaveGuestRip(pVCpu, pCtx);
10504 rc2 |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pCtx);
10505 AssertRCReturn(rc2, rc2);
10506 if ( pCtx->rip != DbgState.uRipStart
10507 || pCtx->cs.Sel != DbgState.uCsStart)
10508 {
10509 rcStrict = VINF_EM_DBG_STEPPED;
10510 break;
10511 }
10512 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
10513 }
10514
10515 /*
10516 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
10517 */
10518 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
10519 hmR0VmxPreRunGuestDebugStateUpdate(pVM, pVCpu, pCtx, &DbgState, &VmxTransient);
10520 }
10521
10522 /*
10523 * Clear the X86_EFL_TF if necessary.
10524 */
10525 if (pVCpu->hm.s.fClearTrapFlag)
10526 {
10527 int rc2 = hmR0VmxSaveGuestRflags(pVCpu, pCtx);
10528 AssertRCReturn(rc2, rc2);
10529 pVCpu->hm.s.fClearTrapFlag = false;
10530 pCtx->eflags.Bits.u1TF = 0;
10531 }
10532 /** @todo there seems to be issues with the resume flag when the monitor trap
10533 * flag is pending without being used. Seen early in bios init when
10534 * accessing APIC page in protected mode. */
10535
10536 /*
10537 * Restore VM-exit control settings as we may not reenter this function the
10538 * next time around.
10539 */
10540 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &DbgState, rcStrict);
10541
10542 /* Restore HMCPU indicators. */
10543 pVCpu->hm.s.fUsingDebugLoop = false;
10544 pVCpu->hm.s.fDebugWantRdTscExit = false;
10545 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
10546
10547 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
10548 return rcStrict;
10549}
10550
10551
10552/** @} */
10553
10554
10555/**
10556 * Checks if any expensive dtrace probes are enabled and we should go to the
10557 * debug loop.
10558 *
10559 * @returns true if we should use debug loop, false if not.
10560 */
10561static bool hmR0VmxAnyExpensiveProbesEnabled(void)
10562{
10563 /* It's probably faster to OR the raw 32-bit counter variables together.
10564 Since the variables are in an array and the probes are next to one
10565 another (more or less), we have good locality. So, better read
10566 eight-nine cache lines ever time and only have one conditional, than
10567 128+ conditionals, right? */
10568 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
10569 | VBOXVMM_XCPT_DE_ENABLED_RAW()
10570 | VBOXVMM_XCPT_DB_ENABLED_RAW()
10571 | VBOXVMM_XCPT_BP_ENABLED_RAW()
10572 | VBOXVMM_XCPT_OF_ENABLED_RAW()
10573 | VBOXVMM_XCPT_BR_ENABLED_RAW()
10574 | VBOXVMM_XCPT_UD_ENABLED_RAW()
10575 | VBOXVMM_XCPT_NM_ENABLED_RAW()
10576 | VBOXVMM_XCPT_DF_ENABLED_RAW()
10577 | VBOXVMM_XCPT_TS_ENABLED_RAW()
10578 | VBOXVMM_XCPT_NP_ENABLED_RAW()
10579 | VBOXVMM_XCPT_SS_ENABLED_RAW()
10580 | VBOXVMM_XCPT_GP_ENABLED_RAW()
10581 | VBOXVMM_XCPT_PF_ENABLED_RAW()
10582 | VBOXVMM_XCPT_MF_ENABLED_RAW()
10583 | VBOXVMM_XCPT_AC_ENABLED_RAW()
10584 | VBOXVMM_XCPT_XF_ENABLED_RAW()
10585 | VBOXVMM_XCPT_VE_ENABLED_RAW()
10586 | VBOXVMM_XCPT_SX_ENABLED_RAW()
10587 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
10588 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
10589 ) != 0
10590 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
10591 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
10592 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
10593 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
10594 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
10595 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
10596 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
10597 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
10598 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
10599 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
10600 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
10601 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
10602 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
10603 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
10604 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
10605 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
10606 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
10607 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
10608 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
10609 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
10610 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
10611 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
10612 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
10613 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
10614 | VBOXVMM_INSTR_STR_ENABLED_RAW()
10615 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
10616 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
10617 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
10618 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
10619 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
10620 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
10621 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
10622 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
10623 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
10624 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
10625 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
10626 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
10627 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
10628 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
10629 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
10630 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
10631 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
10632 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
10633 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
10634 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
10635 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
10636 ) != 0
10637 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
10638 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
10639 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
10640 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
10641 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
10642 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
10643 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
10644 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
10645 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
10646 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
10647 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
10648 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
10649 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
10650 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
10651 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
10652 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
10653 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
10654 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
10655 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
10656 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
10657 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
10658 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
10659 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
10660 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
10661 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
10662 | VBOXVMM_EXIT_STR_ENABLED_RAW()
10663 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
10664 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
10665 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
10666 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
10667 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
10668 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
10669 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
10670 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
10671 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
10672 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
10673 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
10674 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
10675 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
10676 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
10677 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
10678 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
10679 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
10680 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
10681 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
10682 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
10683 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
10684 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
10685 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
10686 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
10687 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
10688 ) != 0;
10689}
10690
10691
10692/**
10693 * Runs the guest code using VT-x.
10694 *
10695 * @returns Strict VBox status code (i.e. informational status codes too).
10696 * @param pVM The cross context VM structure.
10697 * @param pVCpu The cross context virtual CPU structure.
10698 * @param pCtx Pointer to the guest-CPU context.
10699 */
10700VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
10701{
10702 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10703 Assert(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL);
10704 HMVMX_ASSERT_PREEMPT_SAFE();
10705
10706 VMMRZCallRing3SetNotification(pVCpu, hmR0VmxCallRing3Callback, pCtx);
10707
10708 VBOXSTRICTRC rcStrict;
10709 if ( !pVCpu->hm.s.fUseDebugLoop
10710 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
10711 && !DBGFIsStepping(pVCpu)
10712 && !pVM->dbgf.ro.cEnabledInt3Breakpoints)
10713 rcStrict = hmR0VmxRunGuestCodeNormal(pVM, pVCpu, pCtx);
10714 else
10715 rcStrict = hmR0VmxRunGuestCodeDebug(pVM, pVCpu, pCtx);
10716
10717 if (rcStrict == VERR_EM_INTERPRETER)
10718 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
10719 else if (rcStrict == VINF_EM_RESET)
10720 rcStrict = VINF_EM_TRIPLE_FAULT;
10721
10722 int rc2 = hmR0VmxExitToRing3(pVM, pVCpu, pCtx, rcStrict);
10723 if (RT_FAILURE(rc2))
10724 {
10725 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
10726 rcStrict = rc2;
10727 }
10728 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
10729 return rcStrict;
10730}
10731
10732
10733#ifndef HMVMX_USE_FUNCTION_TABLE
10734DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, uint32_t rcReason)
10735{
10736# ifdef DEBUG_ramshankar
10737# define RETURN_EXIT_CALL(a_CallExpr) \
10738 do { \
10739 int rc2 = hmR0VmxSaveGuestState(pVCpu, pMixedCtx); AssertRC(rc2); \
10740 VBOXSTRICTRC rcStrict = a_CallExpr; \
10741 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST); \
10742 return rcStrict; \
10743 } while (0)
10744# else
10745# define RETURN_EXIT_CALL(a_CallExpr) return a_CallExpr
10746# endif
10747 switch (rcReason)
10748 {
10749 case VMX_EXIT_EPT_MISCONFIG: RETURN_EXIT_CALL(hmR0VmxExitEptMisconfig(pVCpu, pMixedCtx, pVmxTransient));
10750 case VMX_EXIT_EPT_VIOLATION: RETURN_EXIT_CALL(hmR0VmxExitEptViolation(pVCpu, pMixedCtx, pVmxTransient));
10751 case VMX_EXIT_IO_INSTR: RETURN_EXIT_CALL(hmR0VmxExitIoInstr(pVCpu, pMixedCtx, pVmxTransient));
10752 case VMX_EXIT_CPUID: RETURN_EXIT_CALL(hmR0VmxExitCpuid(pVCpu, pMixedCtx, pVmxTransient));
10753 case VMX_EXIT_RDTSC: RETURN_EXIT_CALL(hmR0VmxExitRdtsc(pVCpu, pMixedCtx, pVmxTransient));
10754 case VMX_EXIT_RDTSCP: RETURN_EXIT_CALL(hmR0VmxExitRdtscp(pVCpu, pMixedCtx, pVmxTransient));
10755 case VMX_EXIT_APIC_ACCESS: RETURN_EXIT_CALL(hmR0VmxExitApicAccess(pVCpu, pMixedCtx, pVmxTransient));
10756 case VMX_EXIT_XCPT_OR_NMI: RETURN_EXIT_CALL(hmR0VmxExitXcptOrNmi(pVCpu, pMixedCtx, pVmxTransient));
10757 case VMX_EXIT_MOV_CRX: RETURN_EXIT_CALL(hmR0VmxExitMovCRx(pVCpu, pMixedCtx, pVmxTransient));
10758 case VMX_EXIT_EXT_INT: RETURN_EXIT_CALL(hmR0VmxExitExtInt(pVCpu, pMixedCtx, pVmxTransient));
10759 case VMX_EXIT_INT_WINDOW: RETURN_EXIT_CALL(hmR0VmxExitIntWindow(pVCpu, pMixedCtx, pVmxTransient));
10760 case VMX_EXIT_MWAIT: RETURN_EXIT_CALL(hmR0VmxExitMwait(pVCpu, pMixedCtx, pVmxTransient));
10761 case VMX_EXIT_MONITOR: RETURN_EXIT_CALL(hmR0VmxExitMonitor(pVCpu, pMixedCtx, pVmxTransient));
10762 case VMX_EXIT_TASK_SWITCH: RETURN_EXIT_CALL(hmR0VmxExitTaskSwitch(pVCpu, pMixedCtx, pVmxTransient));
10763 case VMX_EXIT_PREEMPT_TIMER: RETURN_EXIT_CALL(hmR0VmxExitPreemptTimer(pVCpu, pMixedCtx, pVmxTransient));
10764 case VMX_EXIT_RDMSR: RETURN_EXIT_CALL(hmR0VmxExitRdmsr(pVCpu, pMixedCtx, pVmxTransient));
10765 case VMX_EXIT_WRMSR: RETURN_EXIT_CALL(hmR0VmxExitWrmsr(pVCpu, pMixedCtx, pVmxTransient));
10766 case VMX_EXIT_MOV_DRX: RETURN_EXIT_CALL(hmR0VmxExitMovDRx(pVCpu, pMixedCtx, pVmxTransient));
10767 case VMX_EXIT_TPR_BELOW_THRESHOLD: RETURN_EXIT_CALL(hmR0VmxExitTprBelowThreshold(pVCpu, pMixedCtx, pVmxTransient));
10768 case VMX_EXIT_HLT: RETURN_EXIT_CALL(hmR0VmxExitHlt(pVCpu, pMixedCtx, pVmxTransient));
10769 case VMX_EXIT_INVD: RETURN_EXIT_CALL(hmR0VmxExitInvd(pVCpu, pMixedCtx, pVmxTransient));
10770 case VMX_EXIT_INVLPG: RETURN_EXIT_CALL(hmR0VmxExitInvlpg(pVCpu, pMixedCtx, pVmxTransient));
10771 case VMX_EXIT_RSM: RETURN_EXIT_CALL(hmR0VmxExitRsm(pVCpu, pMixedCtx, pVmxTransient));
10772 case VMX_EXIT_MTF: RETURN_EXIT_CALL(hmR0VmxExitMtf(pVCpu, pMixedCtx, pVmxTransient));
10773 case VMX_EXIT_PAUSE: RETURN_EXIT_CALL(hmR0VmxExitPause(pVCpu, pMixedCtx, pVmxTransient));
10774 case VMX_EXIT_XDTR_ACCESS: RETURN_EXIT_CALL(hmR0VmxExitXdtrAccess(pVCpu, pMixedCtx, pVmxTransient));
10775 case VMX_EXIT_TR_ACCESS: RETURN_EXIT_CALL(hmR0VmxExitXdtrAccess(pVCpu, pMixedCtx, pVmxTransient));
10776 case VMX_EXIT_WBINVD: RETURN_EXIT_CALL(hmR0VmxExitWbinvd(pVCpu, pMixedCtx, pVmxTransient));
10777 case VMX_EXIT_XSETBV: RETURN_EXIT_CALL(hmR0VmxExitXsetbv(pVCpu, pMixedCtx, pVmxTransient));
10778 case VMX_EXIT_RDRAND: RETURN_EXIT_CALL(hmR0VmxExitRdrand(pVCpu, pMixedCtx, pVmxTransient));
10779 case VMX_EXIT_INVPCID: RETURN_EXIT_CALL(hmR0VmxExitInvpcid(pVCpu, pMixedCtx, pVmxTransient));
10780 case VMX_EXIT_GETSEC: RETURN_EXIT_CALL(hmR0VmxExitGetsec(pVCpu, pMixedCtx, pVmxTransient));
10781 case VMX_EXIT_RDPMC: RETURN_EXIT_CALL(hmR0VmxExitRdpmc(pVCpu, pMixedCtx, pVmxTransient));
10782 case VMX_EXIT_VMCALL: RETURN_EXIT_CALL(hmR0VmxExitVmcall(pVCpu, pMixedCtx, pVmxTransient));
10783
10784 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pMixedCtx, pVmxTransient);
10785 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pMixedCtx, pVmxTransient);
10786 case VMX_EXIT_INIT_SIGNAL: return hmR0VmxExitInitSignal(pVCpu, pMixedCtx, pVmxTransient);
10787 case VMX_EXIT_SIPI: return hmR0VmxExitSipi(pVCpu, pMixedCtx, pVmxTransient);
10788 case VMX_EXIT_IO_SMI: return hmR0VmxExitIoSmi(pVCpu, pMixedCtx, pVmxTransient);
10789 case VMX_EXIT_SMI: return hmR0VmxExitSmi(pVCpu, pMixedCtx, pVmxTransient);
10790 case VMX_EXIT_ERR_MSR_LOAD: return hmR0VmxExitErrMsrLoad(pVCpu, pMixedCtx, pVmxTransient);
10791 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pMixedCtx, pVmxTransient);
10792 case VMX_EXIT_ERR_MACHINE_CHECK: return hmR0VmxExitErrMachineCheck(pVCpu, pMixedCtx, pVmxTransient);
10793
10794 case VMX_EXIT_VMCLEAR:
10795 case VMX_EXIT_VMLAUNCH:
10796 case VMX_EXIT_VMPTRLD:
10797 case VMX_EXIT_VMPTRST:
10798 case VMX_EXIT_VMREAD:
10799 case VMX_EXIT_VMRESUME:
10800 case VMX_EXIT_VMWRITE:
10801 case VMX_EXIT_VMXOFF:
10802 case VMX_EXIT_VMXON:
10803 case VMX_EXIT_INVEPT:
10804 case VMX_EXIT_INVVPID:
10805 case VMX_EXIT_VMFUNC:
10806 case VMX_EXIT_XSAVES:
10807 case VMX_EXIT_XRSTORS:
10808 return hmR0VmxExitSetPendingXcptUD(pVCpu, pMixedCtx, pVmxTransient);
10809 case VMX_EXIT_ENCLS:
10810 case VMX_EXIT_RDSEED: /* only spurious VM-exits, so undefined */
10811 case VMX_EXIT_PML_FULL:
10812 default:
10813 return hmR0VmxExitErrUndefined(pVCpu, pMixedCtx, pVmxTransient);
10814 }
10815#undef RETURN_EXIT_CALL
10816}
10817#endif /* !HMVMX_USE_FUNCTION_TABLE */
10818
10819
10820#ifdef VBOX_STRICT
10821/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
10822# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
10823 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
10824
10825# define HMVMX_ASSERT_PREEMPT_CPUID() \
10826 do { \
10827 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
10828 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
10829 } while (0)
10830
10831# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS() \
10832 do { \
10833 AssertPtr(pVCpu); \
10834 AssertPtr(pMixedCtx); \
10835 AssertPtr(pVmxTransient); \
10836 Assert(pVmxTransient->fVMEntryFailed == false); \
10837 Assert(ASMIntAreEnabled()); \
10838 HMVMX_ASSERT_PREEMPT_SAFE(); \
10839 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
10840 Log4Func(("vcpu[%RU32] -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-v-v-v\n", pVCpu->idCpu)); \
10841 HMVMX_ASSERT_PREEMPT_SAFE(); \
10842 if (VMMR0IsLogFlushDisabled(pVCpu)) \
10843 HMVMX_ASSERT_PREEMPT_CPUID(); \
10844 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
10845 } while (0)
10846
10847# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS() \
10848 do { \
10849 Log4Func(("\n")); \
10850 } while (0)
10851#else /* nonstrict builds: */
10852# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS() \
10853 do { \
10854 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
10855 NOREF(pVCpu); NOREF(pMixedCtx); NOREF(pVmxTransient); \
10856 } while (0)
10857# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS() do { } while (0)
10858#endif
10859
10860
10861/**
10862 * Advances the guest RIP by the specified number of bytes.
10863 *
10864 * @param pVCpu The cross context virtual CPU structure.
10865 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
10866 * out-of-sync. Make sure to update the required fields
10867 * before using them.
10868 * @param cbInstr Number of bytes to advance the RIP by.
10869 *
10870 * @remarks No-long-jump zone!!!
10871 */
10872DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t cbInstr)
10873{
10874 /* Advance the RIP. */
10875 pMixedCtx->rip += cbInstr;
10876 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP);
10877
10878 /* Update interrupt inhibition. */
10879 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
10880 && pMixedCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
10881 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
10882}
10883
10884
10885/**
10886 * Advances the guest RIP after reading it from the VMCS.
10887 *
10888 * @returns VBox status code, no informational status codes.
10889 * @param pVCpu The cross context virtual CPU structure.
10890 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
10891 * out-of-sync. Make sure to update the required fields
10892 * before using them.
10893 * @param pVmxTransient Pointer to the VMX transient structure.
10894 *
10895 * @remarks No-long-jump zone!!!
10896 */
10897static int hmR0VmxAdvanceGuestRip(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
10898{
10899 int rc = hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
10900 rc |= hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
10901 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
10902 AssertRCReturn(rc, rc);
10903
10904 hmR0VmxAdvanceGuestRipBy(pVCpu, pMixedCtx, pVmxTransient->cbInstr);
10905
10906 /*
10907 * Deliver a debug exception to the guest if it is single-stepping. Don't directly inject a #DB but use the
10908 * pending debug exception field as it takes care of priority of events.
10909 *
10910 * See Intel spec. 32.2.1 "Debug Exceptions".
10911 */
10912 if ( !pVCpu->hm.s.fSingleInstruction
10913 && pMixedCtx->eflags.Bits.u1TF)
10914 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
10915
10916 return VINF_SUCCESS;
10917}
10918
10919
10920/**
10921 * Tries to determine what part of the guest-state VT-x has deemed as invalid
10922 * and update error record fields accordingly.
10923 *
10924 * @return VMX_IGS_* return codes.
10925 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
10926 * wrong with the guest state.
10927 *
10928 * @param pVM The cross context VM structure.
10929 * @param pVCpu The cross context virtual CPU structure.
10930 * @param pCtx Pointer to the guest-CPU state.
10931 *
10932 * @remarks This function assumes our cache of the VMCS controls
10933 * are valid, i.e. hmR0VmxCheckVmcsCtls() succeeded.
10934 */
10935static uint32_t hmR0VmxCheckGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
10936{
10937#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
10938#define HMVMX_CHECK_BREAK(expr, err) if (!(expr)) { \
10939 uError = (err); \
10940 break; \
10941 } else do { } while (0)
10942
10943 int rc;
10944 uint32_t uError = VMX_IGS_ERROR;
10945 uint32_t u32Val;
10946 bool fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuest;
10947
10948 do
10949 {
10950 /*
10951 * CR0.
10952 */
10953 uint32_t uSetCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
10954 uint32_t uZapCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
10955 /* Exceptions for unrestricted-guests for fixed CR0 bits (PE, PG).
10956 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
10957 if (fUnrestrictedGuest)
10958 uSetCR0 &= ~(X86_CR0_PE | X86_CR0_PG);
10959
10960 uint32_t u32GuestCR0;
10961 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR0, &u32GuestCR0);
10962 AssertRCBreak(rc);
10963 HMVMX_CHECK_BREAK((u32GuestCR0 & uSetCR0) == uSetCR0, VMX_IGS_CR0_FIXED1);
10964 HMVMX_CHECK_BREAK(!(u32GuestCR0 & ~uZapCR0), VMX_IGS_CR0_FIXED0);
10965 if ( !fUnrestrictedGuest
10966 && (u32GuestCR0 & X86_CR0_PG)
10967 && !(u32GuestCR0 & X86_CR0_PE))
10968 {
10969 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
10970 }
10971
10972 /*
10973 * CR4.
10974 */
10975 uint64_t uSetCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
10976 uint64_t uZapCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
10977
10978 uint32_t u32GuestCR4;
10979 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR4, &u32GuestCR4);
10980 AssertRCBreak(rc);
10981 HMVMX_CHECK_BREAK((u32GuestCR4 & uSetCR4) == uSetCR4, VMX_IGS_CR4_FIXED1);
10982 HMVMX_CHECK_BREAK(!(u32GuestCR4 & ~uZapCR4), VMX_IGS_CR4_FIXED0);
10983
10984 /*
10985 * IA32_DEBUGCTL MSR.
10986 */
10987 uint64_t u64Val;
10988 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
10989 AssertRCBreak(rc);
10990 if ( (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG)
10991 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
10992 {
10993 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
10994 }
10995 uint64_t u64DebugCtlMsr = u64Val;
10996
10997#ifdef VBOX_STRICT
10998 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
10999 AssertRCBreak(rc);
11000 Assert(u32Val == pVCpu->hm.s.vmx.u32EntryCtls);
11001#endif
11002 bool const fLongModeGuest = RT_BOOL(pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST);
11003
11004 /*
11005 * RIP and RFLAGS.
11006 */
11007 uint32_t u32Eflags;
11008#if HC_ARCH_BITS == 64
11009 rc = VMXReadVmcs64(VMX_VMCS_GUEST_RIP, &u64Val);
11010 AssertRCBreak(rc);
11011 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
11012 if ( !fLongModeGuest
11013 || !pCtx->cs.Attr.n.u1Long)
11014 {
11015 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
11016 }
11017 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
11018 * must be identical if the "IA-32e mode guest" VM-entry
11019 * control is 1 and CS.L is 1. No check applies if the
11020 * CPU supports 64 linear-address bits. */
11021
11022 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
11023 rc = VMXReadVmcs64(VMX_VMCS_GUEST_RFLAGS, &u64Val);
11024 AssertRCBreak(rc);
11025 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
11026 VMX_IGS_RFLAGS_RESERVED);
11027 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
11028 u32Eflags = u64Val;
11029#else
11030 rc = VMXReadVmcs32(VMX_VMCS_GUEST_RFLAGS, &u32Eflags);
11031 AssertRCBreak(rc);
11032 HMVMX_CHECK_BREAK(!(u32Eflags & 0xffc08028), VMX_IGS_RFLAGS_RESERVED); /* Bit 31:22, Bit 15, 5, 3 MBZ. */
11033 HMVMX_CHECK_BREAK((u32Eflags & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
11034#endif
11035
11036 if ( fLongModeGuest
11037 || ( fUnrestrictedGuest
11038 && !(u32GuestCR0 & X86_CR0_PE)))
11039 {
11040 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
11041 }
11042
11043 uint32_t u32EntryInfo;
11044 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
11045 AssertRCBreak(rc);
11046 if ( VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(u32EntryInfo)
11047 && VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
11048 {
11049 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
11050 }
11051
11052 /*
11053 * 64-bit checks.
11054 */
11055#if HC_ARCH_BITS == 64
11056 if (fLongModeGuest)
11057 {
11058 HMVMX_CHECK_BREAK(u32GuestCR0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
11059 HMVMX_CHECK_BREAK(u32GuestCR4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
11060 }
11061
11062 if ( !fLongModeGuest
11063 && (u32GuestCR4 & X86_CR4_PCIDE))
11064 {
11065 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
11066 }
11067
11068 /** @todo CR3 field must be such that bits 63:52 and bits in the range
11069 * 51:32 beyond the processor's physical-address width are 0. */
11070
11071 if ( (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG)
11072 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
11073 {
11074 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
11075 }
11076
11077 rc = VMXReadVmcs64(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
11078 AssertRCBreak(rc);
11079 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
11080
11081 rc = VMXReadVmcs64(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
11082 AssertRCBreak(rc);
11083 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
11084#endif
11085
11086 /*
11087 * PERF_GLOBAL MSR.
11088 */
11089 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PERF_MSR)
11090 {
11091 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
11092 AssertRCBreak(rc);
11093 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
11094 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
11095 }
11096
11097 /*
11098 * PAT MSR.
11099 */
11100 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PAT_MSR)
11101 {
11102 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
11103 AssertRCBreak(rc);
11104 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
11105 for (unsigned i = 0; i < 8; i++)
11106 {
11107 uint8_t u8Val = (u64Val & 0xff);
11108 if ( u8Val != 0 /* UC */
11109 && u8Val != 1 /* WC */
11110 && u8Val != 4 /* WT */
11111 && u8Val != 5 /* WP */
11112 && u8Val != 6 /* WB */
11113 && u8Val != 7 /* UC- */)
11114 {
11115 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
11116 }
11117 u64Val >>= 8;
11118 }
11119 }
11120
11121 /*
11122 * EFER MSR.
11123 */
11124 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR)
11125 {
11126 Assert(pVM->hm.s.vmx.fSupportsVmcsEfer);
11127 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
11128 AssertRCBreak(rc);
11129 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
11130 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
11131 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVCpu->hm.s.vmx.u32EntryCtls
11132 & VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST),
11133 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
11134 HMVMX_CHECK_BREAK( fUnrestrictedGuest
11135 || !(u32GuestCR0 & X86_CR0_PG)
11136 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
11137 VMX_IGS_EFER_LMA_LME_MISMATCH);
11138 }
11139
11140 /*
11141 * Segment registers.
11142 */
11143 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
11144 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
11145 if (!(u32Eflags & X86_EFL_VM))
11146 {
11147 /* CS */
11148 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
11149 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
11150 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
11151 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
11152 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
11153 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
11154 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
11155 /* CS cannot be loaded with NULL in protected mode. */
11156 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
11157 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
11158 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
11159 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
11160 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
11161 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
11162 else if (pVM->hm.s.vmx.fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
11163 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
11164 else
11165 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
11166
11167 /* SS */
11168 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
11169 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
11170 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
11171 if ( !(pCtx->cr0 & X86_CR0_PE)
11172 || pCtx->cs.Attr.n.u4Type == 3)
11173 {
11174 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
11175 }
11176 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
11177 {
11178 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
11179 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
11180 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
11181 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
11182 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
11183 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
11184 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
11185 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
11186 }
11187
11188 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxWriteSegmentReg(). */
11189 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
11190 {
11191 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
11192 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
11193 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
11194 || pCtx->ds.Attr.n.u4Type > 11
11195 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
11196 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
11197 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
11198 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
11199 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
11200 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
11201 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
11202 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
11203 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
11204 }
11205 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
11206 {
11207 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
11208 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
11209 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
11210 || pCtx->es.Attr.n.u4Type > 11
11211 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
11212 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
11213 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
11214 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
11215 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
11216 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
11217 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
11218 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
11219 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
11220 }
11221 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
11222 {
11223 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
11224 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
11225 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
11226 || pCtx->fs.Attr.n.u4Type > 11
11227 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
11228 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
11229 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
11230 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
11231 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
11232 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
11233 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
11234 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
11235 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
11236 }
11237 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
11238 {
11239 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
11240 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
11241 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
11242 || pCtx->gs.Attr.n.u4Type > 11
11243 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
11244 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
11245 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
11246 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
11247 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
11248 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
11249 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
11250 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
11251 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
11252 }
11253 /* 64-bit capable CPUs. */
11254#if HC_ARCH_BITS == 64
11255 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
11256 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
11257 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
11258 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
11259 HMVMX_CHECK_BREAK(!(pCtx->cs.u64Base >> 32), VMX_IGS_LONGMODE_CS_BASE_INVALID);
11260 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ss.u64Base >> 32),
11261 VMX_IGS_LONGMODE_SS_BASE_INVALID);
11262 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ds.u64Base >> 32),
11263 VMX_IGS_LONGMODE_DS_BASE_INVALID);
11264 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->es.u64Base >> 32),
11265 VMX_IGS_LONGMODE_ES_BASE_INVALID);
11266#endif
11267 }
11268 else
11269 {
11270 /* V86 mode checks. */
11271 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
11272 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
11273 {
11274 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
11275 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
11276 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
11277 }
11278 else
11279 {
11280 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
11281 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
11282 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
11283 }
11284
11285 /* CS */
11286 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
11287 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
11288 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
11289 /* SS */
11290 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
11291 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
11292 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
11293 /* DS */
11294 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
11295 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
11296 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
11297 /* ES */
11298 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
11299 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
11300 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
11301 /* FS */
11302 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
11303 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
11304 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
11305 /* GS */
11306 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
11307 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
11308 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
11309 /* 64-bit capable CPUs. */
11310#if HC_ARCH_BITS == 64
11311 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
11312 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
11313 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
11314 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
11315 HMVMX_CHECK_BREAK(!(pCtx->cs.u64Base >> 32), VMX_IGS_LONGMODE_CS_BASE_INVALID);
11316 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ss.u64Base >> 32),
11317 VMX_IGS_LONGMODE_SS_BASE_INVALID);
11318 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ds.u64Base >> 32),
11319 VMX_IGS_LONGMODE_DS_BASE_INVALID);
11320 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->es.u64Base >> 32),
11321 VMX_IGS_LONGMODE_ES_BASE_INVALID);
11322#endif
11323 }
11324
11325 /*
11326 * TR.
11327 */
11328 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
11329 /* 64-bit capable CPUs. */
11330#if HC_ARCH_BITS == 64
11331 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
11332#endif
11333 if (fLongModeGuest)
11334 {
11335 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
11336 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
11337 }
11338 else
11339 {
11340 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
11341 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
11342 VMX_IGS_TR_ATTR_TYPE_INVALID);
11343 }
11344 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
11345 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
11346 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
11347 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
11348 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
11349 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
11350 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
11351 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
11352
11353 /*
11354 * GDTR and IDTR.
11355 */
11356#if HC_ARCH_BITS == 64
11357 rc = VMXReadVmcs64(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
11358 AssertRCBreak(rc);
11359 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
11360
11361 rc = VMXReadVmcs64(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
11362 AssertRCBreak(rc);
11363 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
11364#endif
11365
11366 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
11367 AssertRCBreak(rc);
11368 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
11369
11370 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
11371 AssertRCBreak(rc);
11372 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
11373
11374 /*
11375 * Guest Non-Register State.
11376 */
11377 /* Activity State. */
11378 uint32_t u32ActivityState;
11379 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
11380 AssertRCBreak(rc);
11381 HMVMX_CHECK_BREAK( !u32ActivityState
11382 || (u32ActivityState & MSR_IA32_VMX_MISC_ACTIVITY_STATES(pVM->hm.s.vmx.Msrs.u64Misc)),
11383 VMX_IGS_ACTIVITY_STATE_INVALID);
11384 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
11385 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
11386 uint32_t u32IntrState;
11387 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &u32IntrState);
11388 AssertRCBreak(rc);
11389 if ( u32IntrState == VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS
11390 || u32IntrState == VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
11391 {
11392 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
11393 }
11394
11395 /** @todo Activity state and injecting interrupts. Left as a todo since we
11396 * currently don't use activity states but ACTIVE. */
11397
11398 HMVMX_CHECK_BREAK( !(pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_ENTRY_SMM)
11399 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
11400
11401 /* Guest interruptibility-state. */
11402 HMVMX_CHECK_BREAK(!(u32IntrState & 0xfffffff0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
11403 HMVMX_CHECK_BREAK((u32IntrState & ( VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI
11404 | VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS))
11405 != ( VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI
11406 | VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS),
11407 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
11408 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
11409 || !(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI),
11410 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
11411 if (VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(u32EntryInfo))
11412 {
11413 if (VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
11414 {
11415 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
11416 && !(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS),
11417 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
11418 }
11419 else if (VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
11420 {
11421 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS),
11422 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
11423 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI),
11424 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
11425 }
11426 }
11427 /** @todo Assumes the processor is not in SMM. */
11428 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI),
11429 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
11430 HMVMX_CHECK_BREAK( !(pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_ENTRY_SMM)
11431 || (u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI),
11432 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
11433 if ( (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI)
11434 && VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(u32EntryInfo)
11435 && VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
11436 {
11437 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI),
11438 VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
11439 }
11440
11441 /* Pending debug exceptions. */
11442#if HC_ARCH_BITS == 64
11443 rc = VMXReadVmcs64(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, &u64Val);
11444 AssertRCBreak(rc);
11445 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
11446 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
11447 u32Val = u64Val; /* For pending debug exceptions checks below. */
11448#else
11449 rc = VMXReadVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, &u32Val);
11450 AssertRCBreak(rc);
11451 /* Bits 31:15, Bit 13, Bits 11:4 MBZ. */
11452 HMVMX_CHECK_BREAK(!(u32Val & 0xffffaff0), VMX_IGS_PENDING_DEBUG_RESERVED);
11453#endif
11454
11455 if ( (u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
11456 || (u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS)
11457 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
11458 {
11459 if ( (u32Eflags & X86_EFL_TF)
11460 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
11461 {
11462 /* Bit 14 is PendingDebug.BS. */
11463 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
11464 }
11465 if ( !(u32Eflags & X86_EFL_TF)
11466 || (u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
11467 {
11468 /* Bit 14 is PendingDebug.BS. */
11469 HMVMX_CHECK_BREAK(!(u32Val & RT_BIT(14)), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_CLEAR);
11470 }
11471 }
11472
11473 /* VMCS link pointer. */
11474 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
11475 AssertRCBreak(rc);
11476 if (u64Val != UINT64_C(0xffffffffffffffff))
11477 {
11478 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
11479 /** @todo Bits beyond the processor's physical-address width MBZ. */
11480 /** @todo 32-bit located in memory referenced by value of this field (as a
11481 * physical address) must contain the processor's VMCS revision ID. */
11482 /** @todo SMM checks. */
11483 }
11484
11485 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
11486 * not using Nested Paging? */
11487 if ( pVM->hm.s.fNestedPaging
11488 && !fLongModeGuest
11489 && CPUMIsGuestInPAEModeEx(pCtx))
11490 {
11491 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
11492 AssertRCBreak(rc);
11493 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11494
11495 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
11496 AssertRCBreak(rc);
11497 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11498
11499 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
11500 AssertRCBreak(rc);
11501 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11502
11503 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
11504 AssertRCBreak(rc);
11505 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11506 }
11507
11508 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
11509 if (uError == VMX_IGS_ERROR)
11510 uError = VMX_IGS_REASON_NOT_FOUND;
11511 } while (0);
11512
11513 pVCpu->hm.s.u32HMError = uError;
11514 return uError;
11515
11516#undef HMVMX_ERROR_BREAK
11517#undef HMVMX_CHECK_BREAK
11518}
11519
11520/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
11521/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
11522/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
11523
11524/** @name VM-exit handlers.
11525 * @{
11526 */
11527
11528/**
11529 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
11530 */
11531HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11532{
11533 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11534 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
11535 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
11536 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
11537 return VINF_SUCCESS;
11538 return VINF_EM_RAW_INTERRUPT;
11539}
11540
11541
11542/**
11543 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
11544 */
11545HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11546{
11547 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11548 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
11549
11550 int rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
11551 AssertRCReturn(rc, rc);
11552
11553 uint32_t uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(pVmxTransient->uExitIntInfo);
11554 Assert( !(pVCpu->hm.s.vmx.u32ExitCtls & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT)
11555 && uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT);
11556 Assert(VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
11557
11558 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
11559 {
11560 /*
11561 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we injected it ourselves and
11562 * anything we inject is not going to cause a VM-exit directly for the event being injected.
11563 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
11564 *
11565 * Dispatch the NMI to the host. See Intel spec. 27.5.5 "Updating Non-Register State".
11566 */
11567 VMXDispatchHostNmi();
11568 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
11569 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
11570 return VINF_SUCCESS;
11571 }
11572
11573 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
11574 VBOXSTRICTRC rcStrictRc1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
11575 if (RT_UNLIKELY(rcStrictRc1 == VINF_SUCCESS))
11576 { /* likely */ }
11577 else
11578 {
11579 if (rcStrictRc1 == VINF_HM_DOUBLE_FAULT)
11580 rcStrictRc1 = VINF_SUCCESS;
11581 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
11582 return rcStrictRc1;
11583 }
11584
11585 uint32_t uExitIntInfo = pVmxTransient->uExitIntInfo;
11586 uint32_t uVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(uExitIntInfo);
11587 switch (uIntType)
11588 {
11589 case VMX_EXIT_INTERRUPTION_INFO_TYPE_PRIV_SW_XCPT: /* Privileged software exception. (#DB from ICEBP) */
11590 Assert(uVector == X86_XCPT_DB);
11591 /* fall thru */
11592 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT: /* Software exception. (#BP or #OF) */
11593 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_PRIV_SW_XCPT);
11594 /* fall thru */
11595 case VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT:
11596 {
11597 /*
11598 * If there's any exception caused as a result of event injection, the resulting
11599 * secondary/final execption will be pending, we shall continue guest execution
11600 * after injecting the event. The page-fault case is complicated and we manually
11601 * handle any currently pending event in hmR0VmxExitXcptPF.
11602 */
11603 if (!pVCpu->hm.s.Event.fPending)
11604 { /* likely */ }
11605 else if (uVector != X86_XCPT_PF)
11606 {
11607 rc = VINF_SUCCESS;
11608 break;
11609 }
11610
11611 switch (uVector)
11612 {
11613 case X86_XCPT_PF: rc = hmR0VmxExitXcptPF(pVCpu, pMixedCtx, pVmxTransient); break;
11614 case X86_XCPT_GP: rc = hmR0VmxExitXcptGP(pVCpu, pMixedCtx, pVmxTransient); break;
11615 case X86_XCPT_NM: rc = hmR0VmxExitXcptNM(pVCpu, pMixedCtx, pVmxTransient); break;
11616 case X86_XCPT_MF: rc = hmR0VmxExitXcptMF(pVCpu, pMixedCtx, pVmxTransient); break;
11617 case X86_XCPT_DB: rc = hmR0VmxExitXcptDB(pVCpu, pMixedCtx, pVmxTransient); break;
11618 case X86_XCPT_BP: rc = hmR0VmxExitXcptBP(pVCpu, pMixedCtx, pVmxTransient); break;
11619 case X86_XCPT_AC: rc = hmR0VmxExitXcptAC(pVCpu, pMixedCtx, pVmxTransient); break;
11620
11621 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF);
11622 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11623 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
11624 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11625 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
11626 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11627 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
11628 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11629 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
11630 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11631 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS);
11632 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11633 default:
11634 {
11635 rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11636 AssertRCReturn(rc, rc);
11637
11638 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
11639 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
11640 {
11641 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
11642 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
11643 Assert(CPUMIsGuestInRealModeEx(pMixedCtx));
11644
11645 rc = hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
11646 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
11647 AssertRCReturn(rc, rc);
11648 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(uExitIntInfo),
11649 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode,
11650 0 /* GCPtrFaultAddress */);
11651 AssertRCReturn(rc, rc);
11652 }
11653 else
11654 {
11655 AssertMsgFailed(("Unexpected VM-exit caused by exception %#x\n", uVector));
11656 pVCpu->hm.s.u32HMError = uVector;
11657 rc = VERR_VMX_UNEXPECTED_EXCEPTION;
11658 }
11659 break;
11660 }
11661 }
11662 break;
11663 }
11664
11665 default:
11666 {
11667 pVCpu->hm.s.u32HMError = uExitIntInfo;
11668 rc = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
11669 AssertMsgFailed(("Unexpected interruption info %#x\n", VMX_EXIT_INTERRUPTION_INFO_TYPE(uExitIntInfo)));
11670 break;
11671 }
11672 }
11673 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
11674 return rc;
11675}
11676
11677
11678/**
11679 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
11680 */
11681HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11682{
11683 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11684
11685 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
11686 hmR0VmxClearIntWindowExitVmcs(pVCpu);
11687
11688 /* Deliver the pending interrupts via hmR0VmxEvaluatePendingEvent() and resume guest execution. */
11689 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
11690 return VINF_SUCCESS;
11691}
11692
11693
11694/**
11695 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
11696 */
11697HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11698{
11699 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11700 if (RT_UNLIKELY(!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT)))
11701 {
11702 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
11703 HMVMX_RETURN_UNEXPECTED_EXIT();
11704 }
11705
11706 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS));
11707
11708 /*
11709 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
11710 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
11711 */
11712 uint32_t uIntrState = 0;
11713 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &uIntrState);
11714 AssertRCReturn(rc, rc);
11715
11716 bool const fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
11717 if ( fBlockSti
11718 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
11719 {
11720 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
11721 }
11722
11723 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
11724 hmR0VmxClearNmiWindowExitVmcs(pVCpu);
11725
11726 /* Deliver the pending NMI via hmR0VmxEvaluatePendingEvent() and resume guest execution. */
11727 return VINF_SUCCESS;
11728}
11729
11730
11731/**
11732 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
11733 */
11734HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11735{
11736 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11737 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
11738 return hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11739}
11740
11741
11742/**
11743 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
11744 */
11745HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11746{
11747 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11748 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
11749 return hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11750}
11751
11752
11753/**
11754 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
11755 */
11756HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11757{
11758 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11759 PVM pVM = pVCpu->CTX_SUFF(pVM);
11760 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11761 if (RT_LIKELY(rc == VINF_SUCCESS))
11762 {
11763 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11764 Assert(pVmxTransient->cbInstr == 2);
11765 }
11766 else
11767 {
11768 AssertMsgFailed(("hmR0VmxExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
11769 rc = VERR_EM_INTERPRETER;
11770 }
11771 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
11772 return rc;
11773}
11774
11775
11776/**
11777 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
11778 */
11779HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11780{
11781 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11782 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11783 AssertRCReturn(rc, rc);
11784
11785 if (pMixedCtx->cr4 & X86_CR4_SMXE)
11786 return VINF_EM_RAW_EMULATE_INSTR;
11787
11788 AssertMsgFailed(("hmR0VmxExitGetsec: unexpected VM-exit when CR4.SMXE is 0.\n"));
11789 HMVMX_RETURN_UNEXPECTED_EXIT();
11790}
11791
11792
11793/**
11794 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
11795 */
11796HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11797{
11798 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11799 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11800 AssertRCReturn(rc, rc);
11801
11802 PVM pVM = pVCpu->CTX_SUFF(pVM);
11803 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11804 if (RT_LIKELY(rc == VINF_SUCCESS))
11805 {
11806 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11807 Assert(pVmxTransient->cbInstr == 2);
11808 /* If we get a spurious VM-exit when offsetting is enabled, we must reset offsetting on VM-reentry. See @bugref{6634}. */
11809 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING)
11810 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
11811 }
11812 else
11813 rc = VERR_EM_INTERPRETER;
11814 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
11815 return rc;
11816}
11817
11818
11819/**
11820 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
11821 */
11822HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11823{
11824 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11825 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11826 rc |= hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx); /* For MSR_K8_TSC_AUX */
11827 AssertRCReturn(rc, rc);
11828
11829 PVM pVM = pVCpu->CTX_SUFF(pVM);
11830 rc = EMInterpretRdtscp(pVM, pVCpu, pMixedCtx);
11831 if (RT_SUCCESS(rc))
11832 {
11833 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11834 Assert(pVmxTransient->cbInstr == 3);
11835 /* If we get a spurious VM-exit when offsetting is enabled, we must reset offsetting on VM-reentry. See @bugref{6634}. */
11836 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING)
11837 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
11838 }
11839 else
11840 {
11841 AssertMsgFailed(("hmR0VmxExitRdtscp: EMInterpretRdtscp failed with %Rrc\n", rc));
11842 rc = VERR_EM_INTERPRETER;
11843 }
11844 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
11845 return rc;
11846}
11847
11848
11849/**
11850 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
11851 */
11852HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11853{
11854 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11855 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11856 rc |= hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11857 AssertRCReturn(rc, rc);
11858
11859 PVM pVM = pVCpu->CTX_SUFF(pVM);
11860 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11861 if (RT_LIKELY(rc == VINF_SUCCESS))
11862 {
11863 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11864 Assert(pVmxTransient->cbInstr == 2);
11865 }
11866 else
11867 {
11868 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
11869 rc = VERR_EM_INTERPRETER;
11870 }
11871 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
11872 return rc;
11873}
11874
11875
11876/**
11877 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
11878 */
11879HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11880{
11881 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11882 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
11883
11884 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
11885 if (pVCpu->hm.s.fHypercallsEnabled)
11886 {
11887#if 0
11888 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
11889#else
11890 /* Aggressive state sync. for now. */
11891 int rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
11892 rc |= hmR0VmxSaveGuestRflags(pVCpu,pMixedCtx); /* For CPL checks in gimHvHypercall() & gimKvmHypercall() */
11893 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx); /* For long-mode checks in gimKvmHypercall(). */
11894 AssertRCReturn(rc, rc);
11895#endif
11896
11897 /* Perform the hypercall. */
11898 rcStrict = GIMHypercall(pVCpu, pMixedCtx);
11899 if (rcStrict == VINF_SUCCESS)
11900 {
11901 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11902 AssertRCReturn(rc, rc);
11903 }
11904 else
11905 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
11906 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
11907 || RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
11908
11909 /* If the hypercall changes anything other than guest's general-purpose registers,
11910 we would need to reload the guest changed bits here before VM-entry. */
11911 }
11912 else
11913 Log4(("hmR0VmxExitVmcall: Hypercalls not enabled\n"));
11914
11915 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
11916 if (RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)))
11917 {
11918 hmR0VmxSetPendingXcptUD(pVCpu, pMixedCtx);
11919 rcStrict = VINF_SUCCESS;
11920 }
11921
11922 return rcStrict;
11923}
11924
11925
11926/**
11927 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
11928 */
11929HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11930{
11931 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11932 PVM pVM = pVCpu->CTX_SUFF(pVM);
11933 Assert(!pVM->hm.s.fNestedPaging || pVCpu->hm.s.fUsingDebugLoop);
11934
11935 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
11936 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
11937 AssertRCReturn(rc, rc);
11938
11939 VBOXSTRICTRC rcStrict = EMInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx), pVmxTransient->uExitQualification);
11940 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
11941 rcStrict = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11942 else
11943 AssertMsg(rcStrict == VERR_EM_INTERPRETER, ("hmR0VmxExitInvlpg: EMInterpretInvlpg %#RX64 failed with %Rrc\n",
11944 pVmxTransient->uExitQualification, VBOXSTRICTRC_VAL(rcStrict)));
11945 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
11946 return rcStrict;
11947}
11948
11949
11950/**
11951 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
11952 */
11953HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11954{
11955 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11956 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11957 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
11958 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
11959 AssertRCReturn(rc, rc);
11960
11961 PVM pVM = pVCpu->CTX_SUFF(pVM);
11962 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11963 if (RT_LIKELY(rc == VINF_SUCCESS))
11964 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11965 else
11966 {
11967 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0VmxExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
11968 rc = VERR_EM_INTERPRETER;
11969 }
11970 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
11971 return rc;
11972}
11973
11974
11975/**
11976 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
11977 */
11978HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11979{
11980 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11981 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11982 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
11983 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
11984 AssertRCReturn(rc, rc);
11985
11986 PVM pVM = pVCpu->CTX_SUFF(pVM);
11987 VBOXSTRICTRC rc2 = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11988 rc = VBOXSTRICTRC_VAL(rc2);
11989 if (RT_LIKELY( rc == VINF_SUCCESS
11990 || rc == VINF_EM_HALT))
11991 {
11992 int rc3 = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11993 AssertRCReturn(rc3, rc3);
11994
11995 if ( rc == VINF_EM_HALT
11996 && EMMonitorWaitShouldContinue(pVCpu, pMixedCtx))
11997 {
11998 rc = VINF_SUCCESS;
11999 }
12000 }
12001 else
12002 {
12003 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0VmxExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
12004 rc = VERR_EM_INTERPRETER;
12005 }
12006 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
12007 ("hmR0VmxExitMwait: failed, invalid error code %Rrc\n", rc));
12008 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
12009 return rc;
12010}
12011
12012
12013/**
12014 * VM-exit handler for RSM (VMX_EXIT_RSM). Unconditional VM-exit.
12015 */
12016HMVMX_EXIT_NSRC_DECL hmR0VmxExitRsm(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12017{
12018 /*
12019 * Execution of RSM outside of SMM mode causes #UD regardless of VMX root or VMX non-root mode. In theory, we should never
12020 * get this VM-exit. This can happen only if dual-monitor treatment of SMI and VMX is enabled, which can (only?) be done by
12021 * executing VMCALL in VMX root operation. If we get here, something funny is going on.
12022 * See Intel spec. "33.15.5 Enabling the Dual-Monitor Treatment".
12023 */
12024 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12025 AssertMsgFailed(("Unexpected RSM VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12026 HMVMX_RETURN_UNEXPECTED_EXIT();
12027}
12028
12029
12030/**
12031 * VM-exit handler for SMI (VMX_EXIT_SMI). Unconditional VM-exit.
12032 */
12033HMVMX_EXIT_NSRC_DECL hmR0VmxExitSmi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12034{
12035 /*
12036 * This can only happen if we support dual-monitor treatment of SMI, which can be activated by executing VMCALL in VMX
12037 * root operation. Only an STM (SMM transfer monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL
12038 * in VMX root mode or receive an SMI. If we get here, something funny is going on.
12039 * See Intel spec. "33.15.6 Activating the Dual-Monitor Treatment" and Intel spec. 25.3 "Other Causes of VM-Exits"
12040 */
12041 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12042 AssertMsgFailed(("Unexpected SMI VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12043 HMVMX_RETURN_UNEXPECTED_EXIT();
12044}
12045
12046
12047/**
12048 * VM-exit handler for IO SMI (VMX_EXIT_IO_SMI). Unconditional VM-exit.
12049 */
12050HMVMX_EXIT_NSRC_DECL hmR0VmxExitIoSmi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12051{
12052 /* Same treatment as VMX_EXIT_SMI. See comment in hmR0VmxExitSmi(). */
12053 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12054 AssertMsgFailed(("Unexpected IO SMI VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12055 HMVMX_RETURN_UNEXPECTED_EXIT();
12056}
12057
12058
12059/**
12060 * VM-exit handler for SIPI (VMX_EXIT_SIPI). Conditional VM-exit.
12061 */
12062HMVMX_EXIT_NSRC_DECL hmR0VmxExitSipi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12063{
12064 /*
12065 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest activity state is used. We currently
12066 * don't make use of it (see hmR0VmxLoadGuestActivityState()) as our guests don't have direct access to the host LAPIC.
12067 * See Intel spec. 25.3 "Other Causes of VM-exits".
12068 */
12069 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12070 AssertMsgFailed(("Unexpected SIPI VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12071 HMVMX_RETURN_UNEXPECTED_EXIT();
12072}
12073
12074
12075/**
12076 * VM-exit handler for INIT signal (VMX_EXIT_INIT_SIGNAL). Unconditional
12077 * VM-exit.
12078 */
12079HMVMX_EXIT_NSRC_DECL hmR0VmxExitInitSignal(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12080{
12081 /*
12082 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
12083 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery" and Intel spec. 29.3 "VMX Instructions" for "VMXON".
12084 *
12085 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these VM-exits.
12086 * See Intel spec. "23.8 Restrictions on VMX operation".
12087 */
12088 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12089 return VINF_SUCCESS;
12090}
12091
12092
12093/**
12094 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
12095 * VM-exit.
12096 */
12097HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12098{
12099 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12100 return VINF_EM_RESET;
12101}
12102
12103
12104/**
12105 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
12106 */
12107HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12108{
12109 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12110 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT);
12111
12112 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12113 AssertRCReturn(rc, rc);
12114
12115 if (EMShouldContinueAfterHalt(pVCpu, pMixedCtx)) /* Requires eflags. */
12116 rc = VINF_SUCCESS;
12117 else
12118 rc = VINF_EM_HALT;
12119
12120 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
12121 if (rc != VINF_SUCCESS)
12122 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
12123 return rc;
12124}
12125
12126
12127/**
12128 * VM-exit handler for instructions that result in a \#UD exception delivered to
12129 * the guest.
12130 */
12131HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12132{
12133 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12134 hmR0VmxSetPendingXcptUD(pVCpu, pMixedCtx);
12135 return VINF_SUCCESS;
12136}
12137
12138
12139/**
12140 * VM-exit handler for expiry of the VMX preemption timer.
12141 */
12142HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12143{
12144 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12145
12146 /* If the preemption-timer has expired, reinitialize the preemption timer on next VM-entry. */
12147 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
12148
12149 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
12150 PVM pVM = pVCpu->CTX_SUFF(pVM);
12151 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
12152 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
12153 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
12154}
12155
12156
12157/**
12158 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
12159 */
12160HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12161{
12162 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12163
12164 int rc = hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12165 rc |= hmR0VmxSaveGuestRegsForIemExec(pVCpu, pMixedCtx, false /*fMemory*/, false /*fNeedRsp*/);
12166 rc |= hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
12167 AssertRCReturn(rc, rc);
12168
12169 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbInstr);
12170 HMCPU_CF_SET(pVCpu, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS : HM_CHANGED_ALL_GUEST);
12171
12172 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pMixedCtx->cr4 & X86_CR4_OSXSAVE) && pMixedCtx->aXcr[0] != ASMGetXcr0();
12173
12174 return rcStrict;
12175}
12176
12177
12178/**
12179 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
12180 */
12181HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12182{
12183 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12184
12185 /* The guest should not invalidate the host CPU's TLBs, fallback to interpreter. */
12186 /** @todo implement EMInterpretInvpcid() */
12187 return VERR_EM_INTERPRETER;
12188}
12189
12190
12191/**
12192 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE).
12193 * Error VM-exit.
12194 */
12195HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12196{
12197 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
12198 AssertRCReturn(rc, rc);
12199
12200 rc = hmR0VmxCheckVmcsCtls(pVCpu);
12201 AssertRCReturn(rc, rc);
12202
12203 uint32_t uInvalidReason = hmR0VmxCheckGuestState(pVCpu->CTX_SUFF(pVM), pVCpu, pMixedCtx);
12204 NOREF(uInvalidReason);
12205
12206#ifdef VBOX_STRICT
12207 uint32_t uIntrState;
12208 RTHCUINTREG uHCReg;
12209 uint64_t u64Val;
12210 uint32_t u32Val;
12211
12212 rc = hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
12213 rc |= hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
12214 rc |= hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
12215 rc |= VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &uIntrState);
12216 AssertRCReturn(rc, rc);
12217
12218 Log4(("uInvalidReason %u\n", uInvalidReason));
12219 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
12220 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
12221 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
12222 Log4(("VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE %#RX32\n", uIntrState));
12223
12224 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR0, &u32Val); AssertRC(rc);
12225 Log4(("VMX_VMCS_GUEST_CR0 %#RX32\n", u32Val));
12226 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_MASK, &uHCReg); AssertRC(rc);
12227 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RHr\n", uHCReg));
12228 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_READ_SHADOW, &uHCReg); AssertRC(rc);
12229 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
12230 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_MASK, &uHCReg); AssertRC(rc);
12231 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RHr\n", uHCReg));
12232 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_READ_SHADOW, &uHCReg); AssertRC(rc);
12233 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
12234 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
12235 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
12236#else
12237 NOREF(pVmxTransient);
12238#endif
12239
12240 hmR0DumpRegs(pVCpu->CTX_SUFF(pVM), pVCpu, pMixedCtx);
12241 return VERR_VMX_INVALID_GUEST_STATE;
12242}
12243
12244
12245/**
12246 * VM-exit handler for VM-entry failure due to an MSR-load
12247 * (VMX_EXIT_ERR_MSR_LOAD). Error VM-exit.
12248 */
12249HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrMsrLoad(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12250{
12251 NOREF(pVmxTransient);
12252 AssertMsgFailed(("Unexpected MSR-load exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx)); NOREF(pMixedCtx);
12253 HMVMX_RETURN_UNEXPECTED_EXIT();
12254}
12255
12256
12257/**
12258 * VM-exit handler for VM-entry failure due to a machine-check event
12259 * (VMX_EXIT_ERR_MACHINE_CHECK). Error VM-exit.
12260 */
12261HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrMachineCheck(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12262{
12263 NOREF(pVmxTransient);
12264 AssertMsgFailed(("Unexpected machine-check event exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx)); NOREF(pMixedCtx);
12265 HMVMX_RETURN_UNEXPECTED_EXIT();
12266}
12267
12268
12269/**
12270 * VM-exit handler for all undefined reasons. Should never ever happen.. in
12271 * theory.
12272 */
12273HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUndefined(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12274{
12275 AssertMsgFailed(("Huh!? Undefined VM-exit reason %d. pVCpu=%p pMixedCtx=%p\n", pVmxTransient->uExitReason, pVCpu, pMixedCtx));
12276 NOREF(pVCpu); NOREF(pMixedCtx); NOREF(pVmxTransient);
12277 return VERR_VMX_UNDEFINED_EXIT_CODE;
12278}
12279
12280
12281/**
12282 * VM-exit handler for XDTR (LGDT, SGDT, LIDT, SIDT) accesses
12283 * (VMX_EXIT_XDTR_ACCESS) and LDT and TR access (LLDT, LTR, SLDT, STR).
12284 * Conditional VM-exit.
12285 */
12286HMVMX_EXIT_DECL hmR0VmxExitXdtrAccess(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12287{
12288 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12289
12290 /* By default, we don't enable VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT. */
12291 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitXdtrAccess);
12292 if (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT)
12293 return VERR_EM_INTERPRETER;
12294 AssertMsgFailed(("Unexpected XDTR access. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12295 HMVMX_RETURN_UNEXPECTED_EXIT();
12296}
12297
12298
12299/**
12300 * VM-exit handler for RDRAND (VMX_EXIT_RDRAND). Conditional VM-exit.
12301 */
12302HMVMX_EXIT_DECL hmR0VmxExitRdrand(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12303{
12304 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12305
12306 /* By default, we don't enable VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT. */
12307 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdrand);
12308 if (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT)
12309 return VERR_EM_INTERPRETER;
12310 AssertMsgFailed(("Unexpected RDRAND exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12311 HMVMX_RETURN_UNEXPECTED_EXIT();
12312}
12313
12314
12315/**
12316 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
12317 */
12318HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12319{
12320 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12321
12322 /* EMInterpretRdmsr() requires CR0, Eflags and SS segment register. */
12323 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
12324 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
12325 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12326 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS))
12327 {
12328 rc |= hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
12329 rc |= hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
12330 }
12331 AssertRCReturn(rc, rc);
12332 Log4(("ecx=%#RX32\n", pMixedCtx->ecx));
12333
12334#ifdef VBOX_STRICT
12335 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
12336 {
12337 if ( hmR0VmxIsAutoLoadStoreGuestMsr(pVCpu, pMixedCtx->ecx)
12338 && pMixedCtx->ecx != MSR_K6_EFER)
12339 {
12340 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
12341 pMixedCtx->ecx));
12342 HMVMX_RETURN_UNEXPECTED_EXIT();
12343 }
12344 if (hmR0VmxIsLazyGuestMsr(pVCpu, pMixedCtx->ecx))
12345 {
12346 VMXMSREXITREAD enmRead;
12347 VMXMSREXITWRITE enmWrite;
12348 int rc2 = hmR0VmxGetMsrPermission(pVCpu, pMixedCtx->ecx, &enmRead, &enmWrite);
12349 AssertRCReturn(rc2, rc2);
12350 if (enmRead == VMXMSREXIT_PASSTHRU_READ)
12351 {
12352 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", pMixedCtx->ecx));
12353 HMVMX_RETURN_UNEXPECTED_EXIT();
12354 }
12355 }
12356 }
12357#endif
12358
12359 PVM pVM = pVCpu->CTX_SUFF(pVM);
12360 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
12361 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER,
12362 ("hmR0VmxExitRdmsr: failed, invalid error code %Rrc\n", rc));
12363 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
12364 if (RT_SUCCESS(rc))
12365 {
12366 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12367 Assert(pVmxTransient->cbInstr == 2);
12368 }
12369 return rc;
12370}
12371
12372
12373/**
12374 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
12375 */
12376HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12377{
12378 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12379 PVM pVM = pVCpu->CTX_SUFF(pVM);
12380 int rc = VINF_SUCCESS;
12381
12382 /* EMInterpretWrmsr() requires CR0, EFLAGS and SS segment register. */
12383 rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
12384 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
12385 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12386 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS))
12387 {
12388 rc |= hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
12389 rc |= hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
12390 }
12391 AssertRCReturn(rc, rc);
12392 Log4(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", pMixedCtx->ecx, pMixedCtx->edx, pMixedCtx->eax));
12393
12394 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
12395 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER, ("hmR0VmxExitWrmsr: failed, invalid error code %Rrc\n", rc));
12396 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
12397
12398 if (RT_SUCCESS(rc))
12399 {
12400 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12401
12402 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
12403 if ( pMixedCtx->ecx == MSR_IA32_APICBASE
12404 || ( pMixedCtx->ecx >= MSR_IA32_X2APIC_START
12405 && pMixedCtx->ecx <= MSR_IA32_X2APIC_END))
12406 {
12407 /*
12408 * We've already saved the APIC related guest-state (TPR) in hmR0VmxPostRunGuest(). When full APIC register
12409 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCS before
12410 * EMInterpretWrmsr() changes it.
12411 */
12412 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
12413 }
12414 else if (pMixedCtx->ecx == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
12415 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
12416 else if (pMixedCtx->ecx == MSR_K6_EFER)
12417 {
12418 /*
12419 * If the guest touches EFER we need to update the VM-Entry and VM-Exit controls as well,
12420 * even if it is -not- touching bits that cause paging mode changes (LMA/LME). We care about
12421 * the other bits as well, SCE and NXE. See @bugref{7368}.
12422 */
12423 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_CTLS | HM_CHANGED_VMX_EXIT_CTLS);
12424 }
12425
12426 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not supported. */
12427 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS))
12428 {
12429 switch (pMixedCtx->ecx)
12430 {
12431 /*
12432 * For SYSENTER CS, EIP, ESP MSRs, we set both the flags here so we don't accidentally
12433 * overwrite the changed guest-CPU context value while going to ring-3, see @bufref{8745}.
12434 */
12435 case MSR_IA32_SYSENTER_CS:
12436 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR);
12437 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR);
12438 break;
12439 case MSR_IA32_SYSENTER_EIP:
12440 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
12441 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR);
12442 break;
12443 case MSR_IA32_SYSENTER_ESP:
12444 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
12445 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR);
12446 break;
12447 case MSR_K8_FS_BASE: /* fall thru */
12448 case MSR_K8_GS_BASE: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS); break;
12449 case MSR_K6_EFER: /* already handled above */ break;
12450 default:
12451 {
12452 if (hmR0VmxIsAutoLoadStoreGuestMsr(pVCpu, pMixedCtx->ecx))
12453 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
12454 else if (hmR0VmxIsLazyGuestMsr(pVCpu, pMixedCtx->ecx))
12455 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
12456 break;
12457 }
12458 }
12459 }
12460#ifdef VBOX_STRICT
12461 else
12462 {
12463 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
12464 switch (pMixedCtx->ecx)
12465 {
12466 case MSR_IA32_SYSENTER_CS:
12467 case MSR_IA32_SYSENTER_EIP:
12468 case MSR_IA32_SYSENTER_ESP:
12469 case MSR_K8_FS_BASE:
12470 case MSR_K8_GS_BASE:
12471 {
12472 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", pMixedCtx->ecx));
12473 HMVMX_RETURN_UNEXPECTED_EXIT();
12474 }
12475
12476 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
12477 default:
12478 {
12479 if (hmR0VmxIsAutoLoadStoreGuestMsr(pVCpu, pMixedCtx->ecx))
12480 {
12481 /* EFER writes are always intercepted, see hmR0VmxLoadGuestMsrs(). */
12482 if (pMixedCtx->ecx != MSR_K6_EFER)
12483 {
12484 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
12485 pMixedCtx->ecx));
12486 HMVMX_RETURN_UNEXPECTED_EXIT();
12487 }
12488 }
12489
12490 if (hmR0VmxIsLazyGuestMsr(pVCpu, pMixedCtx->ecx))
12491 {
12492 VMXMSREXITREAD enmRead;
12493 VMXMSREXITWRITE enmWrite;
12494 int rc2 = hmR0VmxGetMsrPermission(pVCpu, pMixedCtx->ecx, &enmRead, &enmWrite);
12495 AssertRCReturn(rc2, rc2);
12496 if (enmWrite == VMXMSREXIT_PASSTHRU_WRITE)
12497 {
12498 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", pMixedCtx->ecx));
12499 HMVMX_RETURN_UNEXPECTED_EXIT();
12500 }
12501 }
12502 break;
12503 }
12504 }
12505 }
12506#endif /* VBOX_STRICT */
12507 }
12508 return rc;
12509}
12510
12511
12512/**
12513 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
12514 */
12515HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12516{
12517 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12518
12519 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
12520 return VINF_EM_RAW_INTERRUPT;
12521}
12522
12523
12524/**
12525 * VM-exit handler for when the TPR value is lowered below the specified
12526 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
12527 */
12528HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12529{
12530 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12531 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW);
12532
12533 /*
12534 * The TPR shadow would've been synced with the APIC TPR in hmR0VmxPostRunGuest(). We'll re-evaluate
12535 * pending interrupts and inject them before the next VM-entry so we can just continue execution here.
12536 */
12537 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
12538 return VINF_SUCCESS;
12539}
12540
12541
12542/**
12543 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
12544 * VM-exit.
12545 *
12546 * @retval VINF_SUCCESS when guest execution can continue.
12547 * @retval VINF_PGM_CHANGE_MODE when shadow paging mode changed, back to ring-3.
12548 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
12549 * @retval VERR_EM_INTERPRETER when something unexpected happened, fallback to
12550 * interpreter.
12551 */
12552HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12553{
12554 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12555 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
12556 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12557 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12558 AssertRCReturn(rc, rc);
12559
12560 RTGCUINTPTR const uExitQualification = pVmxTransient->uExitQualification;
12561 uint32_t const uAccessType = VMX_EXIT_QUALIFICATION_CRX_ACCESS(uExitQualification);
12562 PVM pVM = pVCpu->CTX_SUFF(pVM);
12563 VBOXSTRICTRC rcStrict;
12564 rc = hmR0VmxSaveGuestRegsForIemExec(pVCpu, pMixedCtx, false /*fMemory*/, true /*fNeedRsp*/);
12565 switch (uAccessType)
12566 {
12567 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_WRITE: /* MOV to CRx */
12568 {
12569 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12570 AssertRCReturn(rc, rc);
12571
12572 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, pVmxTransient->cbInstr,
12573 VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification),
12574 VMX_EXIT_QUALIFICATION_CRX_GENREG(uExitQualification));
12575 AssertMsg( rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT || rcStrict == VINF_PGM_CHANGE_MODE
12576 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12577 switch (VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification))
12578 {
12579 case 0: /* CR0 */
12580 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
12581 Log4(("CRX CR0 write rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pMixedCtx->cr0));
12582 break;
12583 case 2: /* CR2 */
12584 /* Nothing to do here, CR2 it's not part of the VMCS. */
12585 break;
12586 case 3: /* CR3 */
12587 Assert(!pVM->hm.s.fNestedPaging || !CPUMIsGuestPagingEnabledEx(pMixedCtx) || pVCpu->hm.s.fUsingDebugLoop);
12588 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
12589 Log4(("CRX CR3 write rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pMixedCtx->cr3));
12590 break;
12591 case 4: /* CR4 */
12592 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
12593 Log4(("CRX CR4 write rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n",
12594 VBOXSTRICTRC_VAL(rcStrict), pMixedCtx->cr4, pVCpu->hm.s.fLoadSaveGuestXcr0));
12595 break;
12596 case 8: /* CR8 */
12597 Assert(!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW));
12598 /* CR8 contains the APIC TPR. Was updated by IEMExecDecodedMovCRxWrite(). */
12599 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
12600 break;
12601 default:
12602 AssertMsgFailed(("Invalid CRx register %#x\n", VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification)));
12603 break;
12604 }
12605
12606 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxWrite[VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification)]);
12607 break;
12608 }
12609
12610 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_READ: /* MOV from CRx */
12611 {
12612 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12613 AssertRCReturn(rc, rc);
12614
12615 Assert( !pVM->hm.s.fNestedPaging
12616 || !CPUMIsGuestPagingEnabledEx(pMixedCtx)
12617 || pVCpu->hm.s.fUsingDebugLoop
12618 || VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification) != 3);
12619
12620 /* CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
12621 Assert( VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification) != 8
12622 || !(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW));
12623
12624 rcStrict = IEMExecDecodedMovCRxRead(pVCpu, pVmxTransient->cbInstr,
12625 VMX_EXIT_QUALIFICATION_CRX_GENREG(uExitQualification),
12626 VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification));
12627 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12628 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification)]);
12629 Log4(("CRX CR%d Read access rcStrict=%Rrc\n", VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification),
12630 VBOXSTRICTRC_VAL(rcStrict)));
12631 break;
12632 }
12633
12634 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_CLTS: /* CLTS (Clear Task-Switch Flag in CR0) */
12635 {
12636 AssertRCReturn(rc, rc);
12637 rcStrict = IEMExecDecodedClts(pVCpu, pVmxTransient->cbInstr);
12638 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12639 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
12640 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
12641 Log4(("CRX CLTS rcStrict=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
12642 break;
12643 }
12644
12645 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
12646 {
12647 AssertRCReturn(rc, rc);
12648 rcStrict = IEMExecDecodedLmsw(pVCpu, pVmxTransient->cbInstr,
12649 VMX_EXIT_QUALIFICATION_CRX_LMSW_DATA(uExitQualification));
12650 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT || rcStrict == VINF_PGM_CHANGE_MODE,
12651 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12652 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
12653 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
12654 Log4(("CRX LMSW rcStrict=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
12655 break;
12656 }
12657
12658 default:
12659 AssertMsgFailedReturn(("Invalid access-type in Mov CRx VM-exit qualification %#x\n", uAccessType),
12660 VERR_VMX_UNEXPECTED_EXCEPTION);
12661 }
12662
12663 HMCPU_CF_SET(pVCpu, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS : HM_CHANGED_ALL_GUEST);
12664 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
12665 NOREF(pVM);
12666 return rcStrict;
12667}
12668
12669
12670/**
12671 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
12672 * VM-exit.
12673 */
12674HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12675{
12676 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12677 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
12678
12679 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12680 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12681 rc |= hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
12682 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx); /* Eflag checks in EMInterpretDisasCurrent(). */
12683 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx); /* CR0 checks & PGM* in EMInterpretDisasCurrent(). */
12684 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx); /* SELM checks in EMInterpretDisasCurrent(). */
12685 /* EFER also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
12686 AssertRCReturn(rc, rc);
12687
12688 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
12689 uint32_t uIOPort = VMX_EXIT_QUALIFICATION_IO_PORT(pVmxTransient->uExitQualification);
12690 uint8_t uIOWidth = VMX_EXIT_QUALIFICATION_IO_WIDTH(pVmxTransient->uExitQualification);
12691 bool fIOWrite = ( VMX_EXIT_QUALIFICATION_IO_DIRECTION(pVmxTransient->uExitQualification)
12692 == VMX_EXIT_QUALIFICATION_IO_DIRECTION_OUT);
12693 bool fIOString = VMX_EXIT_QUALIFICATION_IO_IS_STRING(pVmxTransient->uExitQualification);
12694 bool fGstStepping = RT_BOOL(pMixedCtx->eflags.Bits.u1TF);
12695 bool fDbgStepping = pVCpu->hm.s.fSingleInstruction;
12696 AssertReturn(uIOWidth <= 3 && uIOWidth != 2, VERR_VMX_IPE_1);
12697
12698 /* I/O operation lookup arrays. */
12699 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses. */
12700 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving the result (in AL/AX/EAX). */
12701
12702 VBOXSTRICTRC rcStrict;
12703 uint32_t const cbValue = s_aIOSizes[uIOWidth];
12704 uint32_t const cbInstr = pVmxTransient->cbInstr;
12705 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
12706 PVM pVM = pVCpu->CTX_SUFF(pVM);
12707 if (fIOString)
12708 {
12709#ifdef VBOX_WITH_2ND_IEM_STEP /* This used to gurus with debian 32-bit guest without NP (on ATA reads).
12710 See @bugref{5752#c158}. Should work now. */
12711 /*
12712 * INS/OUTS - I/O String instruction.
12713 *
12714 * Use instruction-information if available, otherwise fall back on
12715 * interpreting the instruction.
12716 */
12717 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pMixedCtx->cs.Sel, pMixedCtx->rip, uIOPort, cbValue,
12718 fIOWrite ? 'w' : 'r'));
12719 AssertReturn(pMixedCtx->dx == uIOPort, VERR_VMX_IPE_2);
12720 if (MSR_IA32_VMX_BASIC_INFO_VMCS_INS_OUTS(pVM->hm.s.vmx.Msrs.u64BasicInfo))
12721 {
12722 int rc2 = hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
12723 /** @todo optimize this, IEM should request the additional state if it needs it (GP, PF, ++). */
12724 rc2 |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
12725 AssertRCReturn(rc2, rc2);
12726 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
12727 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
12728 IEMMODE enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
12729 bool fRep = VMX_EXIT_QUALIFICATION_IO_IS_REP(pVmxTransient->uExitQualification);
12730 if (fIOWrite)
12731 {
12732 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
12733 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
12734 }
12735 else
12736 {
12737 /*
12738 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
12739 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
12740 * See Intel Instruction spec. for "INS".
12741 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
12742 */
12743 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
12744 }
12745 }
12746 else
12747 {
12748 /** @todo optimize this, IEM should request the additional state if it needs it (GP, PF, ++). */
12749 int rc2 = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
12750 AssertRCReturn(rc2, rc2);
12751 rcStrict = IEMExecOne(pVCpu);
12752 }
12753 /** @todo IEM needs to be setting these flags somehow. */
12754 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP);
12755 fUpdateRipAlready = true;
12756#else
12757 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
12758 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
12759 if (RT_SUCCESS(rcStrict))
12760 {
12761 if (fIOWrite)
12762 {
12763 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx), uIOPort, pDis->fPrefix,
12764 (DISCPUMODE)pDis->uAddrMode, cbValue);
12765 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
12766 }
12767 else
12768 {
12769 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx), uIOPort, pDis->fPrefix,
12770 (DISCPUMODE)pDis->uAddrMode, cbValue);
12771 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
12772 }
12773 }
12774 else
12775 {
12776 AssertMsg(rcStrict == VERR_EM_INTERPRETER, ("rcStrict=%Rrc RIP=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict),
12777 pMixedCtx->rip));
12778 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
12779 }
12780#endif
12781 }
12782 else
12783 {
12784 /*
12785 * IN/OUT - I/O instruction.
12786 */
12787 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c\n", pMixedCtx->cs.Sel, pMixedCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
12788 uint32_t const uAndVal = s_aIOOpAnd[uIOWidth];
12789 Assert(!VMX_EXIT_QUALIFICATION_IO_IS_REP(pVmxTransient->uExitQualification));
12790 if (fIOWrite)
12791 {
12792 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pMixedCtx->eax & uAndVal, cbValue);
12793 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
12794 }
12795 else
12796 {
12797 uint32_t u32Result = 0;
12798 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
12799 if (IOM_SUCCESS(rcStrict))
12800 {
12801 /* Save result of I/O IN instr. in AL/AX/EAX. */
12802 pMixedCtx->eax = (pMixedCtx->eax & ~uAndVal) | (u32Result & uAndVal);
12803 }
12804 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
12805 HMR0SavePendingIOPortRead(pVCpu, pMixedCtx->rip, pMixedCtx->rip + cbInstr, uIOPort, uAndVal, cbValue);
12806 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
12807 }
12808 }
12809
12810 if (IOM_SUCCESS(rcStrict))
12811 {
12812 if (!fUpdateRipAlready)
12813 {
12814 hmR0VmxAdvanceGuestRipBy(pVCpu, pMixedCtx, cbInstr);
12815 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP);
12816 }
12817
12818 /*
12819 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru while booting Fedora 17 64-bit guest.
12820 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
12821 */
12822 if (fIOString)
12823 {
12824 /** @todo Single-step for INS/OUTS with REP prefix? */
12825 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RFLAGS);
12826 }
12827 else if ( !fDbgStepping
12828 && fGstStepping)
12829 {
12830 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
12831 }
12832
12833 /*
12834 * If any I/O breakpoints are armed, we need to check if one triggered
12835 * and take appropriate action.
12836 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
12837 */
12838 int rc2 = hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
12839 AssertRCReturn(rc2, rc2);
12840
12841 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
12842 * execution engines about whether hyper BPs and such are pending. */
12843 uint32_t const uDr7 = pMixedCtx->dr[7];
12844 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
12845 && X86_DR7_ANY_RW_IO(uDr7)
12846 && (pMixedCtx->cr4 & X86_CR4_DE))
12847 || DBGFBpIsHwIoArmed(pVM)))
12848 {
12849 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
12850
12851 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
12852 VMMRZCallRing3Disable(pVCpu);
12853 HM_DISABLE_PREEMPT();
12854
12855 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
12856
12857 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pMixedCtx, uIOPort, cbValue);
12858 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
12859 {
12860 /* Raise #DB. */
12861 if (fIsGuestDbgActive)
12862 ASMSetDR6(pMixedCtx->dr[6]);
12863 if (pMixedCtx->dr[7] != uDr7)
12864 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
12865
12866 hmR0VmxSetPendingXcptDB(pVCpu, pMixedCtx);
12867 }
12868 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
12869 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
12870 else if ( rcStrict2 != VINF_SUCCESS
12871 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
12872 rcStrict = rcStrict2;
12873 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
12874
12875 HM_RESTORE_PREEMPT();
12876 VMMRZCallRing3Enable(pVCpu);
12877 }
12878 }
12879
12880#ifdef VBOX_STRICT
12881 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
12882 Assert(!fIOWrite);
12883 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
12884 Assert(fIOWrite);
12885 else
12886 {
12887#if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
12888 * statuses, that the VMM device and some others may return. See
12889 * IOM_SUCCESS() for guidance. */
12890 AssertMsg( RT_FAILURE(rcStrict)
12891 || rcStrict == VINF_SUCCESS
12892 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
12893 || rcStrict == VINF_EM_DBG_BREAKPOINT
12894 || rcStrict == VINF_EM_RAW_GUEST_TRAP
12895 || rcStrict == VINF_EM_RAW_TO_R3
12896 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12897#endif
12898 }
12899#endif
12900
12901 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
12902 return rcStrict;
12903}
12904
12905
12906/**
12907 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
12908 * VM-exit.
12909 */
12910HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12911{
12912 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12913
12914 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
12915 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12916 AssertRCReturn(rc, rc);
12917 if (VMX_EXIT_QUALIFICATION_TASK_SWITCH_TYPE(pVmxTransient->uExitQualification) == VMX_EXIT_QUALIFICATION_TASK_SWITCH_TYPE_IDT)
12918 {
12919 rc = hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
12920 AssertRCReturn(rc, rc);
12921 if (VMX_IDT_VECTORING_INFO_VALID(pVmxTransient->uIdtVectoringInfo))
12922 {
12923 uint32_t uErrCode;
12924 RTGCUINTPTR GCPtrFaultAddress;
12925 uint32_t const uIntType = VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo);
12926 uint32_t const uVector = VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo);
12927 bool const fErrorCodeValid = VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uIdtVectoringInfo);
12928 if (fErrorCodeValid)
12929 {
12930 rc = hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
12931 AssertRCReturn(rc, rc);
12932 uErrCode = pVmxTransient->uIdtVectoringErrorCode;
12933 }
12934 else
12935 uErrCode = 0;
12936
12937 if ( uIntType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
12938 && uVector == X86_XCPT_PF)
12939 GCPtrFaultAddress = pMixedCtx->cr2;
12940 else
12941 GCPtrFaultAddress = 0;
12942
12943 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
12944 0 /* cbInstr */, uErrCode, GCPtrFaultAddress);
12945
12946 Log4(("Pending event on TaskSwitch uIntType=%#x uVector=%#x\n", uIntType, uVector));
12947 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
12948 return VINF_EM_RAW_INJECT_TRPM_EVENT;
12949 }
12950 }
12951
12952 /* Fall back to the interpreter to emulate the task-switch. */
12953 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
12954 return VERR_EM_INTERPRETER;
12955}
12956
12957
12958/**
12959 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
12960 */
12961HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12962{
12963 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12964 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG);
12965 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG;
12966 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
12967 AssertRCReturn(rc, rc);
12968 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMtf);
12969 return VINF_EM_DBG_STEPPED;
12970}
12971
12972
12973/**
12974 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
12975 */
12976HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12977{
12978 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12979
12980 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
12981
12982 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
12983 VBOXSTRICTRC rcStrict1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
12984 if (RT_LIKELY(rcStrict1 == VINF_SUCCESS))
12985 {
12986 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
12987 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
12988 {
12989 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
12990 return VINF_EM_RAW_INJECT_TRPM_EVENT;
12991 }
12992 }
12993 else
12994 {
12995 if (rcStrict1 == VINF_HM_DOUBLE_FAULT)
12996 rcStrict1 = VINF_SUCCESS;
12997 return rcStrict1;
12998 }
12999
13000#if 0
13001 /** @todo Investigate if IOMMMIOPhysHandler() requires a lot of state, for now
13002 * just sync the whole thing. */
13003 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13004#else
13005 /* Aggressive state sync. for now. */
13006 int rc = hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
13007 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
13008 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
13009#endif
13010 rc |= hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13011 AssertRCReturn(rc, rc);
13012
13013 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
13014 uint32_t uAccessType = VMX_EXIT_QUALIFICATION_APIC_ACCESS_TYPE(pVmxTransient->uExitQualification);
13015 VBOXSTRICTRC rcStrict2;
13016 switch (uAccessType)
13017 {
13018 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
13019 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
13020 {
13021 AssertMsg( !(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
13022 || VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(pVmxTransient->uExitQualification) != XAPIC_OFF_TPR,
13023 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
13024
13025 RTGCPHYS GCPhys = pVCpu->hm.s.vmx.u64MsrApicBase; /* Always up-to-date, u64MsrApicBase is not part of the VMCS. */
13026 GCPhys &= PAGE_BASE_GC_MASK;
13027 GCPhys += VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(pVmxTransient->uExitQualification);
13028 PVM pVM = pVCpu->CTX_SUFF(pVM);
13029 Log4(("ApicAccess uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
13030 VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(pVmxTransient->uExitQualification)));
13031
13032 rcStrict2 = IOMMMIOPhysHandler(pVM, pVCpu,
13033 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW,
13034 CPUMCTX2CORE(pMixedCtx), GCPhys);
13035 Log4(("ApicAccess rcStrict2=%d\n", VBOXSTRICTRC_VAL(rcStrict2)));
13036 if ( rcStrict2 == VINF_SUCCESS
13037 || rcStrict2 == VERR_PAGE_TABLE_NOT_PRESENT
13038 || rcStrict2 == VERR_PAGE_NOT_PRESENT)
13039 {
13040 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13041 | HM_CHANGED_GUEST_RSP
13042 | HM_CHANGED_GUEST_RFLAGS
13043 | HM_CHANGED_VMX_GUEST_APIC_STATE);
13044 rcStrict2 = VINF_SUCCESS;
13045 }
13046 break;
13047 }
13048
13049 default:
13050 Log4(("ApicAccess uAccessType=%#x\n", uAccessType));
13051 rcStrict2 = VINF_EM_RAW_EMULATE_INSTR;
13052 break;
13053 }
13054
13055 if (rcStrict2 != VINF_SUCCESS)
13056 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
13057 return rcStrict2;
13058}
13059
13060
13061/**
13062 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
13063 * VM-exit.
13064 */
13065HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13066{
13067 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
13068
13069 /* We should -not- get this VM-exit if the guest's debug registers were active. */
13070 if (pVmxTransient->fWasGuestDebugStateActive)
13071 {
13072 AssertMsgFailed(("Unexpected MOV DRx exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
13073 HMVMX_RETURN_UNEXPECTED_EXIT();
13074 }
13075
13076 if ( !pVCpu->hm.s.fSingleInstruction
13077 && !pVmxTransient->fWasHyperDebugStateActive)
13078 {
13079 Assert(!DBGFIsStepping(pVCpu));
13080 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_DB));
13081
13082 /* Don't intercept MOV DRx any more. */
13083 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT;
13084 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
13085 AssertRCReturn(rc, rc);
13086
13087 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
13088 VMMRZCallRing3Disable(pVCpu);
13089 HM_DISABLE_PREEMPT();
13090
13091 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
13092 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
13093 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
13094
13095 HM_RESTORE_PREEMPT();
13096 VMMRZCallRing3Enable(pVCpu);
13097
13098#ifdef VBOX_WITH_STATISTICS
13099 rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13100 AssertRCReturn(rc, rc);
13101 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(pVmxTransient->uExitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
13102 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
13103 else
13104 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
13105#endif
13106 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
13107 return VINF_SUCCESS;
13108 }
13109
13110 /*
13111 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER, CS. EFER is always up-to-date.
13112 * Update the segment registers and DR7 from the CPU.
13113 */
13114 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13115 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
13116 rc |= hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
13117 AssertRCReturn(rc, rc);
13118 Log4(("CS:RIP=%04x:%08RX64\n", pMixedCtx->cs.Sel, pMixedCtx->rip));
13119
13120 PVM pVM = pVCpu->CTX_SUFF(pVM);
13121 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(pVmxTransient->uExitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
13122 {
13123 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx),
13124 VMX_EXIT_QUALIFICATION_DRX_REGISTER(pVmxTransient->uExitQualification),
13125 VMX_EXIT_QUALIFICATION_DRX_GENREG(pVmxTransient->uExitQualification));
13126 if (RT_SUCCESS(rc))
13127 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
13128 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
13129 }
13130 else
13131 {
13132 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx),
13133 VMX_EXIT_QUALIFICATION_DRX_GENREG(pVmxTransient->uExitQualification),
13134 VMX_EXIT_QUALIFICATION_DRX_REGISTER(pVmxTransient->uExitQualification));
13135 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
13136 }
13137
13138 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
13139 if (RT_SUCCESS(rc))
13140 {
13141 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
13142 AssertRCReturn(rc2, rc2);
13143 return VINF_SUCCESS;
13144 }
13145 return rc;
13146}
13147
13148
13149/**
13150 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
13151 * Conditional VM-exit.
13152 */
13153HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13154{
13155 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
13156 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
13157
13158 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
13159 VBOXSTRICTRC rcStrict1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
13160 if (RT_LIKELY(rcStrict1 == VINF_SUCCESS))
13161 {
13162 /* If event delivery causes an EPT misconfig (MMIO), go back to instruction emulation as otherwise
13163 injecting the original pending event would most likely cause the same EPT misconfig VM-exit. */
13164 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
13165 {
13166 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
13167 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13168 }
13169 }
13170 else
13171 {
13172 if (rcStrict1 == VINF_HM_DOUBLE_FAULT)
13173 rcStrict1 = VINF_SUCCESS;
13174 return rcStrict1;
13175 }
13176
13177 RTGCPHYS GCPhys = 0;
13178 int rc = VMXReadVmcs64(VMX_VMCS64_EXIT_GUEST_PHYS_ADDR_FULL, &GCPhys);
13179
13180#if 0
13181 rc |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx); /** @todo Can we do better? */
13182#else
13183 /* Aggressive state sync. for now. */
13184 rc |= hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
13185 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
13186 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
13187#endif
13188 AssertRCReturn(rc, rc);
13189
13190 /*
13191 * If we succeed, resume guest execution.
13192 * If we fail in interpreting the instruction because we couldn't get the guest physical address
13193 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
13194 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
13195 * weird case. See @bugref{6043}.
13196 */
13197 PVM pVM = pVCpu->CTX_SUFF(pVM);
13198 VBOXSTRICTRC rcStrict2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pMixedCtx), GCPhys, UINT32_MAX);
13199 Log4(("EPT misconfig at %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pMixedCtx->rip, VBOXSTRICTRC_VAL(rcStrict2)));
13200 if ( rcStrict2 == VINF_SUCCESS
13201 || rcStrict2 == VERR_PAGE_TABLE_NOT_PRESENT
13202 || rcStrict2 == VERR_PAGE_NOT_PRESENT)
13203 {
13204 /* Successfully handled MMIO operation. */
13205 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13206 | HM_CHANGED_GUEST_RSP
13207 | HM_CHANGED_GUEST_RFLAGS
13208 | HM_CHANGED_VMX_GUEST_APIC_STATE);
13209 return VINF_SUCCESS;
13210 }
13211 return rcStrict2;
13212}
13213
13214
13215/**
13216 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
13217 * VM-exit.
13218 */
13219HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13220{
13221 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
13222 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
13223
13224 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
13225 VBOXSTRICTRC rcStrict1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
13226 if (RT_LIKELY(rcStrict1 == VINF_SUCCESS))
13227 {
13228 /* In the unlikely case that the EPT violation happened as a result of delivering an event, log it. */
13229 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
13230 Log4(("EPT violation with an event pending u64IntInfo=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo));
13231 }
13232 else
13233 {
13234 if (rcStrict1 == VINF_HM_DOUBLE_FAULT)
13235 rcStrict1 = VINF_SUCCESS;
13236 return rcStrict1;
13237 }
13238
13239 RTGCPHYS GCPhys = 0;
13240 int rc = VMXReadVmcs64(VMX_VMCS64_EXIT_GUEST_PHYS_ADDR_FULL, &GCPhys);
13241 rc |= hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13242#if 0
13243 rc |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx); /** @todo Can we do better? */
13244#else
13245 /* Aggressive state sync. for now. */
13246 rc |= hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
13247 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
13248 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
13249#endif
13250 AssertRCReturn(rc, rc);
13251
13252 /* Intel spec. Table 27-7 "Exit Qualifications for EPT violations". */
13253 AssertMsg(((pVmxTransient->uExitQualification >> 7) & 3) != 2, ("%#RX64", pVmxTransient->uExitQualification));
13254
13255 RTGCUINT uErrorCode = 0;
13256 if (pVmxTransient->uExitQualification & VMX_EXIT_QUALIFICATION_EPT_INSTR_FETCH)
13257 uErrorCode |= X86_TRAP_PF_ID;
13258 if (pVmxTransient->uExitQualification & VMX_EXIT_QUALIFICATION_EPT_DATA_WRITE)
13259 uErrorCode |= X86_TRAP_PF_RW;
13260 if (pVmxTransient->uExitQualification & VMX_EXIT_QUALIFICATION_EPT_ENTRY_PRESENT)
13261 uErrorCode |= X86_TRAP_PF_P;
13262
13263 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
13264
13265 Log4(("EPT violation %#x at %#RX64 ErrorCode %#x CS:RIP=%04x:%08RX64\n", pVmxTransient->uExitQualification, GCPhys,
13266 uErrorCode, pMixedCtx->cs.Sel, pMixedCtx->rip));
13267
13268 /* Handle the pagefault trap for the nested shadow table. */
13269 PVM pVM = pVCpu->CTX_SUFF(pVM);
13270 VBOXSTRICTRC rcStrict2 = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pMixedCtx), GCPhys);
13271 TRPMResetTrap(pVCpu);
13272
13273 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
13274 if ( rcStrict2 == VINF_SUCCESS
13275 || rcStrict2 == VERR_PAGE_TABLE_NOT_PRESENT
13276 || rcStrict2 == VERR_PAGE_NOT_PRESENT)
13277 {
13278 /* Successfully synced our nested page tables. */
13279 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
13280 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13281 | HM_CHANGED_GUEST_RSP
13282 | HM_CHANGED_GUEST_RFLAGS);
13283 return VINF_SUCCESS;
13284 }
13285
13286 Log4(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict2)));
13287 return rcStrict2;
13288}
13289
13290/** @} */
13291
13292/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13293/* -=-=-=-=-=-=-=-=-=- VM-exit Exception Handlers -=-=-=-=-=-=-=-=-=-=- */
13294/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13295
13296/** @name VM-exit exception handlers.
13297 * @{
13298 */
13299
13300/**
13301 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
13302 */
13303static int hmR0VmxExitXcptMF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13304{
13305 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13306 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
13307
13308 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
13309 AssertRCReturn(rc, rc);
13310
13311 if (!(pMixedCtx->cr0 & X86_CR0_NE))
13312 {
13313 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
13314 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
13315
13316 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
13317 * provides VM-exit instruction length. If this causes problem later,
13318 * disassemble the instruction like it's done on AMD-V. */
13319 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
13320 AssertRCReturn(rc2, rc2);
13321 return rc;
13322 }
13323
13324 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13325 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13326 return rc;
13327}
13328
13329
13330/**
13331 * VM-exit exception handler for \#BP (Breakpoint exception).
13332 */
13333static int hmR0VmxExitXcptBP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13334{
13335 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13336 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
13337
13338 /** @todo Try optimize this by not saving the entire guest state unless
13339 * really needed. */
13340 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13341 AssertRCReturn(rc, rc);
13342
13343 PVM pVM = pVCpu->CTX_SUFF(pVM);
13344 rc = DBGFRZTrap03Handler(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
13345 if (rc == VINF_EM_RAW_GUEST_TRAP)
13346 {
13347 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13348 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13349 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13350 AssertRCReturn(rc, rc);
13351
13352 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13353 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13354 }
13355
13356 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
13357 return rc;
13358}
13359
13360
13361/**
13362 * VM-exit exception handler for \#AC (alignment check exception).
13363 */
13364static int hmR0VmxExitXcptAC(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13365{
13366 RT_NOREF_PV(pMixedCtx);
13367 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13368
13369 /*
13370 * Re-inject it. We'll detect any nesting before getting here.
13371 */
13372 int rc = hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13373 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13374 AssertRCReturn(rc, rc);
13375 Assert(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO);
13376
13377 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13378 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13379 return VINF_SUCCESS;
13380}
13381
13382
13383/**
13384 * VM-exit exception handler for \#DB (Debug exception).
13385 */
13386static int hmR0VmxExitXcptDB(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13387{
13388 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13389 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
13390 Log6(("XcptDB\n"));
13391
13392 /*
13393 * Get the DR6-like values from the VM-exit qualification and pass it to DBGF
13394 * for processing.
13395 */
13396 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13397 AssertRCReturn(rc, rc);
13398
13399 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
13400 uint64_t uDR6 = X86_DR6_INIT_VAL;
13401 uDR6 |= ( pVmxTransient->uExitQualification
13402 & (X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3 | X86_DR6_BD | X86_DR6_BS));
13403
13404 rc = DBGFRZTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pMixedCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
13405 if (rc == VINF_EM_RAW_GUEST_TRAP)
13406 {
13407 /*
13408 * The exception was for the guest. Update DR6, DR7.GD and
13409 * IA32_DEBUGCTL.LBR before forwarding it.
13410 * (See Intel spec. 27.1 "Architectural State before a VM-Exit".)
13411 */
13412 VMMRZCallRing3Disable(pVCpu);
13413 HM_DISABLE_PREEMPT();
13414
13415 pMixedCtx->dr[6] &= ~X86_DR6_B_MASK;
13416 pMixedCtx->dr[6] |= uDR6;
13417 if (CPUMIsGuestDebugStateActive(pVCpu))
13418 ASMSetDR6(pMixedCtx->dr[6]);
13419
13420 HM_RESTORE_PREEMPT();
13421 VMMRZCallRing3Enable(pVCpu);
13422
13423 rc = hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
13424 AssertRCReturn(rc, rc);
13425
13426 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
13427 pMixedCtx->dr[7] &= ~X86_DR7_GD;
13428
13429 /* Paranoia. */
13430 pMixedCtx->dr[7] &= ~X86_DR7_RAZ_MASK;
13431 pMixedCtx->dr[7] |= X86_DR7_RA1_MASK;
13432
13433 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_DR7, (uint32_t)pMixedCtx->dr[7]);
13434 AssertRCReturn(rc, rc);
13435
13436 /*
13437 * Raise #DB in the guest.
13438 *
13439 * It is important to reflect what the VM-exit gave us (preserving the interruption-type) rather than use
13440 * hmR0VmxSetPendingXcptDB() as the #DB could've been raised while executing ICEBP and not the 'normal' #DB.
13441 * Thus it -may- trigger different handling in the CPU (like skipped DPL checks). See @bugref{6398}.
13442 *
13443 * Since ICEBP isn't documented on Intel, see AMD spec. 15.20 "Event Injection".
13444 */
13445 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13446 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13447 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13448 AssertRCReturn(rc, rc);
13449 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13450 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13451 return VINF_SUCCESS;
13452 }
13453
13454 /*
13455 * Not a guest trap, must be a hypervisor related debug event then.
13456 * Update DR6 in case someone is interested in it.
13457 */
13458 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
13459 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
13460 CPUMSetHyperDR6(pVCpu, uDR6);
13461
13462 return rc;
13463}
13464
13465
13466/**
13467 * VM-exit exception handler for \#NM (Device-not-available exception: floating
13468 * point exception).
13469 */
13470static int hmR0VmxExitXcptNM(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13471{
13472 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13473
13474 /* We require CR0 and EFER. EFER is always up-to-date. */
13475 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
13476 AssertRCReturn(rc, rc);
13477
13478 /* We're playing with the host CPU state here, have to disable preemption or longjmp. */
13479 VMMRZCallRing3Disable(pVCpu);
13480 HM_DISABLE_PREEMPT();
13481
13482 /* If the guest FPU was active at the time of the #NM VM-exit, then it's a guest fault. */
13483 if (pVmxTransient->fWasGuestFPUStateActive)
13484 {
13485 rc = VINF_EM_RAW_GUEST_TRAP;
13486 Assert(CPUMIsGuestFPUStateActive(pVCpu) || HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
13487 }
13488 else
13489 {
13490#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13491 Assert(!pVmxTransient->fWasGuestFPUStateActive || pVCpu->hm.s.fUsingDebugLoop);
13492#endif
13493 rc = CPUMR0Trap07Handler(pVCpu->CTX_SUFF(pVM), pVCpu);
13494 Assert( rc == VINF_EM_RAW_GUEST_TRAP
13495 || ((rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED) && CPUMIsGuestFPUStateActive(pVCpu)));
13496 if (rc == VINF_CPUM_HOST_CR0_MODIFIED)
13497 HMCPU_CF_SET(pVCpu, HM_CHANGED_HOST_CONTEXT);
13498 }
13499
13500 HM_RESTORE_PREEMPT();
13501 VMMRZCallRing3Enable(pVCpu);
13502
13503 if (rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED)
13504 {
13505 /* Guest FPU state was activated, we'll want to change CR0 FPU intercepts before the next VM-reentry. */
13506 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
13507 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
13508 pVCpu->hm.s.fPreloadGuestFpu = true;
13509 }
13510 else
13511 {
13512 /* Forward #NM to the guest. */
13513 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
13514 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13515 AssertRCReturn(rc, rc);
13516 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13517 pVmxTransient->cbInstr, 0 /* error code */, 0 /* GCPtrFaultAddress */);
13518 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
13519 }
13520
13521 return VINF_SUCCESS;
13522}
13523
13524
13525/**
13526 * VM-exit exception handler for \#GP (General-protection exception).
13527 *
13528 * @remarks Requires pVmxTransient->uExitIntInfo to be up-to-date.
13529 */
13530static int hmR0VmxExitXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13531{
13532 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13533 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
13534
13535 int rc;
13536 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
13537 { /* likely */ }
13538 else
13539 {
13540#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13541 Assert(pVCpu->hm.s.fUsingDebugLoop);
13542#endif
13543 /* If the guest is not in real-mode or we have unrestricted execution support, reflect #GP to the guest. */
13544 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13545 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13546 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13547 rc |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13548 AssertRCReturn(rc, rc);
13549 Log4(("#GP Gst: CS:RIP %04x:%08RX64 ErrorCode=%#x CR0=%#RX64 CPL=%u TR=%#04x\n", pMixedCtx->cs.Sel, pMixedCtx->rip,
13550 pVmxTransient->uExitIntErrorCode, pMixedCtx->cr0, CPUMGetGuestCPL(pVCpu), pMixedCtx->tr.Sel));
13551 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13552 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13553 return rc;
13554 }
13555
13556 Assert(CPUMIsGuestInRealModeEx(pMixedCtx));
13557 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest);
13558
13559 /* EMInterpretDisasCurrent() requires a lot of the state, save the entire state. */
13560 rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13561 AssertRCReturn(rc, rc);
13562
13563 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
13564 uint32_t cbOp = 0;
13565 PVM pVM = pVCpu->CTX_SUFF(pVM);
13566 bool fDbgStepping = pVCpu->hm.s.fSingleInstruction;
13567 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
13568 if (RT_SUCCESS(rc))
13569 {
13570 rc = VINF_SUCCESS;
13571 Assert(cbOp == pDis->cbInstr);
13572 Log4(("#GP Disas OpCode=%u CS:EIP %04x:%04RX64\n", pDis->pCurInstr->uOpcode, pMixedCtx->cs.Sel, pMixedCtx->rip));
13573 switch (pDis->pCurInstr->uOpcode)
13574 {
13575 case OP_CLI:
13576 {
13577 pMixedCtx->eflags.Bits.u1IF = 0;
13578 pMixedCtx->eflags.Bits.u1RF = 0;
13579 pMixedCtx->rip += pDis->cbInstr;
13580 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13581 if ( !fDbgStepping
13582 && pMixedCtx->eflags.Bits.u1TF)
13583 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13584 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCli);
13585 break;
13586 }
13587
13588 case OP_STI:
13589 {
13590 bool fOldIF = pMixedCtx->eflags.Bits.u1IF;
13591 pMixedCtx->eflags.Bits.u1IF = 1;
13592 pMixedCtx->eflags.Bits.u1RF = 0;
13593 pMixedCtx->rip += pDis->cbInstr;
13594 if (!fOldIF)
13595 {
13596 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
13597 Assert(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
13598 }
13599 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13600 if ( !fDbgStepping
13601 && pMixedCtx->eflags.Bits.u1TF)
13602 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13603 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitSti);
13604 break;
13605 }
13606
13607 case OP_HLT:
13608 {
13609 rc = VINF_EM_HALT;
13610 pMixedCtx->rip += pDis->cbInstr;
13611 pMixedCtx->eflags.Bits.u1RF = 0;
13612 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13613 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
13614 break;
13615 }
13616
13617 case OP_POPF:
13618 {
13619 Log4(("POPF CS:EIP %04x:%04RX64\n", pMixedCtx->cs.Sel, pMixedCtx->rip));
13620 uint32_t cbParm;
13621 uint32_t uMask;
13622 bool fGstStepping = RT_BOOL(pMixedCtx->eflags.Bits.u1TF);
13623 if (pDis->fPrefix & DISPREFIX_OPSIZE)
13624 {
13625 cbParm = 4;
13626 uMask = 0xffffffff;
13627 }
13628 else
13629 {
13630 cbParm = 2;
13631 uMask = 0xffff;
13632 }
13633
13634 /* Get the stack pointer & pop the contents of the stack onto Eflags. */
13635 RTGCPTR GCPtrStack = 0;
13636 X86EFLAGS Eflags;
13637 Eflags.u32 = 0;
13638 rc = SELMToFlatEx(pVCpu, DISSELREG_SS, CPUMCTX2CORE(pMixedCtx), pMixedCtx->esp & uMask, SELMTOFLAT_FLAGS_CPL0,
13639 &GCPtrStack);
13640 if (RT_SUCCESS(rc))
13641 {
13642 Assert(sizeof(Eflags.u32) >= cbParm);
13643 rc = VBOXSTRICTRC_TODO(PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &Eflags.u32, cbParm, PGMACCESSORIGIN_HM));
13644 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc)); /** @todo allow strict return codes here */
13645 }
13646 if (RT_FAILURE(rc))
13647 {
13648 rc = VERR_EM_INTERPRETER;
13649 break;
13650 }
13651 Log4(("POPF %#x -> %#RX64 mask=%#x RIP=%#RX64\n", Eflags.u, pMixedCtx->rsp, uMask, pMixedCtx->rip));
13652 pMixedCtx->eflags.u32 = (pMixedCtx->eflags.u32 & ~((X86_EFL_POPF_BITS & uMask) | X86_EFL_RF))
13653 | (Eflags.u32 & X86_EFL_POPF_BITS & uMask);
13654 pMixedCtx->esp += cbParm;
13655 pMixedCtx->esp &= uMask;
13656 pMixedCtx->rip += pDis->cbInstr;
13657 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13658 | HM_CHANGED_GUEST_RSP
13659 | HM_CHANGED_GUEST_RFLAGS);
13660 /* Generate a pending-debug exception when the guest stepping over POPF regardless of how
13661 POPF restores EFLAGS.TF. */
13662 if ( !fDbgStepping
13663 && fGstStepping)
13664 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13665 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPopf);
13666 break;
13667 }
13668
13669 case OP_PUSHF:
13670 {
13671 uint32_t cbParm;
13672 uint32_t uMask;
13673 if (pDis->fPrefix & DISPREFIX_OPSIZE)
13674 {
13675 cbParm = 4;
13676 uMask = 0xffffffff;
13677 }
13678 else
13679 {
13680 cbParm = 2;
13681 uMask = 0xffff;
13682 }
13683
13684 /* Get the stack pointer & push the contents of eflags onto the stack. */
13685 RTGCPTR GCPtrStack = 0;
13686 rc = SELMToFlatEx(pVCpu, DISSELREG_SS, CPUMCTX2CORE(pMixedCtx), (pMixedCtx->esp - cbParm) & uMask,
13687 SELMTOFLAT_FLAGS_CPL0, &GCPtrStack);
13688 if (RT_FAILURE(rc))
13689 {
13690 rc = VERR_EM_INTERPRETER;
13691 break;
13692 }
13693 X86EFLAGS Eflags = pMixedCtx->eflags;
13694 /* The RF & VM bits are cleared on image stored on stack; see Intel Instruction reference for PUSHF. */
13695 Eflags.Bits.u1RF = 0;
13696 Eflags.Bits.u1VM = 0;
13697
13698 rc = VBOXSTRICTRC_TODO(PGMPhysWrite(pVM, (RTGCPHYS)GCPtrStack, &Eflags.u, cbParm, PGMACCESSORIGIN_HM));
13699 if (RT_UNLIKELY(rc != VINF_SUCCESS))
13700 {
13701 AssertMsgFailed(("%Rrc\n", rc)); /** @todo allow strict return codes here */
13702 rc = VERR_EM_INTERPRETER;
13703 break;
13704 }
13705 Log4(("PUSHF %#x -> %#RGv\n", Eflags.u, GCPtrStack));
13706 pMixedCtx->esp -= cbParm;
13707 pMixedCtx->esp &= uMask;
13708 pMixedCtx->rip += pDis->cbInstr;
13709 pMixedCtx->eflags.Bits.u1RF = 0;
13710 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13711 | HM_CHANGED_GUEST_RSP
13712 | HM_CHANGED_GUEST_RFLAGS);
13713 if ( !fDbgStepping
13714 && pMixedCtx->eflags.Bits.u1TF)
13715 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13716 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPushf);
13717 break;
13718 }
13719
13720 case OP_IRET:
13721 {
13722 /** @todo Handle 32-bit operand sizes and check stack limits. See Intel
13723 * instruction reference. */
13724 RTGCPTR GCPtrStack = 0;
13725 uint32_t uMask = 0xffff;
13726 bool fGstStepping = RT_BOOL(pMixedCtx->eflags.Bits.u1TF);
13727 uint16_t aIretFrame[3];
13728 if (pDis->fPrefix & (DISPREFIX_OPSIZE | DISPREFIX_ADDRSIZE))
13729 {
13730 rc = VERR_EM_INTERPRETER;
13731 break;
13732 }
13733 rc = SELMToFlatEx(pVCpu, DISSELREG_SS, CPUMCTX2CORE(pMixedCtx), pMixedCtx->esp & uMask, SELMTOFLAT_FLAGS_CPL0,
13734 &GCPtrStack);
13735 if (RT_SUCCESS(rc))
13736 {
13737 rc = VBOXSTRICTRC_TODO(PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &aIretFrame[0], sizeof(aIretFrame),
13738 PGMACCESSORIGIN_HM));
13739 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc)); /** @todo allow strict return codes here */
13740 }
13741 if (RT_FAILURE(rc))
13742 {
13743 rc = VERR_EM_INTERPRETER;
13744 break;
13745 }
13746 pMixedCtx->eip = 0;
13747 pMixedCtx->ip = aIretFrame[0];
13748 pMixedCtx->cs.Sel = aIretFrame[1];
13749 pMixedCtx->cs.ValidSel = aIretFrame[1];
13750 pMixedCtx->cs.u64Base = (uint64_t)pMixedCtx->cs.Sel << 4;
13751 pMixedCtx->eflags.u32 = (pMixedCtx->eflags.u32 & ((UINT32_C(0xffff0000) | X86_EFL_1) & ~X86_EFL_RF))
13752 | (aIretFrame[2] & X86_EFL_POPF_BITS & uMask);
13753 pMixedCtx->sp += sizeof(aIretFrame);
13754 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13755 | HM_CHANGED_GUEST_SEGMENT_REGS
13756 | HM_CHANGED_GUEST_RSP
13757 | HM_CHANGED_GUEST_RFLAGS);
13758 /* Generate a pending-debug exception when stepping over IRET regardless of how IRET modifies EFLAGS.TF. */
13759 if ( !fDbgStepping
13760 && fGstStepping)
13761 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13762 Log4(("IRET %#RX32 to %04x:%04x\n", GCPtrStack, pMixedCtx->cs.Sel, pMixedCtx->ip));
13763 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIret);
13764 break;
13765 }
13766
13767 case OP_INT:
13768 {
13769 uint16_t uVector = pDis->Param1.uValue & 0xff;
13770 hmR0VmxSetPendingIntN(pVCpu, pMixedCtx, uVector, pDis->cbInstr);
13771 /* INT clears EFLAGS.TF, we must not set any pending debug exceptions here. */
13772 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInt);
13773 break;
13774 }
13775
13776 case OP_INTO:
13777 {
13778 if (pMixedCtx->eflags.Bits.u1OF)
13779 {
13780 hmR0VmxSetPendingXcptOF(pVCpu, pMixedCtx, pDis->cbInstr);
13781 /* INTO clears EFLAGS.TF, we must not set any pending debug exceptions here. */
13782 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInt);
13783 }
13784 else
13785 {
13786 pMixedCtx->eflags.Bits.u1RF = 0;
13787 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RFLAGS);
13788 }
13789 break;
13790 }
13791
13792 default:
13793 {
13794 pMixedCtx->eflags.Bits.u1RF = 0; /* This is correct most of the time... */
13795 VBOXSTRICTRC rc2 = EMInterpretInstructionDisasState(pVCpu, pDis, CPUMCTX2CORE(pMixedCtx), 0 /* pvFault */,
13796 EMCODETYPE_SUPERVISOR);
13797 rc = VBOXSTRICTRC_VAL(rc2);
13798 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
13799 /** @todo We have to set pending-debug exceptions here when the guest is
13800 * single-stepping depending on the instruction that was interpreted. */
13801 Log4(("#GP rc=%Rrc\n", rc));
13802 break;
13803 }
13804 }
13805 }
13806 else
13807 rc = VERR_EM_INTERPRETER;
13808
13809 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_EM_HALT,
13810 ("#GP Unexpected rc=%Rrc\n", rc));
13811 return rc;
13812}
13813
13814
13815/**
13816 * VM-exit exception handler wrapper for generic exceptions. Simply re-injects
13817 * the exception reported in the VMX transient structure back into the VM.
13818 *
13819 * @remarks Requires uExitIntInfo in the VMX transient structure to be
13820 * up-to-date.
13821 */
13822static int hmR0VmxExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13823{
13824 RT_NOREF_PV(pMixedCtx);
13825 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13826#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13827 AssertMsg(pVCpu->hm.s.fUsingDebugLoop || pVCpu->hm.s.vmx.RealMode.fRealOnV86Active,
13828 ("uVector=%#04x u32XcptBitmap=%#010RX32\n",
13829 VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo), pVCpu->hm.s.vmx.u32XcptBitmap));
13830#endif
13831
13832 /* Re-inject the exception into the guest. This cannot be a double-fault condition which would have been handled in
13833 hmR0VmxCheckExitDueToEventDelivery(). */
13834 int rc = hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13835 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13836 AssertRCReturn(rc, rc);
13837 Assert(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO);
13838
13839#ifdef DEBUG_ramshankar
13840 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
13841 uint8_t uVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13842 Log(("hmR0VmxExitXcptGeneric: Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
13843#endif
13844
13845 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13846 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13847 return VINF_SUCCESS;
13848}
13849
13850
13851/**
13852 * VM-exit exception handler for \#PF (Page-fault exception).
13853 */
13854static int hmR0VmxExitXcptPF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13855{
13856 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13857 PVM pVM = pVCpu->CTX_SUFF(pVM);
13858 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13859 rc |= hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13860 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13861 AssertRCReturn(rc, rc);
13862
13863 if (!pVM->hm.s.fNestedPaging)
13864 { /* likely */ }
13865 else
13866 {
13867#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
13868 Assert(pVCpu->hm.s.fUsingDebugLoop);
13869#endif
13870 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
13871 if (RT_LIKELY(!pVmxTransient->fVectoringDoublePF))
13872 {
13873 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13874 0 /* cbInstr */, pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQualification);
13875 }
13876 else
13877 {
13878 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13879 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
13880 Log4(("Pending #DF due to vectoring #PF. NP\n"));
13881 }
13882 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13883 return rc;
13884 }
13885
13886 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
13887 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
13888 if (pVmxTransient->fVectoringPF)
13889 {
13890 Assert(pVCpu->hm.s.Event.fPending);
13891 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13892 }
13893
13894 rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13895 AssertRCReturn(rc, rc);
13896
13897 Log4(("#PF: cr2=%#RX64 cs:rip=%#04x:%#RX64 uErrCode %#RX32 cr3=%#RX64\n", pVmxTransient->uExitQualification,
13898 pMixedCtx->cs.Sel, pMixedCtx->rip, pVmxTransient->uExitIntErrorCode, pMixedCtx->cr3));
13899
13900 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQualification, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
13901 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pMixedCtx),
13902 (RTGCPTR)pVmxTransient->uExitQualification);
13903
13904 Log4(("#PF: rc=%Rrc\n", rc));
13905 if (rc == VINF_SUCCESS)
13906 {
13907#if 0
13908 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
13909 /** @todo this isn't quite right, what if guest does lgdt with some MMIO
13910 * memory? We don't update the whole state here... */
13911 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13912 | HM_CHANGED_GUEST_RSP
13913 | HM_CHANGED_GUEST_RFLAGS
13914 | HM_CHANGED_VMX_GUEST_APIC_STATE);
13915#else
13916 /*
13917 * This is typically a shadow page table sync or a MMIO instruction. But we may have
13918 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
13919 */
13920 /** @todo take advantage of CPUM changed flags instead of brute forcing. */
13921 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
13922#endif
13923 TRPMResetTrap(pVCpu);
13924 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
13925 return rc;
13926 }
13927
13928 if (rc == VINF_EM_RAW_GUEST_TRAP)
13929 {
13930 if (!pVmxTransient->fVectoringDoublePF)
13931 {
13932 /* It's a guest page fault and needs to be reflected to the guest. */
13933 uint32_t uGstErrorCode = TRPMGetErrorCode(pVCpu);
13934 TRPMResetTrap(pVCpu);
13935 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
13936 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13937 0 /* cbInstr */, uGstErrorCode, pVmxTransient->uExitQualification);
13938 }
13939 else
13940 {
13941 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13942 TRPMResetTrap(pVCpu);
13943 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
13944 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
13945 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
13946 }
13947
13948 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13949 return VINF_SUCCESS;
13950 }
13951
13952 TRPMResetTrap(pVCpu);
13953 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
13954 return rc;
13955}
13956
13957/** @} */
13958
Note: See TracBrowser for help on using the repository browser.

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