VirtualBox

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

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

VMM: warnings (clang)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 583.3 KB
Line 
1/* $Id: HMVMXR0.cpp 63465 2016-08-15 10:00:20Z 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.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#include <iprt/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#ifdef VBOX_WITH_REM
35# include <VBox/vmm/rem.h>
36#endif
37#ifdef VBOX_WITH_NEW_APIC
38# include <VBox/vmm/apic.h>
39#endif
40#include "HMInternal.h"
41#include <VBox/vmm/vm.h>
42#include "HMVMXR0.h"
43#include "dtrace/VBoxVMM.h"
44
45#ifdef DEBUG_ramshankar
46# define HMVMX_ALWAYS_SAVE_GUEST_RFLAGS
47# define HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE
48# define HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
49# define HMVMX_ALWAYS_CHECK_GUEST_STATE
50# define HMVMX_ALWAYS_TRAP_ALL_XCPTS
51# define HMVMX_ALWAYS_TRAP_PF
52# define HMVMX_ALWAYS_SWAP_FPU_STATE
53# define HMVMX_ALWAYS_FLUSH_TLB
54# define HMVMX_ALWAYS_SWAP_EFER
55#endif
56
57
58/*********************************************************************************************************************************
59* Defined Constants And Macros *
60*********************************************************************************************************************************/
61/** Use the function table. */
62#define HMVMX_USE_FUNCTION_TABLE
63
64/** Determine which tagged-TLB flush handler to use. */
65#define HMVMX_FLUSH_TAGGED_TLB_EPT_VPID 0
66#define HMVMX_FLUSH_TAGGED_TLB_EPT 1
67#define HMVMX_FLUSH_TAGGED_TLB_VPID 2
68#define HMVMX_FLUSH_TAGGED_TLB_NONE 3
69
70/** @name Updated-guest-state flags.
71 * @{ */
72#define HMVMX_UPDATED_GUEST_RIP RT_BIT(0)
73#define HMVMX_UPDATED_GUEST_RSP RT_BIT(1)
74#define HMVMX_UPDATED_GUEST_RFLAGS RT_BIT(2)
75#define HMVMX_UPDATED_GUEST_CR0 RT_BIT(3)
76#define HMVMX_UPDATED_GUEST_CR3 RT_BIT(4)
77#define HMVMX_UPDATED_GUEST_CR4 RT_BIT(5)
78#define HMVMX_UPDATED_GUEST_GDTR RT_BIT(6)
79#define HMVMX_UPDATED_GUEST_IDTR RT_BIT(7)
80#define HMVMX_UPDATED_GUEST_LDTR RT_BIT(8)
81#define HMVMX_UPDATED_GUEST_TR RT_BIT(9)
82#define HMVMX_UPDATED_GUEST_SEGMENT_REGS RT_BIT(10)
83#define HMVMX_UPDATED_GUEST_DEBUG RT_BIT(11)
84#define HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR RT_BIT(12)
85#define HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR RT_BIT(13)
86#define HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR RT_BIT(14)
87#define HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS RT_BIT(15)
88#define HMVMX_UPDATED_GUEST_LAZY_MSRS RT_BIT(16)
89#define HMVMX_UPDATED_GUEST_ACTIVITY_STATE RT_BIT(17)
90#define HMVMX_UPDATED_GUEST_INTR_STATE RT_BIT(18)
91#define HMVMX_UPDATED_GUEST_APIC_STATE RT_BIT(19)
92#define HMVMX_UPDATED_GUEST_ALL ( HMVMX_UPDATED_GUEST_RIP \
93 | HMVMX_UPDATED_GUEST_RSP \
94 | HMVMX_UPDATED_GUEST_RFLAGS \
95 | HMVMX_UPDATED_GUEST_CR0 \
96 | HMVMX_UPDATED_GUEST_CR3 \
97 | HMVMX_UPDATED_GUEST_CR4 \
98 | HMVMX_UPDATED_GUEST_GDTR \
99 | HMVMX_UPDATED_GUEST_IDTR \
100 | HMVMX_UPDATED_GUEST_LDTR \
101 | HMVMX_UPDATED_GUEST_TR \
102 | HMVMX_UPDATED_GUEST_SEGMENT_REGS \
103 | HMVMX_UPDATED_GUEST_DEBUG \
104 | HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR \
105 | HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR \
106 | HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR \
107 | HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS \
108 | HMVMX_UPDATED_GUEST_LAZY_MSRS \
109 | HMVMX_UPDATED_GUEST_ACTIVITY_STATE \
110 | HMVMX_UPDATED_GUEST_INTR_STATE \
111 | HMVMX_UPDATED_GUEST_APIC_STATE)
112/** @} */
113
114/** @name
115 * Flags to skip redundant reads of some common VMCS fields that are not part of
116 * the guest-CPU state but are in the transient structure.
117 */
118#define HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_INFO RT_BIT(0)
119#define HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_ERROR_CODE RT_BIT(1)
120#define HMVMX_UPDATED_TRANSIENT_EXIT_QUALIFICATION RT_BIT(2)
121#define HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_LEN RT_BIT(3)
122#define HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO RT_BIT(4)
123#define HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_ERROR_CODE RT_BIT(5)
124#define HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_INFO RT_BIT(6)
125/** @} */
126
127/** @name
128 * States of the VMCS.
129 *
130 * This does not reflect all possible VMCS states but currently only those
131 * needed for maintaining the VMCS consistently even when thread-context hooks
132 * are used. Maybe later this can be extended (i.e. Nested Virtualization).
133 */
134#define HMVMX_VMCS_STATE_CLEAR RT_BIT(0)
135#define HMVMX_VMCS_STATE_ACTIVE RT_BIT(1)
136#define HMVMX_VMCS_STATE_LAUNCHED RT_BIT(2)
137/** @} */
138
139/**
140 * Exception bitmap mask for real-mode guests (real-on-v86).
141 *
142 * We need to intercept all exceptions manually except:
143 * - \#NM, \#MF handled in hmR0VmxLoadSharedCR0().
144 * - \#AC and \#DB are always intercepted to prevent the CPU from deadlocking
145 * due to bugs in Intel CPUs.
146 * - \#PF need not be intercepted even in real-mode if we have Nested Paging
147 * support.
148 */
149#define HMVMX_REAL_MODE_XCPT_MASK ( RT_BIT(X86_XCPT_DE) /* always: | RT_BIT(X86_XCPT_DB) */ | RT_BIT(X86_XCPT_NMI) \
150 | RT_BIT(X86_XCPT_BP) | RT_BIT(X86_XCPT_OF) | RT_BIT(X86_XCPT_BR) \
151 | RT_BIT(X86_XCPT_UD) /* RT_BIT(X86_XCPT_NM) */ | RT_BIT(X86_XCPT_DF) \
152 | RT_BIT(X86_XCPT_CO_SEG_OVERRUN) | RT_BIT(X86_XCPT_TS) | RT_BIT(X86_XCPT_NP) \
153 | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_GP) /* RT_BIT(X86_XCPT_PF) */ \
154 /* RT_BIT(X86_XCPT_MF) always: | RT_BIT(X86_XCPT_AC) */ | RT_BIT(X86_XCPT_MC) \
155 | RT_BIT(X86_XCPT_XF))
156
157/**
158 * Exception bitmap mask for all contributory exceptions.
159 *
160 * Page fault is deliberately excluded here as it's conditional as to whether
161 * it's contributory or benign. Page faults are handled separately.
162 */
163#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) \
164 | RT_BIT(X86_XCPT_DE))
165
166/** Maximum VM-instruction error number. */
167#define HMVMX_INSTR_ERROR_MAX 28
168
169/** Profiling macro. */
170#ifdef HM_PROFILE_EXIT_DISPATCH
171# define HMVMX_START_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitDispatch, ed)
172# define HMVMX_STOP_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitDispatch, ed)
173#else
174# define HMVMX_START_EXIT_DISPATCH_PROF() do { } while (0)
175# define HMVMX_STOP_EXIT_DISPATCH_PROF() do { } while (0)
176#endif
177
178/** Assert that preemption is disabled or covered by thread-context hooks. */
179#define HMVMX_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
180 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
181
182/** Assert that we haven't migrated CPUs when thread-context hooks are not
183 * used. */
184#define HMVMX_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
185 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
186 ("Illegal migration! Entered on CPU %u Current %u\n", \
187 pVCpu->hm.s.idEnteredCpu, RTMpCpuId())); \
188
189/** Helper macro for VM-exit handlers called unexpectedly. */
190#define HMVMX_RETURN_UNEXPECTED_EXIT() \
191 do { \
192 pVCpu->hm.s.u32HMError = pVmxTransient->uExitReason; \
193 return VERR_VMX_UNEXPECTED_EXIT; \
194 } while (0)
195
196
197/*********************************************************************************************************************************
198* Structures and Typedefs *
199*********************************************************************************************************************************/
200/**
201 * VMX transient state.
202 *
203 * A state structure for holding miscellaneous information across
204 * VMX non-root operation and restored after the transition.
205 */
206typedef struct VMXTRANSIENT
207{
208 /** The host's rflags/eflags. */
209 RTCCUINTREG fEFlags;
210#if HC_ARCH_BITS == 32
211 uint32_t u32Alignment0;
212#endif
213 /** The guest's TPR value used for TPR shadowing. */
214 uint8_t u8GuestTpr;
215 /** Alignment. */
216 uint8_t abAlignment0[7];
217
218 /** The basic VM-exit reason. */
219 uint16_t uExitReason;
220 /** Alignment. */
221 uint16_t u16Alignment0;
222 /** The VM-exit interruption error code. */
223 uint32_t uExitIntErrorCode;
224 /** The VM-exit exit code qualification. */
225 uint64_t uExitQualification;
226
227 /** The VM-exit interruption-information field. */
228 uint32_t uExitIntInfo;
229 /** The VM-exit instruction-length field. */
230 uint32_t cbInstr;
231 /** The VM-exit instruction-information field. */
232 union
233 {
234 /** Plain unsigned int representation. */
235 uint32_t u;
236 /** INS and OUTS information. */
237 struct
238 {
239 uint32_t u7Reserved0 : 7;
240 /** The address size; 0=16-bit, 1=32-bit, 2=64-bit, rest undefined. */
241 uint32_t u3AddrSize : 3;
242 uint32_t u5Reserved1 : 5;
243 /** The segment register (X86_SREG_XXX). */
244 uint32_t iSegReg : 3;
245 uint32_t uReserved2 : 14;
246 } StrIo;
247 } ExitInstrInfo;
248 /** Whether the VM-entry failed or not. */
249 bool fVMEntryFailed;
250 /** Alignment. */
251 uint8_t abAlignment1[3];
252
253 /** The VM-entry interruption-information field. */
254 uint32_t uEntryIntInfo;
255 /** The VM-entry exception error code field. */
256 uint32_t uEntryXcptErrorCode;
257 /** The VM-entry instruction length field. */
258 uint32_t cbEntryInstr;
259
260 /** IDT-vectoring information field. */
261 uint32_t uIdtVectoringInfo;
262 /** IDT-vectoring error code. */
263 uint32_t uIdtVectoringErrorCode;
264
265 /** Mask of currently read VMCS fields; HMVMX_UPDATED_TRANSIENT_*. */
266 uint32_t fVmcsFieldsRead;
267
268 /** Whether the guest FPU was active at the time of VM-exit. */
269 bool fWasGuestFPUStateActive;
270 /** Whether the guest debug state was active at the time of VM-exit. */
271 bool fWasGuestDebugStateActive;
272 /** Whether the hyper debug state was active at the time of VM-exit. */
273 bool fWasHyperDebugStateActive;
274 /** Whether TSC-offsetting should be setup before VM-entry. */
275 bool fUpdateTscOffsettingAndPreemptTimer;
276 /** Whether the VM-exit was caused by a page-fault during delivery of a
277 * contributory exception or a page-fault. */
278 bool fVectoringDoublePF;
279 /** Whether the VM-exit was caused by a page-fault during delivery of an
280 * external interrupt or NMI. */
281 bool fVectoringPF;
282} VMXTRANSIENT;
283AssertCompileMemberAlignment(VMXTRANSIENT, uExitReason, sizeof(uint64_t));
284AssertCompileMemberAlignment(VMXTRANSIENT, uExitIntInfo, sizeof(uint64_t));
285AssertCompileMemberAlignment(VMXTRANSIENT, uEntryIntInfo, sizeof(uint64_t));
286AssertCompileMemberAlignment(VMXTRANSIENT, fWasGuestFPUStateActive, sizeof(uint64_t));
287AssertCompileMemberSize(VMXTRANSIENT, ExitInstrInfo, sizeof(uint32_t));
288/** Pointer to VMX transient state. */
289typedef VMXTRANSIENT *PVMXTRANSIENT;
290
291
292/**
293 * MSR-bitmap read permissions.
294 */
295typedef enum VMXMSREXITREAD
296{
297 /** Reading this MSR causes a VM-exit. */
298 VMXMSREXIT_INTERCEPT_READ = 0xb,
299 /** Reading this MSR does not cause a VM-exit. */
300 VMXMSREXIT_PASSTHRU_READ
301} VMXMSREXITREAD;
302/** Pointer to MSR-bitmap read permissions. */
303typedef VMXMSREXITREAD* PVMXMSREXITREAD;
304
305/**
306 * MSR-bitmap write permissions.
307 */
308typedef enum VMXMSREXITWRITE
309{
310 /** Writing to this MSR causes a VM-exit. */
311 VMXMSREXIT_INTERCEPT_WRITE = 0xd,
312 /** Writing to this MSR does not cause a VM-exit. */
313 VMXMSREXIT_PASSTHRU_WRITE
314} VMXMSREXITWRITE;
315/** Pointer to MSR-bitmap write permissions. */
316typedef VMXMSREXITWRITE* PVMXMSREXITWRITE;
317
318
319/**
320 * VMX VM-exit handler.
321 *
322 * @returns Strict VBox status code (i.e. informational status codes too).
323 * @param pVCpu The cross context virtual CPU structure.
324 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
325 * out-of-sync. Make sure to update the required
326 * fields before using them.
327 * @param pVmxTransient Pointer to the VMX-transient structure.
328 */
329#ifndef HMVMX_USE_FUNCTION_TABLE
330typedef DECLINLINE(VBOXSTRICTRC) FNVMXEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
331#else
332typedef DECLCALLBACK(VBOXSTRICTRC) FNVMXEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
333/** Pointer to VM-exit handler. */
334typedef FNVMXEXITHANDLER *PFNVMXEXITHANDLER;
335#endif
336
337/**
338 * VMX VM-exit handler, non-strict status code.
339 *
340 * This is generally the same as FNVMXEXITHANDLER, the NSRC bit is just FYI.
341 *
342 * @returns VBox status code, no informational status code returned.
343 * @param pVCpu The cross context virtual CPU structure.
344 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
345 * out-of-sync. Make sure to update the required
346 * fields before using them.
347 * @param pVmxTransient Pointer to the VMX-transient structure.
348 *
349 * @remarks This is not used on anything returning VERR_EM_INTERPRETER as the
350 * use of that status code will be replaced with VINF_EM_SOMETHING
351 * later when switching over to IEM.
352 */
353#ifndef HMVMX_USE_FUNCTION_TABLE
354typedef DECLINLINE(int) FNVMXEXITHANDLERNSRC(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
355#else
356typedef FNVMXEXITHANDLER FNVMXEXITHANDLERNSRC;
357#endif
358
359
360/*********************************************************************************************************************************
361* Internal Functions *
362*********************************************************************************************************************************/
363static void hmR0VmxFlushEpt(PVMCPU pVCpu, VMXFLUSHEPT enmFlush);
364static void hmR0VmxFlushVpid(PVM pVM, PVMCPU pVCpu, VMXFLUSHVPID enmFlush, RTGCPTR GCPtr);
365static void hmR0VmxClearIntNmiWindowsVmcs(PVMCPU pVCpu);
366static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint64_t u64IntInfo, uint32_t cbInstr,
367 uint32_t u32ErrCode, RTGCUINTREG GCPtrFaultAddress,
368 bool fStepping, uint32_t *puIntState);
369#if HC_ARCH_BITS == 32
370static int hmR0VmxInitVmcsReadCache(PVM pVM, PVMCPU pVCpu);
371#endif
372#ifndef HMVMX_USE_FUNCTION_TABLE
373DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, uint32_t rcReason);
374# define HMVMX_EXIT_DECL DECLINLINE(VBOXSTRICTRC)
375# define HMVMX_EXIT_NSRC_DECL DECLINLINE(int)
376#else
377# define HMVMX_EXIT_DECL static DECLCALLBACK(VBOXSTRICTRC)
378# define HMVMX_EXIT_NSRC_DECL HMVMX_EXIT_DECL
379#endif
380
381
382/** @name VM-exit handlers.
383 * @{
384 */
385static FNVMXEXITHANDLER hmR0VmxExitXcptOrNmi;
386static FNVMXEXITHANDLER hmR0VmxExitExtInt;
387static FNVMXEXITHANDLER hmR0VmxExitTripleFault;
388static FNVMXEXITHANDLERNSRC hmR0VmxExitInitSignal;
389static FNVMXEXITHANDLERNSRC hmR0VmxExitSipi;
390static FNVMXEXITHANDLERNSRC hmR0VmxExitIoSmi;
391static FNVMXEXITHANDLERNSRC hmR0VmxExitSmi;
392static FNVMXEXITHANDLERNSRC hmR0VmxExitIntWindow;
393static FNVMXEXITHANDLERNSRC hmR0VmxExitNmiWindow;
394static FNVMXEXITHANDLER hmR0VmxExitTaskSwitch;
395static FNVMXEXITHANDLER hmR0VmxExitCpuid;
396static FNVMXEXITHANDLER hmR0VmxExitGetsec;
397static FNVMXEXITHANDLER hmR0VmxExitHlt;
398static FNVMXEXITHANDLERNSRC hmR0VmxExitInvd;
399static FNVMXEXITHANDLER hmR0VmxExitInvlpg;
400static FNVMXEXITHANDLER hmR0VmxExitRdpmc;
401static FNVMXEXITHANDLER hmR0VmxExitVmcall;
402static FNVMXEXITHANDLER hmR0VmxExitRdtsc;
403static FNVMXEXITHANDLERNSRC hmR0VmxExitRsm;
404static FNVMXEXITHANDLERNSRC hmR0VmxExitSetPendingXcptUD;
405static FNVMXEXITHANDLER hmR0VmxExitMovCRx;
406static FNVMXEXITHANDLER hmR0VmxExitMovDRx;
407static FNVMXEXITHANDLER hmR0VmxExitIoInstr;
408static FNVMXEXITHANDLER hmR0VmxExitRdmsr;
409static FNVMXEXITHANDLER hmR0VmxExitWrmsr;
410static FNVMXEXITHANDLERNSRC hmR0VmxExitErrInvalidGuestState;
411static FNVMXEXITHANDLERNSRC hmR0VmxExitErrMsrLoad;
412static FNVMXEXITHANDLERNSRC hmR0VmxExitErrUndefined;
413static FNVMXEXITHANDLER hmR0VmxExitMwait;
414static FNVMXEXITHANDLER hmR0VmxExitMtf;
415static FNVMXEXITHANDLER hmR0VmxExitMonitor;
416static FNVMXEXITHANDLER hmR0VmxExitPause;
417static FNVMXEXITHANDLERNSRC hmR0VmxExitErrMachineCheck;
418static FNVMXEXITHANDLERNSRC hmR0VmxExitTprBelowThreshold;
419static FNVMXEXITHANDLER hmR0VmxExitApicAccess;
420static FNVMXEXITHANDLER hmR0VmxExitXdtrAccess;
421static FNVMXEXITHANDLER hmR0VmxExitXdtrAccess;
422static FNVMXEXITHANDLER hmR0VmxExitEptViolation;
423static FNVMXEXITHANDLER hmR0VmxExitEptMisconfig;
424static FNVMXEXITHANDLER hmR0VmxExitRdtscp;
425static FNVMXEXITHANDLER hmR0VmxExitPreemptTimer;
426static FNVMXEXITHANDLERNSRC hmR0VmxExitWbinvd;
427static FNVMXEXITHANDLER hmR0VmxExitXsetbv;
428static FNVMXEXITHANDLER hmR0VmxExitRdrand;
429static FNVMXEXITHANDLER hmR0VmxExitInvpcid;
430/** @} */
431
432static int hmR0VmxExitXcptNM(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
433static int hmR0VmxExitXcptPF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
434static int hmR0VmxExitXcptMF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
435static int hmR0VmxExitXcptDB(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
436static int hmR0VmxExitXcptBP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
437static int hmR0VmxExitXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
438static int hmR0VmxExitXcptAC(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
439static int hmR0VmxExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient);
440static uint32_t hmR0VmxCheckGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
441
442
443/*********************************************************************************************************************************
444* Global Variables *
445*********************************************************************************************************************************/
446#ifdef HMVMX_USE_FUNCTION_TABLE
447
448/**
449 * VMX_EXIT dispatch table.
450 */
451static const PFNVMXEXITHANDLER g_apfnVMExitHandlers[VMX_EXIT_MAX + 1] =
452{
453 /* 00 VMX_EXIT_XCPT_OR_NMI */ hmR0VmxExitXcptOrNmi,
454 /* 01 VMX_EXIT_EXT_INT */ hmR0VmxExitExtInt,
455 /* 02 VMX_EXIT_TRIPLE_FAULT */ hmR0VmxExitTripleFault,
456 /* 03 VMX_EXIT_INIT_SIGNAL */ hmR0VmxExitInitSignal,
457 /* 04 VMX_EXIT_SIPI */ hmR0VmxExitSipi,
458 /* 05 VMX_EXIT_IO_SMI */ hmR0VmxExitIoSmi,
459 /* 06 VMX_EXIT_SMI */ hmR0VmxExitSmi,
460 /* 07 VMX_EXIT_INT_WINDOW */ hmR0VmxExitIntWindow,
461 /* 08 VMX_EXIT_NMI_WINDOW */ hmR0VmxExitNmiWindow,
462 /* 09 VMX_EXIT_TASK_SWITCH */ hmR0VmxExitTaskSwitch,
463 /* 10 VMX_EXIT_CPUID */ hmR0VmxExitCpuid,
464 /* 11 VMX_EXIT_GETSEC */ hmR0VmxExitGetsec,
465 /* 12 VMX_EXIT_HLT */ hmR0VmxExitHlt,
466 /* 13 VMX_EXIT_INVD */ hmR0VmxExitInvd,
467 /* 14 VMX_EXIT_INVLPG */ hmR0VmxExitInvlpg,
468 /* 15 VMX_EXIT_RDPMC */ hmR0VmxExitRdpmc,
469 /* 16 VMX_EXIT_RDTSC */ hmR0VmxExitRdtsc,
470 /* 17 VMX_EXIT_RSM */ hmR0VmxExitRsm,
471 /* 18 VMX_EXIT_VMCALL */ hmR0VmxExitVmcall,
472 /* 19 VMX_EXIT_VMCLEAR */ hmR0VmxExitSetPendingXcptUD,
473 /* 20 VMX_EXIT_VMLAUNCH */ hmR0VmxExitSetPendingXcptUD,
474 /* 21 VMX_EXIT_VMPTRLD */ hmR0VmxExitSetPendingXcptUD,
475 /* 22 VMX_EXIT_VMPTRST */ hmR0VmxExitSetPendingXcptUD,
476 /* 23 VMX_EXIT_VMREAD */ hmR0VmxExitSetPendingXcptUD,
477 /* 24 VMX_EXIT_VMRESUME */ hmR0VmxExitSetPendingXcptUD,
478 /* 25 VMX_EXIT_VMWRITE */ hmR0VmxExitSetPendingXcptUD,
479 /* 26 VMX_EXIT_VMXOFF */ hmR0VmxExitSetPendingXcptUD,
480 /* 27 VMX_EXIT_VMXON */ hmR0VmxExitSetPendingXcptUD,
481 /* 28 VMX_EXIT_MOV_CRX */ hmR0VmxExitMovCRx,
482 /* 29 VMX_EXIT_MOV_DRX */ hmR0VmxExitMovDRx,
483 /* 30 VMX_EXIT_IO_INSTR */ hmR0VmxExitIoInstr,
484 /* 31 VMX_EXIT_RDMSR */ hmR0VmxExitRdmsr,
485 /* 32 VMX_EXIT_WRMSR */ hmR0VmxExitWrmsr,
486 /* 33 VMX_EXIT_ERR_INVALID_GUEST_STATE */ hmR0VmxExitErrInvalidGuestState,
487 /* 34 VMX_EXIT_ERR_MSR_LOAD */ hmR0VmxExitErrMsrLoad,
488 /* 35 UNDEFINED */ hmR0VmxExitErrUndefined,
489 /* 36 VMX_EXIT_MWAIT */ hmR0VmxExitMwait,
490 /* 37 VMX_EXIT_MTF */ hmR0VmxExitMtf,
491 /* 38 UNDEFINED */ hmR0VmxExitErrUndefined,
492 /* 39 VMX_EXIT_MONITOR */ hmR0VmxExitMonitor,
493 /* 40 UNDEFINED */ hmR0VmxExitPause,
494 /* 41 VMX_EXIT_PAUSE */ hmR0VmxExitErrMachineCheck,
495 /* 42 VMX_EXIT_ERR_MACHINE_CHECK */ hmR0VmxExitErrUndefined,
496 /* 43 VMX_EXIT_TPR_BELOW_THRESHOLD */ hmR0VmxExitTprBelowThreshold,
497 /* 44 VMX_EXIT_APIC_ACCESS */ hmR0VmxExitApicAccess,
498 /* 45 UNDEFINED */ hmR0VmxExitErrUndefined,
499 /* 46 VMX_EXIT_XDTR_ACCESS */ hmR0VmxExitXdtrAccess,
500 /* 47 VMX_EXIT_TR_ACCESS */ hmR0VmxExitXdtrAccess,
501 /* 48 VMX_EXIT_EPT_VIOLATION */ hmR0VmxExitEptViolation,
502 /* 49 VMX_EXIT_EPT_MISCONFIG */ hmR0VmxExitEptMisconfig,
503 /* 50 VMX_EXIT_INVEPT */ hmR0VmxExitSetPendingXcptUD,
504 /* 51 VMX_EXIT_RDTSCP */ hmR0VmxExitRdtscp,
505 /* 52 VMX_EXIT_PREEMPT_TIMER */ hmR0VmxExitPreemptTimer,
506 /* 53 VMX_EXIT_INVVPID */ hmR0VmxExitSetPendingXcptUD,
507 /* 54 VMX_EXIT_WBINVD */ hmR0VmxExitWbinvd,
508 /* 55 VMX_EXIT_XSETBV */ hmR0VmxExitXsetbv,
509 /* 56 VMX_EXIT_APIC_WRITE */ hmR0VmxExitErrUndefined,
510 /* 57 VMX_EXIT_RDRAND */ hmR0VmxExitRdrand,
511 /* 58 VMX_EXIT_INVPCID */ hmR0VmxExitInvpcid,
512 /* 59 VMX_EXIT_VMFUNC */ hmR0VmxExitSetPendingXcptUD,
513 /* 60 VMX_EXIT_RESERVED_60 */ hmR0VmxExitErrUndefined,
514 /* 61 VMX_EXIT_RDSEED */ hmR0VmxExitErrUndefined, /* only spurious exits, so undefined */
515 /* 62 VMX_EXIT_RESERVED_62 */ hmR0VmxExitErrUndefined,
516 /* 63 VMX_EXIT_XSAVES */ hmR0VmxExitSetPendingXcptUD,
517 /* 64 VMX_EXIT_XRSTORS */ hmR0VmxExitSetPendingXcptUD,
518};
519#endif /* HMVMX_USE_FUNCTION_TABLE */
520
521#ifdef VBOX_STRICT
522static const char * const g_apszVmxInstrErrors[HMVMX_INSTR_ERROR_MAX + 1] =
523{
524 /* 0 */ "(Not Used)",
525 /* 1 */ "VMCALL executed in VMX root operation.",
526 /* 2 */ "VMCLEAR with invalid physical address.",
527 /* 3 */ "VMCLEAR with VMXON pointer.",
528 /* 4 */ "VMLAUNCH with non-clear VMCS.",
529 /* 5 */ "VMRESUME with non-launched VMCS.",
530 /* 6 */ "VMRESUME after VMXOFF",
531 /* 7 */ "VM-entry with invalid control fields.",
532 /* 8 */ "VM-entry with invalid host state fields.",
533 /* 9 */ "VMPTRLD with invalid physical address.",
534 /* 10 */ "VMPTRLD with VMXON pointer.",
535 /* 11 */ "VMPTRLD with incorrect revision identifier.",
536 /* 12 */ "VMREAD/VMWRITE from/to unsupported VMCS component.",
537 /* 13 */ "VMWRITE to read-only VMCS component.",
538 /* 14 */ "(Not Used)",
539 /* 15 */ "VMXON executed in VMX root operation.",
540 /* 16 */ "VM-entry with invalid executive-VMCS pointer.",
541 /* 17 */ "VM-entry with non-launched executing VMCS.",
542 /* 18 */ "VM-entry with executive-VMCS pointer not VMXON pointer.",
543 /* 19 */ "VMCALL with non-clear VMCS.",
544 /* 20 */ "VMCALL with invalid VM-exit control fields.",
545 /* 21 */ "(Not Used)",
546 /* 22 */ "VMCALL with incorrect MSEG revision identifier.",
547 /* 23 */ "VMXOFF under dual monitor treatment of SMIs and SMM.",
548 /* 24 */ "VMCALL with invalid SMM-monitor features.",
549 /* 25 */ "VM-entry with invalid VM-execution control fields in executive VMCS.",
550 /* 26 */ "VM-entry with events blocked by MOV SS.",
551 /* 27 */ "(Not Used)",
552 /* 28 */ "Invalid operand to INVEPT/INVVPID."
553};
554#endif /* VBOX_STRICT */
555
556
557
558/**
559 * Updates the VM's last error record.
560 *
561 * If there was a VMX instruction error, reads the error data from the VMCS and
562 * updates VCPU's last error record as well.
563 *
564 * @param pVM The cross context VM structure.
565 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
566 * Can be NULL if @a rc is not VERR_VMX_UNABLE_TO_START_VM or
567 * VERR_VMX_INVALID_VMCS_FIELD.
568 * @param rc The error code.
569 */
570static void hmR0VmxUpdateErrorRecord(PVM pVM, PVMCPU pVCpu, int rc)
571{
572 AssertPtr(pVM);
573 if ( rc == VERR_VMX_INVALID_VMCS_FIELD
574 || rc == VERR_VMX_UNABLE_TO_START_VM)
575 {
576 AssertPtrReturnVoid(pVCpu);
577 VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
578 }
579 pVM->hm.s.lLastError = rc;
580}
581
582
583/**
584 * Reads the VM-entry interruption-information field from the VMCS into the VMX
585 * transient structure.
586 *
587 * @returns VBox status code.
588 * @param pVmxTransient Pointer to the VMX transient structure.
589 *
590 * @remarks No-long-jump zone!!!
591 */
592DECLINLINE(int) hmR0VmxReadEntryIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
593{
594 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &pVmxTransient->uEntryIntInfo);
595 AssertRCReturn(rc, rc);
596 return VINF_SUCCESS;
597}
598
599
600#ifdef VBOX_STRICT
601/**
602 * Reads the VM-entry exception error code field from the VMCS into
603 * the VMX transient structure.
604 *
605 * @returns VBox status code.
606 * @param pVmxTransient Pointer to the VMX transient structure.
607 *
608 * @remarks No-long-jump zone!!!
609 */
610DECLINLINE(int) hmR0VmxReadEntryXcptErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
611{
612 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &pVmxTransient->uEntryXcptErrorCode);
613 AssertRCReturn(rc, rc);
614 return VINF_SUCCESS;
615}
616#endif /* VBOX_STRICT */
617
618
619#ifdef VBOX_STRICT
620/**
621 * Reads the VM-entry exception error code field from the VMCS into
622 * the VMX transient structure.
623 *
624 * @returns VBox status code.
625 * @param pVmxTransient Pointer to the VMX transient structure.
626 *
627 * @remarks No-long-jump zone!!!
628 */
629DECLINLINE(int) hmR0VmxReadEntryInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
630{
631 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &pVmxTransient->cbEntryInstr);
632 AssertRCReturn(rc, rc);
633 return VINF_SUCCESS;
634}
635#endif /* VBOX_STRICT */
636
637
638/**
639 * Reads the VM-exit interruption-information field from the VMCS into the VMX
640 * transient structure.
641 *
642 * @returns VBox status code.
643 * @param pVmxTransient Pointer to the VMX transient structure.
644 */
645DECLINLINE(int) hmR0VmxReadExitIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
646{
647 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO))
648 {
649 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
650 AssertRCReturn(rc, rc);
651 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO;
652 }
653 return VINF_SUCCESS;
654}
655
656
657/**
658 * Reads the VM-exit interruption error code from the VMCS into the VMX
659 * transient structure.
660 *
661 * @returns VBox status code.
662 * @param pVmxTransient Pointer to the VMX transient structure.
663 */
664DECLINLINE(int) hmR0VmxReadExitIntErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
665{
666 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_ERROR_CODE))
667 {
668 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
669 AssertRCReturn(rc, rc);
670 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_ERROR_CODE;
671 }
672 return VINF_SUCCESS;
673}
674
675
676/**
677 * Reads the VM-exit instruction length field from the VMCS into the VMX
678 * transient structure.
679 *
680 * @returns VBox status code.
681 * @param pVmxTransient Pointer to the VMX transient structure.
682 */
683DECLINLINE(int) hmR0VmxReadExitInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
684{
685 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_LEN))
686 {
687 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbInstr);
688 AssertRCReturn(rc, rc);
689 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_LEN;
690 }
691 return VINF_SUCCESS;
692}
693
694
695/**
696 * Reads the VM-exit instruction-information field from the VMCS into
697 * the VMX transient structure.
698 *
699 * @returns VBox status code.
700 * @param pVmxTransient Pointer to the VMX transient structure.
701 */
702DECLINLINE(int) hmR0VmxReadExitInstrInfoVmcs(PVMXTRANSIENT pVmxTransient)
703{
704 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_INFO))
705 {
706 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
707 AssertRCReturn(rc, rc);
708 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_INSTR_INFO;
709 }
710 return VINF_SUCCESS;
711}
712
713
714/**
715 * Reads the exit code qualification from the VMCS into the VMX transient
716 * structure.
717 *
718 * @returns VBox status code.
719 * @param pVCpu The cross context virtual CPU structure of the
720 * calling EMT. (Required for the VMCS cache case.)
721 * @param pVmxTransient Pointer to the VMX transient structure.
722 */
723DECLINLINE(int) hmR0VmxReadExitQualificationVmcs(PVMCPU pVCpu, PVMXTRANSIENT pVmxTransient)
724{
725 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_QUALIFICATION))
726 {
727 int rc = VMXReadVmcsGstN(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQualification); NOREF(pVCpu);
728 AssertRCReturn(rc, rc);
729 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_EXIT_QUALIFICATION;
730 }
731 return VINF_SUCCESS;
732}
733
734
735/**
736 * Reads the IDT-vectoring information field from the VMCS into the VMX
737 * transient structure.
738 *
739 * @returns VBox status code.
740 * @param pVmxTransient Pointer to the VMX transient structure.
741 *
742 * @remarks No-long-jump zone!!!
743 */
744DECLINLINE(int) hmR0VmxReadIdtVectoringInfoVmcs(PVMXTRANSIENT pVmxTransient)
745{
746 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_INFO))
747 {
748 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_INFO, &pVmxTransient->uIdtVectoringInfo);
749 AssertRCReturn(rc, rc);
750 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_INFO;
751 }
752 return VINF_SUCCESS;
753}
754
755
756/**
757 * Reads the IDT-vectoring error code from the VMCS into the VMX
758 * transient structure.
759 *
760 * @returns VBox status code.
761 * @param pVmxTransient Pointer to the VMX transient structure.
762 */
763DECLINLINE(int) hmR0VmxReadIdtVectoringErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
764{
765 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_ERROR_CODE))
766 {
767 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
768 AssertRCReturn(rc, rc);
769 pVmxTransient->fVmcsFieldsRead |= HMVMX_UPDATED_TRANSIENT_IDT_VECTORING_ERROR_CODE;
770 }
771 return VINF_SUCCESS;
772}
773
774
775/**
776 * Enters VMX root mode operation on the current CPU.
777 *
778 * @returns VBox status code.
779 * @param pVM The cross context VM structure. Can be
780 * NULL, after a resume.
781 * @param HCPhysCpuPage Physical address of the VMXON region.
782 * @param pvCpuPage Pointer to the VMXON region.
783 */
784static int hmR0VmxEnterRootMode(PVM pVM, RTHCPHYS HCPhysCpuPage, void *pvCpuPage)
785{
786 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
787 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
788 Assert(pvCpuPage);
789 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
790
791 if (pVM)
792 {
793 /* Write the VMCS revision dword to the VMXON region. */
794 *(uint32_t *)pvCpuPage = MSR_IA32_VMX_BASIC_INFO_VMCS_ID(pVM->hm.s.vmx.Msrs.u64BasicInfo);
795 }
796
797 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with CR4. */
798 RTCCUINTREG fEFlags = ASMIntDisableFlags();
799
800 /* Enable the VMX bit in CR4 if necessary. */
801 RTCCUINTREG uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
802
803 /* Enter VMX root mode. */
804 int rc = VMXEnable(HCPhysCpuPage);
805 if (RT_FAILURE(rc))
806 {
807 if (!(uOldCr4 & X86_CR4_VMXE))
808 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
809
810 if (pVM)
811 pVM->hm.s.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
812 }
813
814 /* Restore interrupts. */
815 ASMSetFlags(fEFlags);
816 return rc;
817}
818
819
820/**
821 * Exits VMX root mode operation on the current CPU.
822 *
823 * @returns VBox status code.
824 */
825static int hmR0VmxLeaveRootMode(void)
826{
827 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
828
829 /* Paranoid: Disable interrupts as, in theory, interrupts handlers might mess with CR4. */
830 RTCCUINTREG fEFlags = ASMIntDisableFlags();
831
832 /* If we're for some reason not in VMX root mode, then don't leave it. */
833 RTCCUINTREG uHostCR4 = ASMGetCR4();
834
835 int rc;
836 if (uHostCR4 & X86_CR4_VMXE)
837 {
838 /* Exit VMX root mode and clear the VMX bit in CR4. */
839 VMXDisable();
840 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
841 rc = VINF_SUCCESS;
842 }
843 else
844 rc = VERR_VMX_NOT_IN_VMX_ROOT_MODE;
845
846 /* Restore interrupts. */
847 ASMSetFlags(fEFlags);
848 return rc;
849}
850
851
852/**
853 * Allocates and maps one physically contiguous page. The allocated page is
854 * zero'd out. (Used by various VT-x structures).
855 *
856 * @returns IPRT status code.
857 * @param pMemObj Pointer to the ring-0 memory object.
858 * @param ppVirt Where to store the virtual address of the
859 * allocation.
860 * @param pHCPhys Where to store the physical address of the
861 * allocation.
862 */
863DECLINLINE(int) hmR0VmxPageAllocZ(PRTR0MEMOBJ pMemObj, PRTR0PTR ppVirt, PRTHCPHYS pHCPhys)
864{
865 AssertPtrReturn(pMemObj, VERR_INVALID_PARAMETER);
866 AssertPtrReturn(ppVirt, VERR_INVALID_PARAMETER);
867 AssertPtrReturn(pHCPhys, VERR_INVALID_PARAMETER);
868
869 int rc = RTR0MemObjAllocCont(pMemObj, PAGE_SIZE, false /* fExecutable */);
870 if (RT_FAILURE(rc))
871 return rc;
872 *ppVirt = RTR0MemObjAddress(*pMemObj);
873 *pHCPhys = RTR0MemObjGetPagePhysAddr(*pMemObj, 0 /* iPage */);
874 ASMMemZero32(*ppVirt, PAGE_SIZE);
875 return VINF_SUCCESS;
876}
877
878
879/**
880 * Frees and unmaps an allocated physical page.
881 *
882 * @param pMemObj Pointer to the ring-0 memory object.
883 * @param ppVirt Where to re-initialize the virtual address of
884 * allocation as 0.
885 * @param pHCPhys Where to re-initialize the physical address of the
886 * allocation as 0.
887 */
888DECLINLINE(void) hmR0VmxPageFree(PRTR0MEMOBJ pMemObj, PRTR0PTR ppVirt, PRTHCPHYS pHCPhys)
889{
890 AssertPtr(pMemObj);
891 AssertPtr(ppVirt);
892 AssertPtr(pHCPhys);
893 if (*pMemObj != NIL_RTR0MEMOBJ)
894 {
895 int rc = RTR0MemObjFree(*pMemObj, true /* fFreeMappings */);
896 AssertRC(rc);
897 *pMemObj = NIL_RTR0MEMOBJ;
898 *ppVirt = 0;
899 *pHCPhys = 0;
900 }
901}
902
903
904/**
905 * Worker function to free VT-x related structures.
906 *
907 * @returns IPRT status code.
908 * @param pVM The cross context VM structure.
909 */
910static void hmR0VmxStructsFree(PVM pVM)
911{
912 for (VMCPUID i = 0; i < pVM->cCpus; i++)
913 {
914 PVMCPU pVCpu = &pVM->aCpus[i];
915 AssertPtr(pVCpu);
916
917 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjHostMsr, &pVCpu->hm.s.vmx.pvHostMsr, &pVCpu->hm.s.vmx.HCPhysHostMsr);
918 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjGuestMsr, &pVCpu->hm.s.vmx.pvGuestMsr, &pVCpu->hm.s.vmx.HCPhysGuestMsr);
919
920 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
921 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjMsrBitmap, &pVCpu->hm.s.vmx.pvMsrBitmap, &pVCpu->hm.s.vmx.HCPhysMsrBitmap);
922
923 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjVirtApic, (PRTR0PTR)&pVCpu->hm.s.vmx.pbVirtApic, &pVCpu->hm.s.vmx.HCPhysVirtApic);
924 hmR0VmxPageFree(&pVCpu->hm.s.vmx.hMemObjVmcs, &pVCpu->hm.s.vmx.pvVmcs, &pVCpu->hm.s.vmx.HCPhysVmcs);
925 }
926
927 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess, &pVM->hm.s.vmx.HCPhysApicAccess);
928#ifdef VBOX_WITH_CRASHDUMP_MAGIC
929 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjScratch, &pVM->hm.s.vmx.pbScratch, &pVM->hm.s.vmx.HCPhysScratch);
930#endif
931}
932
933
934/**
935 * Worker function to allocate VT-x related VM structures.
936 *
937 * @returns IPRT status code.
938 * @param pVM The cross context VM structure.
939 */
940static int hmR0VmxStructsAlloc(PVM pVM)
941{
942 /*
943 * Initialize members up-front so we can cleanup properly on allocation failure.
944 */
945#define VMXLOCAL_INIT_VM_MEMOBJ(a_Name, a_VirtPrefix) \
946 pVM->hm.s.vmx.hMemObj##a_Name = NIL_RTR0MEMOBJ; \
947 pVM->hm.s.vmx.a_VirtPrefix##a_Name = 0; \
948 pVM->hm.s.vmx.HCPhys##a_Name = 0;
949
950#define VMXLOCAL_INIT_VMCPU_MEMOBJ(a_Name, a_VirtPrefix) \
951 pVCpu->hm.s.vmx.hMemObj##a_Name = NIL_RTR0MEMOBJ; \
952 pVCpu->hm.s.vmx.a_VirtPrefix##a_Name = 0; \
953 pVCpu->hm.s.vmx.HCPhys##a_Name = 0;
954
955#ifdef VBOX_WITH_CRASHDUMP_MAGIC
956 VMXLOCAL_INIT_VM_MEMOBJ(Scratch, pv);
957#endif
958 VMXLOCAL_INIT_VM_MEMOBJ(ApicAccess, pb);
959
960 AssertCompile(sizeof(VMCPUID) == sizeof(pVM->cCpus));
961 for (VMCPUID i = 0; i < pVM->cCpus; i++)
962 {
963 PVMCPU pVCpu = &pVM->aCpus[i];
964 VMXLOCAL_INIT_VMCPU_MEMOBJ(Vmcs, pv);
965 VMXLOCAL_INIT_VMCPU_MEMOBJ(VirtApic, pb);
966 VMXLOCAL_INIT_VMCPU_MEMOBJ(MsrBitmap, pv);
967 VMXLOCAL_INIT_VMCPU_MEMOBJ(GuestMsr, pv);
968 VMXLOCAL_INIT_VMCPU_MEMOBJ(HostMsr, pv);
969 }
970#undef VMXLOCAL_INIT_VMCPU_MEMOBJ
971#undef VMXLOCAL_INIT_VM_MEMOBJ
972
973 /* The VMCS size cannot be more than 4096 bytes. See Intel spec. Appendix A.1 "Basic VMX Information". */
974 AssertReturnStmt(MSR_IA32_VMX_BASIC_INFO_VMCS_SIZE(pVM->hm.s.vmx.Msrs.u64BasicInfo) <= PAGE_SIZE,
975 (&pVM->aCpus[0])->hm.s.u32HMError = VMX_UFC_INVALID_VMCS_SIZE,
976 VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO);
977
978 /*
979 * Allocate all the VT-x structures.
980 */
981 int rc = VINF_SUCCESS;
982#ifdef VBOX_WITH_CRASHDUMP_MAGIC
983 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjScratch, &pVM->hm.s.vmx.pbScratch, &pVM->hm.s.vmx.HCPhysScratch);
984 if (RT_FAILURE(rc))
985 goto cleanup;
986 strcpy((char *)pVM->hm.s.vmx.pbScratch, "SCRATCH Magic");
987 *(uint64_t *)(pVM->hm.s.vmx.pbScratch + 16) = UINT64_C(0xdeadbeefdeadbeef);
988#endif
989
990 /* Allocate the APIC-access page for trapping APIC accesses from the guest. */
991 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
992 {
993 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess,
994 &pVM->hm.s.vmx.HCPhysApicAccess);
995 if (RT_FAILURE(rc))
996 goto cleanup;
997 }
998
999 /*
1000 * Initialize per-VCPU VT-x structures.
1001 */
1002 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1003 {
1004 PVMCPU pVCpu = &pVM->aCpus[i];
1005 AssertPtr(pVCpu);
1006
1007 /* Allocate the VM control structure (VMCS). */
1008 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjVmcs, &pVCpu->hm.s.vmx.pvVmcs, &pVCpu->hm.s.vmx.HCPhysVmcs);
1009 if (RT_FAILURE(rc))
1010 goto cleanup;
1011
1012 /* Allocate the Virtual-APIC page for transparent TPR accesses. */
1013 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
1014 {
1015 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjVirtApic, (PRTR0PTR)&pVCpu->hm.s.vmx.pbVirtApic,
1016 &pVCpu->hm.s.vmx.HCPhysVirtApic);
1017 if (RT_FAILURE(rc))
1018 goto cleanup;
1019 }
1020
1021 /*
1022 * Allocate the MSR-bitmap if supported by the CPU. The MSR-bitmap is for
1023 * transparent accesses of specific MSRs.
1024 *
1025 * If the condition for enabling MSR bitmaps changes here, don't forget to
1026 * update HMAreMsrBitmapsAvailable().
1027 */
1028 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1029 {
1030 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjMsrBitmap, &pVCpu->hm.s.vmx.pvMsrBitmap,
1031 &pVCpu->hm.s.vmx.HCPhysMsrBitmap);
1032 if (RT_FAILURE(rc))
1033 goto cleanup;
1034 ASMMemFill32(pVCpu->hm.s.vmx.pvMsrBitmap, PAGE_SIZE, UINT32_C(0xffffffff));
1035 }
1036
1037 /* Allocate the VM-entry MSR-load and VM-exit MSR-store page for the guest MSRs. */
1038 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjGuestMsr, &pVCpu->hm.s.vmx.pvGuestMsr, &pVCpu->hm.s.vmx.HCPhysGuestMsr);
1039 if (RT_FAILURE(rc))
1040 goto cleanup;
1041
1042 /* Allocate the VM-exit MSR-load page for the host MSRs. */
1043 rc = hmR0VmxPageAllocZ(&pVCpu->hm.s.vmx.hMemObjHostMsr, &pVCpu->hm.s.vmx.pvHostMsr, &pVCpu->hm.s.vmx.HCPhysHostMsr);
1044 if (RT_FAILURE(rc))
1045 goto cleanup;
1046 }
1047
1048 return VINF_SUCCESS;
1049
1050cleanup:
1051 hmR0VmxStructsFree(pVM);
1052 return rc;
1053}
1054
1055
1056/**
1057 * Does global VT-x initialization (called during module initialization).
1058 *
1059 * @returns VBox status code.
1060 */
1061VMMR0DECL(int) VMXR0GlobalInit(void)
1062{
1063#ifdef HMVMX_USE_FUNCTION_TABLE
1064 AssertCompile(VMX_EXIT_MAX + 1 == RT_ELEMENTS(g_apfnVMExitHandlers));
1065# ifdef VBOX_STRICT
1066 for (unsigned i = 0; i < RT_ELEMENTS(g_apfnVMExitHandlers); i++)
1067 Assert(g_apfnVMExitHandlers[i]);
1068# endif
1069#endif
1070 return VINF_SUCCESS;
1071}
1072
1073
1074/**
1075 * Does global VT-x termination (called during module termination).
1076 */
1077VMMR0DECL(void) VMXR0GlobalTerm()
1078{
1079 /* Nothing to do currently. */
1080}
1081
1082
1083/**
1084 * Sets up and activates VT-x on the current CPU.
1085 *
1086 * @returns VBox status code.
1087 * @param pCpu Pointer to the global CPU info struct.
1088 * @param pVM The cross context VM structure. Can be
1089 * NULL after a host resume operation.
1090 * @param pvCpuPage Pointer to the VMXON region (can be NULL if @a
1091 * fEnabledByHost is @c true).
1092 * @param HCPhysCpuPage Physical address of the VMXON region (can be 0 if
1093 * @a fEnabledByHost is @c true).
1094 * @param fEnabledByHost Set if SUPR0EnableVTx() or similar was used to
1095 * enable VT-x on the host.
1096 * @param pvMsrs Opaque pointer to VMXMSRS struct.
1097 */
1098VMMR0DECL(int) VMXR0EnableCpu(PHMGLOBALCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
1099 void *pvMsrs)
1100{
1101 Assert(pCpu);
1102 Assert(pvMsrs);
1103 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1104
1105 /* Enable VT-x if it's not already enabled by the host. */
1106 if (!fEnabledByHost)
1107 {
1108 int rc = hmR0VmxEnterRootMode(pVM, HCPhysCpuPage, pvCpuPage);
1109 if (RT_FAILURE(rc))
1110 return rc;
1111 }
1112
1113 /*
1114 * Flush all EPT tagged-TLB entries (in case VirtualBox or any other hypervisor have been using EPTPs) so
1115 * we don't retain any stale guest-physical mappings which won't get invalidated when flushing by VPID.
1116 */
1117 PVMXMSRS pMsrs = (PVMXMSRS)pvMsrs;
1118 if (pMsrs->u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
1119 {
1120 hmR0VmxFlushEpt(NULL /* pVCpu */, VMXFLUSHEPT_ALL_CONTEXTS);
1121 pCpu->fFlushAsidBeforeUse = false;
1122 }
1123 else
1124 pCpu->fFlushAsidBeforeUse = true;
1125
1126 /* Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}. */
1127 ++pCpu->cTlbFlushes;
1128
1129 return VINF_SUCCESS;
1130}
1131
1132
1133/**
1134 * Deactivates VT-x on the current CPU.
1135 *
1136 * @returns VBox status code.
1137 * @param pCpu Pointer to the global CPU info struct.
1138 * @param pvCpuPage Pointer to the VMXON region.
1139 * @param HCPhysCpuPage Physical address of the VMXON region.
1140 *
1141 * @remarks This function should never be called when SUPR0EnableVTx() or
1142 * similar was used to enable VT-x on the host.
1143 */
1144VMMR0DECL(int) VMXR0DisableCpu(PHMGLOBALCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
1145{
1146 NOREF(pCpu);
1147 NOREF(pvCpuPage);
1148 NOREF(HCPhysCpuPage);
1149
1150 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1151 return hmR0VmxLeaveRootMode();
1152}
1153
1154
1155/**
1156 * Sets the permission bits for the specified MSR in the MSR bitmap.
1157 *
1158 * @param pVCpu The cross context virtual CPU structure.
1159 * @param uMsr The MSR value.
1160 * @param enmRead Whether reading this MSR causes a VM-exit.
1161 * @param enmWrite Whether writing this MSR causes a VM-exit.
1162 */
1163static void hmR0VmxSetMsrPermission(PVMCPU pVCpu, uint32_t uMsr, VMXMSREXITREAD enmRead, VMXMSREXITWRITE enmWrite)
1164{
1165 int32_t iBit;
1166 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.vmx.pvMsrBitmap;
1167
1168 /*
1169 * Layout:
1170 * 0x000 - 0x3ff - Low MSR read bits
1171 * 0x400 - 0x7ff - High MSR read bits
1172 * 0x800 - 0xbff - Low MSR write bits
1173 * 0xc00 - 0xfff - High MSR write bits
1174 */
1175 if (uMsr <= 0x00001FFF)
1176 iBit = uMsr;
1177 else if (uMsr - UINT32_C(0xC0000000) <= UINT32_C(0x00001FFF))
1178 {
1179 iBit = uMsr - UINT32_C(0xC0000000);
1180 pbMsrBitmap += 0x400;
1181 }
1182 else
1183 AssertMsgFailedReturnVoid(("hmR0VmxSetMsrPermission: Invalid MSR %#RX32\n", uMsr));
1184
1185 Assert(iBit <= 0x1fff);
1186 if (enmRead == VMXMSREXIT_INTERCEPT_READ)
1187 ASMBitSet(pbMsrBitmap, iBit);
1188 else
1189 ASMBitClear(pbMsrBitmap, iBit);
1190
1191 if (enmWrite == VMXMSREXIT_INTERCEPT_WRITE)
1192 ASMBitSet(pbMsrBitmap + 0x800, iBit);
1193 else
1194 ASMBitClear(pbMsrBitmap + 0x800, iBit);
1195}
1196
1197
1198#ifdef VBOX_STRICT
1199/**
1200 * Gets the permission bits for the specified MSR in the MSR bitmap.
1201 *
1202 * @returns VBox status code.
1203 * @retval VINF_SUCCESS if the specified MSR is found.
1204 * @retval VERR_NOT_FOUND if the specified MSR is not found.
1205 * @retval VERR_NOT_SUPPORTED if VT-x doesn't allow the MSR.
1206 *
1207 * @param pVCpu The cross context virtual CPU structure.
1208 * @param uMsr The MSR.
1209 * @param penmRead Where to store the read permissions.
1210 * @param penmWrite Where to store the write permissions.
1211 */
1212static int hmR0VmxGetMsrPermission(PVMCPU pVCpu, uint32_t uMsr, PVMXMSREXITREAD penmRead, PVMXMSREXITWRITE penmWrite)
1213{
1214 AssertPtrReturn(penmRead, VERR_INVALID_PARAMETER);
1215 AssertPtrReturn(penmWrite, VERR_INVALID_PARAMETER);
1216 int32_t iBit;
1217 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.vmx.pvMsrBitmap;
1218
1219 /* See hmR0VmxSetMsrPermission() for the layout. */
1220 if (uMsr <= 0x00001FFF)
1221 iBit = uMsr;
1222 else if ( uMsr >= 0xC0000000
1223 && uMsr <= 0xC0001FFF)
1224 {
1225 iBit = (uMsr - 0xC0000000);
1226 pbMsrBitmap += 0x400;
1227 }
1228 else
1229 AssertMsgFailedReturn(("hmR0VmxGetMsrPermission: Invalid MSR %#RX32\n", uMsr), VERR_NOT_SUPPORTED);
1230
1231 Assert(iBit <= 0x1fff);
1232 if (ASMBitTest(pbMsrBitmap, iBit))
1233 *penmRead = VMXMSREXIT_INTERCEPT_READ;
1234 else
1235 *penmRead = VMXMSREXIT_PASSTHRU_READ;
1236
1237 if (ASMBitTest(pbMsrBitmap + 0x800, iBit))
1238 *penmWrite = VMXMSREXIT_INTERCEPT_WRITE;
1239 else
1240 *penmWrite = VMXMSREXIT_PASSTHRU_WRITE;
1241 return VINF_SUCCESS;
1242}
1243#endif /* VBOX_STRICT */
1244
1245
1246/**
1247 * Updates the VMCS with the number of effective MSRs in the auto-load/store MSR
1248 * area.
1249 *
1250 * @returns VBox status code.
1251 * @param pVCpu The cross context virtual CPU structure.
1252 * @param cMsrs The number of MSRs.
1253 */
1254DECLINLINE(int) hmR0VmxSetAutoLoadStoreMsrCount(PVMCPU pVCpu, uint32_t cMsrs)
1255{
1256 /* Shouldn't ever happen but there -is- a number. We're well within the recommended 512. */
1257 uint32_t const cMaxSupportedMsrs = MSR_IA32_VMX_MISC_MAX_MSR(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.u64Misc);
1258 if (RT_UNLIKELY(cMsrs > cMaxSupportedMsrs))
1259 {
1260 LogRel(("CPU auto-load/store MSR count in VMCS exceeded cMsrs=%u Supported=%u.\n", cMsrs, cMaxSupportedMsrs));
1261 pVCpu->hm.s.u32HMError = VMX_UFC_INSUFFICIENT_GUEST_MSR_STORAGE;
1262 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
1263 }
1264
1265 /* Update number of guest MSRs to load/store across the world-switch. */
1266 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, cMsrs);
1267 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, cMsrs);
1268
1269 /* Update number of host MSRs to load after the world-switch. Identical to guest-MSR count as it's always paired. */
1270 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, cMsrs);
1271 AssertRCReturn(rc, rc);
1272
1273 /* Update the VCPU's copy of the MSR count. */
1274 pVCpu->hm.s.vmx.cMsrs = cMsrs;
1275
1276 return VINF_SUCCESS;
1277}
1278
1279
1280/**
1281 * Adds a new (or updates the value of an existing) guest/host MSR
1282 * pair to be swapped during the world-switch as part of the
1283 * auto-load/store MSR area in the VMCS.
1284 *
1285 * @returns VBox status code.
1286 * @param pVCpu The cross context virtual CPU structure.
1287 * @param uMsr The MSR.
1288 * @param uGuestMsrValue Value of the guest MSR.
1289 * @param fUpdateHostMsr Whether to update the value of the host MSR if
1290 * necessary.
1291 * @param pfAddedAndUpdated Where to store whether the MSR was added -and-
1292 * its value was updated. Optional, can be NULL.
1293 */
1294static int hmR0VmxAddAutoLoadStoreMsr(PVMCPU pVCpu, uint32_t uMsr, uint64_t uGuestMsrValue, bool fUpdateHostMsr,
1295 bool *pfAddedAndUpdated)
1296{
1297 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1298 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1299 uint32_t i;
1300 for (i = 0; i < cMsrs; i++)
1301 {
1302 if (pGuestMsr->u32Msr == uMsr)
1303 break;
1304 pGuestMsr++;
1305 }
1306
1307 bool fAdded = false;
1308 if (i == cMsrs)
1309 {
1310 ++cMsrs;
1311 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, cMsrs);
1312 AssertMsgRCReturn(rc, ("hmR0VmxAddAutoLoadStoreMsr: Insufficient space to add MSR %u\n", uMsr), rc);
1313
1314 /* Now that we're swapping MSRs during the world-switch, allow the guest to read/write them without causing VM-exits. */
1315 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1316 hmR0VmxSetMsrPermission(pVCpu, uMsr, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
1317
1318 fAdded = true;
1319 }
1320
1321 /* Update the MSR values in the auto-load/store MSR area. */
1322 pGuestMsr->u32Msr = uMsr;
1323 pGuestMsr->u64Value = uGuestMsrValue;
1324
1325 /* Create/update the MSR slot in the host MSR area. */
1326 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1327 pHostMsr += i;
1328 pHostMsr->u32Msr = uMsr;
1329
1330 /*
1331 * Update the host MSR only when requested by the caller AND when we're
1332 * adding it to the auto-load/store area. Otherwise, it would have been
1333 * updated by hmR0VmxSaveHostMsrs(). We do this for performance reasons.
1334 */
1335 bool fUpdatedMsrValue = false;
1336 if ( fAdded
1337 && fUpdateHostMsr)
1338 {
1339 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1340 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1341 pHostMsr->u64Value = ASMRdMsr(pHostMsr->u32Msr);
1342 fUpdatedMsrValue = true;
1343 }
1344
1345 if (pfAddedAndUpdated)
1346 *pfAddedAndUpdated = fUpdatedMsrValue;
1347 return VINF_SUCCESS;
1348}
1349
1350
1351/**
1352 * Removes a guest/host MSR pair to be swapped during the world-switch from the
1353 * auto-load/store MSR area in the VMCS.
1354 *
1355 * @returns VBox status code.
1356 * @param pVCpu The cross context virtual CPU structure.
1357 * @param uMsr The MSR.
1358 */
1359static int hmR0VmxRemoveAutoLoadStoreMsr(PVMCPU pVCpu, uint32_t uMsr)
1360{
1361 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1362 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1363 for (uint32_t i = 0; i < cMsrs; i++)
1364 {
1365 /* Find the MSR. */
1366 if (pGuestMsr->u32Msr == uMsr)
1367 {
1368 /* If it's the last MSR, simply reduce the count. */
1369 if (i == cMsrs - 1)
1370 {
1371 --cMsrs;
1372 break;
1373 }
1374
1375 /* Remove it by swapping the last MSR in place of it, and reducing the count. */
1376 PVMXAUTOMSR pLastGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1377 pLastGuestMsr += cMsrs - 1;
1378 pGuestMsr->u32Msr = pLastGuestMsr->u32Msr;
1379 pGuestMsr->u64Value = pLastGuestMsr->u64Value;
1380
1381 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1382 PVMXAUTOMSR pLastHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1383 pLastHostMsr += cMsrs - 1;
1384 pHostMsr->u32Msr = pLastHostMsr->u32Msr;
1385 pHostMsr->u64Value = pLastHostMsr->u64Value;
1386 --cMsrs;
1387 break;
1388 }
1389 pGuestMsr++;
1390 }
1391
1392 /* Update the VMCS if the count changed (meaning the MSR was found). */
1393 if (cMsrs != pVCpu->hm.s.vmx.cMsrs)
1394 {
1395 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, cMsrs);
1396 AssertRCReturn(rc, rc);
1397
1398 /* We're no longer swapping MSRs during the world-switch, intercept guest read/writes to them. */
1399 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1400 hmR0VmxSetMsrPermission(pVCpu, uMsr, VMXMSREXIT_INTERCEPT_READ, VMXMSREXIT_INTERCEPT_WRITE);
1401
1402 Log4(("Removed MSR %#RX32 new cMsrs=%u\n", uMsr, pVCpu->hm.s.vmx.cMsrs));
1403 return VINF_SUCCESS;
1404 }
1405
1406 return VERR_NOT_FOUND;
1407}
1408
1409
1410/**
1411 * Checks if the specified guest MSR is part of the auto-load/store area in
1412 * the VMCS.
1413 *
1414 * @returns true if found, false otherwise.
1415 * @param pVCpu The cross context virtual CPU structure.
1416 * @param uMsr The MSR to find.
1417 */
1418static bool hmR0VmxIsAutoLoadStoreGuestMsr(PVMCPU pVCpu, uint32_t uMsr)
1419{
1420 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1421 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1422
1423 for (uint32_t i = 0; i < cMsrs; i++, pGuestMsr++)
1424 {
1425 if (pGuestMsr->u32Msr == uMsr)
1426 return true;
1427 }
1428 return false;
1429}
1430
1431
1432/**
1433 * Updates the value of all host MSRs in the auto-load/store area in the VMCS.
1434 *
1435 * @param pVCpu The cross context virtual CPU structure.
1436 *
1437 * @remarks No-long-jump zone!!!
1438 */
1439static void hmR0VmxUpdateAutoLoadStoreHostMsrs(PVMCPU pVCpu)
1440{
1441 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1442 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1443 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1444 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
1445
1446 for (uint32_t i = 0; i < cMsrs; i++, pHostMsr++, pGuestMsr++)
1447 {
1448 AssertReturnVoid(pHostMsr->u32Msr == pGuestMsr->u32Msr);
1449
1450 /*
1451 * Performance hack for the host EFER MSR. We use the cached value rather than re-read it.
1452 * Strict builds will catch mismatches in hmR0VmxCheckAutoLoadStoreMsrs(). See @bugref{7368}.
1453 */
1454 if (pHostMsr->u32Msr == MSR_K6_EFER)
1455 pHostMsr->u64Value = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostEfer;
1456 else
1457 pHostMsr->u64Value = ASMRdMsr(pHostMsr->u32Msr);
1458 }
1459
1460 pVCpu->hm.s.vmx.fUpdatedHostMsrs = true;
1461}
1462
1463
1464/**
1465 * Saves a set of host MSRs to allow read/write passthru access to the guest and
1466 * perform lazy restoration of the host MSRs while leaving VT-x.
1467 *
1468 * @param pVCpu The cross context virtual CPU structure.
1469 *
1470 * @remarks No-long-jump zone!!!
1471 */
1472static void hmR0VmxLazySaveHostMsrs(PVMCPU pVCpu)
1473{
1474 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1475
1476 /*
1477 * Note: If you're adding MSRs here, make sure to update the MSR-bitmap permissions in hmR0VmxSetupProcCtls().
1478 */
1479 if (!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST))
1480 {
1481 Assert(!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)); /* Guest MSRs better not be loaded now. */
1482#if HC_ARCH_BITS == 64
1483 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1484 {
1485 pVCpu->hm.s.vmx.u64HostLStarMsr = ASMRdMsr(MSR_K8_LSTAR);
1486 pVCpu->hm.s.vmx.u64HostStarMsr = ASMRdMsr(MSR_K6_STAR);
1487 pVCpu->hm.s.vmx.u64HostSFMaskMsr = ASMRdMsr(MSR_K8_SF_MASK);
1488 pVCpu->hm.s.vmx.u64HostKernelGSBaseMsr = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
1489 }
1490#endif
1491 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_SAVED_HOST;
1492 }
1493}
1494
1495
1496/**
1497 * Checks whether the MSR belongs to the set of guest MSRs that we restore
1498 * lazily while leaving VT-x.
1499 *
1500 * @returns true if it does, false otherwise.
1501 * @param pVCpu The cross context virtual CPU structure.
1502 * @param uMsr The MSR to check.
1503 */
1504static bool hmR0VmxIsLazyGuestMsr(PVMCPU pVCpu, uint32_t uMsr)
1505{
1506 NOREF(pVCpu);
1507#if HC_ARCH_BITS == 64
1508 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1509 {
1510 switch (uMsr)
1511 {
1512 case MSR_K8_LSTAR:
1513 case MSR_K6_STAR:
1514 case MSR_K8_SF_MASK:
1515 case MSR_K8_KERNEL_GS_BASE:
1516 return true;
1517 }
1518 }
1519#else
1520 RT_NOREF(pVCpu, uMsr);
1521#endif
1522 return false;
1523}
1524
1525
1526/**
1527 * Saves a set of guest MSRs back into the guest-CPU context.
1528 *
1529 * @param pVCpu The cross context virtual CPU structure.
1530 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1531 * out-of-sync. Make sure to update the required fields
1532 * before using them.
1533 *
1534 * @remarks No-long-jump zone!!!
1535 */
1536static void hmR0VmxLazySaveGuestMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1537{
1538 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1539 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1540
1541 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
1542 {
1543 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
1544#if HC_ARCH_BITS == 64
1545 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1546 {
1547 pMixedCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
1548 pMixedCtx->msrSTAR = ASMRdMsr(MSR_K6_STAR);
1549 pMixedCtx->msrSFMASK = ASMRdMsr(MSR_K8_SF_MASK);
1550 pMixedCtx->msrKERNELGSBASE = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
1551 }
1552#else
1553 NOREF(pMixedCtx);
1554#endif
1555 }
1556}
1557
1558
1559/**
1560 * Loads a set of guests MSRs to allow read/passthru to the guest.
1561 *
1562 * The name of this function is slightly confusing. This function does NOT
1563 * postpone loading, but loads the MSR right now. "hmR0VmxLazy" is simply a
1564 * common prefix for functions dealing with "lazy restoration" of the shared
1565 * MSRs.
1566 *
1567 * @param pVCpu The cross context virtual CPU structure.
1568 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1569 * out-of-sync. Make sure to update the required fields
1570 * before using them.
1571 *
1572 * @remarks No-long-jump zone!!!
1573 */
1574static void hmR0VmxLazyLoadGuestMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1575{
1576 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1577 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1578
1579#define VMXLOCAL_LAZY_LOAD_GUEST_MSR(uMsr, a_GuestMsr, a_HostMsr) \
1580 do { \
1581 if (pMixedCtx->msr##a_GuestMsr != pVCpu->hm.s.vmx.u64Host##a_HostMsr##Msr) \
1582 ASMWrMsr(uMsr, pMixedCtx->msr##a_GuestMsr); \
1583 else \
1584 Assert(ASMRdMsr(uMsr) == pVCpu->hm.s.vmx.u64Host##a_HostMsr##Msr); \
1585 } while (0)
1586
1587 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
1588 if (!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
1589 {
1590#if HC_ARCH_BITS == 64
1591 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1592 {
1593 VMXLOCAL_LAZY_LOAD_GUEST_MSR(MSR_K8_LSTAR, LSTAR, LStar);
1594 VMXLOCAL_LAZY_LOAD_GUEST_MSR(MSR_K6_STAR, STAR, Star);
1595 VMXLOCAL_LAZY_LOAD_GUEST_MSR(MSR_K8_SF_MASK, SFMASK, SFMask);
1596 VMXLOCAL_LAZY_LOAD_GUEST_MSR(MSR_K8_KERNEL_GS_BASE, KERNELGSBASE, KernelGSBase);
1597 }
1598#else
1599 RT_NOREF(pMixedCtx);
1600#endif
1601 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_LOADED_GUEST;
1602 }
1603
1604#undef VMXLOCAL_LAZY_LOAD_GUEST_MSR
1605}
1606
1607
1608/**
1609 * Performs lazy restoration of the set of host MSRs if they were previously
1610 * loaded with guest MSR values.
1611 *
1612 * @param pVCpu The cross context virtual CPU structure.
1613 *
1614 * @remarks No-long-jump zone!!!
1615 * @remarks The guest MSRs should have been saved back into the guest-CPU
1616 * context by hmR0VmxSaveGuestLazyMsrs()!!!
1617 */
1618static void hmR0VmxLazyRestoreHostMsrs(PVMCPU pVCpu)
1619{
1620 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1621 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1622
1623 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
1624 {
1625 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
1626#if HC_ARCH_BITS == 64
1627 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
1628 {
1629 ASMWrMsr(MSR_K8_LSTAR, pVCpu->hm.s.vmx.u64HostLStarMsr);
1630 ASMWrMsr(MSR_K6_STAR, pVCpu->hm.s.vmx.u64HostStarMsr);
1631 ASMWrMsr(MSR_K8_SF_MASK, pVCpu->hm.s.vmx.u64HostSFMaskMsr);
1632 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pVCpu->hm.s.vmx.u64HostKernelGSBaseMsr);
1633 }
1634#endif
1635 }
1636 pVCpu->hm.s.vmx.fLazyMsrs &= ~(VMX_LAZY_MSRS_LOADED_GUEST | VMX_LAZY_MSRS_SAVED_HOST);
1637}
1638
1639
1640/**
1641 * Verifies that our cached values of the VMCS controls are all
1642 * consistent with what's actually present in the VMCS.
1643 *
1644 * @returns VBox status code.
1645 * @param pVCpu The cross context virtual CPU structure.
1646 */
1647static int hmR0VmxCheckVmcsCtls(PVMCPU pVCpu)
1648{
1649 uint32_t u32Val;
1650 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
1651 AssertRCReturn(rc, rc);
1652 AssertMsgReturn(pVCpu->hm.s.vmx.u32EntryCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32EntryCtls, u32Val),
1653 VERR_VMX_ENTRY_CTLS_CACHE_INVALID);
1654
1655 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val);
1656 AssertRCReturn(rc, rc);
1657 AssertMsgReturn(pVCpu->hm.s.vmx.u32ExitCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32ExitCtls, u32Val),
1658 VERR_VMX_EXIT_CTLS_CACHE_INVALID);
1659
1660 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val);
1661 AssertRCReturn(rc, rc);
1662 AssertMsgReturn(pVCpu->hm.s.vmx.u32PinCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32PinCtls, u32Val),
1663 VERR_VMX_PIN_EXEC_CTLS_CACHE_INVALID);
1664
1665 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val);
1666 AssertRCReturn(rc, rc);
1667 AssertMsgReturn(pVCpu->hm.s.vmx.u32ProcCtls == u32Val, ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32ProcCtls, u32Val),
1668 VERR_VMX_PROC_EXEC_CTLS_CACHE_INVALID);
1669
1670 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
1671 {
1672 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val);
1673 AssertRCReturn(rc, rc);
1674 AssertMsgReturn(pVCpu->hm.s.vmx.u32ProcCtls2 == u32Val,
1675 ("Cache=%#RX32 VMCS=%#RX32", pVCpu->hm.s.vmx.u32ProcCtls2, u32Val),
1676 VERR_VMX_PROC_EXEC2_CTLS_CACHE_INVALID);
1677 }
1678
1679 return VINF_SUCCESS;
1680}
1681
1682
1683#ifdef VBOX_STRICT
1684/**
1685 * Verifies that our cached host EFER value has not changed
1686 * since we cached it.
1687 *
1688 * @param pVCpu The cross context virtual CPU structure.
1689 */
1690static void hmR0VmxCheckHostEferMsr(PVMCPU pVCpu)
1691{
1692 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1693
1694 if (pVCpu->hm.s.vmx.u32ExitCtls & VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR)
1695 {
1696 uint64_t u64Val;
1697 int rc = VMXReadVmcs64(VMX_VMCS64_HOST_EFER_FULL, &u64Val);
1698 AssertRC(rc);
1699
1700 uint64_t u64HostEferMsr = ASMRdMsr(MSR_K6_EFER);
1701 AssertMsgReturnVoid(u64HostEferMsr == u64Val, ("u64HostEferMsr=%#RX64 u64Val=%#RX64\n", u64HostEferMsr, u64Val));
1702 }
1703}
1704
1705
1706/**
1707 * Verifies whether the guest/host MSR pairs in the auto-load/store area in the
1708 * VMCS are correct.
1709 *
1710 * @param pVCpu The cross context virtual CPU structure.
1711 */
1712static void hmR0VmxCheckAutoLoadStoreMsrs(PVMCPU pVCpu)
1713{
1714 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1715
1716 /* Verify MSR counts in the VMCS are what we think it should be. */
1717 uint32_t cMsrs;
1718 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &cMsrs); AssertRC(rc);
1719 Assert(cMsrs == pVCpu->hm.s.vmx.cMsrs);
1720
1721 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &cMsrs); AssertRC(rc);
1722 Assert(cMsrs == pVCpu->hm.s.vmx.cMsrs);
1723
1724 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &cMsrs); AssertRC(rc);
1725 Assert(cMsrs == pVCpu->hm.s.vmx.cMsrs);
1726
1727 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvHostMsr;
1728 PVMXAUTOMSR pGuestMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
1729 for (uint32_t i = 0; i < cMsrs; i++, pHostMsr++, pGuestMsr++)
1730 {
1731 /* Verify that the MSRs are paired properly and that the host MSR has the correct value. */
1732 AssertMsgReturnVoid(pHostMsr->u32Msr == pGuestMsr->u32Msr, ("HostMsr=%#RX32 GuestMsr=%#RX32 cMsrs=%u\n", pHostMsr->u32Msr,
1733 pGuestMsr->u32Msr, cMsrs));
1734
1735 uint64_t u64Msr = ASMRdMsr(pHostMsr->u32Msr);
1736 AssertMsgReturnVoid(pHostMsr->u64Value == u64Msr, ("u32Msr=%#RX32 VMCS Value=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
1737 pHostMsr->u32Msr, pHostMsr->u64Value, u64Msr, cMsrs));
1738
1739 /* Verify that the permissions are as expected in the MSR bitmap. */
1740 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
1741 {
1742 VMXMSREXITREAD enmRead;
1743 VMXMSREXITWRITE enmWrite;
1744 rc = hmR0VmxGetMsrPermission(pVCpu, pGuestMsr->u32Msr, &enmRead, &enmWrite);
1745 AssertMsgReturnVoid(rc == VINF_SUCCESS, ("hmR0VmxGetMsrPermission! failed. rc=%Rrc\n", rc));
1746 if (pGuestMsr->u32Msr == MSR_K6_EFER)
1747 {
1748 AssertMsgReturnVoid(enmRead == VMXMSREXIT_INTERCEPT_READ, ("Passthru read for EFER!?\n"));
1749 AssertMsgReturnVoid(enmWrite == VMXMSREXIT_INTERCEPT_WRITE, ("Passthru write for EFER!?\n"));
1750 }
1751 else
1752 {
1753 AssertMsgReturnVoid(enmRead == VMXMSREXIT_PASSTHRU_READ, ("u32Msr=%#RX32 cMsrs=%u No passthru read!\n",
1754 pGuestMsr->u32Msr, cMsrs));
1755 AssertMsgReturnVoid(enmWrite == VMXMSREXIT_PASSTHRU_WRITE, ("u32Msr=%#RX32 cMsrs=%u No passthru write!\n",
1756 pGuestMsr->u32Msr, cMsrs));
1757 }
1758 }
1759 }
1760}
1761#endif /* VBOX_STRICT */
1762
1763
1764/**
1765 * Flushes the TLB using EPT.
1766 *
1767 * @returns VBox status code.
1768 * @param pVCpu The cross context virtual CPU structure of the calling
1769 * EMT. Can be NULL depending on @a enmFlush.
1770 * @param enmFlush Type of flush.
1771 *
1772 * @remarks Caller is responsible for making sure this function is called only
1773 * when NestedPaging is supported and providing @a enmFlush that is
1774 * supported by the CPU.
1775 * @remarks Can be called with interrupts disabled.
1776 */
1777static void hmR0VmxFlushEpt(PVMCPU pVCpu, VMXFLUSHEPT enmFlush)
1778{
1779 uint64_t au64Descriptor[2];
1780 if (enmFlush == VMXFLUSHEPT_ALL_CONTEXTS)
1781 au64Descriptor[0] = 0;
1782 else
1783 {
1784 Assert(pVCpu);
1785 au64Descriptor[0] = pVCpu->hm.s.vmx.HCPhysEPTP;
1786 }
1787 au64Descriptor[1] = 0; /* MBZ. Intel spec. 33.3 "VMX Instructions" */
1788
1789 int rc = VMXR0InvEPT(enmFlush, &au64Descriptor[0]);
1790 AssertMsg(rc == VINF_SUCCESS, ("VMXR0InvEPT %#x %RGv failed with %Rrc\n", enmFlush, pVCpu ? pVCpu->hm.s.vmx.HCPhysEPTP : 0,
1791 rc));
1792 if ( RT_SUCCESS(rc)
1793 && pVCpu)
1794 {
1795 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushNestedPaging);
1796 }
1797}
1798
1799
1800/**
1801 * Flushes the TLB using VPID.
1802 *
1803 * @returns VBox status code.
1804 * @param pVM The cross context VM structure.
1805 * @param pVCpu The cross context virtual CPU structure of the calling
1806 * EMT. Can be NULL depending on @a enmFlush.
1807 * @param enmFlush Type of flush.
1808 * @param GCPtr Virtual address of the page to flush (can be 0 depending
1809 * on @a enmFlush).
1810 *
1811 * @remarks Can be called with interrupts disabled.
1812 */
1813static void hmR0VmxFlushVpid(PVM pVM, PVMCPU pVCpu, VMXFLUSHVPID enmFlush, RTGCPTR GCPtr)
1814{
1815 NOREF(pVM);
1816 AssertPtr(pVM);
1817 Assert(pVM->hm.s.vmx.fVpid);
1818
1819 uint64_t au64Descriptor[2];
1820 if (enmFlush == VMXFLUSHVPID_ALL_CONTEXTS)
1821 {
1822 au64Descriptor[0] = 0;
1823 au64Descriptor[1] = 0;
1824 }
1825 else
1826 {
1827 AssertPtr(pVCpu);
1828 AssertMsg(pVCpu->hm.s.uCurrentAsid != 0, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
1829 AssertMsg(pVCpu->hm.s.uCurrentAsid <= UINT16_MAX, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
1830 au64Descriptor[0] = pVCpu->hm.s.uCurrentAsid;
1831 au64Descriptor[1] = GCPtr;
1832 }
1833
1834 int rc = VMXR0InvVPID(enmFlush, &au64Descriptor[0]); NOREF(rc);
1835 AssertMsg(rc == VINF_SUCCESS,
1836 ("VMXR0InvVPID %#x %u %RGv failed with %d\n", enmFlush, pVCpu ? pVCpu->hm.s.uCurrentAsid : 0, GCPtr, rc));
1837 if ( RT_SUCCESS(rc)
1838 && pVCpu)
1839 {
1840 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
1841 }
1842}
1843
1844
1845/**
1846 * Invalidates a guest page by guest virtual address. Only relevant for
1847 * EPT/VPID, otherwise there is nothing really to invalidate.
1848 *
1849 * @returns VBox status code.
1850 * @param pVM The cross context VM structure.
1851 * @param pVCpu The cross context virtual CPU structure.
1852 * @param GCVirt Guest virtual address of the page to invalidate.
1853 */
1854VMMR0DECL(int) VMXR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
1855{
1856 AssertPtr(pVM);
1857 AssertPtr(pVCpu);
1858 LogFlowFunc(("pVM=%p pVCpu=%p GCVirt=%RGv\n", pVM, pVCpu, GCVirt));
1859
1860 bool fFlushPending = VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_FLUSH);
1861 if (!fFlushPending)
1862 {
1863 /*
1864 * We must invalidate the guest TLB entry in either case, we cannot ignore it even for the EPT case
1865 * See @bugref{6043} and @bugref{6177}.
1866 *
1867 * Set the VMCPU_FF_TLB_FLUSH force flag and flush before VM-entry in hmR0VmxFlushTLB*() as this
1868 * function maybe called in a loop with individual addresses.
1869 */
1870 if (pVM->hm.s.vmx.fVpid)
1871 {
1872 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
1873 {
1874 hmR0VmxFlushVpid(pVM, pVCpu, VMXFLUSHVPID_INDIV_ADDR, GCVirt);
1875 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
1876 }
1877 else
1878 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1879 }
1880 else if (pVM->hm.s.fNestedPaging)
1881 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1882 }
1883
1884 return VINF_SUCCESS;
1885}
1886
1887
1888/**
1889 * Invalidates a guest page by physical address. Only relevant for EPT/VPID,
1890 * otherwise there is nothing really to invalidate.
1891 *
1892 * @returns VBox status code.
1893 * @param pVM The cross context VM structure.
1894 * @param pVCpu The cross context virtual CPU structure.
1895 * @param GCPhys Guest physical address of the page to invalidate.
1896 */
1897VMMR0DECL(int) VMXR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
1898{
1899 NOREF(pVM); NOREF(GCPhys);
1900 LogFlowFunc(("%RGp\n", GCPhys));
1901
1902 /*
1903 * We cannot flush a page by guest-physical address. invvpid takes only a linear address while invept only flushes
1904 * by EPT not individual addresses. We update the force flag here and flush before the next VM-entry in hmR0VmxFlushTLB*().
1905 * This function might be called in a loop. This should cause a flush-by-EPT if EPT is in use. See @bugref{6568}.
1906 */
1907 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
1908 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgPhys);
1909 return VINF_SUCCESS;
1910}
1911
1912
1913/**
1914 * Dummy placeholder for tagged-TLB flush handling before VM-entry. Used in the
1915 * case where neither EPT nor VPID is supported by the CPU.
1916 *
1917 * @param pVM The cross context VM structure.
1918 * @param pVCpu The cross context virtual CPU structure.
1919 * @param pCpu Pointer to the global HM struct.
1920 *
1921 * @remarks Called with interrupts disabled.
1922 */
1923static void hmR0VmxFlushTaggedTlbNone(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1924{
1925 AssertPtr(pVCpu);
1926 AssertPtr(pCpu);
1927 NOREF(pVM);
1928
1929 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
1930
1931 Assert(pCpu->idCpu != NIL_RTCPUID);
1932 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
1933 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1934 pVCpu->hm.s.fForceTLBFlush = false;
1935 return;
1936}
1937
1938
1939/**
1940 * Flushes the tagged-TLB entries for EPT+VPID CPUs as necessary.
1941 *
1942 * @param pVM The cross context VM structure.
1943 * @param pVCpu The cross context virtual CPU structure.
1944 * @param pCpu Pointer to the global HM CPU struct.
1945 * @remarks All references to "ASID" in this function pertains to "VPID" in
1946 * Intel's nomenclature. The reason is, to avoid confusion in compare
1947 * statements since the host-CPU copies are named "ASID".
1948 *
1949 * @remarks Called with interrupts disabled.
1950 */
1951static void hmR0VmxFlushTaggedTlbBoth(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1952{
1953#ifdef VBOX_WITH_STATISTICS
1954 bool fTlbFlushed = false;
1955# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { fTlbFlushed = true; } while (0)
1956# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { \
1957 if (!fTlbFlushed) \
1958 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch); \
1959 } while (0)
1960#else
1961# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { } while (0)
1962# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { } while (0)
1963#endif
1964
1965 AssertPtr(pVM);
1966 AssertPtr(pCpu);
1967 AssertPtr(pVCpu);
1968 Assert(pCpu->idCpu != NIL_RTCPUID);
1969
1970 AssertMsg(pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid,
1971 ("hmR0VmxFlushTaggedTlbBoth cannot be invoked unless NestedPaging & VPID are enabled."
1972 "fNestedPaging=%RTbool fVpid=%RTbool", pVM->hm.s.fNestedPaging, pVM->hm.s.vmx.fVpid));
1973
1974 /*
1975 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
1976 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB
1977 * or the host CPU is online after a suspend/resume, so we cannot reuse the current ASID anymore.
1978 */
1979 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
1980 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
1981 {
1982 ++pCpu->uCurrentAsid;
1983 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
1984 {
1985 pCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0. */
1986 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
1987 pCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
1988 }
1989
1990 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
1991 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
1992 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
1993
1994 /*
1995 * Flush by EPT when we get rescheduled to a new host CPU to ensure EPT-only tagged mappings are also
1996 * invalidated. We don't need to flush-by-VPID here as flushing by EPT covers it. See @bugref{6568}.
1997 */
1998 hmR0VmxFlushEpt(pVCpu, pVM->hm.s.vmx.enmFlushEpt);
1999 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2000 HMVMX_SET_TAGGED_TLB_FLUSHED();
2001 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH); /* Already flushed-by-EPT, skip doing it again below. */
2002 }
2003
2004 /* Check for explicit TLB flushes. */
2005 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2006 {
2007 /*
2008 * Changes to the EPT paging structure by VMM requires flushing by EPT as the CPU creates
2009 * guest-physical (only EPT-tagged) mappings while traversing the EPT tables when EPT is in use.
2010 * Flushing by VPID will only flush linear (only VPID-tagged) and combined (EPT+VPID tagged) mappings
2011 * but not guest-physical mappings.
2012 * See Intel spec. 28.3.2 "Creating and Using Cached Translation Information". See @bugref{6568}.
2013 */
2014 hmR0VmxFlushEpt(pVCpu, pVM->hm.s.vmx.enmFlushEpt);
2015 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2016 HMVMX_SET_TAGGED_TLB_FLUSHED();
2017 }
2018
2019 pVCpu->hm.s.fForceTLBFlush = false;
2020 HMVMX_UPDATE_FLUSH_SKIPPED_STAT();
2021
2022 Assert(pVCpu->hm.s.idLastCpu == pCpu->idCpu);
2023 Assert(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes);
2024 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
2025 ("Flush count mismatch for cpu %d (%u vs %u)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
2026 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
2027 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pCpu->idCpu,
2028 pCpu->uCurrentAsid, pCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
2029 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
2030 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
2031
2032 /* Update VMCS with the VPID. */
2033 int rc = VMXWriteVmcs32(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
2034 AssertRC(rc);
2035
2036#undef HMVMX_SET_TAGGED_TLB_FLUSHED
2037}
2038
2039
2040/**
2041 * Flushes the tagged-TLB entries for EPT CPUs as necessary.
2042 *
2043 * @returns VBox status code.
2044 * @param pVM The cross context VM structure.
2045 * @param pVCpu The cross context virtual CPU structure.
2046 * @param pCpu Pointer to the global HM CPU struct.
2047 *
2048 * @remarks Called with interrupts disabled.
2049 */
2050static void hmR0VmxFlushTaggedTlbEpt(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2051{
2052 AssertPtr(pVM);
2053 AssertPtr(pVCpu);
2054 AssertPtr(pCpu);
2055 Assert(pCpu->idCpu != NIL_RTCPUID);
2056 AssertMsg(pVM->hm.s.fNestedPaging, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with NestedPaging disabled."));
2057 AssertMsg(!pVM->hm.s.vmx.fVpid, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with VPID enabled."));
2058
2059 /*
2060 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
2061 * A change in the TLB flush count implies the host CPU is online after a suspend/resume.
2062 */
2063 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
2064 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
2065 {
2066 pVCpu->hm.s.fForceTLBFlush = true;
2067 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2068 }
2069
2070 /* Check for explicit TLB flushes. */
2071 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2072 {
2073 pVCpu->hm.s.fForceTLBFlush = true;
2074 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2075 }
2076
2077 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
2078 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
2079
2080 if (pVCpu->hm.s.fForceTLBFlush)
2081 {
2082 hmR0VmxFlushEpt(pVCpu, pVM->hm.s.vmx.enmFlushEpt);
2083 pVCpu->hm.s.fForceTLBFlush = false;
2084 }
2085}
2086
2087
2088/**
2089 * Flushes the tagged-TLB entries for VPID CPUs as necessary.
2090 *
2091 * @returns VBox status code.
2092 * @param pVM The cross context VM structure.
2093 * @param pVCpu The cross context virtual CPU structure.
2094 * @param pCpu Pointer to the global HM CPU struct.
2095 *
2096 * @remarks Called with interrupts disabled.
2097 */
2098static void hmR0VmxFlushTaggedTlbVpid(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2099{
2100 AssertPtr(pVM);
2101 AssertPtr(pVCpu);
2102 AssertPtr(pCpu);
2103 Assert(pCpu->idCpu != NIL_RTCPUID);
2104 AssertMsg(pVM->hm.s.vmx.fVpid, ("hmR0VmxFlushTlbVpid cannot be invoked with VPID disabled."));
2105 AssertMsg(!pVM->hm.s.fNestedPaging, ("hmR0VmxFlushTlbVpid cannot be invoked with NestedPaging enabled"));
2106
2107 /*
2108 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
2109 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB
2110 * or the host CPU is online after a suspend/resume, so we cannot reuse the current ASID anymore.
2111 */
2112 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
2113 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
2114 {
2115 pVCpu->hm.s.fForceTLBFlush = true;
2116 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2117 }
2118
2119 /* Check for explicit TLB flushes. */
2120 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
2121 {
2122 /*
2123 * If we ever support VPID flush combinations other than ALL or SINGLE-context (see hmR0VmxSetupTaggedTlb())
2124 * we would need to explicitly flush in this case (add an fExplicitFlush = true here and change the
2125 * pCpu->fFlushAsidBeforeUse check below to include fExplicitFlush's too) - an obscure corner case.
2126 */
2127 pVCpu->hm.s.fForceTLBFlush = true;
2128 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2129 }
2130
2131 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
2132 if (pVCpu->hm.s.fForceTLBFlush)
2133 {
2134 ++pCpu->uCurrentAsid;
2135 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
2136 {
2137 pCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0 */
2138 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
2139 pCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
2140 }
2141
2142 pVCpu->hm.s.fForceTLBFlush = false;
2143 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
2144 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
2145 if (pCpu->fFlushAsidBeforeUse)
2146 {
2147 if (pVM->hm.s.vmx.enmFlushVpid == VMXFLUSHVPID_SINGLE_CONTEXT)
2148 hmR0VmxFlushVpid(pVM, pVCpu, VMXFLUSHVPID_SINGLE_CONTEXT, 0 /* GCPtr */);
2149 else if (pVM->hm.s.vmx.enmFlushVpid == VMXFLUSHVPID_ALL_CONTEXTS)
2150 {
2151 hmR0VmxFlushVpid(pVM, pVCpu, VMXFLUSHVPID_ALL_CONTEXTS, 0 /* GCPtr */);
2152 pCpu->fFlushAsidBeforeUse = false;
2153 }
2154 else
2155 {
2156 /* hmR0VmxSetupTaggedTlb() ensures we never get here. Paranoia. */
2157 AssertMsgFailed(("Unsupported VPID-flush context type.\n"));
2158 }
2159 }
2160 }
2161
2162 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
2163 ("Flush count mismatch for cpu %d (%u vs %u)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
2164 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
2165 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pCpu->idCpu,
2166 pCpu->uCurrentAsid, pCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
2167 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
2168 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
2169
2170 int rc = VMXWriteVmcs32(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
2171 AssertRC(rc);
2172}
2173
2174
2175/**
2176 * Flushes the guest TLB entry based on CPU capabilities.
2177 *
2178 * @param pVCpu The cross context virtual CPU structure.
2179 * @param pCpu Pointer to the global HM CPU struct.
2180 */
2181DECLINLINE(void) hmR0VmxFlushTaggedTlb(PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
2182{
2183#ifdef HMVMX_ALWAYS_FLUSH_TLB
2184 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2185#endif
2186 PVM pVM = pVCpu->CTX_SUFF(pVM);
2187 switch (pVM->hm.s.vmx.uFlushTaggedTlb)
2188 {
2189 case HMVMX_FLUSH_TAGGED_TLB_EPT_VPID: hmR0VmxFlushTaggedTlbBoth(pVM, pVCpu, pCpu); break;
2190 case HMVMX_FLUSH_TAGGED_TLB_EPT: hmR0VmxFlushTaggedTlbEpt(pVM, pVCpu, pCpu); break;
2191 case HMVMX_FLUSH_TAGGED_TLB_VPID: hmR0VmxFlushTaggedTlbVpid(pVM, pVCpu, pCpu); break;
2192 case HMVMX_FLUSH_TAGGED_TLB_NONE: hmR0VmxFlushTaggedTlbNone(pVM, pVCpu, pCpu); break;
2193 default:
2194 AssertMsgFailed(("Invalid flush-tag function identifier\n"));
2195 break;
2196 }
2197
2198 /* Don't assert that VMCPU_FF_TLB_FLUSH should no longer be pending. It can be set by other EMTs. */
2199}
2200
2201
2202/**
2203 * Sets up the appropriate tagged TLB-flush level and handler for flushing guest
2204 * TLB entries from the host TLB before VM-entry.
2205 *
2206 * @returns VBox status code.
2207 * @param pVM The cross context VM structure.
2208 */
2209static int hmR0VmxSetupTaggedTlb(PVM pVM)
2210{
2211 /*
2212 * Determine optimal flush type for Nested Paging.
2213 * We cannot ignore EPT if no suitable flush-types is supported by the CPU as we've already setup unrestricted
2214 * guest execution (see hmR3InitFinalizeR0()).
2215 */
2216 if (pVM->hm.s.fNestedPaging)
2217 {
2218 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT)
2219 {
2220 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT)
2221 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_SINGLE_CONTEXT;
2222 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
2223 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_ALL_CONTEXTS;
2224 else
2225 {
2226 /* Shouldn't happen. EPT is supported but no suitable flush-types supported. */
2227 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2228 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_FLUSH_TYPE_UNSUPPORTED;
2229 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2230 }
2231
2232 /* Make sure the write-back cacheable memory type for EPT is supported. */
2233 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB)))
2234 {
2235 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2236 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_MEM_TYPE_NOT_WB;
2237 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2238 }
2239
2240 /* EPT requires a page-walk length of 4. */
2241 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4)))
2242 {
2243 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2244 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_PAGE_WALK_LENGTH_UNSUPPORTED;
2245 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2246 }
2247 }
2248 else
2249 {
2250 /* Shouldn't happen. EPT is supported but INVEPT instruction is not supported. */
2251 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NOT_SUPPORTED;
2252 pVM->aCpus[0].hm.s.u32HMError = VMX_UFC_EPT_INVEPT_UNAVAILABLE;
2253 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2254 }
2255 }
2256
2257 /*
2258 * Determine optimal flush type for VPID.
2259 */
2260 if (pVM->hm.s.vmx.fVpid)
2261 {
2262 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID)
2263 {
2264 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT)
2265 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_SINGLE_CONTEXT;
2266 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS)
2267 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_ALL_CONTEXTS;
2268 else
2269 {
2270 /* Neither SINGLE nor ALL-context flush types for VPID is supported by the CPU. Ignore VPID capability. */
2271 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
2272 LogRel(("hmR0VmxSetupTaggedTlb: Only INDIV_ADDR supported. Ignoring VPID.\n"));
2273 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
2274 LogRel(("hmR0VmxSetupTaggedTlb: Only SINGLE_CONTEXT_RETAIN_GLOBALS supported. Ignoring VPID.\n"));
2275 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_NOT_SUPPORTED;
2276 pVM->hm.s.vmx.fVpid = false;
2277 }
2278 }
2279 else
2280 {
2281 /* Shouldn't happen. VPID is supported but INVVPID is not supported by the CPU. Ignore VPID capability. */
2282 Log4(("hmR0VmxSetupTaggedTlb: VPID supported without INVEPT support. Ignoring VPID.\n"));
2283 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_NOT_SUPPORTED;
2284 pVM->hm.s.vmx.fVpid = false;
2285 }
2286 }
2287
2288 /*
2289 * Setup the handler for flushing tagged-TLBs.
2290 */
2291 if (pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid)
2292 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_EPT_VPID;
2293 else if (pVM->hm.s.fNestedPaging)
2294 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_EPT;
2295 else if (pVM->hm.s.vmx.fVpid)
2296 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_VPID;
2297 else
2298 pVM->hm.s.vmx.uFlushTaggedTlb = HMVMX_FLUSH_TAGGED_TLB_NONE;
2299 return VINF_SUCCESS;
2300}
2301
2302
2303/**
2304 * Sets up pin-based VM-execution controls in the VMCS.
2305 *
2306 * @returns VBox status code.
2307 * @param pVM The cross context VM structure.
2308 * @param pVCpu The cross context virtual CPU structure.
2309 */
2310static int hmR0VmxSetupPinCtls(PVM pVM, PVMCPU pVCpu)
2311{
2312 AssertPtr(pVM);
2313 AssertPtr(pVCpu);
2314
2315 uint32_t val = pVM->hm.s.vmx.Msrs.VmxPinCtls.n.disallowed0; /* Bits set here must always be set. */
2316 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1; /* Bits cleared here must always be cleared. */
2317
2318 val |= VMX_VMCS_CTRL_PIN_EXEC_EXT_INT_EXIT /* External interrupts cause a VM-exit. */
2319 | VMX_VMCS_CTRL_PIN_EXEC_NMI_EXIT; /* Non-maskable interrupts (NMIs) cause a VM-exit. */
2320
2321 if (pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI)
2322 val |= VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI; /* Use virtual NMIs and virtual-NMI blocking features. */
2323
2324 /* Enable the VMX preemption timer. */
2325 if (pVM->hm.s.vmx.fUsePreemptTimer)
2326 {
2327 Assert(pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_PREEMPT_TIMER);
2328 val |= VMX_VMCS_CTRL_PIN_EXEC_PREEMPT_TIMER;
2329 }
2330
2331#ifdef VBOX_WITH_NEW_APIC
2332#if 0
2333 /* Enable posted-interrupt processing. */
2334 if (pVM->hm.s.fPostedIntrs)
2335 {
2336 Assert(pVM->hm.s.vmx.Msrs.VmxPinCtls.n.allowed1 & VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR);
2337 Assert(pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT);
2338 val |= VMX_VMCS_CTRL_PIN_EXEC_POSTED_INTR;
2339 }
2340#endif
2341#endif
2342
2343 if ((val & zap) != val)
2344 {
2345 LogRel(("hmR0VmxSetupPinCtls: Invalid pin-based VM-execution controls combo! cpu=%#RX64 val=%#RX64 zap=%#RX64\n",
2346 pVM->hm.s.vmx.Msrs.VmxPinCtls.n.disallowed0, val, zap));
2347 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PIN_EXEC;
2348 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2349 }
2350
2351 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, val);
2352 AssertRCReturn(rc, rc);
2353
2354 pVCpu->hm.s.vmx.u32PinCtls = val;
2355 return rc;
2356}
2357
2358
2359/**
2360 * Sets up processor-based VM-execution controls in the VMCS.
2361 *
2362 * @returns VBox status code.
2363 * @param pVM The cross context VM structure.
2364 * @param pVCpu The cross context virtual CPU structure.
2365 */
2366static int hmR0VmxSetupProcCtls(PVM pVM, PVMCPU pVCpu)
2367{
2368 AssertPtr(pVM);
2369 AssertPtr(pVCpu);
2370
2371 int rc = VERR_INTERNAL_ERROR_5;
2372 uint32_t val = pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0; /* Bits set here must be set in the VMCS. */
2373 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
2374
2375 val |= VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT /* HLT causes a VM-exit. */
2376 | VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING /* Use TSC-offsetting. */
2377 | VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT /* MOV DRx causes a VM-exit. */
2378 | VMX_VMCS_CTRL_PROC_EXEC_UNCOND_IO_EXIT /* All IO instructions cause a VM-exit. */
2379 | VMX_VMCS_CTRL_PROC_EXEC_RDPMC_EXIT /* RDPMC causes a VM-exit. */
2380 | VMX_VMCS_CTRL_PROC_EXEC_MONITOR_EXIT /* MONITOR causes a VM-exit. */
2381 | VMX_VMCS_CTRL_PROC_EXEC_MWAIT_EXIT; /* MWAIT causes a VM-exit. */
2382
2383 /* We toggle VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT later, check if it's not -always- needed to be set or clear. */
2384 if ( !(pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT)
2385 || (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0 & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT))
2386 {
2387 LogRel(("hmR0VmxSetupProcCtls: Unsupported VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT combo!"));
2388 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_MOV_DRX_EXIT;
2389 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2390 }
2391
2392 /* Without Nested Paging, INVLPG (also affects INVPCID) and MOV CR3 instructions should cause VM-exits. */
2393 if (!pVM->hm.s.fNestedPaging)
2394 {
2395 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest); /* Paranoia. */
2396 val |= VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT
2397 | VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT
2398 | VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT;
2399 }
2400
2401 /* Use TPR shadowing if supported by the CPU. */
2402 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
2403 {
2404 Assert(pVCpu->hm.s.vmx.HCPhysVirtApic);
2405 Assert(!(pVCpu->hm.s.vmx.HCPhysVirtApic & 0xfff)); /* Bits 11:0 MBZ. */
2406 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, 0);
2407 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VAPIC_PAGEADDR_FULL, pVCpu->hm.s.vmx.HCPhysVirtApic);
2408 AssertRCReturn(rc, rc);
2409
2410 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW; /* CR8 reads from the Virtual-APIC page. */
2411 /* CR8 writes cause a VM-exit based on TPR threshold. */
2412 Assert(!(val & VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT));
2413 Assert(!(val & VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT));
2414 }
2415 else
2416 {
2417 /*
2418 * Some 32-bit CPUs do not support CR8 load/store exiting as MOV CR8 is invalid on 32-bit Intel CPUs.
2419 * Set this control only for 64-bit guests.
2420 */
2421 if (pVM->hm.s.fAllow64BitGuests)
2422 {
2423 val |= VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT /* CR8 reads cause a VM-exit. */
2424 | VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT; /* CR8 writes cause a VM-exit. */
2425 }
2426 }
2427
2428 /* Use MSR-bitmaps if supported by the CPU. */
2429 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
2430 {
2431 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS;
2432
2433 Assert(pVCpu->hm.s.vmx.HCPhysMsrBitmap);
2434 Assert(!(pVCpu->hm.s.vmx.HCPhysMsrBitmap & 0xfff)); /* Bits 11:0 MBZ. */
2435 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_MSR_BITMAP_FULL, pVCpu->hm.s.vmx.HCPhysMsrBitmap);
2436 AssertRCReturn(rc, rc);
2437
2438 /*
2439 * The guest can access the following MSRs (read, write) without causing VM-exits; they are loaded/stored
2440 * automatically using dedicated fields in the VMCS.
2441 */
2442 hmR0VmxSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_CS, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2443 hmR0VmxSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_ESP, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2444 hmR0VmxSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_EIP, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2445 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_GS_BASE, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2446 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_FS_BASE, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2447
2448#if HC_ARCH_BITS == 64
2449 /*
2450 * Set passthru permissions for the following MSRs (mandatory for VT-x) required for 64-bit guests.
2451 */
2452 if (pVM->hm.s.fAllow64BitGuests)
2453 {
2454 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_LSTAR, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2455 hmR0VmxSetMsrPermission(pVCpu, MSR_K6_STAR, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2456 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_SF_MASK, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2457 hmR0VmxSetMsrPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, VMXMSREXIT_PASSTHRU_READ, VMXMSREXIT_PASSTHRU_WRITE);
2458 }
2459#endif
2460 /* Though MSR_IA32_PERF_GLOBAL_CTRL is saved/restored lazily, we want intercept reads/write to it for now. */
2461 }
2462
2463 /* Use the secondary processor-based VM-execution controls if supported by the CPU. */
2464 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
2465 val |= VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL;
2466
2467 if ((val & zap) != val)
2468 {
2469 LogRel(("hmR0VmxSetupProcCtls: Invalid processor-based VM-execution controls combo! cpu=%#RX64 val=%#RX64 zap=%#RX64\n",
2470 pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0, val, zap));
2471 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC;
2472 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2473 }
2474
2475 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, val);
2476 AssertRCReturn(rc, rc);
2477
2478 pVCpu->hm.s.vmx.u32ProcCtls = val;
2479
2480 /*
2481 * Secondary processor-based VM-execution controls.
2482 */
2483 if (RT_LIKELY(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL))
2484 {
2485 val = pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.disallowed0; /* Bits set here must be set in the VMCS. */
2486 zap = pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
2487
2488 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT)
2489 val |= VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT; /* WBINVD causes a VM-exit. */
2490
2491 if (pVM->hm.s.fNestedPaging)
2492 val |= VMX_VMCS_CTRL_PROC_EXEC2_EPT; /* Enable EPT. */
2493 else
2494 {
2495 /*
2496 * Without Nested Paging, INVPCID should cause a VM-exit. Enabling this bit causes the CPU to refer to
2497 * VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT when INVPCID is executed by the guest.
2498 * See Intel spec. 25.4 "Changes to instruction behaviour in VMX non-root operation".
2499 */
2500 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_INVPCID)
2501 val |= VMX_VMCS_CTRL_PROC_EXEC2_INVPCID;
2502 }
2503
2504 if (pVM->hm.s.vmx.fVpid)
2505 val |= VMX_VMCS_CTRL_PROC_EXEC2_VPID; /* Enable VPID. */
2506
2507 if (pVM->hm.s.vmx.fUnrestrictedGuest)
2508 val |= VMX_VMCS_CTRL_PROC_EXEC2_UNRESTRICTED_GUEST; /* Enable Unrestricted Execution. */
2509
2510#ifdef VBOX_WITH_NEW_APIC
2511#if 0
2512 if (pVM->hm.s.fVirtApicRegs)
2513 {
2514 Assert(pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT);
2515 val |= VMX_VMCS_CTRL_PROC_EXEC2_APIC_REG_VIRT; /* Enable APIC-register virtualization. */
2516
2517 Assert(pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY);
2518 val |= VMX_VMCS_CTRL_PROC_EXEC2_VIRT_INTR_DELIVERY; /* Enable virtual-interrupt delivery. */
2519 }
2520#endif
2521#endif
2522
2523 /* Enable Virtual-APIC page accesses if supported by the CPU. This is essentially where the TPR shadow resides. */
2524 /** @todo VIRT_X2APIC support, it's mutually exclusive with this. So must be
2525 * done dynamically. */
2526 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC)
2527 {
2528 Assert(pVM->hm.s.vmx.HCPhysApicAccess);
2529 Assert(!(pVM->hm.s.vmx.HCPhysApicAccess & 0xfff)); /* Bits 11:0 MBZ. */
2530 val |= VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC; /* Virtualize APIC accesses. */
2531 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, pVM->hm.s.vmx.HCPhysApicAccess);
2532 AssertRCReturn(rc, rc);
2533 }
2534
2535 if (pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP)
2536 val |= VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP; /* Enable RDTSCP support. */
2537
2538 if ( pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_PAUSE_LOOP_EXIT
2539 && pVM->hm.s.vmx.cPleGapTicks
2540 && pVM->hm.s.vmx.cPleWindowTicks)
2541 {
2542 val |= VMX_VMCS_CTRL_PROC_EXEC2_PAUSE_LOOP_EXIT; /* Enable pause-loop exiting. */
2543
2544 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, pVM->hm.s.vmx.cPleGapTicks);
2545 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, pVM->hm.s.vmx.cPleWindowTicks);
2546 AssertRCReturn(rc, rc);
2547 }
2548
2549 if ((val & zap) != val)
2550 {
2551 LogRel(("hmR0VmxSetupProcCtls: Invalid secondary processor-based VM-execution controls combo! "
2552 "cpu=%#RX64 val=%#RX64 zap=%#RX64\n", pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.disallowed0, val, zap));
2553 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC2;
2554 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2555 }
2556
2557 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, val);
2558 AssertRCReturn(rc, rc);
2559
2560 pVCpu->hm.s.vmx.u32ProcCtls2 = val;
2561 }
2562 else if (RT_UNLIKELY(pVM->hm.s.vmx.fUnrestrictedGuest))
2563 {
2564 LogRel(("hmR0VmxSetupProcCtls: Unrestricted Guest set as true when secondary processor-based VM-execution controls not "
2565 "available\n"));
2566 pVCpu->hm.s.u32HMError = VMX_UFC_INVALID_UX_COMBO;
2567 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2568 }
2569
2570 return VINF_SUCCESS;
2571}
2572
2573
2574/**
2575 * Sets up miscellaneous (everything other than Pin & Processor-based
2576 * VM-execution) control fields in the VMCS.
2577 *
2578 * @returns VBox status code.
2579 * @param pVM The cross context VM structure.
2580 * @param pVCpu The cross context virtual CPU structure.
2581 */
2582static int hmR0VmxSetupMiscCtls(PVM pVM, PVMCPU pVCpu)
2583{
2584 NOREF(pVM);
2585 AssertPtr(pVM);
2586 AssertPtr(pVCpu);
2587
2588 int rc = VERR_GENERAL_FAILURE;
2589
2590 /* All fields are zero-initialized during allocation; but don't remove the commented block below. */
2591#if 0
2592 /* All CR3 accesses cause VM-exits. Later we optimize CR3 accesses (see hmR0VmxLoadGuestCR3AndCR4())*/
2593 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_CR3_TARGET_COUNT, 0);
2594 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, 0);
2595
2596 /*
2597 * Set MASK & MATCH to 0. VMX checks if GuestPFErrCode & MASK == MATCH. If equal (in our case it always is)
2598 * 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.
2599 * We thus use the exception bitmap to control it rather than use both.
2600 */
2601 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, 0);
2602 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, 0);
2603
2604 /** @todo Explore possibility of using IO-bitmaps. */
2605 /* All IO & IOIO instructions cause VM-exits. */
2606 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_IO_BITMAP_A_FULL, 0);
2607 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_IO_BITMAP_B_FULL, 0);
2608
2609 /* Initialize the MSR-bitmap area. */
2610 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, 0);
2611 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, 0);
2612 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, 0);
2613 AssertRCReturn(rc, rc);
2614#endif
2615
2616 /* Setup MSR auto-load/store area. */
2617 Assert(pVCpu->hm.s.vmx.HCPhysGuestMsr);
2618 Assert(!(pVCpu->hm.s.vmx.HCPhysGuestMsr & 0xf)); /* Lower 4 bits MBZ. */
2619 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL, pVCpu->hm.s.vmx.HCPhysGuestMsr);
2620 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL, pVCpu->hm.s.vmx.HCPhysGuestMsr);
2621 AssertRCReturn(rc, rc);
2622
2623 Assert(pVCpu->hm.s.vmx.HCPhysHostMsr);
2624 Assert(!(pVCpu->hm.s.vmx.HCPhysHostMsr & 0xf)); /* Lower 4 bits MBZ. */
2625 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL, pVCpu->hm.s.vmx.HCPhysHostMsr);
2626 AssertRCReturn(rc, rc);
2627
2628 /* Set VMCS link pointer. Reserved for future use, must be -1. Intel spec. 24.4 "Guest-State Area". */
2629 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, UINT64_C(0xffffffffffffffff));
2630 AssertRCReturn(rc, rc);
2631
2632 /* All fields are zero-initialized during allocation; but don't remove the commented block below. */
2633#if 0
2634 /* Setup debug controls */
2635 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, 0); /** @todo We don't support IA32_DEBUGCTL MSR. Should we? */
2636 rc |= VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, 0);
2637 AssertRCReturn(rc, rc);
2638#endif
2639
2640 return rc;
2641}
2642
2643
2644/**
2645 * Sets up the initial exception bitmap in the VMCS based on static conditions.
2646 *
2647 * @returns VBox status code.
2648 * @param pVM The cross context VM structure.
2649 * @param pVCpu The cross context virtual CPU structure.
2650 */
2651static int hmR0VmxInitXcptBitmap(PVM pVM, PVMCPU pVCpu)
2652{
2653 AssertPtr(pVM);
2654 AssertPtr(pVCpu);
2655
2656 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
2657
2658 uint32_t u32XcptBitmap = pVCpu->hm.s.fGIMTrapXcptUD ? RT_BIT(X86_XCPT_UD) : 0;
2659
2660 /* Must always intercept #AC to prevent the guest from hanging the CPU. */
2661 u32XcptBitmap |= RT_BIT_32(X86_XCPT_AC);
2662
2663 /* Because we need to maintain the DR6 state even when intercepting DRx reads
2664 and writes, and because recursive #DBs can cause the CPU hang, we must always
2665 intercept #DB. */
2666 u32XcptBitmap |= RT_BIT_32(X86_XCPT_DB);
2667
2668 /* Without Nested Paging, #PF must cause a VM-exit so we can sync our shadow page tables. */
2669 if (!pVM->hm.s.fNestedPaging)
2670 u32XcptBitmap |= RT_BIT(X86_XCPT_PF);
2671
2672 pVCpu->hm.s.vmx.u32XcptBitmap = u32XcptBitmap;
2673 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
2674 AssertRCReturn(rc, rc);
2675 return rc;
2676}
2677
2678
2679/**
2680 * Sets up the initial guest-state mask. The guest-state mask is consulted
2681 * before reading guest-state fields from the VMCS as VMREADs can be expensive
2682 * for the nested virtualization case (as it would cause a VM-exit).
2683 *
2684 * @param pVCpu The cross context virtual CPU structure.
2685 */
2686static int hmR0VmxInitUpdatedGuestStateMask(PVMCPU pVCpu)
2687{
2688 /* Initially the guest-state is up-to-date as there is nothing in the VMCS. */
2689 HMVMXCPU_GST_RESET_TO(pVCpu, HMVMX_UPDATED_GUEST_ALL);
2690 return VINF_SUCCESS;
2691}
2692
2693
2694/**
2695 * Does per-VM VT-x initialization.
2696 *
2697 * @returns VBox status code.
2698 * @param pVM The cross context VM structure.
2699 */
2700VMMR0DECL(int) VMXR0InitVM(PVM pVM)
2701{
2702 LogFlowFunc(("pVM=%p\n", pVM));
2703
2704 int rc = hmR0VmxStructsAlloc(pVM);
2705 if (RT_FAILURE(rc))
2706 {
2707 LogRel(("VMXR0InitVM: hmR0VmxStructsAlloc failed! rc=%Rrc\n", rc));
2708 return rc;
2709 }
2710
2711 return VINF_SUCCESS;
2712}
2713
2714
2715/**
2716 * Does per-VM VT-x termination.
2717 *
2718 * @returns VBox status code.
2719 * @param pVM The cross context VM structure.
2720 */
2721VMMR0DECL(int) VMXR0TermVM(PVM pVM)
2722{
2723 LogFlowFunc(("pVM=%p\n", pVM));
2724
2725#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2726 if (pVM->hm.s.vmx.hMemObjScratch != NIL_RTR0MEMOBJ)
2727 ASMMemZero32(pVM->hm.s.vmx.pvScratch, PAGE_SIZE);
2728#endif
2729 hmR0VmxStructsFree(pVM);
2730 return VINF_SUCCESS;
2731}
2732
2733
2734/**
2735 * Sets up the VM for execution under VT-x.
2736 * This function is only called once per-VM during initialization.
2737 *
2738 * @returns VBox status code.
2739 * @param pVM The cross context VM structure.
2740 */
2741VMMR0DECL(int) VMXR0SetupVM(PVM pVM)
2742{
2743 AssertPtrReturn(pVM, VERR_INVALID_PARAMETER);
2744 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2745
2746 LogFlowFunc(("pVM=%p\n", pVM));
2747
2748 /*
2749 * Without UnrestrictedGuest, pRealModeTSS and pNonPagingModeEPTPageTable *must* always be allocated.
2750 * We no longer support the highly unlikely case of UnrestrictedGuest without pRealModeTSS. See hmR3InitFinalizeR0Intel().
2751 */
2752 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
2753 && ( !pVM->hm.s.vmx.pNonPagingModeEPTPageTable
2754 || !pVM->hm.s.vmx.pRealModeTSS))
2755 {
2756 LogRel(("VMXR0SetupVM: Invalid real-on-v86 state.\n"));
2757 return VERR_INTERNAL_ERROR;
2758 }
2759
2760 /* Initialize these always, see hmR3InitFinalizeR0().*/
2761 pVM->hm.s.vmx.enmFlushEpt = VMXFLUSHEPT_NONE;
2762 pVM->hm.s.vmx.enmFlushVpid = VMXFLUSHVPID_NONE;
2763
2764 /* Setup the tagged-TLB flush handlers. */
2765 int rc = hmR0VmxSetupTaggedTlb(pVM);
2766 if (RT_FAILURE(rc))
2767 {
2768 LogRel(("VMXR0SetupVM: hmR0VmxSetupTaggedTlb failed! rc=%Rrc\n", rc));
2769 return rc;
2770 }
2771
2772 /* Check if we can use the VMCS controls for swapping the EFER MSR. */
2773 Assert(!pVM->hm.s.vmx.fSupportsVmcsEfer);
2774#if HC_ARCH_BITS == 64
2775 if ( (pVM->hm.s.vmx.Msrs.VmxEntry.n.allowed1 & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR)
2776 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR)
2777 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR))
2778 {
2779 pVM->hm.s.vmx.fSupportsVmcsEfer = true;
2780 }
2781#endif
2782
2783 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
2784 RTCCUINTREG uHostCR4 = ASMGetCR4();
2785 if (RT_UNLIKELY(!(uHostCR4 & X86_CR4_VMXE)))
2786 return VERR_VMX_NOT_IN_VMX_ROOT_MODE;
2787
2788 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2789 {
2790 PVMCPU pVCpu = &pVM->aCpus[i];
2791 AssertPtr(pVCpu);
2792 AssertPtr(pVCpu->hm.s.vmx.pvVmcs);
2793
2794 /* Log the VCPU pointers, useful for debugging SMP VMs. */
2795 Log4(("VMXR0SetupVM: pVCpu=%p idCpu=%RU32\n", pVCpu, pVCpu->idCpu));
2796
2797 /* Initialize the VM-exit history array with end-of-array markers (UINT16_MAX). */
2798 Assert(!pVCpu->hm.s.idxExitHistoryFree);
2799 HMCPU_EXIT_HISTORY_RESET(pVCpu);
2800
2801 /* Set revision dword at the beginning of the VMCS structure. */
2802 *(uint32_t *)pVCpu->hm.s.vmx.pvVmcs = MSR_IA32_VMX_BASIC_INFO_VMCS_ID(pVM->hm.s.vmx.Msrs.u64BasicInfo);
2803
2804 /* Initialize our VMCS region in memory, set the VMCS launch state to "clear". */
2805 rc = VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
2806 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: VMXClearVmcs failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2807 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2808
2809 /* Load this VMCS as the current VMCS. */
2810 rc = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
2811 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: VMXActivateVmcs failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2812 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2813
2814 rc = hmR0VmxSetupPinCtls(pVM, pVCpu);
2815 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxSetupPinCtls failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2816 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2817
2818 rc = hmR0VmxSetupProcCtls(pVM, pVCpu);
2819 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxSetupProcCtls failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2820 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2821
2822 rc = hmR0VmxSetupMiscCtls(pVM, pVCpu);
2823 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxSetupMiscCtls failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2824 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2825
2826 rc = hmR0VmxInitXcptBitmap(pVM, pVCpu);
2827 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxInitXcptBitmap failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2828 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2829
2830 rc = hmR0VmxInitUpdatedGuestStateMask(pVCpu);
2831 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxInitUpdatedGuestStateMask failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2832 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2833
2834#if HC_ARCH_BITS == 32
2835 rc = hmR0VmxInitVmcsReadCache(pVM, pVCpu);
2836 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: hmR0VmxInitVmcsReadCache failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2837 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2838#endif
2839
2840 /* Re-sync the CPU's internal data into our VMCS memory region & reset the launch state to "clear". */
2841 rc = VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
2842 AssertLogRelMsgRCReturnStmt(rc, ("VMXR0SetupVM: VMXClearVmcs(2) failed! rc=%Rrc (pVM=%p)\n", rc, pVM),
2843 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc), rc);
2844
2845 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
2846
2847 hmR0VmxUpdateErrorRecord(pVM, pVCpu, rc);
2848 }
2849
2850 return VINF_SUCCESS;
2851}
2852
2853
2854/**
2855 * Saves the host control registers (CR0, CR3, CR4) into the host-state area in
2856 * the VMCS.
2857 *
2858 * @returns VBox status code.
2859 * @param pVM The cross context VM structure.
2860 * @param pVCpu The cross context virtual CPU structure.
2861 */
2862DECLINLINE(int) hmR0VmxSaveHostControlRegs(PVM pVM, PVMCPU pVCpu)
2863{
2864 NOREF(pVM); NOREF(pVCpu);
2865
2866 RTCCUINTREG uReg = ASMGetCR0();
2867 int rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_CR0, uReg);
2868 AssertRCReturn(rc, rc);
2869
2870 uReg = ASMGetCR3();
2871 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_CR3, uReg);
2872 AssertRCReturn(rc, rc);
2873
2874 uReg = ASMGetCR4();
2875 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_CR4, uReg);
2876 AssertRCReturn(rc, rc);
2877 return rc;
2878}
2879
2880
2881#if HC_ARCH_BITS == 64
2882/**
2883 * Macro for adjusting host segment selectors to satisfy VT-x's VM-entry
2884 * requirements. See hmR0VmxSaveHostSegmentRegs().
2885 */
2886# define VMXLOCAL_ADJUST_HOST_SEG(seg, selValue) \
2887 if ((selValue) & (X86_SEL_RPL | X86_SEL_LDT)) \
2888 { \
2889 bool fValidSelector = true; \
2890 if ((selValue) & X86_SEL_LDT) \
2891 { \
2892 uint32_t uAttr = ASMGetSegAttr((selValue)); \
2893 fValidSelector = RT_BOOL(uAttr != UINT32_MAX && (uAttr & X86_DESC_P)); \
2894 } \
2895 if (fValidSelector) \
2896 { \
2897 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##seg; \
2898 pVCpu->hm.s.vmx.RestoreHost.uHostSel##seg = (selValue); \
2899 } \
2900 (selValue) = 0; \
2901 }
2902#endif
2903
2904
2905/**
2906 * Saves the host segment registers and GDTR, IDTR, (TR, GS and FS bases) into
2907 * the host-state area in the VMCS.
2908 *
2909 * @returns VBox status code.
2910 * @param pVM The cross context VM structure.
2911 * @param pVCpu The cross context virtual CPU structure.
2912 */
2913DECLINLINE(int) hmR0VmxSaveHostSegmentRegs(PVM pVM, PVMCPU pVCpu)
2914{
2915 int rc = VERR_INTERNAL_ERROR_5;
2916
2917#if HC_ARCH_BITS == 64
2918 /*
2919 * If we've executed guest code using VT-x, the host-state bits will be messed up. We
2920 * should -not- save the messed up state without restoring the original host-state. See @bugref{7240}.
2921 *
2922 * This apparently can happen (most likely the FPU changes), deal with it rather than asserting.
2923 * Was observed booting Solaris10u10 32-bit guest.
2924 */
2925 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
2926 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
2927 {
2928 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags,
2929 pVCpu->idCpu));
2930 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
2931 }
2932 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
2933#else
2934 RT_NOREF(pVCpu);
2935#endif
2936
2937 /*
2938 * Host DS, ES, FS and GS segment registers.
2939 */
2940#if HC_ARCH_BITS == 64
2941 RTSEL uSelDS = ASMGetDS();
2942 RTSEL uSelES = ASMGetES();
2943 RTSEL uSelFS = ASMGetFS();
2944 RTSEL uSelGS = ASMGetGS();
2945#else
2946 RTSEL uSelDS = 0;
2947 RTSEL uSelES = 0;
2948 RTSEL uSelFS = 0;
2949 RTSEL uSelGS = 0;
2950#endif
2951
2952 /*
2953 * Host CS and SS segment registers.
2954 */
2955 RTSEL uSelCS = ASMGetCS();
2956 RTSEL uSelSS = ASMGetSS();
2957
2958 /*
2959 * Host TR segment register.
2960 */
2961 RTSEL uSelTR = ASMGetTR();
2962
2963#if HC_ARCH_BITS == 64
2964 /*
2965 * Determine if the host segment registers are suitable for VT-x. Otherwise use zero to gain VM-entry and restore them
2966 * before we get preempted. See Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers".
2967 */
2968 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
2969 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
2970 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
2971 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
2972# undef VMXLOCAL_ADJUST_HOST_SEG
2973#endif
2974
2975 /* Verification based on Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers" */
2976 Assert(!(uSelCS & X86_SEL_RPL)); Assert(!(uSelCS & X86_SEL_LDT));
2977 Assert(!(uSelSS & X86_SEL_RPL)); Assert(!(uSelSS & X86_SEL_LDT));
2978 Assert(!(uSelDS & X86_SEL_RPL)); Assert(!(uSelDS & X86_SEL_LDT));
2979 Assert(!(uSelES & X86_SEL_RPL)); Assert(!(uSelES & X86_SEL_LDT));
2980 Assert(!(uSelFS & X86_SEL_RPL)); Assert(!(uSelFS & X86_SEL_LDT));
2981 Assert(!(uSelGS & X86_SEL_RPL)); Assert(!(uSelGS & X86_SEL_LDT));
2982 Assert(!(uSelTR & X86_SEL_RPL)); Assert(!(uSelTR & X86_SEL_LDT));
2983 Assert(uSelCS);
2984 Assert(uSelTR);
2985
2986 /* Assertion is right but we would not have updated u32ExitCtls yet. */
2987#if 0
2988 if (!(pVCpu->hm.s.vmx.u32ExitCtls & VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE))
2989 Assert(uSelSS != 0);
2990#endif
2991
2992 /* Write these host selector fields into the host-state area in the VMCS. */
2993 rc = VMXWriteVmcs32(VMX_VMCS16_HOST_CS_SEL, uSelCS);
2994 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_SS_SEL, uSelSS);
2995#if HC_ARCH_BITS == 64
2996 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_DS_SEL, uSelDS);
2997 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_ES_SEL, uSelES);
2998 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_FS_SEL, uSelFS);
2999 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_GS_SEL, uSelGS);
3000#else
3001 NOREF(uSelDS);
3002 NOREF(uSelES);
3003 NOREF(uSelFS);
3004 NOREF(uSelGS);
3005#endif
3006 rc |= VMXWriteVmcs32(VMX_VMCS16_HOST_TR_SEL, uSelTR);
3007 AssertRCReturn(rc, rc);
3008
3009 /*
3010 * Host GDTR and IDTR.
3011 */
3012 RTGDTR Gdtr;
3013 RTIDTR Idtr;
3014 RT_ZERO(Gdtr);
3015 RT_ZERO(Idtr);
3016 ASMGetGDTR(&Gdtr);
3017 ASMGetIDTR(&Idtr);
3018 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_GDTR_BASE, Gdtr.pGdt);
3019 rc |= VMXWriteVmcsHstN(VMX_VMCS_HOST_IDTR_BASE, Idtr.pIdt);
3020 AssertRCReturn(rc, rc);
3021
3022#if HC_ARCH_BITS == 64
3023 /*
3024 * Determine if we need to manually need to restore the GDTR and IDTR limits as VT-x zaps them to the
3025 * maximum limit (0xffff) on every VM-exit.
3026 */
3027 if (Gdtr.cbGdt != 0xffff)
3028 {
3029 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDTR;
3030 AssertCompile(sizeof(Gdtr) == sizeof(X86XDTR64));
3031 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostGdtr, &Gdtr, sizeof(X86XDTR64));
3032 }
3033
3034 /*
3035 * IDT limit is effectively capped at 0xfff. (See Intel spec. 6.14.1 "64-Bit Mode IDT"
3036 * and Intel spec. 6.2 "Exception and Interrupt Vectors".) Therefore if the host has the limit as 0xfff, VT-x
3037 * bloating the limit to 0xffff shouldn't cause any different CPU behavior. However, several hosts either insists
3038 * on 0xfff being the limit (Windows Patch Guard) or uses the limit for other purposes (darwin puts the CPU ID in there
3039 * but botches sidt alignment in at least one consumer). So, we're only allowing IDTR.LIMIT to be left at 0xffff on
3040 * hosts where we are pretty sure it won't cause trouble.
3041 */
3042# if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
3043 if (Idtr.cbIdt < 0x0fff)
3044# else
3045 if (Idtr.cbIdt != 0xffff)
3046# endif
3047 {
3048 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_IDTR;
3049 AssertCompile(sizeof(Idtr) == sizeof(X86XDTR64));
3050 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostIdtr, &Idtr, sizeof(X86XDTR64));
3051 }
3052#endif
3053
3054 /*
3055 * Host TR base. Verify that TR selector doesn't point past the GDT. Masking off the TI and RPL bits
3056 * is effectively what the CPU does for "scaling by 8". TI is always 0 and RPL should be too in most cases.
3057 */
3058 AssertMsgReturn((uSelTR | X86_SEL_RPL_LDT) <= Gdtr.cbGdt,
3059 ("hmR0VmxSaveHostSegmentRegs: TR selector exceeds limit. TR=%RTsel cbGdt=%#x\n", uSelTR, Gdtr.cbGdt),
3060 VERR_VMX_INVALID_HOST_STATE);
3061
3062 PCX86DESCHC pDesc = (PCX86DESCHC)(Gdtr.pGdt + (uSelTR & X86_SEL_MASK));
3063#if HC_ARCH_BITS == 64
3064 uintptr_t uTRBase = X86DESC64_BASE(pDesc);
3065
3066 /*
3067 * VT-x unconditionally restores the TR limit to 0x67 and type to 11 (32-bit busy TSS) on all VM-exits.
3068 * The type is the same for 64-bit busy TSS[1]. The limit needs manual restoration if the host has something else.
3069 * Task switching is not supported in 64-bit mode[2], but the limit still matters as IOPM is supported in 64-bit mode.
3070 * Restoring the limit lazily while returning to ring-3 is safe because IOPM is not applicable in ring-0.
3071 *
3072 * [1] See Intel spec. 3.5 "System Descriptor Types".
3073 * [2] See Intel spec. 7.2.3 "TSS Descriptor in 64-bit mode".
3074 */
3075 Assert(pDesc->System.u4Type == 11);
3076 if ( pDesc->System.u16LimitLow != 0x67
3077 || pDesc->System.u4LimitHigh)
3078 {
3079 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_TR;
3080 /* If the host has made GDT read-only, we would need to temporarily toggle CR0.WP before writing the GDT. */
3081 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_READ_ONLY)
3082 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_READ_ONLY;
3083 pVCpu->hm.s.vmx.RestoreHost.uHostSelTR = uSelTR;
3084
3085 /* Store the GDTR here as we need it while restoring TR. */
3086 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostGdtr, &Gdtr, sizeof(X86XDTR64));
3087 }
3088#else
3089 NOREF(pVM);
3090 uintptr_t uTRBase = X86DESC_BASE(pDesc);
3091#endif
3092 rc = VMXWriteVmcsHstN(VMX_VMCS_HOST_TR_BASE, uTRBase);
3093 AssertRCReturn(rc, rc);
3094
3095 /*
3096 * Host FS base and GS base.
3097 */
3098#if HC_ARCH_BITS == 64
3099 uint64_t u64FSBase = ASMRdMsr(MSR_K8_FS_BASE);
3100 uint64_t u64GSBase = ASMRdMsr(MSR_K8_GS_BASE);
3101 rc = VMXWriteVmcs64(VMX_VMCS_HOST_FS_BASE, u64FSBase);
3102 rc |= VMXWriteVmcs64(VMX_VMCS_HOST_GS_BASE, u64GSBase);
3103 AssertRCReturn(rc, rc);
3104
3105 /* Store the base if we have to restore FS or GS manually as we need to restore the base as well. */
3106 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_FS)
3107 pVCpu->hm.s.vmx.RestoreHost.uHostFSBase = u64FSBase;
3108 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_GS)
3109 pVCpu->hm.s.vmx.RestoreHost.uHostGSBase = u64GSBase;
3110#endif
3111 return rc;
3112}
3113
3114
3115/**
3116 * Saves certain host MSRs in the VM-Exit MSR-load area and some in the
3117 * host-state area of the VMCS. Theses MSRs will be automatically restored on
3118 * the host after every successful VM-exit.
3119 *
3120 * @returns VBox status code.
3121 * @param pVM The cross context VM structure.
3122 * @param pVCpu The cross context virtual CPU structure.
3123 *
3124 * @remarks No-long-jump zone!!!
3125 */
3126DECLINLINE(int) hmR0VmxSaveHostMsrs(PVM pVM, PVMCPU pVCpu)
3127{
3128 NOREF(pVM);
3129
3130 AssertPtr(pVCpu);
3131 AssertPtr(pVCpu->hm.s.vmx.pvHostMsr);
3132
3133 /*
3134 * Save MSRs that we restore lazily (due to preemption or transition to ring-3)
3135 * rather than swapping them on every VM-entry.
3136 */
3137 hmR0VmxLazySaveHostMsrs(pVCpu);
3138
3139 /*
3140 * Host Sysenter MSRs.
3141 */
3142 int rc = VMXWriteVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS));
3143#if HC_ARCH_BITS == 32
3144 rc |= VMXWriteVmcs32(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr_Low(MSR_IA32_SYSENTER_ESP));
3145 rc |= VMXWriteVmcs32(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr_Low(MSR_IA32_SYSENTER_EIP));
3146#else
3147 rc |= VMXWriteVmcs64(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP));
3148 rc |= VMXWriteVmcs64(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP));
3149#endif
3150 AssertRCReturn(rc, rc);
3151
3152 /*
3153 * Host EFER MSR.
3154 * If the CPU supports the newer VMCS controls for managing EFER, use it.
3155 * Otherwise it's done as part of auto-load/store MSR area in the VMCS, see hmR0VmxLoadGuestMsrs().
3156 */
3157 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
3158 {
3159 rc = VMXWriteVmcs64(VMX_VMCS64_HOST_EFER_FULL, pVM->hm.s.vmx.u64HostEfer);
3160 AssertRCReturn(rc, rc);
3161 }
3162
3163 /** @todo IA32_PERF_GLOBALCTRL, IA32_PAT also see
3164 * hmR0VmxLoadGuestExitCtls() !! */
3165
3166 return rc;
3167}
3168
3169
3170/**
3171 * Figures out if we need to swap the EFER MSR which is particularly expensive.
3172 *
3173 * We check all relevant bits. For now, that's everything besides LMA/LME, as
3174 * these two bits are handled by VM-entry, see hmR0VmxLoadGuestExitCtls() and
3175 * hmR0VMxLoadGuestEntryCtls().
3176 *
3177 * @returns true if we need to load guest EFER, false otherwise.
3178 * @param pVCpu The cross context virtual CPU structure.
3179 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3180 * out-of-sync. Make sure to update the required fields
3181 * before using them.
3182 *
3183 * @remarks Requires EFER, CR4.
3184 * @remarks No-long-jump zone!!!
3185 */
3186static bool hmR0VmxShouldSwapEferMsr(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3187{
3188#ifdef HMVMX_ALWAYS_SWAP_EFER
3189 return true;
3190#endif
3191
3192#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
3193 /* For 32-bit hosts running 64-bit guests, we always swap EFER in the world-switcher. Nothing to do here. */
3194 if (CPUMIsGuestInLongMode(pVCpu))
3195 return false;
3196#endif
3197
3198 PVM pVM = pVCpu->CTX_SUFF(pVM);
3199 uint64_t u64HostEfer = pVM->hm.s.vmx.u64HostEfer;
3200 uint64_t u64GuestEfer = pMixedCtx->msrEFER;
3201
3202 /*
3203 * For 64-bit guests, if EFER.SCE bit differs, we need to swap to ensure that the
3204 * guest's SYSCALL behaviour isn't screwed. See @bugref{7386}.
3205 */
3206 if ( CPUMIsGuestInLongMode(pVCpu)
3207 && (u64GuestEfer & MSR_K6_EFER_SCE) != (u64HostEfer & MSR_K6_EFER_SCE))
3208 {
3209 return true;
3210 }
3211
3212 /*
3213 * If the guest uses PAE and EFER.NXE bit differs, we need to swap EFER as it
3214 * affects guest paging. 64-bit paging implies CR4.PAE as well.
3215 * See Intel spec. 4.5 "IA-32e Paging" and Intel spec. 4.1.1 "Three Paging Modes".
3216 */
3217 if ( (pMixedCtx->cr4 & X86_CR4_PAE)
3218 && (pMixedCtx->cr0 & X86_CR0_PG)
3219 && (u64GuestEfer & MSR_K6_EFER_NXE) != (u64HostEfer & MSR_K6_EFER_NXE))
3220 {
3221 /* Assert that host is PAE capable. */
3222 Assert(pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_NX);
3223 return true;
3224 }
3225
3226 /** @todo Check the latest Intel spec. for any other bits,
3227 * like SMEP/SMAP? */
3228 return false;
3229}
3230
3231
3232/**
3233 * Sets up VM-entry controls in the VMCS. These controls can affect things done
3234 * on VM-exit; e.g. "load debug controls", see Intel spec. 24.8.1 "VM-entry
3235 * controls".
3236 *
3237 * @returns VBox status code.
3238 * @param pVCpu The cross context virtual CPU structure.
3239 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3240 * out-of-sync. Make sure to update the required fields
3241 * before using them.
3242 *
3243 * @remarks Requires EFER.
3244 * @remarks No-long-jump zone!!!
3245 */
3246DECLINLINE(int) hmR0VmxLoadGuestEntryCtls(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3247{
3248 int rc = VINF_SUCCESS;
3249 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_ENTRY_CTLS))
3250 {
3251 PVM pVM = pVCpu->CTX_SUFF(pVM);
3252 uint32_t val = pVM->hm.s.vmx.Msrs.VmxEntry.n.disallowed0; /* Bits set here must be set in the VMCS. */
3253 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxEntry.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3254
3255 /* Load debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x capable CPUs only supports the 1-setting of this bit. */
3256 val |= VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG;
3257
3258 /* Set if the guest is in long mode. This will set/clear the EFER.LMA bit on VM-entry. */
3259 if (CPUMIsGuestInLongModeEx(pMixedCtx))
3260 {
3261 val |= VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST;
3262 Log4(("Load[%RU32]: VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST\n", pVCpu->idCpu));
3263 }
3264 else
3265 Assert(!(val & VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST));
3266
3267 /* If the CPU supports the newer VMCS controls for managing guest/host EFER, use it. */
3268 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
3269 && hmR0VmxShouldSwapEferMsr(pVCpu, pMixedCtx))
3270 {
3271 val |= VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR;
3272 Log4(("Load[%RU32]: VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR\n", pVCpu->idCpu));
3273 }
3274
3275 /*
3276 * The following should -not- be set (since we're not in SMM mode):
3277 * - VMX_VMCS_CTRL_ENTRY_ENTRY_SMM
3278 * - VMX_VMCS_CTRL_ENTRY_DEACTIVATE_DUALMON
3279 */
3280
3281 /** @todo VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PERF_MSR,
3282 * VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PAT_MSR. */
3283
3284 if ((val & zap) != val)
3285 {
3286 LogRel(("hmR0VmxLoadGuestEntryCtls: Invalid VM-entry controls combo! cpu=%RX64 val=%RX64 zap=%RX64\n",
3287 pVM->hm.s.vmx.Msrs.VmxEntry.n.disallowed0, val, zap));
3288 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_ENTRY;
3289 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3290 }
3291
3292 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY, val);
3293 AssertRCReturn(rc, rc);
3294
3295 pVCpu->hm.s.vmx.u32EntryCtls = val;
3296 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_ENTRY_CTLS);
3297 }
3298 return rc;
3299}
3300
3301
3302/**
3303 * Sets up the VM-exit controls in the VMCS.
3304 *
3305 * @returns VBox status code.
3306 * @param pVCpu The cross context virtual CPU structure.
3307 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3308 * out-of-sync. Make sure to update the required fields
3309 * before using them.
3310 *
3311 * @remarks Requires EFER.
3312 */
3313DECLINLINE(int) hmR0VmxLoadGuestExitCtls(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3314{
3315 NOREF(pMixedCtx);
3316
3317 int rc = VINF_SUCCESS;
3318 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_EXIT_CTLS))
3319 {
3320 PVM pVM = pVCpu->CTX_SUFF(pVM);
3321 uint32_t val = pVM->hm.s.vmx.Msrs.VmxExit.n.disallowed0; /* Bits set here must be set in the VMCS. */
3322 uint32_t zap = pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3323
3324 /* Save debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x CPUs only supported the 1-setting of this bit. */
3325 val |= VMX_VMCS_CTRL_EXIT_SAVE_DEBUG;
3326
3327 /*
3328 * Set the host long mode active (EFER.LMA) bit (which Intel calls "Host address-space size") if necessary.
3329 * On VM-exit, VT-x sets both the host EFER.LMA and EFER.LME bit to this value. See assertion in hmR0VmxSaveHostMsrs().
3330 */
3331#if HC_ARCH_BITS == 64
3332 val |= VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE;
3333 Log4(("Load[%RU32]: VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE\n", pVCpu->idCpu));
3334#else
3335 Assert( pVCpu->hm.s.vmx.pfnStartVM == VMXR0SwitcherStartVM64
3336 || pVCpu->hm.s.vmx.pfnStartVM == VMXR0StartVM32);
3337 /* Set the host address-space size based on the switcher, not guest state. See @bugref{8432}. */
3338 if (pVCpu->hm.s.vmx.pfnStartVM == VMXR0SwitcherStartVM64)
3339 {
3340 /* The switcher returns to long mode, EFER is managed by the switcher. */
3341 val |= VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE;
3342 Log4(("Load[%RU32]: VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE\n", pVCpu->idCpu));
3343 }
3344 else
3345 Assert(!(val & VMX_VMCS_CTRL_EXIT_HOST_ADDR_SPACE_SIZE));
3346#endif
3347
3348 /* If the newer VMCS fields for managing EFER exists, use it. */
3349 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
3350 && hmR0VmxShouldSwapEferMsr(pVCpu, pMixedCtx))
3351 {
3352 val |= VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR
3353 | VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR;
3354 Log4(("Load[%RU32]: VMX_VMCS_CTRL_EXIT_SAVE_GUEST_EFER_MSR, VMX_VMCS_CTRL_EXIT_LOAD_HOST_EFER_MSR\n", pVCpu->idCpu));
3355 }
3356
3357 /* Don't acknowledge external interrupts on VM-exit. We want to let the host do that. */
3358 Assert(!(val & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT));
3359
3360 /** @todo VMX_VMCS_CTRL_EXIT_LOAD_PERF_MSR,
3361 * VMX_VMCS_CTRL_EXIT_SAVE_GUEST_PAT_MSR,
3362 * VMX_VMCS_CTRL_EXIT_LOAD_HOST_PAT_MSR. */
3363
3364 if ( pVM->hm.s.vmx.fUsePreemptTimer
3365 && (pVM->hm.s.vmx.Msrs.VmxExit.n.allowed1 & VMX_VMCS_CTRL_EXIT_SAVE_VMX_PREEMPT_TIMER))
3366 val |= VMX_VMCS_CTRL_EXIT_SAVE_VMX_PREEMPT_TIMER;
3367
3368 if ((val & zap) != val)
3369 {
3370 LogRel(("hmR0VmxSetupProcCtls: Invalid VM-exit controls combo! cpu=%RX64 val=%RX64 zap=%RX64\n",
3371 pVM->hm.s.vmx.Msrs.VmxExit.n.disallowed0, val, zap));
3372 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_EXIT;
3373 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3374 }
3375
3376 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT, val);
3377 AssertRCReturn(rc, rc);
3378
3379 pVCpu->hm.s.vmx.u32ExitCtls = val;
3380 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_EXIT_CTLS);
3381 }
3382 return rc;
3383}
3384
3385
3386/**
3387 * Sets the TPR threshold in the VMCS.
3388 *
3389 * @returns VBox status code.
3390 * @param pVCpu The cross context virtual CPU structure.
3391 * @param u32TprThreshold The TPR threshold (task-priority class only).
3392 */
3393DECLINLINE(int) hmR0VmxApicSetTprThreshold(PVMCPU pVCpu, uint32_t u32TprThreshold)
3394{
3395 Assert(!(u32TprThreshold & 0xfffffff0)); /* Bits 31:4 MBZ. */
3396 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW); RT_NOREF_PV(pVCpu);
3397 return VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
3398}
3399
3400
3401/**
3402 * Loads the guest APIC and related state.
3403 *
3404 * @returns VBox status code.
3405 * @param pVCpu The cross context virtual CPU structure.
3406 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3407 * out-of-sync. Make sure to update the required fields
3408 * before using them.
3409 */
3410DECLINLINE(int) hmR0VmxLoadGuestApicState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3411{
3412 NOREF(pMixedCtx);
3413
3414 int rc = VINF_SUCCESS;
3415 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE))
3416 {
3417 /* Setup TPR shadowing. Also setup TPR patching for 32-bit guests. */
3418 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
3419 {
3420 Assert(pVCpu->hm.s.vmx.HCPhysVirtApic);
3421
3422 bool fPendingIntr = false;
3423 uint8_t u8Tpr = 0;
3424 uint8_t u8PendingIntr = 0;
3425 rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
3426 AssertRCReturn(rc, rc);
3427
3428 /*
3429 * If there are external interrupts pending but masked by the TPR value, instruct VT-x to cause a VM-exit when
3430 * the guest lowers its TPR below the highest-priority pending interrupt and we can deliver the interrupt.
3431 * If there are no external interrupts pending, set threshold to 0 to not cause a VM-exit. We will eventually deliver
3432 * the interrupt when we VM-exit for other reasons.
3433 */
3434 pVCpu->hm.s.vmx.pbVirtApic[0x80] = u8Tpr; /* Offset 0x80 is TPR in the APIC MMIO range. */
3435 uint32_t u32TprThreshold = 0;
3436 if (fPendingIntr)
3437 {
3438 /* Bits 3:0 of the TPR threshold field correspond to bits 7:4 of the TPR (which is the Task-Priority Class). */
3439 const uint8_t u8PendingPriority = (u8PendingIntr >> 4) & 0xf;
3440 const uint8_t u8TprPriority = (u8Tpr >> 4) & 0xf;
3441 if (u8PendingPriority <= u8TprPriority)
3442 u32TprThreshold = u8PendingPriority;
3443 else
3444 u32TprThreshold = u8TprPriority; /* Required for Vista 64-bit guest, see @bugref{6398}. */
3445 }
3446
3447 rc = hmR0VmxApicSetTprThreshold(pVCpu, u32TprThreshold);
3448 AssertRCReturn(rc, rc);
3449 }
3450
3451 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
3452 }
3453 return rc;
3454}
3455
3456
3457/**
3458 * Gets the guest's interruptibility-state ("interrupt shadow" as AMD calls it).
3459 *
3460 * @returns Guest's interruptibility-state.
3461 * @param pVCpu The cross context virtual CPU structure.
3462 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3463 * out-of-sync. Make sure to update the required fields
3464 * before using them.
3465 *
3466 * @remarks No-long-jump zone!!!
3467 */
3468DECLINLINE(uint32_t) hmR0VmxGetGuestIntrState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3469{
3470 /*
3471 * Check if we should inhibit interrupt delivery due to instructions like STI and MOV SS.
3472 */
3473 uint32_t uIntrState = 0;
3474 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3475 {
3476 /* If inhibition is active, RIP & RFLAGS should've been accessed (i.e. read previously from the VMCS or from ring-3). */
3477 AssertMsg(HMVMXCPU_GST_IS_SET(pVCpu, HMVMX_UPDATED_GUEST_RIP | HMVMX_UPDATED_GUEST_RFLAGS),
3478 ("%#x\n", HMVMXCPU_GST_VALUE(pVCpu)));
3479 if (pMixedCtx->rip == EMGetInhibitInterruptsPC(pVCpu))
3480 {
3481 if (pMixedCtx->eflags.Bits.u1IF)
3482 uIntrState = VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI;
3483 else
3484 uIntrState = VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS;
3485 }
3486 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
3487 {
3488 /*
3489 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
3490 * VT-x, the flag's condition to be cleared is met and thus the cleared state is correct.
3491 */
3492 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3493 }
3494 }
3495
3496 /*
3497 * NMIs to the guest are blocked after an NMI is injected until the guest executes an IRET. We only
3498 * bother with virtual-NMI blocking when we have support for virtual NMIs in the CPU, otherwise
3499 * setting this would block host-NMIs and IRET will not clear the blocking.
3500 *
3501 * See Intel spec. 26.6.1 "Interruptibility state". See @bugref{7445}.
3502 */
3503 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS)
3504 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI))
3505 {
3506 uIntrState |= VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI;
3507 }
3508
3509 return uIntrState;
3510}
3511
3512
3513/**
3514 * Loads the guest's interruptibility-state into the guest-state area in the
3515 * VMCS.
3516 *
3517 * @returns VBox status code.
3518 * @param pVCpu The cross context virtual CPU structure.
3519 * @param uIntrState The interruptibility-state to set.
3520 */
3521static int hmR0VmxLoadGuestIntrState(PVMCPU pVCpu, uint32_t uIntrState)
3522{
3523 NOREF(pVCpu);
3524 AssertMsg(!(uIntrState & 0xfffffff0), ("%#x\n", uIntrState)); /* Bits 31:4 MBZ. */
3525 Assert((uIntrState & 0x3) != 0x3); /* Block-by-STI and MOV SS cannot be simultaneously set. */
3526 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, uIntrState);
3527 AssertRC(rc);
3528 return rc;
3529}
3530
3531
3532/**
3533 * Loads the exception intercepts required for guest execution in the VMCS.
3534 *
3535 * @returns VBox status code.
3536 * @param pVCpu The cross context virtual CPU structure.
3537 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3538 * out-of-sync. Make sure to update the required fields
3539 * before using them.
3540 */
3541static int hmR0VmxLoadGuestXcptIntercepts(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3542{
3543 NOREF(pMixedCtx);
3544 int rc = VINF_SUCCESS;
3545 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
3546 {
3547 /* The remaining exception intercepts are handled elsewhere, e.g. in hmR0VmxLoadSharedCR0(). */
3548 if (pVCpu->hm.s.fGIMTrapXcptUD)
3549 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_UD);
3550#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
3551 else
3552 pVCpu->hm.s.vmx.u32XcptBitmap &= ~RT_BIT(X86_XCPT_UD);
3553#endif
3554
3555 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_AC));
3556 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_DB));
3557
3558 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVCpu->hm.s.vmx.u32XcptBitmap);
3559 AssertRCReturn(rc, rc);
3560
3561 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
3562 Log4(("Load[%RU32]: VMX_VMCS32_CTRL_EXCEPTION_BITMAP=%#RX64 fContextUseFlags=%#RX32\n", pVCpu->idCpu,
3563 pVCpu->hm.s.vmx.u32XcptBitmap, HMCPU_CF_VALUE(pVCpu)));
3564 }
3565 return rc;
3566}
3567
3568
3569/**
3570 * Loads the guest's RIP into the guest-state area in the VMCS.
3571 *
3572 * @returns VBox status code.
3573 * @param pVCpu The cross context virtual CPU structure.
3574 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3575 * out-of-sync. Make sure to update the required fields
3576 * before using them.
3577 *
3578 * @remarks No-long-jump zone!!!
3579 */
3580static int hmR0VmxLoadGuestRip(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3581{
3582 int rc = VINF_SUCCESS;
3583 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RIP))
3584 {
3585 rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_RIP, pMixedCtx->rip);
3586 AssertRCReturn(rc, rc);
3587
3588 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP);
3589 Log4(("Load[%RU32]: VMX_VMCS_GUEST_RIP=%#RX64 fContextUseFlags=%#RX32\n", pVCpu->idCpu, pMixedCtx->rip,
3590 HMCPU_CF_VALUE(pVCpu)));
3591 }
3592 return rc;
3593}
3594
3595
3596/**
3597 * Loads the guest's RSP 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 hmR0VmxLoadGuestRsp(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3608{
3609 int rc = VINF_SUCCESS;
3610 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RSP))
3611 {
3612 rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_RSP, pMixedCtx->rsp);
3613 AssertRCReturn(rc, rc);
3614
3615 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RSP);
3616 Log4(("Load[%RU32]: VMX_VMCS_GUEST_RSP=%#RX64\n", pVCpu->idCpu, pMixedCtx->rsp));
3617 }
3618 return rc;
3619}
3620
3621
3622/**
3623 * Loads the guest's RFLAGS into the guest-state area in the VMCS.
3624 *
3625 * @returns VBox status code.
3626 * @param pVCpu The cross context virtual CPU structure.
3627 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3628 * out-of-sync. Make sure to update the required fields
3629 * before using them.
3630 *
3631 * @remarks No-long-jump zone!!!
3632 */
3633static int hmR0VmxLoadGuestRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3634{
3635 int rc = VINF_SUCCESS;
3636 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RFLAGS))
3637 {
3638 /* Intel spec. 2.3.1 "System Flags and Fields in IA-32e Mode" claims the upper 32-bits of RFLAGS are reserved (MBZ).
3639 Let us assert it as such and use 32-bit VMWRITE. */
3640 Assert(!(pMixedCtx->rflags.u64 >> 32));
3641 X86EFLAGS Eflags = pMixedCtx->eflags;
3642 /** @todo r=bird: There shall be no need to OR in X86_EFL_1 here, nor
3643 * shall there be any reason for clearing bits 63:22, 15, 5 and 3.
3644 * These will never be cleared/set, unless some other part of the VMM
3645 * code is buggy - in which case we're better of finding and fixing
3646 * those bugs than hiding them. */
3647 Assert(Eflags.u32 & X86_EFL_RA1_MASK);
3648 Assert(!(Eflags.u32 & ~(X86_EFL_1 | X86_EFL_LIVE_MASK)));
3649 Eflags.u32 &= VMX_EFLAGS_RESERVED_0; /* Bits 22-31, 15, 5 & 3 MBZ. */
3650 Eflags.u32 |= VMX_EFLAGS_RESERVED_1; /* Bit 1 MB1. */
3651
3652 /*
3653 * If we're emulating real-mode using Virtual 8086 mode, save the real-mode eflags so we can restore them on VM-exit.
3654 * Modify the real-mode guest's eflags so that VT-x can run the real-mode guest code under Virtual 8086 mode.
3655 */
3656 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
3657 {
3658 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
3659 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
3660 pVCpu->hm.s.vmx.RealMode.Eflags.u32 = Eflags.u32; /* Save the original eflags of the real-mode guest. */
3661 Eflags.Bits.u1VM = 1; /* Set the Virtual 8086 mode bit. */
3662 Eflags.Bits.u2IOPL = 0; /* Change IOPL to 0, otherwise certain instructions won't fault. */
3663 }
3664
3665 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_RFLAGS, Eflags.u32);
3666 AssertRCReturn(rc, rc);
3667
3668 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RFLAGS);
3669 Log4(("Load[%RU32]: VMX_VMCS_GUEST_RFLAGS=%#RX32\n", pVCpu->idCpu, Eflags.u32));
3670 }
3671 return rc;
3672}
3673
3674
3675/**
3676 * Loads the guest RIP, RSP and RFLAGS into the guest-state area in the VMCS.
3677 *
3678 * @returns VBox status code.
3679 * @param pVCpu The cross context virtual CPU structure.
3680 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3681 * out-of-sync. Make sure to update the required fields
3682 * before using them.
3683 *
3684 * @remarks No-long-jump zone!!!
3685 */
3686DECLINLINE(int) hmR0VmxLoadGuestRipRspRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3687{
3688 int rc = hmR0VmxLoadGuestRip(pVCpu, pMixedCtx);
3689 rc |= hmR0VmxLoadGuestRsp(pVCpu, pMixedCtx);
3690 rc |= hmR0VmxLoadGuestRflags(pVCpu, pMixedCtx);
3691 AssertRCReturn(rc, rc);
3692 return rc;
3693}
3694
3695
3696/**
3697 * Loads the guest CR0 control register into the guest-state area in the VMCS.
3698 * CR0 is partially shared with the host and we have to consider the FPU bits.
3699 *
3700 * @returns VBox status code.
3701 * @param pVCpu The cross context virtual CPU structure.
3702 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3703 * out-of-sync. Make sure to update the required fields
3704 * before using them.
3705 *
3706 * @remarks No-long-jump zone!!!
3707 */
3708static int hmR0VmxLoadSharedCR0(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3709{
3710 /*
3711 * Guest CR0.
3712 * Guest FPU.
3713 */
3714 int rc = VINF_SUCCESS;
3715 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
3716 {
3717 Assert(!(pMixedCtx->cr0 >> 32));
3718 uint32_t u32GuestCR0 = pMixedCtx->cr0;
3719 PVM pVM = pVCpu->CTX_SUFF(pVM);
3720
3721 /* The guest's view (read access) of its CR0 is unblemished. */
3722 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR0_READ_SHADOW, u32GuestCR0);
3723 AssertRCReturn(rc, rc);
3724 Log4(("Load[%RU32]: VMX_VMCS_CTRL_CR0_READ_SHADOW=%#RX32\n", pVCpu->idCpu, u32GuestCR0));
3725
3726 /* Setup VT-x's view of the guest CR0. */
3727 /* Minimize VM-exits due to CR3 changes when we have NestedPaging. */
3728 if (pVM->hm.s.fNestedPaging)
3729 {
3730 if (CPUMIsGuestPagingEnabledEx(pMixedCtx))
3731 {
3732 /* The guest has paging enabled, let it access CR3 without causing a VM-exit if supported. */
3733 pVCpu->hm.s.vmx.u32ProcCtls &= ~( VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT
3734 | VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT);
3735 }
3736 else
3737 {
3738 /* The guest doesn't have paging enabled, make CR3 access cause a VM-exit to update our shadow. */
3739 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT
3740 | VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT;
3741 }
3742
3743 /* If we have unrestricted guest execution, we never have to intercept CR3 reads. */
3744 if (pVM->hm.s.vmx.fUnrestrictedGuest)
3745 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT;
3746
3747 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
3748 AssertRCReturn(rc, rc);
3749 }
3750 else
3751 u32GuestCR0 |= X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
3752
3753 /*
3754 * Guest FPU bits.
3755 * Intel spec. 23.8 "Restrictions on VMX operation" mentions that CR0.NE bit must always be set on the first
3756 * CPUs to support VT-x and no mention of with regards to UX in VM-entry checks.
3757 */
3758 u32GuestCR0 |= X86_CR0_NE;
3759 bool fInterceptNM = false;
3760 if (CPUMIsGuestFPUStateActive(pVCpu))
3761 {
3762 fInterceptNM = false; /* Guest FPU active, no need to VM-exit on #NM. */
3763 /* The guest should still get #NM exceptions when it expects it to, so we should not clear TS & MP bits here.
3764 We're only concerned about -us- not intercepting #NMs when the guest-FPU is active. Not the guest itself! */
3765 }
3766 else
3767 {
3768 fInterceptNM = true; /* Guest FPU inactive, VM-exit on #NM for lazy FPU loading. */
3769 u32GuestCR0 |= X86_CR0_TS /* Guest can task switch quickly and do lazy FPU syncing. */
3770 | X86_CR0_MP; /* FWAIT/WAIT should not ignore CR0.TS and should generate #NM. */
3771 }
3772
3773 /* Catch floating point exceptions if we need to report them to the guest in a different way. */
3774 bool fInterceptMF = false;
3775 if (!(pMixedCtx->cr0 & X86_CR0_NE))
3776 fInterceptMF = true;
3777
3778 /* Finally, intercept all exceptions as we cannot directly inject them in real-mode, see hmR0VmxInjectEventVmcs(). */
3779 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
3780 {
3781 Assert(PDMVmmDevHeapIsEnabled(pVM));
3782 Assert(pVM->hm.s.vmx.pRealModeTSS);
3783 pVCpu->hm.s.vmx.u32XcptBitmap |= HMVMX_REAL_MODE_XCPT_MASK;
3784 fInterceptNM = true;
3785 fInterceptMF = true;
3786 }
3787 else
3788 {
3789 /* For now, cleared here as mode-switches can happen outside HM/VT-x. See @bugref{7626#c11}. */
3790 pVCpu->hm.s.vmx.u32XcptBitmap &= ~HMVMX_REAL_MODE_XCPT_MASK;
3791 }
3792 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
3793
3794 if (fInterceptNM)
3795 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_NM);
3796 else
3797 pVCpu->hm.s.vmx.u32XcptBitmap &= ~RT_BIT(X86_XCPT_NM);
3798
3799 if (fInterceptMF)
3800 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_MF);
3801 else
3802 pVCpu->hm.s.vmx.u32XcptBitmap &= ~RT_BIT(X86_XCPT_MF);
3803
3804 /* Additional intercepts for debugging, define these yourself explicitly. */
3805#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
3806 pVCpu->hm.s.vmx.u32XcptBitmap |= 0
3807 | RT_BIT(X86_XCPT_BP)
3808 | RT_BIT(X86_XCPT_DE)
3809 | RT_BIT(X86_XCPT_NM)
3810 | RT_BIT(X86_XCPT_TS)
3811 | RT_BIT(X86_XCPT_UD)
3812 | RT_BIT(X86_XCPT_NP)
3813 | RT_BIT(X86_XCPT_SS)
3814 | RT_BIT(X86_XCPT_GP)
3815 | RT_BIT(X86_XCPT_PF)
3816 | RT_BIT(X86_XCPT_MF)
3817 ;
3818#elif defined(HMVMX_ALWAYS_TRAP_PF)
3819 pVCpu->hm.s.vmx.u32XcptBitmap |= RT_BIT(X86_XCPT_PF);
3820#endif
3821
3822 Assert(pVM->hm.s.fNestedPaging || (pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT(X86_XCPT_PF)));
3823
3824 /* Set/clear the CR0 specific bits along with their exceptions (PE, PG, CD, NW). */
3825 uint32_t uSetCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
3826 uint32_t uZapCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
3827 if (pVM->hm.s.vmx.fUnrestrictedGuest) /* Exceptions for unrestricted-guests for fixed CR0 bits (PE, PG). */
3828 uSetCR0 &= ~(X86_CR0_PE | X86_CR0_PG);
3829 else
3830 Assert((uSetCR0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG));
3831
3832 u32GuestCR0 |= uSetCR0;
3833 u32GuestCR0 &= uZapCR0;
3834 u32GuestCR0 &= ~(X86_CR0_CD | X86_CR0_NW); /* Always enable caching. */
3835
3836 /* Write VT-x's view of the guest CR0 into the VMCS. */
3837 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_CR0, u32GuestCR0);
3838 AssertRCReturn(rc, rc);
3839 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR0=%#RX32 (uSetCR0=%#RX32 uZapCR0=%#RX32)\n", pVCpu->idCpu, u32GuestCR0, uSetCR0,
3840 uZapCR0));
3841
3842 /*
3843 * CR0 is shared between host and guest along with a CR0 read shadow. Therefore, certain bits must not be changed
3844 * by the guest because VT-x ignores saving/restoring them (namely CD, ET, NW) and for certain other bits
3845 * we want to be notified immediately of guest CR0 changes (e.g. PG to update our shadow page tables).
3846 */
3847 uint32_t u32CR0Mask = 0;
3848 u32CR0Mask = X86_CR0_PE
3849 | X86_CR0_NE
3850 | X86_CR0_WP
3851 | X86_CR0_PG
3852 | X86_CR0_ET /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.ET */
3853 | X86_CR0_CD /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.CD */
3854 | X86_CR0_NW; /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.NW */
3855
3856 /** @todo Avoid intercepting CR0.PE with unrestricted guests. Fix PGM
3857 * enmGuestMode to be in-sync with the current mode. See @bugref{6398}
3858 * and @bugref{6944}. */
3859#if 0
3860 if (pVM->hm.s.vmx.fUnrestrictedGuest)
3861 u32CR0Mask &= ~X86_CR0_PE;
3862#endif
3863 if (pVM->hm.s.fNestedPaging)
3864 u32CR0Mask &= ~X86_CR0_WP;
3865
3866 /* If the guest FPU state is active, don't need to VM-exit on writes to FPU related bits in CR0. */
3867 if (fInterceptNM)
3868 {
3869 u32CR0Mask |= X86_CR0_TS
3870 | X86_CR0_MP;
3871 }
3872
3873 /* Write the CR0 mask into the VMCS and update the VCPU's copy of the current CR0 mask. */
3874 pVCpu->hm.s.vmx.u32CR0Mask = u32CR0Mask;
3875 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR0_MASK, u32CR0Mask);
3876 AssertRCReturn(rc, rc);
3877 Log4(("Load[%RU32]: VMX_VMCS_CTRL_CR0_MASK=%#RX32\n", pVCpu->idCpu, u32CR0Mask));
3878
3879 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR0);
3880 }
3881 return rc;
3882}
3883
3884
3885/**
3886 * Loads the guest control registers (CR3, CR4) into the guest-state area
3887 * in the VMCS.
3888 *
3889 * @returns VBox strict status code.
3890 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
3891 * without unrestricted guest access and the VMMDev is not presently
3892 * mapped (e.g. EFI32).
3893 *
3894 * @param pVCpu The cross context virtual CPU structure.
3895 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
3896 * out-of-sync. Make sure to update the required fields
3897 * before using them.
3898 *
3899 * @remarks No-long-jump zone!!!
3900 */
3901static VBOXSTRICTRC hmR0VmxLoadGuestCR3AndCR4(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
3902{
3903 int rc = VINF_SUCCESS;
3904 PVM pVM = pVCpu->CTX_SUFF(pVM);
3905
3906 /*
3907 * Guest CR2.
3908 * It's always loaded in the assembler code. Nothing to do here.
3909 */
3910
3911 /*
3912 * Guest CR3.
3913 */
3914 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR3))
3915 {
3916 RTGCPHYS GCPhysGuestCR3 = NIL_RTGCPHYS;
3917 if (pVM->hm.s.fNestedPaging)
3918 {
3919 pVCpu->hm.s.vmx.HCPhysEPTP = PGMGetHyperCR3(pVCpu);
3920
3921 /* Validate. See Intel spec. 28.2.2 "EPT Translation Mechanism" and 24.6.11 "Extended-Page-Table Pointer (EPTP)" */
3922 Assert(pVCpu->hm.s.vmx.HCPhysEPTP);
3923 Assert(!(pVCpu->hm.s.vmx.HCPhysEPTP & UINT64_C(0xfff0000000000000)));
3924 Assert(!(pVCpu->hm.s.vmx.HCPhysEPTP & 0xfff));
3925
3926 /* VMX_EPT_MEMTYPE_WB support is already checked in hmR0VmxSetupTaggedTlb(). */
3927 pVCpu->hm.s.vmx.HCPhysEPTP |= VMX_EPT_MEMTYPE_WB
3928 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
3929
3930 /* Validate. See Intel spec. 26.2.1 "Checks on VMX Controls" */
3931 AssertMsg( ((pVCpu->hm.s.vmx.HCPhysEPTP >> 3) & 0x07) == 3 /* Bits 3:5 (EPT page walk length - 1) must be 3. */
3932 && ((pVCpu->hm.s.vmx.HCPhysEPTP >> 7) & 0x1f) == 0, /* Bits 7:11 MBZ. */
3933 ("EPTP %#RX64\n", pVCpu->hm.s.vmx.HCPhysEPTP));
3934 AssertMsg( !((pVCpu->hm.s.vmx.HCPhysEPTP >> 6) & 0x01) /* Bit 6 (EPT accessed & dirty bit). */
3935 || (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY),
3936 ("EPTP accessed/dirty bit not supported by CPU but set %#RX64\n", pVCpu->hm.s.vmx.HCPhysEPTP));
3937
3938 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, pVCpu->hm.s.vmx.HCPhysEPTP);
3939 AssertRCReturn(rc, rc);
3940 Log4(("Load[%RU32]: VMX_VMCS64_CTRL_EPTP_FULL=%#RX64\n", pVCpu->idCpu, pVCpu->hm.s.vmx.HCPhysEPTP));
3941
3942 if ( pVM->hm.s.vmx.fUnrestrictedGuest
3943 || CPUMIsGuestPagingEnabledEx(pMixedCtx))
3944 {
3945 /* If the guest is in PAE mode, pass the PDPEs to VT-x using the VMCS fields. */
3946 if (CPUMIsGuestInPAEModeEx(pMixedCtx))
3947 {
3948 rc = PGMGstGetPaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
3949 AssertRCReturn(rc, rc);
3950 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, pVCpu->hm.s.aPdpes[0].u);
3951 rc |= VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, pVCpu->hm.s.aPdpes[1].u);
3952 rc |= VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, pVCpu->hm.s.aPdpes[2].u);
3953 rc |= VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, pVCpu->hm.s.aPdpes[3].u);
3954 AssertRCReturn(rc, rc);
3955 }
3956
3957 /* The guest's view of its CR3 is unblemished with Nested Paging when the guest is using paging or we
3958 have Unrestricted Execution to handle the guest when it's not using paging. */
3959 GCPhysGuestCR3 = pMixedCtx->cr3;
3960 }
3961 else
3962 {
3963 /*
3964 * The guest is not using paging, but the CPU (VT-x) has to. While the guest thinks it accesses physical memory
3965 * directly, we use our identity-mapped page table to map guest-linear to guest-physical addresses.
3966 * EPT takes care of translating it to host-physical addresses.
3967 */
3968 RTGCPHYS GCPhys;
3969 Assert(pVM->hm.s.vmx.pNonPagingModeEPTPageTable);
3970
3971 /* We obtain it here every time as the guest could have relocated this PCI region. */
3972 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
3973 if (RT_SUCCESS(rc))
3974 { /* likely */ }
3975 else if (rc == VERR_PDM_DEV_HEAP_R3_TO_GCPHYS)
3976 {
3977 Log4(("Load[%RU32]: VERR_PDM_DEV_HEAP_R3_TO_GCPHYS -> VINF_EM_RESCHEDULE_REM\n", pVCpu->idCpu));
3978 return VINF_EM_RESCHEDULE_REM; /* We cannot execute now, switch to REM/IEM till the guest maps in VMMDev. */
3979 }
3980 else
3981 AssertMsgFailedReturn(("%Rrc\n", rc), rc);
3982
3983 GCPhysGuestCR3 = GCPhys;
3984 }
3985
3986 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR3=%#RGp (GstN)\n", pVCpu->idCpu, GCPhysGuestCR3));
3987 rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_CR3, GCPhysGuestCR3);
3988 }
3989 else
3990 {
3991 /* Non-nested paging case, just use the hypervisor's CR3. */
3992 RTHCPHYS HCPhysGuestCR3 = PGMGetHyperCR3(pVCpu);
3993
3994 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR3=%#RHv (HstN)\n", pVCpu->idCpu, HCPhysGuestCR3));
3995 rc = VMXWriteVmcsHstN(VMX_VMCS_GUEST_CR3, HCPhysGuestCR3);
3996 }
3997 AssertRCReturn(rc, rc);
3998
3999 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR3);
4000 }
4001
4002 /*
4003 * Guest CR4.
4004 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
4005 */
4006 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR4))
4007 {
4008 Assert(!(pMixedCtx->cr4 >> 32));
4009 uint32_t u32GuestCR4 = pMixedCtx->cr4;
4010
4011 /* The guest's view of its CR4 is unblemished. */
4012 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR4_READ_SHADOW, u32GuestCR4);
4013 AssertRCReturn(rc, rc);
4014 Log4(("Load[%RU32]: VMX_VMCS_CTRL_CR4_READ_SHADOW=%#RX32\n", pVCpu->idCpu, u32GuestCR4));
4015
4016 /* Setup VT-x's view of the guest CR4. */
4017 /*
4018 * If we're emulating real-mode using virtual-8086 mode, we want to redirect software interrupts to the 8086 program
4019 * interrupt handler. Clear the VME bit (the interrupt redirection bitmap is already all 0, see hmR3InitFinalizeR0())
4020 * See Intel spec. 20.2 "Software Interrupt Handling Methods While in Virtual-8086 Mode".
4021 */
4022 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4023 {
4024 Assert(pVM->hm.s.vmx.pRealModeTSS);
4025 Assert(PDMVmmDevHeapIsEnabled(pVM));
4026 u32GuestCR4 &= ~X86_CR4_VME;
4027 }
4028
4029 if (pVM->hm.s.fNestedPaging)
4030 {
4031 if ( !CPUMIsGuestPagingEnabledEx(pMixedCtx)
4032 && !pVM->hm.s.vmx.fUnrestrictedGuest)
4033 {
4034 /* We use 4 MB pages in our identity mapping page table when the guest doesn't have paging. */
4035 u32GuestCR4 |= X86_CR4_PSE;
4036 /* Our identity mapping is a 32-bit page directory. */
4037 u32GuestCR4 &= ~X86_CR4_PAE;
4038 }
4039 /* else use guest CR4.*/
4040 }
4041 else
4042 {
4043 /*
4044 * The shadow paging modes and guest paging modes are different, the shadow is in accordance with the host
4045 * paging mode and thus we need to adjust VT-x's view of CR4 depending on our shadow page tables.
4046 */
4047 switch (pVCpu->hm.s.enmShadowMode)
4048 {
4049 case PGMMODE_REAL: /* Real-mode. */
4050 case PGMMODE_PROTECTED: /* Protected mode without paging. */
4051 case PGMMODE_32_BIT: /* 32-bit paging. */
4052 {
4053 u32GuestCR4 &= ~X86_CR4_PAE;
4054 break;
4055 }
4056
4057 case PGMMODE_PAE: /* PAE paging. */
4058 case PGMMODE_PAE_NX: /* PAE paging with NX. */
4059 {
4060 u32GuestCR4 |= X86_CR4_PAE;
4061 break;
4062 }
4063
4064 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
4065 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
4066#ifdef VBOX_ENABLE_64_BITS_GUESTS
4067 break;
4068#endif
4069 default:
4070 AssertFailed();
4071 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
4072 }
4073 }
4074
4075 /* We need to set and clear the CR4 specific bits here (mainly the X86_CR4_VMXE bit). */
4076 uint64_t uSetCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
4077 uint64_t uZapCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
4078 u32GuestCR4 |= uSetCR4;
4079 u32GuestCR4 &= uZapCR4;
4080
4081 /* Write VT-x's view of the guest CR4 into the VMCS. */
4082 Log4(("Load[%RU32]: VMX_VMCS_GUEST_CR4=%#RX32 (Set=%#RX32 Zap=%#RX32)\n", pVCpu->idCpu, u32GuestCR4, uSetCR4, uZapCR4));
4083 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_CR4, u32GuestCR4);
4084 AssertRCReturn(rc, rc);
4085
4086 /* Setup CR4 mask. CR4 flags owned by the host, if the guest attempts to change them, that would cause a VM-exit. */
4087 uint32_t u32CR4Mask = X86_CR4_VME
4088 | X86_CR4_PAE
4089 | X86_CR4_PGE
4090 | X86_CR4_PSE
4091 | X86_CR4_VMXE;
4092 if (pVM->cpum.ro.HostFeatures.fXSaveRstor)
4093 u32CR4Mask |= X86_CR4_OSXSAVE;
4094 pVCpu->hm.s.vmx.u32CR4Mask = u32CR4Mask;
4095 rc = VMXWriteVmcs32(VMX_VMCS_CTRL_CR4_MASK, u32CR4Mask);
4096 AssertRCReturn(rc, rc);
4097
4098 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
4099 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pMixedCtx->cr4 & X86_CR4_OSXSAVE) && pMixedCtx->aXcr[0] != ASMGetXcr0();
4100
4101 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR4);
4102 }
4103 return rc;
4104}
4105
4106
4107/**
4108 * Loads the guest debug registers into the guest-state area in the VMCS.
4109 *
4110 * This also sets up whether \#DB and MOV DRx accesses cause VM-exits.
4111 *
4112 * The guest debug bits are partially shared with the host (e.g. DR6, DR0-3).
4113 *
4114 * @returns VBox status code.
4115 * @param pVCpu The cross context virtual CPU structure.
4116 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4117 * out-of-sync. Make sure to update the required fields
4118 * before using them.
4119 *
4120 * @remarks No-long-jump zone!!!
4121 */
4122static int hmR0VmxLoadSharedDebugState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4123{
4124 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
4125 return VINF_SUCCESS;
4126
4127#ifdef VBOX_STRICT
4128 /* Validate. Intel spec. 26.3.1.1 "Checks on Guest Controls Registers, Debug Registers, MSRs" */
4129 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG)
4130 {
4131 /* Validate. Intel spec. 17.2 "Debug Registers", recompiler paranoia checks. */
4132 Assert((pMixedCtx->dr[7] & (X86_DR7_MBZ_MASK | X86_DR7_RAZ_MASK)) == 0); /* Bits 63:32, 15, 14, 12, 11 are reserved. */
4133 Assert((pMixedCtx->dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK); /* Bit 10 is reserved (RA1). */
4134 }
4135#endif
4136
4137 int rc;
4138 PVM pVM = pVCpu->CTX_SUFF(pVM);
4139 bool fSteppingDB = false;
4140 bool fInterceptMovDRx = false;
4141 if (pVCpu->hm.s.fSingleInstruction)
4142 {
4143 /* If the CPU supports the monitor trap flag, use it for single stepping in DBGF and avoid intercepting #DB. */
4144 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG)
4145 {
4146 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG;
4147 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
4148 AssertRCReturn(rc, rc);
4149 Assert(fSteppingDB == false);
4150 }
4151 else
4152 {
4153 pMixedCtx->eflags.u32 |= X86_EFL_TF;
4154 pVCpu->hm.s.fClearTrapFlag = true;
4155 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RFLAGS);
4156 fSteppingDB = true;
4157 }
4158 }
4159
4160 if ( fSteppingDB
4161 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
4162 {
4163 /*
4164 * Use the combined guest and host DRx values found in the hypervisor
4165 * register set because the debugger has breakpoints active or someone
4166 * is single stepping on the host side without a monitor trap flag.
4167 *
4168 * Note! DBGF expects a clean DR6 state before executing guest code.
4169 */
4170#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4171 if ( CPUMIsGuestInLongModeEx(pMixedCtx)
4172 && !CPUMIsHyperDebugStateActivePending(pVCpu))
4173 {
4174 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
4175 Assert(CPUMIsHyperDebugStateActivePending(pVCpu));
4176 Assert(!CPUMIsGuestDebugStateActivePending(pVCpu));
4177 }
4178 else
4179#endif
4180 if (!CPUMIsHyperDebugStateActive(pVCpu))
4181 {
4182 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
4183 Assert(CPUMIsHyperDebugStateActive(pVCpu));
4184 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
4185 }
4186
4187 /* Update DR7. (The other DRx values are handled by CPUM one way or the other.) */
4188 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_DR7, (uint32_t)CPUMGetHyperDR7(pVCpu));
4189 AssertRCReturn(rc, rc);
4190
4191 pVCpu->hm.s.fUsingHyperDR7 = true;
4192 fInterceptMovDRx = true;
4193 }
4194 else
4195 {
4196 /*
4197 * If the guest has enabled debug registers, we need to load them prior to
4198 * executing guest code so they'll trigger at the right time.
4199 */
4200 if (pMixedCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
4201 {
4202#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4203 if ( CPUMIsGuestInLongModeEx(pMixedCtx)
4204 && !CPUMIsGuestDebugStateActivePending(pVCpu))
4205 {
4206 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
4207 Assert(CPUMIsGuestDebugStateActivePending(pVCpu));
4208 Assert(!CPUMIsHyperDebugStateActivePending(pVCpu));
4209 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
4210 }
4211 else
4212#endif
4213 if (!CPUMIsGuestDebugStateActive(pVCpu))
4214 {
4215 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
4216 Assert(CPUMIsGuestDebugStateActive(pVCpu));
4217 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
4218 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
4219 }
4220 Assert(!fInterceptMovDRx);
4221 }
4222 /*
4223 * If no debugging enabled, we'll lazy load DR0-3. Unlike on AMD-V, we
4224 * must intercept #DB in order to maintain a correct DR6 guest value, and
4225 * because we need to intercept it to prevent nested #DBs from hanging the
4226 * CPU, we end up always having to intercept it. See hmR0VmxInitXcptBitmap.
4227 */
4228#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
4229 else if ( !CPUMIsGuestDebugStateActivePending(pVCpu)
4230 && !CPUMIsGuestDebugStateActive(pVCpu))
4231#else
4232 else if (!CPUMIsGuestDebugStateActive(pVCpu))
4233#endif
4234 {
4235 fInterceptMovDRx = true;
4236 }
4237
4238 /* Update guest DR7. */
4239 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_DR7, pMixedCtx->dr[7]);
4240 AssertRCReturn(rc, rc);
4241
4242 pVCpu->hm.s.fUsingHyperDR7 = false;
4243 }
4244
4245 /*
4246 * Update the processor-based VM-execution controls regarding intercepting MOV DRx instructions.
4247 */
4248 if (fInterceptMovDRx)
4249 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT;
4250 else
4251 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT;
4252 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
4253 AssertRCReturn(rc, rc);
4254
4255 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_DEBUG);
4256 return VINF_SUCCESS;
4257}
4258
4259
4260#ifdef VBOX_STRICT
4261/**
4262 * Strict function to validate segment registers.
4263 *
4264 * @remarks ASSUMES CR0 is up to date.
4265 */
4266static void hmR0VmxValidateSegmentRegs(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4267{
4268 /* Validate segment registers. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers". */
4269 /* NOTE: The reason we check for attribute value 0 and not just the unusable bit here is because hmR0VmxWriteSegmentReg()
4270 * only updates the VMCS' copy of the value with the unusable bit and doesn't change the guest-context value. */
4271 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
4272 && ( !CPUMIsGuestInRealModeEx(pCtx)
4273 && !CPUMIsGuestInV86ModeEx(pCtx)))
4274 {
4275 /* Protected mode checks */
4276 /* CS */
4277 Assert(pCtx->cs.Attr.n.u1Present);
4278 Assert(!(pCtx->cs.Attr.u & 0xf00));
4279 Assert(!(pCtx->cs.Attr.u & 0xfffe0000));
4280 Assert( (pCtx->cs.u32Limit & 0xfff) == 0xfff
4281 || !(pCtx->cs.Attr.n.u1Granularity));
4282 Assert( !(pCtx->cs.u32Limit & 0xfff00000)
4283 || (pCtx->cs.Attr.n.u1Granularity));
4284 /* CS cannot be loaded with NULL in protected mode. */
4285 Assert(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE)); /** @todo is this really true even for 64-bit CS? */
4286 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
4287 Assert(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl);
4288 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
4289 Assert(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl);
4290 else
4291 AssertMsgFailed(("Invalid CS Type %#x\n", pCtx->cs.Attr.n.u2Dpl));
4292 /* SS */
4293 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
4294 Assert(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL));
4295 if ( !(pCtx->cr0 & X86_CR0_PE)
4296 || pCtx->cs.Attr.n.u4Type == 3)
4297 {
4298 Assert(!pCtx->ss.Attr.n.u2Dpl);
4299 }
4300 if (pCtx->ss.Attr.u && !(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
4301 {
4302 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
4303 Assert(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7);
4304 Assert(pCtx->ss.Attr.n.u1Present);
4305 Assert(!(pCtx->ss.Attr.u & 0xf00));
4306 Assert(!(pCtx->ss.Attr.u & 0xfffe0000));
4307 Assert( (pCtx->ss.u32Limit & 0xfff) == 0xfff
4308 || !(pCtx->ss.Attr.n.u1Granularity));
4309 Assert( !(pCtx->ss.u32Limit & 0xfff00000)
4310 || (pCtx->ss.Attr.n.u1Granularity));
4311 }
4312 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxWriteSegmentReg(). */
4313 if (pCtx->ds.Attr.u && !(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
4314 {
4315 Assert(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4316 Assert(pCtx->ds.Attr.n.u1Present);
4317 Assert(pCtx->ds.Attr.n.u4Type > 11 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL));
4318 Assert(!(pCtx->ds.Attr.u & 0xf00));
4319 Assert(!(pCtx->ds.Attr.u & 0xfffe0000));
4320 Assert( (pCtx->ds.u32Limit & 0xfff) == 0xfff
4321 || !(pCtx->ds.Attr.n.u1Granularity));
4322 Assert( !(pCtx->ds.u32Limit & 0xfff00000)
4323 || (pCtx->ds.Attr.n.u1Granularity));
4324 Assert( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4325 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ));
4326 }
4327 if (pCtx->es.Attr.u && !(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
4328 {
4329 Assert(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4330 Assert(pCtx->es.Attr.n.u1Present);
4331 Assert(pCtx->es.Attr.n.u4Type > 11 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL));
4332 Assert(!(pCtx->es.Attr.u & 0xf00));
4333 Assert(!(pCtx->es.Attr.u & 0xfffe0000));
4334 Assert( (pCtx->es.u32Limit & 0xfff) == 0xfff
4335 || !(pCtx->es.Attr.n.u1Granularity));
4336 Assert( !(pCtx->es.u32Limit & 0xfff00000)
4337 || (pCtx->es.Attr.n.u1Granularity));
4338 Assert( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4339 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ));
4340 }
4341 if (pCtx->fs.Attr.u && !(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
4342 {
4343 Assert(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4344 Assert(pCtx->fs.Attr.n.u1Present);
4345 Assert(pCtx->fs.Attr.n.u4Type > 11 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL));
4346 Assert(!(pCtx->fs.Attr.u & 0xf00));
4347 Assert(!(pCtx->fs.Attr.u & 0xfffe0000));
4348 Assert( (pCtx->fs.u32Limit & 0xfff) == 0xfff
4349 || !(pCtx->fs.Attr.n.u1Granularity));
4350 Assert( !(pCtx->fs.u32Limit & 0xfff00000)
4351 || (pCtx->fs.Attr.n.u1Granularity));
4352 Assert( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4353 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ));
4354 }
4355 if (pCtx->gs.Attr.u && !(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
4356 {
4357 Assert(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
4358 Assert(pCtx->gs.Attr.n.u1Present);
4359 Assert(pCtx->gs.Attr.n.u4Type > 11 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL));
4360 Assert(!(pCtx->gs.Attr.u & 0xf00));
4361 Assert(!(pCtx->gs.Attr.u & 0xfffe0000));
4362 Assert( (pCtx->gs.u32Limit & 0xfff) == 0xfff
4363 || !(pCtx->gs.Attr.n.u1Granularity));
4364 Assert( !(pCtx->gs.u32Limit & 0xfff00000)
4365 || (pCtx->gs.Attr.n.u1Granularity));
4366 Assert( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
4367 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ));
4368 }
4369 /* 64-bit capable CPUs. */
4370# if HC_ARCH_BITS == 64
4371 Assert(!(pCtx->cs.u64Base >> 32));
4372 Assert(!pCtx->ss.Attr.u || !(pCtx->ss.u64Base >> 32));
4373 Assert(!pCtx->ds.Attr.u || !(pCtx->ds.u64Base >> 32));
4374 Assert(!pCtx->es.Attr.u || !(pCtx->es.u64Base >> 32));
4375# endif
4376 }
4377 else if ( CPUMIsGuestInV86ModeEx(pCtx)
4378 || ( CPUMIsGuestInRealModeEx(pCtx)
4379 && !pVM->hm.s.vmx.fUnrestrictedGuest))
4380 {
4381 /* Real and v86 mode checks. */
4382 /* hmR0VmxWriteSegmentReg() writes the modified in VMCS. We want what we're feeding to VT-x. */
4383 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
4384 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4385 {
4386 u32CSAttr = 0xf3; u32SSAttr = 0xf3; u32DSAttr = 0xf3; u32ESAttr = 0xf3; u32FSAttr = 0xf3; u32GSAttr = 0xf3;
4387 }
4388 else
4389 {
4390 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u; u32DSAttr = pCtx->ds.Attr.u;
4391 u32ESAttr = pCtx->es.Attr.u; u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
4392 }
4393
4394 /* CS */
4395 AssertMsg((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), ("CS base %#x %#x\n", pCtx->cs.u64Base, pCtx->cs.Sel));
4396 Assert(pCtx->cs.u32Limit == 0xffff);
4397 Assert(u32CSAttr == 0xf3);
4398 /* SS */
4399 Assert(pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4);
4400 Assert(pCtx->ss.u32Limit == 0xffff);
4401 Assert(u32SSAttr == 0xf3);
4402 /* DS */
4403 Assert(pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4);
4404 Assert(pCtx->ds.u32Limit == 0xffff);
4405 Assert(u32DSAttr == 0xf3);
4406 /* ES */
4407 Assert(pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4);
4408 Assert(pCtx->es.u32Limit == 0xffff);
4409 Assert(u32ESAttr == 0xf3);
4410 /* FS */
4411 Assert(pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4);
4412 Assert(pCtx->fs.u32Limit == 0xffff);
4413 Assert(u32FSAttr == 0xf3);
4414 /* GS */
4415 Assert(pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4);
4416 Assert(pCtx->gs.u32Limit == 0xffff);
4417 Assert(u32GSAttr == 0xf3);
4418 /* 64-bit capable CPUs. */
4419# if HC_ARCH_BITS == 64
4420 Assert(!(pCtx->cs.u64Base >> 32));
4421 Assert(!u32SSAttr || !(pCtx->ss.u64Base >> 32));
4422 Assert(!u32DSAttr || !(pCtx->ds.u64Base >> 32));
4423 Assert(!u32ESAttr || !(pCtx->es.u64Base >> 32));
4424# endif
4425 }
4426}
4427#endif /* VBOX_STRICT */
4428
4429
4430/**
4431 * Writes a guest segment register into the guest-state area in the VMCS.
4432 *
4433 * @returns VBox status code.
4434 * @param pVCpu The cross context virtual CPU structure.
4435 * @param idxSel Index of the selector in the VMCS.
4436 * @param idxLimit Index of the segment limit in the VMCS.
4437 * @param idxBase Index of the segment base in the VMCS.
4438 * @param idxAccess Index of the access rights of the segment in the VMCS.
4439 * @param pSelReg Pointer to the segment selector.
4440 *
4441 * @remarks No-long-jump zone!!!
4442 */
4443static int hmR0VmxWriteSegmentReg(PVMCPU pVCpu, uint32_t idxSel, uint32_t idxLimit, uint32_t idxBase,
4444 uint32_t idxAccess, PCPUMSELREG pSelReg)
4445{
4446 int rc = VMXWriteVmcs32(idxSel, pSelReg->Sel); /* 16-bit guest selector field. */
4447 rc |= VMXWriteVmcs32(idxLimit, pSelReg->u32Limit); /* 32-bit guest segment limit field. */
4448 rc |= VMXWriteVmcsGstN(idxBase, pSelReg->u64Base); /* Natural width guest segment base field.*/
4449 AssertRCReturn(rc, rc);
4450
4451 uint32_t u32Access = pSelReg->Attr.u;
4452 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4453 {
4454 /* VT-x requires our real-using-v86 mode hack to override the segment access-right bits. */
4455 u32Access = 0xf3;
4456 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
4457 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
4458 }
4459 else
4460 {
4461 /*
4462 * The way to differentiate between whether this is really a null selector or was just a selector loaded with 0 in
4463 * real-mode is using the segment attributes. A selector loaded in real-mode with the value 0 is valid and usable in
4464 * protected-mode and we should -not- mark it as an unusable segment. Both the recompiler & VT-x ensures NULL selectors
4465 * loaded in protected-mode have their attribute as 0.
4466 */
4467 if (!u32Access)
4468 u32Access = X86DESCATTR_UNUSABLE;
4469 }
4470
4471 /* Validate segment access rights. Refer to Intel spec. "26.3.1.2 Checks on Guest Segment Registers". */
4472 AssertMsg((u32Access & X86DESCATTR_UNUSABLE) || (u32Access & X86_SEL_TYPE_ACCESSED),
4473 ("Access bit not set for usable segment. idx=%#x sel=%#x attr %#x\n", idxBase, pSelReg, pSelReg->Attr.u));
4474
4475 rc = VMXWriteVmcs32(idxAccess, u32Access); /* 32-bit guest segment access-rights field. */
4476 AssertRCReturn(rc, rc);
4477 return rc;
4478}
4479
4480
4481/**
4482 * Loads the guest segment registers, GDTR, IDTR, LDTR, (TR, FS and GS bases)
4483 * into the guest-state area in the VMCS.
4484 *
4485 * @returns VBox status code.
4486 * @param pVCpu The cross context virtual CPU structure.
4487 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4488 * out-of-sync. Make sure to update the required fields
4489 * before using them.
4490 *
4491 * @remarks ASSUMES pMixedCtx->cr0 is up to date (strict builds validation).
4492 * @remarks No-long-jump zone!!!
4493 */
4494static int hmR0VmxLoadGuestSegmentRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4495{
4496 int rc = VERR_INTERNAL_ERROR_5;
4497 PVM pVM = pVCpu->CTX_SUFF(pVM);
4498
4499 /*
4500 * Guest Segment registers: CS, SS, DS, ES, FS, GS.
4501 */
4502 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS))
4503 {
4504 /* Save the segment attributes for real-on-v86 mode hack, so we can restore them on VM-exit. */
4505 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4506 {
4507 pVCpu->hm.s.vmx.RealMode.AttrCS.u = pMixedCtx->cs.Attr.u;
4508 pVCpu->hm.s.vmx.RealMode.AttrSS.u = pMixedCtx->ss.Attr.u;
4509 pVCpu->hm.s.vmx.RealMode.AttrDS.u = pMixedCtx->ds.Attr.u;
4510 pVCpu->hm.s.vmx.RealMode.AttrES.u = pMixedCtx->es.Attr.u;
4511 pVCpu->hm.s.vmx.RealMode.AttrFS.u = pMixedCtx->fs.Attr.u;
4512 pVCpu->hm.s.vmx.RealMode.AttrGS.u = pMixedCtx->gs.Attr.u;
4513 }
4514
4515#ifdef VBOX_WITH_REM
4516 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
4517 {
4518 Assert(pVM->hm.s.vmx.pRealModeTSS);
4519 AssertCompile(PGMMODE_REAL < PGMMODE_PROTECTED);
4520 if ( pVCpu->hm.s.vmx.fWasInRealMode
4521 && PGMGetGuestMode(pVCpu) >= PGMMODE_PROTECTED)
4522 {
4523 /* Signal that the recompiler must flush its code-cache as the guest -may- rewrite code it will later execute
4524 in real-mode (e.g. OpenBSD 4.0) */
4525 REMFlushTBs(pVM);
4526 Log4(("Load[%RU32]: Switch to protected mode detected!\n", pVCpu->idCpu));
4527 pVCpu->hm.s.vmx.fWasInRealMode = false;
4528 }
4529 }
4530#endif
4531 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_CS_SEL, VMX_VMCS32_GUEST_CS_LIMIT, VMX_VMCS_GUEST_CS_BASE,
4532 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS, &pMixedCtx->cs);
4533 AssertRCReturn(rc, rc);
4534 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_SS_SEL, VMX_VMCS32_GUEST_SS_LIMIT, VMX_VMCS_GUEST_SS_BASE,
4535 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS, &pMixedCtx->ss);
4536 AssertRCReturn(rc, rc);
4537 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_DS_SEL, VMX_VMCS32_GUEST_DS_LIMIT, VMX_VMCS_GUEST_DS_BASE,
4538 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS, &pMixedCtx->ds);
4539 AssertRCReturn(rc, rc);
4540 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_ES_SEL, VMX_VMCS32_GUEST_ES_LIMIT, VMX_VMCS_GUEST_ES_BASE,
4541 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS, &pMixedCtx->es);
4542 AssertRCReturn(rc, rc);
4543 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_FS_SEL, VMX_VMCS32_GUEST_FS_LIMIT, VMX_VMCS_GUEST_FS_BASE,
4544 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS, &pMixedCtx->fs);
4545 AssertRCReturn(rc, rc);
4546 rc = hmR0VmxWriteSegmentReg(pVCpu, VMX_VMCS16_GUEST_GS_SEL, VMX_VMCS32_GUEST_GS_LIMIT, VMX_VMCS_GUEST_GS_BASE,
4547 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS, &pMixedCtx->gs);
4548 AssertRCReturn(rc, rc);
4549
4550#ifdef VBOX_STRICT
4551 /* Validate. */
4552 hmR0VmxValidateSegmentRegs(pVM, pVCpu, pMixedCtx);
4553#endif
4554
4555 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS);
4556 Log4(("Load[%RU32]: CS=%#RX16 Base=%#RX64 Limit=%#RX32 Attr=%#RX32\n", pVCpu->idCpu, pMixedCtx->cs.Sel,
4557 pMixedCtx->cs.u64Base, pMixedCtx->cs.u32Limit, pMixedCtx->cs.Attr.u));
4558 }
4559
4560 /*
4561 * Guest TR.
4562 */
4563 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_TR))
4564 {
4565 /*
4566 * Real-mode emulation using virtual-8086 mode with CR4.VME. Interrupt redirection is achieved
4567 * using the interrupt redirection bitmap (all bits cleared to let the guest handle INT-n's) in the TSS.
4568 * See hmR3InitFinalizeR0() to see how pRealModeTSS is setup.
4569 */
4570 uint16_t u16Sel = 0;
4571 uint32_t u32Limit = 0;
4572 uint64_t u64Base = 0;
4573 uint32_t u32AccessRights = 0;
4574
4575 if (!pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
4576 {
4577 u16Sel = pMixedCtx->tr.Sel;
4578 u32Limit = pMixedCtx->tr.u32Limit;
4579 u64Base = pMixedCtx->tr.u64Base;
4580 u32AccessRights = pMixedCtx->tr.Attr.u;
4581 }
4582 else
4583 {
4584 Assert(pVM->hm.s.vmx.pRealModeTSS);
4585 Assert(PDMVmmDevHeapIsEnabled(pVM)); /* Guaranteed by HMR3CanExecuteGuest() -XXX- what about inner loop changes? */
4586
4587 /* We obtain it here every time as PCI regions could be reconfigured in the guest, changing the VMMDev base. */
4588 RTGCPHYS GCPhys;
4589 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
4590 AssertRCReturn(rc, rc);
4591
4592 X86DESCATTR DescAttr;
4593 DescAttr.u = 0;
4594 DescAttr.n.u1Present = 1;
4595 DescAttr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
4596
4597 u16Sel = 0;
4598 u32Limit = HM_VTX_TSS_SIZE;
4599 u64Base = GCPhys; /* in real-mode phys = virt. */
4600 u32AccessRights = DescAttr.u;
4601 }
4602
4603 /* Validate. */
4604 Assert(!(u16Sel & RT_BIT(2)));
4605 AssertMsg( (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY
4606 || (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("TSS is not busy!? %#x\n", u32AccessRights));
4607 AssertMsg(!(u32AccessRights & X86DESCATTR_UNUSABLE), ("TR unusable bit is not clear!? %#x\n", u32AccessRights));
4608 Assert(!(u32AccessRights & RT_BIT(4))); /* System MBZ.*/
4609 Assert(u32AccessRights & RT_BIT(7)); /* Present MB1.*/
4610 Assert(!(u32AccessRights & 0xf00)); /* 11:8 MBZ. */
4611 Assert(!(u32AccessRights & 0xfffe0000)); /* 31:17 MBZ. */
4612 Assert( (u32Limit & 0xfff) == 0xfff
4613 || !(u32AccessRights & RT_BIT(15))); /* Granularity MBZ. */
4614 Assert( !(pMixedCtx->tr.u32Limit & 0xfff00000)
4615 || (u32AccessRights & RT_BIT(15))); /* Granularity MB1. */
4616
4617 rc = VMXWriteVmcs32(VMX_VMCS16_GUEST_TR_SEL, u16Sel);
4618 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, u32Limit);
4619 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_TR_BASE, u64Base);
4620 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, u32AccessRights);
4621 AssertRCReturn(rc, rc);
4622
4623 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_TR);
4624 Log4(("Load[%RU32]: VMX_VMCS_GUEST_TR_BASE=%#RX64\n", pVCpu->idCpu, u64Base));
4625 }
4626
4627 /*
4628 * Guest GDTR.
4629 */
4630 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_GDTR))
4631 {
4632 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, pMixedCtx->gdtr.cbGdt);
4633 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_GDTR_BASE, pMixedCtx->gdtr.pGdt);
4634 AssertRCReturn(rc, rc);
4635
4636 /* Validate. */
4637 Assert(!(pMixedCtx->gdtr.cbGdt & 0xffff0000)); /* Bits 31:16 MBZ. */
4638
4639 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_GDTR);
4640 Log4(("Load[%RU32]: VMX_VMCS_GUEST_GDTR_BASE=%#RX64\n", pVCpu->idCpu, pMixedCtx->gdtr.pGdt));
4641 }
4642
4643 /*
4644 * Guest LDTR.
4645 */
4646 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LDTR))
4647 {
4648 /* The unusable bit is specific to VT-x, if it's a null selector mark it as an unusable segment. */
4649 uint32_t u32Access = 0;
4650 if (!pMixedCtx->ldtr.Attr.u)
4651 u32Access = X86DESCATTR_UNUSABLE;
4652 else
4653 u32Access = pMixedCtx->ldtr.Attr.u;
4654
4655 rc = VMXWriteVmcs32(VMX_VMCS16_GUEST_LDTR_SEL, pMixedCtx->ldtr.Sel);
4656 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, pMixedCtx->ldtr.u32Limit);
4657 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_LDTR_BASE, pMixedCtx->ldtr.u64Base);
4658 rc |= VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, u32Access);
4659 AssertRCReturn(rc, rc);
4660
4661 /* Validate. */
4662 if (!(u32Access & X86DESCATTR_UNUSABLE))
4663 {
4664 Assert(!(pMixedCtx->ldtr.Sel & RT_BIT(2))); /* TI MBZ. */
4665 Assert(pMixedCtx->ldtr.Attr.n.u4Type == 2); /* Type MB2 (LDT). */
4666 Assert(!pMixedCtx->ldtr.Attr.n.u1DescType); /* System MBZ. */
4667 Assert(pMixedCtx->ldtr.Attr.n.u1Present == 1); /* Present MB1. */
4668 Assert(!pMixedCtx->ldtr.Attr.n.u4LimitHigh); /* 11:8 MBZ. */
4669 Assert(!(pMixedCtx->ldtr.Attr.u & 0xfffe0000)); /* 31:17 MBZ. */
4670 Assert( (pMixedCtx->ldtr.u32Limit & 0xfff) == 0xfff
4671 || !pMixedCtx->ldtr.Attr.n.u1Granularity); /* Granularity MBZ. */
4672 Assert( !(pMixedCtx->ldtr.u32Limit & 0xfff00000)
4673 || pMixedCtx->ldtr.Attr.n.u1Granularity); /* Granularity MB1. */
4674 }
4675
4676 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LDTR);
4677 Log4(("Load[%RU32]: VMX_VMCS_GUEST_LDTR_BASE=%#RX64\n", pVCpu->idCpu, pMixedCtx->ldtr.u64Base));
4678 }
4679
4680 /*
4681 * Guest IDTR.
4682 */
4683 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_IDTR))
4684 {
4685 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, pMixedCtx->idtr.cbIdt);
4686 rc |= VMXWriteVmcsGstN(VMX_VMCS_GUEST_IDTR_BASE, pMixedCtx->idtr.pIdt);
4687 AssertRCReturn(rc, rc);
4688
4689 /* Validate. */
4690 Assert(!(pMixedCtx->idtr.cbIdt & 0xffff0000)); /* Bits 31:16 MBZ. */
4691
4692 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_IDTR);
4693 Log4(("Load[%RU32]: VMX_VMCS_GUEST_IDTR_BASE=%#RX64\n", pVCpu->idCpu, pMixedCtx->idtr.pIdt));
4694 }
4695
4696 return VINF_SUCCESS;
4697}
4698
4699
4700/**
4701 * Loads certain guest MSRs into the VM-entry MSR-load and VM-exit MSR-store
4702 * areas.
4703 *
4704 * These MSRs will automatically be loaded to the host CPU on every successful
4705 * VM-entry and stored from the host CPU on every successful VM-exit. This also
4706 * creates/updates MSR slots for the host MSRs. The actual host MSR values are
4707 * -not- updated here for performance reasons. See hmR0VmxSaveHostMsrs().
4708 *
4709 * Also loads the sysenter MSRs into the guest-state area in the VMCS.
4710 *
4711 * @returns VBox status code.
4712 * @param pVCpu The cross context virtual CPU structure.
4713 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4714 * out-of-sync. Make sure to update the required fields
4715 * before using them.
4716 *
4717 * @remarks No-long-jump zone!!!
4718 */
4719static int hmR0VmxLoadGuestMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4720{
4721 AssertPtr(pVCpu);
4722 AssertPtr(pVCpu->hm.s.vmx.pvGuestMsr);
4723
4724 /*
4725 * MSRs that we use the auto-load/store MSR area in the VMCS.
4726 */
4727 PVM pVM = pVCpu->CTX_SUFF(pVM);
4728 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS))
4729 {
4730 /* For 64-bit hosts, we load/restore them lazily, see hmR0VmxLazyLoadGuestMsrs(). */
4731#if HC_ARCH_BITS == 32
4732 if (pVM->hm.s.fAllow64BitGuests)
4733 {
4734 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_LSTAR, pMixedCtx->msrLSTAR, false, NULL);
4735 rc |= hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K6_STAR, pMixedCtx->msrSTAR, false, NULL);
4736 rc |= hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_SF_MASK, pMixedCtx->msrSFMASK, false, NULL);
4737 rc |= hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_KERNEL_GS_BASE, pMixedCtx->msrKERNELGSBASE, false, NULL);
4738 AssertRCReturn(rc, rc);
4739# ifdef LOG_ENABLED
4740 PVMXAUTOMSR pMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
4741 for (uint32_t i = 0; i < pVCpu->hm.s.vmx.cMsrs; i++, pMsr++)
4742 {
4743 Log4(("Load[%RU32]: MSR[%RU32]: u32Msr=%#RX32 u64Value=%#RX64\n", pVCpu->idCpu, i, pMsr->u32Msr,
4744 pMsr->u64Value));
4745 }
4746# endif
4747 }
4748#endif
4749 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
4750 }
4751
4752 /*
4753 * Guest Sysenter MSRs.
4754 * These flags are only set when MSR-bitmaps are not supported by the CPU and we cause
4755 * VM-exits on WRMSRs for these MSRs.
4756 */
4757 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR))
4758 {
4759 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, pMixedCtx->SysEnter.cs); AssertRCReturn(rc, rc);
4760 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR);
4761 }
4762
4763 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR))
4764 {
4765 int rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_SYSENTER_EIP, pMixedCtx->SysEnter.eip); AssertRCReturn(rc, rc);
4766 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
4767 }
4768
4769 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR))
4770 {
4771 int rc = VMXWriteVmcsGstN(VMX_VMCS_GUEST_SYSENTER_ESP, pMixedCtx->SysEnter.esp); AssertRCReturn(rc, rc);
4772 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
4773 }
4774
4775 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_EFER_MSR))
4776 {
4777 if (hmR0VmxShouldSwapEferMsr(pVCpu, pMixedCtx))
4778 {
4779 /*
4780 * If the CPU supports VMCS controls for swapping EFER, use it. Otherwise, we have no option
4781 * but to use the auto-load store MSR area in the VMCS for swapping EFER. See @bugref{7368}.
4782 */
4783 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
4784 {
4785 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_EFER_FULL, pMixedCtx->msrEFER);
4786 AssertRCReturn(rc,rc);
4787 Log4(("Load[%RU32]: VMX_VMCS64_GUEST_EFER_FULL=%#RX64\n", pVCpu->idCpu, pMixedCtx->msrEFER));
4788 }
4789 else
4790 {
4791 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K6_EFER, pMixedCtx->msrEFER, false /* fUpdateHostMsr */,
4792 NULL /* pfAddedAndUpdated */);
4793 AssertRCReturn(rc, rc);
4794
4795 /* We need to intercept reads too, see @bugref{7386#c16}. */
4796 if (pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
4797 hmR0VmxSetMsrPermission(pVCpu, MSR_K6_EFER, VMXMSREXIT_INTERCEPT_READ, VMXMSREXIT_INTERCEPT_WRITE);
4798 Log4(("Load[%RU32]: MSR[--]: u32Msr=%#RX32 u64Value=%#RX64 cMsrs=%u\n", pVCpu->idCpu, MSR_K6_EFER,
4799 pMixedCtx->msrEFER, pVCpu->hm.s.vmx.cMsrs));
4800 }
4801 }
4802 else if (!pVM->hm.s.vmx.fSupportsVmcsEfer)
4803 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, MSR_K6_EFER);
4804 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
4805 }
4806
4807 return VINF_SUCCESS;
4808}
4809
4810
4811/**
4812 * Loads the guest activity state into the guest-state area in the VMCS.
4813 *
4814 * @returns VBox status code.
4815 * @param pVCpu The cross context virtual CPU structure.
4816 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4817 * out-of-sync. Make sure to update the required fields
4818 * before using them.
4819 *
4820 * @remarks No-long-jump zone!!!
4821 */
4822static int hmR0VmxLoadGuestActivityState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4823{
4824 NOREF(pMixedCtx);
4825 /** @todo See if we can make use of other states, e.g.
4826 * VMX_VMCS_GUEST_ACTIVITY_SHUTDOWN or HLT. */
4827 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_VMX_GUEST_ACTIVITY_STATE))
4828 {
4829 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, VMX_VMCS_GUEST_ACTIVITY_ACTIVE);
4830 AssertRCReturn(rc, rc);
4831
4832 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_VMX_GUEST_ACTIVITY_STATE);
4833 }
4834 return VINF_SUCCESS;
4835}
4836
4837
4838#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
4839/**
4840 * Check if guest state allows safe use of 32-bit switcher again.
4841 *
4842 * Segment bases and protected mode structures must be 32-bit addressable
4843 * because the 32-bit switcher will ignore high dword when writing these VMCS
4844 * fields. See @bugref{8432} for details.
4845 *
4846 * @returns true if safe, false if must continue to use the 64-bit switcher.
4847 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4848 * out-of-sync. Make sure to update the required fields
4849 * before using them.
4850 *
4851 * @remarks No-long-jump zone!!!
4852 */
4853static bool hmR0VmxIs32BitSwitcherSafe(PCPUMCTX pMixedCtx)
4854{
4855 if (pMixedCtx->gdtr.pGdt & UINT64_C(0xffffffff00000000))
4856 return false;
4857 if (pMixedCtx->idtr.pIdt & UINT64_C(0xffffffff00000000))
4858 return false;
4859 if (pMixedCtx->ldtr.u64Base & UINT64_C(0xffffffff00000000))
4860 return false;
4861 if (pMixedCtx->tr.u64Base & UINT64_C(0xffffffff00000000))
4862 return false;
4863 if (pMixedCtx->es.u64Base & UINT64_C(0xffffffff00000000))
4864 return false;
4865 if (pMixedCtx->cs.u64Base & UINT64_C(0xffffffff00000000))
4866 return false;
4867 if (pMixedCtx->ss.u64Base & UINT64_C(0xffffffff00000000))
4868 return false;
4869 if (pMixedCtx->ds.u64Base & UINT64_C(0xffffffff00000000))
4870 return false;
4871 if (pMixedCtx->fs.u64Base & UINT64_C(0xffffffff00000000))
4872 return false;
4873 if (pMixedCtx->gs.u64Base & UINT64_C(0xffffffff00000000))
4874 return false;
4875 /* All good, bases are 32-bit. */
4876 return true;
4877}
4878#endif
4879
4880
4881/**
4882 * Sets up the appropriate function to run guest code.
4883 *
4884 * @returns VBox status code.
4885 * @param pVCpu The cross context virtual CPU structure.
4886 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
4887 * out-of-sync. Make sure to update the required fields
4888 * before using them.
4889 *
4890 * @remarks No-long-jump zone!!!
4891 */
4892static int hmR0VmxSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
4893{
4894 if (CPUMIsGuestInLongModeEx(pMixedCtx))
4895 {
4896#ifndef VBOX_ENABLE_64_BITS_GUESTS
4897 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
4898#endif
4899 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
4900#if HC_ARCH_BITS == 32
4901 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
4902 if (pVCpu->hm.s.vmx.pfnStartVM != VMXR0SwitcherStartVM64)
4903 {
4904 if (pVCpu->hm.s.vmx.pfnStartVM != NULL) /* Very first entry would have saved host-state already, ignore it. */
4905 {
4906 /* Currently, all mode changes sends us back to ring-3, so these should be set. See @bugref{6944}. */
4907 AssertMsg(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_VMX_EXIT_CTLS
4908 | HM_CHANGED_VMX_ENTRY_CTLS
4909 | HM_CHANGED_GUEST_EFER_MSR), ("flags=%#x\n", HMCPU_CF_VALUE(pVCpu)));
4910 }
4911 pVCpu->hm.s.vmx.pfnStartVM = VMXR0SwitcherStartVM64;
4912
4913 /* Mark that we've switched to 64-bit handler, we can't safely switch back to 32-bit for
4914 the rest of the VM run (until VM reset). See @bugref{8432#c7}. */
4915 pVCpu->hm.s.vmx.fSwitchedTo64on32 = true;
4916 Log4(("Load[%RU32]: hmR0VmxSetupVMRunHandler: selected 64-bit switcher\n", pVCpu->idCpu));
4917 }
4918#else
4919 /* 64-bit host. */
4920 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM64;
4921#endif
4922 }
4923 else
4924 {
4925 /* Guest is not in long mode, use the 32-bit handler. */
4926#if HC_ARCH_BITS == 32
4927 if ( pVCpu->hm.s.vmx.pfnStartVM != VMXR0StartVM32
4928 && !pVCpu->hm.s.vmx.fSwitchedTo64on32 /* If set, guest mode change does not imply switcher change. */
4929 && pVCpu->hm.s.vmx.pfnStartVM != NULL) /* Very first entry would have saved host-state already, ignore it. */
4930 {
4931 /* Currently, all mode changes sends us back to ring-3, so these should be set. See @bugref{6944}. */
4932 AssertMsg(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_VMX_EXIT_CTLS
4933 | HM_CHANGED_VMX_ENTRY_CTLS
4934 | HM_CHANGED_GUEST_EFER_MSR), ("flags=%#x\n", HMCPU_CF_VALUE(pVCpu)));
4935 }
4936# ifdef VBOX_ENABLE_64_BITS_GUESTS
4937 /*
4938 * Keep using the 64-bit switcher even though we're in 32-bit because of bad Intel design, see @bugref{8432#c7}.
4939 * If real-on-v86 mode is active, clear the 64-bit switcher flag because now we know the guest is in a sane
4940 * state where it's safe to use the 32-bit switcher. Otherwise check the guest state if it's safe to use
4941 * the much faster 32-bit switcher again.
4942 */
4943 if (!pVCpu->hm.s.vmx.fSwitchedTo64on32)
4944 {
4945 if (pVCpu->hm.s.vmx.pfnStartVM != VMXR0StartVM32)
4946 Log4(("Load[%RU32]: hmR0VmxSetupVMRunHandler: selected 32-bit switcher\n", pVCpu->idCpu));
4947 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4948 }
4949 else
4950 {
4951 Assert(pVCpu->hm.s.vmx.pfnStartVM == VMXR0SwitcherStartVM64);
4952 if ( pVCpu->hm.s.vmx.RealMode.fRealOnV86Active
4953 || hmR0VmxIs32BitSwitcherSafe(pMixedCtx))
4954 {
4955 pVCpu->hm.s.vmx.fSwitchedTo64on32 = false;
4956 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4957 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR
4958 | HM_CHANGED_VMX_ENTRY_CTLS
4959 | HM_CHANGED_VMX_EXIT_CTLS
4960 | HM_CHANGED_HOST_CONTEXT);
4961 Log4(("Load[%RU32]: hmR0VmxSetupVMRunHandler: selected 32-bit switcher (safe)\n", pVCpu->idCpu));
4962 }
4963 }
4964# else
4965 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4966# endif
4967#else
4968 pVCpu->hm.s.vmx.pfnStartVM = VMXR0StartVM32;
4969#endif
4970 }
4971 Assert(pVCpu->hm.s.vmx.pfnStartVM);
4972 return VINF_SUCCESS;
4973}
4974
4975
4976/**
4977 * Wrapper for running the guest code in VT-x.
4978 *
4979 * @returns VBox status code, no informational status codes.
4980 * @param pVM The cross context VM structure.
4981 * @param pVCpu The cross context virtual CPU structure.
4982 * @param pCtx Pointer to the guest-CPU context.
4983 *
4984 * @remarks No-long-jump zone!!!
4985 */
4986DECLINLINE(int) hmR0VmxRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
4987{
4988 /*
4989 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
4990 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
4991 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
4992 */
4993 bool const fResumeVM = RT_BOOL(pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_LAUNCHED);
4994 /** @todo Add stats for resume vs launch. */
4995#ifdef VBOX_WITH_KERNEL_USING_XMM
4996 int rc = HMR0VMXStartVMWrapXMM(fResumeVM, pCtx, &pVCpu->hm.s.vmx.VMCSCache, pVM, pVCpu, pVCpu->hm.s.vmx.pfnStartVM);
4997#else
4998 int rc = pVCpu->hm.s.vmx.pfnStartVM(fResumeVM, pCtx, &pVCpu->hm.s.vmx.VMCSCache, pVM, pVCpu);
4999#endif
5000 AssertMsg(rc <= VINF_SUCCESS, ("%Rrc\n", rc));
5001 return rc;
5002}
5003
5004
5005/**
5006 * Reports world-switch error and dumps some useful debug info.
5007 *
5008 * @param pVM The cross context VM structure.
5009 * @param pVCpu The cross context virtual CPU structure.
5010 * @param rcVMRun The return code from VMLAUNCH/VMRESUME.
5011 * @param pCtx Pointer to the guest-CPU context.
5012 * @param pVmxTransient Pointer to the VMX transient structure (only
5013 * exitReason updated).
5014 */
5015static void hmR0VmxReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx, PVMXTRANSIENT pVmxTransient)
5016{
5017 Assert(pVM);
5018 Assert(pVCpu);
5019 Assert(pCtx);
5020 Assert(pVmxTransient);
5021 HMVMX_ASSERT_PREEMPT_SAFE();
5022
5023 Log4(("VM-entry failure: %Rrc\n", rcVMRun));
5024 switch (rcVMRun)
5025 {
5026 case VERR_VMX_INVALID_VMXON_PTR:
5027 AssertFailed();
5028 break;
5029 case VINF_SUCCESS: /* VMLAUNCH/VMRESUME succeeded but VM-entry failed... yeah, true story. */
5030 case VERR_VMX_UNABLE_TO_START_VM: /* VMLAUNCH/VMRESUME itself failed. */
5031 {
5032 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &pVCpu->hm.s.vmx.LastError.u32ExitReason);
5033 rc |= VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
5034 rc |= hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
5035 AssertRC(rc);
5036
5037 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
5038 /* LastError.idCurrentCpu was already updated in hmR0VmxPreRunGuestCommitted().
5039 Cannot do it here as we may have been long preempted. */
5040
5041#ifdef VBOX_STRICT
5042 Log4(("uExitReason %#RX32 (VmxTransient %#RX16)\n", pVCpu->hm.s.vmx.LastError.u32ExitReason,
5043 pVmxTransient->uExitReason));
5044 Log4(("Exit Qualification %#RX64\n", pVmxTransient->uExitQualification));
5045 Log4(("InstrError %#RX32\n", pVCpu->hm.s.vmx.LastError.u32InstrError));
5046 if (pVCpu->hm.s.vmx.LastError.u32InstrError <= HMVMX_INSTR_ERROR_MAX)
5047 Log4(("InstrError Desc. \"%s\"\n", g_apszVmxInstrErrors[pVCpu->hm.s.vmx.LastError.u32InstrError]));
5048 else
5049 Log4(("InstrError Desc. Range exceeded %u\n", HMVMX_INSTR_ERROR_MAX));
5050 Log4(("Entered host CPU %u\n", pVCpu->hm.s.vmx.LastError.idEnteredCpu));
5051 Log4(("Current host CPU %u\n", pVCpu->hm.s.vmx.LastError.idCurrentCpu));
5052
5053 /* VMX control bits. */
5054 uint32_t u32Val;
5055 uint64_t u64Val;
5056 RTHCUINTREG uHCReg;
5057 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val); AssertRC(rc);
5058 Log4(("VMX_VMCS32_CTRL_PIN_EXEC %#RX32\n", u32Val));
5059 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val); AssertRC(rc);
5060 Log4(("VMX_VMCS32_CTRL_PROC_EXEC %#RX32\n", u32Val));
5061 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
5062 {
5063 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val); AssertRC(rc);
5064 Log4(("VMX_VMCS32_CTRL_PROC_EXEC2 %#RX32\n", u32Val));
5065 }
5066 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val); AssertRC(rc);
5067 Log4(("VMX_VMCS32_CTRL_ENTRY %#RX32\n", u32Val));
5068 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val); AssertRC(rc);
5069 Log4(("VMX_VMCS32_CTRL_EXIT %#RX32\n", u32Val));
5070 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_CR3_TARGET_COUNT, &u32Val); AssertRC(rc);
5071 Log4(("VMX_VMCS32_CTRL_CR3_TARGET_COUNT %#RX32\n", u32Val));
5072 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32Val); AssertRC(rc);
5073 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", u32Val));
5074 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &u32Val); AssertRC(rc);
5075 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", u32Val));
5076 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &u32Val); AssertRC(rc);
5077 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %u\n", u32Val));
5078 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, &u32Val); AssertRC(rc);
5079 Log4(("VMX_VMCS32_CTRL_TPR_THRESHOLD %u\n", u32Val));
5080 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &u32Val); AssertRC(rc);
5081 Log4(("VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT %u (guest MSRs)\n", u32Val));
5082 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &u32Val); AssertRC(rc);
5083 Log4(("VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT %u (host MSRs)\n", u32Val));
5084 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &u32Val); AssertRC(rc);
5085 Log4(("VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT %u (guest MSRs)\n", u32Val));
5086 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, &u32Val); AssertRC(rc);
5087 Log4(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP %#RX32\n", u32Val));
5088 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, &u32Val); AssertRC(rc);
5089 Log4(("VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK %#RX32\n", u32Val));
5090 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, &u32Val); AssertRC(rc);
5091 Log4(("VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH %#RX32\n", u32Val));
5092 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_MASK, &uHCReg); AssertRC(rc);
5093 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RHr\n", uHCReg));
5094 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_READ_SHADOW, &uHCReg); AssertRC(rc);
5095 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
5096 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_MASK, &uHCReg); AssertRC(rc);
5097 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RHr\n", uHCReg));
5098 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_READ_SHADOW, &uHCReg); AssertRC(rc);
5099 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
5100 if (pVM->hm.s.fNestedPaging)
5101 {
5102 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
5103 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
5104 }
5105
5106 /* Guest bits. */
5107 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RIP, &u64Val); AssertRC(rc);
5108 Log4(("Old Guest Rip %#RX64 New %#RX64\n", pCtx->rip, u64Val));
5109 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RSP, &u64Val); AssertRC(rc);
5110 Log4(("Old Guest Rsp %#RX64 New %#RX64\n", pCtx->rsp, u64Val));
5111 rc = VMXReadVmcs32(VMX_VMCS_GUEST_RFLAGS, &u32Val); AssertRC(rc);
5112 Log4(("Old Guest Rflags %#RX32 New %#RX32\n", pCtx->eflags.u32, u32Val));
5113 if (pVM->hm.s.vmx.fVpid)
5114 {
5115 rc = VMXReadVmcs32(VMX_VMCS16_VPID, &u32Val); AssertRC(rc);
5116 Log4(("VMX_VMCS16_VPID %u\n", u32Val));
5117 }
5118
5119 /* Host bits. */
5120 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_CR0, &uHCReg); AssertRC(rc);
5121 Log4(("Host CR0 %#RHr\n", uHCReg));
5122 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_CR3, &uHCReg); AssertRC(rc);
5123 Log4(("Host CR3 %#RHr\n", uHCReg));
5124 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_CR4, &uHCReg); AssertRC(rc);
5125 Log4(("Host CR4 %#RHr\n", uHCReg));
5126
5127 RTGDTR HostGdtr;
5128 PCX86DESCHC pDesc;
5129 ASMGetGDTR(&HostGdtr);
5130 rc = VMXReadVmcs32(VMX_VMCS16_HOST_CS_SEL, &u32Val); AssertRC(rc);
5131 Log4(("Host CS %#08x\n", u32Val));
5132 if (u32Val < HostGdtr.cbGdt)
5133 {
5134 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5135 HMR0DumpDescriptor(pDesc, u32Val, "CS: ");
5136 }
5137
5138 rc = VMXReadVmcs32(VMX_VMCS16_HOST_DS_SEL, &u32Val); AssertRC(rc);
5139 Log4(("Host DS %#08x\n", u32Val));
5140 if (u32Val < HostGdtr.cbGdt)
5141 {
5142 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5143 HMR0DumpDescriptor(pDesc, u32Val, "DS: ");
5144 }
5145
5146 rc = VMXReadVmcs32(VMX_VMCS16_HOST_ES_SEL, &u32Val); AssertRC(rc);
5147 Log4(("Host ES %#08x\n", u32Val));
5148 if (u32Val < HostGdtr.cbGdt)
5149 {
5150 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5151 HMR0DumpDescriptor(pDesc, u32Val, "ES: ");
5152 }
5153
5154 rc = VMXReadVmcs32(VMX_VMCS16_HOST_FS_SEL, &u32Val); AssertRC(rc);
5155 Log4(("Host FS %#08x\n", u32Val));
5156 if (u32Val < HostGdtr.cbGdt)
5157 {
5158 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5159 HMR0DumpDescriptor(pDesc, u32Val, "FS: ");
5160 }
5161
5162 rc = VMXReadVmcs32(VMX_VMCS16_HOST_GS_SEL, &u32Val); AssertRC(rc);
5163 Log4(("Host GS %#08x\n", u32Val));
5164 if (u32Val < HostGdtr.cbGdt)
5165 {
5166 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5167 HMR0DumpDescriptor(pDesc, u32Val, "GS: ");
5168 }
5169
5170 rc = VMXReadVmcs32(VMX_VMCS16_HOST_SS_SEL, &u32Val); AssertRC(rc);
5171 Log4(("Host SS %#08x\n", u32Val));
5172 if (u32Val < HostGdtr.cbGdt)
5173 {
5174 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5175 HMR0DumpDescriptor(pDesc, u32Val, "SS: ");
5176 }
5177
5178 rc = VMXReadVmcs32(VMX_VMCS16_HOST_TR_SEL, &u32Val); AssertRC(rc);
5179 Log4(("Host TR %#08x\n", u32Val));
5180 if (u32Val < HostGdtr.cbGdt)
5181 {
5182 pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u32Val & X86_SEL_MASK));
5183 HMR0DumpDescriptor(pDesc, u32Val, "TR: ");
5184 }
5185
5186 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_TR_BASE, &uHCReg); AssertRC(rc);
5187 Log4(("Host TR Base %#RHv\n", uHCReg));
5188 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_GDTR_BASE, &uHCReg); AssertRC(rc);
5189 Log4(("Host GDTR Base %#RHv\n", uHCReg));
5190 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_IDTR_BASE, &uHCReg); AssertRC(rc);
5191 Log4(("Host IDTR Base %#RHv\n", uHCReg));
5192 rc = VMXReadVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, &u32Val); AssertRC(rc);
5193 Log4(("Host SYSENTER CS %#08x\n", u32Val));
5194 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_SYSENTER_EIP, &uHCReg); AssertRC(rc);
5195 Log4(("Host SYSENTER EIP %#RHv\n", uHCReg));
5196 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_SYSENTER_ESP, &uHCReg); AssertRC(rc);
5197 Log4(("Host SYSENTER ESP %#RHv\n", uHCReg));
5198 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_RSP, &uHCReg); AssertRC(rc);
5199 Log4(("Host RSP %#RHv\n", uHCReg));
5200 rc = VMXReadVmcsHstN(VMX_VMCS_HOST_RIP, &uHCReg); AssertRC(rc);
5201 Log4(("Host RIP %#RHv\n", uHCReg));
5202# if HC_ARCH_BITS == 64
5203 Log4(("MSR_K6_EFER = %#RX64\n", ASMRdMsr(MSR_K6_EFER)));
5204 Log4(("MSR_K8_CSTAR = %#RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
5205 Log4(("MSR_K8_LSTAR = %#RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
5206 Log4(("MSR_K6_STAR = %#RX64\n", ASMRdMsr(MSR_K6_STAR)));
5207 Log4(("MSR_K8_SF_MASK = %#RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
5208 Log4(("MSR_K8_KERNEL_GS_BASE = %#RX64\n", ASMRdMsr(MSR_K8_KERNEL_GS_BASE)));
5209# endif
5210#endif /* VBOX_STRICT */
5211 break;
5212 }
5213
5214 default:
5215 /* Impossible */
5216 AssertMsgFailed(("hmR0VmxReportWorldSwitchError %Rrc (%#x)\n", rcVMRun, rcVMRun));
5217 break;
5218 }
5219 NOREF(pVM); NOREF(pCtx);
5220}
5221
5222
5223#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
5224#ifndef VMX_USE_CACHED_VMCS_ACCESSES
5225# error "VMX_USE_CACHED_VMCS_ACCESSES not defined when it should be!"
5226#endif
5227#ifdef VBOX_STRICT
5228static bool hmR0VmxIsValidWriteField(uint32_t idxField)
5229{
5230 switch (idxField)
5231 {
5232 case VMX_VMCS_GUEST_RIP:
5233 case VMX_VMCS_GUEST_RSP:
5234 case VMX_VMCS_GUEST_SYSENTER_EIP:
5235 case VMX_VMCS_GUEST_SYSENTER_ESP:
5236 case VMX_VMCS_GUEST_GDTR_BASE:
5237 case VMX_VMCS_GUEST_IDTR_BASE:
5238 case VMX_VMCS_GUEST_CS_BASE:
5239 case VMX_VMCS_GUEST_DS_BASE:
5240 case VMX_VMCS_GUEST_ES_BASE:
5241 case VMX_VMCS_GUEST_FS_BASE:
5242 case VMX_VMCS_GUEST_GS_BASE:
5243 case VMX_VMCS_GUEST_SS_BASE:
5244 case VMX_VMCS_GUEST_LDTR_BASE:
5245 case VMX_VMCS_GUEST_TR_BASE:
5246 case VMX_VMCS_GUEST_CR3:
5247 return true;
5248 }
5249 return false;
5250}
5251
5252static bool hmR0VmxIsValidReadField(uint32_t idxField)
5253{
5254 switch (idxField)
5255 {
5256 /* Read-only fields. */
5257 case VMX_VMCS_RO_EXIT_QUALIFICATION:
5258 return true;
5259 }
5260 /* Remaining readable fields should also be writable. */
5261 return hmR0VmxIsValidWriteField(idxField);
5262}
5263#endif /* VBOX_STRICT */
5264
5265
5266/**
5267 * Executes the specified handler in 64-bit mode.
5268 *
5269 * @returns VBox status code (no informational status codes).
5270 * @param pVM The cross context VM structure.
5271 * @param pVCpu The cross context virtual CPU structure.
5272 * @param pCtx Pointer to the guest CPU context.
5273 * @param enmOp The operation to perform.
5274 * @param cParams Number of parameters.
5275 * @param paParam Array of 32-bit parameters.
5276 */
5277VMMR0DECL(int) VMXR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp,
5278 uint32_t cParams, uint32_t *paParam)
5279{
5280 NOREF(pCtx);
5281
5282 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
5283 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
5284 Assert(pVCpu->hm.s.vmx.VMCSCache.Write.cValidEntries <= RT_ELEMENTS(pVCpu->hm.s.vmx.VMCSCache.Write.aField));
5285 Assert(pVCpu->hm.s.vmx.VMCSCache.Read.cValidEntries <= RT_ELEMENTS(pVCpu->hm.s.vmx.VMCSCache.Read.aField));
5286
5287#ifdef VBOX_STRICT
5288 for (uint32_t i = 0; i < pVCpu->hm.s.vmx.VMCSCache.Write.cValidEntries; i++)
5289 Assert(hmR0VmxIsValidWriteField(pVCpu->hm.s.vmx.VMCSCache.Write.aField[i]));
5290
5291 for (uint32_t i = 0; i <pVCpu->hm.s.vmx.VMCSCache.Read.cValidEntries; i++)
5292 Assert(hmR0VmxIsValidReadField(pVCpu->hm.s.vmx.VMCSCache.Read.aField[i]));
5293#endif
5294
5295 /* Disable interrupts. */
5296 RTCCUINTREG fOldEFlags = ASMIntDisableFlags();
5297
5298#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
5299 RTCPUID idHostCpu = RTMpCpuId();
5300 CPUMR0SetLApic(pVCpu, idHostCpu);
5301#endif
5302
5303 PHMGLOBALCPUINFO pCpu = HMR0GetCurrentCpu();
5304 RTHCPHYS HCPhysCpuPage = pCpu->HCPhysMemObj;
5305
5306 /* Clear VMCS. Marking it inactive, clearing implementation-specific data and writing VMCS data back to memory. */
5307 VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
5308 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
5309
5310 /* Leave VMX Root Mode. */
5311 VMXDisable();
5312
5313 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
5314
5315 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
5316 CPUMSetHyperEIP(pVCpu, enmOp);
5317 for (int i = (int)cParams - 1; i >= 0; i--)
5318 CPUMPushHyper(pVCpu, paParam[i]);
5319
5320 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
5321
5322 /* Call the switcher. */
5323 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
5324 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
5325
5326 /** @todo replace with hmR0VmxEnterRootMode() and hmR0VmxLeaveRootMode(). */
5327 /* Make sure the VMX instructions don't cause #UD faults. */
5328 SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
5329
5330 /* Re-enter VMX Root Mode */
5331 int rc2 = VMXEnable(HCPhysCpuPage);
5332 if (RT_FAILURE(rc2))
5333 {
5334 SUPR0ChangeCR4(0, ~X86_CR4_VMXE);
5335 ASMSetFlags(fOldEFlags);
5336 pVM->hm.s.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
5337 return rc2;
5338 }
5339
5340 rc2 = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
5341 AssertRC(rc2);
5342 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_ACTIVE;
5343 Assert(!(ASMGetFlags() & X86_EFL_IF));
5344 ASMSetFlags(fOldEFlags);
5345 return rc;
5346}
5347
5348
5349/**
5350 * Prepares for and executes VMLAUNCH (64-bit guests) for 32-bit hosts
5351 * supporting 64-bit guests.
5352 *
5353 * @returns VBox status code.
5354 * @param fResume Whether to VMLAUNCH or VMRESUME.
5355 * @param pCtx Pointer to the guest-CPU context.
5356 * @param pCache Pointer to the VMCS cache.
5357 * @param pVM The cross context VM structure.
5358 * @param pVCpu The cross context virtual CPU structure.
5359 */
5360DECLASM(int) VMXR0SwitcherStartVM64(RTHCUINT fResume, PCPUMCTX pCtx, PVMCSCACHE pCache, PVM pVM, PVMCPU pVCpu)
5361{
5362 NOREF(fResume);
5363
5364 PHMGLOBALCPUINFO pCpu = HMR0GetCurrentCpu();
5365 RTHCPHYS HCPhysCpuPage = pCpu->HCPhysMemObj;
5366
5367#ifdef VBOX_WITH_CRASHDUMP_MAGIC
5368 pCache->uPos = 1;
5369 pCache->interPD = PGMGetInterPaeCR3(pVM);
5370 pCache->pSwitcher = (uint64_t)pVM->hm.s.pfnHost32ToGuest64R0;
5371#endif
5372
5373#if defined(DEBUG) && defined(VMX_USE_CACHED_VMCS_ACCESSES)
5374 pCache->TestIn.HCPhysCpuPage = 0;
5375 pCache->TestIn.HCPhysVmcs = 0;
5376 pCache->TestIn.pCache = 0;
5377 pCache->TestOut.HCPhysVmcs = 0;
5378 pCache->TestOut.pCache = 0;
5379 pCache->TestOut.pCtx = 0;
5380 pCache->TestOut.eflags = 0;
5381#else
5382 NOREF(pCache);
5383#endif
5384
5385 uint32_t aParam[10];
5386 aParam[0] = (uint32_t)(HCPhysCpuPage); /* Param 1: VMXON physical address - Lo. */
5387 aParam[1] = (uint32_t)(HCPhysCpuPage >> 32); /* Param 1: VMXON physical address - Hi. */
5388 aParam[2] = (uint32_t)(pVCpu->hm.s.vmx.HCPhysVmcs); /* Param 2: VMCS physical address - Lo. */
5389 aParam[3] = (uint32_t)(pVCpu->hm.s.vmx.HCPhysVmcs >> 32); /* Param 2: VMCS physical address - Hi. */
5390 aParam[4] = VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hm.s.vmx.VMCSCache);
5391 aParam[5] = 0;
5392 aParam[6] = VM_RC_ADDR(pVM, pVM);
5393 aParam[7] = 0;
5394 aParam[8] = VM_RC_ADDR(pVM, pVCpu);
5395 aParam[9] = 0;
5396
5397#ifdef VBOX_WITH_CRASHDUMP_MAGIC
5398 pCtx->dr[4] = pVM->hm.s.vmx.pScratchPhys + 16 + 8;
5399 *(uint32_t *)(pVM->hm.s.vmx.pScratch + 16 + 8) = 1;
5400#endif
5401 int rc = VMXR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_VMXRCStartVM64, RT_ELEMENTS(aParam), &aParam[0]);
5402
5403#ifdef VBOX_WITH_CRASHDUMP_MAGIC
5404 Assert(*(uint32_t *)(pVM->hm.s.vmx.pScratch + 16 + 8) == 5);
5405 Assert(pCtx->dr[4] == 10);
5406 *(uint32_t *)(pVM->hm.s.vmx.pScratch + 16 + 8) = 0xff;
5407#endif
5408
5409#if defined(DEBUG) && defined(VMX_USE_CACHED_VMCS_ACCESSES)
5410 AssertMsg(pCache->TestIn.HCPhysCpuPage == HCPhysCpuPage, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysCpuPage, HCPhysCpuPage));
5411 AssertMsg(pCache->TestIn.HCPhysVmcs == pVCpu->hm.s.vmx.HCPhysVmcs, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysVmcs,
5412 pVCpu->hm.s.vmx.HCPhysVmcs));
5413 AssertMsg(pCache->TestIn.HCPhysVmcs == pCache->TestOut.HCPhysVmcs, ("%RHp vs %RHp\n", pCache->TestIn.HCPhysVmcs,
5414 pCache->TestOut.HCPhysVmcs));
5415 AssertMsg(pCache->TestIn.pCache == pCache->TestOut.pCache, ("%RGv vs %RGv\n", pCache->TestIn.pCache,
5416 pCache->TestOut.pCache));
5417 AssertMsg(pCache->TestIn.pCache == VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hm.s.vmx.VMCSCache),
5418 ("%RGv vs %RGv\n", pCache->TestIn.pCache, VM_RC_ADDR(pVM, &pVM->aCpus[pVCpu->idCpu].hm.s.vmx.VMCSCache)));
5419 AssertMsg(pCache->TestIn.pCtx == pCache->TestOut.pCtx, ("%RGv vs %RGv\n", pCache->TestIn.pCtx,
5420 pCache->TestOut.pCtx));
5421 Assert(!(pCache->TestOut.eflags & X86_EFL_IF));
5422#endif
5423 return rc;
5424}
5425
5426
5427/**
5428 * Initialize the VMCS-Read cache.
5429 *
5430 * The VMCS cache is used for 32-bit hosts running 64-bit guests (except 32-bit
5431 * Darwin which runs with 64-bit paging in 32-bit mode) for 64-bit fields that
5432 * cannot be accessed in 32-bit mode. Some 64-bit fields -can- be accessed
5433 * (those that have a 32-bit FULL & HIGH part).
5434 *
5435 * @returns VBox status code.
5436 * @param pVM The cross context VM structure.
5437 * @param pVCpu The cross context virtual CPU structure.
5438 */
5439static int hmR0VmxInitVmcsReadCache(PVM pVM, PVMCPU pVCpu)
5440{
5441#define VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, idxField) \
5442{ \
5443 Assert(pCache->Read.aField[idxField##_CACHE_IDX] == 0); \
5444 pCache->Read.aField[idxField##_CACHE_IDX] = idxField; \
5445 pCache->Read.aFieldVal[idxField##_CACHE_IDX] = 0; \
5446 ++cReadFields; \
5447}
5448
5449 AssertPtr(pVM);
5450 AssertPtr(pVCpu);
5451 PVMCSCACHE pCache = &pVCpu->hm.s.vmx.VMCSCache;
5452 uint32_t cReadFields = 0;
5453
5454 /*
5455 * Don't remove the #if 0'd fields in this code. They're listed here for consistency
5456 * and serve to indicate exceptions to the rules.
5457 */
5458
5459 /* Guest-natural selector base fields. */
5460#if 0
5461 /* These are 32-bit in practice. See Intel spec. 2.5 "Control Registers". */
5462 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR0);
5463 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR4);
5464#endif
5465 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_ES_BASE);
5466 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CS_BASE);
5467 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_SS_BASE);
5468 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_DS_BASE);
5469 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_FS_BASE);
5470 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_GS_BASE);
5471 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_LDTR_BASE);
5472 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_TR_BASE);
5473 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_GDTR_BASE);
5474 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_IDTR_BASE);
5475 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_RSP);
5476 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_RIP);
5477#if 0
5478 /* Unused natural width guest-state fields. */
5479 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS);
5480 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR3); /* Handled in Nested Paging case */
5481#endif
5482 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_SYSENTER_ESP);
5483 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_SYSENTER_EIP);
5484
5485 /* 64-bit guest-state fields; unused as we use two 32-bit VMREADs for these 64-bit fields (using "FULL" and "HIGH" fields). */
5486#if 0
5487 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL);
5488 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_DEBUGCTL_FULL);
5489 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PAT_FULL);
5490 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_EFER_FULL);
5491 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL);
5492 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE0_FULL);
5493 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE1_FULL);
5494 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE2_FULL);
5495 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS64_GUEST_PDPTE3_FULL);
5496#endif
5497
5498 /* Natural width guest-state fields. */
5499 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_RO_EXIT_QUALIFICATION);
5500#if 0
5501 /* Currently unused field. */
5502 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_RO_EXIT_GUEST_LINEAR_ADDR);
5503#endif
5504
5505 if (pVM->hm.s.fNestedPaging)
5506 {
5507 VMXLOCAL_INIT_READ_CACHE_FIELD(pCache, VMX_VMCS_GUEST_CR3);
5508 AssertMsg(cReadFields == VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX, ("cReadFields=%u expected %u\n", cReadFields,
5509 VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX));
5510 pCache->Read.cValidEntries = VMX_VMCS_MAX_NESTED_PAGING_CACHE_IDX;
5511 }
5512 else
5513 {
5514 AssertMsg(cReadFields == VMX_VMCS_MAX_CACHE_IDX, ("cReadFields=%u expected %u\n", cReadFields, VMX_VMCS_MAX_CACHE_IDX));
5515 pCache->Read.cValidEntries = VMX_VMCS_MAX_CACHE_IDX;
5516 }
5517
5518#undef VMXLOCAL_INIT_READ_CACHE_FIELD
5519 return VINF_SUCCESS;
5520}
5521
5522
5523/**
5524 * Writes a field into the VMCS. This can either directly invoke a VMWRITE or
5525 * queue up the VMWRITE by using the VMCS write cache (on 32-bit hosts, except
5526 * darwin, running 64-bit guests).
5527 *
5528 * @returns VBox status code.
5529 * @param pVCpu The cross context virtual CPU structure.
5530 * @param idxField The VMCS field encoding.
5531 * @param u64Val 16, 32 or 64-bit value.
5532 */
5533VMMR0DECL(int) VMXWriteVmcs64Ex(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
5534{
5535 int rc;
5536 switch (idxField)
5537 {
5538 /*
5539 * These fields consists of a "FULL" and a "HIGH" part which can be written to individually.
5540 */
5541 /* 64-bit Control fields. */
5542 case VMX_VMCS64_CTRL_IO_BITMAP_A_FULL:
5543 case VMX_VMCS64_CTRL_IO_BITMAP_B_FULL:
5544 case VMX_VMCS64_CTRL_MSR_BITMAP_FULL:
5545 case VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL:
5546 case VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL:
5547 case VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL:
5548 case VMX_VMCS64_CTRL_EXEC_VMCS_PTR_FULL:
5549 case VMX_VMCS64_CTRL_TSC_OFFSET_FULL:
5550 case VMX_VMCS64_CTRL_VAPIC_PAGEADDR_FULL:
5551 case VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL:
5552 case VMX_VMCS64_CTRL_VMFUNC_CTRLS_FULL:
5553 case VMX_VMCS64_CTRL_EPTP_FULL:
5554 case VMX_VMCS64_CTRL_EPTP_LIST_FULL:
5555 /* 64-bit Guest-state fields. */
5556 case VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL:
5557 case VMX_VMCS64_GUEST_DEBUGCTL_FULL:
5558 case VMX_VMCS64_GUEST_PAT_FULL:
5559 case VMX_VMCS64_GUEST_EFER_FULL:
5560 case VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL:
5561 case VMX_VMCS64_GUEST_PDPTE0_FULL:
5562 case VMX_VMCS64_GUEST_PDPTE1_FULL:
5563 case VMX_VMCS64_GUEST_PDPTE2_FULL:
5564 case VMX_VMCS64_GUEST_PDPTE3_FULL:
5565 /* 64-bit Host-state fields. */
5566 case VMX_VMCS64_HOST_PAT_FULL:
5567 case VMX_VMCS64_HOST_EFER_FULL:
5568 case VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_FULL:
5569 {
5570 rc = VMXWriteVmcs32(idxField, u64Val);
5571 rc |= VMXWriteVmcs32(idxField + 1, (uint32_t)(u64Val >> 32));
5572 break;
5573 }
5574
5575 /*
5576 * These fields do not have high and low parts. Queue up the VMWRITE by using the VMCS write-cache (for 64-bit
5577 * values). When we switch the host to 64-bit mode for running 64-bit guests, these VMWRITEs get executed then.
5578 */
5579 /* Natural-width Guest-state fields. */
5580 case VMX_VMCS_GUEST_CR3:
5581 case VMX_VMCS_GUEST_ES_BASE:
5582 case VMX_VMCS_GUEST_CS_BASE:
5583 case VMX_VMCS_GUEST_SS_BASE:
5584 case VMX_VMCS_GUEST_DS_BASE:
5585 case VMX_VMCS_GUEST_FS_BASE:
5586 case VMX_VMCS_GUEST_GS_BASE:
5587 case VMX_VMCS_GUEST_LDTR_BASE:
5588 case VMX_VMCS_GUEST_TR_BASE:
5589 case VMX_VMCS_GUEST_GDTR_BASE:
5590 case VMX_VMCS_GUEST_IDTR_BASE:
5591 case VMX_VMCS_GUEST_RSP:
5592 case VMX_VMCS_GUEST_RIP:
5593 case VMX_VMCS_GUEST_SYSENTER_ESP:
5594 case VMX_VMCS_GUEST_SYSENTER_EIP:
5595 {
5596 if (!(u64Val >> 32))
5597 {
5598 /* If this field is 64-bit, VT-x will zero out the top bits. */
5599 rc = VMXWriteVmcs32(idxField, (uint32_t)u64Val);
5600 }
5601 else
5602 {
5603 /* Assert that only the 32->64 switcher case should ever come here. */
5604 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests);
5605 rc = VMXWriteCachedVmcsEx(pVCpu, idxField, u64Val);
5606 }
5607 break;
5608 }
5609
5610 default:
5611 {
5612 AssertMsgFailed(("VMXWriteVmcs64Ex: Invalid field %#RX32 (pVCpu=%p u64Val=%#RX64)\n", idxField, pVCpu, u64Val));
5613 rc = VERR_INVALID_PARAMETER;
5614 break;
5615 }
5616 }
5617 AssertRCReturn(rc, rc);
5618 return rc;
5619}
5620
5621
5622/**
5623 * Queue up a VMWRITE by using the VMCS write cache.
5624 * This is only used on 32-bit hosts (except darwin) for 64-bit guests.
5625 *
5626 * @param pVCpu The cross context virtual CPU structure.
5627 * @param idxField The VMCS field encoding.
5628 * @param u64Val 16, 32 or 64-bit value.
5629 */
5630VMMR0DECL(int) VMXWriteCachedVmcsEx(PVMCPU pVCpu, uint32_t idxField, uint64_t u64Val)
5631{
5632 AssertPtr(pVCpu);
5633 PVMCSCACHE pCache = &pVCpu->hm.s.vmx.VMCSCache;
5634
5635 AssertMsgReturn(pCache->Write.cValidEntries < VMCSCACHE_MAX_ENTRY - 1,
5636 ("entries=%u\n", pCache->Write.cValidEntries), VERR_ACCESS_DENIED);
5637
5638 /* Make sure there are no duplicates. */
5639 for (uint32_t i = 0; i < pCache->Write.cValidEntries; i++)
5640 {
5641 if (pCache->Write.aField[i] == idxField)
5642 {
5643 pCache->Write.aFieldVal[i] = u64Val;
5644 return VINF_SUCCESS;
5645 }
5646 }
5647
5648 pCache->Write.aField[pCache->Write.cValidEntries] = idxField;
5649 pCache->Write.aFieldVal[pCache->Write.cValidEntries] = u64Val;
5650 pCache->Write.cValidEntries++;
5651 return VINF_SUCCESS;
5652}
5653#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
5654
5655
5656/**
5657 * Sets up the usage of TSC-offsetting and updates the VMCS.
5658 *
5659 * If offsetting is not possible, cause VM-exits on RDTSC(P)s. Also sets up the
5660 * VMX preemption timer.
5661 *
5662 * @returns VBox status code.
5663 * @param pVM The cross context VM structure.
5664 * @param pVCpu The cross context virtual CPU structure.
5665 *
5666 * @remarks No-long-jump zone!!!
5667 */
5668static void hmR0VmxUpdateTscOffsettingAndPreemptTimer(PVM pVM, PVMCPU pVCpu)
5669{
5670 int rc;
5671 bool fOffsettedTsc;
5672 bool fParavirtTsc;
5673 if (pVM->hm.s.vmx.fUsePreemptTimer)
5674 {
5675 uint64_t cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVM, pVCpu, &pVCpu->hm.s.vmx.u64TSCOffset,
5676 &fOffsettedTsc, &fParavirtTsc);
5677
5678 /* Make sure the returned values have sane upper and lower boundaries. */
5679 uint64_t u64CpuHz = SUPGetCpuHzFromGipBySetIndex(g_pSUPGlobalInfoPage, pVCpu->iHostCpuSet);
5680 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64th of a second */
5681 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 2048); /* 1/2048th of a second */
5682 cTicksToDeadline >>= pVM->hm.s.vmx.cPreemptTimerShift;
5683
5684 uint32_t cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
5685 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_PREEMPT_TIMER_VALUE, cPreemptionTickCount); AssertRC(rc);
5686 }
5687 else
5688 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &pVCpu->hm.s.vmx.u64TSCOffset, &fParavirtTsc);
5689
5690 /** @todo later optimize this to be done elsewhere and not before every
5691 * VM-entry. */
5692 if (fParavirtTsc)
5693 {
5694 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
5695 information before every VM-entry, hence disable it for performance sake. */
5696#if 0
5697 rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
5698 AssertRC(rc);
5699#endif
5700 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
5701 }
5702
5703 if (fOffsettedTsc && RT_LIKELY(!pVCpu->hm.s.fDebugWantRdTscExit))
5704 {
5705 /* Note: VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT takes precedence over TSC_OFFSET, applies to RDTSCP too. */
5706 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, pVCpu->hm.s.vmx.u64TSCOffset); AssertRC(rc);
5707
5708 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT;
5709 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls); AssertRC(rc);
5710 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
5711 }
5712 else
5713 {
5714 /* We can't use TSC-offsetting (non-fixed TSC, warp drive active etc.), VM-exit on RDTSC(P). */
5715 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT;
5716 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls); AssertRC(rc);
5717 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
5718 }
5719}
5720
5721
5722/**
5723 * Determines if an exception is a contributory exception.
5724 *
5725 * Contributory exceptions are ones which can cause double-faults unless the
5726 * original exception was a benign exception. Page-fault is intentionally not
5727 * included here as it's a conditional contributory exception.
5728 *
5729 * @returns true if the exception is contributory, false otherwise.
5730 * @param uVector The exception vector.
5731 */
5732DECLINLINE(bool) hmR0VmxIsContributoryXcpt(const uint32_t uVector)
5733{
5734 switch (uVector)
5735 {
5736 case X86_XCPT_GP:
5737 case X86_XCPT_SS:
5738 case X86_XCPT_NP:
5739 case X86_XCPT_TS:
5740 case X86_XCPT_DE:
5741 return true;
5742 default:
5743 break;
5744 }
5745 return false;
5746}
5747
5748
5749/**
5750 * Sets an event as a pending event to be injected into the guest.
5751 *
5752 * @param pVCpu The cross context virtual CPU structure.
5753 * @param u32IntInfo The VM-entry interruption-information field.
5754 * @param cbInstr The VM-entry instruction length in bytes (for software
5755 * interrupts, exceptions and privileged software
5756 * exceptions).
5757 * @param u32ErrCode The VM-entry exception error code.
5758 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
5759 * page-fault.
5760 *
5761 * @remarks Statistics counter assumes this is a guest event being injected or
5762 * re-injected into the guest, i.e. 'StatInjectPendingReflect' is
5763 * always incremented.
5764 */
5765DECLINLINE(void) hmR0VmxSetPendingEvent(PVMCPU pVCpu, uint32_t u32IntInfo, uint32_t cbInstr, uint32_t u32ErrCode,
5766 RTGCUINTPTR GCPtrFaultAddress)
5767{
5768 Assert(!pVCpu->hm.s.Event.fPending);
5769 pVCpu->hm.s.Event.fPending = true;
5770 pVCpu->hm.s.Event.u64IntInfo = u32IntInfo;
5771 pVCpu->hm.s.Event.u32ErrCode = u32ErrCode;
5772 pVCpu->hm.s.Event.cbInstr = cbInstr;
5773 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
5774}
5775
5776
5777/**
5778 * Sets a double-fault (\#DF) exception as pending-for-injection into the VM.
5779 *
5780 * @param pVCpu The cross context virtual CPU structure.
5781 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
5782 * out-of-sync. Make sure to update the required fields
5783 * before using them.
5784 */
5785DECLINLINE(void) hmR0VmxSetPendingXcptDF(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
5786{
5787 NOREF(pMixedCtx);
5788 uint32_t u32IntInfo = X86_XCPT_DF | VMX_EXIT_INTERRUPTION_INFO_VALID;
5789 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
5790 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
5791 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
5792}
5793
5794
5795/**
5796 * Handle a condition that occurred while delivering an event through the guest
5797 * IDT.
5798 *
5799 * @returns Strict VBox status code (i.e. informational status codes too).
5800 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
5801 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
5802 * to continue execution of the guest which will delivery the \#DF.
5803 * @retval VINF_EM_RESET if we detected a triple-fault condition.
5804 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
5805 *
5806 * @param pVCpu The cross context virtual CPU structure.
5807 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
5808 * out-of-sync. Make sure to update the required fields
5809 * before using them.
5810 * @param pVmxTransient Pointer to the VMX transient structure.
5811 *
5812 * @remarks No-long-jump zone!!!
5813 */
5814static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
5815{
5816 uint32_t uExitVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo);
5817
5818 int rc2 = hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient); AssertRCReturn(rc2, rc2);
5819 rc2 = hmR0VmxReadExitIntInfoVmcs(pVmxTransient); AssertRCReturn(rc2, rc2);
5820
5821 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
5822 if (VMX_IDT_VECTORING_INFO_VALID(pVmxTransient->uIdtVectoringInfo))
5823 {
5824 uint32_t uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo);
5825 uint32_t uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo);
5826
5827 typedef enum
5828 {
5829 VMXREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
5830 VMXREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
5831 VMXREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
5832 VMXREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
5833 VMXREFLECTXCPT_NONE /* Nothing to reflect. */
5834 } VMXREFLECTXCPT;
5835
5836 /* See Intel spec. 30.7.1.1 "Reflecting Exceptions to Guest Software". */
5837 VMXREFLECTXCPT enmReflect = VMXREFLECTXCPT_NONE;
5838 if (VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo))
5839 {
5840 if (uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT)
5841 {
5842 enmReflect = VMXREFLECTXCPT_XCPT;
5843#ifdef VBOX_STRICT
5844 if ( hmR0VmxIsContributoryXcpt(uIdtVector)
5845 && uExitVector == X86_XCPT_PF)
5846 {
5847 Log4(("IDT: vcpu[%RU32] Contributory #PF uCR2=%#RX64\n", pVCpu->idCpu, pMixedCtx->cr2));
5848 }
5849#endif
5850 if ( uExitVector == X86_XCPT_PF
5851 && uIdtVector == X86_XCPT_PF)
5852 {
5853 pVmxTransient->fVectoringDoublePF = true;
5854 Log4(("IDT: vcpu[%RU32] Vectoring Double #PF uCR2=%#RX64\n", pVCpu->idCpu, pMixedCtx->cr2));
5855 }
5856 else if ( uExitVector == X86_XCPT_AC
5857 && uIdtVector == X86_XCPT_AC)
5858 {
5859 enmReflect = VMXREFLECTXCPT_HANG;
5860 Log4(("IDT: Nested #AC - Bad guest\n"));
5861 }
5862 else if ( (pVCpu->hm.s.vmx.u32XcptBitmap & HMVMX_CONTRIBUTORY_XCPT_MASK)
5863 && hmR0VmxIsContributoryXcpt(uExitVector)
5864 && ( hmR0VmxIsContributoryXcpt(uIdtVector)
5865 || uIdtVector == X86_XCPT_PF))
5866 {
5867 enmReflect = VMXREFLECTXCPT_DF;
5868 }
5869 else if (uIdtVector == X86_XCPT_DF)
5870 enmReflect = VMXREFLECTXCPT_TF;
5871 }
5872 else if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT
5873 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI)
5874 {
5875 /*
5876 * Ignore software interrupts (INT n), software exceptions (#BP, #OF) and
5877 * privileged software exception (#DB from ICEBP) as they reoccur when restarting the instruction.
5878 */
5879 enmReflect = VMXREFLECTXCPT_XCPT;
5880
5881 if (uExitVector == X86_XCPT_PF)
5882 {
5883 pVmxTransient->fVectoringPF = true;
5884 Log4(("IDT: vcpu[%RU32] Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pVCpu->idCpu, pMixedCtx->cr2));
5885 }
5886 }
5887 }
5888 else if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
5889 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT
5890 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI)
5891 {
5892 /*
5893 * If event delivery caused an EPT violation/misconfig or APIC access VM-exit, then the VM-exit
5894 * interruption-information will not be valid as it's not an exception and we end up here. In such cases,
5895 * it is sufficient to reflect the original exception to the guest after handling the VM-exit.
5896 */
5897 enmReflect = VMXREFLECTXCPT_XCPT;
5898 }
5899
5900 /*
5901 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig etc.) occurred
5902 * while delivering the NMI, we need to clear the block-by-NMI field in the guest interruptibility-state before
5903 * re-delivering the NMI after handling the VM-exit. Otherwise the subsequent VM-entry would fail.
5904 *
5905 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception". See @bugref{7445}.
5906 */
5907 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
5908 && enmReflect == VMXREFLECTXCPT_XCPT
5909 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI)
5910 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
5911 {
5912 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5913 }
5914
5915 switch (enmReflect)
5916 {
5917 case VMXREFLECTXCPT_XCPT:
5918 {
5919 Assert( uIdtVectorType != VMX_IDT_VECTORING_INFO_TYPE_SW_INT
5920 && uIdtVectorType != VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
5921 && uIdtVectorType != VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT);
5922
5923 uint32_t u32ErrCode = 0;
5924 if (VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uIdtVectoringInfo))
5925 {
5926 rc2 = hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
5927 AssertRCReturn(rc2, rc2);
5928 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
5929 }
5930
5931 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF. See hmR0VmxExitXcptPF(). */
5932 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
5933 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
5934 0 /* cbInstr */, u32ErrCode, pMixedCtx->cr2);
5935 rcStrict = VINF_SUCCESS;
5936 Log4(("IDT: vcpu[%RU32] Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->idCpu,
5937 pVCpu->hm.s.Event.u64IntInfo, pVCpu->hm.s.Event.u32ErrCode));
5938
5939 break;
5940 }
5941
5942 case VMXREFLECTXCPT_DF:
5943 {
5944 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
5945 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
5946 rcStrict = VINF_HM_DOUBLE_FAULT;
5947 Log4(("IDT: vcpu[%RU32] Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->idCpu,
5948 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
5949
5950 break;
5951 }
5952
5953 case VMXREFLECTXCPT_TF:
5954 {
5955 rcStrict = VINF_EM_RESET;
5956 Log4(("IDT: vcpu[%RU32] Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", pVCpu->idCpu, uIdtVector,
5957 uExitVector));
5958 break;
5959 }
5960
5961 case VMXREFLECTXCPT_HANG:
5962 {
5963 rcStrict = VERR_EM_GUEST_CPU_HANG;
5964 break;
5965 }
5966
5967 default:
5968 Assert(rcStrict == VINF_SUCCESS);
5969 break;
5970 }
5971 }
5972 else if ( VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo)
5973 && VMX_EXIT_INTERRUPTION_INFO_NMI_UNBLOCK_IRET(pVmxTransient->uExitIntInfo)
5974 && uExitVector != X86_XCPT_DF
5975 && (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI))
5976 {
5977 /*
5978 * Execution of IRET caused this fault when NMI blocking was in effect (i.e we're in the guest NMI handler).
5979 * We need to set the block-by-NMI field so that NMIs remain blocked until the IRET execution is restarted.
5980 * See Intel spec. 30.7.1.2 "Resuming guest software after handling an exception".
5981 */
5982 if (!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
5983 {
5984 Log4(("hmR0VmxCheckExitDueToEventDelivery: vcpu[%RU32] Setting VMCPU_FF_BLOCK_NMIS. Valid=%RTbool uExitReason=%u\n",
5985 pVCpu->idCpu, VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo), pVmxTransient->uExitReason));
5986 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
5987 }
5988 }
5989
5990 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
5991 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
5992 return rcStrict;
5993}
5994
5995
5996/**
5997 * Saves the guest's CR0 register from the VMCS into the guest-CPU context.
5998 *
5999 * @returns VBox status code.
6000 * @param pVCpu The cross context virtual CPU structure.
6001 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6002 * out-of-sync. Make sure to update the required fields
6003 * before using them.
6004 *
6005 * @remarks No-long-jump zone!!!
6006 */
6007static int hmR0VmxSaveGuestCR0(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6008{
6009 NOREF(pMixedCtx);
6010
6011 /*
6012 * While in the middle of saving guest-CR0, we could get preempted and re-invoked from the preemption hook,
6013 * see hmR0VmxLeave(). Safer to just make this code non-preemptible.
6014 */
6015 VMMRZCallRing3Disable(pVCpu);
6016 HM_DISABLE_PREEMPT();
6017
6018 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0))
6019 {
6020 uint32_t uVal = 0;
6021 uint32_t uShadow = 0;
6022 int rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR0, &uVal);
6023 rc |= VMXReadVmcs32(VMX_VMCS_CTRL_CR0_READ_SHADOW, &uShadow);
6024 AssertRCReturn(rc, rc);
6025
6026 uVal = (uShadow & pVCpu->hm.s.vmx.u32CR0Mask) | (uVal & ~pVCpu->hm.s.vmx.u32CR0Mask);
6027 CPUMSetGuestCR0(pVCpu, uVal);
6028 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0);
6029 }
6030
6031 HM_RESTORE_PREEMPT();
6032 VMMRZCallRing3Enable(pVCpu);
6033 return VINF_SUCCESS;
6034}
6035
6036
6037/**
6038 * Saves the guest's CR4 register from the VMCS into the guest-CPU context.
6039 *
6040 * @returns VBox status code.
6041 * @param pVCpu The cross context virtual CPU structure.
6042 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6043 * out-of-sync. Make sure to update the required fields
6044 * before using them.
6045 *
6046 * @remarks No-long-jump zone!!!
6047 */
6048static int hmR0VmxSaveGuestCR4(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6049{
6050 NOREF(pMixedCtx);
6051
6052 int rc = VINF_SUCCESS;
6053 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR4))
6054 {
6055 uint32_t uVal = 0;
6056 uint32_t uShadow = 0;
6057 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR4, &uVal);
6058 rc |= VMXReadVmcs32(VMX_VMCS_CTRL_CR4_READ_SHADOW, &uShadow);
6059 AssertRCReturn(rc, rc);
6060
6061 uVal = (uShadow & pVCpu->hm.s.vmx.u32CR4Mask) | (uVal & ~pVCpu->hm.s.vmx.u32CR4Mask);
6062 CPUMSetGuestCR4(pVCpu, uVal);
6063 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR4);
6064 }
6065 return rc;
6066}
6067
6068
6069/**
6070 * Saves the guest's RIP register from the VMCS into the guest-CPU context.
6071 *
6072 * @returns VBox status code.
6073 * @param pVCpu The cross context virtual CPU structure.
6074 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6075 * out-of-sync. Make sure to update the required fields
6076 * before using them.
6077 *
6078 * @remarks No-long-jump zone!!!
6079 */
6080static int hmR0VmxSaveGuestRip(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6081{
6082 int rc = VINF_SUCCESS;
6083 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RIP))
6084 {
6085 uint64_t u64Val = 0;
6086 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RIP, &u64Val);
6087 AssertRCReturn(rc, rc);
6088
6089 pMixedCtx->rip = u64Val;
6090 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RIP);
6091 }
6092 return rc;
6093}
6094
6095
6096/**
6097 * Saves the guest's RSP register from the VMCS into the guest-CPU context.
6098 *
6099 * @returns VBox status code.
6100 * @param pVCpu The cross context virtual CPU structure.
6101 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6102 * out-of-sync. Make sure to update the required fields
6103 * before using them.
6104 *
6105 * @remarks No-long-jump zone!!!
6106 */
6107static int hmR0VmxSaveGuestRsp(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6108{
6109 int rc = VINF_SUCCESS;
6110 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RSP))
6111 {
6112 uint64_t u64Val = 0;
6113 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_RSP, &u64Val);
6114 AssertRCReturn(rc, rc);
6115
6116 pMixedCtx->rsp = u64Val;
6117 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RSP);
6118 }
6119 return rc;
6120}
6121
6122
6123/**
6124 * Saves the guest's RFLAGS from the VMCS into the guest-CPU context.
6125 *
6126 * @returns VBox status code.
6127 * @param pVCpu The cross context virtual CPU structure.
6128 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6129 * out-of-sync. Make sure to update the required fields
6130 * before using them.
6131 *
6132 * @remarks No-long-jump zone!!!
6133 */
6134static int hmR0VmxSaveGuestRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6135{
6136 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS))
6137 {
6138 uint32_t uVal = 0;
6139 int rc = VMXReadVmcs32(VMX_VMCS_GUEST_RFLAGS, &uVal);
6140 AssertRCReturn(rc, rc);
6141
6142 pMixedCtx->eflags.u32 = uVal;
6143 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active) /* Undo our real-on-v86-mode changes to eflags if necessary. */
6144 {
6145 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
6146 Log4(("Saving real-mode EFLAGS VT-x view=%#RX32\n", pMixedCtx->eflags.u32));
6147
6148 pMixedCtx->eflags.Bits.u1VM = 0;
6149 pMixedCtx->eflags.Bits.u2IOPL = pVCpu->hm.s.vmx.RealMode.Eflags.Bits.u2IOPL;
6150 }
6151
6152 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS);
6153 }
6154 return VINF_SUCCESS;
6155}
6156
6157
6158/**
6159 * Wrapper for saving the guest's RIP, RSP and RFLAGS from the VMCS into the
6160 * guest-CPU context.
6161 */
6162DECLINLINE(int) hmR0VmxSaveGuestRipRspRflags(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6163{
6164 int rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
6165 rc |= hmR0VmxSaveGuestRsp(pVCpu, pMixedCtx);
6166 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
6167 return rc;
6168}
6169
6170
6171/**
6172 * Saves the guest's interruptibility-state ("interrupt shadow" as AMD calls it)
6173 * from the guest-state area in the VMCS.
6174 *
6175 * @param pVCpu The cross context virtual CPU structure.
6176 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6177 * out-of-sync. Make sure to update the required fields
6178 * before using them.
6179 *
6180 * @remarks No-long-jump zone!!!
6181 */
6182static void hmR0VmxSaveGuestIntrState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6183{
6184 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_INTR_STATE))
6185 {
6186 uint32_t uIntrState = 0;
6187 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &uIntrState);
6188 AssertRC(rc);
6189
6190 if (!uIntrState)
6191 {
6192 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
6193 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
6194
6195 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6196 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6197 }
6198 else
6199 {
6200 if (uIntrState & ( VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS
6201 | VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI))
6202 {
6203 rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
6204 AssertRC(rc);
6205 rc = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx); /* for hmR0VmxGetGuestIntrState(). */
6206 AssertRC(rc);
6207
6208 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
6209 Assert(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
6210 }
6211 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
6212 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
6213
6214 if (uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI)
6215 {
6216 if (!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6217 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
6218 }
6219 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
6220 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
6221 }
6222
6223 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_INTR_STATE);
6224 }
6225}
6226
6227
6228/**
6229 * Saves the guest's activity state.
6230 *
6231 * @returns VBox status code.
6232 * @param pVCpu The cross context virtual CPU structure.
6233 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6234 * out-of-sync. Make sure to update the required fields
6235 * before using them.
6236 *
6237 * @remarks No-long-jump zone!!!
6238 */
6239static int hmR0VmxSaveGuestActivityState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6240{
6241 NOREF(pMixedCtx);
6242 /* Nothing to do for now until we make use of different guest-CPU activity state. Just update the flag. */
6243 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_ACTIVITY_STATE);
6244 return VINF_SUCCESS;
6245}
6246
6247
6248/**
6249 * Saves the guest SYSENTER MSRs (SYSENTER_CS, SYSENTER_EIP, SYSENTER_ESP) from
6250 * the current VMCS into the guest-CPU context.
6251 *
6252 * @returns VBox status code.
6253 * @param pVCpu The cross context virtual CPU structure.
6254 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6255 * out-of-sync. Make sure to update the required fields
6256 * before using them.
6257 *
6258 * @remarks No-long-jump zone!!!
6259 */
6260static int hmR0VmxSaveGuestSysenterMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6261{
6262 int rc = VINF_SUCCESS;
6263 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR))
6264 {
6265 uint32_t u32Val = 0;
6266 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, &u32Val); AssertRCReturn(rc, rc);
6267 pMixedCtx->SysEnter.cs = u32Val;
6268 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_CS_MSR);
6269 }
6270
6271 uint64_t u64Val = 0;
6272 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR))
6273 {
6274 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_SYSENTER_EIP, &u64Val); AssertRCReturn(rc, rc);
6275 pMixedCtx->SysEnter.eip = u64Val;
6276 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_EIP_MSR);
6277 }
6278 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR))
6279 {
6280 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_SYSENTER_ESP, &u64Val); AssertRCReturn(rc, rc);
6281 pMixedCtx->SysEnter.esp = u64Val;
6282 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SYSENTER_ESP_MSR);
6283 }
6284 return rc;
6285}
6286
6287
6288/**
6289 * Saves the set of guest MSRs (that we restore lazily while leaving VT-x) from
6290 * the CPU back into the guest-CPU context.
6291 *
6292 * @returns VBox status code.
6293 * @param pVCpu The cross context virtual CPU structure.
6294 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6295 * out-of-sync. Make sure to update the required fields
6296 * before using them.
6297 *
6298 * @remarks No-long-jump zone!!!
6299 */
6300static int hmR0VmxSaveGuestLazyMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6301{
6302 /* Since this can be called from our preemption hook it's safer to make the guest-MSRs update non-preemptible. */
6303 VMMRZCallRing3Disable(pVCpu);
6304 HM_DISABLE_PREEMPT();
6305
6306 /* Doing the check here ensures we don't overwrite already-saved guest MSRs from a preemption hook. */
6307 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LAZY_MSRS))
6308 {
6309 hmR0VmxLazySaveGuestMsrs(pVCpu, pMixedCtx);
6310 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LAZY_MSRS);
6311 }
6312
6313 HM_RESTORE_PREEMPT();
6314 VMMRZCallRing3Enable(pVCpu);
6315
6316 return VINF_SUCCESS;
6317}
6318
6319
6320/**
6321 * Saves the auto load/store'd guest MSRs from the current VMCS into
6322 * the guest-CPU context.
6323 *
6324 * @returns VBox status code.
6325 * @param pVCpu The cross context virtual CPU structure.
6326 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6327 * out-of-sync. Make sure to update the required fields
6328 * before using them.
6329 *
6330 * @remarks No-long-jump zone!!!
6331 */
6332static int hmR0VmxSaveGuestAutoLoadStoreMsrs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6333{
6334 if (HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS))
6335 return VINF_SUCCESS;
6336
6337 PVMXAUTOMSR pMsr = (PVMXAUTOMSR)pVCpu->hm.s.vmx.pvGuestMsr;
6338 uint32_t cMsrs = pVCpu->hm.s.vmx.cMsrs;
6339 Log4(("hmR0VmxSaveGuestAutoLoadStoreMsrs: cMsrs=%u\n", cMsrs));
6340 for (uint32_t i = 0; i < cMsrs; i++, pMsr++)
6341 {
6342 switch (pMsr->u32Msr)
6343 {
6344 case MSR_K8_TSC_AUX: CPUMR0SetGuestTscAux(pVCpu, pMsr->u64Value); break;
6345 case MSR_K8_LSTAR: pMixedCtx->msrLSTAR = pMsr->u64Value; break;
6346 case MSR_K6_STAR: pMixedCtx->msrSTAR = pMsr->u64Value; break;
6347 case MSR_K8_SF_MASK: pMixedCtx->msrSFMASK = pMsr->u64Value; break;
6348 case MSR_K8_KERNEL_GS_BASE: pMixedCtx->msrKERNELGSBASE = pMsr->u64Value; break;
6349 case MSR_K6_EFER: /* Nothing to do here since we intercept writes, see hmR0VmxLoadGuestMsrs(). */
6350 break;
6351
6352 default:
6353 {
6354 AssertMsgFailed(("Unexpected MSR in auto-load/store area. uMsr=%#RX32 cMsrs=%u\n", pMsr->u32Msr, cMsrs));
6355 pVCpu->hm.s.u32HMError = pMsr->u32Msr;
6356 return VERR_HM_UNEXPECTED_LD_ST_MSR;
6357 }
6358 }
6359 }
6360
6361 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS);
6362 return VINF_SUCCESS;
6363}
6364
6365
6366/**
6367 * Saves the guest control registers from the current VMCS into the guest-CPU
6368 * context.
6369 *
6370 * @returns VBox status code.
6371 * @param pVCpu The cross context virtual CPU structure.
6372 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6373 * out-of-sync. Make sure to update the required fields
6374 * before using them.
6375 *
6376 * @remarks No-long-jump zone!!!
6377 */
6378static int hmR0VmxSaveGuestControlRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6379{
6380 /* Guest CR0. Guest FPU. */
6381 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6382 AssertRCReturn(rc, rc);
6383
6384 /* Guest CR4. */
6385 rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
6386 AssertRCReturn(rc, rc);
6387
6388 /* Guest CR2 - updated always during the world-switch or in #PF. */
6389 /* Guest CR3. Only changes with Nested Paging. This must be done -after- saving CR0 and CR4 from the guest! */
6390 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR3))
6391 {
6392 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0));
6393 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR4));
6394
6395 PVM pVM = pVCpu->CTX_SUFF(pVM);
6396 if ( pVM->hm.s.vmx.fUnrestrictedGuest
6397 || ( pVM->hm.s.fNestedPaging
6398 && CPUMIsGuestPagingEnabledEx(pMixedCtx)))
6399 {
6400 uint64_t u64Val = 0;
6401 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_CR3, &u64Val);
6402 if (pMixedCtx->cr3 != u64Val)
6403 {
6404 CPUMSetGuestCR3(pVCpu, u64Val);
6405 if (VMMRZCallRing3IsEnabled(pVCpu))
6406 {
6407 PGMUpdateCR3(pVCpu, u64Val);
6408 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
6409 }
6410 else
6411 {
6412 /* Set the force flag to inform PGM about it when necessary. It is cleared by PGMUpdateCR3().*/
6413 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
6414 }
6415 }
6416
6417 /* If the guest is in PAE mode, sync back the PDPE's into the guest state. */
6418 if (CPUMIsGuestInPAEModeEx(pMixedCtx)) /* Reads CR0, CR4 and EFER MSR (EFER is always up-to-date). */
6419 {
6420 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &pVCpu->hm.s.aPdpes[0].u);
6421 rc |= VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &pVCpu->hm.s.aPdpes[1].u);
6422 rc |= VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &pVCpu->hm.s.aPdpes[2].u);
6423 rc |= VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &pVCpu->hm.s.aPdpes[3].u);
6424 AssertRCReturn(rc, rc);
6425
6426 if (VMMRZCallRing3IsEnabled(pVCpu))
6427 {
6428 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
6429 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
6430 }
6431 else
6432 {
6433 /* Set the force flag to inform PGM about it when necessary. It is cleared by PGMGstUpdatePaePdpes(). */
6434 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES);
6435 }
6436 }
6437 }
6438
6439 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR3);
6440 }
6441
6442 /*
6443 * Consider this scenario: VM-exit -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp -> hmR0VmxCallRing3Callback()
6444 * -> VMMRZCallRing3Disable() -> hmR0VmxSaveGuestState() -> Set VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp
6445 * -> continue with VM-exit handling -> hmR0VmxSaveGuestControlRegs() and here we are.
6446 *
6447 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be up-to-date and thus
6448 * if any CR3-saves -before- the VM-exit (longjmp) postponed the CR3 update via the force-flag, any VM-exit handler that
6449 * calls into PGM when it re-saves CR3 will end up here and we call PGMUpdateCR3(). This is why the code below should
6450 * -NOT- check if HMVMX_UPDATED_GUEST_CR3 is already set or not!
6451 *
6452 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again. We cover for it here.
6453 */
6454 if (VMMRZCallRing3IsEnabled(pVCpu))
6455 {
6456 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
6457 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
6458
6459 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
6460 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
6461
6462 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
6463 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
6464 }
6465
6466 return rc;
6467}
6468
6469
6470/**
6471 * Reads a guest segment register from the current VMCS into the guest-CPU
6472 * context.
6473 *
6474 * @returns VBox status code.
6475 * @param pVCpu The cross context virtual CPU structure.
6476 * @param idxSel Index of the selector in the VMCS.
6477 * @param idxLimit Index of the segment limit in the VMCS.
6478 * @param idxBase Index of the segment base in the VMCS.
6479 * @param idxAccess Index of the access rights of the segment in the VMCS.
6480 * @param pSelReg Pointer to the segment selector.
6481 *
6482 * @remarks No-long-jump zone!!!
6483 * @remarks Never call this function directly!!! Use the VMXLOCAL_READ_SEG()
6484 * macro as that takes care of whether to read from the VMCS cache or
6485 * not.
6486 */
6487DECLINLINE(int) hmR0VmxReadSegmentReg(PVMCPU pVCpu, uint32_t idxSel, uint32_t idxLimit, uint32_t idxBase, uint32_t idxAccess,
6488 PCPUMSELREG pSelReg)
6489{
6490 NOREF(pVCpu);
6491
6492 uint32_t u32Val = 0;
6493 int rc = VMXReadVmcs32(idxSel, &u32Val);
6494 AssertRCReturn(rc, rc);
6495 pSelReg->Sel = (uint16_t)u32Val;
6496 pSelReg->ValidSel = (uint16_t)u32Val;
6497 pSelReg->fFlags = CPUMSELREG_FLAGS_VALID;
6498
6499 rc = VMXReadVmcs32(idxLimit, &u32Val);
6500 AssertRCReturn(rc, rc);
6501 pSelReg->u32Limit = u32Val;
6502
6503 uint64_t u64Val = 0;
6504 rc = VMXReadVmcsGstNByIdxVal(idxBase, &u64Val);
6505 AssertRCReturn(rc, rc);
6506 pSelReg->u64Base = u64Val;
6507
6508 rc = VMXReadVmcs32(idxAccess, &u32Val);
6509 AssertRCReturn(rc, rc);
6510 pSelReg->Attr.u = u32Val;
6511
6512 /*
6513 * If VT-x marks the segment as unusable, most other bits remain undefined:
6514 * - For CS the L, D and G bits have meaning.
6515 * - For SS the DPL has meaning (it -is- the CPL for Intel and VBox).
6516 * - For the remaining data segments no bits are defined.
6517 *
6518 * The present bit and the unusable bit has been observed to be set at the
6519 * same time (the selector was supposed to be invalid as we started executing
6520 * a V8086 interrupt in ring-0).
6521 *
6522 * What should be important for the rest of the VBox code, is that the P bit is
6523 * cleared. Some of the other VBox code recognizes the unusable bit, but
6524 * AMD-V certainly don't, and REM doesn't really either. So, to be on the
6525 * safe side here, we'll strip off P and other bits we don't care about. If
6526 * any code breaks because Attr.u != 0 when Sel < 4, it should be fixed.
6527 *
6528 * See Intel spec. 27.3.2 "Saving Segment Registers and Descriptor-Table Registers".
6529 */
6530 if (pSelReg->Attr.u & X86DESCATTR_UNUSABLE)
6531 {
6532 Assert(idxSel != VMX_VMCS16_GUEST_TR_SEL); /* TR is the only selector that can never be unusable. */
6533
6534 /* Masking off: X86DESCATTR_P, X86DESCATTR_LIMIT_HIGH, and X86DESCATTR_AVL. The latter two are really irrelevant. */
6535 pSelReg->Attr.u &= X86DESCATTR_UNUSABLE | X86DESCATTR_L | X86DESCATTR_D | X86DESCATTR_G
6536 | X86DESCATTR_DPL | X86DESCATTR_TYPE | X86DESCATTR_DT;
6537
6538 Log4(("hmR0VmxReadSegmentReg: Unusable idxSel=%#x attr=%#x -> %#x\n", idxSel, u32Val, pSelReg->Attr.u));
6539#ifdef DEBUG_bird
6540 AssertMsg((u32Val & ~X86DESCATTR_P) == pSelReg->Attr.u,
6541 ("%#x: %#x != %#x (sel=%#x base=%#llx limit=%#x)\n",
6542 idxSel, u32Val, pSelReg->Attr.u, pSelReg->Sel, pSelReg->u64Base, pSelReg->u32Limit));
6543#endif
6544 }
6545 return VINF_SUCCESS;
6546}
6547
6548
6549#ifdef VMX_USE_CACHED_VMCS_ACCESSES
6550# define VMXLOCAL_READ_SEG(Sel, CtxSel) \
6551 hmR0VmxReadSegmentReg(pVCpu, VMX_VMCS16_GUEST_##Sel##_SEL, VMX_VMCS32_GUEST_##Sel##_LIMIT, \
6552 VMX_VMCS_GUEST_##Sel##_BASE_CACHE_IDX, VMX_VMCS32_GUEST_##Sel##_ACCESS_RIGHTS, &pMixedCtx->CtxSel)
6553#else
6554# define VMXLOCAL_READ_SEG(Sel, CtxSel) \
6555 hmR0VmxReadSegmentReg(pVCpu, VMX_VMCS16_GUEST_##Sel##_SEL, VMX_VMCS32_GUEST_##Sel##_LIMIT, \
6556 VMX_VMCS_GUEST_##Sel##_BASE, VMX_VMCS32_GUEST_##Sel##_ACCESS_RIGHTS, &pMixedCtx->CtxSel)
6557#endif
6558
6559
6560/**
6561 * Saves the guest segment registers from the current VMCS into the guest-CPU
6562 * context.
6563 *
6564 * @returns VBox status code.
6565 * @param pVCpu The cross context virtual CPU structure.
6566 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6567 * out-of-sync. Make sure to update the required fields
6568 * before using them.
6569 *
6570 * @remarks No-long-jump zone!!!
6571 */
6572static int hmR0VmxSaveGuestSegmentRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6573{
6574 /* Guest segment registers. */
6575 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SEGMENT_REGS))
6576 {
6577 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6578 AssertRCReturn(rc, rc);
6579
6580 rc = VMXLOCAL_READ_SEG(CS, cs);
6581 rc |= VMXLOCAL_READ_SEG(SS, ss);
6582 rc |= VMXLOCAL_READ_SEG(DS, ds);
6583 rc |= VMXLOCAL_READ_SEG(ES, es);
6584 rc |= VMXLOCAL_READ_SEG(FS, fs);
6585 rc |= VMXLOCAL_READ_SEG(GS, gs);
6586 AssertRCReturn(rc, rc);
6587
6588 /* Restore segment attributes for real-on-v86 mode hack. */
6589 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
6590 {
6591 pMixedCtx->cs.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrCS.u;
6592 pMixedCtx->ss.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrSS.u;
6593 pMixedCtx->ds.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrDS.u;
6594 pMixedCtx->es.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrES.u;
6595 pMixedCtx->fs.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrFS.u;
6596 pMixedCtx->gs.Attr.u = pVCpu->hm.s.vmx.RealMode.AttrGS.u;
6597 }
6598 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_SEGMENT_REGS);
6599 }
6600
6601 return VINF_SUCCESS;
6602}
6603
6604
6605/**
6606 * Saves the guest descriptor table registers and task register from the current
6607 * VMCS into the guest-CPU context.
6608 *
6609 * @returns VBox status code.
6610 * @param pVCpu The cross context virtual CPU structure.
6611 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6612 * out-of-sync. Make sure to update the required fields
6613 * before using them.
6614 *
6615 * @remarks No-long-jump zone!!!
6616 */
6617static int hmR0VmxSaveGuestTableRegs(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6618{
6619 int rc = VINF_SUCCESS;
6620
6621 /* Guest LDTR. */
6622 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LDTR))
6623 {
6624 rc = VMXLOCAL_READ_SEG(LDTR, ldtr);
6625 AssertRCReturn(rc, rc);
6626 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LDTR);
6627 }
6628
6629 /* Guest GDTR. */
6630 uint64_t u64Val = 0;
6631 uint32_t u32Val = 0;
6632 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_GDTR))
6633 {
6634 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
6635 rc |= VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val); AssertRCReturn(rc, rc);
6636 pMixedCtx->gdtr.pGdt = u64Val;
6637 pMixedCtx->gdtr.cbGdt = u32Val;
6638 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_GDTR);
6639 }
6640
6641 /* Guest IDTR. */
6642 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_IDTR))
6643 {
6644 rc = VMXReadVmcsGstN(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
6645 rc |= VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val); AssertRCReturn(rc, rc);
6646 pMixedCtx->idtr.pIdt = u64Val;
6647 pMixedCtx->idtr.cbIdt = u32Val;
6648 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_IDTR);
6649 }
6650
6651 /* Guest TR. */
6652 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_TR))
6653 {
6654 rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6655 AssertRCReturn(rc, rc);
6656
6657 /* For real-mode emulation using virtual-8086 mode we have the fake TSS (pRealModeTSS) in TR, don't save the fake one. */
6658 if (!pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
6659 {
6660 rc = VMXLOCAL_READ_SEG(TR, tr);
6661 AssertRCReturn(rc, rc);
6662 }
6663 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_TR);
6664 }
6665 return rc;
6666}
6667
6668#undef VMXLOCAL_READ_SEG
6669
6670
6671/**
6672 * Saves the guest debug-register DR7 from the current VMCS into the guest-CPU
6673 * context.
6674 *
6675 * @returns VBox status code.
6676 * @param pVCpu The cross context virtual CPU structure.
6677 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6678 * out-of-sync. Make sure to update the required fields
6679 * before using them.
6680 *
6681 * @remarks No-long-jump zone!!!
6682 */
6683static int hmR0VmxSaveGuestDR7(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6684{
6685 if (!HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_DEBUG))
6686 {
6687 if (!pVCpu->hm.s.fUsingHyperDR7)
6688 {
6689 /* Upper 32-bits are always zero. See Intel spec. 2.7.3 "Loading and Storing Debug Registers". */
6690 uint32_t u32Val;
6691 int rc = VMXReadVmcs32(VMX_VMCS_GUEST_DR7, &u32Val); AssertRCReturn(rc, rc);
6692 pMixedCtx->dr[7] = u32Val;
6693 }
6694
6695 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_DEBUG);
6696 }
6697 return VINF_SUCCESS;
6698}
6699
6700
6701/**
6702 * Saves the guest APIC state from the current VMCS into the guest-CPU context.
6703 *
6704 * @returns VBox status code.
6705 * @param pVCpu The cross context virtual CPU structure.
6706 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
6707 * out-of-sync. Make sure to update the required fields
6708 * before using them.
6709 *
6710 * @remarks No-long-jump zone!!!
6711 */
6712static int hmR0VmxSaveGuestApicState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6713{
6714 NOREF(pMixedCtx);
6715
6716 /* Updating TPR is already done in hmR0VmxPostRunGuest(). Just update the flag. */
6717 HMVMXCPU_GST_SET_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_APIC_STATE);
6718 return VINF_SUCCESS;
6719}
6720
6721
6722/**
6723 * Saves the entire guest state from the currently active VMCS into the
6724 * guest-CPU context.
6725 *
6726 * This essentially VMREADs all guest-data.
6727 *
6728 * @returns VBox status code.
6729 * @param pVCpu The cross context virtual CPU structure.
6730 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
6731 * out-of-sync. Make sure to update the required fields
6732 * before using them.
6733 */
6734static int hmR0VmxSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6735{
6736 Assert(pVCpu);
6737 Assert(pMixedCtx);
6738
6739 if (HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL)
6740 return VINF_SUCCESS;
6741
6742 /* Though we can longjmp to ring-3 due to log-flushes here and get recalled
6743 again on the ring-3 callback path, there is no real need to. */
6744 if (VMMRZCallRing3IsEnabled(pVCpu))
6745 VMMR0LogFlushDisable(pVCpu);
6746 else
6747 Assert(VMMR0IsLogFlushDisabled(pVCpu));
6748 Log4Func(("vcpu[%RU32]\n", pVCpu->idCpu));
6749
6750 int rc = hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
6751 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestRipRspRflags failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6752
6753 rc = hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
6754 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestControlRegs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6755
6756 rc = hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
6757 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestSegmentRegs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6758
6759 rc = hmR0VmxSaveGuestTableRegs(pVCpu, pMixedCtx);
6760 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestTableRegs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6761
6762 rc = hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
6763 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestDR7 failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6764
6765 rc = hmR0VmxSaveGuestSysenterMsrs(pVCpu, pMixedCtx);
6766 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestSysenterMsrs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6767
6768 rc = hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
6769 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestLazyMsrs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6770
6771 rc = hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
6772 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestAutoLoadStoreMsrs failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6773
6774 rc = hmR0VmxSaveGuestActivityState(pVCpu, pMixedCtx);
6775 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestActivityState failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6776
6777 rc = hmR0VmxSaveGuestApicState(pVCpu, pMixedCtx);
6778 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveGuestApicState failed! rc=%Rrc (pVCpu=%p)\n", rc, pVCpu), rc);
6779
6780 AssertMsg(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL,
6781 ("Missed guest state bits while saving state; missing %RX32 (got %RX32, want %RX32) - check log for any previous errors!\n",
6782 HMVMX_UPDATED_GUEST_ALL ^ HMVMXCPU_GST_VALUE(pVCpu), HMVMXCPU_GST_VALUE(pVCpu), HMVMX_UPDATED_GUEST_ALL));
6783
6784 if (VMMRZCallRing3IsEnabled(pVCpu))
6785 VMMR0LogFlushEnable(pVCpu);
6786
6787 return VINF_SUCCESS;
6788}
6789
6790
6791/**
6792 * Saves basic guest registers needed for IEM instruction execution.
6793 *
6794 * @returns VBox status code (OR-able).
6795 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
6796 * @param pMixedCtx Pointer to the CPU context of the guest.
6797 * @param fMemory Whether the instruction being executed operates on
6798 * memory or not. Only CR0 is synced up if clear.
6799 * @param fNeedRsp Need RSP (any instruction working on GPRs or stack).
6800 */
6801static int hmR0VmxSaveGuestRegsForIemExec(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fMemory, bool fNeedRsp)
6802{
6803 /*
6804 * We assume all general purpose registers other than RSP are available.
6805 *
6806 * RIP is a must, as it will be incremented or otherwise changed.
6807 *
6808 * RFLAGS are always required to figure the CPL.
6809 *
6810 * RSP isn't always required, however it's a GPR, so frequently required.
6811 *
6812 * SS and CS are the only segment register needed if IEM doesn't do memory
6813 * access (CPL + 16/32/64-bit mode), but we can only get all segment registers.
6814 *
6815 * CR0 is always required by IEM for the CPL, while CR3 and CR4 will only
6816 * be required for memory accesses.
6817 *
6818 * Note! Before IEM dispatches an exception, it will call us to sync in everything.
6819 */
6820 int rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
6821 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
6822 if (fNeedRsp)
6823 rc |= hmR0VmxSaveGuestRsp(pVCpu, pMixedCtx);
6824 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
6825 if (!fMemory)
6826 rc |= hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
6827 else
6828 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
6829 AssertRCReturn(rc, rc);
6830 return rc;
6831}
6832
6833
6834/**
6835 * Ensures that we've got a complete basic guest-context.
6836 *
6837 * This excludes the FPU, SSE, AVX, and similar extended state. The interface
6838 * is for the interpreter.
6839 *
6840 * @returns VBox status code.
6841 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
6842 * @param pMixedCtx Pointer to the guest-CPU context which may have data
6843 * needing to be synced in.
6844 * @thread EMT(pVCpu)
6845 */
6846VMMR0_INT_DECL(int) HMR0EnsureCompleteBasicContext(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
6847{
6848 /* Note! Since this is only applicable to VT-x, the implementation is placed
6849 in the VT-x part of the sources instead of the generic stuff. */
6850 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported)
6851 {
6852 /* For now, imply that the caller might change everything too. */
6853 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
6854 return hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
6855 }
6856 return VINF_SUCCESS;
6857}
6858
6859
6860/**
6861 * Check per-VM and per-VCPU force flag actions that require us to go back to
6862 * ring-3 for one reason or another.
6863 *
6864 * @returns Strict VBox status code (i.e. informational status codes too)
6865 * @retval VINF_SUCCESS if we don't have any actions that require going back to
6866 * ring-3.
6867 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
6868 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
6869 * interrupts)
6870 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
6871 * all EMTs to be in ring-3.
6872 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
6873 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
6874 * to the EM loop.
6875 *
6876 * @param pVM The cross context VM structure.
6877 * @param pVCpu The cross context virtual CPU structure.
6878 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
6879 * out-of-sync. Make sure to update the required fields
6880 * before using them.
6881 * @param fStepping Running in hmR0VmxRunGuestCodeStep().
6882 */
6883static VBOXSTRICTRC hmR0VmxCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fStepping)
6884{
6885 Assert(VMMRZCallRing3IsEnabled(pVCpu));
6886
6887 /*
6888 * Anything pending? Should be more likely than not if we're doing a good job.
6889 */
6890 if ( !fStepping
6891 ? !VM_FF_IS_PENDING(pVM, VM_FF_HP_R0_PRE_HM_MASK)
6892 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HP_R0_PRE_HM_MASK)
6893 : !VM_FF_IS_PENDING(pVM, VM_FF_HP_R0_PRE_HM_STEP_MASK)
6894 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
6895 return VINF_SUCCESS;
6896
6897 /* We need the control registers now, make sure the guest-CPU context is updated. */
6898 int rc3 = hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
6899 AssertRCReturn(rc3, rc3);
6900
6901 /* Pending HM CR3 sync. */
6902 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
6903 {
6904 int rc2 = PGMUpdateCR3(pVCpu, pMixedCtx->cr3);
6905 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
6906 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
6907 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
6908 }
6909
6910 /* Pending HM PAE PDPEs. */
6911 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
6912 {
6913 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
6914 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
6915 }
6916
6917 /* Pending PGM C3 sync. */
6918 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
6919 {
6920 VBOXSTRICTRC rcStrict2 = PGMSyncCR3(pVCpu, pMixedCtx->cr0, pMixedCtx->cr3, pMixedCtx->cr4,
6921 VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
6922 if (rcStrict2 != VINF_SUCCESS)
6923 {
6924 AssertRC(VBOXSTRICTRC_VAL(rcStrict2));
6925 Log4(("hmR0VmxCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc2=%d\n", VBOXSTRICTRC_VAL(rcStrict2)));
6926 return rcStrict2;
6927 }
6928 }
6929
6930 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
6931 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
6932 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
6933 {
6934 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
6935 int rc2 = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
6936 Log4(("hmR0VmxCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc2));
6937 return rc2;
6938 }
6939
6940 /* Pending VM request packets, such as hardware interrupts. */
6941 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
6942 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
6943 {
6944 Log4(("hmR0VmxCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
6945 return VINF_EM_PENDING_REQUEST;
6946 }
6947
6948 /* Pending PGM pool flushes. */
6949 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
6950 {
6951 Log4(("hmR0VmxCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
6952 return VINF_PGM_POOL_FLUSH_PENDING;
6953 }
6954
6955 /* Pending DMA requests. */
6956 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
6957 {
6958 Log4(("hmR0VmxCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
6959 return VINF_EM_RAW_TO_R3;
6960 }
6961
6962 return VINF_SUCCESS;
6963}
6964
6965
6966/**
6967 * Converts any TRPM trap into a pending HM event. This is typically used when
6968 * entering from ring-3 (not longjmp returns).
6969 *
6970 * @param pVCpu The cross context virtual CPU structure.
6971 */
6972static void hmR0VmxTrpmTrapToPendingEvent(PVMCPU pVCpu)
6973{
6974 Assert(TRPMHasTrap(pVCpu));
6975 Assert(!pVCpu->hm.s.Event.fPending);
6976
6977 uint8_t uVector;
6978 TRPMEVENT enmTrpmEvent;
6979 RTGCUINT uErrCode;
6980 RTGCUINTPTR GCPtrFaultAddress;
6981 uint8_t cbInstr;
6982
6983 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
6984 AssertRC(rc);
6985
6986 /* Refer Intel spec. 24.8.3 "VM-entry Controls for Event Injection" for the format of u32IntInfo. */
6987 uint32_t u32IntInfo = uVector | VMX_EXIT_INTERRUPTION_INFO_VALID;
6988 if (enmTrpmEvent == TRPM_TRAP)
6989 {
6990 switch (uVector)
6991 {
6992 case X86_XCPT_NMI:
6993 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
6994 break;
6995
6996 case X86_XCPT_BP:
6997 case X86_XCPT_OF:
6998 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
6999 break;
7000
7001 case X86_XCPT_PF:
7002 case X86_XCPT_DF:
7003 case X86_XCPT_TS:
7004 case X86_XCPT_NP:
7005 case X86_XCPT_SS:
7006 case X86_XCPT_GP:
7007 case X86_XCPT_AC:
7008 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
7009 /* no break! */
7010 default:
7011 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7012 break;
7013 }
7014 }
7015 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
7016 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7017 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
7018 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7019 else
7020 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
7021
7022 rc = TRPMResetTrap(pVCpu);
7023 AssertRC(rc);
7024 Log4(("TRPM->HM event: u32IntInfo=%#RX32 enmTrpmEvent=%d cbInstr=%u uErrCode=%#RX32 GCPtrFaultAddress=%#RGv\n",
7025 u32IntInfo, enmTrpmEvent, cbInstr, uErrCode, GCPtrFaultAddress));
7026
7027 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, uErrCode, GCPtrFaultAddress);
7028}
7029
7030
7031/**
7032 * Converts the pending HM event into a TRPM trap.
7033 *
7034 * @param pVCpu The cross context virtual CPU structure.
7035 */
7036static void hmR0VmxPendingEventToTrpmTrap(PVMCPU pVCpu)
7037{
7038 Assert(pVCpu->hm.s.Event.fPending);
7039
7040 uint32_t uVectorType = VMX_IDT_VECTORING_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
7041 uint32_t uVector = VMX_IDT_VECTORING_INFO_VECTOR(pVCpu->hm.s.Event.u64IntInfo);
7042 bool fErrorCodeValid = VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVCpu->hm.s.Event.u64IntInfo);
7043 uint32_t uErrorCode = pVCpu->hm.s.Event.u32ErrCode;
7044
7045 /* If a trap was already pending, we did something wrong! */
7046 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
7047
7048 TRPMEVENT enmTrapType;
7049 switch (uVectorType)
7050 {
7051 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
7052 enmTrapType = TRPM_HARDWARE_INT;
7053 break;
7054
7055 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
7056 enmTrapType = TRPM_SOFTWARE_INT;
7057 break;
7058
7059 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
7060 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
7061 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT: /* #BP and #OF */
7062 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
7063 enmTrapType = TRPM_TRAP;
7064 break;
7065
7066 default:
7067 AssertMsgFailed(("Invalid trap type %#x\n", uVectorType));
7068 enmTrapType = TRPM_32BIT_HACK;
7069 break;
7070 }
7071
7072 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, enmTrapType));
7073
7074 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
7075 AssertRC(rc);
7076
7077 if (fErrorCodeValid)
7078 TRPMSetErrorCode(pVCpu, uErrorCode);
7079
7080 if ( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
7081 && uVector == X86_XCPT_PF)
7082 {
7083 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
7084 }
7085 else if ( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
7086 || uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
7087 || uVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
7088 {
7089 AssertMsg( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
7090 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
7091 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
7092 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
7093 }
7094
7095 /* Clear any pending events from the VMCS. */
7096 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0); AssertRC(rc);
7097 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, 0); AssertRC(rc);
7098
7099 /* We're now done converting the pending event. */
7100 pVCpu->hm.s.Event.fPending = false;
7101}
7102
7103
7104/**
7105 * Does the necessary state syncing before returning to ring-3 for any reason
7106 * (longjmp, preemption, voluntary exits to ring-3) from VT-x.
7107 *
7108 * @returns VBox status code.
7109 * @param pVCpu The cross context virtual CPU structure.
7110 * @param pMixedCtx Pointer to the guest-CPU context. The data may
7111 * be out-of-sync. Make sure to update the required
7112 * fields before using them.
7113 * @param fSaveGuestState Whether to save the guest state or not.
7114 *
7115 * @remarks No-long-jmp zone!!!
7116 */
7117static int hmR0VmxLeave(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fSaveGuestState)
7118{
7119 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7120 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7121
7122 RTCPUID idCpu = RTMpCpuId();
7123 Log4Func(("HostCpuId=%u\n", idCpu));
7124
7125 /*
7126 * !!! IMPORTANT !!!
7127 * If you modify code here, check whether hmR0VmxCallRing3Callback() needs to be updated too.
7128 */
7129
7130 /* Save the guest state if necessary. */
7131 if ( fSaveGuestState
7132 && HMVMXCPU_GST_VALUE(pVCpu) != HMVMX_UPDATED_GUEST_ALL)
7133 {
7134 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
7135 AssertRCReturn(rc, rc);
7136 Assert(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL);
7137 }
7138
7139 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
7140 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu))
7141 {
7142 if (fSaveGuestState)
7143 {
7144 /* We shouldn't reload CR0 without saving it first. */
7145 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
7146 AssertRCReturn(rc, rc);
7147 }
7148 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
7149 }
7150
7151 /* Restore host debug registers if necessary and resync on next R0 reentry. */
7152#ifdef VBOX_STRICT
7153 if (CPUMIsHyperDebugStateActive(pVCpu))
7154 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT);
7155#endif
7156 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */))
7157 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
7158 Assert(!CPUMIsGuestDebugStateActive(pVCpu) && !CPUMIsGuestDebugStateActivePending(pVCpu));
7159 Assert(!CPUMIsHyperDebugStateActive(pVCpu) && !CPUMIsHyperDebugStateActivePending(pVCpu));
7160
7161#if HC_ARCH_BITS == 64
7162 /* Restore host-state bits that VT-x only restores partially. */
7163 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7164 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7165 {
7166 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags, idCpu));
7167 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7168 }
7169 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7170#endif
7171
7172 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7173 if (pVCpu->hm.s.vmx.fLazyMsrs)
7174 {
7175 /* We shouldn't reload the guest MSRs without saving it first. */
7176 if (!fSaveGuestState)
7177 {
7178 int rc = hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
7179 AssertRCReturn(rc, rc);
7180 }
7181 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_LAZY_MSRS));
7182 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7183 Assert(!pVCpu->hm.s.vmx.fLazyMsrs);
7184 }
7185
7186 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7187 pVCpu->hm.s.vmx.fUpdatedHostMsrs = false;
7188
7189 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
7190 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
7191 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
7192 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
7193 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitIO);
7194 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitMovCRx);
7195 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitXcptNmi);
7196 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
7197
7198 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
7199
7200 /** @todo This partially defeats the purpose of having preemption hooks.
7201 * The problem is, deregistering the hooks should be moved to a place that
7202 * lasts until the EMT is about to be destroyed not everytime while leaving HM
7203 * context.
7204 */
7205 if (pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_ACTIVE)
7206 {
7207 int rc = VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
7208 AssertRCReturn(rc, rc);
7209
7210 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
7211 Log4Func(("Cleared Vmcs. HostCpuId=%u\n", idCpu));
7212 }
7213 Assert(!(pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_LAUNCHED));
7214 NOREF(idCpu);
7215
7216 return VINF_SUCCESS;
7217}
7218
7219
7220/**
7221 * Leaves the VT-x session.
7222 *
7223 * @returns VBox status code.
7224 * @param pVCpu The cross context virtual CPU structure.
7225 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7226 * out-of-sync. Make sure to update the required fields
7227 * before using them.
7228 *
7229 * @remarks No-long-jmp zone!!!
7230 */
7231DECLINLINE(int) hmR0VmxLeaveSession(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7232{
7233 HM_DISABLE_PREEMPT();
7234 HMVMX_ASSERT_CPU_SAFE();
7235 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7236 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7237
7238 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
7239 and done this from the VMXR0ThreadCtxCallback(). */
7240 if (!pVCpu->hm.s.fLeaveDone)
7241 {
7242 int rc2 = hmR0VmxLeave(pVCpu, pMixedCtx, true /* fSaveGuestState */);
7243 AssertRCReturnStmt(rc2, HM_RESTORE_PREEMPT(), rc2);
7244 pVCpu->hm.s.fLeaveDone = true;
7245 }
7246 Assert(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL);
7247
7248 /*
7249 * !!! IMPORTANT !!!
7250 * If you modify code here, make sure to check whether hmR0VmxCallRing3Callback() needs to be updated too.
7251 */
7252
7253 /* Deregister hook now that we've left HM context before re-enabling preemption. */
7254 /** @todo Deregistering here means we need to VMCLEAR always
7255 * (longjmp/exit-to-r3) in VT-x which is not efficient. */
7256 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
7257 VMMR0ThreadCtxHookDisable(pVCpu);
7258
7259 /* Leave HM context. This takes care of local init (term). */
7260 int rc = HMR0LeaveCpu(pVCpu);
7261
7262 HM_RESTORE_PREEMPT();
7263 return rc;
7264}
7265
7266
7267/**
7268 * Does the necessary state syncing before doing a longjmp to ring-3.
7269 *
7270 * @returns VBox status code.
7271 * @param pVCpu The cross context virtual CPU structure.
7272 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7273 * out-of-sync. Make sure to update the required fields
7274 * before using them.
7275 *
7276 * @remarks No-long-jmp zone!!!
7277 */
7278DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7279{
7280 return hmR0VmxLeaveSession(pVCpu, pMixedCtx);
7281}
7282
7283
7284/**
7285 * Take necessary actions before going back to ring-3.
7286 *
7287 * An action requires us to go back to ring-3. This function does the necessary
7288 * steps before we can safely return to ring-3. This is not the same as longjmps
7289 * to ring-3, this is voluntary and prepares the guest so it may continue
7290 * executing outside HM (recompiler/IEM).
7291 *
7292 * @returns VBox status code.
7293 * @param pVM The cross context VM structure.
7294 * @param pVCpu The cross context virtual CPU structure.
7295 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7296 * out-of-sync. Make sure to update the required fields
7297 * before using them.
7298 * @param rcExit The reason for exiting to ring-3. Can be
7299 * VINF_VMM_UNKNOWN_RING3_CALL.
7300 */
7301static int hmR0VmxExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, VBOXSTRICTRC rcExit)
7302{
7303 Assert(pVM);
7304 Assert(pVCpu);
7305 Assert(pMixedCtx);
7306 HMVMX_ASSERT_PREEMPT_SAFE();
7307
7308 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
7309 {
7310 VMXGetActivatedVmcs(&pVCpu->hm.s.vmx.LastError.u64VMCSPhys);
7311 pVCpu->hm.s.vmx.LastError.u32VMCSRevision = *(uint32_t *)pVCpu->hm.s.vmx.pvVmcs;
7312 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
7313 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
7314 }
7315
7316 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
7317 VMMRZCallRing3Disable(pVCpu);
7318 Log4(("hmR0VmxExitToRing3: pVCpu=%p idCpu=%RU32 rcExit=%d\n", pVCpu, pVCpu->idCpu, VBOXSTRICTRC_VAL(rcExit)));
7319
7320 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
7321 if (pVCpu->hm.s.Event.fPending)
7322 {
7323 hmR0VmxPendingEventToTrpmTrap(pVCpu);
7324 Assert(!pVCpu->hm.s.Event.fPending);
7325 }
7326
7327 /* Clear interrupt-window and NMI-window controls as we re-evaluate it when we return from ring-3. */
7328 hmR0VmxClearIntNmiWindowsVmcs(pVCpu);
7329
7330 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
7331 and if we're injecting an event we should have a TRPM trap pending. */
7332 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
7333#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a tripple fault in progress. */
7334 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
7335#endif
7336
7337 /* Save guest state and restore host state bits. */
7338 int rc = hmR0VmxLeaveSession(pVCpu, pMixedCtx);
7339 AssertRCReturn(rc, rc);
7340 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
7341 /* Thread-context hooks are unregistered at this point!!! */
7342
7343 /* Sync recompiler state. */
7344 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
7345 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
7346 | CPUM_CHANGED_LDTR
7347 | CPUM_CHANGED_GDTR
7348 | CPUM_CHANGED_IDTR
7349 | CPUM_CHANGED_TR
7350 | CPUM_CHANGED_HIDDEN_SEL_REGS);
7351 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0));
7352 if ( pVM->hm.s.fNestedPaging
7353 && CPUMIsGuestPagingEnabledEx(pMixedCtx))
7354 {
7355 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
7356 }
7357
7358 Assert(!pVCpu->hm.s.fClearTrapFlag);
7359
7360 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
7361 if (rcExit != VINF_EM_RAW_INTERRUPT)
7362 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
7363
7364 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
7365
7366 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
7367 VMMRZCallRing3RemoveNotification(pVCpu);
7368 VMMRZCallRing3Enable(pVCpu);
7369
7370 return rc;
7371}
7372
7373
7374/**
7375 * VMMRZCallRing3() callback wrapper which saves the guest state before we
7376 * longjump to ring-3 and possibly get preempted.
7377 *
7378 * @returns VBox status code.
7379 * @param pVCpu The cross context virtual CPU structure.
7380 * @param enmOperation The operation causing the ring-3 longjump.
7381 * @param pvUser Opaque pointer to the guest-CPU context. The data
7382 * may be out-of-sync. Make sure to update the required
7383 * fields before using them.
7384 */
7385static DECLCALLBACK(int) hmR0VmxCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
7386{
7387 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
7388 {
7389 /*
7390 * !!! IMPORTANT !!!
7391 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
7392 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
7393 */
7394 VMMRZCallRing3RemoveNotification(pVCpu);
7395 VMMRZCallRing3Disable(pVCpu);
7396 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
7397 RTThreadPreemptDisable(&PreemptState);
7398
7399 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
7400 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
7401
7402#if HC_ARCH_BITS == 64
7403 /* Restore host-state bits that VT-x only restores partially. */
7404 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7405 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7406 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7407 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7408#endif
7409 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7410 if (pVCpu->hm.s.vmx.fLazyMsrs)
7411 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7412
7413 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7414 pVCpu->hm.s.vmx.fUpdatedHostMsrs = false;
7415 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
7416 if (pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_ACTIVE)
7417 {
7418 VMXClearVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
7419 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_CLEAR;
7420 }
7421
7422 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
7423 VMMR0ThreadCtxHookDisable(pVCpu);
7424 HMR0LeaveCpu(pVCpu);
7425 RTThreadPreemptRestore(&PreemptState);
7426 return VINF_SUCCESS;
7427 }
7428
7429 Assert(pVCpu);
7430 Assert(pvUser);
7431 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7432 HMVMX_ASSERT_PREEMPT_SAFE();
7433
7434 VMMRZCallRing3Disable(pVCpu);
7435 Assert(VMMR0IsLogFlushDisabled(pVCpu));
7436
7437 Log4(("hmR0VmxCallRing3Callback->hmR0VmxLongJmpToRing3 pVCpu=%p idCpu=%RU32 enmOperation=%d\n", pVCpu, pVCpu->idCpu,
7438 enmOperation));
7439
7440 int rc = hmR0VmxLongJmpToRing3(pVCpu, (PCPUMCTX)pvUser);
7441 AssertRCReturn(rc, rc);
7442
7443 VMMRZCallRing3Enable(pVCpu);
7444 return VINF_SUCCESS;
7445}
7446
7447
7448/**
7449 * Sets the interrupt-window exiting control in the VMCS which instructs VT-x to
7450 * cause a VM-exit as soon as the guest is in a state to receive interrupts.
7451 *
7452 * @param pVCpu The cross context virtual CPU structure.
7453 */
7454DECLINLINE(void) hmR0VmxSetIntWindowExitVmcs(PVMCPU pVCpu)
7455{
7456 if (RT_LIKELY(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT))
7457 {
7458 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT))
7459 {
7460 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT;
7461 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7462 AssertRC(rc);
7463 Log4(("Setup interrupt-window exiting\n"));
7464 }
7465 } /* else we will deliver interrupts whenever the guest exits next and is in a state to receive events. */
7466}
7467
7468
7469/**
7470 * Clears the interrupt-window exiting control in the VMCS.
7471 *
7472 * @param pVCpu The cross context virtual CPU structure.
7473 */
7474DECLINLINE(void) hmR0VmxClearIntWindowExitVmcs(PVMCPU pVCpu)
7475{
7476 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT);
7477 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT;
7478 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7479 AssertRC(rc);
7480 Log4(("Cleared interrupt-window exiting\n"));
7481}
7482
7483
7484/**
7485 * Sets the NMI-window exiting control in the VMCS which instructs VT-x to
7486 * cause a VM-exit as soon as the guest is in a state to receive NMIs.
7487 *
7488 * @param pVCpu The cross context virtual CPU structure.
7489 */
7490DECLINLINE(void) hmR0VmxSetNmiWindowExitVmcs(PVMCPU pVCpu)
7491{
7492 if (RT_LIKELY(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT))
7493 {
7494 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT))
7495 {
7496 pVCpu->hm.s.vmx.u32ProcCtls |= VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT;
7497 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7498 AssertRC(rc);
7499 Log4(("Setup NMI-window exiting\n"));
7500 }
7501 } /* else we will deliver NMIs whenever we VM-exit next, even possibly nesting NMIs. Can't be helped on ancient CPUs. */
7502}
7503
7504
7505/**
7506 * Clears the NMI-window exiting control in the VMCS.
7507 *
7508 * @param pVCpu The cross context virtual CPU structure.
7509 */
7510DECLINLINE(void) hmR0VmxClearNmiWindowExitVmcs(PVMCPU pVCpu)
7511{
7512 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT);
7513 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT;
7514 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
7515 AssertRC(rc);
7516 Log4(("Cleared NMI-window exiting\n"));
7517}
7518
7519
7520/**
7521 * Evaluates the event to be delivered to the guest and sets it as the pending
7522 * event.
7523 *
7524 * @returns The VT-x guest-interruptibility state.
7525 * @param pVCpu The cross context virtual CPU structure.
7526 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7527 * out-of-sync. Make sure to update the required fields
7528 * before using them.
7529 */
7530static uint32_t hmR0VmxEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7531{
7532 /* Get the current interruptibility-state of the guest and then figure out what can be injected. */
7533 uint32_t const uIntrState = hmR0VmxGetGuestIntrState(pVCpu, pMixedCtx);
7534 bool const fBlockMovSS = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS);
7535 bool const fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
7536 bool const fBlockNmi = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI);
7537
7538 Assert(!fBlockSti || HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS));
7539 Assert(!(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
7540 Assert(!fBlockSti || pMixedCtx->eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
7541 Assert(!TRPMHasTrap(pVCpu));
7542
7543#ifdef VBOX_WITH_NEW_APIC
7544 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
7545 APICUpdatePendingInterrupts(pVCpu);
7546#endif
7547
7548 /*
7549 * Toggling of interrupt force-flags here is safe since we update TRPM on premature exits
7550 * to ring-3 before executing guest code, see hmR0VmxExitToRing3(). We must NOT restore these force-flags.
7551 */
7552 /** @todo SMI. SMIs take priority over NMIs. */
7553 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts. */
7554 {
7555 /* On some CPUs block-by-STI also blocks NMIs. See Intel spec. 26.3.1.5 "Checks On Guest Non-Register State". */
7556 if ( !pVCpu->hm.s.Event.fPending
7557 && !fBlockNmi
7558 && !fBlockSti
7559 && !fBlockMovSS)
7560 {
7561 Log4(("Pending NMI vcpu[%RU32]\n", pVCpu->idCpu));
7562 uint32_t u32IntInfo = X86_XCPT_NMI | VMX_EXIT_INTERRUPTION_INFO_VALID;
7563 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7564
7565 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7566 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
7567 }
7568 else
7569 hmR0VmxSetNmiWindowExitVmcs(pVCpu);
7570 }
7571 /*
7572 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
7573 * a valid interrupt we must- deliver the interrupt. We can no longer re-request it from the APIC.
7574 */
7575 else if ( VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC))
7576 && !pVCpu->hm.s.fSingleInstruction)
7577 {
7578 Assert(!DBGFIsStepping(pVCpu));
7579 int rc = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
7580 AssertRC(rc);
7581 bool const fBlockInt = !(pMixedCtx->eflags.u32 & X86_EFL_IF);
7582 if ( !pVCpu->hm.s.Event.fPending
7583 && !fBlockInt
7584 && !fBlockSti
7585 && !fBlockMovSS)
7586 {
7587 uint8_t u8Interrupt;
7588 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
7589 if (RT_SUCCESS(rc))
7590 {
7591 Log4(("Pending interrupt vcpu[%RU32] u8Interrupt=%#x \n", pVCpu->idCpu, u8Interrupt));
7592 uint32_t u32IntInfo = u8Interrupt | VMX_EXIT_INTERRUPTION_INFO_VALID;
7593 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7594
7595 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrfaultAddress */);
7596 }
7597 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
7598 {
7599 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
7600 hmR0VmxApicSetTprThreshold(pVCpu, u8Interrupt >> 4);
7601 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
7602 }
7603 else
7604 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
7605 }
7606 else
7607 hmR0VmxSetIntWindowExitVmcs(pVCpu);
7608 }
7609
7610 return uIntrState;
7611}
7612
7613
7614/**
7615 * Sets a pending-debug exception to be delivered to the guest if the guest is
7616 * single-stepping in the VMCS.
7617 *
7618 * @param pVCpu The cross context virtual CPU structure.
7619 */
7620DECLINLINE(void) hmR0VmxSetPendingDebugXcptVmcs(PVMCPU pVCpu)
7621{
7622 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS)); NOREF(pVCpu);
7623 int rc = VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, VMX_VMCS_GUEST_DEBUG_EXCEPTIONS_BS);
7624 AssertRC(rc);
7625}
7626
7627
7628/**
7629 * Injects any pending events into the guest if the guest is in a state to
7630 * receive them.
7631 *
7632 * @returns Strict VBox status code (i.e. informational status codes too).
7633 * @param pVCpu The cross context virtual CPU structure.
7634 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7635 * out-of-sync. Make sure to update the required fields
7636 * before using them.
7637 * @param uIntrState The VT-x guest-interruptibility state.
7638 * @param fStepping Running in hmR0VmxRunGuestCodeStep() and we should
7639 * return VINF_EM_DBG_STEPPED if the event was
7640 * dispatched directly.
7641 */
7642static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t uIntrState, bool fStepping)
7643{
7644 HMVMX_ASSERT_PREEMPT_SAFE();
7645 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7646
7647 bool fBlockMovSS = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS);
7648 bool fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
7649
7650 Assert(!fBlockSti || HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RFLAGS));
7651 Assert(!(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
7652 Assert(!fBlockSti || pMixedCtx->eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
7653 Assert(!TRPMHasTrap(pVCpu));
7654
7655 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
7656 if (pVCpu->hm.s.Event.fPending)
7657 {
7658 /*
7659 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
7660 * pending even while injecting an event and in this case, we want a VM-exit as soon as
7661 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
7662 *
7663 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
7664 */
7665 uint32_t const uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
7666#ifdef VBOX_STRICT
7667 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
7668 {
7669 bool const fBlockInt = !(pMixedCtx->eflags.u32 & X86_EFL_IF);
7670 Assert(!fBlockInt);
7671 Assert(!fBlockSti);
7672 Assert(!fBlockMovSS);
7673 }
7674 else if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
7675 {
7676 bool const fBlockNmi = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI);
7677 Assert(!fBlockSti);
7678 Assert(!fBlockMovSS);
7679 Assert(!fBlockNmi);
7680 }
7681#endif
7682 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#x\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
7683 (uint8_t)uIntType));
7684 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pMixedCtx, pVCpu->hm.s.Event.u64IntInfo, pVCpu->hm.s.Event.cbInstr,
7685 pVCpu->hm.s.Event.u32ErrCode, pVCpu->hm.s.Event.GCPtrFaultAddress,
7686 fStepping, &uIntrState);
7687 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
7688
7689 /* Update the interruptibility-state as it could have been changed by
7690 hmR0VmxInjectEventVmcs() (e.g. real-on-v86 guest injecting software interrupts) */
7691 fBlockMovSS = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS);
7692 fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
7693
7694 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
7695 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
7696 else
7697 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
7698 }
7699
7700 /* Deliver pending debug exception if the guest is single-stepping. Evaluate and set the BS bit. */
7701 if ( fBlockSti
7702 || fBlockMovSS)
7703 {
7704 if (!pVCpu->hm.s.fSingleInstruction)
7705 {
7706 /*
7707 * The pending-debug exceptions field is cleared on all VM-exits except VMX_EXIT_TPR_BELOW_THRESHOLD,
7708 * VMX_EXIT_MTF, VMX_EXIT_APIC_WRITE and VMX_EXIT_VIRTUALIZED_EOI.
7709 * See Intel spec. 27.3.4 "Saving Non-Register State".
7710 */
7711 Assert(!DBGFIsStepping(pVCpu));
7712 int rc2 = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
7713 AssertRCReturn(rc2, rc2);
7714 if (pMixedCtx->eflags.Bits.u1TF)
7715 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
7716 }
7717 else if (pMixedCtx->eflags.Bits.u1TF)
7718 {
7719 /*
7720 * We are single-stepping in the hypervisor debugger using EFLAGS.TF. Clear interrupt inhibition as setting the
7721 * BS bit would mean delivering a #DB to the guest upon VM-entry when it shouldn't be.
7722 */
7723 Assert(!(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG));
7724 uIntrState = 0;
7725 }
7726 }
7727
7728 /*
7729 * There's no need to clear the VM-entry interruption-information field here if we're not injecting anything.
7730 * VT-x clears the valid bit on every VM-exit. See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
7731 */
7732 int rc2 = hmR0VmxLoadGuestIntrState(pVCpu, uIntrState);
7733 AssertRC(rc2);
7734
7735 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
7736 NOREF(fBlockMovSS); NOREF(fBlockSti);
7737 return rcStrict;
7738}
7739
7740
7741/**
7742 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
7743 *
7744 * @param pVCpu The cross context virtual CPU structure.
7745 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7746 * out-of-sync. Make sure to update the required fields
7747 * before using them.
7748 */
7749DECLINLINE(void) hmR0VmxSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7750{
7751 NOREF(pMixedCtx);
7752 uint32_t u32IntInfo = X86_XCPT_UD | VMX_EXIT_INTERRUPTION_INFO_VALID;
7753 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7754}
7755
7756
7757/**
7758 * Injects a double-fault (\#DF) exception into the VM.
7759 *
7760 * @returns Strict VBox status code (i.e. informational status codes too).
7761 * @param pVCpu The cross context virtual CPU structure.
7762 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7763 * out-of-sync. Make sure to update the required fields
7764 * before using them.
7765 * @param fStepping Whether we're running in hmR0VmxRunGuestCodeStep()
7766 * and should return VINF_EM_DBG_STEPPED if the event
7767 * is injected directly (register modified by us, not
7768 * by hardware on VM-entry).
7769 * @param puIntrState Pointer to the current guest interruptibility-state.
7770 * This interruptibility-state will be updated if
7771 * necessary. This cannot not be NULL.
7772 */
7773DECLINLINE(VBOXSTRICTRC) hmR0VmxInjectXcptDF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fStepping, uint32_t *puIntrState)
7774{
7775 uint32_t u32IntInfo = X86_XCPT_DF | VMX_EXIT_INTERRUPTION_INFO_VALID;
7776 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7777 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
7778 return hmR0VmxInjectEventVmcs(pVCpu, pMixedCtx, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */,
7779 fStepping, puIntrState);
7780}
7781
7782
7783/**
7784 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
7785 *
7786 * @param pVCpu The cross context virtual CPU structure.
7787 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7788 * out-of-sync. Make sure to update the required fields
7789 * before using them.
7790 */
7791DECLINLINE(void) hmR0VmxSetPendingXcptDB(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
7792{
7793 NOREF(pMixedCtx);
7794 uint32_t u32IntInfo = X86_XCPT_DB | VMX_EXIT_INTERRUPTION_INFO_VALID;
7795 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7796 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7797}
7798
7799
7800/**
7801 * Sets an overflow (\#OF) exception as pending-for-injection into the VM.
7802 *
7803 * @param pVCpu The cross context virtual CPU structure.
7804 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7805 * out-of-sync. Make sure to update the required fields
7806 * before using them.
7807 * @param cbInstr The value of RIP that is to be pushed on the guest
7808 * stack.
7809 */
7810DECLINLINE(void) hmR0VmxSetPendingXcptOF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t cbInstr)
7811{
7812 NOREF(pMixedCtx);
7813 uint32_t u32IntInfo = X86_XCPT_OF | VMX_EXIT_INTERRUPTION_INFO_VALID;
7814 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7815 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7816}
7817
7818
7819/**
7820 * Injects a general-protection (\#GP) fault into the VM.
7821 *
7822 * @returns Strict VBox status code (i.e. informational status codes too).
7823 * @param pVCpu The cross context virtual CPU structure.
7824 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7825 * out-of-sync. Make sure to update the required fields
7826 * before using them.
7827 * @param fErrorCodeValid Whether the error code is valid (depends on the CPU
7828 * mode, i.e. in real-mode it's not valid).
7829 * @param u32ErrorCode The error code associated with the \#GP.
7830 * @param fStepping Whether we're running in
7831 * hmR0VmxRunGuestCodeStep() and should return
7832 * VINF_EM_DBG_STEPPED if the event is injected
7833 * directly (register modified by us, not by
7834 * hardware on VM-entry).
7835 * @param puIntrState Pointer to the current guest interruptibility-state.
7836 * This interruptibility-state will be updated if
7837 * necessary. This cannot not be NULL.
7838 */
7839DECLINLINE(VBOXSTRICTRC) hmR0VmxInjectXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, bool fErrorCodeValid, uint32_t u32ErrorCode,
7840 bool fStepping, uint32_t *puIntrState)
7841{
7842 uint32_t u32IntInfo = X86_XCPT_GP | VMX_EXIT_INTERRUPTION_INFO_VALID;
7843 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7844 if (fErrorCodeValid)
7845 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
7846 return hmR0VmxInjectEventVmcs(pVCpu, pMixedCtx, u32IntInfo, 0 /* cbInstr */, u32ErrorCode, 0 /* GCPtrFaultAddress */,
7847 fStepping, puIntrState);
7848}
7849
7850
7851#if 0 /* unused */
7852/**
7853 * Sets a general-protection (\#GP) exception as pending-for-injection into the
7854 * VM.
7855 *
7856 * @param pVCpu The cross context virtual CPU structure.
7857 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7858 * out-of-sync. Make sure to update the required fields
7859 * before using them.
7860 * @param u32ErrorCode The error code associated with the \#GP.
7861 */
7862DECLINLINE(void) hmR0VmxSetPendingXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t u32ErrorCode)
7863{
7864 NOREF(pMixedCtx);
7865 uint32_t u32IntInfo = X86_XCPT_GP | VMX_EXIT_INTERRUPTION_INFO_VALID;
7866 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7867 u32IntInfo |= VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
7868 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrorCode, 0 /* GCPtrFaultAddress */);
7869}
7870#endif /* unused */
7871
7872
7873/**
7874 * Sets a software interrupt (INTn) as pending-for-injection into the VM.
7875 *
7876 * @param pVCpu The cross context virtual CPU structure.
7877 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
7878 * out-of-sync. Make sure to update the required fields
7879 * before using them.
7880 * @param uVector The software interrupt vector number.
7881 * @param cbInstr The value of RIP that is to be pushed on the guest
7882 * stack.
7883 */
7884DECLINLINE(void) hmR0VmxSetPendingIntN(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint16_t uVector, uint32_t cbInstr)
7885{
7886 NOREF(pMixedCtx);
7887 uint32_t u32IntInfo = uVector | VMX_EXIT_INTERRUPTION_INFO_VALID;
7888 if ( uVector == X86_XCPT_BP
7889 || uVector == X86_XCPT_OF)
7890 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7891 else
7892 u32IntInfo |= (VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT << VMX_EXIT_INTERRUPTION_INFO_TYPE_SHIFT);
7893 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7894}
7895
7896
7897/**
7898 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
7899 * stack.
7900 *
7901 * @returns Strict VBox status code (i.e. informational status codes too).
7902 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
7903 * @param pVM The cross context VM structure.
7904 * @param pMixedCtx Pointer to the guest-CPU context.
7905 * @param uValue The value to push to the guest stack.
7906 */
7907DECLINLINE(VBOXSTRICTRC) hmR0VmxRealModeGuestStackPush(PVM pVM, PCPUMCTX pMixedCtx, uint16_t uValue)
7908{
7909 /*
7910 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
7911 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
7912 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
7913 */
7914 if (pMixedCtx->sp == 1)
7915 return VINF_EM_RESET;
7916 pMixedCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
7917 int rc = PGMPhysSimpleWriteGCPhys(pVM, pMixedCtx->ss.u64Base + pMixedCtx->sp, &uValue, sizeof(uint16_t));
7918 AssertRC(rc);
7919 return rc;
7920}
7921
7922
7923/**
7924 * Injects an event into the guest upon VM-entry by updating the relevant fields
7925 * in the VM-entry area in the VMCS.
7926 *
7927 * @returns Strict VBox status code (i.e. informational status codes too).
7928 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
7929 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
7930 *
7931 * @param pVCpu The cross context virtual CPU structure.
7932 * @param pMixedCtx Pointer to the guest-CPU context. The data may
7933 * be out-of-sync. Make sure to update the required
7934 * fields before using them.
7935 * @param u64IntInfo The VM-entry interruption-information field.
7936 * @param cbInstr The VM-entry instruction length in bytes (for
7937 * software interrupts, exceptions and privileged
7938 * software exceptions).
7939 * @param u32ErrCode The VM-entry exception error code.
7940 * @param GCPtrFaultAddress The page-fault address for \#PF exceptions.
7941 * @param puIntrState Pointer to the current guest interruptibility-state.
7942 * This interruptibility-state will be updated if
7943 * necessary. This cannot not be NULL.
7944 * @param fStepping Whether we're running in
7945 * hmR0VmxRunGuestCodeStep() and should return
7946 * VINF_EM_DBG_STEPPED if the event is injected
7947 * directly (register modified by us, not by
7948 * hardware on VM-entry).
7949 *
7950 * @remarks Requires CR0!
7951 * @remarks No-long-jump zone!!!
7952 */
7953static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint64_t u64IntInfo, uint32_t cbInstr,
7954 uint32_t u32ErrCode, RTGCUINTREG GCPtrFaultAddress, bool fStepping,
7955 uint32_t *puIntrState)
7956{
7957 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
7958 AssertMsg(u64IntInfo >> 32 == 0, ("%#RX64\n", u64IntInfo));
7959 Assert(puIntrState);
7960 uint32_t u32IntInfo = (uint32_t)u64IntInfo;
7961
7962 uint32_t const uVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(u32IntInfo);
7963 uint32_t const uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(u32IntInfo);
7964
7965#ifdef VBOX_STRICT
7966 /* Validate the error-code-valid bit for hardware exceptions. */
7967 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT)
7968 {
7969 switch (uVector)
7970 {
7971 case X86_XCPT_PF:
7972 case X86_XCPT_DF:
7973 case X86_XCPT_TS:
7974 case X86_XCPT_NP:
7975 case X86_XCPT_SS:
7976 case X86_XCPT_GP:
7977 case X86_XCPT_AC:
7978 AssertMsg(VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(u32IntInfo),
7979 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
7980 /* fallthru */
7981 default:
7982 break;
7983 }
7984 }
7985#endif
7986
7987 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
7988 Assert( uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI
7989 || !(*puIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS));
7990
7991 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
7992
7993 /* We require CR0 to check if the guest is in real-mode. */
7994 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
7995 AssertRCReturn(rc, rc);
7996
7997 /*
7998 * Hardware interrupts & exceptions cannot be delivered through the software interrupt redirection bitmap to the real
7999 * mode task in virtual-8086 mode. We must jump to the interrupt handler in the (real-mode) guest.
8000 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode" for interrupt & exception classes.
8001 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8002 */
8003 if (CPUMIsGuestInRealModeEx(pMixedCtx))
8004 {
8005 PVM pVM = pVCpu->CTX_SUFF(pVM);
8006 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
8007 {
8008 Assert(PDMVmmDevHeapIsEnabled(pVM));
8009 Assert(pVM->hm.s.vmx.pRealModeTSS);
8010
8011 /* We require RIP, RSP, RFLAGS, CS, IDTR. Save the required ones from the VMCS. */
8012 rc = hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
8013 rc |= hmR0VmxSaveGuestTableRegs(pVCpu, pMixedCtx);
8014 rc |= hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
8015 AssertRCReturn(rc, rc);
8016 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_RIP));
8017
8018 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8019 size_t const cbIdtEntry = sizeof(X86IDTR16);
8020 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pMixedCtx->idtr.cbIdt)
8021 {
8022 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8023 if (uVector == X86_XCPT_DF)
8024 return VINF_EM_RESET;
8025
8026 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault. */
8027 if (uVector == X86_XCPT_GP)
8028 return hmR0VmxInjectXcptDF(pVCpu, pMixedCtx, fStepping, puIntrState);
8029
8030 /* If we're injecting an interrupt/exception with no valid IDT entry, inject a general-protection fault. */
8031 /* No error codes for exceptions in real-mode. See Intel spec. 20.1.4 "Interrupt and Exception Handling" */
8032 return hmR0VmxInjectXcptGP(pVCpu, pMixedCtx, false /* fErrCodeValid */, 0 /* u32ErrCode */,
8033 fStepping, puIntrState);
8034 }
8035
8036 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8037 uint16_t uGuestIp = pMixedCtx->ip;
8038 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT)
8039 {
8040 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8041 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8042 uGuestIp = pMixedCtx->ip + (uint16_t)cbInstr;
8043 }
8044 else if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT)
8045 uGuestIp = pMixedCtx->ip + (uint16_t)cbInstr;
8046
8047 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8048 X86IDTR16 IdtEntry;
8049 RTGCPHYS GCPhysIdtEntry = (RTGCPHYS)pMixedCtx->idtr.pIdt + uVector * cbIdtEntry;
8050 rc = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8051 AssertRCReturn(rc, rc);
8052
8053 /* Construct the stack frame for the interrupt/exception handler. */
8054 VBOXSTRICTRC rcStrict;
8055 rcStrict = hmR0VmxRealModeGuestStackPush(pVM, pMixedCtx, pMixedCtx->eflags.u32);
8056 if (rcStrict == VINF_SUCCESS)
8057 rcStrict = hmR0VmxRealModeGuestStackPush(pVM, pMixedCtx, pMixedCtx->cs.Sel);
8058 if (rcStrict == VINF_SUCCESS)
8059 rcStrict = hmR0VmxRealModeGuestStackPush(pVM, pMixedCtx, uGuestIp);
8060
8061 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8062 if (rcStrict == VINF_SUCCESS)
8063 {
8064 pMixedCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8065 pMixedCtx->rip = IdtEntry.offSel;
8066 pMixedCtx->cs.Sel = IdtEntry.uSel;
8067 pMixedCtx->cs.ValidSel = IdtEntry.uSel;
8068 pMixedCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8069 if ( uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT
8070 && uVector == X86_XCPT_PF)
8071 pMixedCtx->cr2 = GCPtrFaultAddress;
8072
8073 /* If any other guest-state bits are changed here, make sure to update
8074 hmR0VmxPreRunGuestCommitted() when thread-context hooks are used. */
8075 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS
8076 | HM_CHANGED_GUEST_RIP
8077 | HM_CHANGED_GUEST_RFLAGS
8078 | HM_CHANGED_GUEST_RSP);
8079
8080 /* We're clearing interrupts, which means no block-by-STI interrupt-inhibition. */
8081 if (*puIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
8082 {
8083 Assert( uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI
8084 && uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT);
8085 Log4(("Clearing inhibition due to STI.\n"));
8086 *puIntrState &= ~VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI;
8087 }
8088 Log4(("Injecting real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8089 u32IntInfo, u32ErrCode, cbInstr, pMixedCtx->eflags.u, pMixedCtx->cs.Sel, pMixedCtx->eip));
8090
8091 /* The event has been truly dispatched. Mark it as no longer pending so we don't attempt to 'undo'
8092 it, if we are returning to ring-3 before executing guest code. */
8093 pVCpu->hm.s.Event.fPending = false;
8094
8095 /* Make hmR0VmxPreRunGuest return if we're stepping since we've changed cs:rip. */
8096 if (fStepping)
8097 rcStrict = VINF_EM_DBG_STEPPED;
8098 }
8099 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8100 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8101 return rcStrict;
8102 }
8103
8104 /*
8105 * For unrestricted execution enabled CPUs running real-mode guests, we must not set the deliver-error-code bit.
8106 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8107 */
8108 u32IntInfo &= ~VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_VALID;
8109 }
8110
8111 /* Validate. */
8112 Assert(VMX_EXIT_INTERRUPTION_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
8113 Assert(!VMX_EXIT_INTERRUPTION_INFO_NMI_UNBLOCK_IRET(u32IntInfo)); /* Bit 12 MBZ. */
8114 Assert(!(u32IntInfo & 0x7ffff000)); /* Bits 30:12 MBZ. */
8115
8116 /* Inject. */
8117 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
8118 if (VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(u32IntInfo))
8119 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
8120 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
8121
8122 if ( VMX_EXIT_INTERRUPTION_INFO_TYPE(u32IntInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT
8123 && uVector == X86_XCPT_PF)
8124 pMixedCtx->cr2 = GCPtrFaultAddress;
8125
8126 Log4(("Injecting vcpu[%RU32] u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x pMixedCtx->uCR2=%#RX64\n", pVCpu->idCpu,
8127 u32IntInfo, u32ErrCode, cbInstr, pMixedCtx->cr2));
8128
8129 AssertRCReturn(rc, rc);
8130 return VINF_SUCCESS;
8131}
8132
8133
8134/**
8135 * Clears the interrupt-window exiting control in the VMCS and if necessary
8136 * clears the current event in the VMCS as well.
8137 *
8138 * @returns VBox status code.
8139 * @param pVCpu The cross context virtual CPU structure.
8140 *
8141 * @remarks Use this function only to clear events that have not yet been
8142 * delivered to the guest but are injected in the VMCS!
8143 * @remarks No-long-jump zone!!!
8144 */
8145static void hmR0VmxClearIntNmiWindowsVmcs(PVMCPU pVCpu)
8146{
8147 Log4Func(("vcpu[%d]\n", pVCpu->idCpu));
8148
8149 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_INT_WINDOW_EXIT)
8150 hmR0VmxClearIntWindowExitVmcs(pVCpu);
8151
8152 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT)
8153 hmR0VmxClearNmiWindowExitVmcs(pVCpu);
8154}
8155
8156
8157/**
8158 * Enters the VT-x session.
8159 *
8160 * @returns VBox status code.
8161 * @param pVM The cross context VM structure.
8162 * @param pVCpu The cross context virtual CPU structure.
8163 * @param pCpu Pointer to the CPU info struct.
8164 */
8165VMMR0DECL(int) VMXR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
8166{
8167 AssertPtr(pVM);
8168 AssertPtr(pVCpu);
8169 Assert(pVM->hm.s.vmx.fSupported);
8170 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8171 NOREF(pCpu); NOREF(pVM);
8172
8173 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
8174 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
8175
8176#ifdef VBOX_STRICT
8177 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
8178 RTCCUINTREG uHostCR4 = ASMGetCR4();
8179 if (!(uHostCR4 & X86_CR4_VMXE))
8180 {
8181 LogRel(("VMXR0Enter: X86_CR4_VMXE bit in CR4 is not set!\n"));
8182 return VERR_VMX_X86_CR4_VMXE_CLEARED;
8183 }
8184#endif
8185
8186 /*
8187 * Load the VCPU's VMCS as the current (and active) one.
8188 */
8189 Assert(pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_CLEAR);
8190 int rc = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
8191 if (RT_FAILURE(rc))
8192 return rc;
8193
8194 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_ACTIVE;
8195 pVCpu->hm.s.fLeaveDone = false;
8196 Log4Func(("Activated Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8197
8198 return VINF_SUCCESS;
8199}
8200
8201
8202/**
8203 * The thread-context callback (only on platforms which support it).
8204 *
8205 * @param enmEvent The thread-context event.
8206 * @param pVCpu The cross context virtual CPU structure.
8207 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
8208 * @thread EMT(pVCpu)
8209 */
8210VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
8211{
8212 NOREF(fGlobalInit);
8213
8214 switch (enmEvent)
8215 {
8216 case RTTHREADCTXEVENT_OUT:
8217 {
8218 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8219 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8220 VMCPU_ASSERT_EMT(pVCpu);
8221
8222 PCPUMCTX pMixedCtx = CPUMQueryGuestCtxPtr(pVCpu);
8223
8224 /* No longjmps (logger flushes, locks) in this fragile context. */
8225 VMMRZCallRing3Disable(pVCpu);
8226 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
8227
8228 /*
8229 * Restore host-state (FPU, debug etc.)
8230 */
8231 if (!pVCpu->hm.s.fLeaveDone)
8232 {
8233 /* Do -not- save guest-state here as we might already be in the middle of saving it (esp. bad if we are
8234 holding the PGM lock while saving the guest state (see hmR0VmxSaveGuestControlRegs()). */
8235 hmR0VmxLeave(pVCpu, pMixedCtx, false /* fSaveGuestState */);
8236 pVCpu->hm.s.fLeaveDone = true;
8237 }
8238
8239 /* Leave HM context, takes care of local init (term). */
8240 int rc = HMR0LeaveCpu(pVCpu);
8241 AssertRC(rc); NOREF(rc);
8242
8243 /* Restore longjmp state. */
8244 VMMRZCallRing3Enable(pVCpu);
8245 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
8246 break;
8247 }
8248
8249 case RTTHREADCTXEVENT_IN:
8250 {
8251 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8252 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8253 VMCPU_ASSERT_EMT(pVCpu);
8254
8255 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
8256 VMMRZCallRing3Disable(pVCpu);
8257 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
8258
8259 /* Initialize the bare minimum state required for HM. This takes care of
8260 initializing VT-x if necessary (onlined CPUs, local init etc.) */
8261 int rc = HMR0EnterCpu(pVCpu);
8262 AssertRC(rc);
8263 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
8264
8265 /* Load the active VMCS as the current one. */
8266 if (pVCpu->hm.s.vmx.uVmcsState & HMVMX_VMCS_STATE_CLEAR)
8267 {
8268 rc = VMXActivateVmcs(pVCpu->hm.s.vmx.HCPhysVmcs);
8269 AssertRC(rc); NOREF(rc);
8270 pVCpu->hm.s.vmx.uVmcsState = HMVMX_VMCS_STATE_ACTIVE;
8271 Log4Func(("Resumed: Activated Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8272 }
8273 pVCpu->hm.s.fLeaveDone = false;
8274
8275 /* Restore longjmp state. */
8276 VMMRZCallRing3Enable(pVCpu);
8277 break;
8278 }
8279
8280 default:
8281 break;
8282 }
8283}
8284
8285
8286/**
8287 * Saves the host state in the VMCS host-state.
8288 * Sets up the VM-exit MSR-load area.
8289 *
8290 * The CPU state will be loaded from these fields on every successful VM-exit.
8291 *
8292 * @returns VBox status code.
8293 * @param pVM The cross context VM structure.
8294 * @param pVCpu The cross context virtual CPU structure.
8295 *
8296 * @remarks No-long-jump zone!!!
8297 */
8298static int hmR0VmxSaveHostState(PVM pVM, PVMCPU pVCpu)
8299{
8300 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8301
8302 int rc = VINF_SUCCESS;
8303 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_CONTEXT))
8304 {
8305 rc = hmR0VmxSaveHostControlRegs(pVM, pVCpu);
8306 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveHostControlRegisters failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8307
8308 rc = hmR0VmxSaveHostSegmentRegs(pVM, pVCpu);
8309 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveHostSegmentRegisters failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8310
8311 rc = hmR0VmxSaveHostMsrs(pVM, pVCpu);
8312 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSaveHostMsrs failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8313
8314 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT);
8315 }
8316 return rc;
8317}
8318
8319
8320/**
8321 * Saves the host state in the VMCS host-state.
8322 *
8323 * @returns VBox status code.
8324 * @param pVM The cross context VM structure.
8325 * @param pVCpu The cross context virtual CPU structure.
8326 *
8327 * @remarks No-long-jump zone!!!
8328 */
8329VMMR0DECL(int) VMXR0SaveHostState(PVM pVM, PVMCPU pVCpu)
8330{
8331 AssertPtr(pVM);
8332 AssertPtr(pVCpu);
8333
8334 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
8335
8336 /* Save the host state here while entering HM context. When thread-context hooks are used, we might get preempted
8337 and have to resave the host state but most of the time we won't be, so do it here before we disable interrupts. */
8338 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8339 return hmR0VmxSaveHostState(pVM, pVCpu);
8340}
8341
8342
8343/**
8344 * Loads the guest state into the VMCS guest-state area.
8345 *
8346 * The will typically be done before VM-entry when the guest-CPU state and the
8347 * VMCS state may potentially be out of sync.
8348 *
8349 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
8350 * VM-entry controls.
8351 * Sets up the appropriate VMX non-root function to execute guest code based on
8352 * the guest CPU mode.
8353 *
8354 * @returns VBox strict status code.
8355 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
8356 * without unrestricted guest access and the VMMDev is not presently
8357 * mapped (e.g. EFI32).
8358 *
8359 * @param pVM The cross context VM structure.
8360 * @param pVCpu The cross context virtual CPU structure.
8361 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8362 * out-of-sync. Make sure to update the required fields
8363 * before using them.
8364 *
8365 * @remarks No-long-jump zone!!! (Disables and enables long jmps for itself,
8366 * caller disables then again on successfull return. Confusing.)
8367 */
8368static VBOXSTRICTRC hmR0VmxLoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx)
8369{
8370 AssertPtr(pVM);
8371 AssertPtr(pVCpu);
8372 AssertPtr(pMixedCtx);
8373 HMVMX_ASSERT_PREEMPT_SAFE();
8374
8375 VMMRZCallRing3Disable(pVCpu);
8376 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8377
8378 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
8379
8380 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
8381
8382 /* Determine real-on-v86 mode. */
8383 pVCpu->hm.s.vmx.RealMode.fRealOnV86Active = false;
8384 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
8385 && CPUMIsGuestInRealModeEx(pMixedCtx))
8386 {
8387 pVCpu->hm.s.vmx.RealMode.fRealOnV86Active = true;
8388 }
8389
8390 /*
8391 * Load the guest-state into the VMCS.
8392 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
8393 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
8394 */
8395 int rc = hmR0VmxSetupVMRunHandler(pVCpu, pMixedCtx);
8396 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8397
8398 /* This needs to be done after hmR0VmxSetupVMRunHandler() as changing pfnStartVM may require VM-entry control updates. */
8399 rc = hmR0VmxLoadGuestEntryCtls(pVCpu, pMixedCtx);
8400 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestEntryCtls! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8401
8402 /* This needs to be done after hmR0VmxSetupVMRunHandler() as changing pfnStartVM may require VM-exit control updates. */
8403 rc = hmR0VmxLoadGuestExitCtls(pVCpu, pMixedCtx);
8404 AssertLogRelMsgRCReturn(rc, ("hmR0VmxSetupExitCtls failed! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8405
8406 rc = hmR0VmxLoadGuestActivityState(pVCpu, pMixedCtx);
8407 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestActivityState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8408
8409 VBOXSTRICTRC rcStrict = hmR0VmxLoadGuestCR3AndCR4(pVCpu, pMixedCtx);
8410 if (rcStrict == VINF_SUCCESS)
8411 { /* likely */ }
8412 else
8413 {
8414 VMMRZCallRing3Enable(pVCpu);
8415 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
8416 return rcStrict;
8417 }
8418
8419 /* Assumes pMixedCtx->cr0 is up-to-date (strict builds require CR0 for segment register validation checks). */
8420 rc = hmR0VmxLoadGuestSegmentRegs(pVCpu, pMixedCtx);
8421 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestSegmentRegs: rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8422
8423 /* This needs to be done after hmR0VmxLoadGuestEntryCtls() and hmR0VmxLoadGuestExitCtls() as it may alter controls if we
8424 determine we don't have to swap EFER after all. */
8425 rc = hmR0VmxLoadGuestMsrs(pVCpu, pMixedCtx);
8426 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadSharedMsrs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8427
8428 rc = hmR0VmxLoadGuestApicState(pVCpu, pMixedCtx);
8429 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8430
8431 rc = hmR0VmxLoadGuestXcptIntercepts(pVCpu, pMixedCtx);
8432 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestXcptIntercepts! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8433
8434 /*
8435 * Loading Rflags here is fine, even though Rflags.TF might depend on guest debug state (which is not loaded here).
8436 * It is re-evaluated and updated if necessary in hmR0VmxLoadSharedState().
8437 */
8438 rc = hmR0VmxLoadGuestRipRspRflags(pVCpu, pMixedCtx);
8439 AssertLogRelMsgRCReturn(rc, ("hmR0VmxLoadGuestRipRspRflags! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
8440
8441 /* Clear any unused and reserved bits. */
8442 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR2);
8443
8444 VMMRZCallRing3Enable(pVCpu);
8445
8446 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
8447 return rc;
8448}
8449
8450
8451/**
8452 * Loads the state shared between the host and guest into the VMCS.
8453 *
8454 * @param pVM The cross context VM structure.
8455 * @param pVCpu The cross context virtual CPU structure.
8456 * @param pCtx Pointer to the guest-CPU context.
8457 *
8458 * @remarks No-long-jump zone!!!
8459 */
8460static void hmR0VmxLoadSharedState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
8461{
8462 NOREF(pVM);
8463
8464 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8465 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8466
8467 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
8468 {
8469 int rc = hmR0VmxLoadSharedCR0(pVCpu, pCtx);
8470 AssertRC(rc);
8471 }
8472
8473 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
8474 {
8475 int rc = hmR0VmxLoadSharedDebugState(pVCpu, pCtx);
8476 AssertRC(rc);
8477
8478 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
8479 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_RFLAGS))
8480 {
8481 rc = hmR0VmxLoadGuestRflags(pVCpu, pCtx);
8482 AssertRC(rc);
8483 }
8484 }
8485
8486 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS))
8487 {
8488 hmR0VmxLazyLoadGuestMsrs(pVCpu, pCtx);
8489 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
8490 }
8491
8492 /* Loading CR0, debug state might have changed intercepts, update VMCS. */
8493 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
8494 {
8495 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_AC));
8496 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_DB));
8497 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVCpu->hm.s.vmx.u32XcptBitmap);
8498 AssertRC(rc);
8499 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
8500 }
8501
8502 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
8503 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8504}
8505
8506
8507/**
8508 * Worker for loading the guest-state bits in the inner VT-x execution loop.
8509 *
8510 * @returns Strict VBox status code (i.e. informational status codes too).
8511 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
8512 * without unrestricted guest access and the VMMDev is not presently
8513 * mapped (e.g. EFI32).
8514 *
8515 * @param pVM The cross context VM structure.
8516 * @param pVCpu The cross context virtual CPU structure.
8517 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8518 * out-of-sync. Make sure to update the required fields
8519 * before using them.
8520 */
8521static VBOXSTRICTRC hmR0VmxLoadGuestStateOptimal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx)
8522{
8523 HMVMX_ASSERT_PREEMPT_SAFE();
8524
8525 Log5(("LoadFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8526#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
8527 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
8528#endif
8529
8530 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
8531 if (HMCPU_CF_IS_SET_ONLY(pVCpu, HM_CHANGED_GUEST_RIP))
8532 {
8533 rcStrict = hmR0VmxLoadGuestRip(pVCpu, pMixedCtx);
8534 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8535 { /* likely */}
8536 else
8537 {
8538 AssertMsgFailedReturn(("hmR0VmxLoadGuestStateOptimal: hmR0VmxLoadGuestRip failed! rc=%Rrc\n",
8539 VBOXSTRICTRC_VAL(rcStrict)), rcStrict);
8540 }
8541 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadMinimal);
8542 }
8543 else if (HMCPU_CF_VALUE(pVCpu))
8544 {
8545 rcStrict = hmR0VmxLoadGuestState(pVM, pVCpu, pMixedCtx);
8546 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8547 { /* likely */}
8548 else
8549 {
8550 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM,
8551 ("hmR0VmxLoadGuestStateOptimal: hmR0VmxLoadGuestState failed! rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8552 return rcStrict;
8553 }
8554 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
8555 }
8556
8557 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
8558 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
8559 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
8560 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8561 return rcStrict;
8562}
8563
8564
8565/**
8566 * Does the preparations before executing guest code in VT-x.
8567 *
8568 * This may cause longjmps to ring-3 and may even result in rescheduling to the
8569 * recompiler/IEM. We must be cautious what we do here regarding committing
8570 * guest-state information into the VMCS assuming we assuredly execute the
8571 * guest in VT-x mode.
8572 *
8573 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
8574 * the common-state (TRPM/forceflags), we must undo those changes so that the
8575 * recompiler/IEM can (and should) use them when it resumes guest execution.
8576 * Otherwise such operations must be done when we can no longer exit to ring-3.
8577 *
8578 * @returns Strict VBox status code (i.e. informational status codes too).
8579 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
8580 * have been disabled.
8581 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
8582 * double-fault into the guest.
8583 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
8584 * dispatched directly.
8585 * @retval VINF_* scheduling changes, we have to go back to ring-3.
8586 *
8587 * @param pVM The cross context VM structure.
8588 * @param pVCpu The cross context virtual CPU structure.
8589 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8590 * out-of-sync. Make sure to update the required fields
8591 * before using them.
8592 * @param pVmxTransient Pointer to the VMX transient structure.
8593 * @param fStepping Set if called from hmR0VmxRunGuestCodeStep(). Makes
8594 * us ignore some of the reasons for returning to
8595 * ring-3, and return VINF_EM_DBG_STEPPED if event
8596 * dispatching took place.
8597 */
8598static VBOXSTRICTRC hmR0VmxPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, bool fStepping)
8599{
8600 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8601
8602#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
8603 PGMRZDynMapFlushAutoSet(pVCpu);
8604#endif
8605
8606 /* Check force flag actions that might require us to go back to ring-3. */
8607 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVM, pVCpu, pMixedCtx, fStepping);
8608 if (rcStrict == VINF_SUCCESS)
8609 { /* FFs doesn't get set all the time. */ }
8610 else
8611 return rcStrict;
8612
8613#ifndef IEM_VERIFICATION_MODE_FULL
8614 /* Setup the Virtualized APIC accesses. pMixedCtx->msrApicBase is always up-to-date. It's not part of the VMCS. */
8615 if ( pVCpu->hm.s.vmx.u64MsrApicBase != pMixedCtx->msrApicBase
8616 && (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_VIRT_APIC))
8617 {
8618 Assert(pVM->hm.s.vmx.HCPhysApicAccess);
8619 RTGCPHYS GCPhysApicBase;
8620 GCPhysApicBase = pMixedCtx->msrApicBase;
8621 GCPhysApicBase &= PAGE_BASE_GC_MASK;
8622
8623 /* Unalias any existing mapping. */
8624 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
8625 AssertRCReturn(rc, rc);
8626
8627 /* Map the HC APIC-access page into the GC space, this also updates the shadow page tables if necessary. */
8628 Log4(("Mapped HC APIC-access page into GC: GCPhysApicBase=%#RGp\n", GCPhysApicBase));
8629 rc = IOMMMIOMapMMIOHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hm.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
8630 AssertRCReturn(rc, rc);
8631
8632 pVCpu->hm.s.vmx.u64MsrApicBase = pMixedCtx->msrApicBase;
8633 }
8634#endif /* !IEM_VERIFICATION_MODE_FULL */
8635
8636 if (TRPMHasTrap(pVCpu))
8637 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
8638 uint32_t uIntrState = hmR0VmxEvaluatePendingEvent(pVCpu, pMixedCtx);
8639
8640 /*
8641 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus needs to be done with
8642 * longjmps or interrupts + preemption enabled. Event injection might also result in triple-faulting the VM.
8643 */
8644 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pMixedCtx, uIntrState, fStepping);
8645 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8646 { /* likely */ }
8647 else
8648 {
8649 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8650 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8651 return rcStrict;
8652 }
8653
8654 /*
8655 * Load the guest state bits, we can handle longjmps/getting preempted here.
8656 *
8657 * If we are injecting events to a real-on-v86 mode guest, we will have to update
8658 * RIP and some segment registers, i.e. hmR0VmxInjectPendingEvent()->hmR0VmxInjectEventVmcs().
8659 * Hence, this needs to be done -after- injection of events.
8660 */
8661 rcStrict = hmR0VmxLoadGuestStateOptimal(pVM, pVCpu, pMixedCtx);
8662 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
8663 { /* likely */ }
8664 else
8665 return rcStrict;
8666
8667 /*
8668 * No longjmps to ring-3 from this point on!!!
8669 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
8670 * This also disables flushing of the R0-logger instance (if any).
8671 */
8672 VMMRZCallRing3Disable(pVCpu);
8673
8674 /*
8675 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
8676 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
8677 *
8678 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
8679 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
8680 *
8681 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
8682 * executing guest code.
8683 */
8684 pVmxTransient->fEFlags = ASMIntDisableFlags();
8685
8686 if ( ( !VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
8687 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
8688 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
8689 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
8690 {
8691 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
8692 {
8693 /* We've injected any pending events. This is really the point of no return (to ring-3). */
8694 pVCpu->hm.s.Event.fPending = false;
8695
8696 return VINF_SUCCESS;
8697 }
8698
8699 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
8700 rcStrict = VINF_EM_RAW_INTERRUPT;
8701 }
8702 else
8703 {
8704 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
8705 rcStrict = VINF_EM_RAW_TO_R3;
8706 }
8707
8708 ASMSetFlags(pVmxTransient->fEFlags);
8709 VMMRZCallRing3Enable(pVCpu);
8710
8711 return rcStrict;
8712}
8713
8714
8715/**
8716 * Prepares to run guest code in VT-x and we've committed to doing so. This
8717 * means there is no backing out to ring-3 or anywhere else at this
8718 * point.
8719 *
8720 * @param pVM The cross context VM structure.
8721 * @param pVCpu The cross context virtual CPU structure.
8722 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
8723 * out-of-sync. Make sure to update the required fields
8724 * before using them.
8725 * @param pVmxTransient Pointer to the VMX transient structure.
8726 *
8727 * @remarks Called with preemption disabled.
8728 * @remarks No-long-jump zone!!!
8729 */
8730static void hmR0VmxPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
8731{
8732 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8733 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8734 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8735
8736 /*
8737 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
8738 */
8739 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
8740 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
8741
8742#ifdef HMVMX_ALWAYS_SWAP_FPU_STATE
8743 if (!CPUMIsGuestFPUStateActive(pVCpu))
8744 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
8745 HMCPU_CF_SET(pVCpu, HM_CHANGED_HOST_CONTEXT);
8746 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
8747#endif
8748
8749 if ( pVCpu->hm.s.fPreloadGuestFpu
8750 && !CPUMIsGuestFPUStateActive(pVCpu))
8751 {
8752 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
8753 HMCPU_CF_SET(pVCpu, HM_CHANGED_HOST_CONTEXT);
8754 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_CR0));
8755 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
8756 }
8757
8758 /*
8759 * Lazy-update of the host MSRs values in the auto-load/store MSR area.
8760 */
8761 if ( !pVCpu->hm.s.vmx.fUpdatedHostMsrs
8762 && pVCpu->hm.s.vmx.cMsrs > 0)
8763 {
8764 hmR0VmxUpdateAutoLoadStoreHostMsrs(pVCpu);
8765 }
8766
8767 /*
8768 * Load the host state bits as we may've been preempted (only happens when
8769 * thread-context hooks are used or when hmR0VmxSetupVMRunHandler() changes pfnStartVM).
8770 * Note that the 64-on-32 switcher saves the (64-bit) host state into the VMCS and
8771 * if we change the switcher back to 32-bit, we *must* save the 32-bit host state here.
8772 * See @bugref{8432}.
8773 */
8774 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_CONTEXT))
8775 {
8776 int rc = hmR0VmxSaveHostState(pVM, pVCpu);
8777 AssertRC(rc);
8778 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreemptSaveHostState);
8779 }
8780 Assert(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_CONTEXT));
8781
8782 /*
8783 * Load the state shared between host and guest (FPU, debug, lazy MSRs).
8784 */
8785 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
8786 hmR0VmxLoadSharedState(pVM, pVCpu, pMixedCtx);
8787 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
8788
8789 /* Store status of the shared guest-host state at the time of VM-entry. */
8790#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
8791 if (CPUMIsGuestInLongModeEx(pMixedCtx))
8792 {
8793 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
8794 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
8795 }
8796 else
8797#endif
8798 {
8799 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
8800 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
8801 }
8802 pVmxTransient->fWasGuestFPUStateActive = CPUMIsGuestFPUStateActive(pVCpu);
8803
8804 /*
8805 * Cache the TPR-shadow for checking on every VM-exit if it might have changed.
8806 */
8807 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
8808 pVmxTransient->u8GuestTpr = pVCpu->hm.s.vmx.pbVirtApic[0x80];
8809
8810 PHMGLOBALCPUINFO pCpu = HMR0GetCurrentCpu();
8811 RTCPUID idCurrentCpu = pCpu->idCpu;
8812 if ( pVmxTransient->fUpdateTscOffsettingAndPreemptTimer
8813 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
8814 {
8815 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVM, pVCpu);
8816 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = false;
8817 }
8818
8819 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
8820 hmR0VmxFlushTaggedTlb(pVCpu, pCpu); /* Invalidate the appropriate guest entries from the TLB. */
8821 Assert(idCurrentCpu == pVCpu->hm.s.idLastCpu);
8822 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Update the error reporting info. with the current host CPU. */
8823
8824 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
8825
8826 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
8827 to start executing. */
8828
8829 /*
8830 * Load the TSC_AUX MSR when we are not intercepting RDTSCP.
8831 */
8832 if (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_RDTSCP)
8833 {
8834 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT))
8835 {
8836 bool fMsrUpdated;
8837 int rc2 = hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
8838 AssertRC(rc2);
8839 Assert(HMVMXCPU_GST_IS_UPDATED(pVCpu, HMVMX_UPDATED_GUEST_AUTO_LOAD_STORE_MSRS));
8840
8841 rc2 = hmR0VmxAddAutoLoadStoreMsr(pVCpu, MSR_K8_TSC_AUX, CPUMR0GetGuestTscAux(pVCpu), true /* fUpdateHostMsr */,
8842 &fMsrUpdated);
8843 AssertRC(rc2);
8844 Assert(fMsrUpdated || pVCpu->hm.s.vmx.fUpdatedHostMsrs);
8845
8846 /* Finally, mark that all host MSR values are updated so we don't redo it without leaving VT-x. See @bugref{6956}. */
8847 pVCpu->hm.s.vmx.fUpdatedHostMsrs = true;
8848 }
8849 else
8850 {
8851 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, MSR_K8_TSC_AUX);
8852 Assert(!pVCpu->hm.s.vmx.cMsrs || pVCpu->hm.s.vmx.fUpdatedHostMsrs);
8853 }
8854 }
8855
8856#ifdef VBOX_STRICT
8857 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu);
8858 hmR0VmxCheckHostEferMsr(pVCpu);
8859 AssertRC(hmR0VmxCheckVmcsCtls(pVCpu));
8860#endif
8861#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
8862 uint32_t uInvalidReason = hmR0VmxCheckGuestState(pVM, pVCpu, pMixedCtx);
8863 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
8864 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
8865#endif
8866}
8867
8868
8869/**
8870 * Performs some essential restoration of state after running guest code in
8871 * VT-x.
8872 *
8873 * @param pVM The cross context VM structure.
8874 * @param pVCpu The cross context virtual CPU structure.
8875 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
8876 * out-of-sync. Make sure to update the required fields
8877 * before using them.
8878 * @param pVmxTransient Pointer to the VMX transient structure.
8879 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
8880 *
8881 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
8882 *
8883 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
8884 * unconditionally when it is safe to do so.
8885 */
8886static void hmR0VmxPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, int rcVMRun)
8887{
8888 NOREF(pVM);
8889
8890 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8891
8892 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
8893 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
8894 HMVMXCPU_GST_RESET_TO(pVCpu, 0); /* Exits/longjmps to ring-3 requires saving the guest state. */
8895 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
8896 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
8897 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
8898
8899 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT))
8900 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVCpu->hm.s.vmx.u64TSCOffset);
8901
8902 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
8903 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
8904 Assert(!ASMIntAreEnabled());
8905 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
8906
8907#ifdef HMVMX_ALWAYS_SWAP_FPU_STATE
8908 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVM, pVCpu))
8909 {
8910 hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
8911 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
8912 }
8913#endif
8914
8915#if HC_ARCH_BITS == 64
8916 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Host state messed up by VT-x, we must restore. */
8917#endif
8918#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
8919 /* The 64-on-32 switcher maintains uVmcsState on its own and we need to leave it alone here. */
8920 if (pVCpu->hm.s.vmx.pfnStartVM != VMXR0SwitcherStartVM64)
8921 pVCpu->hm.s.vmx.uVmcsState |= HMVMX_VMCS_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
8922#else
8923 pVCpu->hm.s.vmx.uVmcsState |= HMVMX_VMCS_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
8924#endif
8925#ifdef VBOX_STRICT
8926 hmR0VmxCheckHostEferMsr(pVCpu); /* Verify that VMRUN/VMLAUNCH didn't modify host EFER. */
8927#endif
8928 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
8929 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
8930
8931 /* Save the basic VM-exit reason. Refer Intel spec. 24.9.1 "Basic VM-exit Information". */
8932 uint32_t uExitReason;
8933 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
8934 rc |= hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
8935 AssertRC(rc);
8936 pVmxTransient->uExitReason = (uint16_t)VMX_EXIT_REASON_BASIC(uExitReason);
8937 pVmxTransient->fVMEntryFailed = VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uEntryIntInfo);
8938
8939 /* Update the VM-exit history array. */
8940 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmxTransient->uExitReason);
8941
8942 /* If the VMLAUNCH/VMRESUME failed, we can bail out early. This does -not- cover VMX_EXIT_ERR_*. */
8943 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
8944 {
8945 Log4(("VM-entry failure: pVCpu=%p idCpu=%RU32 rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", pVCpu, pVCpu->idCpu, rcVMRun,
8946 pVmxTransient->fVMEntryFailed));
8947 return;
8948 }
8949
8950 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
8951 {
8952 /** @todo We can optimize this by only syncing with our force-flags when
8953 * really needed and keeping the VMCS state as it is for most
8954 * VM-exits. */
8955 /* Update the guest interruptibility-state from the VMCS. */
8956 hmR0VmxSaveGuestIntrState(pVCpu, pMixedCtx);
8957
8958#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
8959 rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
8960 AssertRC(rc);
8961#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
8962 rc = hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
8963 AssertRC(rc);
8964#endif
8965
8966 /*
8967 * If the TPR was raised by the guest, it wouldn't cause a VM-exit immediately. Instead we sync the TPR lazily whenever
8968 * we eventually get a VM-exit for any reason. This maybe expensive as PDMApicSetTPR() can longjmp to ring-3 and which is
8969 * why it's done here as it's easier and no less efficient to deal with it here than making hmR0VmxSaveGuestState()
8970 * cope with longjmps safely (see VMCPU_FF_HM_UPDATE_CR3 handling).
8971 */
8972 if ( (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
8973 && pVmxTransient->u8GuestTpr != pVCpu->hm.s.vmx.pbVirtApic[0x80])
8974 {
8975 rc = PDMApicSetTPR(pVCpu, pVCpu->hm.s.vmx.pbVirtApic[0x80]);
8976 AssertRC(rc);
8977 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
8978 }
8979 }
8980}
8981
8982
8983/**
8984 * Runs the guest code using VT-x the normal way.
8985 *
8986 * @returns VBox status code.
8987 * @param pVM The cross context VM structure.
8988 * @param pVCpu The cross context virtual CPU structure.
8989 * @param pCtx Pointer to the guest-CPU context.
8990 *
8991 * @note Mostly the same as hmR0VmxRunGuestCodeStep().
8992 */
8993static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
8994{
8995 VMXTRANSIENT VmxTransient;
8996 VmxTransient.fUpdateTscOffsettingAndPreemptTimer = true;
8997 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
8998 uint32_t cLoops = 0;
8999
9000 for (;; cLoops++)
9001 {
9002 Assert(!HMR0SuspendPending());
9003 HMVMX_ASSERT_CPU_SAFE();
9004
9005 /* Preparatory work for running guest code, this may force us to return
9006 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
9007 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
9008 rcStrict = hmR0VmxPreRunGuest(pVM, pVCpu, pCtx, &VmxTransient, false /* fStepping */);
9009 if (rcStrict != VINF_SUCCESS)
9010 break;
9011
9012 hmR0VmxPreRunGuestCommitted(pVM, pVCpu, pCtx, &VmxTransient);
9013 int rcRun = hmR0VmxRunGuest(pVM, pVCpu, pCtx);
9014 /* The guest-CPU context is now outdated, 'pCtx' is to be treated as 'pMixedCtx' from this point on!!! */
9015
9016 /* Restore any residual host-state and save any bits shared between host
9017 and guest into the guest-CPU state. Re-enables interrupts! */
9018 hmR0VmxPostRunGuest(pVM, pVCpu, pCtx, &VmxTransient, VBOXSTRICTRC_TODO(rcStrict));
9019
9020 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
9021 if (RT_SUCCESS(rcRun))
9022 { /* very likely */ }
9023 else
9024 {
9025 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
9026 hmR0VmxReportWorldSwitchError(pVM, pVCpu, rcRun, pCtx, &VmxTransient);
9027 return rcRun;
9028 }
9029
9030 /* Profile the VM-exit. */
9031 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
9032 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
9033 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
9034 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
9035 HMVMX_START_EXIT_DISPATCH_PROF();
9036
9037 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, pCtx, VmxTransient.uExitReason);
9038
9039 /* Handle the VM-exit. */
9040#ifdef HMVMX_USE_FUNCTION_TABLE
9041 rcStrict = g_apfnVMExitHandlers[VmxTransient.uExitReason](pVCpu, pCtx, &VmxTransient);
9042#else
9043 rcStrict = hmR0VmxHandleExit(pVCpu, pCtx, &VmxTransient, VmxTransient.uExitReason);
9044#endif
9045 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
9046 if (rcStrict == VINF_SUCCESS)
9047 {
9048 if (cLoops <= pVM->hm.s.cMaxResumeLoops)
9049 continue; /* likely */
9050 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
9051 rcStrict = VINF_EM_RAW_INTERRUPT;
9052 }
9053 break;
9054 }
9055
9056 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
9057 return rcStrict;
9058}
9059
9060
9061
9062/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
9063 * probes.
9064 *
9065 * The following few functions and associated structure contains the bloat
9066 * necessary for providing detailed debug events and dtrace probes as well as
9067 * reliable host side single stepping. This works on the principle of
9068 * "subclassing" the normal execution loop and workers. We replace the loop
9069 * method completely and override selected helpers to add necessary adjustments
9070 * to their core operation.
9071 *
9072 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
9073 * any performance for debug and analysis features.
9074 *
9075 * @{
9076 */
9077
9078typedef struct VMXRUNDBGSTATE
9079{
9080 /** The RIP we started executing at. This is for detecting that we stepped. */
9081 uint64_t uRipStart;
9082 /** The CS we started executing with. */
9083 uint16_t uCsStart;
9084
9085 /** Whether we've actually modified the 1st execution control field. */
9086 bool fModifiedProcCtls : 1;
9087 /** Whether we've actually modified the 2nd execution control field. */
9088 bool fModifiedProcCtls2 : 1;
9089 /** Whether we've actually modified the exception bitmap. */
9090 bool fModifiedXcptBitmap : 1;
9091
9092 /** We desire the modified the CR0 mask to be cleared. */
9093 bool fClearCr0Mask : 1;
9094 /** We desire the modified the CR4 mask to be cleared. */
9095 bool fClearCr4Mask : 1;
9096 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
9097 uint32_t fCpe1Extra;
9098 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
9099 uint32_t fCpe1Unwanted;
9100 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
9101 uint32_t fCpe2Extra;
9102 /** Extra stuff we need in */
9103 uint32_t bmXcptExtra;
9104 /** The sequence number of the Dtrace provider settings the state was
9105 * configured against. */
9106 uint32_t uDtraceSettingsSeqNo;
9107 /** Exits to check (one bit per exit). */
9108 uint32_t bmExitsToCheck[3];
9109
9110 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
9111 uint32_t fProcCtlsInitial;
9112 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
9113 uint32_t fProcCtls2Initial;
9114 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
9115 uint32_t bmXcptInitial;
9116} VMXRUNDBGSTATE;
9117AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
9118typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
9119
9120
9121/**
9122 * Initializes the VMXRUNDBGSTATE structure.
9123 *
9124 * @param pVCpu The cross context virtual CPU structure of the
9125 * calling EMT.
9126 * @param pCtx The CPU register context to go with @a pVCpu.
9127 * @param pDbgState The structure to initialize.
9128 */
9129DECLINLINE(void) hmR0VmxRunDebugStateInit(PVMCPU pVCpu, PCCPUMCTX pCtx, PVMXRUNDBGSTATE pDbgState)
9130{
9131 pDbgState->uRipStart = pCtx->rip;
9132 pDbgState->uCsStart = pCtx->cs.Sel;
9133
9134 pDbgState->fModifiedProcCtls = false;
9135 pDbgState->fModifiedProcCtls2 = false;
9136 pDbgState->fModifiedXcptBitmap = false;
9137 pDbgState->fClearCr0Mask = false;
9138 pDbgState->fClearCr4Mask = false;
9139 pDbgState->fCpe1Extra = 0;
9140 pDbgState->fCpe1Unwanted = 0;
9141 pDbgState->fCpe2Extra = 0;
9142 pDbgState->bmXcptExtra = 0;
9143 pDbgState->fProcCtlsInitial = pVCpu->hm.s.vmx.u32ProcCtls;
9144 pDbgState->fProcCtls2Initial = pVCpu->hm.s.vmx.u32ProcCtls2;
9145 pDbgState->bmXcptInitial = pVCpu->hm.s.vmx.u32XcptBitmap;
9146}
9147
9148
9149/**
9150 * Updates the VMSC fields with changes requested by @a pDbgState.
9151 *
9152 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
9153 * immediately before executing guest code, i.e. when interrupts are disabled.
9154 * We don't check status codes here as we cannot easily assert or return in the
9155 * latter case.
9156 *
9157 * @param pVCpu The cross context virtual CPU structure.
9158 * @param pDbgState The debug state.
9159 */
9160DECLINLINE(void) hmR0VmxPreRunGuestDebugStateApply(PVMCPU pVCpu, PVMXRUNDBGSTATE pDbgState)
9161{
9162 /*
9163 * Ensure desired flags in VMCS control fields are set.
9164 * (Ignoring write failure here, as we're committed and it's just debug extras.)
9165 *
9166 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
9167 * there should be no stale data in pCtx at this point.
9168 */
9169 if ( (pVCpu->hm.s.vmx.u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
9170 || (pVCpu->hm.s.vmx.u32ProcCtls & pDbgState->fCpe1Unwanted))
9171 {
9172 pVCpu->hm.s.vmx.u32ProcCtls |= pDbgState->fCpe1Extra;
9173 pVCpu->hm.s.vmx.u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
9174 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
9175 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVCpu->hm.s.vmx.u32ProcCtls));
9176 pDbgState->fModifiedProcCtls = true;
9177 }
9178
9179 if ((pVCpu->hm.s.vmx.u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
9180 {
9181 pVCpu->hm.s.vmx.u32ProcCtls2 |= pDbgState->fCpe2Extra;
9182 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVCpu->hm.s.vmx.u32ProcCtls2);
9183 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVCpu->hm.s.vmx.u32ProcCtls2));
9184 pDbgState->fModifiedProcCtls2 = true;
9185 }
9186
9187 if ((pVCpu->hm.s.vmx.u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
9188 {
9189 pVCpu->hm.s.vmx.u32XcptBitmap |= pDbgState->bmXcptExtra;
9190 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVCpu->hm.s.vmx.u32XcptBitmap);
9191 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVCpu->hm.s.vmx.u32XcptBitmap));
9192 pDbgState->fModifiedXcptBitmap = true;
9193 }
9194
9195 if (pDbgState->fClearCr0Mask && pVCpu->hm.s.vmx.u32CR0Mask != 0)
9196 {
9197 pVCpu->hm.s.vmx.u32CR0Mask = 0;
9198 VMXWriteVmcs32(VMX_VMCS_CTRL_CR0_MASK, 0);
9199 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS_CTRL_CR0_MASK: 0\n"));
9200 }
9201
9202 if (pDbgState->fClearCr4Mask && pVCpu->hm.s.vmx.u32CR4Mask != 0)
9203 {
9204 pVCpu->hm.s.vmx.u32CR4Mask = 0;
9205 VMXWriteVmcs32(VMX_VMCS_CTRL_CR4_MASK, 0);
9206 Log6(("hmR0VmxRunDebugStateRevert: VMX_VMCS_CTRL_CR4_MASK: 0\n"));
9207 }
9208}
9209
9210
9211DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugStateRevert(PVMCPU pVCpu, PVMXRUNDBGSTATE pDbgState, VBOXSTRICTRC rcStrict)
9212{
9213 /*
9214 * Restore exit control settings as we may not reenter this function the
9215 * next time around.
9216 */
9217 /* We reload the initial value, trigger what we can of recalculations the
9218 next time around. From the looks of things, that's all that's required atm. */
9219 if (pDbgState->fModifiedProcCtls)
9220 {
9221 if (!(pDbgState->fProcCtlsInitial & VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
9222 pDbgState->fProcCtlsInitial |= VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
9223 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
9224 AssertRCReturn(rc2, rc2);
9225 pVCpu->hm.s.vmx.u32ProcCtls = pDbgState->fProcCtlsInitial;
9226 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0 | HM_CHANGED_GUEST_DEBUG);
9227 }
9228
9229 /* We're currently the only ones messing with this one, so just restore the
9230 cached value and reload the field. */
9231 if ( pDbgState->fModifiedProcCtls2
9232 && pVCpu->hm.s.vmx.u32ProcCtls2 != pDbgState->fProcCtls2Initial)
9233 {
9234 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
9235 AssertRCReturn(rc2, rc2);
9236 pVCpu->hm.s.vmx.u32ProcCtls2 = pDbgState->fProcCtls2Initial;
9237 }
9238
9239 /* If we've modified the exception bitmap, we restore it and trigger
9240 reloading and partial recalculation the next time around. */
9241 if (pDbgState->fModifiedXcptBitmap)
9242 {
9243 pVCpu->hm.s.vmx.u32XcptBitmap = pDbgState->bmXcptInitial;
9244 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS | HM_CHANGED_GUEST_CR0);
9245 }
9246
9247 /* We assume hmR0VmxLoadSharedCR0 will recalculate and load the CR0 mask. */
9248 if (pDbgState->fClearCr0Mask)
9249 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9250
9251 /* We assume hmR0VmxLoadGuestCR3AndCR4 will recalculate and load the CR4 mask. */
9252 if (pDbgState->fClearCr4Mask)
9253 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
9254
9255 return rcStrict;
9256}
9257
9258
9259/**
9260 * Configures VM-exit controls for current DBGF and DTrace settings.
9261 *
9262 * This updates @a pDbgState and the VMCS execution control fields to reflect
9263 * the necessary exits demanded by DBGF and DTrace.
9264 *
9265 * @param pVM The cross context VM structure.
9266 * @param pVCpu The cross context virtual CPU structure.
9267 * @param pCtx Pointer to the guest-CPU context.
9268 * @param pDbgState The debug state.
9269 * @param pVmxTransient Pointer to the VMX transient structure. May update
9270 * fUpdateTscOffsettingAndPreemptTimer.
9271 */
9272static void hmR0VmxPreRunGuestDebugStateUpdate(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx,
9273 PVMXRUNDBGSTATE pDbgState, PVMXTRANSIENT pVmxTransient)
9274{
9275 /*
9276 * Take down the dtrace serial number so we can spot changes.
9277 */
9278 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
9279 ASMCompilerBarrier();
9280
9281 /*
9282 * We'll rebuild most of the middle block of data members (holding the
9283 * current settings) as we go along here, so start by clearing it all.
9284 */
9285 pDbgState->bmXcptExtra = 0;
9286 pDbgState->fCpe1Extra = 0;
9287 pDbgState->fCpe1Unwanted = 0;
9288 pDbgState->fCpe2Extra = 0;
9289 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
9290 pDbgState->bmExitsToCheck[i] = 0;
9291
9292 /*
9293 * Software interrupts (INT XXh) - no idea how to trigger these...
9294 */
9295 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
9296 || VBOXVMM_INT_SOFTWARE_ENABLED())
9297 {
9298 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
9299 }
9300
9301 /*
9302 * Exception bitmap and XCPT events+probes.
9303 */
9304 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
9305 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
9306 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
9307
9308 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
9309 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
9310 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
9311 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
9312 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
9313 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
9314 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
9315 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
9316 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
9317 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
9318 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
9319 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
9320 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
9321 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
9322 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
9323 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
9324 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
9325 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
9326
9327 if (pDbgState->bmXcptExtra)
9328 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
9329
9330 /*
9331 * Process events and probes for VM exits, making sure we get the wanted exits.
9332 *
9333 * Note! This is the reverse of waft hmR0VmxHandleExitDtraceEvents does.
9334 * So, when adding/changing/removing please don't forget to update it.
9335 *
9336 * Some of the macros are picking up local variables to save horizontal space,
9337 * (being able to see it in a table is the lesser evil here).
9338 */
9339#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
9340 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
9341 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
9342#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
9343 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9344 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9345 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9346 } else do { } while (0)
9347#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
9348 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9349 { \
9350 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
9351 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9352 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9353 } else do { } while (0)
9354#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
9355 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9356 { \
9357 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
9358 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9359 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9360 } else do { } while (0)
9361#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
9362 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
9363 { \
9364 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
9365 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
9366 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
9367 } else do { } while (0)
9368
9369 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
9370 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
9371 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
9372 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
9373 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
9374
9375 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
9376 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
9377 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
9378 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
9379 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT); /* paranoia */
9380 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
9381 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
9382 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
9383 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT);
9384 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
9385 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_VMCS_CTRL_PROC_EXEC_RDPMC_EXIT);
9386 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
9387 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT);
9388 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
9389 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
9390 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
9391 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
9392 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
9393 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
9394 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
9395 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
9396 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
9397 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
9398 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
9399 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
9400 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
9401 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
9402 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
9403 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
9404 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
9405 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
9406 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
9407 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
9408 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
9409 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
9410 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
9411
9412 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
9413 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
9414 {
9415 int rc2 = hmR0VmxSaveGuestCR0(pVCpu, pCtx);
9416 rc2 |= hmR0VmxSaveGuestCR4(pVCpu, pCtx);
9417 rc2 |= hmR0VmxSaveGuestApicState(pVCpu, pCtx);
9418 AssertRC(rc2);
9419
9420#if 0 /** @todo fix me */
9421 pDbgState->fClearCr0Mask = true;
9422 pDbgState->fClearCr4Mask = true;
9423#endif
9424 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
9425 pDbgState->fCpe1Extra |= VMX_VMCS_CTRL_PROC_EXEC_CR3_STORE_EXIT | VMX_VMCS_CTRL_PROC_EXEC_CR8_STORE_EXIT;
9426 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
9427 pDbgState->fCpe1Extra |= VMX_VMCS_CTRL_PROC_EXEC_CR3_LOAD_EXIT | VMX_VMCS_CTRL_PROC_EXEC_CR8_LOAD_EXIT;
9428 pDbgState->fCpe1Unwanted |= VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW; /* risky? */
9429 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
9430 require clearing here and in the loop if we start using it. */
9431 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
9432 }
9433 else
9434 {
9435 if (pDbgState->fClearCr0Mask)
9436 {
9437 pDbgState->fClearCr0Mask = false;
9438 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
9439 }
9440 if (pDbgState->fClearCr4Mask)
9441 {
9442 pDbgState->fClearCr4Mask = false;
9443 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
9444 }
9445 }
9446 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
9447 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
9448
9449 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
9450 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
9451 {
9452 /** @todo later, need to fix handler as it assumes this won't usually happen. */
9453 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
9454 }
9455 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
9456 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
9457
9458 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS); /* risky clearing this? */
9459 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
9460 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS);
9461 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
9462 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_VMCS_CTRL_PROC_EXEC_MWAIT_EXIT); /* paranoia */
9463 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
9464 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_VMCS_CTRL_PROC_EXEC_MONITOR_EXIT); /* paranoia */
9465 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
9466#if 0 /** @todo too slow, fix handler. */
9467 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_VMCS_CTRL_PROC_EXEC_PAUSE_EXIT);
9468#endif
9469 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
9470
9471 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
9472 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
9473 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
9474 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
9475 {
9476 pDbgState->fCpe2Extra |= VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT;
9477 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XDTR_ACCESS);
9478 }
9479 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_XDTR_ACCESS);
9480 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_XDTR_ACCESS);
9481 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_XDTR_ACCESS);
9482 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_XDTR_ACCESS);
9483
9484 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
9485 || IS_EITHER_ENABLED(pVM, INSTR_STR)
9486 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
9487 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
9488 {
9489 pDbgState->fCpe2Extra |= VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT;
9490 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_TR_ACCESS);
9491 }
9492 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_TR_ACCESS);
9493 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_TR_ACCESS);
9494 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_TR_ACCESS);
9495 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_TR_ACCESS);
9496
9497 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
9498 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
9499 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT);
9500 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
9501 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
9502 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
9503 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_VMCS_CTRL_PROC_EXEC2_WBINVD_EXIT);
9504 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
9505 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
9506 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
9507 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT);
9508 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
9509 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_VMCS_CTRL_PROC_EXEC_INVLPG_EXIT);
9510 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
9511 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
9512 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
9513 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_VMCS_CTRL_PROC_EXEC2_RDSEED_EXIT);
9514 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
9515 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
9516 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
9517 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
9518 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
9519
9520#undef IS_EITHER_ENABLED
9521#undef SET_ONLY_XBM_IF_EITHER_EN
9522#undef SET_CPE1_XBM_IF_EITHER_EN
9523#undef SET_CPEU_XBM_IF_EITHER_EN
9524#undef SET_CPE2_XBM_IF_EITHER_EN
9525
9526 /*
9527 * Sanitize the control stuff.
9528 */
9529 pDbgState->fCpe2Extra &= pVM->hm.s.vmx.Msrs.VmxProcCtls2.n.allowed1;
9530 if (pDbgState->fCpe2Extra)
9531 pDbgState->fCpe1Extra |= VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL;
9532 pDbgState->fCpe1Extra &= pVM->hm.s.vmx.Msrs.VmxProcCtls.n.allowed1;
9533 pDbgState->fCpe1Unwanted &= ~pVM->hm.s.vmx.Msrs.VmxProcCtls.n.disallowed0;
9534 if (pVCpu->hm.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_VMCS_CTRL_PROC_EXEC_RDTSC_EXIT))
9535 {
9536 pVCpu->hm.s.fDebugWantRdTscExit ^= true;
9537 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
9538 }
9539
9540 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
9541 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
9542 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
9543 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
9544}
9545
9546
9547/**
9548 * Fires off DBGF events and dtrace probes for an exit, when it's appropriate.
9549 *
9550 * The caller has checked exit against the VMXRUNDBGSTATE::bmExitsToCheck
9551 * bitmap. The caller has checked for NMIs already, so we don't have to do that
9552 * either.
9553 *
9554 * @returns Strict VBox status code (i.e. informational status codes too).
9555 * @param pVM The cross context VM structure.
9556 * @param pVCpu The cross context virtual CPU structure.
9557 * @param pMixedCtx Pointer to the guest-CPU context.
9558 * @param pVmxTransient Pointer to the VMX-transient structure.
9559 * @param uExitReason The VM-exit reason.
9560 *
9561 * @remarks The name of this function is displayed by dtrace, so keep it short
9562 * and to the point. No longer than 33 chars long, please.
9563 */
9564static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx,
9565 PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
9566{
9567 /*
9568 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
9569 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
9570 *
9571 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
9572 * does. Must add/change/remove both places. Same ordering, please.
9573 *
9574 * Added/removed events must also be reflected in the next section
9575 * where we dispatch dtrace events.
9576 */
9577 bool fDtrace1 = false;
9578 bool fDtrace2 = false;
9579 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
9580 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
9581 uint32_t uEventArg = 0;
9582#define SET_EXIT(a_EventSubName) \
9583 do { \
9584 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
9585 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
9586 } while (0)
9587#define SET_BOTH(a_EventSubName) \
9588 do { \
9589 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
9590 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
9591 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
9592 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
9593 } while (0)
9594 switch (uExitReason)
9595 {
9596 case VMX_EXIT_MTF:
9597 return hmR0VmxExitMtf(pVCpu, pMixedCtx, pVmxTransient);
9598
9599 case VMX_EXIT_XCPT_OR_NMI:
9600 {
9601 uint8_t const idxVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo);
9602 switch (VMX_EXIT_INTERRUPTION_INFO_TYPE(pVmxTransient->uExitIntInfo))
9603 {
9604 case VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT:
9605 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT:
9606 case VMX_EXIT_INTERRUPTION_INFO_TYPE_PRIV_SW_XCPT:
9607 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
9608 {
9609 if (VMX_EXIT_INTERRUPTION_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uExitIntInfo))
9610 {
9611 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
9612 uEventArg = pVmxTransient->uExitIntErrorCode;
9613 }
9614 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
9615 switch (enmEvent1)
9616 {
9617 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
9618 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
9619 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
9620 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
9621 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
9622 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
9623 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
9624 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
9625 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
9626 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
9627 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
9628 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
9629 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
9630 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
9631 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
9632 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
9633 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
9634 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
9635 default: break;
9636 }
9637 }
9638 else
9639 AssertFailed();
9640 break;
9641
9642 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_INT:
9643 uEventArg = idxVector;
9644 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
9645 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
9646 break;
9647 }
9648 break;
9649 }
9650
9651 case VMX_EXIT_TRIPLE_FAULT:
9652 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
9653 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
9654 break;
9655 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
9656 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
9657 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
9658 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
9659 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
9660
9661 /* Instruction specific VM-exits: */
9662 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
9663 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
9664 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
9665 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
9666 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
9667 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
9668 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
9669 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
9670 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
9671 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
9672 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
9673 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
9674 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
9675 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
9676 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
9677 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
9678 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
9679 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
9680 case VMX_EXIT_MOV_CRX:
9681 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
9682/** @todo r=bird: I feel these macros aren't very descriptive and needs to be at least 30 chars longer! ;-)
9683* Sensible abbreviations strongly recommended here because even with 130 columns this stuff get too wide! */
9684 if ( VMX_EXIT_QUALIFICATION_CRX_ACCESS(pVmxTransient->uExitQualification)
9685 == VMX_EXIT_QUALIFICATION_CRX_ACCESS_READ)
9686 SET_BOTH(CRX_READ);
9687 else
9688 SET_BOTH(CRX_WRITE);
9689 uEventArg = VMX_EXIT_QUALIFICATION_CRX_REGISTER(pVmxTransient->uExitQualification);
9690 break;
9691 case VMX_EXIT_MOV_DRX:
9692 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
9693 if ( VMX_EXIT_QUALIFICATION_DRX_DIRECTION(pVmxTransient->uExitQualification)
9694 == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_READ)
9695 SET_BOTH(DRX_READ);
9696 else
9697 SET_BOTH(DRX_WRITE);
9698 uEventArg = VMX_EXIT_QUALIFICATION_DRX_REGISTER(pVmxTransient->uExitQualification);
9699 break;
9700 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
9701 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
9702 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
9703 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
9704 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
9705 case VMX_EXIT_XDTR_ACCESS:
9706 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
9707 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_XDTR_INSINFO_INSTR_ID))
9708 {
9709 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
9710 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
9711 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
9712 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
9713 }
9714 break;
9715
9716 case VMX_EXIT_TR_ACCESS:
9717 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
9718 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_YYTR_INSINFO_INSTR_ID))
9719 {
9720 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
9721 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
9722 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
9723 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
9724 }
9725 break;
9726
9727 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
9728 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
9729 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
9730 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
9731 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
9732 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
9733 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
9734 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
9735 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
9736 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
9737 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
9738
9739 /* Events that aren't relevant at this point. */
9740 case VMX_EXIT_EXT_INT:
9741 case VMX_EXIT_INT_WINDOW:
9742 case VMX_EXIT_NMI_WINDOW:
9743 case VMX_EXIT_TPR_BELOW_THRESHOLD:
9744 case VMX_EXIT_PREEMPT_TIMER:
9745 case VMX_EXIT_IO_INSTR:
9746 break;
9747
9748 /* Errors and unexpected events. */
9749 case VMX_EXIT_INIT_SIGNAL:
9750 case VMX_EXIT_SIPI:
9751 case VMX_EXIT_IO_SMI:
9752 case VMX_EXIT_SMI:
9753 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
9754 case VMX_EXIT_ERR_MSR_LOAD:
9755 case VMX_EXIT_ERR_MACHINE_CHECK:
9756 break;
9757
9758 default:
9759 AssertMsgFailed(("Unexpected exit=%#x\n", uExitReason));
9760 break;
9761 }
9762#undef SET_BOTH
9763#undef SET_EXIT
9764
9765 /*
9766 * Dtrace tracepoints go first. We do them here at once so we don't
9767 * have to copy the guest state saving and stuff a few dozen times.
9768 * Down side is that we've got to repeat the switch, though this time
9769 * we use enmEvent since the probes are a subset of what DBGF does.
9770 */
9771 if (fDtrace1 || fDtrace2)
9772 {
9773 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
9774 hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
9775 switch (enmEvent1)
9776 {
9777 /** @todo consider which extra parameters would be helpful for each probe. */
9778 case DBGFEVENT_END: break;
9779 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pMixedCtx); break;
9780 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pMixedCtx, pMixedCtx->dr[6]); break;
9781 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pMixedCtx); break;
9782 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pMixedCtx); break;
9783 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pMixedCtx); break;
9784 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pMixedCtx); break;
9785 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pMixedCtx); break;
9786 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pMixedCtx); break;
9787 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pMixedCtx, uEventArg); break;
9788 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pMixedCtx, uEventArg); break;
9789 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pMixedCtx, uEventArg); break;
9790 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pMixedCtx, uEventArg); break;
9791 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pMixedCtx, uEventArg, pMixedCtx->cr2); break;
9792 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pMixedCtx); break;
9793 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pMixedCtx); break;
9794 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pMixedCtx); break;
9795 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pMixedCtx); break;
9796 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pMixedCtx, uEventArg); break;
9797 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9798 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pMixedCtx, pMixedCtx->eax, pMixedCtx->ecx); break;
9799 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pMixedCtx); break;
9800 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pMixedCtx); break;
9801 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pMixedCtx); break;
9802 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pMixedCtx); break;
9803 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pMixedCtx); break;
9804 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pMixedCtx); break;
9805 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pMixedCtx); break;
9806 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9807 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9808 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9809 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9810 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pMixedCtx, pMixedCtx->ecx); break;
9811 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pMixedCtx, pMixedCtx->ecx,
9812 RT_MAKE_U64(pMixedCtx->eax, pMixedCtx->edx)); break;
9813 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pMixedCtx); break;
9814 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pMixedCtx); break;
9815 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pMixedCtx); break;
9816 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pMixedCtx); break;
9817 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pMixedCtx); break;
9818 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pMixedCtx); break;
9819 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pMixedCtx); break;
9820 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pMixedCtx); break;
9821 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pMixedCtx); break;
9822 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pMixedCtx); break;
9823 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pMixedCtx); break;
9824 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pMixedCtx); break;
9825 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pMixedCtx); break;
9826 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pMixedCtx); break;
9827 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pMixedCtx); break;
9828 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pMixedCtx); break;
9829 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pMixedCtx); break;
9830 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pMixedCtx); break;
9831 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pMixedCtx); break;
9832 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pMixedCtx); break;
9833 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pMixedCtx); break;
9834 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pMixedCtx); break;
9835 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pMixedCtx); break;
9836 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pMixedCtx); break;
9837 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pMixedCtx); break;
9838 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pMixedCtx); break;
9839 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pMixedCtx); break;
9840 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pMixedCtx); break;
9841 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pMixedCtx); break;
9842 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pMixedCtx); break;
9843 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pMixedCtx); break;
9844 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pMixedCtx); break;
9845 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
9846 }
9847 switch (enmEvent2)
9848 {
9849 /** @todo consider which extra parameters would be helpful for each probe. */
9850 case DBGFEVENT_END: break;
9851 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pMixedCtx); break;
9852 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pMixedCtx, pMixedCtx->eax, pMixedCtx->ecx); break;
9853 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pMixedCtx); break;
9854 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pMixedCtx); break;
9855 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pMixedCtx); break;
9856 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pMixedCtx); break;
9857 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pMixedCtx); break;
9858 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pMixedCtx); break;
9859 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pMixedCtx); break;
9860 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9861 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9862 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9863 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pMixedCtx, (uint8_t)uEventArg); break;
9864 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pMixedCtx, pMixedCtx->ecx); break;
9865 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pMixedCtx, pMixedCtx->ecx,
9866 RT_MAKE_U64(pMixedCtx->eax, pMixedCtx->edx)); break;
9867 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pMixedCtx); break;
9868 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pMixedCtx); break;
9869 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pMixedCtx); break;
9870 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pMixedCtx); break;
9871 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pMixedCtx); break;
9872 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pMixedCtx); break;
9873 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pMixedCtx); break;
9874 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pMixedCtx); break;
9875 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pMixedCtx); break;
9876 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pMixedCtx); break;
9877 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pMixedCtx); break;
9878 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pMixedCtx); break;
9879 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pMixedCtx); break;
9880 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pMixedCtx); break;
9881 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pMixedCtx); break;
9882 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pMixedCtx); break;
9883 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pMixedCtx); break;
9884 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pMixedCtx); break;
9885 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pMixedCtx); break;
9886 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pMixedCtx); break;
9887 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pMixedCtx); break;
9888 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pMixedCtx); break;
9889 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pMixedCtx); break;
9890 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pMixedCtx); break;
9891 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pMixedCtx); break;
9892 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pMixedCtx); break;
9893 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pMixedCtx); break;
9894 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pMixedCtx); break;
9895 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pMixedCtx); break;
9896 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pMixedCtx); break;
9897 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pMixedCtx); break;
9898 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pMixedCtx); break;
9899 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pMixedCtx); break;
9900 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pMixedCtx); break;
9901 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pMixedCtx); break;
9902 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pMixedCtx); break;
9903 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
9904 }
9905 }
9906
9907 /*
9908 * Fire of the DBGF event, if enabled (our check here is just a quick one,
9909 * the DBGF call will do a full check).
9910 *
9911 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
9912 * Note! If we have to events, we prioritize the first, i.e. the instruction
9913 * one, in order to avoid event nesting.
9914 */
9915 if ( enmEvent1 != DBGFEVENT_END
9916 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
9917 {
9918 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArg(pVM, pVCpu, enmEvent1, uEventArg, DBGFEVENTCTX_HM);
9919 if (rcStrict != VINF_SUCCESS)
9920 return rcStrict;
9921 }
9922 else if ( enmEvent2 != DBGFEVENT_END
9923 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
9924 {
9925 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArg(pVM, pVCpu, enmEvent2, uEventArg, DBGFEVENTCTX_HM);
9926 if (rcStrict != VINF_SUCCESS)
9927 return rcStrict;
9928 }
9929
9930 return VINF_SUCCESS;
9931}
9932
9933
9934/**
9935 * Single-stepping VM-exit filtering.
9936 *
9937 * This is preprocessing the exits and deciding whether we've gotten far enough
9938 * to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit handling is
9939 * performed.
9940 *
9941 * @returns Strict VBox status code (i.e. informational status codes too).
9942 * @param pVM The cross context VM structure.
9943 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
9944 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
9945 * out-of-sync. Make sure to update the required
9946 * fields before using them.
9947 * @param pVmxTransient Pointer to the VMX-transient structure.
9948 * @param uExitReason The VM-exit reason.
9949 * @param pDbgState The debug state.
9950 */
9951DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient,
9952 uint32_t uExitReason, PVMXRUNDBGSTATE pDbgState)
9953{
9954 /*
9955 * Expensive (saves context) generic dtrace exit probe.
9956 */
9957 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
9958 { /* more likely */ }
9959 else
9960 {
9961 hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
9962 hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
9963 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, pMixedCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQualification);
9964 }
9965
9966 /*
9967 * Check for host NMI, just to get that out of the way.
9968 */
9969 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
9970 { /* normally likely */ }
9971 else
9972 {
9973 int rc2 = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
9974 AssertRCReturn(rc2, rc2);
9975 uint32_t uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(pVmxTransient->uExitIntInfo);
9976 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
9977 return hmR0VmxExitXcptOrNmi(pVCpu, pMixedCtx, pVmxTransient);
9978 }
9979
9980 /*
9981 * Check for single stepping event if we're stepping.
9982 */
9983 if (pVCpu->hm.s.fSingleInstruction)
9984 {
9985 switch (uExitReason)
9986 {
9987 case VMX_EXIT_MTF:
9988 return hmR0VmxExitMtf(pVCpu, pMixedCtx, pVmxTransient);
9989
9990 /* Various events: */
9991 case VMX_EXIT_XCPT_OR_NMI:
9992 case VMX_EXIT_EXT_INT:
9993 case VMX_EXIT_TRIPLE_FAULT:
9994 case VMX_EXIT_INT_WINDOW:
9995 case VMX_EXIT_NMI_WINDOW:
9996 case VMX_EXIT_TASK_SWITCH:
9997 case VMX_EXIT_TPR_BELOW_THRESHOLD:
9998 case VMX_EXIT_APIC_ACCESS:
9999 case VMX_EXIT_EPT_VIOLATION:
10000 case VMX_EXIT_EPT_MISCONFIG:
10001 case VMX_EXIT_PREEMPT_TIMER:
10002
10003 /* Instruction specific VM-exits: */
10004 case VMX_EXIT_CPUID:
10005 case VMX_EXIT_GETSEC:
10006 case VMX_EXIT_HLT:
10007 case VMX_EXIT_INVD:
10008 case VMX_EXIT_INVLPG:
10009 case VMX_EXIT_RDPMC:
10010 case VMX_EXIT_RDTSC:
10011 case VMX_EXIT_RSM:
10012 case VMX_EXIT_VMCALL:
10013 case VMX_EXIT_VMCLEAR:
10014 case VMX_EXIT_VMLAUNCH:
10015 case VMX_EXIT_VMPTRLD:
10016 case VMX_EXIT_VMPTRST:
10017 case VMX_EXIT_VMREAD:
10018 case VMX_EXIT_VMRESUME:
10019 case VMX_EXIT_VMWRITE:
10020 case VMX_EXIT_VMXOFF:
10021 case VMX_EXIT_VMXON:
10022 case VMX_EXIT_MOV_CRX:
10023 case VMX_EXIT_MOV_DRX:
10024 case VMX_EXIT_IO_INSTR:
10025 case VMX_EXIT_RDMSR:
10026 case VMX_EXIT_WRMSR:
10027 case VMX_EXIT_MWAIT:
10028 case VMX_EXIT_MONITOR:
10029 case VMX_EXIT_PAUSE:
10030 case VMX_EXIT_XDTR_ACCESS:
10031 case VMX_EXIT_TR_ACCESS:
10032 case VMX_EXIT_INVEPT:
10033 case VMX_EXIT_RDTSCP:
10034 case VMX_EXIT_INVVPID:
10035 case VMX_EXIT_WBINVD:
10036 case VMX_EXIT_XSETBV:
10037 case VMX_EXIT_RDRAND:
10038 case VMX_EXIT_INVPCID:
10039 case VMX_EXIT_VMFUNC:
10040 case VMX_EXIT_RDSEED:
10041 case VMX_EXIT_XSAVES:
10042 case VMX_EXIT_XRSTORS:
10043 {
10044 int rc2 = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
10045 rc2 |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
10046 AssertRCReturn(rc2, rc2);
10047 if ( pMixedCtx->rip != pDbgState->uRipStart
10048 || pMixedCtx->cs.Sel != pDbgState->uCsStart)
10049 return VINF_EM_DBG_STEPPED;
10050 break;
10051 }
10052
10053 /* Errors and unexpected events: */
10054 case VMX_EXIT_INIT_SIGNAL:
10055 case VMX_EXIT_SIPI:
10056 case VMX_EXIT_IO_SMI:
10057 case VMX_EXIT_SMI:
10058 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
10059 case VMX_EXIT_ERR_MSR_LOAD:
10060 case VMX_EXIT_ERR_MACHINE_CHECK:
10061 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
10062 break;
10063
10064 default:
10065 AssertMsgFailed(("Unexpected exit=%#x\n", uExitReason));
10066 break;
10067 }
10068 }
10069
10070 /*
10071 * Check for debugger event breakpoints and dtrace probes.
10072 */
10073 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
10074 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
10075 {
10076 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVM, pVCpu, pMixedCtx, pVmxTransient, uExitReason);
10077 if (rcStrict != VINF_SUCCESS)
10078 return rcStrict;
10079 }
10080
10081 /*
10082 * Normal processing.
10083 */
10084#ifdef HMVMX_USE_FUNCTION_TABLE
10085 return g_apfnVMExitHandlers[uExitReason](pVCpu, pMixedCtx, pVmxTransient);
10086#else
10087 return hmR0VmxHandleExit(pVCpu, pMixedCtx, pVmxTransient, uExitReason);
10088#endif
10089}
10090
10091
10092/**
10093 * Single steps guest code using VT-x.
10094 *
10095 * @returns Strict VBox status code (i.e. informational status codes too).
10096 * @param pVM The cross context VM structure.
10097 * @param pVCpu The cross context virtual CPU structure.
10098 * @param pCtx Pointer to the guest-CPU context.
10099 *
10100 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
10101 */
10102static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
10103{
10104 VMXTRANSIENT VmxTransient;
10105 VmxTransient.fUpdateTscOffsettingAndPreemptTimer = true;
10106
10107 /* Set HMCPU indicators. */
10108 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
10109 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
10110 pVCpu->hm.s.fDebugWantRdTscExit = false;
10111 pVCpu->hm.s.fUsingDebugLoop = true;
10112
10113 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
10114 VMXRUNDBGSTATE DbgState;
10115 hmR0VmxRunDebugStateInit(pVCpu, pCtx, &DbgState);
10116 hmR0VmxPreRunGuestDebugStateUpdate(pVM, pVCpu, pCtx, &DbgState, &VmxTransient);
10117
10118 /*
10119 * The loop.
10120 */
10121 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10122 for (uint32_t cLoops = 0; ; cLoops++)
10123 {
10124 Assert(!HMR0SuspendPending());
10125 HMVMX_ASSERT_CPU_SAFE();
10126 bool fStepping = pVCpu->hm.s.fSingleInstruction;
10127
10128 /*
10129 * Preparatory work for running guest code, this may force us to return
10130 * to ring-3. This bugger disables interrupts on VINF_SUCCESS!
10131 */
10132 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10133 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &DbgState); /* Set up execute controls the next to can respond to. */
10134 rcStrict = hmR0VmxPreRunGuest(pVM, pVCpu, pCtx, &VmxTransient, fStepping);
10135 if (rcStrict != VINF_SUCCESS)
10136 break;
10137
10138 hmR0VmxPreRunGuestCommitted(pVM, pVCpu, pCtx, &VmxTransient);
10139 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &DbgState); /* Override any obnoxious code in the above two calls. */
10140
10141 /*
10142 * Now we can run the guest code.
10143 */
10144 int rcRun = hmR0VmxRunGuest(pVM, pVCpu, pCtx);
10145
10146 /* The guest-CPU context is now outdated, 'pCtx' is to be treated as 'pMixedCtx' from this point on!!! */
10147
10148 /*
10149 * Restore any residual host-state and save any bits shared between host
10150 * and guest into the guest-CPU state. Re-enables interrupts!
10151 */
10152 hmR0VmxPostRunGuest(pVM, pVCpu, pCtx, &VmxTransient, VBOXSTRICTRC_TODO(rcStrict));
10153
10154 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
10155 if (RT_SUCCESS(rcRun))
10156 { /* very likely */ }
10157 else
10158 {
10159 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
10160 hmR0VmxReportWorldSwitchError(pVM, pVCpu, rcRun, pCtx, &VmxTransient);
10161 return rcRun;
10162 }
10163
10164 /* Profile the VM-exit. */
10165 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10166 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10167 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10168 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
10169 HMVMX_START_EXIT_DISPATCH_PROF();
10170
10171 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, pCtx, VmxTransient.uExitReason);
10172
10173 /*
10174 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
10175 */
10176 rcStrict = hmR0VmxRunDebugHandleExit(pVM, pVCpu, pCtx, &VmxTransient, VmxTransient.uExitReason, &DbgState);
10177 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
10178 if (rcStrict != VINF_SUCCESS)
10179 break;
10180 if (cLoops > pVM->hm.s.cMaxResumeLoops)
10181 {
10182 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10183 rcStrict = VINF_EM_RAW_INTERRUPT;
10184 break;
10185 }
10186
10187 /*
10188 * Stepping: Did the RIP change, if so, consider it a single step.
10189 * Otherwise, make sure one of the TFs gets set.
10190 */
10191 if (fStepping)
10192 {
10193 int rc2 = hmR0VmxSaveGuestRip(pVCpu, pCtx);
10194 rc2 |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pCtx);
10195 AssertRCReturn(rc2, rc2);
10196 if ( pCtx->rip != DbgState.uRipStart
10197 || pCtx->cs.Sel != DbgState.uCsStart)
10198 {
10199 rcStrict = VINF_EM_DBG_STEPPED;
10200 break;
10201 }
10202 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
10203 }
10204
10205 /*
10206 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
10207 */
10208 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
10209 hmR0VmxPreRunGuestDebugStateUpdate(pVM, pVCpu, pCtx, &DbgState, &VmxTransient);
10210 }
10211
10212 /*
10213 * Clear the X86_EFL_TF if necessary.
10214 */
10215 if (pVCpu->hm.s.fClearTrapFlag)
10216 {
10217 int rc2 = hmR0VmxSaveGuestRflags(pVCpu, pCtx);
10218 AssertRCReturn(rc2, rc2);
10219 pVCpu->hm.s.fClearTrapFlag = false;
10220 pCtx->eflags.Bits.u1TF = 0;
10221 }
10222 /** @todo there seems to be issues with the resume flag when the monitor trap
10223 * flag is pending without being used. Seen early in bios init when
10224 * accessing APIC page in protected mode. */
10225
10226 /*
10227 * Restore VM-exit control settings as we may not reenter this function the
10228 * next time around.
10229 */
10230 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &DbgState, rcStrict);
10231
10232 /* Restore HMCPU indicators. */
10233 pVCpu->hm.s.fUsingDebugLoop = false;
10234 pVCpu->hm.s.fDebugWantRdTscExit = false;
10235 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
10236
10237 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
10238 return rcStrict;
10239}
10240
10241
10242/** @} */
10243
10244
10245/**
10246 * Checks if any expensive dtrace probes are enabled and we should go to the
10247 * debug loop.
10248 *
10249 * @returns true if we should use debug loop, false if not.
10250 */
10251static bool hmR0VmxAnyExpensiveProbesEnabled(void)
10252{
10253 /* It's probably faster to OR the raw 32-bit counter variables together.
10254 Since the variables are in an array and the probes are next to one
10255 another (more or less), we have good locality. So, better read
10256 eight-nine cache lines ever time and only have one conditional, than
10257 128+ conditionals, right? */
10258 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
10259 | VBOXVMM_XCPT_DE_ENABLED_RAW()
10260 | VBOXVMM_XCPT_DB_ENABLED_RAW()
10261 | VBOXVMM_XCPT_BP_ENABLED_RAW()
10262 | VBOXVMM_XCPT_OF_ENABLED_RAW()
10263 | VBOXVMM_XCPT_BR_ENABLED_RAW()
10264 | VBOXVMM_XCPT_UD_ENABLED_RAW()
10265 | VBOXVMM_XCPT_NM_ENABLED_RAW()
10266 | VBOXVMM_XCPT_DF_ENABLED_RAW()
10267 | VBOXVMM_XCPT_TS_ENABLED_RAW()
10268 | VBOXVMM_XCPT_NP_ENABLED_RAW()
10269 | VBOXVMM_XCPT_SS_ENABLED_RAW()
10270 | VBOXVMM_XCPT_GP_ENABLED_RAW()
10271 | VBOXVMM_XCPT_PF_ENABLED_RAW()
10272 | VBOXVMM_XCPT_MF_ENABLED_RAW()
10273 | VBOXVMM_XCPT_AC_ENABLED_RAW()
10274 | VBOXVMM_XCPT_XF_ENABLED_RAW()
10275 | VBOXVMM_XCPT_VE_ENABLED_RAW()
10276 | VBOXVMM_XCPT_SX_ENABLED_RAW()
10277 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
10278 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
10279 ) != 0
10280 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
10281 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
10282 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
10283 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
10284 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
10285 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
10286 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
10287 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
10288 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
10289 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
10290 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
10291 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
10292 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
10293 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
10294 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
10295 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
10296 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
10297 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
10298 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
10299 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
10300 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
10301 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
10302 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
10303 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
10304 | VBOXVMM_INSTR_STR_ENABLED_RAW()
10305 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
10306 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
10307 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
10308 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
10309 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
10310 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
10311 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
10312 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
10313 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
10314 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
10315 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
10316 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
10317 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
10318 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
10319 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
10320 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
10321 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
10322 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
10323 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
10324 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
10325 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
10326 ) != 0
10327 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
10328 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
10329 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
10330 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
10331 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
10332 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
10333 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
10334 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
10335 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
10336 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
10337 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
10338 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
10339 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
10340 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
10341 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
10342 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
10343 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
10344 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
10345 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
10346 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
10347 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
10348 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
10349 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
10350 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
10351 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
10352 | VBOXVMM_EXIT_STR_ENABLED_RAW()
10353 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
10354 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
10355 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
10356 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
10357 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
10358 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
10359 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
10360 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
10361 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
10362 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
10363 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
10364 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
10365 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
10366 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
10367 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
10368 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
10369 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
10370 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
10371 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
10372 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
10373 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
10374 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
10375 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
10376 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
10377 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
10378 ) != 0;
10379}
10380
10381
10382/**
10383 * Runs the guest code using VT-x.
10384 *
10385 * @returns Strict VBox status code (i.e. informational status codes too).
10386 * @param pVM The cross context VM structure.
10387 * @param pVCpu The cross context virtual CPU structure.
10388 * @param pCtx Pointer to the guest-CPU context.
10389 */
10390VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
10391{
10392 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10393 Assert(HMVMXCPU_GST_VALUE(pVCpu) == HMVMX_UPDATED_GUEST_ALL);
10394 HMVMX_ASSERT_PREEMPT_SAFE();
10395
10396 VMMRZCallRing3SetNotification(pVCpu, hmR0VmxCallRing3Callback, pCtx);
10397
10398 VBOXSTRICTRC rcStrict;
10399 if ( !pVCpu->hm.s.fUseDebugLoop
10400 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
10401 && !DBGFIsStepping(pVCpu) )
10402 rcStrict = hmR0VmxRunGuestCodeNormal(pVM, pVCpu, pCtx);
10403 else
10404 rcStrict = hmR0VmxRunGuestCodeDebug(pVM, pVCpu, pCtx);
10405
10406 if (rcStrict == VERR_EM_INTERPRETER)
10407 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
10408 else if (rcStrict == VINF_EM_RESET)
10409 rcStrict = VINF_EM_TRIPLE_FAULT;
10410
10411 int rc2 = hmR0VmxExitToRing3(pVM, pVCpu, pCtx, rcStrict);
10412 if (RT_FAILURE(rc2))
10413 {
10414 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
10415 rcStrict = rc2;
10416 }
10417 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
10418 return rcStrict;
10419}
10420
10421
10422#ifndef HMVMX_USE_FUNCTION_TABLE
10423DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient, uint32_t rcReason)
10424{
10425# ifdef DEBUG_ramshankar
10426# define RETURN_EXIT_CALL(a_CallExpr) \
10427 do { \
10428 int rc2 = hmR0VmxSaveGuestState(pVCpu, pMixedCtx); AssertRC(rc2); \
10429 VBOXSTRICTRC rcStrict = a_CallExpr; \
10430 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST); \
10431 return rcStrict; \
10432 } while (0)
10433# else
10434# define RETURN_EXIT_CALL(a_CallExpr) return a_CallExpr
10435# endif
10436 switch (rcReason)
10437 {
10438 case VMX_EXIT_EPT_MISCONFIG: RETURN_EXIT_CALL(hmR0VmxExitEptMisconfig(pVCpu, pMixedCtx, pVmxTransient));
10439 case VMX_EXIT_EPT_VIOLATION: RETURN_EXIT_CALL(hmR0VmxExitEptViolation(pVCpu, pMixedCtx, pVmxTransient));
10440 case VMX_EXIT_IO_INSTR: RETURN_EXIT_CALL(hmR0VmxExitIoInstr(pVCpu, pMixedCtx, pVmxTransient));
10441 case VMX_EXIT_CPUID: RETURN_EXIT_CALL(hmR0VmxExitCpuid(pVCpu, pMixedCtx, pVmxTransient));
10442 case VMX_EXIT_RDTSC: RETURN_EXIT_CALL(hmR0VmxExitRdtsc(pVCpu, pMixedCtx, pVmxTransient));
10443 case VMX_EXIT_RDTSCP: RETURN_EXIT_CALL(hmR0VmxExitRdtscp(pVCpu, pMixedCtx, pVmxTransient));
10444 case VMX_EXIT_APIC_ACCESS: RETURN_EXIT_CALL(hmR0VmxExitApicAccess(pVCpu, pMixedCtx, pVmxTransient));
10445 case VMX_EXIT_XCPT_OR_NMI: RETURN_EXIT_CALL(hmR0VmxExitXcptOrNmi(pVCpu, pMixedCtx, pVmxTransient));
10446 case VMX_EXIT_MOV_CRX: RETURN_EXIT_CALL(hmR0VmxExitMovCRx(pVCpu, pMixedCtx, pVmxTransient));
10447 case VMX_EXIT_EXT_INT: RETURN_EXIT_CALL(hmR0VmxExitExtInt(pVCpu, pMixedCtx, pVmxTransient));
10448 case VMX_EXIT_INT_WINDOW: RETURN_EXIT_CALL(hmR0VmxExitIntWindow(pVCpu, pMixedCtx, pVmxTransient));
10449 case VMX_EXIT_MWAIT: RETURN_EXIT_CALL(hmR0VmxExitMwait(pVCpu, pMixedCtx, pVmxTransient));
10450 case VMX_EXIT_MONITOR: RETURN_EXIT_CALL(hmR0VmxExitMonitor(pVCpu, pMixedCtx, pVmxTransient));
10451 case VMX_EXIT_TASK_SWITCH: RETURN_EXIT_CALL(hmR0VmxExitTaskSwitch(pVCpu, pMixedCtx, pVmxTransient));
10452 case VMX_EXIT_PREEMPT_TIMER: RETURN_EXIT_CALL(hmR0VmxExitPreemptTimer(pVCpu, pMixedCtx, pVmxTransient));
10453 case VMX_EXIT_RDMSR: RETURN_EXIT_CALL(hmR0VmxExitRdmsr(pVCpu, pMixedCtx, pVmxTransient));
10454 case VMX_EXIT_WRMSR: RETURN_EXIT_CALL(hmR0VmxExitWrmsr(pVCpu, pMixedCtx, pVmxTransient));
10455 case VMX_EXIT_MOV_DRX: RETURN_EXIT_CALL(hmR0VmxExitMovDRx(pVCpu, pMixedCtx, pVmxTransient));
10456 case VMX_EXIT_TPR_BELOW_THRESHOLD: RETURN_EXIT_CALL(hmR0VmxExitTprBelowThreshold(pVCpu, pMixedCtx, pVmxTransient));
10457 case VMX_EXIT_HLT: RETURN_EXIT_CALL(hmR0VmxExitHlt(pVCpu, pMixedCtx, pVmxTransient));
10458 case VMX_EXIT_INVD: RETURN_EXIT_CALL(hmR0VmxExitInvd(pVCpu, pMixedCtx, pVmxTransient));
10459 case VMX_EXIT_INVLPG: RETURN_EXIT_CALL(hmR0VmxExitInvlpg(pVCpu, pMixedCtx, pVmxTransient));
10460 case VMX_EXIT_RSM: RETURN_EXIT_CALL(hmR0VmxExitRsm(pVCpu, pMixedCtx, pVmxTransient));
10461 case VMX_EXIT_MTF: RETURN_EXIT_CALL(hmR0VmxExitMtf(pVCpu, pMixedCtx, pVmxTransient));
10462 case VMX_EXIT_PAUSE: RETURN_EXIT_CALL(hmR0VmxExitPause(pVCpu, pMixedCtx, pVmxTransient));
10463 case VMX_EXIT_XDTR_ACCESS: RETURN_EXIT_CALL(hmR0VmxExitXdtrAccess(pVCpu, pMixedCtx, pVmxTransient));
10464 case VMX_EXIT_TR_ACCESS: RETURN_EXIT_CALL(hmR0VmxExitXdtrAccess(pVCpu, pMixedCtx, pVmxTransient));
10465 case VMX_EXIT_WBINVD: RETURN_EXIT_CALL(hmR0VmxExitWbinvd(pVCpu, pMixedCtx, pVmxTransient));
10466 case VMX_EXIT_XSETBV: RETURN_EXIT_CALL(hmR0VmxExitXsetbv(pVCpu, pMixedCtx, pVmxTransient));
10467 case VMX_EXIT_RDRAND: RETURN_EXIT_CALL(hmR0VmxExitRdrand(pVCpu, pMixedCtx, pVmxTransient));
10468 case VMX_EXIT_INVPCID: RETURN_EXIT_CALL(hmR0VmxExitInvpcid(pVCpu, pMixedCtx, pVmxTransient));
10469 case VMX_EXIT_GETSEC: RETURN_EXIT_CALL(hmR0VmxExitGetsec(pVCpu, pMixedCtx, pVmxTransient));
10470 case VMX_EXIT_RDPMC: RETURN_EXIT_CALL(hmR0VmxExitRdpmc(pVCpu, pMixedCtx, pVmxTransient));
10471 case VMX_EXIT_VMCALL: RETURN_EXIT_CALL(hmR0VmxExitVmcall(pVCpu, pMixedCtx, pVmxTransient));
10472
10473 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pMixedCtx, pVmxTransient);
10474 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pMixedCtx, pVmxTransient);
10475 case VMX_EXIT_INIT_SIGNAL: return hmR0VmxExitInitSignal(pVCpu, pMixedCtx, pVmxTransient);
10476 case VMX_EXIT_SIPI: return hmR0VmxExitSipi(pVCpu, pMixedCtx, pVmxTransient);
10477 case VMX_EXIT_IO_SMI: return hmR0VmxExitIoSmi(pVCpu, pMixedCtx, pVmxTransient);
10478 case VMX_EXIT_SMI: return hmR0VmxExitSmi(pVCpu, pMixedCtx, pVmxTransient);
10479 case VMX_EXIT_ERR_MSR_LOAD: return hmR0VmxExitErrMsrLoad(pVCpu, pMixedCtx, pVmxTransient);
10480 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pMixedCtx, pVmxTransient);
10481 case VMX_EXIT_ERR_MACHINE_CHECK: return hmR0VmxExitErrMachineCheck(pVCpu, pMixedCtx, pVmxTransient);
10482
10483 case VMX_EXIT_VMCLEAR:
10484 case VMX_EXIT_VMLAUNCH:
10485 case VMX_EXIT_VMPTRLD:
10486 case VMX_EXIT_VMPTRST:
10487 case VMX_EXIT_VMREAD:
10488 case VMX_EXIT_VMRESUME:
10489 case VMX_EXIT_VMWRITE:
10490 case VMX_EXIT_VMXOFF:
10491 case VMX_EXIT_VMXON:
10492 case VMX_EXIT_INVEPT:
10493 case VMX_EXIT_INVVPID:
10494 case VMX_EXIT_VMFUNC:
10495 case VMX_EXIT_XSAVES:
10496 case VMX_EXIT_XRSTORS:
10497 return hmR0VmxExitSetPendingXcptUD(pVCpu, pMixedCtx, pVmxTransient);
10498 case VMX_EXIT_RESERVED_60:
10499 case VMX_EXIT_RDSEED: /* only spurious exits, so undefined */
10500 case VMX_EXIT_RESERVED_62:
10501 default:
10502 return hmR0VmxExitErrUndefined(pVCpu, pMixedCtx, pVmxTransient);
10503 }
10504#undef RETURN_EXIT_CALL
10505}
10506#endif /* !HMVMX_USE_FUNCTION_TABLE */
10507
10508
10509#ifdef VBOX_STRICT
10510/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
10511# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
10512 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
10513
10514# define HMVMX_ASSERT_PREEMPT_CPUID() \
10515 do { \
10516 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
10517 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
10518 } while (0)
10519
10520# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS() \
10521 do { \
10522 AssertPtr(pVCpu); \
10523 AssertPtr(pMixedCtx); \
10524 AssertPtr(pVmxTransient); \
10525 Assert(pVmxTransient->fVMEntryFailed == false); \
10526 Assert(ASMIntAreEnabled()); \
10527 HMVMX_ASSERT_PREEMPT_SAFE(); \
10528 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
10529 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)); \
10530 HMVMX_ASSERT_PREEMPT_SAFE(); \
10531 if (VMMR0IsLogFlushDisabled(pVCpu)) \
10532 HMVMX_ASSERT_PREEMPT_CPUID(); \
10533 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
10534 } while (0)
10535
10536# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS() \
10537 do { \
10538 Log4Func(("\n")); \
10539 } while (0)
10540#else /* nonstrict builds: */
10541# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS() \
10542 do { \
10543 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
10544 NOREF(pVCpu); NOREF(pMixedCtx); NOREF(pVmxTransient); \
10545 } while (0)
10546# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS() do { } while (0)
10547#endif
10548
10549
10550/**
10551 * Advances the guest RIP by the specified number of bytes.
10552 *
10553 * @param pVCpu The cross context virtual CPU structure.
10554 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
10555 * out-of-sync. Make sure to update the required fields
10556 * before using them.
10557 * @param cbInstr Number of bytes to advance the RIP by.
10558 *
10559 * @remarks No-long-jump zone!!!
10560 */
10561DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPU pVCpu, PCPUMCTX pMixedCtx, uint32_t cbInstr)
10562{
10563 /* Advance the RIP. */
10564 pMixedCtx->rip += cbInstr;
10565 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP);
10566
10567 /* Update interrupt inhibition. */
10568 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
10569 && pMixedCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
10570 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
10571}
10572
10573
10574/**
10575 * Advances the guest RIP after reading it from the VMCS.
10576 *
10577 * @returns VBox status code, no informational status codes.
10578 * @param pVCpu The cross context virtual CPU structure.
10579 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
10580 * out-of-sync. Make sure to update the required fields
10581 * before using them.
10582 * @param pVmxTransient Pointer to the VMX transient structure.
10583 *
10584 * @remarks No-long-jump zone!!!
10585 */
10586static int hmR0VmxAdvanceGuestRip(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
10587{
10588 int rc = hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
10589 rc |= hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
10590 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
10591 AssertRCReturn(rc, rc);
10592
10593 hmR0VmxAdvanceGuestRipBy(pVCpu, pMixedCtx, pVmxTransient->cbInstr);
10594
10595 /*
10596 * Deliver a debug exception to the guest if it is single-stepping. Don't directly inject a #DB but use the
10597 * pending debug exception field as it takes care of priority of events.
10598 *
10599 * See Intel spec. 32.2.1 "Debug Exceptions".
10600 */
10601 if ( !pVCpu->hm.s.fSingleInstruction
10602 && pMixedCtx->eflags.Bits.u1TF)
10603 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
10604
10605 return VINF_SUCCESS;
10606}
10607
10608
10609/**
10610 * Tries to determine what part of the guest-state VT-x has deemed as invalid
10611 * and update error record fields accordingly.
10612 *
10613 * @return VMX_IGS_* return codes.
10614 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
10615 * wrong with the guest state.
10616 *
10617 * @param pVM The cross context VM structure.
10618 * @param pVCpu The cross context virtual CPU structure.
10619 * @param pCtx Pointer to the guest-CPU state.
10620 *
10621 * @remarks This function assumes our cache of the VMCS controls
10622 * are valid, i.e. hmR0VmxCheckVmcsCtls() succeeded.
10623 */
10624static uint32_t hmR0VmxCheckGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
10625{
10626#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
10627#define HMVMX_CHECK_BREAK(expr, err) if (!(expr)) { \
10628 uError = (err); \
10629 break; \
10630 } else do { } while (0)
10631
10632 int rc;
10633 uint32_t uError = VMX_IGS_ERROR;
10634 uint32_t u32Val;
10635 bool fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuest;
10636
10637 do
10638 {
10639 /*
10640 * CR0.
10641 */
10642 uint32_t uSetCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
10643 uint32_t uZapCR0 = (uint32_t)(pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
10644 /* Exceptions for unrestricted-guests for fixed CR0 bits (PE, PG).
10645 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
10646 if (fUnrestrictedGuest)
10647 uSetCR0 &= ~(X86_CR0_PE | X86_CR0_PG);
10648
10649 uint32_t u32GuestCR0;
10650 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR0, &u32GuestCR0);
10651 AssertRCBreak(rc);
10652 HMVMX_CHECK_BREAK((u32GuestCR0 & uSetCR0) == uSetCR0, VMX_IGS_CR0_FIXED1);
10653 HMVMX_CHECK_BREAK(!(u32GuestCR0 & ~uZapCR0), VMX_IGS_CR0_FIXED0);
10654 if ( !fUnrestrictedGuest
10655 && (u32GuestCR0 & X86_CR0_PG)
10656 && !(u32GuestCR0 & X86_CR0_PE))
10657 {
10658 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
10659 }
10660
10661 /*
10662 * CR4.
10663 */
10664 uint64_t uSetCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
10665 uint64_t uZapCR4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
10666
10667 uint32_t u32GuestCR4;
10668 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR4, &u32GuestCR4);
10669 AssertRCBreak(rc);
10670 HMVMX_CHECK_BREAK((u32GuestCR4 & uSetCR4) == uSetCR4, VMX_IGS_CR4_FIXED1);
10671 HMVMX_CHECK_BREAK(!(u32GuestCR4 & ~uZapCR4), VMX_IGS_CR4_FIXED0);
10672
10673 /*
10674 * IA32_DEBUGCTL MSR.
10675 */
10676 uint64_t u64Val;
10677 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
10678 AssertRCBreak(rc);
10679 if ( (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG)
10680 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
10681 {
10682 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
10683 }
10684 uint64_t u64DebugCtlMsr = u64Val;
10685
10686#ifdef VBOX_STRICT
10687 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
10688 AssertRCBreak(rc);
10689 Assert(u32Val == pVCpu->hm.s.vmx.u32EntryCtls);
10690#endif
10691 bool const fLongModeGuest = RT_BOOL(pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST);
10692
10693 /*
10694 * RIP and RFLAGS.
10695 */
10696 uint32_t u32Eflags;
10697#if HC_ARCH_BITS == 64
10698 rc = VMXReadVmcs64(VMX_VMCS_GUEST_RIP, &u64Val);
10699 AssertRCBreak(rc);
10700 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
10701 if ( !fLongModeGuest
10702 || !pCtx->cs.Attr.n.u1Long)
10703 {
10704 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
10705 }
10706 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
10707 * must be identical if the "IA-32e mode guest" VM-entry
10708 * control is 1 and CS.L is 1. No check applies if the
10709 * CPU supports 64 linear-address bits. */
10710
10711 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
10712 rc = VMXReadVmcs64(VMX_VMCS_GUEST_RFLAGS, &u64Val);
10713 AssertRCBreak(rc);
10714 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
10715 VMX_IGS_RFLAGS_RESERVED);
10716 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
10717 u32Eflags = u64Val;
10718#else
10719 rc = VMXReadVmcs32(VMX_VMCS_GUEST_RFLAGS, &u32Eflags);
10720 AssertRCBreak(rc);
10721 HMVMX_CHECK_BREAK(!(u32Eflags & 0xffc08028), VMX_IGS_RFLAGS_RESERVED); /* Bit 31:22, Bit 15, 5, 3 MBZ. */
10722 HMVMX_CHECK_BREAK((u32Eflags & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
10723#endif
10724
10725 if ( fLongModeGuest
10726 || ( fUnrestrictedGuest
10727 && !(u32GuestCR0 & X86_CR0_PE)))
10728 {
10729 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
10730 }
10731
10732 uint32_t u32EntryInfo;
10733 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
10734 AssertRCBreak(rc);
10735 if ( VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(u32EntryInfo)
10736 && VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
10737 {
10738 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
10739 }
10740
10741 /*
10742 * 64-bit checks.
10743 */
10744#if HC_ARCH_BITS == 64
10745 if (fLongModeGuest)
10746 {
10747 HMVMX_CHECK_BREAK(u32GuestCR0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
10748 HMVMX_CHECK_BREAK(u32GuestCR4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
10749 }
10750
10751 if ( !fLongModeGuest
10752 && (u32GuestCR4 & X86_CR4_PCIDE))
10753 {
10754 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
10755 }
10756
10757 /** @todo CR3 field must be such that bits 63:52 and bits in the range
10758 * 51:32 beyond the processor's physical-address width are 0. */
10759
10760 if ( (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_DEBUG)
10761 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
10762 {
10763 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
10764 }
10765
10766 rc = VMXReadVmcs64(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
10767 AssertRCBreak(rc);
10768 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
10769
10770 rc = VMXReadVmcs64(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
10771 AssertRCBreak(rc);
10772 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
10773#endif
10774
10775 /*
10776 * PERF_GLOBAL MSR.
10777 */
10778 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PERF_MSR)
10779 {
10780 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
10781 AssertRCBreak(rc);
10782 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
10783 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
10784 }
10785
10786 /*
10787 * PAT MSR.
10788 */
10789 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_PAT_MSR)
10790 {
10791 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
10792 AssertRCBreak(rc);
10793 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
10794 for (unsigned i = 0; i < 8; i++)
10795 {
10796 uint8_t u8Val = (u64Val & 0xff);
10797 if ( u8Val != 0 /* UC */
10798 && u8Val != 1 /* WC */
10799 && u8Val != 4 /* WT */
10800 && u8Val != 5 /* WP */
10801 && u8Val != 6 /* WB */
10802 && u8Val != 7 /* UC- */)
10803 {
10804 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
10805 }
10806 u64Val >>= 8;
10807 }
10808 }
10809
10810 /*
10811 * EFER MSR.
10812 */
10813 if (pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_LOAD_GUEST_EFER_MSR)
10814 {
10815 Assert(pVM->hm.s.vmx.fSupportsVmcsEfer);
10816 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
10817 AssertRCBreak(rc);
10818 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
10819 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
10820 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVCpu->hm.s.vmx.u32EntryCtls
10821 & VMX_VMCS_CTRL_ENTRY_IA32E_MODE_GUEST),
10822 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
10823 HMVMX_CHECK_BREAK( fUnrestrictedGuest
10824 || !(u32GuestCR0 & X86_CR0_PG)
10825 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
10826 VMX_IGS_EFER_LMA_LME_MISMATCH);
10827 }
10828
10829 /*
10830 * Segment registers.
10831 */
10832 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
10833 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
10834 if (!(u32Eflags & X86_EFL_VM))
10835 {
10836 /* CS */
10837 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
10838 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
10839 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
10840 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
10841 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
10842 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
10843 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
10844 /* CS cannot be loaded with NULL in protected mode. */
10845 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
10846 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
10847 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
10848 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
10849 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
10850 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
10851 else if (pVM->hm.s.vmx.fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
10852 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
10853 else
10854 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
10855
10856 /* SS */
10857 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
10858 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
10859 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
10860 if ( !(pCtx->cr0 & X86_CR0_PE)
10861 || pCtx->cs.Attr.n.u4Type == 3)
10862 {
10863 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
10864 }
10865 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
10866 {
10867 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
10868 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
10869 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
10870 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
10871 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
10872 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
10873 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
10874 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
10875 }
10876
10877 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxWriteSegmentReg(). */
10878 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
10879 {
10880 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
10881 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
10882 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
10883 || pCtx->ds.Attr.n.u4Type > 11
10884 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
10885 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
10886 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
10887 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
10888 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
10889 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
10890 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
10891 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10892 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
10893 }
10894 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
10895 {
10896 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
10897 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
10898 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
10899 || pCtx->es.Attr.n.u4Type > 11
10900 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
10901 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
10902 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
10903 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
10904 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
10905 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
10906 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
10907 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10908 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
10909 }
10910 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
10911 {
10912 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
10913 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
10914 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
10915 || pCtx->fs.Attr.n.u4Type > 11
10916 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
10917 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
10918 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
10919 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
10920 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
10921 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
10922 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
10923 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10924 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
10925 }
10926 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
10927 {
10928 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
10929 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
10930 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
10931 || pCtx->gs.Attr.n.u4Type > 11
10932 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
10933 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
10934 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
10935 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
10936 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
10937 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
10938 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
10939 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10940 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
10941 }
10942 /* 64-bit capable CPUs. */
10943#if HC_ARCH_BITS == 64
10944 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
10945 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
10946 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
10947 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
10948 HMVMX_CHECK_BREAK(!(pCtx->cs.u64Base >> 32), VMX_IGS_LONGMODE_CS_BASE_INVALID);
10949 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ss.u64Base >> 32),
10950 VMX_IGS_LONGMODE_SS_BASE_INVALID);
10951 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ds.u64Base >> 32),
10952 VMX_IGS_LONGMODE_DS_BASE_INVALID);
10953 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->es.u64Base >> 32),
10954 VMX_IGS_LONGMODE_ES_BASE_INVALID);
10955#endif
10956 }
10957 else
10958 {
10959 /* V86 mode checks. */
10960 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
10961 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
10962 {
10963 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
10964 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
10965 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
10966 }
10967 else
10968 {
10969 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
10970 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
10971 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
10972 }
10973
10974 /* CS */
10975 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
10976 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
10977 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
10978 /* SS */
10979 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
10980 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
10981 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
10982 /* DS */
10983 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
10984 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
10985 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
10986 /* ES */
10987 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
10988 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
10989 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
10990 /* FS */
10991 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
10992 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
10993 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
10994 /* GS */
10995 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
10996 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
10997 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
10998 /* 64-bit capable CPUs. */
10999#if HC_ARCH_BITS == 64
11000 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
11001 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
11002 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
11003 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
11004 HMVMX_CHECK_BREAK(!(pCtx->cs.u64Base >> 32), VMX_IGS_LONGMODE_CS_BASE_INVALID);
11005 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ss.u64Base >> 32),
11006 VMX_IGS_LONGMODE_SS_BASE_INVALID);
11007 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->ds.u64Base >> 32),
11008 VMX_IGS_LONGMODE_DS_BASE_INVALID);
11009 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !(pCtx->es.u64Base >> 32),
11010 VMX_IGS_LONGMODE_ES_BASE_INVALID);
11011#endif
11012 }
11013
11014 /*
11015 * TR.
11016 */
11017 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
11018 /* 64-bit capable CPUs. */
11019#if HC_ARCH_BITS == 64
11020 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
11021#endif
11022 if (fLongModeGuest)
11023 {
11024 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
11025 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
11026 }
11027 else
11028 {
11029 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
11030 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
11031 VMX_IGS_TR_ATTR_TYPE_INVALID);
11032 }
11033 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
11034 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
11035 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
11036 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
11037 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
11038 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
11039 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
11040 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
11041
11042 /*
11043 * GDTR and IDTR.
11044 */
11045#if HC_ARCH_BITS == 64
11046 rc = VMXReadVmcs64(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
11047 AssertRCBreak(rc);
11048 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
11049
11050 rc = VMXReadVmcs64(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
11051 AssertRCBreak(rc);
11052 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
11053#endif
11054
11055 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
11056 AssertRCBreak(rc);
11057 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
11058
11059 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
11060 AssertRCBreak(rc);
11061 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
11062
11063 /*
11064 * Guest Non-Register State.
11065 */
11066 /* Activity State. */
11067 uint32_t u32ActivityState;
11068 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
11069 AssertRCBreak(rc);
11070 HMVMX_CHECK_BREAK( !u32ActivityState
11071 || (u32ActivityState & MSR_IA32_VMX_MISC_ACTIVITY_STATES(pVM->hm.s.vmx.Msrs.u64Misc)),
11072 VMX_IGS_ACTIVITY_STATE_INVALID);
11073 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
11074 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
11075 uint32_t u32IntrState;
11076 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &u32IntrState);
11077 AssertRCBreak(rc);
11078 if ( u32IntrState == VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS
11079 || u32IntrState == VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
11080 {
11081 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
11082 }
11083
11084 /** @todo Activity state and injecting interrupts. Left as a todo since we
11085 * currently don't use activity states but ACTIVE. */
11086
11087 HMVMX_CHECK_BREAK( !(pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_ENTRY_SMM)
11088 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
11089
11090 /* Guest interruptibility-state. */
11091 HMVMX_CHECK_BREAK(!(u32IntrState & 0xfffffff0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
11092 HMVMX_CHECK_BREAK((u32IntrState & ( VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI
11093 | VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS))
11094 != ( VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI
11095 | VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS),
11096 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
11097 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
11098 || !(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI),
11099 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
11100 if (VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(u32EntryInfo))
11101 {
11102 if (VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT)
11103 {
11104 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
11105 && !(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS),
11106 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
11107 }
11108 else if (VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
11109 {
11110 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS),
11111 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
11112 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI),
11113 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
11114 }
11115 }
11116 /** @todo Assumes the processor is not in SMM. */
11117 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI),
11118 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
11119 HMVMX_CHECK_BREAK( !(pVCpu->hm.s.vmx.u32EntryCtls & VMX_VMCS_CTRL_ENTRY_ENTRY_SMM)
11120 || (u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_SMI),
11121 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
11122 if ( (pVCpu->hm.s.vmx.u32PinCtls & VMX_VMCS_CTRL_PIN_EXEC_VIRTUAL_NMI)
11123 && VMX_ENTRY_INTERRUPTION_INFO_IS_VALID(u32EntryInfo)
11124 && VMX_ENTRY_INTERRUPTION_INFO_TYPE(u32EntryInfo) == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
11125 {
11126 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_NMI),
11127 VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
11128 }
11129
11130 /* Pending debug exceptions. */
11131#if HC_ARCH_BITS == 64
11132 rc = VMXReadVmcs64(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, &u64Val);
11133 AssertRCBreak(rc);
11134 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
11135 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
11136 u32Val = u64Val; /* For pending debug exceptions checks below. */
11137#else
11138 rc = VMXReadVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_EXCEPTIONS, &u32Val);
11139 AssertRCBreak(rc);
11140 /* Bits 31:15, Bit 13, Bits 11:4 MBZ. */
11141 HMVMX_CHECK_BREAK(!(u32Val & 0xffffaff0), VMX_IGS_PENDING_DEBUG_RESERVED);
11142#endif
11143
11144 if ( (u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI)
11145 || (u32IntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_MOVSS)
11146 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
11147 {
11148 if ( (u32Eflags & X86_EFL_TF)
11149 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
11150 {
11151 /* Bit 14 is PendingDebug.BS. */
11152 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
11153 }
11154 if ( !(u32Eflags & X86_EFL_TF)
11155 || (u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
11156 {
11157 /* Bit 14 is PendingDebug.BS. */
11158 HMVMX_CHECK_BREAK(!(u32Val & RT_BIT(14)), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_CLEAR);
11159 }
11160 }
11161
11162 /* VMCS link pointer. */
11163 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
11164 AssertRCBreak(rc);
11165 if (u64Val != UINT64_C(0xffffffffffffffff))
11166 {
11167 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
11168 /** @todo Bits beyond the processor's physical-address width MBZ. */
11169 /** @todo 32-bit located in memory referenced by value of this field (as a
11170 * physical address) must contain the processor's VMCS revision ID. */
11171 /** @todo SMM checks. */
11172 }
11173
11174 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
11175 * not using Nested Paging? */
11176 if ( pVM->hm.s.fNestedPaging
11177 && !fLongModeGuest
11178 && CPUMIsGuestInPAEModeEx(pCtx))
11179 {
11180 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
11181 AssertRCBreak(rc);
11182 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11183
11184 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
11185 AssertRCBreak(rc);
11186 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11187
11188 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
11189 AssertRCBreak(rc);
11190 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11191
11192 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
11193 AssertRCBreak(rc);
11194 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
11195 }
11196
11197 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
11198 if (uError == VMX_IGS_ERROR)
11199 uError = VMX_IGS_REASON_NOT_FOUND;
11200 } while (0);
11201
11202 pVCpu->hm.s.u32HMError = uError;
11203 return uError;
11204
11205#undef HMVMX_ERROR_BREAK
11206#undef HMVMX_CHECK_BREAK
11207}
11208
11209/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
11210/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
11211/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
11212
11213/** @name VM-exit handlers.
11214 * @{
11215 */
11216
11217/**
11218 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
11219 */
11220HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11221{
11222 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11223 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
11224 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
11225 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
11226 return VINF_SUCCESS;
11227 return VINF_EM_RAW_INTERRUPT;
11228}
11229
11230
11231/**
11232 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
11233 */
11234HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11235{
11236 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11237 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
11238
11239 int rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
11240 AssertRCReturn(rc, rc);
11241
11242 uint32_t uIntType = VMX_EXIT_INTERRUPTION_INFO_TYPE(pVmxTransient->uExitIntInfo);
11243 Assert( !(pVCpu->hm.s.vmx.u32ExitCtls & VMX_VMCS_CTRL_EXIT_ACK_EXT_INT)
11244 && uIntType != VMX_EXIT_INTERRUPTION_INFO_TYPE_EXT_INT);
11245 Assert(VMX_EXIT_INTERRUPTION_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
11246
11247 if (uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_NMI)
11248 {
11249 /*
11250 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we injected it ourselves and
11251 * anything we inject is not going to cause a VM-exit directly for the event being injected.
11252 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
11253 *
11254 * Dispatch the NMI to the host. See Intel spec. 27.5.5 "Updating Non-Register State".
11255 */
11256 VMXDispatchHostNmi();
11257 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
11258 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
11259 return VINF_SUCCESS;
11260 }
11261
11262 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
11263 VBOXSTRICTRC rcStrictRc1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
11264 if (RT_UNLIKELY(rcStrictRc1 == VINF_SUCCESS))
11265 { /* likely */ }
11266 else
11267 {
11268 if (rcStrictRc1 == VINF_HM_DOUBLE_FAULT)
11269 rcStrictRc1 = VINF_SUCCESS;
11270 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
11271 return rcStrictRc1;
11272 }
11273
11274 uint32_t uExitIntInfo = pVmxTransient->uExitIntInfo;
11275 uint32_t uVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(uExitIntInfo);
11276 switch (uIntType)
11277 {
11278 case VMX_EXIT_INTERRUPTION_INFO_TYPE_PRIV_SW_XCPT: /* Privileged software exception. (#DB from ICEBP) */
11279 Assert(uVector == X86_XCPT_DB);
11280 /* no break */
11281 case VMX_EXIT_INTERRUPTION_INFO_TYPE_SW_XCPT: /* Software exception. (#BP or #OF) */
11282 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uIntType == VMX_EXIT_INTERRUPTION_INFO_TYPE_PRIV_SW_XCPT);
11283 /* no break */
11284 case VMX_EXIT_INTERRUPTION_INFO_TYPE_HW_XCPT:
11285 {
11286 /*
11287 * If there's any exception caused as a result of event injection, go back to
11288 * the interpreter. The page-fault case is complicated and we manually handle
11289 * any currently pending event in hmR0VmxExitXcptPF. Nested #ACs are already
11290 * handled in hmR0VmxCheckExitDueToEventDelivery.
11291 */
11292 if (!pVCpu->hm.s.Event.fPending)
11293 { /* likely */ }
11294 else if ( uVector != X86_XCPT_PF
11295 && uVector != X86_XCPT_AC)
11296 {
11297 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
11298 rc = VERR_EM_INTERPRETER;
11299 break;
11300 }
11301
11302 switch (uVector)
11303 {
11304 case X86_XCPT_PF: rc = hmR0VmxExitXcptPF(pVCpu, pMixedCtx, pVmxTransient); break;
11305 case X86_XCPT_GP: rc = hmR0VmxExitXcptGP(pVCpu, pMixedCtx, pVmxTransient); break;
11306 case X86_XCPT_NM: rc = hmR0VmxExitXcptNM(pVCpu, pMixedCtx, pVmxTransient); break;
11307 case X86_XCPT_MF: rc = hmR0VmxExitXcptMF(pVCpu, pMixedCtx, pVmxTransient); break;
11308 case X86_XCPT_DB: rc = hmR0VmxExitXcptDB(pVCpu, pMixedCtx, pVmxTransient); break;
11309 case X86_XCPT_BP: rc = hmR0VmxExitXcptBP(pVCpu, pMixedCtx, pVmxTransient); break;
11310 case X86_XCPT_AC: rc = hmR0VmxExitXcptAC(pVCpu, pMixedCtx, pVmxTransient); break;
11311
11312 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF);
11313 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11314 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
11315 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11316 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
11317 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11318 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
11319 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11320 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
11321 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11322 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS);
11323 rc = hmR0VmxExitXcptGeneric(pVCpu, pMixedCtx, pVmxTransient); break;
11324 default:
11325 {
11326 rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11327 AssertRCReturn(rc, rc);
11328
11329 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
11330 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
11331 {
11332 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
11333 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
11334 Assert(CPUMIsGuestInRealModeEx(pMixedCtx));
11335
11336 rc = hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
11337 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
11338 AssertRCReturn(rc, rc);
11339 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(uExitIntInfo),
11340 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode,
11341 0 /* GCPtrFaultAddress */);
11342 AssertRCReturn(rc, rc);
11343 }
11344 else
11345 {
11346 AssertMsgFailed(("Unexpected VM-exit caused by exception %#x\n", uVector));
11347 pVCpu->hm.s.u32HMError = uVector;
11348 rc = VERR_VMX_UNEXPECTED_EXCEPTION;
11349 }
11350 break;
11351 }
11352 }
11353 break;
11354 }
11355
11356 default:
11357 {
11358 pVCpu->hm.s.u32HMError = uExitIntInfo;
11359 rc = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
11360 AssertMsgFailed(("Unexpected interruption info %#x\n", VMX_EXIT_INTERRUPTION_INFO_TYPE(uExitIntInfo)));
11361 break;
11362 }
11363 }
11364 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
11365 return rc;
11366}
11367
11368
11369/**
11370 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
11371 */
11372HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11373{
11374 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11375
11376 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
11377 hmR0VmxClearIntWindowExitVmcs(pVCpu);
11378
11379 /* Deliver the pending interrupts via hmR0VmxEvaluatePendingEvent() and resume guest execution. */
11380 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
11381 return VINF_SUCCESS;
11382}
11383
11384
11385/**
11386 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
11387 */
11388HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11389{
11390 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11391 if (RT_UNLIKELY(!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_NMI_WINDOW_EXIT)))
11392 {
11393 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
11394 HMVMX_RETURN_UNEXPECTED_EXIT();
11395 }
11396
11397 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS));
11398
11399 /*
11400 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
11401 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
11402 */
11403 uint32_t uIntrState = 0;
11404 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &uIntrState);
11405 AssertRCReturn(rc, rc);
11406
11407 bool const fBlockSti = RT_BOOL(uIntrState & VMX_VMCS_GUEST_INTERRUPTIBILITY_STATE_BLOCK_STI);
11408 if ( fBlockSti
11409 && VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
11410 {
11411 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
11412 }
11413
11414 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
11415 hmR0VmxClearNmiWindowExitVmcs(pVCpu);
11416
11417 /* Deliver the pending NMI via hmR0VmxEvaluatePendingEvent() and resume guest execution. */
11418 return VINF_SUCCESS;
11419}
11420
11421
11422/**
11423 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
11424 */
11425HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11426{
11427 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11428 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
11429 return hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11430}
11431
11432
11433/**
11434 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
11435 */
11436HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11437{
11438 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11439 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
11440 return hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11441}
11442
11443
11444/**
11445 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
11446 */
11447HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11448{
11449 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11450 PVM pVM = pVCpu->CTX_SUFF(pVM);
11451 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11452 if (RT_LIKELY(rc == VINF_SUCCESS))
11453 {
11454 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11455 Assert(pVmxTransient->cbInstr == 2);
11456 }
11457 else
11458 {
11459 AssertMsgFailed(("hmR0VmxExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
11460 rc = VERR_EM_INTERPRETER;
11461 }
11462 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
11463 return rc;
11464}
11465
11466
11467/**
11468 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
11469 */
11470HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11471{
11472 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11473 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11474 AssertRCReturn(rc, rc);
11475
11476 if (pMixedCtx->cr4 & X86_CR4_SMXE)
11477 return VINF_EM_RAW_EMULATE_INSTR;
11478
11479 AssertMsgFailed(("hmR0VmxExitGetsec: unexpected VM-exit when CR4.SMXE is 0.\n"));
11480 HMVMX_RETURN_UNEXPECTED_EXIT();
11481}
11482
11483
11484/**
11485 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
11486 */
11487HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11488{
11489 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11490 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11491 AssertRCReturn(rc, rc);
11492
11493 PVM pVM = pVCpu->CTX_SUFF(pVM);
11494 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11495 if (RT_LIKELY(rc == VINF_SUCCESS))
11496 {
11497 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11498 Assert(pVmxTransient->cbInstr == 2);
11499 /* If we get a spurious VM-exit when offsetting is enabled, we must reset offsetting on VM-reentry. See @bugref{6634}. */
11500 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING)
11501 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
11502 }
11503 else
11504 rc = VERR_EM_INTERPRETER;
11505 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
11506 return rc;
11507}
11508
11509
11510/**
11511 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
11512 */
11513HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11514{
11515 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11516 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11517 rc |= hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx); /* For MSR_K8_TSC_AUX */
11518 AssertRCReturn(rc, rc);
11519
11520 PVM pVM = pVCpu->CTX_SUFF(pVM);
11521 rc = EMInterpretRdtscp(pVM, pVCpu, pMixedCtx);
11522 if (RT_SUCCESS(rc))
11523 {
11524 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11525 Assert(pVmxTransient->cbInstr == 3);
11526 /* If we get a spurious VM-exit when offsetting is enabled, we must reset offsetting on VM-reentry. See @bugref{6634}. */
11527 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TSC_OFFSETTING)
11528 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
11529 }
11530 else
11531 {
11532 AssertMsgFailed(("hmR0VmxExitRdtscp: EMInterpretRdtscp failed with %Rrc\n", rc));
11533 rc = VERR_EM_INTERPRETER;
11534 }
11535 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
11536 return rc;
11537}
11538
11539
11540/**
11541 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
11542 */
11543HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11544{
11545 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11546 int rc = hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11547 rc |= hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11548 AssertRCReturn(rc, rc);
11549
11550 PVM pVM = pVCpu->CTX_SUFF(pVM);
11551 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11552 if (RT_LIKELY(rc == VINF_SUCCESS))
11553 {
11554 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11555 Assert(pVmxTransient->cbInstr == 2);
11556 }
11557 else
11558 {
11559 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
11560 rc = VERR_EM_INTERPRETER;
11561 }
11562 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
11563 return rc;
11564}
11565
11566
11567/**
11568 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
11569 */
11570HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11571{
11572 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11573 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
11574
11575 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
11576 if (pVCpu->hm.s.fHypercallsEnabled)
11577 {
11578#if 0
11579 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
11580#else
11581 /* Aggressive state sync. for now. */
11582 int rc = hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
11583 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx); /* For long-mode checks in gimKvmHypercall(). */
11584 AssertRCReturn(rc, rc);
11585#endif
11586
11587 /* Perform the hypercall. */
11588 rcStrict = GIMHypercall(pVCpu, pMixedCtx);
11589 if (rcStrict == VINF_SUCCESS)
11590 {
11591 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11592 AssertRCReturn(rc, rc);
11593 }
11594 else
11595 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
11596 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
11597 || RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
11598
11599 /* If the hypercall changes anything other than guest's general-purpose registers,
11600 we would need to reload the guest changed bits here before VM-entry. */
11601 }
11602 else
11603 Log4(("hmR0VmxExitVmcall: Hypercalls not enabled\n"));
11604
11605 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
11606 if (RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)))
11607 {
11608 hmR0VmxSetPendingXcptUD(pVCpu, pMixedCtx);
11609 rcStrict = VINF_SUCCESS;
11610 }
11611
11612 return rcStrict;
11613}
11614
11615
11616/**
11617 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
11618 */
11619HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11620{
11621 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11622 PVM pVM = pVCpu->CTX_SUFF(pVM);
11623 Assert(!pVM->hm.s.fNestedPaging || pVCpu->hm.s.fUsingDebugLoop);
11624
11625 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
11626 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
11627 AssertRCReturn(rc, rc);
11628
11629 VBOXSTRICTRC rcStrict = EMInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx), pVmxTransient->uExitQualification);
11630 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
11631 rcStrict = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11632 else
11633 AssertMsg(rcStrict == VERR_EM_INTERPRETER, ("hmR0VmxExitInvlpg: EMInterpretInvlpg %#RX64 failed with %Rrc\n",
11634 pVmxTransient->uExitQualification, VBOXSTRICTRC_VAL(rcStrict)));
11635 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
11636 return rcStrict;
11637}
11638
11639
11640/**
11641 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
11642 */
11643HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11644{
11645 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11646 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11647 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
11648 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
11649 AssertRCReturn(rc, rc);
11650
11651 PVM pVM = pVCpu->CTX_SUFF(pVM);
11652 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11653 if (RT_LIKELY(rc == VINF_SUCCESS))
11654 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11655 else
11656 {
11657 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0VmxExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
11658 rc = VERR_EM_INTERPRETER;
11659 }
11660 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
11661 return rc;
11662}
11663
11664
11665/**
11666 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
11667 */
11668HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11669{
11670 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11671 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
11672 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
11673 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
11674 AssertRCReturn(rc, rc);
11675
11676 PVM pVM = pVCpu->CTX_SUFF(pVM);
11677 VBOXSTRICTRC rc2 = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
11678 rc = VBOXSTRICTRC_VAL(rc2);
11679 if (RT_LIKELY( rc == VINF_SUCCESS
11680 || rc == VINF_EM_HALT))
11681 {
11682 int rc3 = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11683 AssertRCReturn(rc3, rc3);
11684
11685 if ( rc == VINF_EM_HALT
11686 && EMMonitorWaitShouldContinue(pVCpu, pMixedCtx))
11687 {
11688 rc = VINF_SUCCESS;
11689 }
11690 }
11691 else
11692 {
11693 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0VmxExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
11694 rc = VERR_EM_INTERPRETER;
11695 }
11696 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
11697 ("hmR0VmxExitMwait: failed, invalid error code %Rrc\n", rc));
11698 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
11699 return rc;
11700}
11701
11702
11703/**
11704 * VM-exit handler for RSM (VMX_EXIT_RSM). Unconditional VM-exit.
11705 */
11706HMVMX_EXIT_NSRC_DECL hmR0VmxExitRsm(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11707{
11708 /*
11709 * Execution of RSM outside of SMM mode causes #UD regardless of VMX root or VMX non-root mode. In theory, we should never
11710 * get this VM-exit. This can happen only if dual-monitor treatment of SMI and VMX is enabled, which can (only?) be done by
11711 * executing VMCALL in VMX root operation. If we get here, something funny is going on.
11712 * See Intel spec. "33.15.5 Enabling the Dual-Monitor Treatment".
11713 */
11714 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11715 AssertMsgFailed(("Unexpected RSM VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
11716 HMVMX_RETURN_UNEXPECTED_EXIT();
11717}
11718
11719
11720/**
11721 * VM-exit handler for SMI (VMX_EXIT_SMI). Unconditional VM-exit.
11722 */
11723HMVMX_EXIT_NSRC_DECL hmR0VmxExitSmi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11724{
11725 /*
11726 * This can only happen if we support dual-monitor treatment of SMI, which can be activated by executing VMCALL in VMX
11727 * root operation. Only an STM (SMM transfer monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL
11728 * in VMX root mode or receive an SMI. If we get here, something funny is going on.
11729 * See Intel spec. "33.15.6 Activating the Dual-Monitor Treatment" and Intel spec. 25.3 "Other Causes of VM-Exits"
11730 */
11731 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11732 AssertMsgFailed(("Unexpected SMI VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
11733 HMVMX_RETURN_UNEXPECTED_EXIT();
11734}
11735
11736
11737/**
11738 * VM-exit handler for IO SMI (VMX_EXIT_IO_SMI). Unconditional VM-exit.
11739 */
11740HMVMX_EXIT_NSRC_DECL hmR0VmxExitIoSmi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11741{
11742 /* Same treatment as VMX_EXIT_SMI. See comment in hmR0VmxExitSmi(). */
11743 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11744 AssertMsgFailed(("Unexpected IO SMI VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
11745 HMVMX_RETURN_UNEXPECTED_EXIT();
11746}
11747
11748
11749/**
11750 * VM-exit handler for SIPI (VMX_EXIT_SIPI). Conditional VM-exit.
11751 */
11752HMVMX_EXIT_NSRC_DECL hmR0VmxExitSipi(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11753{
11754 /*
11755 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest activity state is used. We currently
11756 * don't make use of it (see hmR0VmxLoadGuestActivityState()) as our guests don't have direct access to the host LAPIC.
11757 * See Intel spec. 25.3 "Other Causes of VM-exits".
11758 */
11759 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11760 AssertMsgFailed(("Unexpected SIPI VM-exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
11761 HMVMX_RETURN_UNEXPECTED_EXIT();
11762}
11763
11764
11765/**
11766 * VM-exit handler for INIT signal (VMX_EXIT_INIT_SIGNAL). Unconditional
11767 * VM-exit.
11768 */
11769HMVMX_EXIT_NSRC_DECL hmR0VmxExitInitSignal(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11770{
11771 /*
11772 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
11773 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery" and Intel spec. 29.3 "VMX Instructions" for "VMXON".
11774 *
11775 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these VM-exits.
11776 * See Intel spec. "23.8 Restrictions on VMX operation".
11777 */
11778 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11779 return VINF_SUCCESS;
11780}
11781
11782
11783/**
11784 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
11785 * VM-exit.
11786 */
11787HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11788{
11789 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11790 return VINF_EM_RESET;
11791}
11792
11793
11794/**
11795 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
11796 */
11797HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11798{
11799 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11800 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_HLT_EXIT);
11801
11802 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
11803 AssertRCReturn(rc, rc);
11804
11805 if (EMShouldContinueAfterHalt(pVCpu, pMixedCtx)) /* Requires eflags. */
11806 rc = VINF_SUCCESS;
11807 else
11808 rc = VINF_EM_HALT;
11809
11810 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
11811 if (rc != VINF_SUCCESS)
11812 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
11813 return rc;
11814}
11815
11816
11817/**
11818 * VM-exit handler for instructions that result in a \#UD exception delivered to
11819 * the guest.
11820 */
11821HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11822{
11823 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11824 hmR0VmxSetPendingXcptUD(pVCpu, pMixedCtx);
11825 return VINF_SUCCESS;
11826}
11827
11828
11829/**
11830 * VM-exit handler for expiry of the VMX preemption timer.
11831 */
11832HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11833{
11834 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11835
11836 /* If the preemption-timer has expired, reinitialize the preemption timer on next VM-entry. */
11837 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
11838
11839 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
11840 PVM pVM = pVCpu->CTX_SUFF(pVM);
11841 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
11842 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
11843 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
11844}
11845
11846
11847/**
11848 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
11849 */
11850HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11851{
11852 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11853
11854 int rc = hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
11855 rc |= hmR0VmxSaveGuestRegsForIemExec(pVCpu, pMixedCtx, false /*fMemory*/, false /*fNeedRsp*/);
11856 rc |= hmR0VmxSaveGuestCR4(pVCpu, pMixedCtx);
11857 AssertRCReturn(rc, rc);
11858
11859 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbInstr);
11860 HMCPU_CF_SET(pVCpu, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS : HM_CHANGED_ALL_GUEST);
11861
11862 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pMixedCtx->cr4 & X86_CR4_OSXSAVE) && pMixedCtx->aXcr[0] != ASMGetXcr0();
11863
11864 return rcStrict;
11865}
11866
11867
11868/**
11869 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
11870 */
11871HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11872{
11873 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11874
11875 /* The guest should not invalidate the host CPU's TLBs, fallback to interpreter. */
11876 /** @todo implement EMInterpretInvpcid() */
11877 return VERR_EM_INTERPRETER;
11878}
11879
11880
11881/**
11882 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE).
11883 * Error VM-exit.
11884 */
11885HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11886{
11887 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
11888 AssertRCReturn(rc, rc);
11889
11890 rc = hmR0VmxCheckVmcsCtls(pVCpu);
11891 AssertRCReturn(rc, rc);
11892
11893 uint32_t uInvalidReason = hmR0VmxCheckGuestState(pVCpu->CTX_SUFF(pVM), pVCpu, pMixedCtx);
11894 NOREF(uInvalidReason);
11895
11896#ifdef VBOX_STRICT
11897 uint32_t uIntrState;
11898 RTHCUINTREG uHCReg;
11899 uint64_t u64Val;
11900 uint32_t u32Val;
11901
11902 rc = hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
11903 rc |= hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
11904 rc |= hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
11905 rc |= VMXReadVmcs32(VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE, &uIntrState);
11906 AssertRCReturn(rc, rc);
11907
11908 Log4(("uInvalidReason %u\n", uInvalidReason));
11909 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
11910 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
11911 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
11912 Log4(("VMX_VMCS32_GUEST_INTERRUPTIBILITY_STATE %#RX32\n", uIntrState));
11913
11914 rc = VMXReadVmcs32(VMX_VMCS_GUEST_CR0, &u32Val); AssertRC(rc);
11915 Log4(("VMX_VMCS_GUEST_CR0 %#RX32\n", u32Val));
11916 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_MASK, &uHCReg); AssertRC(rc);
11917 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RHr\n", uHCReg));
11918 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR0_READ_SHADOW, &uHCReg); AssertRC(rc);
11919 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
11920 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_MASK, &uHCReg); AssertRC(rc);
11921 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RHr\n", uHCReg));
11922 rc = VMXReadVmcsHstN(VMX_VMCS_CTRL_CR4_READ_SHADOW, &uHCReg); AssertRC(rc);
11923 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RHr\n", uHCReg));
11924 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
11925 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
11926#else
11927 NOREF(pVmxTransient);
11928#endif
11929
11930 HMDumpRegs(pVCpu->CTX_SUFF(pVM), pVCpu, pMixedCtx);
11931 return VERR_VMX_INVALID_GUEST_STATE;
11932}
11933
11934
11935/**
11936 * VM-exit handler for VM-entry failure due to an MSR-load
11937 * (VMX_EXIT_ERR_MSR_LOAD). Error VM-exit.
11938 */
11939HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrMsrLoad(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11940{
11941 NOREF(pVmxTransient);
11942 AssertMsgFailed(("Unexpected MSR-load exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx)); NOREF(pMixedCtx);
11943 HMVMX_RETURN_UNEXPECTED_EXIT();
11944}
11945
11946
11947/**
11948 * VM-exit handler for VM-entry failure due to a machine-check event
11949 * (VMX_EXIT_ERR_MACHINE_CHECK). Error VM-exit.
11950 */
11951HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrMachineCheck(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11952{
11953 NOREF(pVmxTransient);
11954 AssertMsgFailed(("Unexpected machine-check event exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx)); NOREF(pMixedCtx);
11955 HMVMX_RETURN_UNEXPECTED_EXIT();
11956}
11957
11958
11959/**
11960 * VM-exit handler for all undefined reasons. Should never ever happen.. in
11961 * theory.
11962 */
11963HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUndefined(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11964{
11965 AssertMsgFailed(("Huh!? Undefined VM-exit reason %d. pVCpu=%p pMixedCtx=%p\n", pVmxTransient->uExitReason, pVCpu, pMixedCtx));
11966 NOREF(pVCpu); NOREF(pMixedCtx); NOREF(pVmxTransient);
11967 return VERR_VMX_UNDEFINED_EXIT_CODE;
11968}
11969
11970
11971/**
11972 * VM-exit handler for XDTR (LGDT, SGDT, LIDT, SIDT) accesses
11973 * (VMX_EXIT_XDTR_ACCESS) and LDT and TR access (LLDT, LTR, SLDT, STR).
11974 * Conditional VM-exit.
11975 */
11976HMVMX_EXIT_DECL hmR0VmxExitXdtrAccess(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11977{
11978 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11979
11980 /* By default, we don't enable VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT. */
11981 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitXdtrAccess);
11982 if (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_DESCRIPTOR_TABLE_EXIT)
11983 return VERR_EM_INTERPRETER;
11984 AssertMsgFailed(("Unexpected XDTR access. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
11985 HMVMX_RETURN_UNEXPECTED_EXIT();
11986}
11987
11988
11989/**
11990 * VM-exit handler for RDRAND (VMX_EXIT_RDRAND). Conditional VM-exit.
11991 */
11992HMVMX_EXIT_DECL hmR0VmxExitRdrand(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
11993{
11994 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
11995
11996 /* By default, we don't enable VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT. */
11997 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdrand);
11998 if (pVCpu->hm.s.vmx.u32ProcCtls2 & VMX_VMCS_CTRL_PROC_EXEC2_RDRAND_EXIT)
11999 return VERR_EM_INTERPRETER;
12000 AssertMsgFailed(("Unexpected RDRAND exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12001 HMVMX_RETURN_UNEXPECTED_EXIT();
12002}
12003
12004
12005/**
12006 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
12007 */
12008HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12009{
12010 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12011
12012 /* EMInterpretRdmsr() requires CR0, Eflags and SS segment register. */
12013 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
12014 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
12015 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12016 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS))
12017 {
12018 rc |= hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
12019 rc |= hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
12020 }
12021 AssertRCReturn(rc, rc);
12022 Log4(("ecx=%#RX32\n", pMixedCtx->ecx));
12023
12024#ifdef VBOX_STRICT
12025 if (pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS)
12026 {
12027 if ( hmR0VmxIsAutoLoadStoreGuestMsr(pVCpu, pMixedCtx->ecx)
12028 && pMixedCtx->ecx != MSR_K6_EFER)
12029 {
12030 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
12031 pMixedCtx->ecx));
12032 HMVMX_RETURN_UNEXPECTED_EXIT();
12033 }
12034 if (hmR0VmxIsLazyGuestMsr(pVCpu, pMixedCtx->ecx))
12035 {
12036 VMXMSREXITREAD enmRead;
12037 VMXMSREXITWRITE enmWrite;
12038 int rc2 = hmR0VmxGetMsrPermission(pVCpu, pMixedCtx->ecx, &enmRead, &enmWrite);
12039 AssertRCReturn(rc2, rc2);
12040 if (enmRead == VMXMSREXIT_PASSTHRU_READ)
12041 {
12042 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", pMixedCtx->ecx));
12043 HMVMX_RETURN_UNEXPECTED_EXIT();
12044 }
12045 }
12046 }
12047#endif
12048
12049 PVM pVM = pVCpu->CTX_SUFF(pVM);
12050 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
12051 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER,
12052 ("hmR0VmxExitRdmsr: failed, invalid error code %Rrc\n", rc));
12053 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
12054 if (RT_SUCCESS(rc))
12055 {
12056 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12057 Assert(pVmxTransient->cbInstr == 2);
12058 }
12059 return rc;
12060}
12061
12062
12063/**
12064 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
12065 */
12066HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12067{
12068 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12069 PVM pVM = pVCpu->CTX_SUFF(pVM);
12070 int rc = VINF_SUCCESS;
12071
12072 /* EMInterpretWrmsr() requires CR0, EFLAGS and SS segment register. */
12073 rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
12074 rc |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx);
12075 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12076 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS))
12077 {
12078 rc |= hmR0VmxSaveGuestLazyMsrs(pVCpu, pMixedCtx);
12079 rc |= hmR0VmxSaveGuestAutoLoadStoreMsrs(pVCpu, pMixedCtx);
12080 }
12081 AssertRCReturn(rc, rc);
12082 Log4(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", pMixedCtx->ecx, pMixedCtx->edx, pMixedCtx->eax));
12083
12084 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
12085 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER, ("hmR0VmxExitWrmsr: failed, invalid error code %Rrc\n", rc));
12086 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
12087
12088 if (RT_SUCCESS(rc))
12089 {
12090 rc = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12091
12092 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
12093 if ( pMixedCtx->ecx >= MSR_IA32_X2APIC_START
12094 && pMixedCtx->ecx <= MSR_IA32_X2APIC_END)
12095 {
12096 /* We've already saved the APIC related guest-state (TPR) in hmR0VmxPostRunGuest(). When full APIC register
12097 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCS before
12098 EMInterpretWrmsr() changes it. */
12099 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
12100 }
12101 else if (pMixedCtx->ecx == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
12102 pVmxTransient->fUpdateTscOffsettingAndPreemptTimer = true;
12103 else if (pMixedCtx->ecx == MSR_K6_EFER)
12104 {
12105 /*
12106 * If the guest touches EFER we need to update the VM-Entry and VM-Exit controls as well,
12107 * even if it is -not- touching bits that cause paging mode changes (LMA/LME). We care about
12108 * the other bits as well, SCE and NXE. See @bugref{7368}.
12109 */
12110 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_CTLS | HM_CHANGED_VMX_EXIT_CTLS);
12111 }
12112
12113 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not supported. */
12114 if (!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_MSR_BITMAPS))
12115 {
12116 switch (pMixedCtx->ecx)
12117 {
12118 case MSR_IA32_SYSENTER_CS: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
12119 case MSR_IA32_SYSENTER_EIP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
12120 case MSR_IA32_SYSENTER_ESP: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
12121 case MSR_K8_FS_BASE: /* no break */
12122 case MSR_K8_GS_BASE: HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS); break;
12123 case MSR_K6_EFER: /* already handled above */ break;
12124 default:
12125 {
12126 if (hmR0VmxIsAutoLoadStoreGuestMsr(pVCpu, pMixedCtx->ecx))
12127 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
12128 else if (hmR0VmxIsLazyGuestMsr(pVCpu, pMixedCtx->ecx))
12129 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
12130 break;
12131 }
12132 }
12133 }
12134#ifdef VBOX_STRICT
12135 else
12136 {
12137 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
12138 switch (pMixedCtx->ecx)
12139 {
12140 case MSR_IA32_SYSENTER_CS:
12141 case MSR_IA32_SYSENTER_EIP:
12142 case MSR_IA32_SYSENTER_ESP:
12143 case MSR_K8_FS_BASE:
12144 case MSR_K8_GS_BASE:
12145 {
12146 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", pMixedCtx->ecx));
12147 HMVMX_RETURN_UNEXPECTED_EXIT();
12148 }
12149
12150 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
12151 default:
12152 {
12153 if (hmR0VmxIsAutoLoadStoreGuestMsr(pVCpu, pMixedCtx->ecx))
12154 {
12155 /* EFER writes are always intercepted, see hmR0VmxLoadGuestMsrs(). */
12156 if (pMixedCtx->ecx != MSR_K6_EFER)
12157 {
12158 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
12159 pMixedCtx->ecx));
12160 HMVMX_RETURN_UNEXPECTED_EXIT();
12161 }
12162 }
12163
12164 if (hmR0VmxIsLazyGuestMsr(pVCpu, pMixedCtx->ecx))
12165 {
12166 VMXMSREXITREAD enmRead;
12167 VMXMSREXITWRITE enmWrite;
12168 int rc2 = hmR0VmxGetMsrPermission(pVCpu, pMixedCtx->ecx, &enmRead, &enmWrite);
12169 AssertRCReturn(rc2, rc2);
12170 if (enmWrite == VMXMSREXIT_PASSTHRU_WRITE)
12171 {
12172 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", pMixedCtx->ecx));
12173 HMVMX_RETURN_UNEXPECTED_EXIT();
12174 }
12175 }
12176 break;
12177 }
12178 }
12179 }
12180#endif /* VBOX_STRICT */
12181 }
12182 return rc;
12183}
12184
12185
12186/**
12187 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
12188 */
12189HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12190{
12191 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12192
12193 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
12194 return VINF_EM_RAW_INTERRUPT;
12195}
12196
12197
12198/**
12199 * VM-exit handler for when the TPR value is lowered below the specified
12200 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
12201 */
12202HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12203{
12204 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12205 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW);
12206
12207 /*
12208 * The TPR has already been updated, see hmR0VMXPostRunGuest(). RIP is also updated as part of the VM-exit by VT-x. Update
12209 * the threshold in the VMCS, deliver the pending interrupt via hmR0VmxPreRunGuest()->hmR0VmxInjectPendingEvent() and
12210 * resume guest execution.
12211 */
12212 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
12213 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
12214 return VINF_SUCCESS;
12215}
12216
12217
12218/**
12219 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
12220 * VM-exit.
12221 *
12222 * @retval VINF_SUCCESS when guest execution can continue.
12223 * @retval VINF_PGM_CHANGE_MODE when shadow paging mode changed, back to ring-3.
12224 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
12225 * @retval VERR_EM_INTERPRETER when something unexpected happened, fallback to
12226 * interpreter.
12227 */
12228HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12229{
12230 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12231 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
12232 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12233 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12234 AssertRCReturn(rc, rc);
12235
12236 RTGCUINTPTR const uExitQualification = pVmxTransient->uExitQualification;
12237 uint32_t const uAccessType = VMX_EXIT_QUALIFICATION_CRX_ACCESS(uExitQualification);
12238 PVM pVM = pVCpu->CTX_SUFF(pVM);
12239 VBOXSTRICTRC rcStrict;
12240 rc = hmR0VmxSaveGuestRegsForIemExec(pVCpu, pMixedCtx, false /*fMemory*/, true /*fNeedRsp*/);
12241 switch (uAccessType)
12242 {
12243 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_WRITE: /* MOV to CRx */
12244 {
12245 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12246 AssertRCReturn(rc, rc);
12247
12248 rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, pVmxTransient->cbInstr,
12249 VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification),
12250 VMX_EXIT_QUALIFICATION_CRX_GENREG(uExitQualification));
12251 AssertMsg( rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT || rcStrict == VINF_PGM_CHANGE_MODE
12252 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12253 switch (VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification))
12254 {
12255 case 0: /* CR0 */
12256 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
12257 Log4(("CRX CR0 write rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pMixedCtx->cr0));
12258 break;
12259 case 2: /* CR2 */
12260 /* Nothing to do here, CR2 it's not part of the VMCS. */
12261 break;
12262 case 3: /* CR3 */
12263 Assert(!pVM->hm.s.fNestedPaging || !CPUMIsGuestPagingEnabledEx(pMixedCtx) || pVCpu->hm.s.fUsingDebugLoop);
12264 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
12265 Log4(("CRX CR3 write rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pMixedCtx->cr3));
12266 break;
12267 case 4: /* CR4 */
12268 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
12269 Log4(("CRX CR4 write rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n",
12270 VBOXSTRICTRC_VAL(rcStrict), pMixedCtx->cr4, pVCpu->hm.s.fLoadSaveGuestXcr0));
12271 break;
12272 case 8: /* CR8 */
12273 Assert(!(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW));
12274 /* CR8 contains the APIC TPR. Was updated by IEMExecDecodedMovCRxWrite(). */
12275 HMCPU_CF_SET(pVCpu, HM_CHANGED_VMX_GUEST_APIC_STATE);
12276 break;
12277 default:
12278 AssertMsgFailed(("Invalid CRx register %#x\n", VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification)));
12279 break;
12280 }
12281
12282 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxWrite[VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification)]);
12283 break;
12284 }
12285
12286 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_READ: /* MOV from CRx */
12287 {
12288 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12289 AssertRCReturn(rc, rc);
12290
12291 Assert( !pVM->hm.s.fNestedPaging
12292 || !CPUMIsGuestPagingEnabledEx(pMixedCtx)
12293 || pVCpu->hm.s.fUsingDebugLoop
12294 || VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification) != 3);
12295
12296 /* CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
12297 Assert( VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification) != 8
12298 || !(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW));
12299
12300 rcStrict = IEMExecDecodedMovCRxRead(pVCpu, pVmxTransient->cbInstr,
12301 VMX_EXIT_QUALIFICATION_CRX_GENREG(uExitQualification),
12302 VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification));
12303 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12304 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification)]);
12305 Log4(("CRX CR%d Read access rcStrict=%Rrc\n", VMX_EXIT_QUALIFICATION_CRX_REGISTER(uExitQualification),
12306 VBOXSTRICTRC_VAL(rcStrict)));
12307 break;
12308 }
12309
12310 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_CLTS: /* CLTS (Clear Task-Switch Flag in CR0) */
12311 {
12312 AssertRCReturn(rc, rc);
12313 rcStrict = IEMExecDecodedClts(pVCpu, pVmxTransient->cbInstr);
12314 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12315 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
12316 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
12317 Log4(("CRX CLTS rcStrict=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
12318 break;
12319 }
12320
12321 case VMX_EXIT_QUALIFICATION_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
12322 {
12323 AssertRCReturn(rc, rc);
12324 rcStrict = IEMExecDecodedLmsw(pVCpu, pVmxTransient->cbInstr,
12325 VMX_EXIT_QUALIFICATION_CRX_LMSW_DATA(uExitQualification));
12326 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_IEM_RAISED_XCPT || rcStrict == VINF_PGM_CHANGE_MODE,
12327 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12328 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
12329 Log4(("CRX LMSW rcStrict=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
12330 break;
12331 }
12332
12333 default:
12334 AssertMsgFailedReturn(("Invalid access-type in Mov CRx VM-exit qualification %#x\n", uAccessType),
12335 VERR_VMX_UNEXPECTED_EXCEPTION);
12336 }
12337
12338 HMCPU_CF_SET(pVCpu, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS : HM_CHANGED_ALL_GUEST);
12339 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
12340 NOREF(pVM);
12341 return rcStrict;
12342}
12343
12344
12345/**
12346 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
12347 * VM-exit.
12348 */
12349HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12350{
12351 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12352 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
12353
12354 int rc2 = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12355 rc2 |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12356 rc2 |= hmR0VmxSaveGuestRip(pVCpu, pMixedCtx);
12357 rc2 |= hmR0VmxSaveGuestRflags(pVCpu, pMixedCtx); /* Eflag checks in EMInterpretDisasCurrent(). */
12358 rc2 |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx); /* CR0 checks & PGM* in EMInterpretDisasCurrent(). */
12359 rc2 |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx); /* SELM checks in EMInterpretDisasCurrent(). */
12360 /* EFER also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
12361 AssertRCReturn(rc2, rc2);
12362
12363 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
12364 uint32_t uIOPort = VMX_EXIT_QUALIFICATION_IO_PORT(pVmxTransient->uExitQualification);
12365 uint8_t uIOWidth = VMX_EXIT_QUALIFICATION_IO_WIDTH(pVmxTransient->uExitQualification);
12366 bool fIOWrite = ( VMX_EXIT_QUALIFICATION_IO_DIRECTION(pVmxTransient->uExitQualification)
12367 == VMX_EXIT_QUALIFICATION_IO_DIRECTION_OUT);
12368 bool fIOString = VMX_EXIT_QUALIFICATION_IO_IS_STRING(pVmxTransient->uExitQualification);
12369 bool fGstStepping = RT_BOOL(pMixedCtx->eflags.Bits.u1TF);
12370 bool fDbgStepping = pVCpu->hm.s.fSingleInstruction;
12371 AssertReturn(uIOWidth <= 3 && uIOWidth != 2, VERR_VMX_IPE_1);
12372
12373 /* I/O operation lookup arrays. */
12374 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses. */
12375 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving the result (in AL/AX/EAX). */
12376
12377 VBOXSTRICTRC rcStrict;
12378 uint32_t const cbValue = s_aIOSizes[uIOWidth];
12379 uint32_t const cbInstr = pVmxTransient->cbInstr;
12380 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
12381 PVM pVM = pVCpu->CTX_SUFF(pVM);
12382 if (fIOString)
12383 {
12384#ifdef VBOX_WITH_2ND_IEM_STEP /* This used to gurus with debian 32-bit guest without NP (on ATA reads).
12385 See @bugref{5752#c158}. Should work now. */
12386 /*
12387 * INS/OUTS - I/O String instruction.
12388 *
12389 * Use instruction-information if available, otherwise fall back on
12390 * interpreting the instruction.
12391 */
12392 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pMixedCtx->cs.Sel, pMixedCtx->rip, uIOPort, cbValue,
12393 fIOWrite ? 'w' : 'r'));
12394 AssertReturn(pMixedCtx->dx == uIOPort, VERR_VMX_IPE_2);
12395 if (MSR_IA32_VMX_BASIC_INFO_VMCS_INS_OUTS(pVM->hm.s.vmx.Msrs.u64BasicInfo))
12396 {
12397 rc2 = hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
12398 /** @todo optimize this, IEM should request the additional state if it needs it (GP, PF, ++). */
12399 rc2 |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
12400 AssertRCReturn(rc2, rc2);
12401 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
12402 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
12403 IEMMODE enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
12404 bool fRep = VMX_EXIT_QUALIFICATION_IO_IS_REP(pVmxTransient->uExitQualification);
12405 if (fIOWrite)
12406 {
12407 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
12408 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
12409 }
12410 else
12411 {
12412 /*
12413 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
12414 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
12415 * See Intel Instruction spec. for "INS".
12416 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
12417 */
12418 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
12419 }
12420 }
12421 else
12422 {
12423 /** @todo optimize this, IEM should request the additional state if it needs it (GP, PF, ++). */
12424 rc2 = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
12425 AssertRCReturn(rc2, rc2);
12426 rcStrict = IEMExecOne(pVCpu);
12427 }
12428 /** @todo IEM needs to be setting these flags somehow. */
12429 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP);
12430 fUpdateRipAlready = true;
12431#else
12432 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
12433 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
12434 if (RT_SUCCESS(rcStrict))
12435 {
12436 if (fIOWrite)
12437 {
12438 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx), uIOPort, pDis->fPrefix,
12439 (DISCPUMODE)pDis->uAddrMode, cbValue);
12440 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
12441 }
12442 else
12443 {
12444 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx), uIOPort, pDis->fPrefix,
12445 (DISCPUMODE)pDis->uAddrMode, cbValue);
12446 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
12447 }
12448 }
12449 else
12450 {
12451 AssertMsg(rcStrict == VERR_EM_INTERPRETER, ("rcStrict=%Rrc RIP=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict),
12452 pMixedCtx->rip));
12453 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
12454 }
12455#endif
12456 }
12457 else
12458 {
12459 /*
12460 * IN/OUT - I/O instruction.
12461 */
12462 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c\n", pMixedCtx->cs.Sel, pMixedCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
12463 uint32_t const uAndVal = s_aIOOpAnd[uIOWidth];
12464 Assert(!VMX_EXIT_QUALIFICATION_IO_IS_REP(pVmxTransient->uExitQualification));
12465 if (fIOWrite)
12466 {
12467 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pMixedCtx->eax & uAndVal, cbValue);
12468 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
12469 }
12470 else
12471 {
12472 uint32_t u32Result = 0;
12473 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
12474 if (IOM_SUCCESS(rcStrict))
12475 {
12476 /* Save result of I/O IN instr. in AL/AX/EAX. */
12477 pMixedCtx->eax = (pMixedCtx->eax & ~uAndVal) | (u32Result & uAndVal);
12478 }
12479 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
12480 HMR0SavePendingIOPortRead(pVCpu, pMixedCtx->rip, pMixedCtx->rip + cbInstr, uIOPort, uAndVal, cbValue);
12481 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
12482 }
12483 }
12484
12485 if (IOM_SUCCESS(rcStrict))
12486 {
12487 if (!fUpdateRipAlready)
12488 {
12489 hmR0VmxAdvanceGuestRipBy(pVCpu, pMixedCtx, cbInstr);
12490 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP);
12491 }
12492
12493 /*
12494 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru while booting Fedora 17 64-bit guest.
12495 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
12496 */
12497 if (fIOString)
12498 {
12499 /** @todo Single-step for INS/OUTS with REP prefix? */
12500 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RFLAGS);
12501 }
12502 else if ( !fDbgStepping
12503 && fGstStepping)
12504 {
12505 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
12506 }
12507
12508 /*
12509 * If any I/O breakpoints are armed, we need to check if one triggered
12510 * and take appropriate action.
12511 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
12512 */
12513 rc2 = hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
12514 AssertRCReturn(rc2, rc2);
12515
12516 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
12517 * execution engines about whether hyper BPs and such are pending. */
12518 uint32_t const uDr7 = pMixedCtx->dr[7];
12519 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
12520 && X86_DR7_ANY_RW_IO(uDr7)
12521 && (pMixedCtx->cr4 & X86_CR4_DE))
12522 || DBGFBpIsHwIoArmed(pVM)))
12523 {
12524 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
12525
12526 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
12527 VMMRZCallRing3Disable(pVCpu);
12528 HM_DISABLE_PREEMPT();
12529
12530 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
12531
12532 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pMixedCtx, uIOPort, cbValue);
12533 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
12534 {
12535 /* Raise #DB. */
12536 if (fIsGuestDbgActive)
12537 ASMSetDR6(pMixedCtx->dr[6]);
12538 if (pMixedCtx->dr[7] != uDr7)
12539 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
12540
12541 hmR0VmxSetPendingXcptDB(pVCpu, pMixedCtx);
12542 }
12543 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
12544 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
12545 else if ( rcStrict2 != VINF_SUCCESS
12546 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
12547 rcStrict = rcStrict2;
12548 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
12549
12550 HM_RESTORE_PREEMPT();
12551 VMMRZCallRing3Enable(pVCpu);
12552 }
12553 }
12554
12555#ifdef VBOX_STRICT
12556 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
12557 Assert(!fIOWrite);
12558 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
12559 Assert(fIOWrite);
12560 else
12561 {
12562#if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
12563 * statuses, that the VMM device and some others may return. See
12564 * IOM_SUCCESS() for guidance. */
12565 AssertMsg( RT_FAILURE(rcStrict)
12566 || rcStrict == VINF_SUCCESS
12567 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
12568 || rcStrict == VINF_EM_DBG_BREAKPOINT
12569 || rcStrict == VINF_EM_RAW_GUEST_TRAP
12570 || rcStrict == VINF_EM_RAW_TO_R3
12571 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
12572#endif
12573 }
12574#endif
12575
12576 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
12577 return rcStrict;
12578}
12579
12580
12581/**
12582 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
12583 * VM-exit.
12584 */
12585HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12586{
12587 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12588
12589 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
12590 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12591 AssertRCReturn(rc, rc);
12592 if (VMX_EXIT_QUALIFICATION_TASK_SWITCH_TYPE(pVmxTransient->uExitQualification) == VMX_EXIT_QUALIFICATION_TASK_SWITCH_TYPE_IDT)
12593 {
12594 rc = hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
12595 AssertRCReturn(rc, rc);
12596 if (VMX_IDT_VECTORING_INFO_VALID(pVmxTransient->uIdtVectoringInfo))
12597 {
12598 uint32_t uIntType = VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo);
12599
12600 uint32_t uVector = VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo);
12601 bool fErrorCodeValid = VMX_IDT_VECTORING_INFO_ERROR_CODE_IS_VALID(pVmxTransient->uIdtVectoringInfo);
12602
12603 /* Save it as a pending event and it'll be converted to a TRPM event on the way out to ring-3. */
12604 Assert(!pVCpu->hm.s.Event.fPending);
12605 pVCpu->hm.s.Event.fPending = true;
12606 pVCpu->hm.s.Event.u64IntInfo = pVmxTransient->uIdtVectoringInfo;
12607 rc = hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
12608 AssertRCReturn(rc, rc);
12609 if (fErrorCodeValid)
12610 pVCpu->hm.s.Event.u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
12611 else
12612 pVCpu->hm.s.Event.u32ErrCode = 0;
12613 if ( uIntType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
12614 && uVector == X86_XCPT_PF)
12615 {
12616 pVCpu->hm.s.Event.GCPtrFaultAddress = pMixedCtx->cr2;
12617 }
12618
12619 Log4(("Pending event on TaskSwitch uIntType=%#x uVector=%#x\n", uIntType, uVector));
12620 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
12621 return VINF_EM_RAW_INJECT_TRPM_EVENT;
12622 }
12623 }
12624
12625 /* Fall back to the interpreter to emulate the task-switch. */
12626 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
12627 return VERR_EM_INTERPRETER;
12628}
12629
12630
12631/**
12632 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
12633 */
12634HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12635{
12636 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12637 Assert(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG);
12638 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_MONITOR_TRAP_FLAG;
12639 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
12640 AssertRCReturn(rc, rc);
12641 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMtf);
12642 return VINF_EM_DBG_STEPPED;
12643}
12644
12645
12646/**
12647 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
12648 */
12649HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12650{
12651 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12652
12653 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
12654
12655 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
12656 VBOXSTRICTRC rcStrict1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
12657 if (RT_LIKELY(rcStrict1 == VINF_SUCCESS))
12658 {
12659 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
12660 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
12661 {
12662 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
12663 return VERR_EM_INTERPRETER;
12664 }
12665 }
12666 else
12667 {
12668 if (rcStrict1 == VINF_HM_DOUBLE_FAULT)
12669 rcStrict1 = VINF_SUCCESS;
12670 return rcStrict1;
12671 }
12672
12673#if 0
12674 /** @todo Investigate if IOMMMIOPhysHandler() requires a lot of state, for now
12675 * just sync the whole thing. */
12676 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
12677#else
12678 /* Aggressive state sync. for now. */
12679 int rc = hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
12680 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12681 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12682#endif
12683 rc |= hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12684 AssertRCReturn(rc, rc);
12685
12686 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
12687 uint32_t uAccessType = VMX_EXIT_QUALIFICATION_APIC_ACCESS_TYPE(pVmxTransient->uExitQualification);
12688 VBOXSTRICTRC rcStrict2;
12689 switch (uAccessType)
12690 {
12691 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
12692 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
12693 {
12694 AssertMsg( !(pVCpu->hm.s.vmx.u32ProcCtls & VMX_VMCS_CTRL_PROC_EXEC_USE_TPR_SHADOW)
12695 || VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(pVmxTransient->uExitQualification) != 0x80,
12696 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
12697
12698 RTGCPHYS GCPhys = pMixedCtx->msrApicBase; /* Always up-to-date, msrApicBase is not part of the VMCS. */
12699 GCPhys &= PAGE_BASE_GC_MASK;
12700 GCPhys += VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(pVmxTransient->uExitQualification);
12701 PVM pVM = pVCpu->CTX_SUFF(pVM);
12702 Log4(("ApicAccess uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
12703 VMX_EXIT_QUALIFICATION_APIC_ACCESS_OFFSET(pVmxTransient->uExitQualification)));
12704
12705 rcStrict2 = IOMMMIOPhysHandler(pVM, pVCpu,
12706 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW,
12707 CPUMCTX2CORE(pMixedCtx), GCPhys);
12708 Log4(("ApicAccess rcStrict2=%d\n", VBOXSTRICTRC_VAL(rcStrict2)));
12709 if ( rcStrict2 == VINF_SUCCESS
12710 || rcStrict2 == VERR_PAGE_TABLE_NOT_PRESENT
12711 || rcStrict2 == VERR_PAGE_NOT_PRESENT)
12712 {
12713 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
12714 | HM_CHANGED_GUEST_RSP
12715 | HM_CHANGED_GUEST_RFLAGS
12716 | HM_CHANGED_VMX_GUEST_APIC_STATE);
12717 rcStrict2 = VINF_SUCCESS;
12718 }
12719 break;
12720 }
12721
12722 default:
12723 Log4(("ApicAccess uAccessType=%#x\n", uAccessType));
12724 rcStrict2 = VINF_EM_RAW_EMULATE_INSTR;
12725 break;
12726 }
12727
12728 if (rcStrict2 != VINF_SUCCESS)
12729 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
12730 return rcStrict2;
12731}
12732
12733
12734/**
12735 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
12736 * VM-exit.
12737 */
12738HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12739{
12740 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12741
12742 /* We should -not- get this VM-exit if the guest's debug registers were active. */
12743 if (pVmxTransient->fWasGuestDebugStateActive)
12744 {
12745 AssertMsgFailed(("Unexpected MOV DRx exit. pVCpu=%p pMixedCtx=%p\n", pVCpu, pMixedCtx));
12746 HMVMX_RETURN_UNEXPECTED_EXIT();
12747 }
12748
12749 if ( !pVCpu->hm.s.fSingleInstruction
12750 && !pVmxTransient->fWasHyperDebugStateActive)
12751 {
12752 Assert(!DBGFIsStepping(pVCpu));
12753 Assert(pVCpu->hm.s.vmx.u32XcptBitmap & RT_BIT_32(X86_XCPT_DB));
12754
12755 /* Don't intercept MOV DRx any more. */
12756 pVCpu->hm.s.vmx.u32ProcCtls &= ~VMX_VMCS_CTRL_PROC_EXEC_MOV_DR_EXIT;
12757 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVCpu->hm.s.vmx.u32ProcCtls);
12758 AssertRCReturn(rc, rc);
12759
12760 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
12761 VMMRZCallRing3Disable(pVCpu);
12762 HM_DISABLE_PREEMPT();
12763
12764 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
12765 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
12766 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
12767
12768 HM_RESTORE_PREEMPT();
12769 VMMRZCallRing3Enable(pVCpu);
12770
12771#ifdef VBOX_WITH_STATISTICS
12772 rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12773 AssertRCReturn(rc, rc);
12774 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(pVmxTransient->uExitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
12775 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
12776 else
12777 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
12778#endif
12779 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
12780 return VINF_SUCCESS;
12781 }
12782
12783 /*
12784 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER, CS. EFER is always up-to-date.
12785 * Update the segment registers and DR7 from the CPU.
12786 */
12787 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12788 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12789 rc |= hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
12790 AssertRCReturn(rc, rc);
12791 Log4(("CS:RIP=%04x:%08RX64\n", pMixedCtx->cs.Sel, pMixedCtx->rip));
12792
12793 PVM pVM = pVCpu->CTX_SUFF(pVM);
12794 if (VMX_EXIT_QUALIFICATION_DRX_DIRECTION(pVmxTransient->uExitQualification) == VMX_EXIT_QUALIFICATION_DRX_DIRECTION_WRITE)
12795 {
12796 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx),
12797 VMX_EXIT_QUALIFICATION_DRX_REGISTER(pVmxTransient->uExitQualification),
12798 VMX_EXIT_QUALIFICATION_DRX_GENREG(pVmxTransient->uExitQualification));
12799 if (RT_SUCCESS(rc))
12800 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
12801 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
12802 }
12803 else
12804 {
12805 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx),
12806 VMX_EXIT_QUALIFICATION_DRX_GENREG(pVmxTransient->uExitQualification),
12807 VMX_EXIT_QUALIFICATION_DRX_REGISTER(pVmxTransient->uExitQualification));
12808 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
12809 }
12810
12811 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
12812 if (RT_SUCCESS(rc))
12813 {
12814 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12815 AssertRCReturn(rc2, rc2);
12816 return VINF_SUCCESS;
12817 }
12818 return rc;
12819}
12820
12821
12822/**
12823 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
12824 * Conditional VM-exit.
12825 */
12826HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12827{
12828 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12829 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
12830
12831 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
12832 VBOXSTRICTRC rcStrict1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
12833 if (RT_LIKELY(rcStrict1 == VINF_SUCCESS))
12834 {
12835 /* If event delivery causes an EPT misconfig (MMIO), go back to instruction emulation as otherwise
12836 injecting the original pending event would most likely cause the same EPT misconfig VM-exit. */
12837 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
12838 {
12839 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
12840 return VERR_EM_INTERPRETER;
12841 }
12842 }
12843 else
12844 {
12845 if (rcStrict1 == VINF_HM_DOUBLE_FAULT)
12846 rcStrict1 = VINF_SUCCESS;
12847 return rcStrict1;
12848 }
12849
12850 RTGCPHYS GCPhys = 0;
12851 int rc = VMXReadVmcs64(VMX_VMCS64_EXIT_GUEST_PHYS_ADDR_FULL, &GCPhys);
12852
12853#if 0
12854 rc |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx); /** @todo Can we do better? */
12855#else
12856 /* Aggressive state sync. for now. */
12857 rc |= hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
12858 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12859 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12860#endif
12861 AssertRCReturn(rc, rc);
12862
12863 /*
12864 * If we succeed, resume guest execution.
12865 * If we fail in interpreting the instruction because we couldn't get the guest physical address
12866 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
12867 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
12868 * weird case. See @bugref{6043}.
12869 */
12870 PVM pVM = pVCpu->CTX_SUFF(pVM);
12871 VBOXSTRICTRC rcStrict2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pMixedCtx), GCPhys, UINT32_MAX);
12872 Log4(("EPT misconfig at %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pMixedCtx->rip, VBOXSTRICTRC_VAL(rcStrict2)));
12873 if ( rcStrict2 == VINF_SUCCESS
12874 || rcStrict2 == VERR_PAGE_TABLE_NOT_PRESENT
12875 || rcStrict2 == VERR_PAGE_NOT_PRESENT)
12876 {
12877 /* Successfully handled MMIO operation. */
12878 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
12879 | HM_CHANGED_GUEST_RSP
12880 | HM_CHANGED_GUEST_RFLAGS
12881 | HM_CHANGED_VMX_GUEST_APIC_STATE);
12882 return VINF_SUCCESS;
12883 }
12884 return rcStrict2;
12885}
12886
12887
12888/**
12889 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
12890 * VM-exit.
12891 */
12892HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12893{
12894 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS();
12895 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
12896
12897 /* If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly. */
12898 VBOXSTRICTRC rcStrict1 = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pMixedCtx, pVmxTransient);
12899 if (RT_LIKELY(rcStrict1 == VINF_SUCCESS))
12900 {
12901 /* In the unlikely case that the EPT violation happened as a result of delivering an event, log it. */
12902 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
12903 Log4(("EPT violation with an event pending u64IntInfo=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo));
12904 }
12905 else
12906 {
12907 if (rcStrict1 == VINF_HM_DOUBLE_FAULT)
12908 rcStrict1 = VINF_SUCCESS;
12909 return rcStrict1;
12910 }
12911
12912 RTGCPHYS GCPhys = 0;
12913 int rc = VMXReadVmcs64(VMX_VMCS64_EXIT_GUEST_PHYS_ADDR_FULL, &GCPhys);
12914 rc |= hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
12915#if 0
12916 rc |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx); /** @todo Can we do better? */
12917#else
12918 /* Aggressive state sync. for now. */
12919 rc |= hmR0VmxSaveGuestRipRspRflags(pVCpu, pMixedCtx);
12920 rc |= hmR0VmxSaveGuestControlRegs(pVCpu, pMixedCtx);
12921 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
12922#endif
12923 AssertRCReturn(rc, rc);
12924
12925 /* Intel spec. Table 27-7 "Exit Qualifications for EPT violations". */
12926 AssertMsg(((pVmxTransient->uExitQualification >> 7) & 3) != 2, ("%#RX64", pVmxTransient->uExitQualification));
12927
12928 RTGCUINT uErrorCode = 0;
12929 if (pVmxTransient->uExitQualification & VMX_EXIT_QUALIFICATION_EPT_INSTR_FETCH)
12930 uErrorCode |= X86_TRAP_PF_ID;
12931 if (pVmxTransient->uExitQualification & VMX_EXIT_QUALIFICATION_EPT_DATA_WRITE)
12932 uErrorCode |= X86_TRAP_PF_RW;
12933 if (pVmxTransient->uExitQualification & VMX_EXIT_QUALIFICATION_EPT_ENTRY_PRESENT)
12934 uErrorCode |= X86_TRAP_PF_P;
12935
12936 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
12937
12938 Log4(("EPT violation %#x at %#RX64 ErrorCode %#x CS:RIP=%04x:%08RX64\n", pVmxTransient->uExitQualification, GCPhys,
12939 uErrorCode, pMixedCtx->cs.Sel, pMixedCtx->rip));
12940
12941 /* Handle the pagefault trap for the nested shadow table. */
12942 PVM pVM = pVCpu->CTX_SUFF(pVM);
12943 VBOXSTRICTRC rcStrict2 = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pMixedCtx), GCPhys);
12944 TRPMResetTrap(pVCpu);
12945
12946 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
12947 if ( rcStrict2 == VINF_SUCCESS
12948 || rcStrict2 == VERR_PAGE_TABLE_NOT_PRESENT
12949 || rcStrict2 == VERR_PAGE_NOT_PRESENT)
12950 {
12951 /* Successfully synced our nested page tables. */
12952 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
12953 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
12954 | HM_CHANGED_GUEST_RSP
12955 | HM_CHANGED_GUEST_RFLAGS);
12956 return VINF_SUCCESS;
12957 }
12958
12959 Log4(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict2)));
12960 return rcStrict2;
12961}
12962
12963/** @} */
12964
12965/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12966/* -=-=-=-=-=-=-=-=-=- VM-exit Exception Handlers -=-=-=-=-=-=-=-=-=-=- */
12967/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12968
12969/** @name VM-exit exception handlers.
12970 * @{
12971 */
12972
12973/**
12974 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
12975 */
12976static int hmR0VmxExitXcptMF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
12977{
12978 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
12979 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
12980
12981 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
12982 AssertRCReturn(rc, rc);
12983
12984 if (!(pMixedCtx->cr0 & X86_CR0_NE))
12985 {
12986 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
12987 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
12988
12989 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
12990 * provides VM-exit instruction length. If this causes problem later,
12991 * disassemble the instruction like it's done on AMD-V. */
12992 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pMixedCtx, pVmxTransient);
12993 AssertRCReturn(rc2, rc2);
12994 return rc;
12995 }
12996
12997 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
12998 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
12999 return rc;
13000}
13001
13002
13003/**
13004 * VM-exit exception handler for \#BP (Breakpoint exception).
13005 */
13006static int hmR0VmxExitXcptBP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13007{
13008 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13009 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
13010
13011 /** @todo Try optimize this by not saving the entire guest state unless
13012 * really needed. */
13013 int rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13014 AssertRCReturn(rc, rc);
13015
13016 PVM pVM = pVCpu->CTX_SUFF(pVM);
13017 rc = DBGFRZTrap03Handler(pVM, pVCpu, CPUMCTX2CORE(pMixedCtx));
13018 if (rc == VINF_EM_RAW_GUEST_TRAP)
13019 {
13020 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13021 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13022 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13023 AssertRCReturn(rc, rc);
13024
13025 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13026 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13027 }
13028
13029 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
13030 return rc;
13031}
13032
13033
13034/**
13035 * VM-exit exception handler for \#AC (alignment check exception).
13036 */
13037static int hmR0VmxExitXcptAC(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13038{
13039 RT_NOREF_PV(pMixedCtx);
13040 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13041
13042 /*
13043 * Re-inject it. We'll detect any nesting before getting here.
13044 */
13045 int rc = hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13046 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13047 AssertRCReturn(rc, rc);
13048 Assert(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO);
13049
13050 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13051 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13052 return VINF_SUCCESS;
13053}
13054
13055
13056/**
13057 * VM-exit exception handler for \#DB (Debug exception).
13058 */
13059static int hmR0VmxExitXcptDB(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13060{
13061 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13062 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
13063 Log6(("XcptDB\n"));
13064
13065 /*
13066 * Get the DR6-like values from the VM-exit qualification and pass it to DBGF
13067 * for processing.
13068 */
13069 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13070 AssertRCReturn(rc, rc);
13071
13072 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
13073 uint64_t uDR6 = X86_DR6_INIT_VAL;
13074 uDR6 |= ( pVmxTransient->uExitQualification
13075 & (X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3 | X86_DR6_BD | X86_DR6_BS));
13076
13077 rc = DBGFRZTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pMixedCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
13078 if (rc == VINF_EM_RAW_GUEST_TRAP)
13079 {
13080 /*
13081 * The exception was for the guest. Update DR6, DR7.GD and
13082 * IA32_DEBUGCTL.LBR before forwarding it.
13083 * (See Intel spec. 27.1 "Architectural State before a VM-Exit".)
13084 */
13085 VMMRZCallRing3Disable(pVCpu);
13086 HM_DISABLE_PREEMPT();
13087
13088 pMixedCtx->dr[6] &= ~X86_DR6_B_MASK;
13089 pMixedCtx->dr[6] |= uDR6;
13090 if (CPUMIsGuestDebugStateActive(pVCpu))
13091 ASMSetDR6(pMixedCtx->dr[6]);
13092
13093 HM_RESTORE_PREEMPT();
13094 VMMRZCallRing3Enable(pVCpu);
13095
13096 rc = hmR0VmxSaveGuestDR7(pVCpu, pMixedCtx);
13097 AssertRCReturn(rc, rc);
13098
13099 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
13100 pMixedCtx->dr[7] &= ~X86_DR7_GD;
13101
13102 /* Paranoia. */
13103 pMixedCtx->dr[7] &= ~X86_DR7_RAZ_MASK;
13104 pMixedCtx->dr[7] |= X86_DR7_RA1_MASK;
13105
13106 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_DR7, (uint32_t)pMixedCtx->dr[7]);
13107 AssertRCReturn(rc, rc);
13108
13109 /*
13110 * Raise #DB in the guest.
13111 *
13112 * It is important to reflect what the VM-exit gave us (preserving the interruption-type) rather than use
13113 * hmR0VmxSetPendingXcptDB() as the #DB could've been raised while executing ICEBP and not the 'normal' #DB.
13114 * Thus it -may- trigger different handling in the CPU (like skipped DPL checks). See @bugref{6398}.
13115 *
13116 * Since ICEBP isn't documented on Intel, see AMD spec. 15.20 "Event Injection".
13117 */
13118 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13119 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13120 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13121 AssertRCReturn(rc, rc);
13122 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13123 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13124 return VINF_SUCCESS;
13125 }
13126
13127 /*
13128 * Not a guest trap, must be a hypervisor related debug event then.
13129 * Update DR6 in case someone is interested in it.
13130 */
13131 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
13132 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
13133 CPUMSetHyperDR6(pVCpu, uDR6);
13134
13135 return rc;
13136}
13137
13138
13139/**
13140 * VM-exit exception handler for \#NM (Device-not-available exception: floating
13141 * point exception).
13142 */
13143static int hmR0VmxExitXcptNM(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13144{
13145 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13146
13147 /* We require CR0 and EFER. EFER is always up-to-date. */
13148 int rc = hmR0VmxSaveGuestCR0(pVCpu, pMixedCtx);
13149 AssertRCReturn(rc, rc);
13150
13151 /* We're playing with the host CPU state here, have to disable preemption or longjmp. */
13152 VMMRZCallRing3Disable(pVCpu);
13153 HM_DISABLE_PREEMPT();
13154
13155 /* If the guest FPU was active at the time of the #NM exit, then it's a guest fault. */
13156 if (pVmxTransient->fWasGuestFPUStateActive)
13157 {
13158 rc = VINF_EM_RAW_GUEST_TRAP;
13159 Assert(CPUMIsGuestFPUStateActive(pVCpu) || HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
13160 }
13161 else
13162 {
13163#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13164 Assert(!pVmxTransient->fWasGuestFPUStateActive || pVCpu->hm.s.fUsingDebugLoop);
13165#endif
13166 rc = CPUMR0Trap07Handler(pVCpu->CTX_SUFF(pVM), pVCpu);
13167 Assert( rc == VINF_EM_RAW_GUEST_TRAP
13168 || ((rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED) && CPUMIsGuestFPUStateActive(pVCpu)));
13169 if (rc == VINF_CPUM_HOST_CR0_MODIFIED)
13170 HMCPU_CF_SET(pVCpu, HM_CHANGED_HOST_CONTEXT);
13171 }
13172
13173 HM_RESTORE_PREEMPT();
13174 VMMRZCallRing3Enable(pVCpu);
13175
13176 if (rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED)
13177 {
13178 /* Guest FPU state was activated, we'll want to change CR0 FPU intercepts before the next VM-reentry. */
13179 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
13180 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
13181 pVCpu->hm.s.fPreloadGuestFpu = true;
13182 }
13183 else
13184 {
13185 /* Forward #NM to the guest. */
13186 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
13187 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13188 AssertRCReturn(rc, rc);
13189 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13190 pVmxTransient->cbInstr, 0 /* error code */, 0 /* GCPtrFaultAddress */);
13191 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
13192 }
13193
13194 return VINF_SUCCESS;
13195}
13196
13197
13198/**
13199 * VM-exit exception handler for \#GP (General-protection exception).
13200 *
13201 * @remarks Requires pVmxTransient->uExitIntInfo to be up-to-date.
13202 */
13203static int hmR0VmxExitXcptGP(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13204{
13205 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13206 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
13207
13208 int rc;
13209 if (pVCpu->hm.s.vmx.RealMode.fRealOnV86Active)
13210 { /* likely */ }
13211 else
13212 {
13213#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13214 Assert(pVCpu->hm.s.fUsingDebugLoop);
13215#endif
13216 /* If the guest is not in real-mode or we have unrestricted execution support, reflect #GP to the guest. */
13217 rc = hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13218 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13219 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13220 rc |= hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13221 AssertRCReturn(rc, rc);
13222 Log4(("#GP Gst: CS:RIP %04x:%08RX64 ErrorCode=%#x CR0=%#RX64 CPL=%u TR=%#04x\n", pMixedCtx->cs.Sel, pMixedCtx->rip,
13223 pVmxTransient->uExitIntErrorCode, pMixedCtx->cr0, CPUMGetGuestCPL(pVCpu), pMixedCtx->tr.Sel));
13224 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13225 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13226 return rc;
13227 }
13228
13229 Assert(CPUMIsGuestInRealModeEx(pMixedCtx));
13230 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest);
13231
13232 /* EMInterpretDisasCurrent() requires a lot of the state, save the entire state. */
13233 rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13234 AssertRCReturn(rc, rc);
13235
13236 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
13237 uint32_t cbOp = 0;
13238 PVM pVM = pVCpu->CTX_SUFF(pVM);
13239 bool fDbgStepping = pVCpu->hm.s.fSingleInstruction;
13240 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
13241 if (RT_SUCCESS(rc))
13242 {
13243 rc = VINF_SUCCESS;
13244 Assert(cbOp == pDis->cbInstr);
13245 Log4(("#GP Disas OpCode=%u CS:EIP %04x:%04RX64\n", pDis->pCurInstr->uOpcode, pMixedCtx->cs.Sel, pMixedCtx->rip));
13246 switch (pDis->pCurInstr->uOpcode)
13247 {
13248 case OP_CLI:
13249 {
13250 pMixedCtx->eflags.Bits.u1IF = 0;
13251 pMixedCtx->eflags.Bits.u1RF = 0;
13252 pMixedCtx->rip += pDis->cbInstr;
13253 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13254 if ( !fDbgStepping
13255 && pMixedCtx->eflags.Bits.u1TF)
13256 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13257 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCli);
13258 break;
13259 }
13260
13261 case OP_STI:
13262 {
13263 bool fOldIF = pMixedCtx->eflags.Bits.u1IF;
13264 pMixedCtx->eflags.Bits.u1IF = 1;
13265 pMixedCtx->eflags.Bits.u1RF = 0;
13266 pMixedCtx->rip += pDis->cbInstr;
13267 if (!fOldIF)
13268 {
13269 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
13270 Assert(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
13271 }
13272 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13273 if ( !fDbgStepping
13274 && pMixedCtx->eflags.Bits.u1TF)
13275 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13276 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitSti);
13277 break;
13278 }
13279
13280 case OP_HLT:
13281 {
13282 rc = VINF_EM_HALT;
13283 pMixedCtx->rip += pDis->cbInstr;
13284 pMixedCtx->eflags.Bits.u1RF = 0;
13285 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13286 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
13287 break;
13288 }
13289
13290 case OP_POPF:
13291 {
13292 Log4(("POPF CS:EIP %04x:%04RX64\n", pMixedCtx->cs.Sel, pMixedCtx->rip));
13293 uint32_t cbParm;
13294 uint32_t uMask;
13295 bool fGstStepping = RT_BOOL(pMixedCtx->eflags.Bits.u1TF);
13296 if (pDis->fPrefix & DISPREFIX_OPSIZE)
13297 {
13298 cbParm = 4;
13299 uMask = 0xffffffff;
13300 }
13301 else
13302 {
13303 cbParm = 2;
13304 uMask = 0xffff;
13305 }
13306
13307 /* Get the stack pointer & pop the contents of the stack onto Eflags. */
13308 RTGCPTR GCPtrStack = 0;
13309 X86EFLAGS Eflags;
13310 Eflags.u32 = 0;
13311 rc = SELMToFlatEx(pVCpu, DISSELREG_SS, CPUMCTX2CORE(pMixedCtx), pMixedCtx->esp & uMask, SELMTOFLAT_FLAGS_CPL0,
13312 &GCPtrStack);
13313 if (RT_SUCCESS(rc))
13314 {
13315 Assert(sizeof(Eflags.u32) >= cbParm);
13316 rc = VBOXSTRICTRC_TODO(PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &Eflags.u32, cbParm, PGMACCESSORIGIN_HM));
13317 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc)); /** @todo allow strict return codes here */
13318 }
13319 if (RT_FAILURE(rc))
13320 {
13321 rc = VERR_EM_INTERPRETER;
13322 break;
13323 }
13324 Log4(("POPF %#x -> %#RX64 mask=%#x RIP=%#RX64\n", Eflags.u, pMixedCtx->rsp, uMask, pMixedCtx->rip));
13325 pMixedCtx->eflags.u32 = (pMixedCtx->eflags.u32 & ~((X86_EFL_POPF_BITS & uMask) | X86_EFL_RF))
13326 | (Eflags.u32 & X86_EFL_POPF_BITS & uMask);
13327 pMixedCtx->esp += cbParm;
13328 pMixedCtx->esp &= uMask;
13329 pMixedCtx->rip += pDis->cbInstr;
13330 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13331 | HM_CHANGED_GUEST_RSP
13332 | HM_CHANGED_GUEST_RFLAGS);
13333 /* Generate a pending-debug exception when the guest stepping over POPF regardless of how
13334 POPF restores EFLAGS.TF. */
13335 if ( !fDbgStepping
13336 && fGstStepping)
13337 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13338 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPopf);
13339 break;
13340 }
13341
13342 case OP_PUSHF:
13343 {
13344 uint32_t cbParm;
13345 uint32_t uMask;
13346 if (pDis->fPrefix & DISPREFIX_OPSIZE)
13347 {
13348 cbParm = 4;
13349 uMask = 0xffffffff;
13350 }
13351 else
13352 {
13353 cbParm = 2;
13354 uMask = 0xffff;
13355 }
13356
13357 /* Get the stack pointer & push the contents of eflags onto the stack. */
13358 RTGCPTR GCPtrStack = 0;
13359 rc = SELMToFlatEx(pVCpu, DISSELREG_SS, CPUMCTX2CORE(pMixedCtx), (pMixedCtx->esp - cbParm) & uMask,
13360 SELMTOFLAT_FLAGS_CPL0, &GCPtrStack);
13361 if (RT_FAILURE(rc))
13362 {
13363 rc = VERR_EM_INTERPRETER;
13364 break;
13365 }
13366 X86EFLAGS Eflags = pMixedCtx->eflags;
13367 /* The RF & VM bits are cleared on image stored on stack; see Intel Instruction reference for PUSHF. */
13368 Eflags.Bits.u1RF = 0;
13369 Eflags.Bits.u1VM = 0;
13370
13371 rc = VBOXSTRICTRC_TODO(PGMPhysWrite(pVM, (RTGCPHYS)GCPtrStack, &Eflags.u, cbParm, PGMACCESSORIGIN_HM));
13372 if (RT_UNLIKELY(rc != VINF_SUCCESS))
13373 {
13374 AssertMsgFailed(("%Rrc\n", rc)); /** @todo allow strict return codes here */
13375 rc = VERR_EM_INTERPRETER;
13376 break;
13377 }
13378 Log4(("PUSHF %#x -> %#RGv\n", Eflags.u, GCPtrStack));
13379 pMixedCtx->esp -= cbParm;
13380 pMixedCtx->esp &= uMask;
13381 pMixedCtx->rip += pDis->cbInstr;
13382 pMixedCtx->eflags.Bits.u1RF = 0;
13383 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13384 | HM_CHANGED_GUEST_RSP
13385 | HM_CHANGED_GUEST_RFLAGS);
13386 if ( !fDbgStepping
13387 && pMixedCtx->eflags.Bits.u1TF)
13388 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13389 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPushf);
13390 break;
13391 }
13392
13393 case OP_IRET:
13394 {
13395 /** @todo Handle 32-bit operand sizes and check stack limits. See Intel
13396 * instruction reference. */
13397 RTGCPTR GCPtrStack = 0;
13398 uint32_t uMask = 0xffff;
13399 bool fGstStepping = RT_BOOL(pMixedCtx->eflags.Bits.u1TF);
13400 uint16_t aIretFrame[3];
13401 if (pDis->fPrefix & (DISPREFIX_OPSIZE | DISPREFIX_ADDRSIZE))
13402 {
13403 rc = VERR_EM_INTERPRETER;
13404 break;
13405 }
13406 rc = SELMToFlatEx(pVCpu, DISSELREG_SS, CPUMCTX2CORE(pMixedCtx), pMixedCtx->esp & uMask, SELMTOFLAT_FLAGS_CPL0,
13407 &GCPtrStack);
13408 if (RT_SUCCESS(rc))
13409 {
13410 rc = VBOXSTRICTRC_TODO(PGMPhysRead(pVM, (RTGCPHYS)GCPtrStack, &aIretFrame[0], sizeof(aIretFrame),
13411 PGMACCESSORIGIN_HM));
13412 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc)); /** @todo allow strict return codes here */
13413 }
13414 if (RT_FAILURE(rc))
13415 {
13416 rc = VERR_EM_INTERPRETER;
13417 break;
13418 }
13419 pMixedCtx->eip = 0;
13420 pMixedCtx->ip = aIretFrame[0];
13421 pMixedCtx->cs.Sel = aIretFrame[1];
13422 pMixedCtx->cs.ValidSel = aIretFrame[1];
13423 pMixedCtx->cs.u64Base = (uint64_t)pMixedCtx->cs.Sel << 4;
13424 pMixedCtx->eflags.u32 = (pMixedCtx->eflags.u32 & ((UINT32_C(0xffff0000) | X86_EFL_1) & ~X86_EFL_RF))
13425 | (aIretFrame[2] & X86_EFL_POPF_BITS & uMask);
13426 pMixedCtx->sp += sizeof(aIretFrame);
13427 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13428 | HM_CHANGED_GUEST_SEGMENT_REGS
13429 | HM_CHANGED_GUEST_RSP
13430 | HM_CHANGED_GUEST_RFLAGS);
13431 /* Generate a pending-debug exception when stepping over IRET regardless of how IRET modifies EFLAGS.TF. */
13432 if ( !fDbgStepping
13433 && fGstStepping)
13434 hmR0VmxSetPendingDebugXcptVmcs(pVCpu);
13435 Log4(("IRET %#RX32 to %04x:%04x\n", GCPtrStack, pMixedCtx->cs.Sel, pMixedCtx->ip));
13436 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIret);
13437 break;
13438 }
13439
13440 case OP_INT:
13441 {
13442 uint16_t uVector = pDis->Param1.uValue & 0xff;
13443 hmR0VmxSetPendingIntN(pVCpu, pMixedCtx, uVector, pDis->cbInstr);
13444 /* INT clears EFLAGS.TF, we must not set any pending debug exceptions here. */
13445 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInt);
13446 break;
13447 }
13448
13449 case OP_INTO:
13450 {
13451 if (pMixedCtx->eflags.Bits.u1OF)
13452 {
13453 hmR0VmxSetPendingXcptOF(pVCpu, pMixedCtx, pDis->cbInstr);
13454 /* INTO clears EFLAGS.TF, we must not set any pending debug exceptions here. */
13455 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInt);
13456 }
13457 else
13458 {
13459 pMixedCtx->eflags.Bits.u1RF = 0;
13460 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RFLAGS);
13461 }
13462 break;
13463 }
13464
13465 default:
13466 {
13467 pMixedCtx->eflags.Bits.u1RF = 0; /* This is correct most of the time... */
13468 VBOXSTRICTRC rc2 = EMInterpretInstructionDisasState(pVCpu, pDis, CPUMCTX2CORE(pMixedCtx), 0 /* pvFault */,
13469 EMCODETYPE_SUPERVISOR);
13470 rc = VBOXSTRICTRC_VAL(rc2);
13471 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
13472 /** @todo We have to set pending-debug exceptions here when the guest is
13473 * single-stepping depending on the instruction that was interpreted. */
13474 Log4(("#GP rc=%Rrc\n", rc));
13475 break;
13476 }
13477 }
13478 }
13479 else
13480 rc = VERR_EM_INTERPRETER;
13481
13482 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_EM_HALT,
13483 ("#GP Unexpected rc=%Rrc\n", rc));
13484 return rc;
13485}
13486
13487
13488/**
13489 * VM-exit exception handler wrapper for generic exceptions. Simply re-injects
13490 * the exception reported in the VMX transient structure back into the VM.
13491 *
13492 * @remarks Requires uExitIntInfo in the VMX transient structure to be
13493 * up-to-date.
13494 */
13495static int hmR0VmxExitXcptGeneric(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13496{
13497 RT_NOREF_PV(pMixedCtx);
13498 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13499#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13500 Assert(pVCpu->hm.s.fUsingDebugLoop);
13501#endif
13502
13503 /* Re-inject the exception into the guest. This cannot be a double-fault condition which would have been handled in
13504 hmR0VmxCheckExitDueToEventDelivery(). */
13505 int rc = hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13506 rc |= hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13507 AssertRCReturn(rc, rc);
13508 Assert(pVmxTransient->fVmcsFieldsRead & HMVMX_UPDATED_TRANSIENT_EXIT_INTERRUPTION_INFO);
13509
13510#ifdef DEBUG_ramshankar
13511 rc |= hmR0VmxSaveGuestSegmentRegs(pVCpu, pMixedCtx);
13512 uint8_t uVector = VMX_EXIT_INTERRUPTION_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13513 Log(("hmR0VmxExitXcptGeneric: Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
13514#endif
13515
13516 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13517 pVmxTransient->cbInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13518 return VINF_SUCCESS;
13519}
13520
13521
13522/**
13523 * VM-exit exception handler for \#PF (Page-fault exception).
13524 */
13525static int hmR0VmxExitXcptPF(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PVMXTRANSIENT pVmxTransient)
13526{
13527 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS();
13528 PVM pVM = pVCpu->CTX_SUFF(pVM);
13529 int rc = hmR0VmxReadExitQualificationVmcs(pVCpu, pVmxTransient);
13530 rc |= hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
13531 rc |= hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
13532 AssertRCReturn(rc, rc);
13533
13534 if (!pVM->hm.s.fNestedPaging)
13535 { /* likely */ }
13536 else
13537 {
13538#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
13539 Assert(pVCpu->hm.s.fUsingDebugLoop);
13540#endif
13541 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
13542 if (RT_LIKELY(!pVmxTransient->fVectoringDoublePF))
13543 {
13544 pMixedCtx->cr2 = pVmxTransient->uExitQualification; /* Update here in case we go back to ring-3 before injection. */
13545 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13546 0 /* cbInstr */, pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQualification);
13547 }
13548 else
13549 {
13550 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13551 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
13552 Log4(("Pending #DF due to vectoring #PF. NP\n"));
13553 }
13554 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13555 return rc;
13556 }
13557
13558 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
13559 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
13560 if (pVmxTransient->fVectoringPF)
13561 {
13562 Assert(pVCpu->hm.s.Event.fPending);
13563 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13564 }
13565
13566 rc = hmR0VmxSaveGuestState(pVCpu, pMixedCtx);
13567 AssertRCReturn(rc, rc);
13568
13569 Log4(("#PF: cr2=%#RX64 cs:rip=%#04x:%#RX64 uErrCode %#RX32 cr3=%#RX64\n", pVmxTransient->uExitQualification,
13570 pMixedCtx->cs.Sel, pMixedCtx->rip, pVmxTransient->uExitIntErrorCode, pMixedCtx->cr3));
13571
13572 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQualification, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
13573 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pMixedCtx),
13574 (RTGCPTR)pVmxTransient->uExitQualification);
13575
13576 Log4(("#PF: rc=%Rrc\n", rc));
13577 if (rc == VINF_SUCCESS)
13578 {
13579#if 0
13580 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
13581 /** @todo this isn't quite right, what if guest does lgdt with some MMIO
13582 * memory? We don't update the whole state here... */
13583 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_RIP
13584 | HM_CHANGED_GUEST_RSP
13585 | HM_CHANGED_GUEST_RFLAGS
13586 | HM_CHANGED_VMX_GUEST_APIC_STATE);
13587#else
13588 /*
13589 * This is typically a shadow page table sync or a MMIO instruction. But we may have
13590 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
13591 */
13592 /** @todo take advantage of CPUM changed flags instead of brute forcing. */
13593 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
13594#endif
13595 TRPMResetTrap(pVCpu);
13596 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
13597 return rc;
13598 }
13599
13600 if (rc == VINF_EM_RAW_GUEST_TRAP)
13601 {
13602 if (!pVmxTransient->fVectoringDoublePF)
13603 {
13604 /* It's a guest page fault and needs to be reflected to the guest. */
13605 uint32_t uGstErrorCode = TRPMGetErrorCode(pVCpu);
13606 TRPMResetTrap(pVCpu);
13607 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
13608 pMixedCtx->cr2 = pVmxTransient->uExitQualification; /* Update here in case we go back to ring-3 before injection. */
13609 hmR0VmxSetPendingEvent(pVCpu, VMX_VMCS_CTRL_ENTRY_IRQ_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13610 0 /* cbInstr */, uGstErrorCode, pVmxTransient->uExitQualification);
13611 }
13612 else
13613 {
13614 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13615 TRPMResetTrap(pVCpu);
13616 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
13617 hmR0VmxSetPendingXcptDF(pVCpu, pMixedCtx);
13618 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
13619 }
13620
13621 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13622 return VINF_SUCCESS;
13623 }
13624
13625 TRPMResetTrap(pVCpu);
13626 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
13627 return rc;
13628}
13629
13630/** @} */
13631
Note: See TracBrowser for help on using the repository browser.

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