VirtualBox

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

Last change on this file since 90997 was 90947, checked in by vboxsync, 3 years ago

VMM/HM: Don't use VMMR0IsLogFlushDisabled, use !VMMRZCallRing3IsEnabled instead. The VMMR0*LogFlushDisable functions will disappear shortly. bugref:10086

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 739.8 KB
Line 
1/* $Id: HMVMXR0.cpp 90947 2021-08-27 11:40:29Z vboxsync $ */
2/** @file
3 * HM VMX (Intel VT-x) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2012-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#define VMCPU_INCL_CPUM_GST_CTX
24#include <iprt/x86.h>
25#include <iprt/asm-amd64-x86.h>
26#include <iprt/thread.h>
27#include <iprt/mem.h>
28#include <iprt/mp.h>
29
30#include <VBox/vmm/pdmapi.h>
31#include <VBox/vmm/dbgf.h>
32#include <VBox/vmm/iem.h>
33#include <VBox/vmm/iom.h>
34#include <VBox/vmm/tm.h>
35#include <VBox/vmm/em.h>
36#include <VBox/vmm/gim.h>
37#include <VBox/vmm/apic.h>
38#include "HMInternal.h"
39#include <VBox/vmm/vmcc.h>
40#include <VBox/vmm/hmvmxinline.h>
41#include "HMVMXR0.h"
42#include "dtrace/VBoxVMM.h"
43
44#ifdef DEBUG_ramshankar
45# define HMVMX_ALWAYS_SAVE_GUEST_RFLAGS
46# define HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
47# define HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE
48# define HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
49# define HMVMX_ALWAYS_CLEAN_TRANSIENT
50# define HMVMX_ALWAYS_CHECK_GUEST_STATE
51# define HMVMX_ALWAYS_TRAP_ALL_XCPTS
52# define HMVMX_ALWAYS_TRAP_PF
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/**
71 * Flags to skip redundant reads of some common VMCS fields that are not part of
72 * the guest-CPU or VCPU state but are needed while handling VM-exits.
73 */
74#define HMVMX_READ_IDT_VECTORING_INFO RT_BIT_32(0)
75#define HMVMX_READ_IDT_VECTORING_ERROR_CODE RT_BIT_32(1)
76#define HMVMX_READ_EXIT_QUALIFICATION RT_BIT_32(2)
77#define HMVMX_READ_EXIT_INSTR_LEN RT_BIT_32(3)
78#define HMVMX_READ_EXIT_INTERRUPTION_INFO RT_BIT_32(4)
79#define HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE RT_BIT_32(5)
80#define HMVMX_READ_EXIT_INSTR_INFO RT_BIT_32(6)
81#define HMVMX_READ_GUEST_LINEAR_ADDR RT_BIT_32(7)
82#define HMVMX_READ_GUEST_PHYSICAL_ADDR RT_BIT_32(8)
83#define HMVMX_READ_GUEST_PENDING_DBG_XCPTS RT_BIT_32(9)
84
85/** All the VMCS fields required for processing of exception/NMI VM-exits. */
86#define HMVMX_READ_XCPT_INFO ( HMVMX_READ_EXIT_INTERRUPTION_INFO \
87 | HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE \
88 | HMVMX_READ_EXIT_INSTR_LEN \
89 | HMVMX_READ_IDT_VECTORING_INFO \
90 | HMVMX_READ_IDT_VECTORING_ERROR_CODE)
91
92/** Assert that all the given fields have been read from the VMCS. */
93#ifdef VBOX_STRICT
94# define HMVMX_ASSERT_READ(a_pVmxTransient, a_fReadFields) \
95 do { \
96 uint32_t const fVmcsFieldRead = ASMAtomicUoReadU32(&pVmxTransient->fVmcsFieldsRead); \
97 Assert((fVmcsFieldRead & (a_fReadFields)) == (a_fReadFields)); \
98 } while (0)
99#else
100# define HMVMX_ASSERT_READ(a_pVmxTransient, a_fReadFields) do { } while (0)
101#endif
102
103/**
104 * Subset of the guest-CPU state that is kept by VMX R0 code while executing the
105 * guest using hardware-assisted VMX.
106 *
107 * This excludes state like GPRs (other than RSP) which are always are
108 * swapped and restored across the world-switch and also registers like EFER,
109 * MSR which cannot be modified by the guest without causing a VM-exit.
110 */
111#define HMVMX_CPUMCTX_EXTRN_ALL ( CPUMCTX_EXTRN_RIP \
112 | CPUMCTX_EXTRN_RFLAGS \
113 | CPUMCTX_EXTRN_RSP \
114 | CPUMCTX_EXTRN_SREG_MASK \
115 | CPUMCTX_EXTRN_TABLE_MASK \
116 | CPUMCTX_EXTRN_KERNEL_GS_BASE \
117 | CPUMCTX_EXTRN_SYSCALL_MSRS \
118 | CPUMCTX_EXTRN_SYSENTER_MSRS \
119 | CPUMCTX_EXTRN_TSC_AUX \
120 | CPUMCTX_EXTRN_OTHER_MSRS \
121 | CPUMCTX_EXTRN_CR0 \
122 | CPUMCTX_EXTRN_CR3 \
123 | CPUMCTX_EXTRN_CR4 \
124 | CPUMCTX_EXTRN_DR7 \
125 | CPUMCTX_EXTRN_HWVIRT \
126 | CPUMCTX_EXTRN_HM_VMX_MASK)
127
128/**
129 * Exception bitmap mask for real-mode guests (real-on-v86).
130 *
131 * We need to intercept all exceptions manually except:
132 * - \#AC and \#DB are always intercepted to prevent the CPU from deadlocking
133 * due to bugs in Intel CPUs.
134 * - \#PF need not be intercepted even in real-mode if we have nested paging
135 * support.
136 */
137#define HMVMX_REAL_MODE_XCPT_MASK ( RT_BIT(X86_XCPT_DE) /* always: | RT_BIT(X86_XCPT_DB) */ | RT_BIT(X86_XCPT_NMI) \
138 | RT_BIT(X86_XCPT_BP) | RT_BIT(X86_XCPT_OF) | RT_BIT(X86_XCPT_BR) \
139 | RT_BIT(X86_XCPT_UD) | RT_BIT(X86_XCPT_NM) | RT_BIT(X86_XCPT_DF) \
140 | RT_BIT(X86_XCPT_CO_SEG_OVERRUN) | RT_BIT(X86_XCPT_TS) | RT_BIT(X86_XCPT_NP) \
141 | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_GP) /* RT_BIT(X86_XCPT_PF) */ \
142 | RT_BIT(X86_XCPT_MF) /* always: | RT_BIT(X86_XCPT_AC) */ | RT_BIT(X86_XCPT_MC) \
143 | RT_BIT(X86_XCPT_XF))
144
145/** Maximum VM-instruction error number. */
146#define HMVMX_INSTR_ERROR_MAX 28
147
148/** Profiling macro. */
149#ifdef HM_PROFILE_EXIT_DISPATCH
150# define HMVMX_START_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitDispatch, ed)
151# define HMVMX_STOP_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitDispatch, ed)
152#else
153# define HMVMX_START_EXIT_DISPATCH_PROF() do { } while (0)
154# define HMVMX_STOP_EXIT_DISPATCH_PROF() do { } while (0)
155#endif
156
157/** Assert that preemption is disabled or covered by thread-context hooks. */
158#define HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu) Assert( VMMR0ThreadCtxHookIsEnabled((a_pVCpu)) \
159 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD))
160
161/** Assert that we haven't migrated CPUs when thread-context hooks are not
162 * used. */
163#define HMVMX_ASSERT_CPU_SAFE(a_pVCpu) AssertMsg( VMMR0ThreadCtxHookIsEnabled((a_pVCpu)) \
164 || (a_pVCpu)->hmr0.s.idEnteredCpu == RTMpCpuId(), \
165 ("Illegal migration! Entered on CPU %u Current %u\n", \
166 (a_pVCpu)->hmr0.s.idEnteredCpu, RTMpCpuId()))
167
168/** Asserts that the given CPUMCTX_EXTRN_XXX bits are present in the guest-CPU
169 * context. */
170#define HMVMX_CPUMCTX_ASSERT(a_pVCpu, a_fExtrnMbz) AssertMsg(!((a_pVCpu)->cpum.GstCtx.fExtrn & (a_fExtrnMbz)), \
171 ("fExtrn=%#RX64 fExtrnMbz=%#RX64\n", \
172 (a_pVCpu)->cpum.GstCtx.fExtrn, (a_fExtrnMbz)))
173
174/** Log the VM-exit reason with an easily visible marker to identify it in a
175 * potential sea of logging data. */
176#define HMVMX_LOG_EXIT(a_pVCpu, a_uExitReason) \
177 do { \
178 Log4(("VM-exit: vcpu[%RU32] %85s -v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-v-\n", (a_pVCpu)->idCpu, \
179 HMGetVmxExitName(a_uExitReason))); \
180 } while (0) \
181
182
183/*********************************************************************************************************************************
184* Structures and Typedefs *
185*********************************************************************************************************************************/
186/**
187 * VMX per-VCPU transient state.
188 *
189 * A state structure for holding miscellaneous information across
190 * VMX non-root operation and restored after the transition.
191 *
192 * Note: The members are ordered and aligned such that the most
193 * frequently used ones (in the guest execution loop) fall within
194 * the first cache line.
195 */
196typedef struct VMXTRANSIENT
197{
198 /** Mask of currently read VMCS fields; HMVMX_READ_XXX. */
199 uint32_t fVmcsFieldsRead;
200 /** The guest's TPR value used for TPR shadowing. */
201 uint8_t u8GuestTpr;
202 uint8_t abAlignment0[3];
203
204 /** Whether the VM-exit was caused by a page-fault during delivery of an
205 * external interrupt or NMI. */
206 bool fVectoringPF;
207 /** Whether the VM-exit was caused by a page-fault during delivery of a
208 * contributory exception or a page-fault. */
209 bool fVectoringDoublePF;
210 /** Whether the VM-entry failed or not. */
211 bool fVMEntryFailed;
212 /** Whether the TSC_AUX MSR needs to be removed from the auto-load/store MSR
213 * area after VM-exit. */
214 bool fRemoveTscAuxMsr;
215 /** Whether TSC-offsetting and VMX-preemption timer was updated before VM-entry. */
216 bool fUpdatedTscOffsettingAndPreemptTimer;
217 /** Whether we are currently executing a nested-guest. */
218 bool fIsNestedGuest;
219 /** Whether the guest debug state was active at the time of VM-exit. */
220 bool fWasGuestDebugStateActive;
221 /** Whether the hyper debug state was active at the time of VM-exit. */
222 bool fWasHyperDebugStateActive;
223
224 /** The basic VM-exit reason. */
225 uint32_t uExitReason;
226 /** The VM-exit interruption error code. */
227 uint32_t uExitIntErrorCode;
228
229 /** The host's rflags/eflags. */
230 RTCCUINTREG fEFlags;
231
232 /** The VM-exit exit code qualification. */
233 uint64_t uExitQual;
234
235 /** The VMCS info. object. */
236 PVMXVMCSINFO pVmcsInfo;
237
238 /** The VM-exit interruption-information field. */
239 uint32_t uExitIntInfo;
240 /** The VM-exit instruction-length field. */
241 uint32_t cbExitInstr;
242
243 /** The VM-exit instruction-information field. */
244 VMXEXITINSTRINFO ExitInstrInfo;
245 /** IDT-vectoring information field. */
246 uint32_t uIdtVectoringInfo;
247
248 /** IDT-vectoring error code. */
249 uint32_t uIdtVectoringErrorCode;
250 uint32_t u32Alignment0;
251
252 /** The Guest-linear address. */
253 uint64_t uGuestLinearAddr;
254
255 /** The Guest-physical address. */
256 uint64_t uGuestPhysicalAddr;
257
258 /** The Guest pending-debug exceptions. */
259 uint64_t uGuestPendingDbgXcpts;
260
261 /** The VM-entry interruption-information field. */
262 uint32_t uEntryIntInfo;
263 /** The VM-entry exception error code field. */
264 uint32_t uEntryXcptErrorCode;
265
266 /** The VM-entry instruction length field. */
267 uint32_t cbEntryInstr;
268} VMXTRANSIENT;
269AssertCompileMemberSize(VMXTRANSIENT, ExitInstrInfo, sizeof(uint32_t));
270AssertCompileMemberAlignment(VMXTRANSIENT, fVmcsFieldsRead, 8);
271AssertCompileMemberAlignment(VMXTRANSIENT, fVectoringPF, 8);
272AssertCompileMemberAlignment(VMXTRANSIENT, uExitReason, 8);
273AssertCompileMemberAlignment(VMXTRANSIENT, fEFlags, 8);
274AssertCompileMemberAlignment(VMXTRANSIENT, uExitQual, 8);
275AssertCompileMemberAlignment(VMXTRANSIENT, pVmcsInfo, 8);
276AssertCompileMemberAlignment(VMXTRANSIENT, uExitIntInfo, 8);
277AssertCompileMemberAlignment(VMXTRANSIENT, ExitInstrInfo, 8);
278AssertCompileMemberAlignment(VMXTRANSIENT, uIdtVectoringErrorCode, 8);
279AssertCompileMemberAlignment(VMXTRANSIENT, uGuestLinearAddr, 8);
280AssertCompileMemberAlignment(VMXTRANSIENT, uGuestPhysicalAddr, 8);
281AssertCompileMemberAlignment(VMXTRANSIENT, uEntryIntInfo, 8);
282AssertCompileMemberAlignment(VMXTRANSIENT, cbEntryInstr, 8);
283/** Pointer to VMX transient state. */
284typedef VMXTRANSIENT *PVMXTRANSIENT;
285/** Pointer to a const VMX transient state. */
286typedef const VMXTRANSIENT *PCVMXTRANSIENT;
287
288/**
289 * VMX page allocation information.
290 */
291typedef struct
292{
293 uint32_t fValid; /**< Whether to allocate this page (e.g, based on a CPU feature). */
294 uint32_t uPadding0; /**< Padding to ensure array of these structs are aligned to a multiple of 8. */
295 PRTHCPHYS pHCPhys; /**< Where to store the host-physical address of the allocation. */
296 PRTR0PTR ppVirt; /**< Where to store the host-virtual address of the allocation. */
297} VMXPAGEALLOCINFO;
298/** Pointer to VMX page-allocation info. */
299typedef VMXPAGEALLOCINFO *PVMXPAGEALLOCINFO;
300/** Pointer to a const VMX page-allocation info. */
301typedef const VMXPAGEALLOCINFO *PCVMXPAGEALLOCINFO;
302AssertCompileSizeAlignment(VMXPAGEALLOCINFO, 8);
303
304/**
305 * Memory operand read or write access.
306 */
307typedef enum VMXMEMACCESS
308{
309 VMXMEMACCESS_READ = 0,
310 VMXMEMACCESS_WRITE = 1
311} VMXMEMACCESS;
312
313/**
314 * VMX VM-exit handler.
315 *
316 * @returns Strict VBox status code (i.e. informational status codes too).
317 * @param pVCpu The cross context virtual CPU structure.
318 * @param pVmxTransient The VMX-transient structure.
319 */
320#ifndef HMVMX_USE_FUNCTION_TABLE
321typedef VBOXSTRICTRC FNVMXEXITHANDLER(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
322#else
323typedef DECLCALLBACKTYPE(VBOXSTRICTRC, FNVMXEXITHANDLER,(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient));
324/** Pointer to VM-exit handler. */
325typedef FNVMXEXITHANDLER *PFNVMXEXITHANDLER;
326#endif
327
328/**
329 * VMX VM-exit handler, non-strict status code.
330 *
331 * This is generally the same as FNVMXEXITHANDLER, the NSRC bit is just FYI.
332 *
333 * @returns VBox status code, no informational status code returned.
334 * @param pVCpu The cross context virtual CPU structure.
335 * @param pVmxTransient The VMX-transient structure.
336 *
337 * @remarks This is not used on anything returning VERR_EM_INTERPRETER as the
338 * use of that status code will be replaced with VINF_EM_SOMETHING
339 * later when switching over to IEM.
340 */
341#ifndef HMVMX_USE_FUNCTION_TABLE
342typedef int FNVMXEXITHANDLERNSRC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
343#else
344typedef FNVMXEXITHANDLER FNVMXEXITHANDLERNSRC;
345#endif
346
347
348/*********************************************************************************************************************************
349* Internal Functions *
350*********************************************************************************************************************************/
351#ifndef HMVMX_USE_FUNCTION_TABLE
352DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
353# define HMVMX_EXIT_DECL DECLINLINE(VBOXSTRICTRC)
354# define HMVMX_EXIT_NSRC_DECL DECLINLINE(int)
355#else
356# define HMVMX_EXIT_DECL static DECLCALLBACK(VBOXSTRICTRC)
357# define HMVMX_EXIT_NSRC_DECL HMVMX_EXIT_DECL
358#endif
359#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
360DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
361#endif
362
363static int hmR0VmxImportGuestState(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint64_t fWhat);
364
365/** @name VM-exit handler prototypes.
366 * @{
367 */
368static FNVMXEXITHANDLER hmR0VmxExitXcptOrNmi;
369static FNVMXEXITHANDLER hmR0VmxExitExtInt;
370static FNVMXEXITHANDLER hmR0VmxExitTripleFault;
371static FNVMXEXITHANDLERNSRC hmR0VmxExitIntWindow;
372static FNVMXEXITHANDLERNSRC hmR0VmxExitNmiWindow;
373static FNVMXEXITHANDLER hmR0VmxExitTaskSwitch;
374static FNVMXEXITHANDLER hmR0VmxExitCpuid;
375static FNVMXEXITHANDLER hmR0VmxExitGetsec;
376static FNVMXEXITHANDLER hmR0VmxExitHlt;
377static FNVMXEXITHANDLERNSRC hmR0VmxExitInvd;
378static FNVMXEXITHANDLER hmR0VmxExitInvlpg;
379static FNVMXEXITHANDLER hmR0VmxExitRdpmc;
380static FNVMXEXITHANDLER hmR0VmxExitVmcall;
381#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
382static FNVMXEXITHANDLER hmR0VmxExitVmclear;
383static FNVMXEXITHANDLER hmR0VmxExitVmlaunch;
384static FNVMXEXITHANDLER hmR0VmxExitVmptrld;
385static FNVMXEXITHANDLER hmR0VmxExitVmptrst;
386static FNVMXEXITHANDLER hmR0VmxExitVmread;
387static FNVMXEXITHANDLER hmR0VmxExitVmresume;
388static FNVMXEXITHANDLER hmR0VmxExitVmwrite;
389static FNVMXEXITHANDLER hmR0VmxExitVmxoff;
390static FNVMXEXITHANDLER hmR0VmxExitVmxon;
391static FNVMXEXITHANDLER hmR0VmxExitInvvpid;
392#endif
393static FNVMXEXITHANDLER hmR0VmxExitRdtsc;
394static FNVMXEXITHANDLER hmR0VmxExitMovCRx;
395static FNVMXEXITHANDLER hmR0VmxExitMovDRx;
396static FNVMXEXITHANDLER hmR0VmxExitIoInstr;
397static FNVMXEXITHANDLER hmR0VmxExitRdmsr;
398static FNVMXEXITHANDLER hmR0VmxExitWrmsr;
399static FNVMXEXITHANDLER hmR0VmxExitMwait;
400static FNVMXEXITHANDLER hmR0VmxExitMtf;
401static FNVMXEXITHANDLER hmR0VmxExitMonitor;
402static FNVMXEXITHANDLER hmR0VmxExitPause;
403static FNVMXEXITHANDLERNSRC hmR0VmxExitTprBelowThreshold;
404static FNVMXEXITHANDLER hmR0VmxExitApicAccess;
405static FNVMXEXITHANDLER hmR0VmxExitEptViolation;
406static FNVMXEXITHANDLER hmR0VmxExitEptMisconfig;
407static FNVMXEXITHANDLER hmR0VmxExitRdtscp;
408static FNVMXEXITHANDLER hmR0VmxExitPreemptTimer;
409static FNVMXEXITHANDLERNSRC hmR0VmxExitWbinvd;
410static FNVMXEXITHANDLER hmR0VmxExitXsetbv;
411static FNVMXEXITHANDLER hmR0VmxExitInvpcid;
412static FNVMXEXITHANDLERNSRC hmR0VmxExitSetPendingXcptUD;
413static FNVMXEXITHANDLERNSRC hmR0VmxExitErrInvalidGuestState;
414static FNVMXEXITHANDLERNSRC hmR0VmxExitErrUnexpected;
415/** @} */
416
417#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
418/** @name Nested-guest VM-exit handler prototypes.
419 * @{
420 */
421static FNVMXEXITHANDLER hmR0VmxExitXcptOrNmiNested;
422static FNVMXEXITHANDLER hmR0VmxExitTripleFaultNested;
423static FNVMXEXITHANDLERNSRC hmR0VmxExitIntWindowNested;
424static FNVMXEXITHANDLERNSRC hmR0VmxExitNmiWindowNested;
425static FNVMXEXITHANDLER hmR0VmxExitTaskSwitchNested;
426static FNVMXEXITHANDLER hmR0VmxExitHltNested;
427static FNVMXEXITHANDLER hmR0VmxExitInvlpgNested;
428static FNVMXEXITHANDLER hmR0VmxExitRdpmcNested;
429static FNVMXEXITHANDLER hmR0VmxExitVmreadVmwriteNested;
430static FNVMXEXITHANDLER hmR0VmxExitRdtscNested;
431static FNVMXEXITHANDLER hmR0VmxExitMovCRxNested;
432static FNVMXEXITHANDLER hmR0VmxExitMovDRxNested;
433static FNVMXEXITHANDLER hmR0VmxExitIoInstrNested;
434static FNVMXEXITHANDLER hmR0VmxExitRdmsrNested;
435static FNVMXEXITHANDLER hmR0VmxExitWrmsrNested;
436static FNVMXEXITHANDLER hmR0VmxExitMwaitNested;
437static FNVMXEXITHANDLER hmR0VmxExitMtfNested;
438static FNVMXEXITHANDLER hmR0VmxExitMonitorNested;
439static FNVMXEXITHANDLER hmR0VmxExitPauseNested;
440static FNVMXEXITHANDLERNSRC hmR0VmxExitTprBelowThresholdNested;
441static FNVMXEXITHANDLER hmR0VmxExitApicAccessNested;
442static FNVMXEXITHANDLER hmR0VmxExitApicWriteNested;
443static FNVMXEXITHANDLER hmR0VmxExitVirtEoiNested;
444static FNVMXEXITHANDLER hmR0VmxExitRdtscpNested;
445static FNVMXEXITHANDLERNSRC hmR0VmxExitWbinvdNested;
446static FNVMXEXITHANDLER hmR0VmxExitInvpcidNested;
447static FNVMXEXITHANDLERNSRC hmR0VmxExitErrInvalidGuestStateNested;
448static FNVMXEXITHANDLER hmR0VmxExitInstrNested;
449static FNVMXEXITHANDLER hmR0VmxExitInstrWithInfoNested;
450/** @} */
451#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
452
453
454/*********************************************************************************************************************************
455* Global Variables *
456*********************************************************************************************************************************/
457#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
458/**
459 * Array of all VMCS fields.
460 * Any fields added to the VT-x spec. should be added here.
461 *
462 * Currently only used to derive shadow VMCS fields for hardware-assisted execution
463 * of nested-guests.
464 */
465static const uint32_t g_aVmcsFields[] =
466{
467 /* 16-bit control fields. */
468 VMX_VMCS16_VPID,
469 VMX_VMCS16_POSTED_INT_NOTIFY_VECTOR,
470 VMX_VMCS16_EPTP_INDEX,
471
472 /* 16-bit guest-state fields. */
473 VMX_VMCS16_GUEST_ES_SEL,
474 VMX_VMCS16_GUEST_CS_SEL,
475 VMX_VMCS16_GUEST_SS_SEL,
476 VMX_VMCS16_GUEST_DS_SEL,
477 VMX_VMCS16_GUEST_FS_SEL,
478 VMX_VMCS16_GUEST_GS_SEL,
479 VMX_VMCS16_GUEST_LDTR_SEL,
480 VMX_VMCS16_GUEST_TR_SEL,
481 VMX_VMCS16_GUEST_INTR_STATUS,
482 VMX_VMCS16_GUEST_PML_INDEX,
483
484 /* 16-bits host-state fields. */
485 VMX_VMCS16_HOST_ES_SEL,
486 VMX_VMCS16_HOST_CS_SEL,
487 VMX_VMCS16_HOST_SS_SEL,
488 VMX_VMCS16_HOST_DS_SEL,
489 VMX_VMCS16_HOST_FS_SEL,
490 VMX_VMCS16_HOST_GS_SEL,
491 VMX_VMCS16_HOST_TR_SEL,
492
493 /* 64-bit control fields. */
494 VMX_VMCS64_CTRL_IO_BITMAP_A_FULL,
495 VMX_VMCS64_CTRL_IO_BITMAP_A_HIGH,
496 VMX_VMCS64_CTRL_IO_BITMAP_B_FULL,
497 VMX_VMCS64_CTRL_IO_BITMAP_B_HIGH,
498 VMX_VMCS64_CTRL_MSR_BITMAP_FULL,
499 VMX_VMCS64_CTRL_MSR_BITMAP_HIGH,
500 VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL,
501 VMX_VMCS64_CTRL_EXIT_MSR_STORE_HIGH,
502 VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL,
503 VMX_VMCS64_CTRL_EXIT_MSR_LOAD_HIGH,
504 VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL,
505 VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_HIGH,
506 VMX_VMCS64_CTRL_EXEC_VMCS_PTR_FULL,
507 VMX_VMCS64_CTRL_EXEC_VMCS_PTR_HIGH,
508 VMX_VMCS64_CTRL_EXEC_PML_ADDR_FULL,
509 VMX_VMCS64_CTRL_EXEC_PML_ADDR_HIGH,
510 VMX_VMCS64_CTRL_TSC_OFFSET_FULL,
511 VMX_VMCS64_CTRL_TSC_OFFSET_HIGH,
512 VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL,
513 VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_HIGH,
514 VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL,
515 VMX_VMCS64_CTRL_APIC_ACCESSADDR_HIGH,
516 VMX_VMCS64_CTRL_POSTED_INTR_DESC_FULL,
517 VMX_VMCS64_CTRL_POSTED_INTR_DESC_HIGH,
518 VMX_VMCS64_CTRL_VMFUNC_CTRLS_FULL,
519 VMX_VMCS64_CTRL_VMFUNC_CTRLS_HIGH,
520 VMX_VMCS64_CTRL_EPTP_FULL,
521 VMX_VMCS64_CTRL_EPTP_HIGH,
522 VMX_VMCS64_CTRL_EOI_BITMAP_0_FULL,
523 VMX_VMCS64_CTRL_EOI_BITMAP_0_HIGH,
524 VMX_VMCS64_CTRL_EOI_BITMAP_1_FULL,
525 VMX_VMCS64_CTRL_EOI_BITMAP_1_HIGH,
526 VMX_VMCS64_CTRL_EOI_BITMAP_2_FULL,
527 VMX_VMCS64_CTRL_EOI_BITMAP_2_HIGH,
528 VMX_VMCS64_CTRL_EOI_BITMAP_3_FULL,
529 VMX_VMCS64_CTRL_EOI_BITMAP_3_HIGH,
530 VMX_VMCS64_CTRL_EPTP_LIST_FULL,
531 VMX_VMCS64_CTRL_EPTP_LIST_HIGH,
532 VMX_VMCS64_CTRL_VMREAD_BITMAP_FULL,
533 VMX_VMCS64_CTRL_VMREAD_BITMAP_HIGH,
534 VMX_VMCS64_CTRL_VMWRITE_BITMAP_FULL,
535 VMX_VMCS64_CTRL_VMWRITE_BITMAP_HIGH,
536 VMX_VMCS64_CTRL_VE_XCPT_INFO_ADDR_FULL,
537 VMX_VMCS64_CTRL_VE_XCPT_INFO_ADDR_HIGH,
538 VMX_VMCS64_CTRL_XSS_EXITING_BITMAP_FULL,
539 VMX_VMCS64_CTRL_XSS_EXITING_BITMAP_HIGH,
540 VMX_VMCS64_CTRL_ENCLS_EXITING_BITMAP_FULL,
541 VMX_VMCS64_CTRL_ENCLS_EXITING_BITMAP_HIGH,
542 VMX_VMCS64_CTRL_SPPTP_FULL,
543 VMX_VMCS64_CTRL_SPPTP_HIGH,
544 VMX_VMCS64_CTRL_TSC_MULTIPLIER_FULL,
545 VMX_VMCS64_CTRL_TSC_MULTIPLIER_HIGH,
546 VMX_VMCS64_CTRL_PROC_EXEC3_FULL,
547 VMX_VMCS64_CTRL_PROC_EXEC3_HIGH,
548 VMX_VMCS64_CTRL_ENCLV_EXITING_BITMAP_FULL,
549 VMX_VMCS64_CTRL_ENCLV_EXITING_BITMAP_HIGH,
550
551 /* 64-bit read-only data fields. */
552 VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL,
553 VMX_VMCS64_RO_GUEST_PHYS_ADDR_HIGH,
554
555 /* 64-bit guest-state fields. */
556 VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL,
557 VMX_VMCS64_GUEST_VMCS_LINK_PTR_HIGH,
558 VMX_VMCS64_GUEST_DEBUGCTL_FULL,
559 VMX_VMCS64_GUEST_DEBUGCTL_HIGH,
560 VMX_VMCS64_GUEST_PAT_FULL,
561 VMX_VMCS64_GUEST_PAT_HIGH,
562 VMX_VMCS64_GUEST_EFER_FULL,
563 VMX_VMCS64_GUEST_EFER_HIGH,
564 VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL,
565 VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_HIGH,
566 VMX_VMCS64_GUEST_PDPTE0_FULL,
567 VMX_VMCS64_GUEST_PDPTE0_HIGH,
568 VMX_VMCS64_GUEST_PDPTE1_FULL,
569 VMX_VMCS64_GUEST_PDPTE1_HIGH,
570 VMX_VMCS64_GUEST_PDPTE2_FULL,
571 VMX_VMCS64_GUEST_PDPTE2_HIGH,
572 VMX_VMCS64_GUEST_PDPTE3_FULL,
573 VMX_VMCS64_GUEST_PDPTE3_HIGH,
574 VMX_VMCS64_GUEST_BNDCFGS_FULL,
575 VMX_VMCS64_GUEST_BNDCFGS_HIGH,
576 VMX_VMCS64_GUEST_RTIT_CTL_FULL,
577 VMX_VMCS64_GUEST_RTIT_CTL_HIGH,
578 VMX_VMCS64_GUEST_PKRS_FULL,
579 VMX_VMCS64_GUEST_PKRS_HIGH,
580
581 /* 64-bit host-state fields. */
582 VMX_VMCS64_HOST_PAT_FULL,
583 VMX_VMCS64_HOST_PAT_HIGH,
584 VMX_VMCS64_HOST_EFER_FULL,
585 VMX_VMCS64_HOST_EFER_HIGH,
586 VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_FULL,
587 VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_HIGH,
588 VMX_VMCS64_HOST_PKRS_FULL,
589 VMX_VMCS64_HOST_PKRS_HIGH,
590
591 /* 32-bit control fields. */
592 VMX_VMCS32_CTRL_PIN_EXEC,
593 VMX_VMCS32_CTRL_PROC_EXEC,
594 VMX_VMCS32_CTRL_EXCEPTION_BITMAP,
595 VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK,
596 VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH,
597 VMX_VMCS32_CTRL_CR3_TARGET_COUNT,
598 VMX_VMCS32_CTRL_EXIT,
599 VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT,
600 VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT,
601 VMX_VMCS32_CTRL_ENTRY,
602 VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT,
603 VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO,
604 VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE,
605 VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH,
606 VMX_VMCS32_CTRL_TPR_THRESHOLD,
607 VMX_VMCS32_CTRL_PROC_EXEC2,
608 VMX_VMCS32_CTRL_PLE_GAP,
609 VMX_VMCS32_CTRL_PLE_WINDOW,
610
611 /* 32-bits read-only fields. */
612 VMX_VMCS32_RO_VM_INSTR_ERROR,
613 VMX_VMCS32_RO_EXIT_REASON,
614 VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO,
615 VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE,
616 VMX_VMCS32_RO_IDT_VECTORING_INFO,
617 VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE,
618 VMX_VMCS32_RO_EXIT_INSTR_LENGTH,
619 VMX_VMCS32_RO_EXIT_INSTR_INFO,
620
621 /* 32-bit guest-state fields. */
622 VMX_VMCS32_GUEST_ES_LIMIT,
623 VMX_VMCS32_GUEST_CS_LIMIT,
624 VMX_VMCS32_GUEST_SS_LIMIT,
625 VMX_VMCS32_GUEST_DS_LIMIT,
626 VMX_VMCS32_GUEST_FS_LIMIT,
627 VMX_VMCS32_GUEST_GS_LIMIT,
628 VMX_VMCS32_GUEST_LDTR_LIMIT,
629 VMX_VMCS32_GUEST_TR_LIMIT,
630 VMX_VMCS32_GUEST_GDTR_LIMIT,
631 VMX_VMCS32_GUEST_IDTR_LIMIT,
632 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS,
633 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS,
634 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS,
635 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS,
636 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS,
637 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS,
638 VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS,
639 VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS,
640 VMX_VMCS32_GUEST_INT_STATE,
641 VMX_VMCS32_GUEST_ACTIVITY_STATE,
642 VMX_VMCS32_GUEST_SMBASE,
643 VMX_VMCS32_GUEST_SYSENTER_CS,
644 VMX_VMCS32_PREEMPT_TIMER_VALUE,
645
646 /* 32-bit host-state fields. */
647 VMX_VMCS32_HOST_SYSENTER_CS,
648
649 /* Natural-width control fields. */
650 VMX_VMCS_CTRL_CR0_MASK,
651 VMX_VMCS_CTRL_CR4_MASK,
652 VMX_VMCS_CTRL_CR0_READ_SHADOW,
653 VMX_VMCS_CTRL_CR4_READ_SHADOW,
654 VMX_VMCS_CTRL_CR3_TARGET_VAL0,
655 VMX_VMCS_CTRL_CR3_TARGET_VAL1,
656 VMX_VMCS_CTRL_CR3_TARGET_VAL2,
657 VMX_VMCS_CTRL_CR3_TARGET_VAL3,
658
659 /* Natural-width read-only data fields. */
660 VMX_VMCS_RO_EXIT_QUALIFICATION,
661 VMX_VMCS_RO_IO_RCX,
662 VMX_VMCS_RO_IO_RSI,
663 VMX_VMCS_RO_IO_RDI,
664 VMX_VMCS_RO_IO_RIP,
665 VMX_VMCS_RO_GUEST_LINEAR_ADDR,
666
667 /* Natural-width guest-state field */
668 VMX_VMCS_GUEST_CR0,
669 VMX_VMCS_GUEST_CR3,
670 VMX_VMCS_GUEST_CR4,
671 VMX_VMCS_GUEST_ES_BASE,
672 VMX_VMCS_GUEST_CS_BASE,
673 VMX_VMCS_GUEST_SS_BASE,
674 VMX_VMCS_GUEST_DS_BASE,
675 VMX_VMCS_GUEST_FS_BASE,
676 VMX_VMCS_GUEST_GS_BASE,
677 VMX_VMCS_GUEST_LDTR_BASE,
678 VMX_VMCS_GUEST_TR_BASE,
679 VMX_VMCS_GUEST_GDTR_BASE,
680 VMX_VMCS_GUEST_IDTR_BASE,
681 VMX_VMCS_GUEST_DR7,
682 VMX_VMCS_GUEST_RSP,
683 VMX_VMCS_GUEST_RIP,
684 VMX_VMCS_GUEST_RFLAGS,
685 VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS,
686 VMX_VMCS_GUEST_SYSENTER_ESP,
687 VMX_VMCS_GUEST_SYSENTER_EIP,
688 VMX_VMCS_GUEST_S_CET,
689 VMX_VMCS_GUEST_SSP,
690 VMX_VMCS_GUEST_INTR_SSP_TABLE_ADDR,
691
692 /* Natural-width host-state fields */
693 VMX_VMCS_HOST_CR0,
694 VMX_VMCS_HOST_CR3,
695 VMX_VMCS_HOST_CR4,
696 VMX_VMCS_HOST_FS_BASE,
697 VMX_VMCS_HOST_GS_BASE,
698 VMX_VMCS_HOST_TR_BASE,
699 VMX_VMCS_HOST_GDTR_BASE,
700 VMX_VMCS_HOST_IDTR_BASE,
701 VMX_VMCS_HOST_SYSENTER_ESP,
702 VMX_VMCS_HOST_SYSENTER_EIP,
703 VMX_VMCS_HOST_RSP,
704 VMX_VMCS_HOST_RIP,
705 VMX_VMCS_HOST_S_CET,
706 VMX_VMCS_HOST_SSP,
707 VMX_VMCS_HOST_INTR_SSP_TABLE_ADDR
708};
709#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
710
711#ifdef VBOX_STRICT
712static const uint32_t g_aVmcsSegBase[] =
713{
714 VMX_VMCS_GUEST_ES_BASE,
715 VMX_VMCS_GUEST_CS_BASE,
716 VMX_VMCS_GUEST_SS_BASE,
717 VMX_VMCS_GUEST_DS_BASE,
718 VMX_VMCS_GUEST_FS_BASE,
719 VMX_VMCS_GUEST_GS_BASE
720};
721static const uint32_t g_aVmcsSegSel[] =
722{
723 VMX_VMCS16_GUEST_ES_SEL,
724 VMX_VMCS16_GUEST_CS_SEL,
725 VMX_VMCS16_GUEST_SS_SEL,
726 VMX_VMCS16_GUEST_DS_SEL,
727 VMX_VMCS16_GUEST_FS_SEL,
728 VMX_VMCS16_GUEST_GS_SEL
729};
730static const uint32_t g_aVmcsSegLimit[] =
731{
732 VMX_VMCS32_GUEST_ES_LIMIT,
733 VMX_VMCS32_GUEST_CS_LIMIT,
734 VMX_VMCS32_GUEST_SS_LIMIT,
735 VMX_VMCS32_GUEST_DS_LIMIT,
736 VMX_VMCS32_GUEST_FS_LIMIT,
737 VMX_VMCS32_GUEST_GS_LIMIT
738};
739static const uint32_t g_aVmcsSegAttr[] =
740{
741 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS,
742 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS,
743 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS,
744 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS,
745 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS,
746 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS
747};
748AssertCompile(RT_ELEMENTS(g_aVmcsSegSel) == X86_SREG_COUNT);
749AssertCompile(RT_ELEMENTS(g_aVmcsSegLimit) == X86_SREG_COUNT);
750AssertCompile(RT_ELEMENTS(g_aVmcsSegBase) == X86_SREG_COUNT);
751AssertCompile(RT_ELEMENTS(g_aVmcsSegAttr) == X86_SREG_COUNT);
752#endif /* VBOX_STRICT */
753
754#ifdef HMVMX_USE_FUNCTION_TABLE
755/**
756 * VMX_EXIT dispatch table.
757 */
758static const struct CLANG11NOTHROWWEIRDNESS { PFNVMXEXITHANDLER pfn; } g_aVMExitHandlers[VMX_EXIT_MAX + 1] =
759{
760 /* 0 VMX_EXIT_XCPT_OR_NMI */ { hmR0VmxExitXcptOrNmi },
761 /* 1 VMX_EXIT_EXT_INT */ { hmR0VmxExitExtInt },
762 /* 2 VMX_EXIT_TRIPLE_FAULT */ { hmR0VmxExitTripleFault },
763 /* 3 VMX_EXIT_INIT_SIGNAL */ { hmR0VmxExitErrUnexpected },
764 /* 4 VMX_EXIT_SIPI */ { hmR0VmxExitErrUnexpected },
765 /* 5 VMX_EXIT_IO_SMI */ { hmR0VmxExitErrUnexpected },
766 /* 6 VMX_EXIT_SMI */ { hmR0VmxExitErrUnexpected },
767 /* 7 VMX_EXIT_INT_WINDOW */ { hmR0VmxExitIntWindow },
768 /* 8 VMX_EXIT_NMI_WINDOW */ { hmR0VmxExitNmiWindow },
769 /* 9 VMX_EXIT_TASK_SWITCH */ { hmR0VmxExitTaskSwitch },
770 /* 10 VMX_EXIT_CPUID */ { hmR0VmxExitCpuid },
771 /* 11 VMX_EXIT_GETSEC */ { hmR0VmxExitGetsec },
772 /* 12 VMX_EXIT_HLT */ { hmR0VmxExitHlt },
773 /* 13 VMX_EXIT_INVD */ { hmR0VmxExitInvd },
774 /* 14 VMX_EXIT_INVLPG */ { hmR0VmxExitInvlpg },
775 /* 15 VMX_EXIT_RDPMC */ { hmR0VmxExitRdpmc },
776 /* 16 VMX_EXIT_RDTSC */ { hmR0VmxExitRdtsc },
777 /* 17 VMX_EXIT_RSM */ { hmR0VmxExitErrUnexpected },
778 /* 18 VMX_EXIT_VMCALL */ { hmR0VmxExitVmcall },
779#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
780 /* 19 VMX_EXIT_VMCLEAR */ { hmR0VmxExitVmclear },
781 /* 20 VMX_EXIT_VMLAUNCH */ { hmR0VmxExitVmlaunch },
782 /* 21 VMX_EXIT_VMPTRLD */ { hmR0VmxExitVmptrld },
783 /* 22 VMX_EXIT_VMPTRST */ { hmR0VmxExitVmptrst },
784 /* 23 VMX_EXIT_VMREAD */ { hmR0VmxExitVmread },
785 /* 24 VMX_EXIT_VMRESUME */ { hmR0VmxExitVmresume },
786 /* 25 VMX_EXIT_VMWRITE */ { hmR0VmxExitVmwrite },
787 /* 26 VMX_EXIT_VMXOFF */ { hmR0VmxExitVmxoff },
788 /* 27 VMX_EXIT_VMXON */ { hmR0VmxExitVmxon },
789#else
790 /* 19 VMX_EXIT_VMCLEAR */ { hmR0VmxExitSetPendingXcptUD },
791 /* 20 VMX_EXIT_VMLAUNCH */ { hmR0VmxExitSetPendingXcptUD },
792 /* 21 VMX_EXIT_VMPTRLD */ { hmR0VmxExitSetPendingXcptUD },
793 /* 22 VMX_EXIT_VMPTRST */ { hmR0VmxExitSetPendingXcptUD },
794 /* 23 VMX_EXIT_VMREAD */ { hmR0VmxExitSetPendingXcptUD },
795 /* 24 VMX_EXIT_VMRESUME */ { hmR0VmxExitSetPendingXcptUD },
796 /* 25 VMX_EXIT_VMWRITE */ { hmR0VmxExitSetPendingXcptUD },
797 /* 26 VMX_EXIT_VMXOFF */ { hmR0VmxExitSetPendingXcptUD },
798 /* 27 VMX_EXIT_VMXON */ { hmR0VmxExitSetPendingXcptUD },
799#endif
800 /* 28 VMX_EXIT_MOV_CRX */ { hmR0VmxExitMovCRx },
801 /* 29 VMX_EXIT_MOV_DRX */ { hmR0VmxExitMovDRx },
802 /* 30 VMX_EXIT_IO_INSTR */ { hmR0VmxExitIoInstr },
803 /* 31 VMX_EXIT_RDMSR */ { hmR0VmxExitRdmsr },
804 /* 32 VMX_EXIT_WRMSR */ { hmR0VmxExitWrmsr },
805 /* 33 VMX_EXIT_ERR_INVALID_GUEST_STATE */ { hmR0VmxExitErrInvalidGuestState },
806 /* 34 VMX_EXIT_ERR_MSR_LOAD */ { hmR0VmxExitErrUnexpected },
807 /* 35 UNDEFINED */ { hmR0VmxExitErrUnexpected },
808 /* 36 VMX_EXIT_MWAIT */ { hmR0VmxExitMwait },
809 /* 37 VMX_EXIT_MTF */ { hmR0VmxExitMtf },
810 /* 38 UNDEFINED */ { hmR0VmxExitErrUnexpected },
811 /* 39 VMX_EXIT_MONITOR */ { hmR0VmxExitMonitor },
812 /* 40 VMX_EXIT_PAUSE */ { hmR0VmxExitPause },
813 /* 41 VMX_EXIT_ERR_MACHINE_CHECK */ { hmR0VmxExitErrUnexpected },
814 /* 42 UNDEFINED */ { hmR0VmxExitErrUnexpected },
815 /* 43 VMX_EXIT_TPR_BELOW_THRESHOLD */ { hmR0VmxExitTprBelowThreshold },
816 /* 44 VMX_EXIT_APIC_ACCESS */ { hmR0VmxExitApicAccess },
817 /* 45 VMX_EXIT_VIRTUALIZED_EOI */ { hmR0VmxExitErrUnexpected },
818 /* 46 VMX_EXIT_GDTR_IDTR_ACCESS */ { hmR0VmxExitErrUnexpected },
819 /* 47 VMX_EXIT_LDTR_TR_ACCESS */ { hmR0VmxExitErrUnexpected },
820 /* 48 VMX_EXIT_EPT_VIOLATION */ { hmR0VmxExitEptViolation },
821 /* 49 VMX_EXIT_EPT_MISCONFIG */ { hmR0VmxExitEptMisconfig },
822 /* 50 VMX_EXIT_INVEPT */ { hmR0VmxExitSetPendingXcptUD },
823 /* 51 VMX_EXIT_RDTSCP */ { hmR0VmxExitRdtscp },
824 /* 52 VMX_EXIT_PREEMPT_TIMER */ { hmR0VmxExitPreemptTimer },
825#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
826 /* 53 VMX_EXIT_INVVPID */ { hmR0VmxExitInvvpid },
827#else
828 /* 53 VMX_EXIT_INVVPID */ { hmR0VmxExitSetPendingXcptUD },
829#endif
830 /* 54 VMX_EXIT_WBINVD */ { hmR0VmxExitWbinvd },
831 /* 55 VMX_EXIT_XSETBV */ { hmR0VmxExitXsetbv },
832 /* 56 VMX_EXIT_APIC_WRITE */ { hmR0VmxExitErrUnexpected },
833 /* 57 VMX_EXIT_RDRAND */ { hmR0VmxExitErrUnexpected },
834 /* 58 VMX_EXIT_INVPCID */ { hmR0VmxExitInvpcid },
835 /* 59 VMX_EXIT_VMFUNC */ { hmR0VmxExitErrUnexpected },
836 /* 60 VMX_EXIT_ENCLS */ { hmR0VmxExitErrUnexpected },
837 /* 61 VMX_EXIT_RDSEED */ { hmR0VmxExitErrUnexpected },
838 /* 62 VMX_EXIT_PML_FULL */ { hmR0VmxExitErrUnexpected },
839 /* 63 VMX_EXIT_XSAVES */ { hmR0VmxExitErrUnexpected },
840 /* 64 VMX_EXIT_XRSTORS */ { hmR0VmxExitErrUnexpected },
841 /* 65 UNDEFINED */ { hmR0VmxExitErrUnexpected },
842 /* 66 VMX_EXIT_SPP_EVENT */ { hmR0VmxExitErrUnexpected },
843 /* 67 VMX_EXIT_UMWAIT */ { hmR0VmxExitErrUnexpected },
844 /* 68 VMX_EXIT_TPAUSE */ { hmR0VmxExitErrUnexpected },
845};
846#endif /* HMVMX_USE_FUNCTION_TABLE */
847
848#if defined(VBOX_STRICT) && defined(LOG_ENABLED)
849static const char * const g_apszVmxInstrErrors[HMVMX_INSTR_ERROR_MAX + 1] =
850{
851 /* 0 */ "(Not Used)",
852 /* 1 */ "VMCALL executed in VMX root operation.",
853 /* 2 */ "VMCLEAR with invalid physical address.",
854 /* 3 */ "VMCLEAR with VMXON pointer.",
855 /* 4 */ "VMLAUNCH with non-clear VMCS.",
856 /* 5 */ "VMRESUME with non-launched VMCS.",
857 /* 6 */ "VMRESUME after VMXOFF",
858 /* 7 */ "VM-entry with invalid control fields.",
859 /* 8 */ "VM-entry with invalid host state fields.",
860 /* 9 */ "VMPTRLD with invalid physical address.",
861 /* 10 */ "VMPTRLD with VMXON pointer.",
862 /* 11 */ "VMPTRLD with incorrect revision identifier.",
863 /* 12 */ "VMREAD/VMWRITE from/to unsupported VMCS component.",
864 /* 13 */ "VMWRITE to read-only VMCS component.",
865 /* 14 */ "(Not Used)",
866 /* 15 */ "VMXON executed in VMX root operation.",
867 /* 16 */ "VM-entry with invalid executive-VMCS pointer.",
868 /* 17 */ "VM-entry with non-launched executing VMCS.",
869 /* 18 */ "VM-entry with executive-VMCS pointer not VMXON pointer.",
870 /* 19 */ "VMCALL with non-clear VMCS.",
871 /* 20 */ "VMCALL with invalid VM-exit control fields.",
872 /* 21 */ "(Not Used)",
873 /* 22 */ "VMCALL with incorrect MSEG revision identifier.",
874 /* 23 */ "VMXOFF under dual monitor treatment of SMIs and SMM.",
875 /* 24 */ "VMCALL with invalid SMM-monitor features.",
876 /* 25 */ "VM-entry with invalid VM-execution control fields in executive VMCS.",
877 /* 26 */ "VM-entry with events blocked by MOV SS.",
878 /* 27 */ "(Not Used)",
879 /* 28 */ "Invalid operand to INVEPT/INVVPID."
880};
881#endif /* VBOX_STRICT && LOG_ENABLED */
882
883
884/**
885 * Checks if the given MSR is part of the lastbranch-from-IP MSR stack.
886 * @returns @c true if it's part of LBR stack, @c false otherwise.
887 *
888 * @param pVM The cross context VM structure.
889 * @param idMsr The MSR.
890 * @param pidxMsr Where to store the index of the MSR in the LBR MSR array.
891 * Optional, can be NULL.
892 *
893 * @remarks Must only be called when LBR is enabled.
894 */
895DECL_FORCE_INLINE(bool) hmR0VmxIsLbrBranchFromMsr(PCVMCC pVM, uint32_t idMsr, uint32_t *pidxMsr)
896{
897 Assert(pVM->hmr0.s.vmx.fLbr);
898 Assert(pVM->hmr0.s.vmx.idLbrFromIpMsrFirst);
899 uint32_t const cLbrStack = pVM->hmr0.s.vmx.idLbrFromIpMsrLast - pVM->hmr0.s.vmx.idLbrFromIpMsrFirst + 1;
900 uint32_t const idxMsr = idMsr - pVM->hmr0.s.vmx.idLbrFromIpMsrFirst;
901 if (idxMsr < cLbrStack)
902 {
903 if (pidxMsr)
904 *pidxMsr = idxMsr;
905 return true;
906 }
907 return false;
908}
909
910
911/**
912 * Checks if the given MSR is part of the lastbranch-to-IP MSR stack.
913 * @returns @c true if it's part of LBR stack, @c false otherwise.
914 *
915 * @param pVM The cross context VM structure.
916 * @param idMsr The MSR.
917 * @param pidxMsr Where to store the index of the MSR in the LBR MSR array.
918 * Optional, can be NULL.
919 *
920 * @remarks Must only be called when LBR is enabled and when lastbranch-to-IP MSRs
921 * are supported by the CPU (see hmR0VmxSetupLbrMsrRange).
922 */
923DECL_FORCE_INLINE(bool) hmR0VmxIsLbrBranchToMsr(PCVMCC pVM, uint32_t idMsr, uint32_t *pidxMsr)
924{
925 Assert(pVM->hmr0.s.vmx.fLbr);
926 if (pVM->hmr0.s.vmx.idLbrToIpMsrFirst)
927 {
928 uint32_t const cLbrStack = pVM->hmr0.s.vmx.idLbrToIpMsrLast - pVM->hmr0.s.vmx.idLbrToIpMsrFirst + 1;
929 uint32_t const idxMsr = idMsr - pVM->hmr0.s.vmx.idLbrToIpMsrFirst;
930 if (idxMsr < cLbrStack)
931 {
932 if (pidxMsr)
933 *pidxMsr = idxMsr;
934 return true;
935 }
936 }
937 return false;
938}
939
940
941/**
942 * Gets the CR0 guest/host mask.
943 *
944 * These bits typically does not change through the lifetime of a VM. Any bit set in
945 * this mask is owned by the host/hypervisor and would cause a VM-exit when modified
946 * by the guest.
947 *
948 * @returns The CR0 guest/host mask.
949 * @param pVCpu The cross context virtual CPU structure.
950 */
951static uint64_t hmR0VmxGetFixedCr0Mask(PCVMCPUCC pVCpu)
952{
953 /*
954 * Modifications to CR0 bits that VT-x ignores saving/restoring (CD, ET, NW) and
955 * to CR0 bits that we require for shadow paging (PG) by the guest must cause VM-exits.
956 *
957 * Furthermore, modifications to any bits that are reserved/unspecified currently
958 * by the Intel spec. must also cause a VM-exit. This prevents unpredictable behavior
959 * when future CPUs specify and use currently reserved/unspecified bits.
960 */
961 /** @todo Avoid intercepting CR0.PE with unrestricted guest execution. Fix PGM
962 * enmGuestMode to be in-sync with the current mode. See @bugref{6398}
963 * and @bugref{6944}. */
964 PCVMCC pVM = pVCpu->CTX_SUFF(pVM);
965 return ( X86_CR0_PE
966 | X86_CR0_NE
967 | (pVM->hmr0.s.fNestedPaging ? 0 : X86_CR0_WP)
968 | X86_CR0_PG
969 | VMX_EXIT_HOST_CR0_IGNORE_MASK);
970}
971
972
973/**
974 * Gets the CR4 guest/host mask.
975 *
976 * These bits typically does not change through the lifetime of a VM. Any bit set in
977 * this mask is owned by the host/hypervisor and would cause a VM-exit when modified
978 * by the guest.
979 *
980 * @returns The CR4 guest/host mask.
981 * @param pVCpu The cross context virtual CPU structure.
982 */
983static uint64_t hmR0VmxGetFixedCr4Mask(PCVMCPUCC pVCpu)
984{
985 /*
986 * We construct a mask of all CR4 bits that the guest can modify without causing
987 * a VM-exit. Then invert this mask to obtain all CR4 bits that should cause
988 * a VM-exit when the guest attempts to modify them when executing using
989 * hardware-assisted VMX.
990 *
991 * When a feature is not exposed to the guest (and may be present on the host),
992 * we want to intercept guest modifications to the bit so we can emulate proper
993 * behavior (e.g., #GP).
994 *
995 * Furthermore, only modifications to those bits that don't require immediate
996 * emulation is allowed. For e.g., PCIDE is excluded because the behavior
997 * depends on CR3 which might not always be the guest value while executing
998 * using hardware-assisted VMX.
999 */
1000 PCVMCC pVM = pVCpu->CTX_SUFF(pVM);
1001 bool const fFsGsBase = pVM->cpum.ro.GuestFeatures.fFsGsBase;
1002 bool const fXSaveRstor = pVM->cpum.ro.GuestFeatures.fXSaveRstor;
1003 bool const fFxSaveRstor = pVM->cpum.ro.GuestFeatures.fFxSaveRstor;
1004
1005 /*
1006 * Paranoia.
1007 * Ensure features exposed to the guest are present on the host.
1008 */
1009 Assert(!fFsGsBase || pVM->cpum.ro.HostFeatures.fFsGsBase);
1010 Assert(!fXSaveRstor || pVM->cpum.ro.HostFeatures.fXSaveRstor);
1011 Assert(!fFxSaveRstor || pVM->cpum.ro.HostFeatures.fFxSaveRstor);
1012
1013 uint64_t const fGstMask = ( X86_CR4_PVI
1014 | X86_CR4_TSD
1015 | X86_CR4_DE
1016 | X86_CR4_MCE
1017 | X86_CR4_PCE
1018 | X86_CR4_OSXMMEEXCPT
1019 | (fFsGsBase ? X86_CR4_FSGSBASE : 0)
1020 | (fXSaveRstor ? X86_CR4_OSXSAVE : 0)
1021 | (fFxSaveRstor ? X86_CR4_OSFXSR : 0));
1022 return ~fGstMask;
1023}
1024
1025
1026/**
1027 * Gets the active (in use) VMCS info. object for the specified VCPU.
1028 *
1029 * This is either the guest or nested-guest VMCS info. and need not necessarily
1030 * pertain to the "current" VMCS (in the VMX definition of the term). For instance,
1031 * if the VM-entry failed due to an invalid-guest state, we may have "cleared" the
1032 * current VMCS while returning to ring-3. However, the VMCS info. object for that
1033 * VMCS would still be active and returned here so that we could dump the VMCS
1034 * fields to ring-3 for diagnostics. This function is thus only used to
1035 * distinguish between the nested-guest or guest VMCS.
1036 *
1037 * @returns The active VMCS information.
1038 * @param pVCpu The cross context virtual CPU structure.
1039 *
1040 * @thread EMT.
1041 * @remarks This function may be called with preemption or interrupts disabled!
1042 */
1043DECLINLINE(PVMXVMCSINFO) hmGetVmxActiveVmcsInfo(PVMCPUCC pVCpu)
1044{
1045 if (!pVCpu->hmr0.s.vmx.fSwitchedToNstGstVmcs)
1046 return &pVCpu->hmr0.s.vmx.VmcsInfo;
1047 return &pVCpu->hmr0.s.vmx.VmcsInfoNstGst;
1048}
1049
1050
1051/**
1052 * Returns whether the VM-exit MSR-store area differs from the VM-exit MSR-load
1053 * area.
1054 *
1055 * @returns @c true if it's different, @c false otherwise.
1056 * @param pVmcsInfo The VMCS info. object.
1057 */
1058DECL_FORCE_INLINE(bool) hmR0VmxIsSeparateExitMsrStoreAreaVmcs(PCVMXVMCSINFO pVmcsInfo)
1059{
1060 return RT_BOOL( pVmcsInfo->pvGuestMsrStore != pVmcsInfo->pvGuestMsrLoad
1061 && pVmcsInfo->pvGuestMsrStore);
1062}
1063
1064
1065/**
1066 * Sets the given Processor-based VM-execution controls.
1067 *
1068 * @param pVmxTransient The VMX-transient structure.
1069 * @param uProcCtls The Processor-based VM-execution controls to set.
1070 */
1071static void hmR0VmxSetProcCtlsVmcs(PVMXTRANSIENT pVmxTransient, uint32_t uProcCtls)
1072{
1073 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1074 if ((pVmcsInfo->u32ProcCtls & uProcCtls) != uProcCtls)
1075 {
1076 pVmcsInfo->u32ProcCtls |= uProcCtls;
1077 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
1078 AssertRC(rc);
1079 }
1080}
1081
1082
1083/**
1084 * Removes the given Processor-based VM-execution controls.
1085 *
1086 * @param pVCpu The cross context virtual CPU structure.
1087 * @param pVmxTransient The VMX-transient structure.
1088 * @param uProcCtls The Processor-based VM-execution controls to remove.
1089 *
1090 * @remarks When executing a nested-guest, this will not remove any of the specified
1091 * controls if the nested hypervisor has set any one of them.
1092 */
1093static void hmR0VmxRemoveProcCtlsVmcs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uProcCtls)
1094{
1095 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1096 if (pVmcsInfo->u32ProcCtls & uProcCtls)
1097 {
1098#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1099 if ( !pVmxTransient->fIsNestedGuest
1100 || !CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, uProcCtls))
1101#else
1102 NOREF(pVCpu);
1103 if (!pVmxTransient->fIsNestedGuest)
1104#endif
1105 {
1106 pVmcsInfo->u32ProcCtls &= ~uProcCtls;
1107 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
1108 AssertRC(rc);
1109 }
1110 }
1111}
1112
1113
1114/**
1115 * Sets the TSC offset for the current VMCS.
1116 *
1117 * @param uTscOffset The TSC offset to set.
1118 * @param pVmcsInfo The VMCS info. object.
1119 */
1120static void hmR0VmxSetTscOffsetVmcs(PVMXVMCSINFO pVmcsInfo, uint64_t uTscOffset)
1121{
1122 if (pVmcsInfo->u64TscOffset != uTscOffset)
1123 {
1124 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, uTscOffset);
1125 AssertRC(rc);
1126 pVmcsInfo->u64TscOffset = uTscOffset;
1127 }
1128}
1129
1130
1131/**
1132 * Adds one or more exceptions to the exception bitmap and commits it to the current
1133 * VMCS.
1134 *
1135 * @param pVmxTransient The VMX-transient structure.
1136 * @param uXcptMask The exception(s) to add.
1137 */
1138static void hmR0VmxAddXcptInterceptMask(PCVMXTRANSIENT pVmxTransient, uint32_t uXcptMask)
1139{
1140 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1141 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
1142 if ((uXcptBitmap & uXcptMask) != uXcptMask)
1143 {
1144 uXcptBitmap |= uXcptMask;
1145 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
1146 AssertRC(rc);
1147 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
1148 }
1149}
1150
1151
1152/**
1153 * Adds an exception to the exception bitmap and commits it to the current VMCS.
1154 *
1155 * @param pVmxTransient The VMX-transient structure.
1156 * @param uXcpt The exception to add.
1157 */
1158static void hmR0VmxAddXcptIntercept(PCVMXTRANSIENT pVmxTransient, uint8_t uXcpt)
1159{
1160 Assert(uXcpt <= X86_XCPT_LAST);
1161 hmR0VmxAddXcptInterceptMask(pVmxTransient, RT_BIT_32(uXcpt));
1162}
1163
1164
1165/**
1166 * Remove one or more exceptions from the exception bitmap and commits it to the
1167 * current VMCS.
1168 *
1169 * This takes care of not removing the exception intercept if a nested-guest
1170 * requires the exception to be intercepted.
1171 *
1172 * @returns VBox status code.
1173 * @param pVCpu The cross context virtual CPU structure.
1174 * @param pVmxTransient The VMX-transient structure.
1175 * @param uXcptMask The exception(s) to remove.
1176 */
1177static int hmR0VmxRemoveXcptInterceptMask(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t uXcptMask)
1178{
1179 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1180 uint32_t u32XcptBitmap = pVmcsInfo->u32XcptBitmap;
1181 if (u32XcptBitmap & uXcptMask)
1182 {
1183#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1184 if (!pVmxTransient->fIsNestedGuest)
1185 { /* likely */ }
1186 else
1187 {
1188 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
1189 uXcptMask &= ~pVmcsNstGst->u32XcptBitmap;
1190 }
1191#endif
1192#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
1193 uXcptMask &= ~( RT_BIT(X86_XCPT_BP)
1194 | RT_BIT(X86_XCPT_DE)
1195 | RT_BIT(X86_XCPT_NM)
1196 | RT_BIT(X86_XCPT_TS)
1197 | RT_BIT(X86_XCPT_UD)
1198 | RT_BIT(X86_XCPT_NP)
1199 | RT_BIT(X86_XCPT_SS)
1200 | RT_BIT(X86_XCPT_GP)
1201 | RT_BIT(X86_XCPT_PF)
1202 | RT_BIT(X86_XCPT_MF));
1203#elif defined(HMVMX_ALWAYS_TRAP_PF)
1204 uXcptMask &= ~RT_BIT(X86_XCPT_PF);
1205#endif
1206 if (uXcptMask)
1207 {
1208 /* Validate we are not removing any essential exception intercepts. */
1209 Assert(pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging || !(uXcptMask & RT_BIT(X86_XCPT_PF)));
1210 NOREF(pVCpu);
1211 Assert(!(uXcptMask & RT_BIT(X86_XCPT_DB)));
1212 Assert(!(uXcptMask & RT_BIT(X86_XCPT_AC)));
1213
1214 /* Remove it from the exception bitmap. */
1215 u32XcptBitmap &= ~uXcptMask;
1216
1217 /* Commit and update the cache if necessary. */
1218 if (pVmcsInfo->u32XcptBitmap != u32XcptBitmap)
1219 {
1220 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
1221 AssertRC(rc);
1222 pVmcsInfo->u32XcptBitmap = u32XcptBitmap;
1223 }
1224 }
1225 }
1226 return VINF_SUCCESS;
1227}
1228
1229
1230/**
1231 * Remove an exceptions from the exception bitmap and commits it to the current
1232 * VMCS.
1233 *
1234 * @returns VBox status code.
1235 * @param pVCpu The cross context virtual CPU structure.
1236 * @param pVmxTransient The VMX-transient structure.
1237 * @param uXcpt The exception to remove.
1238 */
1239static int hmR0VmxRemoveXcptIntercept(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint8_t uXcpt)
1240{
1241 return hmR0VmxRemoveXcptInterceptMask(pVCpu, pVmxTransient, RT_BIT(uXcpt));
1242}
1243
1244
1245/**
1246 * Loads the VMCS specified by the VMCS info. object.
1247 *
1248 * @returns VBox status code.
1249 * @param pVmcsInfo The VMCS info. object.
1250 *
1251 * @remarks Can be called with interrupts disabled.
1252 */
1253static int hmR0VmxLoadVmcs(PVMXVMCSINFO pVmcsInfo)
1254{
1255 Assert(pVmcsInfo->HCPhysVmcs != 0 && pVmcsInfo->HCPhysVmcs != NIL_RTHCPHYS);
1256 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1257
1258 int rc = VMXLoadVmcs(pVmcsInfo->HCPhysVmcs);
1259 if (RT_SUCCESS(rc))
1260 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_CURRENT;
1261 return rc;
1262}
1263
1264
1265/**
1266 * Clears the VMCS specified by the VMCS info. object.
1267 *
1268 * @returns VBox status code.
1269 * @param pVmcsInfo The VMCS info. object.
1270 *
1271 * @remarks Can be called with interrupts disabled.
1272 */
1273static int hmR0VmxClearVmcs(PVMXVMCSINFO pVmcsInfo)
1274{
1275 Assert(pVmcsInfo->HCPhysVmcs != 0 && pVmcsInfo->HCPhysVmcs != NIL_RTHCPHYS);
1276 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1277
1278 int rc = VMXClearVmcs(pVmcsInfo->HCPhysVmcs);
1279 if (RT_SUCCESS(rc))
1280 pVmcsInfo->fVmcsState = VMX_V_VMCS_LAUNCH_STATE_CLEAR;
1281 return rc;
1282}
1283
1284
1285#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1286/**
1287 * Loads the shadow VMCS specified by the VMCS info. object.
1288 *
1289 * @returns VBox status code.
1290 * @param pVmcsInfo The VMCS info. object.
1291 *
1292 * @remarks Can be called with interrupts disabled.
1293 */
1294static int hmR0VmxLoadShadowVmcs(PVMXVMCSINFO pVmcsInfo)
1295{
1296 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1297 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
1298
1299 int rc = VMXLoadVmcs(pVmcsInfo->HCPhysShadowVmcs);
1300 if (RT_SUCCESS(rc))
1301 pVmcsInfo->fShadowVmcsState |= VMX_V_VMCS_LAUNCH_STATE_CURRENT;
1302 return rc;
1303}
1304
1305
1306/**
1307 * Clears the shadow VMCS specified by the VMCS info. object.
1308 *
1309 * @returns VBox status code.
1310 * @param pVmcsInfo The VMCS info. object.
1311 *
1312 * @remarks Can be called with interrupts disabled.
1313 */
1314static int hmR0VmxClearShadowVmcs(PVMXVMCSINFO pVmcsInfo)
1315{
1316 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1317 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
1318
1319 int rc = VMXClearVmcs(pVmcsInfo->HCPhysShadowVmcs);
1320 if (RT_SUCCESS(rc))
1321 pVmcsInfo->fShadowVmcsState = VMX_V_VMCS_LAUNCH_STATE_CLEAR;
1322 return rc;
1323}
1324
1325
1326/**
1327 * Switches from and to the specified VMCSes.
1328 *
1329 * @returns VBox status code.
1330 * @param pVmcsInfoFrom The VMCS info. object we are switching from.
1331 * @param pVmcsInfoTo The VMCS info. object we are switching to.
1332 *
1333 * @remarks Called with interrupts disabled.
1334 */
1335static int hmR0VmxSwitchVmcs(PVMXVMCSINFO pVmcsInfoFrom, PVMXVMCSINFO pVmcsInfoTo)
1336{
1337 /*
1338 * Clear the VMCS we are switching out if it has not already been cleared.
1339 * This will sync any CPU internal data back to the VMCS.
1340 */
1341 if (pVmcsInfoFrom->fVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
1342 {
1343 int rc = hmR0VmxClearVmcs(pVmcsInfoFrom);
1344 if (RT_SUCCESS(rc))
1345 {
1346 /*
1347 * The shadow VMCS, if any, would not be active at this point since we
1348 * would have cleared it while importing the virtual hardware-virtualization
1349 * state as part the VMLAUNCH/VMRESUME VM-exit. Hence, there's no need to
1350 * clear the shadow VMCS here, just assert for safety.
1351 */
1352 Assert(!pVmcsInfoFrom->pvShadowVmcs || pVmcsInfoFrom->fShadowVmcsState == VMX_V_VMCS_LAUNCH_STATE_CLEAR);
1353 }
1354 else
1355 return rc;
1356 }
1357
1358 /*
1359 * Clear the VMCS we are switching to if it has not already been cleared.
1360 * This will initialize the VMCS launch state to "clear" required for loading it.
1361 *
1362 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
1363 */
1364 if (pVmcsInfoTo->fVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
1365 {
1366 int rc = hmR0VmxClearVmcs(pVmcsInfoTo);
1367 if (RT_SUCCESS(rc))
1368 { /* likely */ }
1369 else
1370 return rc;
1371 }
1372
1373 /*
1374 * Finally, load the VMCS we are switching to.
1375 */
1376 return hmR0VmxLoadVmcs(pVmcsInfoTo);
1377}
1378
1379
1380/**
1381 * Switches between the guest VMCS and the nested-guest VMCS as specified by the
1382 * caller.
1383 *
1384 * @returns VBox status code.
1385 * @param pVCpu The cross context virtual CPU structure.
1386 * @param fSwitchToNstGstVmcs Whether to switch to the nested-guest VMCS (pass
1387 * true) or guest VMCS (pass false).
1388 */
1389static int hmR0VmxSwitchToGstOrNstGstVmcs(PVMCPUCC pVCpu, bool fSwitchToNstGstVmcs)
1390{
1391 /* Ensure we have synced everything from the guest-CPU context to the VMCS before switching. */
1392 HMVMX_CPUMCTX_ASSERT(pVCpu, HMVMX_CPUMCTX_EXTRN_ALL);
1393
1394 PVMXVMCSINFO pVmcsInfoFrom;
1395 PVMXVMCSINFO pVmcsInfoTo;
1396 if (fSwitchToNstGstVmcs)
1397 {
1398 pVmcsInfoFrom = &pVCpu->hmr0.s.vmx.VmcsInfo;
1399 pVmcsInfoTo = &pVCpu->hmr0.s.vmx.VmcsInfoNstGst;
1400 }
1401 else
1402 {
1403 pVmcsInfoFrom = &pVCpu->hmr0.s.vmx.VmcsInfoNstGst;
1404 pVmcsInfoTo = &pVCpu->hmr0.s.vmx.VmcsInfo;
1405 }
1406
1407 /*
1408 * Disable interrupts to prevent being preempted while we switch the current VMCS as the
1409 * preemption hook code path acquires the current VMCS.
1410 */
1411 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1412
1413 int rc = hmR0VmxSwitchVmcs(pVmcsInfoFrom, pVmcsInfoTo);
1414 if (RT_SUCCESS(rc))
1415 {
1416 pVCpu->hmr0.s.vmx.fSwitchedToNstGstVmcs = fSwitchToNstGstVmcs;
1417 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcsCopyForRing3 = fSwitchToNstGstVmcs;
1418
1419 /*
1420 * If we are switching to a VMCS that was executed on a different host CPU or was
1421 * never executed before, flag that we need to export the host state before executing
1422 * guest/nested-guest code using hardware-assisted VMX.
1423 *
1424 * This could probably be done in a preemptible context since the preemption hook
1425 * will flag the necessary change in host context. However, since preemption is
1426 * already disabled and to avoid making assumptions about host specific code in
1427 * RTMpCpuId when called with preemption enabled, we'll do this while preemption is
1428 * disabled.
1429 */
1430 if (pVmcsInfoTo->idHostCpuState == RTMpCpuId())
1431 { /* likely */ }
1432 else
1433 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE);
1434
1435 ASMSetFlags(fEFlags);
1436
1437 /*
1438 * We use a different VM-exit MSR-store areas for the guest and nested-guest. Hence,
1439 * flag that we need to update the host MSR values there. Even if we decide in the
1440 * future to share the VM-exit MSR-store area page between the guest and nested-guest,
1441 * if its content differs, we would have to update the host MSRs anyway.
1442 */
1443 pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs = false;
1444 }
1445 else
1446 ASMSetFlags(fEFlags);
1447 return rc;
1448}
1449#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
1450
1451
1452/**
1453 * Updates the VM's last error record.
1454 *
1455 * If there was a VMX instruction error, reads the error data from the VMCS and
1456 * updates VCPU's last error record as well.
1457 *
1458 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1459 * Can be NULL if @a rc is not VERR_VMX_UNABLE_TO_START_VM or
1460 * VERR_VMX_INVALID_VMCS_FIELD.
1461 * @param rc The error code.
1462 */
1463static void hmR0VmxUpdateErrorRecord(PVMCPUCC pVCpu, int rc)
1464{
1465 if ( rc == VERR_VMX_INVALID_VMCS_FIELD
1466 || rc == VERR_VMX_UNABLE_TO_START_VM)
1467 {
1468 AssertPtrReturnVoid(pVCpu);
1469 VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
1470 }
1471 pVCpu->CTX_SUFF(pVM)->hm.s.ForR3.rcInit = rc;
1472}
1473
1474
1475#ifdef VBOX_STRICT
1476/**
1477 * Reads the VM-entry interruption-information field from the VMCS into the VMX
1478 * transient structure.
1479 *
1480 * @param pVmxTransient The VMX-transient structure.
1481 */
1482DECLINLINE(void) hmR0VmxReadEntryIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
1483{
1484 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &pVmxTransient->uEntryIntInfo);
1485 AssertRC(rc);
1486}
1487
1488
1489/**
1490 * Reads the VM-entry exception error code field from the VMCS into
1491 * the VMX transient structure.
1492 *
1493 * @param pVmxTransient The VMX-transient structure.
1494 */
1495DECLINLINE(void) hmR0VmxReadEntryXcptErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1496{
1497 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &pVmxTransient->uEntryXcptErrorCode);
1498 AssertRC(rc);
1499}
1500
1501
1502/**
1503 * Reads the VM-entry exception error code field from the VMCS into
1504 * the VMX transient structure.
1505 *
1506 * @param pVmxTransient The VMX-transient structure.
1507 */
1508DECLINLINE(void) hmR0VmxReadEntryInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
1509{
1510 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &pVmxTransient->cbEntryInstr);
1511 AssertRC(rc);
1512}
1513#endif /* VBOX_STRICT */
1514
1515
1516/**
1517 * Reads the VM-exit interruption-information field from the VMCS into the VMX
1518 * transient structure.
1519 *
1520 * @param pVmxTransient The VMX-transient structure.
1521 */
1522DECLINLINE(void) hmR0VmxReadExitIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
1523{
1524 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INTERRUPTION_INFO))
1525 {
1526 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
1527 AssertRC(rc);
1528 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INTERRUPTION_INFO;
1529 }
1530}
1531
1532
1533/**
1534 * Reads the VM-exit interruption error code from the VMCS into the VMX
1535 * transient structure.
1536 *
1537 * @param pVmxTransient The VMX-transient structure.
1538 */
1539DECLINLINE(void) hmR0VmxReadExitIntErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1540{
1541 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE))
1542 {
1543 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
1544 AssertRC(rc);
1545 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE;
1546 }
1547}
1548
1549
1550/**
1551 * Reads the VM-exit instruction length field from the VMCS into the VMX
1552 * transient structure.
1553 *
1554 * @param pVmxTransient The VMX-transient structure.
1555 */
1556DECLINLINE(void) hmR0VmxReadExitInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
1557{
1558 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INSTR_LEN))
1559 {
1560 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbExitInstr);
1561 AssertRC(rc);
1562 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INSTR_LEN;
1563 }
1564}
1565
1566
1567/**
1568 * Reads the VM-exit instruction-information field from the VMCS into
1569 * the VMX transient structure.
1570 *
1571 * @param pVmxTransient The VMX-transient structure.
1572 */
1573DECLINLINE(void) hmR0VmxReadExitInstrInfoVmcs(PVMXTRANSIENT pVmxTransient)
1574{
1575 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INSTR_INFO))
1576 {
1577 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
1578 AssertRC(rc);
1579 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INSTR_INFO;
1580 }
1581}
1582
1583
1584/**
1585 * Reads the Exit Qualification from the VMCS into the VMX transient structure.
1586 *
1587 * @param pVmxTransient The VMX-transient structure.
1588 */
1589DECLINLINE(void) hmR0VmxReadExitQualVmcs(PVMXTRANSIENT pVmxTransient)
1590{
1591 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_QUALIFICATION))
1592 {
1593 int rc = VMXReadVmcsNw(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQual);
1594 AssertRC(rc);
1595 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_QUALIFICATION;
1596 }
1597}
1598
1599
1600/**
1601 * Reads the Guest-linear address from the VMCS into the VMX transient structure.
1602 *
1603 * @param pVmxTransient The VMX-transient structure.
1604 */
1605DECLINLINE(void) hmR0VmxReadGuestLinearAddrVmcs(PVMXTRANSIENT pVmxTransient)
1606{
1607 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_LINEAR_ADDR))
1608 {
1609 int rc = VMXReadVmcsNw(VMX_VMCS_RO_GUEST_LINEAR_ADDR, &pVmxTransient->uGuestLinearAddr);
1610 AssertRC(rc);
1611 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_LINEAR_ADDR;
1612 }
1613}
1614
1615
1616/**
1617 * Reads the Guest-physical address from the VMCS into the VMX transient structure.
1618 *
1619 * @param pVmxTransient The VMX-transient structure.
1620 */
1621DECLINLINE(void) hmR0VmxReadGuestPhysicalAddrVmcs(PVMXTRANSIENT pVmxTransient)
1622{
1623 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_PHYSICAL_ADDR))
1624 {
1625 int rc = VMXReadVmcs64(VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL, &pVmxTransient->uGuestPhysicalAddr);
1626 AssertRC(rc);
1627 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_PHYSICAL_ADDR;
1628 }
1629}
1630
1631#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1632/**
1633 * Reads the Guest pending-debug exceptions from the VMCS into the VMX transient
1634 * structure.
1635 *
1636 * @param pVmxTransient The VMX-transient structure.
1637 */
1638DECLINLINE(void) hmR0VmxReadGuestPendingDbgXctps(PVMXTRANSIENT pVmxTransient)
1639{
1640 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_PENDING_DBG_XCPTS))
1641 {
1642 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &pVmxTransient->uGuestPendingDbgXcpts);
1643 AssertRC(rc);
1644 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_PENDING_DBG_XCPTS;
1645 }
1646}
1647#endif
1648
1649/**
1650 * Reads the IDT-vectoring information field from the VMCS into the VMX
1651 * transient structure.
1652 *
1653 * @param pVmxTransient The VMX-transient structure.
1654 *
1655 * @remarks No-long-jump zone!!!
1656 */
1657DECLINLINE(void) hmR0VmxReadIdtVectoringInfoVmcs(PVMXTRANSIENT pVmxTransient)
1658{
1659 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_IDT_VECTORING_INFO))
1660 {
1661 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_INFO, &pVmxTransient->uIdtVectoringInfo);
1662 AssertRC(rc);
1663 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_IDT_VECTORING_INFO;
1664 }
1665}
1666
1667
1668/**
1669 * Reads the IDT-vectoring error code from the VMCS into the VMX
1670 * transient structure.
1671 *
1672 * @param pVmxTransient The VMX-transient structure.
1673 */
1674DECLINLINE(void) hmR0VmxReadIdtVectoringErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1675{
1676 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_IDT_VECTORING_ERROR_CODE))
1677 {
1678 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
1679 AssertRC(rc);
1680 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_IDT_VECTORING_ERROR_CODE;
1681 }
1682}
1683
1684#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
1685/**
1686 * Reads all relevant read-only VMCS fields into the VMX transient structure.
1687 *
1688 * @param pVmxTransient The VMX-transient structure.
1689 */
1690static void hmR0VmxReadAllRoFieldsVmcs(PVMXTRANSIENT pVmxTransient)
1691{
1692 int rc = VMXReadVmcsNw(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQual);
1693 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbExitInstr);
1694 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
1695 rc |= VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_INFO, &pVmxTransient->uIdtVectoringInfo);
1696 rc |= VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
1697 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
1698 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
1699 rc |= VMXReadVmcsNw(VMX_VMCS_RO_GUEST_LINEAR_ADDR, &pVmxTransient->uGuestLinearAddr);
1700 rc |= VMXReadVmcs64(VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL, &pVmxTransient->uGuestPhysicalAddr);
1701 AssertRC(rc);
1702 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_QUALIFICATION
1703 | HMVMX_READ_EXIT_INSTR_LEN
1704 | HMVMX_READ_EXIT_INSTR_INFO
1705 | HMVMX_READ_IDT_VECTORING_INFO
1706 | HMVMX_READ_IDT_VECTORING_ERROR_CODE
1707 | HMVMX_READ_EXIT_INTERRUPTION_INFO
1708 | HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE
1709 | HMVMX_READ_GUEST_LINEAR_ADDR
1710 | HMVMX_READ_GUEST_PHYSICAL_ADDR;
1711}
1712#endif
1713
1714/**
1715 * Enters VMX root mode operation on the current CPU.
1716 *
1717 * @returns VBox status code.
1718 * @param pHostCpu The HM physical-CPU structure.
1719 * @param pVM The cross context VM structure. Can be
1720 * NULL, after a resume.
1721 * @param HCPhysCpuPage Physical address of the VMXON region.
1722 * @param pvCpuPage Pointer to the VMXON region.
1723 */
1724static int hmR0VmxEnterRootMode(PHMPHYSCPU pHostCpu, PVMCC pVM, RTHCPHYS HCPhysCpuPage, void *pvCpuPage)
1725{
1726 Assert(pHostCpu);
1727 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
1728 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
1729 Assert(pvCpuPage);
1730 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1731
1732 if (pVM)
1733 {
1734 /* Write the VMCS revision identifier to the VMXON region. */
1735 *(uint32_t *)pvCpuPage = RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_ID);
1736 }
1737
1738 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with CR4. */
1739 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1740
1741 /* Enable the VMX bit in CR4 if necessary. */
1742 RTCCUINTREG const uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
1743
1744 /* Record whether VMXE was already prior to us enabling it above. */
1745 pHostCpu->fVmxeAlreadyEnabled = RT_BOOL(uOldCr4 & X86_CR4_VMXE);
1746
1747 /* Enter VMX root mode. */
1748 int rc = VMXEnable(HCPhysCpuPage);
1749 if (RT_FAILURE(rc))
1750 {
1751 /* Restore CR4.VMXE if it was not set prior to our attempt to set it above. */
1752 if (!pHostCpu->fVmxeAlreadyEnabled)
1753 SUPR0ChangeCR4(0 /* fOrMask */, ~(uint64_t)X86_CR4_VMXE);
1754
1755 if (pVM)
1756 pVM->hm.s.ForR3.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
1757 }
1758
1759 /* Restore interrupts. */
1760 ASMSetFlags(fEFlags);
1761 return rc;
1762}
1763
1764
1765/**
1766 * Exits VMX root mode operation on the current CPU.
1767 *
1768 * @returns VBox status code.
1769 * @param pHostCpu The HM physical-CPU structure.
1770 */
1771static int hmR0VmxLeaveRootMode(PHMPHYSCPU pHostCpu)
1772{
1773 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1774
1775 /* Paranoid: Disable interrupts as, in theory, interrupts handlers might mess with CR4. */
1776 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1777
1778 /* If we're for some reason not in VMX root mode, then don't leave it. */
1779 RTCCUINTREG const uHostCr4 = ASMGetCR4();
1780
1781 int rc;
1782 if (uHostCr4 & X86_CR4_VMXE)
1783 {
1784 /* Exit VMX root mode and clear the VMX bit in CR4. */
1785 VMXDisable();
1786
1787 /* Clear CR4.VMXE only if it was clear prior to use setting it. */
1788 if (!pHostCpu->fVmxeAlreadyEnabled)
1789 SUPR0ChangeCR4(0 /* fOrMask */, ~(uint64_t)X86_CR4_VMXE);
1790
1791 rc = VINF_SUCCESS;
1792 }
1793 else
1794 rc = VERR_VMX_NOT_IN_VMX_ROOT_MODE;
1795
1796 /* Restore interrupts. */
1797 ASMSetFlags(fEFlags);
1798 return rc;
1799}
1800
1801
1802/**
1803 * Allocates pages specified as specified by an array of VMX page allocation info
1804 * objects.
1805 *
1806 * The pages contents are zero'd after allocation.
1807 *
1808 * @returns VBox status code.
1809 * @param phMemObj Where to return the handle to the allocation.
1810 * @param paAllocInfo The pointer to the first element of the VMX
1811 * page-allocation info object array.
1812 * @param cEntries The number of elements in the @a paAllocInfo array.
1813 */
1814static int hmR0VmxPagesAllocZ(PRTR0MEMOBJ phMemObj, PVMXPAGEALLOCINFO paAllocInfo, uint32_t cEntries)
1815{
1816 *phMemObj = NIL_RTR0MEMOBJ;
1817
1818 /* Figure out how many pages to allocate. */
1819 uint32_t cPages = 0;
1820 for (uint32_t iPage = 0; iPage < cEntries; iPage++)
1821 cPages += !!paAllocInfo[iPage].fValid;
1822
1823 /* Allocate the pages. */
1824 if (cPages)
1825 {
1826 size_t const cbPages = cPages << PAGE_SHIFT;
1827 int rc = RTR0MemObjAllocPage(phMemObj, cbPages, false /* fExecutable */);
1828 if (RT_FAILURE(rc))
1829 return rc;
1830
1831 /* Zero the contents and assign each page to the corresponding VMX page-allocation entry. */
1832 void *pvFirstPage = RTR0MemObjAddress(*phMemObj);
1833 RT_BZERO(pvFirstPage, cbPages);
1834
1835 uint32_t iPage = 0;
1836 for (uint32_t i = 0; i < cEntries; i++)
1837 if (paAllocInfo[i].fValid)
1838 {
1839 RTHCPHYS const HCPhysPage = RTR0MemObjGetPagePhysAddr(*phMemObj, iPage);
1840 void *pvPage = (void *)((uintptr_t)pvFirstPage + (iPage << X86_PAGE_4K_SHIFT));
1841 Assert(HCPhysPage && HCPhysPage != NIL_RTHCPHYS);
1842 AssertPtr(pvPage);
1843
1844 Assert(paAllocInfo[iPage].pHCPhys);
1845 Assert(paAllocInfo[iPage].ppVirt);
1846 *paAllocInfo[iPage].pHCPhys = HCPhysPage;
1847 *paAllocInfo[iPage].ppVirt = pvPage;
1848
1849 /* Move to next page. */
1850 ++iPage;
1851 }
1852
1853 /* Make sure all valid (requested) pages have been assigned. */
1854 Assert(iPage == cPages);
1855 }
1856 return VINF_SUCCESS;
1857}
1858
1859
1860/**
1861 * Frees pages allocated using hmR0VmxPagesAllocZ.
1862 *
1863 * @param phMemObj Pointer to the memory object handle. Will be set to
1864 * NIL.
1865 */
1866DECL_FORCE_INLINE(void) hmR0VmxPagesFree(PRTR0MEMOBJ phMemObj)
1867{
1868 /* We can cleanup wholesale since it's all one allocation. */
1869 if (*phMemObj != NIL_RTR0MEMOBJ)
1870 {
1871 RTR0MemObjFree(*phMemObj, true /* fFreeMappings */);
1872 *phMemObj = NIL_RTR0MEMOBJ;
1873 }
1874}
1875
1876
1877/**
1878 * Initializes a VMCS info. object.
1879 *
1880 * @param pVmcsInfo The VMCS info. object.
1881 * @param pVmcsInfoShared The VMCS info. object shared with ring-3.
1882 */
1883static void hmR0VmxVmcsInfoInit(PVMXVMCSINFO pVmcsInfo, PVMXVMCSINFOSHARED pVmcsInfoShared)
1884{
1885 RT_ZERO(*pVmcsInfo);
1886 RT_ZERO(*pVmcsInfoShared);
1887
1888 pVmcsInfo->pShared = pVmcsInfoShared;
1889 Assert(pVmcsInfo->hMemObj == NIL_RTR0MEMOBJ);
1890 pVmcsInfo->HCPhysVmcs = NIL_RTHCPHYS;
1891 pVmcsInfo->HCPhysShadowVmcs = NIL_RTHCPHYS;
1892 pVmcsInfo->HCPhysMsrBitmap = NIL_RTHCPHYS;
1893 pVmcsInfo->HCPhysGuestMsrLoad = NIL_RTHCPHYS;
1894 pVmcsInfo->HCPhysGuestMsrStore = NIL_RTHCPHYS;
1895 pVmcsInfo->HCPhysHostMsrLoad = NIL_RTHCPHYS;
1896 pVmcsInfo->HCPhysVirtApic = NIL_RTHCPHYS;
1897 pVmcsInfo->HCPhysEPTP = NIL_RTHCPHYS;
1898 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
1899 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
1900 pVmcsInfo->idHostCpuExec = NIL_RTCPUID;
1901}
1902
1903
1904/**
1905 * Frees the VT-x structures for a VMCS info. object.
1906 *
1907 * @param pVmcsInfo The VMCS info. object.
1908 * @param pVmcsInfoShared The VMCS info. object shared with ring-3.
1909 */
1910static void hmR0VmxVmcsInfoFree(PVMXVMCSINFO pVmcsInfo, PVMXVMCSINFOSHARED pVmcsInfoShared)
1911{
1912 hmR0VmxPagesFree(&pVmcsInfo->hMemObj);
1913 hmR0VmxVmcsInfoInit(pVmcsInfo, pVmcsInfoShared);
1914}
1915
1916
1917/**
1918 * Allocates the VT-x structures for a VMCS info. object.
1919 *
1920 * @returns VBox status code.
1921 * @param pVCpu The cross context virtual CPU structure.
1922 * @param pVmcsInfo The VMCS info. object.
1923 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
1924 *
1925 * @remarks The caller is expected to take care of any and all allocation failures.
1926 * This function will not perform any cleanup for failures half-way
1927 * through.
1928 */
1929static int hmR0VmxAllocVmcsInfo(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
1930{
1931 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1932
1933 bool const fMsrBitmaps = RT_BOOL(g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS);
1934 bool const fShadowVmcs = !fIsNstGstVmcs ? pVM->hmr0.s.vmx.fUseVmcsShadowing : pVM->cpum.ro.GuestFeatures.fVmxVmcsShadowing;
1935 Assert(!pVM->cpum.ro.GuestFeatures.fVmxVmcsShadowing); /* VMCS shadowing is not yet exposed to the guest. */
1936 VMXPAGEALLOCINFO aAllocInfo[] =
1937 {
1938 { true, 0 /* Unused */, &pVmcsInfo->HCPhysVmcs, &pVmcsInfo->pvVmcs },
1939 { true, 0 /* Unused */, &pVmcsInfo->HCPhysGuestMsrLoad, &pVmcsInfo->pvGuestMsrLoad },
1940 { true, 0 /* Unused */, &pVmcsInfo->HCPhysHostMsrLoad, &pVmcsInfo->pvHostMsrLoad },
1941 { fMsrBitmaps, 0 /* Unused */, &pVmcsInfo->HCPhysMsrBitmap, &pVmcsInfo->pvMsrBitmap },
1942 { fShadowVmcs, 0 /* Unused */, &pVmcsInfo->HCPhysShadowVmcs, &pVmcsInfo->pvShadowVmcs },
1943 };
1944
1945 int rc = hmR0VmxPagesAllocZ(&pVmcsInfo->hMemObj, &aAllocInfo[0], RT_ELEMENTS(aAllocInfo));
1946 if (RT_FAILURE(rc))
1947 return rc;
1948
1949 /*
1950 * We use the same page for VM-entry MSR-load and VM-exit MSR store areas.
1951 * Because they contain a symmetric list of guest MSRs to load on VM-entry and store on VM-exit.
1952 */
1953 AssertCompile(RT_ELEMENTS(aAllocInfo) > 0);
1954 Assert(pVmcsInfo->HCPhysGuestMsrLoad != NIL_RTHCPHYS);
1955 pVmcsInfo->pvGuestMsrStore = pVmcsInfo->pvGuestMsrLoad;
1956 pVmcsInfo->HCPhysGuestMsrStore = pVmcsInfo->HCPhysGuestMsrLoad;
1957
1958 /*
1959 * Get the virtual-APIC page rather than allocating them again.
1960 */
1961 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW)
1962 {
1963 if (!fIsNstGstVmcs)
1964 {
1965 if (PDMHasApic(pVM))
1966 {
1967 rc = APICGetApicPageForCpu(pVCpu, &pVmcsInfo->HCPhysVirtApic, (PRTR0PTR)&pVmcsInfo->pbVirtApic, NULL /*pR3Ptr*/);
1968 if (RT_FAILURE(rc))
1969 return rc;
1970 Assert(pVmcsInfo->pbVirtApic);
1971 Assert(pVmcsInfo->HCPhysVirtApic && pVmcsInfo->HCPhysVirtApic != NIL_RTHCPHYS);
1972 }
1973 }
1974 else
1975 {
1976 pVmcsInfo->pbVirtApic = (uint8_t *)CPUMGetGuestVmxVirtApicPage(&pVCpu->cpum.GstCtx, &pVmcsInfo->HCPhysVirtApic);
1977 Assert(pVmcsInfo->pbVirtApic);
1978 Assert(pVmcsInfo->HCPhysVirtApic && pVmcsInfo->HCPhysVirtApic != NIL_RTHCPHYS);
1979 }
1980 }
1981
1982 return VINF_SUCCESS;
1983}
1984
1985
1986/**
1987 * Free all VT-x structures for the VM.
1988 *
1989 * @returns IPRT status code.
1990 * @param pVM The cross context VM structure.
1991 */
1992static void hmR0VmxStructsFree(PVMCC pVM)
1993{
1994 hmR0VmxPagesFree(&pVM->hmr0.s.vmx.hMemObj);
1995#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1996 if (pVM->hmr0.s.vmx.fUseVmcsShadowing)
1997 {
1998 RTMemFree(pVM->hmr0.s.vmx.paShadowVmcsFields);
1999 pVM->hmr0.s.vmx.paShadowVmcsFields = NULL;
2000 RTMemFree(pVM->hmr0.s.vmx.paShadowVmcsRoFields);
2001 pVM->hmr0.s.vmx.paShadowVmcsRoFields = NULL;
2002 }
2003#endif
2004
2005 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2006 {
2007 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
2008 hmR0VmxVmcsInfoFree(&pVCpu->hmr0.s.vmx.VmcsInfo, &pVCpu->hm.s.vmx.VmcsInfo);
2009#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2010 if (pVM->cpum.ro.GuestFeatures.fVmx)
2011 hmR0VmxVmcsInfoFree(&pVCpu->hmr0.s.vmx.VmcsInfoNstGst, &pVCpu->hm.s.vmx.VmcsInfoNstGst);
2012#endif
2013 }
2014}
2015
2016
2017/**
2018 * Allocate all VT-x structures for the VM.
2019 *
2020 * @returns IPRT status code.
2021 * @param pVM The cross context VM structure.
2022 *
2023 * @remarks This functions will cleanup on memory allocation failures.
2024 */
2025static int hmR0VmxStructsAlloc(PVMCC pVM)
2026{
2027 /*
2028 * Sanity check the VMCS size reported by the CPU as we assume 4KB allocations.
2029 * The VMCS size cannot be more than 4096 bytes.
2030 *
2031 * See Intel spec. Appendix A.1 "Basic VMX Information".
2032 */
2033 uint32_t const cbVmcs = RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_SIZE);
2034 if (cbVmcs <= X86_PAGE_4K_SIZE)
2035 { /* likely */ }
2036 else
2037 {
2038 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_INVALID_VMCS_SIZE;
2039 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2040 }
2041
2042 /*
2043 * Allocate per-VM VT-x structures.
2044 */
2045 bool const fVirtApicAccess = RT_BOOL(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
2046 bool const fUseVmcsShadowing = pVM->hmr0.s.vmx.fUseVmcsShadowing;
2047 VMXPAGEALLOCINFO aAllocInfo[] =
2048 {
2049 { fVirtApicAccess, 0 /* Unused */, &pVM->hmr0.s.vmx.HCPhysApicAccess, (PRTR0PTR)&pVM->hmr0.s.vmx.pbApicAccess },
2050 { fUseVmcsShadowing, 0 /* Unused */, &pVM->hmr0.s.vmx.HCPhysVmreadBitmap, &pVM->hmr0.s.vmx.pvVmreadBitmap },
2051 { fUseVmcsShadowing, 0 /* Unused */, &pVM->hmr0.s.vmx.HCPhysVmwriteBitmap, &pVM->hmr0.s.vmx.pvVmwriteBitmap },
2052#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2053 { true, 0 /* Unused */, &pVM->hmr0.s.vmx.HCPhysScratch, (PRTR0PTR)&pVM->hmr0.s.vmx.pbScratch },
2054#endif
2055 };
2056
2057 int rc = hmR0VmxPagesAllocZ(&pVM->hmr0.s.vmx.hMemObj, &aAllocInfo[0], RT_ELEMENTS(aAllocInfo));
2058 if (RT_SUCCESS(rc))
2059 {
2060#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2061 /* Allocate the shadow VMCS-fields array. */
2062 if (fUseVmcsShadowing)
2063 {
2064 Assert(!pVM->hmr0.s.vmx.cShadowVmcsFields);
2065 Assert(!pVM->hmr0.s.vmx.cShadowVmcsRoFields);
2066 pVM->hmr0.s.vmx.paShadowVmcsFields = (uint32_t *)RTMemAllocZ(sizeof(g_aVmcsFields));
2067 pVM->hmr0.s.vmx.paShadowVmcsRoFields = (uint32_t *)RTMemAllocZ(sizeof(g_aVmcsFields));
2068 if (!pVM->hmr0.s.vmx.paShadowVmcsFields || !pVM->hmr0.s.vmx.paShadowVmcsRoFields)
2069 rc = VERR_NO_MEMORY;
2070 }
2071#endif
2072
2073 /*
2074 * Allocate per-VCPU VT-x structures.
2075 */
2076 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus && RT_SUCCESS(rc); idCpu++)
2077 {
2078 /* Allocate the guest VMCS structures. */
2079 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
2080 rc = hmR0VmxAllocVmcsInfo(pVCpu, &pVCpu->hmr0.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
2081
2082#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2083 /* Allocate the nested-guest VMCS structures, when the VMX feature is exposed to the guest. */
2084 if (pVM->cpum.ro.GuestFeatures.fVmx && RT_SUCCESS(rc))
2085 rc = hmR0VmxAllocVmcsInfo(pVCpu, &pVCpu->hmr0.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
2086#endif
2087 }
2088 if (RT_SUCCESS(rc))
2089 return VINF_SUCCESS;
2090 }
2091 hmR0VmxStructsFree(pVM);
2092 return rc;
2093}
2094
2095
2096/**
2097 * Pre-initializes non-zero fields in VMX structures that will be allocated.
2098 *
2099 * @param pVM The cross context VM structure.
2100 */
2101static void hmR0VmxStructsInit(PVMCC pVM)
2102{
2103 /* Paranoia. */
2104 Assert(pVM->hmr0.s.vmx.pbApicAccess == NULL);
2105#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2106 Assert(pVM->hmr0.s.vmx.pbScratch == NULL);
2107#endif
2108
2109 /*
2110 * Initialize members up-front so we can cleanup en masse on allocation failures.
2111 */
2112#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2113 pVM->hmr0.s.vmx.HCPhysScratch = NIL_RTHCPHYS;
2114#endif
2115 pVM->hmr0.s.vmx.HCPhysApicAccess = NIL_RTHCPHYS;
2116 pVM->hmr0.s.vmx.HCPhysVmreadBitmap = NIL_RTHCPHYS;
2117 pVM->hmr0.s.vmx.HCPhysVmwriteBitmap = NIL_RTHCPHYS;
2118 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2119 {
2120 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
2121 hmR0VmxVmcsInfoInit(&pVCpu->hmr0.s.vmx.VmcsInfo, &pVCpu->hm.s.vmx.VmcsInfo);
2122 hmR0VmxVmcsInfoInit(&pVCpu->hmr0.s.vmx.VmcsInfoNstGst, &pVCpu->hm.s.vmx.VmcsInfoNstGst);
2123 }
2124}
2125
2126#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2127/**
2128 * Returns whether an MSR at the given MSR-bitmap offset is intercepted or not.
2129 *
2130 * @returns @c true if the MSR is intercepted, @c false otherwise.
2131 * @param pvMsrBitmap The MSR bitmap.
2132 * @param offMsr The MSR byte offset.
2133 * @param iBit The bit offset from the byte offset.
2134 */
2135DECLINLINE(bool) hmR0VmxIsMsrBitSet(const void *pvMsrBitmap, uint16_t offMsr, int32_t iBit)
2136{
2137 uint8_t const * const pbMsrBitmap = (uint8_t const * const)pvMsrBitmap;
2138 Assert(pbMsrBitmap);
2139 Assert(offMsr + (iBit >> 3) <= X86_PAGE_4K_SIZE);
2140 return ASMBitTest(pbMsrBitmap + offMsr, iBit);
2141}
2142#endif
2143
2144/**
2145 * Sets the permission bits for the specified MSR in the given MSR bitmap.
2146 *
2147 * If the passed VMCS is a nested-guest VMCS, this function ensures that the
2148 * read/write intercept is cleared from the MSR bitmap used for hardware-assisted
2149 * VMX execution of the nested-guest, only if nested-guest is also not intercepting
2150 * the read/write access of this MSR.
2151 *
2152 * @param pVCpu The cross context virtual CPU structure.
2153 * @param pVmcsInfo The VMCS info. object.
2154 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2155 * @param idMsr The MSR value.
2156 * @param fMsrpm The MSR permissions (see VMXMSRPM_XXX). This must
2157 * include both a read -and- a write permission!
2158 *
2159 * @sa CPUMGetVmxMsrPermission.
2160 * @remarks Can be called with interrupts disabled.
2161 */
2162static void hmR0VmxSetMsrPermission(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs, uint32_t idMsr, uint32_t fMsrpm)
2163{
2164 uint8_t *pbMsrBitmap = (uint8_t *)pVmcsInfo->pvMsrBitmap;
2165 Assert(pbMsrBitmap);
2166 Assert(VMXMSRPM_IS_FLAG_VALID(fMsrpm));
2167
2168 /*
2169 * MSR-bitmap Layout:
2170 * Byte index MSR range Interpreted as
2171 * 0x000 - 0x3ff 0x00000000 - 0x00001fff Low MSR read bits.
2172 * 0x400 - 0x7ff 0xc0000000 - 0xc0001fff High MSR read bits.
2173 * 0x800 - 0xbff 0x00000000 - 0x00001fff Low MSR write bits.
2174 * 0xc00 - 0xfff 0xc0000000 - 0xc0001fff High MSR write bits.
2175 *
2176 * A bit corresponding to an MSR within the above range causes a VM-exit
2177 * if the bit is 1 on executions of RDMSR/WRMSR. If an MSR falls out of
2178 * the MSR range, it always cause a VM-exit.
2179 *
2180 * See Intel spec. 24.6.9 "MSR-Bitmap Address".
2181 */
2182 uint16_t const offBitmapRead = 0;
2183 uint16_t const offBitmapWrite = 0x800;
2184 uint16_t offMsr;
2185 int32_t iBit;
2186 if (idMsr <= UINT32_C(0x00001fff))
2187 {
2188 offMsr = 0;
2189 iBit = idMsr;
2190 }
2191 else if (idMsr - UINT32_C(0xc0000000) <= UINT32_C(0x00001fff))
2192 {
2193 offMsr = 0x400;
2194 iBit = idMsr - UINT32_C(0xc0000000);
2195 }
2196 else
2197 AssertMsgFailedReturnVoid(("Invalid MSR %#RX32\n", idMsr));
2198
2199 /*
2200 * Set the MSR read permission.
2201 */
2202 uint16_t const offMsrRead = offBitmapRead + offMsr;
2203 Assert(offMsrRead + (iBit >> 3) < offBitmapWrite);
2204 if (fMsrpm & VMXMSRPM_ALLOW_RD)
2205 {
2206#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2207 bool const fClear = !fIsNstGstVmcs ? true
2208 : !hmR0VmxIsMsrBitSet(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), offMsrRead, iBit);
2209#else
2210 RT_NOREF2(pVCpu, fIsNstGstVmcs);
2211 bool const fClear = true;
2212#endif
2213 if (fClear)
2214 ASMBitClear(pbMsrBitmap + offMsrRead, iBit);
2215 }
2216 else
2217 ASMBitSet(pbMsrBitmap + offMsrRead, iBit);
2218
2219 /*
2220 * Set the MSR write permission.
2221 */
2222 uint16_t const offMsrWrite = offBitmapWrite + offMsr;
2223 Assert(offMsrWrite + (iBit >> 3) < X86_PAGE_4K_SIZE);
2224 if (fMsrpm & VMXMSRPM_ALLOW_WR)
2225 {
2226#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2227 bool const fClear = !fIsNstGstVmcs ? true
2228 : !hmR0VmxIsMsrBitSet(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), offMsrWrite, iBit);
2229#else
2230 RT_NOREF2(pVCpu, fIsNstGstVmcs);
2231 bool const fClear = true;
2232#endif
2233 if (fClear)
2234 ASMBitClear(pbMsrBitmap + offMsrWrite, iBit);
2235 }
2236 else
2237 ASMBitSet(pbMsrBitmap + offMsrWrite, iBit);
2238}
2239
2240
2241/**
2242 * Updates the VMCS with the number of effective MSRs in the auto-load/store MSR
2243 * area.
2244 *
2245 * @returns VBox status code.
2246 * @param pVCpu The cross context virtual CPU structure.
2247 * @param pVmcsInfo The VMCS info. object.
2248 * @param cMsrs The number of MSRs.
2249 */
2250static int hmR0VmxSetAutoLoadStoreMsrCount(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint32_t cMsrs)
2251{
2252 /* Shouldn't ever happen but there -is- a number. We're well within the recommended 512. */
2253 uint32_t const cMaxSupportedMsrs = VMX_MISC_MAX_MSRS(g_HmMsrs.u.vmx.u64Misc);
2254 if (RT_LIKELY(cMsrs < cMaxSupportedMsrs))
2255 {
2256 /* Commit the MSR counts to the VMCS and update the cache. */
2257 if (pVmcsInfo->cEntryMsrLoad != cMsrs)
2258 {
2259 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, cMsrs); AssertRC(rc);
2260 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, cMsrs); AssertRC(rc);
2261 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, cMsrs); AssertRC(rc);
2262 pVmcsInfo->cEntryMsrLoad = cMsrs;
2263 pVmcsInfo->cExitMsrStore = cMsrs;
2264 pVmcsInfo->cExitMsrLoad = cMsrs;
2265 }
2266 return VINF_SUCCESS;
2267 }
2268
2269 LogRel(("Auto-load/store MSR count exceeded! cMsrs=%u MaxSupported=%u\n", cMsrs, cMaxSupportedMsrs));
2270 pVCpu->hm.s.u32HMError = VMX_UFC_INSUFFICIENT_GUEST_MSR_STORAGE;
2271 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2272}
2273
2274
2275/**
2276 * Adds a new (or updates the value of an existing) guest/host MSR
2277 * pair to be swapped during the world-switch as part of the
2278 * auto-load/store MSR area in the VMCS.
2279 *
2280 * @returns VBox status code.
2281 * @param pVCpu The cross context virtual CPU structure.
2282 * @param pVmxTransient The VMX-transient structure.
2283 * @param idMsr The MSR.
2284 * @param uGuestMsrValue Value of the guest MSR.
2285 * @param fSetReadWrite Whether to set the guest read/write access of this
2286 * MSR (thus not causing a VM-exit).
2287 * @param fUpdateHostMsr Whether to update the value of the host MSR if
2288 * necessary.
2289 */
2290static int hmR0VmxAddAutoLoadStoreMsr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t idMsr, uint64_t uGuestMsrValue,
2291 bool fSetReadWrite, bool fUpdateHostMsr)
2292{
2293 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
2294 bool const fIsNstGstVmcs = pVmxTransient->fIsNestedGuest;
2295 PVMXAUTOMSR pGuestMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2296 uint32_t cMsrs = pVmcsInfo->cEntryMsrLoad;
2297 uint32_t i;
2298
2299 /* Paranoia. */
2300 Assert(pGuestMsrLoad);
2301
2302#ifndef DEBUG_bird
2303 LogFlowFunc(("pVCpu=%p idMsr=%#RX32 uGuestMsrValue=%#RX64\n", pVCpu, idMsr, uGuestMsrValue));
2304#endif
2305
2306 /* Check if the MSR already exists in the VM-entry MSR-load area. */
2307 for (i = 0; i < cMsrs; i++)
2308 {
2309 if (pGuestMsrLoad[i].u32Msr == idMsr)
2310 break;
2311 }
2312
2313 bool fAdded = false;
2314 if (i == cMsrs)
2315 {
2316 /* The MSR does not exist, bump the MSR count to make room for the new MSR. */
2317 ++cMsrs;
2318 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, pVmcsInfo, cMsrs);
2319 AssertMsgRCReturn(rc, ("Insufficient space to add MSR to VM-entry MSR-load/store area %u\n", idMsr), rc);
2320
2321 /* Set the guest to read/write this MSR without causing VM-exits. */
2322 if ( fSetReadWrite
2323 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
2324 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, fIsNstGstVmcs, idMsr, VMXMSRPM_ALLOW_RD_WR);
2325
2326 Log4Func(("Added MSR %#RX32, cMsrs=%u\n", idMsr, cMsrs));
2327 fAdded = true;
2328 }
2329
2330 /* Update the MSR value for the newly added or already existing MSR. */
2331 pGuestMsrLoad[i].u32Msr = idMsr;
2332 pGuestMsrLoad[i].u64Value = uGuestMsrValue;
2333
2334 /* Create the corresponding slot in the VM-exit MSR-store area if we use a different page. */
2335 if (hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo))
2336 {
2337 PVMXAUTOMSR pGuestMsrStore = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2338 pGuestMsrStore[i].u32Msr = idMsr;
2339 pGuestMsrStore[i].u64Value = uGuestMsrValue;
2340 }
2341
2342 /* Update the corresponding slot in the host MSR area. */
2343 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2344 Assert(pHostMsr != pVmcsInfo->pvGuestMsrLoad);
2345 Assert(pHostMsr != pVmcsInfo->pvGuestMsrStore);
2346 pHostMsr[i].u32Msr = idMsr;
2347
2348 /*
2349 * Only if the caller requests to update the host MSR value AND we've newly added the
2350 * MSR to the host MSR area do we actually update the value. Otherwise, it will be
2351 * updated by hmR0VmxUpdateAutoLoadHostMsrs().
2352 *
2353 * We do this for performance reasons since reading MSRs may be quite expensive.
2354 */
2355 if (fAdded)
2356 {
2357 if (fUpdateHostMsr)
2358 {
2359 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2360 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2361 pHostMsr[i].u64Value = ASMRdMsr(idMsr);
2362 }
2363 else
2364 {
2365 /* Someone else can do the work. */
2366 pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs = false;
2367 }
2368 }
2369 return VINF_SUCCESS;
2370}
2371
2372
2373/**
2374 * Removes a guest/host MSR pair to be swapped during the world-switch from the
2375 * auto-load/store MSR area in the VMCS.
2376 *
2377 * @returns VBox status code.
2378 * @param pVCpu The cross context virtual CPU structure.
2379 * @param pVmxTransient The VMX-transient structure.
2380 * @param idMsr The MSR.
2381 */
2382static int hmR0VmxRemoveAutoLoadStoreMsr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t idMsr)
2383{
2384 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
2385 bool const fIsNstGstVmcs = pVmxTransient->fIsNestedGuest;
2386 PVMXAUTOMSR pGuestMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2387 uint32_t cMsrs = pVmcsInfo->cEntryMsrLoad;
2388
2389#ifndef DEBUG_bird
2390 LogFlowFunc(("pVCpu=%p idMsr=%#RX32\n", pVCpu, idMsr));
2391#endif
2392
2393 for (uint32_t i = 0; i < cMsrs; i++)
2394 {
2395 /* Find the MSR. */
2396 if (pGuestMsrLoad[i].u32Msr == idMsr)
2397 {
2398 /*
2399 * If it's the last MSR, we only need to reduce the MSR count.
2400 * If it's -not- the last MSR, copy the last MSR in place of it and reduce the MSR count.
2401 */
2402 if (i < cMsrs - 1)
2403 {
2404 /* Remove it from the VM-entry MSR-load area. */
2405 pGuestMsrLoad[i].u32Msr = pGuestMsrLoad[cMsrs - 1].u32Msr;
2406 pGuestMsrLoad[i].u64Value = pGuestMsrLoad[cMsrs - 1].u64Value;
2407
2408 /* Remove it from the VM-exit MSR-store area if it's in a different page. */
2409 if (hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo))
2410 {
2411 PVMXAUTOMSR pGuestMsrStore = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2412 Assert(pGuestMsrStore[i].u32Msr == idMsr);
2413 pGuestMsrStore[i].u32Msr = pGuestMsrStore[cMsrs - 1].u32Msr;
2414 pGuestMsrStore[i].u64Value = pGuestMsrStore[cMsrs - 1].u64Value;
2415 }
2416
2417 /* Remove it from the VM-exit MSR-load area. */
2418 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2419 Assert(pHostMsr[i].u32Msr == idMsr);
2420 pHostMsr[i].u32Msr = pHostMsr[cMsrs - 1].u32Msr;
2421 pHostMsr[i].u64Value = pHostMsr[cMsrs - 1].u64Value;
2422 }
2423
2424 /* Reduce the count to reflect the removed MSR and bail. */
2425 --cMsrs;
2426 break;
2427 }
2428 }
2429
2430 /* Update the VMCS if the count changed (meaning the MSR was found and removed). */
2431 if (cMsrs != pVmcsInfo->cEntryMsrLoad)
2432 {
2433 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, pVmcsInfo, cMsrs);
2434 AssertRCReturn(rc, rc);
2435
2436 /* We're no longer swapping MSRs during the world-switch, intercept guest read/writes to them. */
2437 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
2438 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, fIsNstGstVmcs, idMsr, VMXMSRPM_EXIT_RD | VMXMSRPM_EXIT_WR);
2439
2440 Log4Func(("Removed MSR %#RX32, cMsrs=%u\n", idMsr, cMsrs));
2441 return VINF_SUCCESS;
2442 }
2443
2444 return VERR_NOT_FOUND;
2445}
2446
2447
2448/**
2449 * Checks if the specified guest MSR is part of the VM-entry MSR-load area.
2450 *
2451 * @returns @c true if found, @c false otherwise.
2452 * @param pVmcsInfo The VMCS info. object.
2453 * @param idMsr The MSR to find.
2454 */
2455static bool hmR0VmxIsAutoLoadGuestMsr(PCVMXVMCSINFO pVmcsInfo, uint32_t idMsr)
2456{
2457 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2458 uint32_t const cMsrs = pVmcsInfo->cEntryMsrLoad;
2459 Assert(pMsrs);
2460 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
2461 for (uint32_t i = 0; i < cMsrs; i++)
2462 {
2463 if (pMsrs[i].u32Msr == idMsr)
2464 return true;
2465 }
2466 return false;
2467}
2468
2469
2470/**
2471 * Updates the value of all host MSRs in the VM-exit MSR-load area.
2472 *
2473 * @param pVCpu The cross context virtual CPU structure.
2474 * @param pVmcsInfo The VMCS info. object.
2475 *
2476 * @remarks No-long-jump zone!!!
2477 */
2478static void hmR0VmxUpdateAutoLoadHostMsrs(PCVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2479{
2480 RT_NOREF(pVCpu);
2481 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2482
2483 PVMXAUTOMSR pHostMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2484 uint32_t const cMsrs = pVmcsInfo->cExitMsrLoad;
2485 Assert(pHostMsrLoad);
2486 Assert(sizeof(*pHostMsrLoad) * cMsrs <= X86_PAGE_4K_SIZE);
2487 LogFlowFunc(("pVCpu=%p cMsrs=%u\n", pVCpu, cMsrs));
2488 for (uint32_t i = 0; i < cMsrs; i++)
2489 {
2490 /*
2491 * Performance hack for the host EFER MSR. We use the cached value rather than re-read it.
2492 * Strict builds will catch mismatches in hmR0VmxCheckAutoLoadStoreMsrs(). See @bugref{7368}.
2493 */
2494 if (pHostMsrLoad[i].u32Msr == MSR_K6_EFER)
2495 pHostMsrLoad[i].u64Value = g_uHmVmxHostMsrEfer;
2496 else
2497 pHostMsrLoad[i].u64Value = ASMRdMsr(pHostMsrLoad[i].u32Msr);
2498 }
2499}
2500
2501
2502/**
2503 * Saves a set of host MSRs to allow read/write passthru access to the guest and
2504 * perform lazy restoration of the host MSRs while leaving VT-x.
2505 *
2506 * @param pVCpu The cross context virtual CPU structure.
2507 *
2508 * @remarks No-long-jump zone!!!
2509 */
2510static void hmR0VmxLazySaveHostMsrs(PVMCPUCC pVCpu)
2511{
2512 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2513
2514 /*
2515 * Note: If you're adding MSRs here, make sure to update the MSR-bitmap accesses in hmR0VmxSetupVmcsProcCtls().
2516 */
2517 if (!(pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST))
2518 {
2519 Assert(!(pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)); /* Guest MSRs better not be loaded now. */
2520 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.fAllow64BitGuests)
2521 {
2522 pVCpu->hmr0.s.vmx.u64HostMsrLStar = ASMRdMsr(MSR_K8_LSTAR);
2523 pVCpu->hmr0.s.vmx.u64HostMsrStar = ASMRdMsr(MSR_K6_STAR);
2524 pVCpu->hmr0.s.vmx.u64HostMsrSfMask = ASMRdMsr(MSR_K8_SF_MASK);
2525 pVCpu->hmr0.s.vmx.u64HostMsrKernelGsBase = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
2526 }
2527 pVCpu->hmr0.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_SAVED_HOST;
2528 }
2529}
2530
2531
2532/**
2533 * Checks whether the MSR belongs to the set of guest MSRs that we restore
2534 * lazily while leaving VT-x.
2535 *
2536 * @returns true if it does, false otherwise.
2537 * @param pVCpu The cross context virtual CPU structure.
2538 * @param idMsr The MSR to check.
2539 */
2540static bool hmR0VmxIsLazyGuestMsr(PCVMCPUCC pVCpu, uint32_t idMsr)
2541{
2542 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.fAllow64BitGuests)
2543 {
2544 switch (idMsr)
2545 {
2546 case MSR_K8_LSTAR:
2547 case MSR_K6_STAR:
2548 case MSR_K8_SF_MASK:
2549 case MSR_K8_KERNEL_GS_BASE:
2550 return true;
2551 }
2552 }
2553 return false;
2554}
2555
2556
2557/**
2558 * Loads a set of guests MSRs to allow read/passthru to the guest.
2559 *
2560 * The name of this function is slightly confusing. This function does NOT
2561 * postpone loading, but loads the MSR right now. "hmR0VmxLazy" is simply a
2562 * common prefix for functions dealing with "lazy restoration" of the shared
2563 * MSRs.
2564 *
2565 * @param pVCpu The cross context virtual CPU structure.
2566 *
2567 * @remarks No-long-jump zone!!!
2568 */
2569static void hmR0VmxLazyLoadGuestMsrs(PVMCPUCC pVCpu)
2570{
2571 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2572 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2573
2574 Assert(pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
2575 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.fAllow64BitGuests)
2576 {
2577 /*
2578 * If the guest MSRs are not loaded -and- if all the guest MSRs are identical
2579 * to the MSRs on the CPU (which are the saved host MSRs, see assertion above) then
2580 * we can skip a few MSR writes.
2581 *
2582 * Otherwise, it implies either 1. they're not loaded, or 2. they're loaded but the
2583 * guest MSR values in the guest-CPU context might be different to what's currently
2584 * loaded in the CPU. In either case, we need to write the new guest MSR values to the
2585 * CPU, see @bugref{8728}.
2586 */
2587 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2588 if ( !(pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
2589 && pCtx->msrKERNELGSBASE == pVCpu->hmr0.s.vmx.u64HostMsrKernelGsBase
2590 && pCtx->msrLSTAR == pVCpu->hmr0.s.vmx.u64HostMsrLStar
2591 && pCtx->msrSTAR == pVCpu->hmr0.s.vmx.u64HostMsrStar
2592 && pCtx->msrSFMASK == pVCpu->hmr0.s.vmx.u64HostMsrSfMask)
2593 {
2594#ifdef VBOX_STRICT
2595 Assert(ASMRdMsr(MSR_K8_KERNEL_GS_BASE) == pCtx->msrKERNELGSBASE);
2596 Assert(ASMRdMsr(MSR_K8_LSTAR) == pCtx->msrLSTAR);
2597 Assert(ASMRdMsr(MSR_K6_STAR) == pCtx->msrSTAR);
2598 Assert(ASMRdMsr(MSR_K8_SF_MASK) == pCtx->msrSFMASK);
2599#endif
2600 }
2601 else
2602 {
2603 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pCtx->msrKERNELGSBASE);
2604 ASMWrMsr(MSR_K8_LSTAR, pCtx->msrLSTAR);
2605 ASMWrMsr(MSR_K6_STAR, pCtx->msrSTAR);
2606 /* The system call flag mask register isn't as benign and accepting of all
2607 values as the above, so mask it to avoid #GP'ing on corrupted input. */
2608 Assert(!(pCtx->msrSFMASK & ~(uint64_t)UINT32_MAX));
2609 ASMWrMsr(MSR_K8_SF_MASK, pCtx->msrSFMASK & UINT32_MAX);
2610 }
2611 }
2612 pVCpu->hmr0.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_LOADED_GUEST;
2613}
2614
2615
2616/**
2617 * Performs lazy restoration of the set of host MSRs if they were previously
2618 * loaded with guest MSR values.
2619 *
2620 * @param pVCpu The cross context virtual CPU structure.
2621 *
2622 * @remarks No-long-jump zone!!!
2623 * @remarks The guest MSRs should have been saved back into the guest-CPU
2624 * context by hmR0VmxImportGuestState()!!!
2625 */
2626static void hmR0VmxLazyRestoreHostMsrs(PVMCPUCC pVCpu)
2627{
2628 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2629 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2630
2631 if (pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
2632 {
2633 Assert(pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
2634 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.fAllow64BitGuests)
2635 {
2636 ASMWrMsr(MSR_K8_LSTAR, pVCpu->hmr0.s.vmx.u64HostMsrLStar);
2637 ASMWrMsr(MSR_K6_STAR, pVCpu->hmr0.s.vmx.u64HostMsrStar);
2638 ASMWrMsr(MSR_K8_SF_MASK, pVCpu->hmr0.s.vmx.u64HostMsrSfMask);
2639 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pVCpu->hmr0.s.vmx.u64HostMsrKernelGsBase);
2640 }
2641 }
2642 pVCpu->hmr0.s.vmx.fLazyMsrs &= ~(VMX_LAZY_MSRS_LOADED_GUEST | VMX_LAZY_MSRS_SAVED_HOST);
2643}
2644
2645
2646/**
2647 * Verifies that our cached values of the VMCS fields are all consistent with
2648 * what's actually present in the VMCS.
2649 *
2650 * @returns VBox status code.
2651 * @retval VINF_SUCCESS if all our caches match their respective VMCS fields.
2652 * @retval VERR_VMX_VMCS_FIELD_CACHE_INVALID if a cache field doesn't match the
2653 * VMCS content. HMCPU error-field is
2654 * updated, see VMX_VCI_XXX.
2655 * @param pVCpu The cross context virtual CPU structure.
2656 * @param pVmcsInfo The VMCS info. object.
2657 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2658 */
2659static int hmR0VmxCheckCachedVmcsCtls(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
2660{
2661 const char * const pcszVmcs = fIsNstGstVmcs ? "Nested-guest VMCS" : "VMCS";
2662
2663 uint32_t u32Val;
2664 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
2665 AssertRC(rc);
2666 AssertMsgReturnStmt(pVmcsInfo->u32EntryCtls == u32Val,
2667 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32EntryCtls, u32Val),
2668 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_ENTRY,
2669 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2670
2671 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val);
2672 AssertRC(rc);
2673 AssertMsgReturnStmt(pVmcsInfo->u32ExitCtls == u32Val,
2674 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ExitCtls, u32Val),
2675 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_EXIT,
2676 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2677
2678 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val);
2679 AssertRC(rc);
2680 AssertMsgReturnStmt(pVmcsInfo->u32PinCtls == u32Val,
2681 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32PinCtls, u32Val),
2682 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PIN_EXEC,
2683 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2684
2685 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val);
2686 AssertRC(rc);
2687 AssertMsgReturnStmt(pVmcsInfo->u32ProcCtls == u32Val,
2688 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ProcCtls, u32Val),
2689 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PROC_EXEC,
2690 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2691
2692 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
2693 {
2694 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val);
2695 AssertRC(rc);
2696 AssertMsgReturnStmt(pVmcsInfo->u32ProcCtls2 == u32Val,
2697 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ProcCtls2, u32Val),
2698 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PROC_EXEC2,
2699 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2700 }
2701
2702 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, &u32Val);
2703 AssertRC(rc);
2704 AssertMsgReturnStmt(pVmcsInfo->u32XcptBitmap == u32Val,
2705 ("%s exception bitmap mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32XcptBitmap, u32Val),
2706 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_XCPT_BITMAP,
2707 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2708
2709 uint64_t u64Val;
2710 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, &u64Val);
2711 AssertRC(rc);
2712 AssertMsgReturnStmt(pVmcsInfo->u64TscOffset == u64Val,
2713 ("%s TSC offset mismatch: Cache=%#RX64 VMCS=%#RX64\n", pcszVmcs, pVmcsInfo->u64TscOffset, u64Val),
2714 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_TSC_OFFSET,
2715 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2716
2717 NOREF(pcszVmcs);
2718 return VINF_SUCCESS;
2719}
2720
2721#ifdef VBOX_STRICT
2722
2723/**
2724 * Verifies that our cached host EFER MSR value has not changed since we cached it.
2725 *
2726 * @param pVmcsInfo The VMCS info. object.
2727 */
2728static void hmR0VmxCheckHostEferMsr(PCVMXVMCSINFO pVmcsInfo)
2729{
2730 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2731
2732 if (pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_LOAD_EFER_MSR)
2733 {
2734 uint64_t const uHostEferMsr = ASMRdMsr(MSR_K6_EFER);
2735 uint64_t const uHostEferMsrCache = g_uHmVmxHostMsrEfer;
2736 uint64_t uVmcsEferMsrVmcs;
2737 int rc = VMXReadVmcs64(VMX_VMCS64_HOST_EFER_FULL, &uVmcsEferMsrVmcs);
2738 AssertRC(rc);
2739
2740 AssertMsgReturnVoid(uHostEferMsr == uVmcsEferMsrVmcs,
2741 ("EFER Host/VMCS mismatch! host=%#RX64 vmcs=%#RX64\n", uHostEferMsr, uVmcsEferMsrVmcs));
2742 AssertMsgReturnVoid(uHostEferMsr == uHostEferMsrCache,
2743 ("EFER Host/Cache mismatch! host=%#RX64 cache=%#RX64\n", uHostEferMsr, uHostEferMsrCache));
2744 }
2745}
2746
2747
2748/**
2749 * Verifies whether the guest/host MSR pairs in the auto-load/store area in the
2750 * VMCS are correct.
2751 *
2752 * @param pVCpu The cross context virtual CPU structure.
2753 * @param pVmcsInfo The VMCS info. object.
2754 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2755 */
2756static void hmR0VmxCheckAutoLoadStoreMsrs(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
2757{
2758 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2759
2760 /* Read the various MSR-area counts from the VMCS. */
2761 uint32_t cEntryLoadMsrs;
2762 uint32_t cExitStoreMsrs;
2763 uint32_t cExitLoadMsrs;
2764 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &cEntryLoadMsrs); AssertRC(rc);
2765 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &cExitStoreMsrs); AssertRC(rc);
2766 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &cExitLoadMsrs); AssertRC(rc);
2767
2768 /* Verify all the MSR counts are the same. */
2769 Assert(cEntryLoadMsrs == cExitStoreMsrs);
2770 Assert(cExitStoreMsrs == cExitLoadMsrs);
2771 uint32_t const cMsrs = cExitLoadMsrs;
2772
2773 /* Verify the MSR counts do not exceed the maximum count supported by the hardware. */
2774 Assert(cMsrs < VMX_MISC_MAX_MSRS(g_HmMsrs.u.vmx.u64Misc));
2775
2776 /* Verify the MSR counts are within the allocated page size. */
2777 Assert(sizeof(VMXAUTOMSR) * cMsrs <= X86_PAGE_4K_SIZE);
2778
2779 /* Verify the relevant contents of the MSR areas match. */
2780 PCVMXAUTOMSR pGuestMsrLoad = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2781 PCVMXAUTOMSR pGuestMsrStore = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2782 PCVMXAUTOMSR pHostMsrLoad = (PCVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2783 bool const fSeparateExitMsrStorePage = hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo);
2784 for (uint32_t i = 0; i < cMsrs; i++)
2785 {
2786 /* Verify that the MSRs are paired properly and that the host MSR has the correct value. */
2787 if (fSeparateExitMsrStorePage)
2788 {
2789 AssertMsgReturnVoid(pGuestMsrLoad->u32Msr == pGuestMsrStore->u32Msr,
2790 ("GuestMsrLoad=%#RX32 GuestMsrStore=%#RX32 cMsrs=%u\n",
2791 pGuestMsrLoad->u32Msr, pGuestMsrStore->u32Msr, cMsrs));
2792 }
2793
2794 AssertMsgReturnVoid(pHostMsrLoad->u32Msr == pGuestMsrLoad->u32Msr,
2795 ("HostMsrLoad=%#RX32 GuestMsrLoad=%#RX32 cMsrs=%u\n",
2796 pHostMsrLoad->u32Msr, pGuestMsrLoad->u32Msr, cMsrs));
2797
2798 uint64_t const u64HostMsr = ASMRdMsr(pHostMsrLoad->u32Msr);
2799 AssertMsgReturnVoid(pHostMsrLoad->u64Value == u64HostMsr,
2800 ("u32Msr=%#RX32 VMCS Value=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
2801 pHostMsrLoad->u32Msr, pHostMsrLoad->u64Value, u64HostMsr, cMsrs));
2802
2803 /* Verify that cached host EFER MSR matches what's loaded on the CPU. */
2804 bool const fIsEferMsr = RT_BOOL(pHostMsrLoad->u32Msr == MSR_K6_EFER);
2805 AssertMsgReturnVoid(!fIsEferMsr || u64HostMsr == g_uHmVmxHostMsrEfer,
2806 ("Cached=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n", g_uHmVmxHostMsrEfer, u64HostMsr, cMsrs));
2807
2808 /* Verify that the accesses are as expected in the MSR bitmap for auto-load/store MSRs. */
2809 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
2810 {
2811 uint32_t const fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, pGuestMsrLoad->u32Msr);
2812 if (fIsEferMsr)
2813 {
2814 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_EXIT_RD), ("Passthru read for EFER MSR!?\n"));
2815 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_EXIT_WR), ("Passthru write for EFER MSR!?\n"));
2816 }
2817 else
2818 {
2819 /* Verify LBR MSRs (used only for debugging) are intercepted. We don't passthru these MSRs to the guest yet. */
2820 PCVMCC pVM = pVCpu->CTX_SUFF(pVM);
2821 if ( pVM->hmr0.s.vmx.fLbr
2822 && ( hmR0VmxIsLbrBranchFromMsr(pVM, pGuestMsrLoad->u32Msr, NULL /* pidxMsr */)
2823 || hmR0VmxIsLbrBranchToMsr(pVM, pGuestMsrLoad->u32Msr, NULL /* pidxMsr */)
2824 || pGuestMsrLoad->u32Msr == pVM->hmr0.s.vmx.idLbrTosMsr))
2825 {
2826 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_MASK) == VMXMSRPM_EXIT_RD_WR,
2827 ("u32Msr=%#RX32 cMsrs=%u Passthru read/write for LBR MSRs!\n",
2828 pGuestMsrLoad->u32Msr, cMsrs));
2829 }
2830 else if (!fIsNstGstVmcs)
2831 {
2832 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_MASK) == VMXMSRPM_ALLOW_RD_WR,
2833 ("u32Msr=%#RX32 cMsrs=%u No passthru read/write!\n", pGuestMsrLoad->u32Msr, cMsrs));
2834 }
2835 else
2836 {
2837 /*
2838 * A nested-guest VMCS must -also- allow read/write passthrough for the MSR for us to
2839 * execute a nested-guest with MSR passthrough.
2840 *
2841 * Check if the nested-guest MSR bitmap allows passthrough, and if so, assert that we
2842 * allow passthrough too.
2843 */
2844 void const *pvMsrBitmapNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
2845 Assert(pvMsrBitmapNstGst);
2846 uint32_t const fMsrpmNstGst = CPUMGetVmxMsrPermission(pvMsrBitmapNstGst, pGuestMsrLoad->u32Msr);
2847 AssertMsgReturnVoid(fMsrpm == fMsrpmNstGst,
2848 ("u32Msr=%#RX32 cMsrs=%u Permission mismatch fMsrpm=%#x fMsrpmNstGst=%#x!\n",
2849 pGuestMsrLoad->u32Msr, cMsrs, fMsrpm, fMsrpmNstGst));
2850 }
2851 }
2852 }
2853
2854 /* Move to the next MSR. */
2855 pHostMsrLoad++;
2856 pGuestMsrLoad++;
2857 pGuestMsrStore++;
2858 }
2859}
2860
2861#endif /* VBOX_STRICT */
2862
2863/**
2864 * Flushes the TLB using EPT.
2865 *
2866 * @returns VBox status code.
2867 * @param pVCpu The cross context virtual CPU structure of the calling
2868 * EMT. Can be NULL depending on @a enmTlbFlush.
2869 * @param pVmcsInfo The VMCS info. object. Can be NULL depending on @a
2870 * enmTlbFlush.
2871 * @param enmTlbFlush Type of flush.
2872 *
2873 * @remarks Caller is responsible for making sure this function is called only
2874 * when NestedPaging is supported and providing @a enmTlbFlush that is
2875 * supported by the CPU.
2876 * @remarks Can be called with interrupts disabled.
2877 */
2878static void hmR0VmxFlushEpt(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, VMXTLBFLUSHEPT enmTlbFlush)
2879{
2880 uint64_t au64Descriptor[2];
2881 if (enmTlbFlush == VMXTLBFLUSHEPT_ALL_CONTEXTS)
2882 au64Descriptor[0] = 0;
2883 else
2884 {
2885 Assert(pVCpu);
2886 Assert(pVmcsInfo);
2887 au64Descriptor[0] = pVmcsInfo->HCPhysEPTP;
2888 }
2889 au64Descriptor[1] = 0; /* MBZ. Intel spec. 33.3 "VMX Instructions" */
2890
2891 int rc = VMXR0InvEPT(enmTlbFlush, &au64Descriptor[0]);
2892 AssertMsg(rc == VINF_SUCCESS, ("VMXR0InvEPT %#x %#RHp failed. rc=%Rrc\n", enmTlbFlush, au64Descriptor[0], rc));
2893
2894 if ( RT_SUCCESS(rc)
2895 && pVCpu)
2896 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushNestedPaging);
2897}
2898
2899
2900/**
2901 * Flushes the TLB using VPID.
2902 *
2903 * @returns VBox status code.
2904 * @param pVCpu The cross context virtual CPU structure of the calling
2905 * EMT. Can be NULL depending on @a enmTlbFlush.
2906 * @param enmTlbFlush Type of flush.
2907 * @param GCPtr Virtual address of the page to flush (can be 0 depending
2908 * on @a enmTlbFlush).
2909 *
2910 * @remarks Can be called with interrupts disabled.
2911 */
2912static void hmR0VmxFlushVpid(PVMCPUCC pVCpu, VMXTLBFLUSHVPID enmTlbFlush, RTGCPTR GCPtr)
2913{
2914 Assert(pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fVpid);
2915
2916 uint64_t au64Descriptor[2];
2917 if (enmTlbFlush == VMXTLBFLUSHVPID_ALL_CONTEXTS)
2918 {
2919 au64Descriptor[0] = 0;
2920 au64Descriptor[1] = 0;
2921 }
2922 else
2923 {
2924 AssertPtr(pVCpu);
2925 AssertMsg(pVCpu->hmr0.s.uCurrentAsid != 0, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hmr0.s.uCurrentAsid));
2926 AssertMsg(pVCpu->hmr0.s.uCurrentAsid <= UINT16_MAX, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hmr0.s.uCurrentAsid));
2927 au64Descriptor[0] = pVCpu->hmr0.s.uCurrentAsid;
2928 au64Descriptor[1] = GCPtr;
2929 }
2930
2931 int rc = VMXR0InvVPID(enmTlbFlush, &au64Descriptor[0]);
2932 AssertMsg(rc == VINF_SUCCESS,
2933 ("VMXR0InvVPID %#x %u %RGv failed with %Rrc\n", enmTlbFlush, pVCpu ? pVCpu->hmr0.s.uCurrentAsid : 0, GCPtr, rc));
2934
2935 if ( RT_SUCCESS(rc)
2936 && pVCpu)
2937 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
2938 NOREF(rc);
2939}
2940
2941
2942/**
2943 * Invalidates a guest page by guest virtual address. Only relevant for EPT/VPID,
2944 * otherwise there is nothing really to invalidate.
2945 *
2946 * @returns VBox status code.
2947 * @param pVCpu The cross context virtual CPU structure.
2948 * @param GCVirt Guest virtual address of the page to invalidate.
2949 */
2950VMMR0DECL(int) VMXR0InvalidatePage(PVMCPUCC pVCpu, RTGCPTR GCVirt)
2951{
2952 AssertPtr(pVCpu);
2953 LogFlowFunc(("pVCpu=%p GCVirt=%RGv\n", pVCpu, GCVirt));
2954
2955 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TLB_FLUSH))
2956 {
2957 /*
2958 * We must invalidate the guest TLB entry in either case, we cannot ignore it even for
2959 * the EPT case. See @bugref{6043} and @bugref{6177}.
2960 *
2961 * Set the VMCPU_FF_TLB_FLUSH force flag and flush before VM-entry in hmR0VmxFlushTLB*()
2962 * as this function maybe called in a loop with individual addresses.
2963 */
2964 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2965 if (pVM->hmr0.s.vmx.fVpid)
2966 {
2967 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
2968 {
2969 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_INDIV_ADDR, GCVirt);
2970 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
2971 }
2972 else
2973 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2974 }
2975 else if (pVM->hmr0.s.fNestedPaging)
2976 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2977 }
2978
2979 return VINF_SUCCESS;
2980}
2981
2982
2983/**
2984 * Dummy placeholder for tagged-TLB flush handling before VM-entry. Used in the
2985 * case where neither EPT nor VPID is supported by the CPU.
2986 *
2987 * @param pHostCpu The HM physical-CPU structure.
2988 * @param pVCpu The cross context virtual CPU structure.
2989 *
2990 * @remarks Called with interrupts disabled.
2991 */
2992static void hmR0VmxFlushTaggedTlbNone(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu)
2993{
2994 AssertPtr(pVCpu);
2995 AssertPtr(pHostCpu);
2996
2997 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2998
2999 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3000 pVCpu->hmr0.s.idLastCpu = pHostCpu->idCpu;
3001 pVCpu->hmr0.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3002 pVCpu->hmr0.s.fForceTLBFlush = false;
3003 return;
3004}
3005
3006
3007/**
3008 * Flushes the tagged-TLB entries for EPT+VPID CPUs as necessary.
3009 *
3010 * @param pHostCpu The HM physical-CPU structure.
3011 * @param pVCpu The cross context virtual CPU structure.
3012 * @param pVmcsInfo The VMCS info. object.
3013 *
3014 * @remarks All references to "ASID" in this function pertains to "VPID" in Intel's
3015 * nomenclature. The reason is, to avoid confusion in compare statements
3016 * since the host-CPU copies are named "ASID".
3017 *
3018 * @remarks Called with interrupts disabled.
3019 */
3020static void hmR0VmxFlushTaggedTlbBoth(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
3021{
3022#ifdef VBOX_WITH_STATISTICS
3023 bool fTlbFlushed = false;
3024# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { fTlbFlushed = true; } while (0)
3025# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { \
3026 if (!fTlbFlushed) \
3027 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch); \
3028 } while (0)
3029#else
3030# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { } while (0)
3031# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { } while (0)
3032#endif
3033
3034 AssertPtr(pVCpu);
3035 AssertPtr(pHostCpu);
3036 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3037
3038 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3039 AssertMsg(pVM->hmr0.s.fNestedPaging && pVM->hmr0.s.vmx.fVpid,
3040 ("hmR0VmxFlushTaggedTlbBoth cannot be invoked unless NestedPaging & VPID are enabled."
3041 "fNestedPaging=%RTbool fVpid=%RTbool", pVM->hmr0.s.fNestedPaging, pVM->hmr0.s.vmx.fVpid));
3042
3043 /*
3044 * Force a TLB flush for the first world-switch if the current CPU differs from the one we
3045 * ran on last. If the TLB flush count changed, another VM (VCPU rather) has hit the ASID
3046 * limit while flushing the TLB or the host CPU is online after a suspend/resume, so we
3047 * cannot reuse the current ASID anymore.
3048 */
3049 if ( pVCpu->hmr0.s.idLastCpu != pHostCpu->idCpu
3050 || pVCpu->hmr0.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3051 {
3052 ++pHostCpu->uCurrentAsid;
3053 if (pHostCpu->uCurrentAsid >= g_uHmMaxAsid)
3054 {
3055 pHostCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0. */
3056 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
3057 pHostCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
3058 }
3059
3060 pVCpu->hmr0.s.uCurrentAsid = pHostCpu->uCurrentAsid;
3061 pVCpu->hmr0.s.idLastCpu = pHostCpu->idCpu;
3062 pVCpu->hmr0.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3063
3064 /*
3065 * Flush by EPT when we get rescheduled to a new host CPU to ensure EPT-only tagged mappings are also
3066 * invalidated. We don't need to flush-by-VPID here as flushing by EPT covers it. See @bugref{6568}.
3067 */
3068 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hmr0.s.vmx.enmTlbFlushEpt);
3069 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3070 HMVMX_SET_TAGGED_TLB_FLUSHED();
3071 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
3072 }
3073 else if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH)) /* Check for explicit TLB flushes. */
3074 {
3075 /*
3076 * Changes to the EPT paging structure by VMM requires flushing-by-EPT as the CPU
3077 * creates guest-physical (ie. only EPT-tagged) mappings while traversing the EPT
3078 * tables when EPT is in use. Flushing-by-VPID will only flush linear (only
3079 * VPID-tagged) and combined (EPT+VPID tagged) mappings but not guest-physical
3080 * mappings, see @bugref{6568}.
3081 *
3082 * See Intel spec. 28.3.2 "Creating and Using Cached Translation Information".
3083 */
3084 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hmr0.s.vmx.enmTlbFlushEpt);
3085 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3086 HMVMX_SET_TAGGED_TLB_FLUSHED();
3087 }
3088 else if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3089 {
3090 /*
3091 * The nested-guest specifies its own guest-physical address to use as the APIC-access
3092 * address which requires flushing the TLB of EPT cached structures.
3093 *
3094 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
3095 */
3096 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hmr0.s.vmx.enmTlbFlushEpt);
3097 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3098 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3099 HMVMX_SET_TAGGED_TLB_FLUSHED();
3100 }
3101
3102
3103 pVCpu->hmr0.s.fForceTLBFlush = false;
3104 HMVMX_UPDATE_FLUSH_SKIPPED_STAT();
3105
3106 Assert(pVCpu->hmr0.s.idLastCpu == pHostCpu->idCpu);
3107 Assert(pVCpu->hmr0.s.cTlbFlushes == pHostCpu->cTlbFlushes);
3108 AssertMsg(pVCpu->hmr0.s.cTlbFlushes == pHostCpu->cTlbFlushes,
3109 ("Flush count mismatch for cpu %d (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hmr0.s.cTlbFlushes, pHostCpu->cTlbFlushes));
3110 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < g_uHmMaxAsid,
3111 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pHostCpu->idCpu,
3112 pHostCpu->uCurrentAsid, pHostCpu->cTlbFlushes, pVCpu->hmr0.s.idLastCpu, pVCpu->hmr0.s.cTlbFlushes));
3113 AssertMsg(pVCpu->hmr0.s.uCurrentAsid >= 1 && pVCpu->hmr0.s.uCurrentAsid < g_uHmMaxAsid,
3114 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pHostCpu->idCpu, pVCpu->hmr0.s.uCurrentAsid));
3115
3116 /* Update VMCS with the VPID. */
3117 int rc = VMXWriteVmcs16(VMX_VMCS16_VPID, pVCpu->hmr0.s.uCurrentAsid);
3118 AssertRC(rc);
3119
3120#undef HMVMX_SET_TAGGED_TLB_FLUSHED
3121}
3122
3123
3124/**
3125 * Flushes the tagged-TLB entries for EPT CPUs as necessary.
3126 *
3127 * @param pHostCpu The HM physical-CPU structure.
3128 * @param pVCpu The cross context virtual CPU structure.
3129 * @param pVmcsInfo The VMCS info. object.
3130 *
3131 * @remarks Called with interrupts disabled.
3132 */
3133static void hmR0VmxFlushTaggedTlbEpt(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
3134{
3135 AssertPtr(pVCpu);
3136 AssertPtr(pHostCpu);
3137 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3138 AssertMsg(pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked without NestedPaging."));
3139 AssertMsg(!pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fVpid, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with VPID."));
3140
3141 /*
3142 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
3143 * A change in the TLB flush count implies the host CPU is online after a suspend/resume.
3144 */
3145 if ( pVCpu->hmr0.s.idLastCpu != pHostCpu->idCpu
3146 || pVCpu->hmr0.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3147 {
3148 pVCpu->hmr0.s.fForceTLBFlush = true;
3149 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3150 }
3151
3152 /* Check for explicit TLB flushes. */
3153 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
3154 {
3155 pVCpu->hmr0.s.fForceTLBFlush = true;
3156 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3157 }
3158
3159 /* Check for TLB flushes while switching to/from a nested-guest. */
3160 if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3161 {
3162 pVCpu->hmr0.s.fForceTLBFlush = true;
3163 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3164 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3165 }
3166
3167 pVCpu->hmr0.s.idLastCpu = pHostCpu->idCpu;
3168 pVCpu->hmr0.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3169
3170 if (pVCpu->hmr0.s.fForceTLBFlush)
3171 {
3172 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.enmTlbFlushEpt);
3173 pVCpu->hmr0.s.fForceTLBFlush = false;
3174 }
3175}
3176
3177
3178/**
3179 * Flushes the tagged-TLB entries for VPID CPUs as necessary.
3180 *
3181 * @param pHostCpu The HM physical-CPU structure.
3182 * @param pVCpu The cross context virtual CPU structure.
3183 *
3184 * @remarks Called with interrupts disabled.
3185 */
3186static void hmR0VmxFlushTaggedTlbVpid(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu)
3187{
3188 AssertPtr(pVCpu);
3189 AssertPtr(pHostCpu);
3190 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3191 AssertMsg(pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fVpid, ("hmR0VmxFlushTlbVpid cannot be invoked without VPID."));
3192 AssertMsg(!pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging, ("hmR0VmxFlushTlbVpid cannot be invoked with NestedPaging"));
3193
3194 /*
3195 * Force a TLB flush for the first world switch if the current CPU differs from the one we
3196 * ran on last. If the TLB flush count changed, another VM (VCPU rather) has hit the ASID
3197 * limit while flushing the TLB or the host CPU is online after a suspend/resume, so we
3198 * cannot reuse the current ASID anymore.
3199 */
3200 if ( pVCpu->hmr0.s.idLastCpu != pHostCpu->idCpu
3201 || pVCpu->hmr0.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3202 {
3203 pVCpu->hmr0.s.fForceTLBFlush = true;
3204 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3205 }
3206
3207 /* Check for explicit TLB flushes. */
3208 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
3209 {
3210 /*
3211 * If we ever support VPID flush combinations other than ALL or SINGLE-context (see
3212 * hmR0VmxSetupTaggedTlb()) we would need to explicitly flush in this case (add an
3213 * fExplicitFlush = true here and change the pHostCpu->fFlushAsidBeforeUse check below to
3214 * include fExplicitFlush's too) - an obscure corner case.
3215 */
3216 pVCpu->hmr0.s.fForceTLBFlush = true;
3217 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3218 }
3219
3220 /* Check for TLB flushes while switching to/from a nested-guest. */
3221 if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3222 {
3223 pVCpu->hmr0.s.fForceTLBFlush = true;
3224 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3225 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3226 }
3227
3228 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3229 pVCpu->hmr0.s.idLastCpu = pHostCpu->idCpu;
3230 if (pVCpu->hmr0.s.fForceTLBFlush)
3231 {
3232 ++pHostCpu->uCurrentAsid;
3233 if (pHostCpu->uCurrentAsid >= g_uHmMaxAsid)
3234 {
3235 pHostCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0 */
3236 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
3237 pHostCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
3238 }
3239
3240 pVCpu->hmr0.s.fForceTLBFlush = false;
3241 pVCpu->hmr0.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3242 pVCpu->hmr0.s.uCurrentAsid = pHostCpu->uCurrentAsid;
3243 if (pHostCpu->fFlushAsidBeforeUse)
3244 {
3245 if (pVM->hmr0.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT)
3246 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_SINGLE_CONTEXT, 0 /* GCPtr */);
3247 else if (pVM->hmr0.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_ALL_CONTEXTS)
3248 {
3249 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_ALL_CONTEXTS, 0 /* GCPtr */);
3250 pHostCpu->fFlushAsidBeforeUse = false;
3251 }
3252 else
3253 {
3254 /* hmR0VmxSetupTaggedTlb() ensures we never get here. Paranoia. */
3255 AssertMsgFailed(("Unsupported VPID-flush context type.\n"));
3256 }
3257 }
3258 }
3259
3260 AssertMsg(pVCpu->hmr0.s.cTlbFlushes == pHostCpu->cTlbFlushes,
3261 ("Flush count mismatch for cpu %d (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hmr0.s.cTlbFlushes, pHostCpu->cTlbFlushes));
3262 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < g_uHmMaxAsid,
3263 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pHostCpu->idCpu,
3264 pHostCpu->uCurrentAsid, pHostCpu->cTlbFlushes, pVCpu->hmr0.s.idLastCpu, pVCpu->hmr0.s.cTlbFlushes));
3265 AssertMsg(pVCpu->hmr0.s.uCurrentAsid >= 1 && pVCpu->hmr0.s.uCurrentAsid < g_uHmMaxAsid,
3266 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pHostCpu->idCpu, pVCpu->hmr0.s.uCurrentAsid));
3267
3268 int rc = VMXWriteVmcs16(VMX_VMCS16_VPID, pVCpu->hmr0.s.uCurrentAsid);
3269 AssertRC(rc);
3270}
3271
3272
3273/**
3274 * Flushes the guest TLB entry based on CPU capabilities.
3275 *
3276 * @param pHostCpu The HM physical-CPU structure.
3277 * @param pVCpu The cross context virtual CPU structure.
3278 * @param pVmcsInfo The VMCS info. object.
3279 *
3280 * @remarks Called with interrupts disabled.
3281 */
3282static void hmR0VmxFlushTaggedTlb(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3283{
3284#ifdef HMVMX_ALWAYS_FLUSH_TLB
3285 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3286#endif
3287 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3288 switch (pVM->hmr0.s.vmx.enmTlbFlushType)
3289 {
3290 case VMXTLBFLUSHTYPE_EPT_VPID: hmR0VmxFlushTaggedTlbBoth(pHostCpu, pVCpu, pVmcsInfo); break;
3291 case VMXTLBFLUSHTYPE_EPT: hmR0VmxFlushTaggedTlbEpt(pHostCpu, pVCpu, pVmcsInfo); break;
3292 case VMXTLBFLUSHTYPE_VPID: hmR0VmxFlushTaggedTlbVpid(pHostCpu, pVCpu); break;
3293 case VMXTLBFLUSHTYPE_NONE: hmR0VmxFlushTaggedTlbNone(pHostCpu, pVCpu); break;
3294 default:
3295 AssertMsgFailed(("Invalid flush-tag function identifier\n"));
3296 break;
3297 }
3298 /* Don't assert that VMCPU_FF_TLB_FLUSH should no longer be pending. It can be set by other EMTs. */
3299}
3300
3301
3302/**
3303 * Sets up the appropriate tagged TLB-flush level and handler for flushing guest
3304 * TLB entries from the host TLB before VM-entry.
3305 *
3306 * @returns VBox status code.
3307 * @param pVM The cross context VM structure.
3308 */
3309static int hmR0VmxSetupTaggedTlb(PVMCC pVM)
3310{
3311 /*
3312 * Determine optimal flush type for nested paging.
3313 * We cannot ignore EPT if no suitable flush-types is supported by the CPU as we've already setup
3314 * unrestricted guest execution (see hmR3InitFinalizeR0()).
3315 */
3316 if (pVM->hmr0.s.fNestedPaging)
3317 {
3318 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT)
3319 {
3320 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT)
3321 pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_SINGLE_CONTEXT;
3322 else if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
3323 pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_ALL_CONTEXTS;
3324 else
3325 {
3326 /* Shouldn't happen. EPT is supported but no suitable flush-types supported. */
3327 pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3328 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_FLUSH_TYPE_UNSUPPORTED;
3329 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3330 }
3331
3332 /* Make sure the write-back cacheable memory type for EPT is supported. */
3333 if (RT_UNLIKELY(!(g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB)))
3334 {
3335 pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3336 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_MEM_TYPE_NOT_WB;
3337 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3338 }
3339
3340 /* EPT requires a page-walk length of 4. */
3341 if (RT_UNLIKELY(!(g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4)))
3342 {
3343 pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3344 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_PAGE_WALK_LENGTH_UNSUPPORTED;
3345 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3346 }
3347 }
3348 else
3349 {
3350 /* Shouldn't happen. EPT is supported but INVEPT instruction is not supported. */
3351 pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3352 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_INVEPT_UNAVAILABLE;
3353 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3354 }
3355 }
3356
3357 /*
3358 * Determine optimal flush type for VPID.
3359 */
3360 if (pVM->hmr0.s.vmx.fVpid)
3361 {
3362 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID)
3363 {
3364 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT)
3365 pVM->hmr0.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_SINGLE_CONTEXT;
3366 else if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS)
3367 pVM->hmr0.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_ALL_CONTEXTS;
3368 else
3369 {
3370 /* Neither SINGLE nor ALL-context flush types for VPID is supported by the CPU. Ignore VPID capability. */
3371 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
3372 LogRelFunc(("Only INDIV_ADDR supported. Ignoring VPID.\n"));
3373 if (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
3374 LogRelFunc(("Only SINGLE_CONTEXT_RETAIN_GLOBALS supported. Ignoring VPID.\n"));
3375 pVM->hmr0.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NOT_SUPPORTED;
3376 pVM->hmr0.s.vmx.fVpid = false;
3377 }
3378 }
3379 else
3380 {
3381 /* Shouldn't happen. VPID is supported but INVVPID is not supported by the CPU. Ignore VPID capability. */
3382 Log4Func(("VPID supported without INVEPT support. Ignoring VPID.\n"));
3383 pVM->hmr0.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NOT_SUPPORTED;
3384 pVM->hmr0.s.vmx.fVpid = false;
3385 }
3386 }
3387
3388 /*
3389 * Setup the handler for flushing tagged-TLBs.
3390 */
3391 if (pVM->hmr0.s.fNestedPaging && pVM->hmr0.s.vmx.fVpid)
3392 pVM->hmr0.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_EPT_VPID;
3393 else if (pVM->hmr0.s.fNestedPaging)
3394 pVM->hmr0.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_EPT;
3395 else if (pVM->hmr0.s.vmx.fVpid)
3396 pVM->hmr0.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_VPID;
3397 else
3398 pVM->hmr0.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_NONE;
3399
3400
3401 /*
3402 * Copy out the result to ring-3.
3403 */
3404 pVM->hm.s.ForR3.vmx.fVpid = pVM->hmr0.s.vmx.fVpid;
3405 pVM->hm.s.ForR3.vmx.enmTlbFlushType = pVM->hmr0.s.vmx.enmTlbFlushType;
3406 pVM->hm.s.ForR3.vmx.enmTlbFlushEpt = pVM->hmr0.s.vmx.enmTlbFlushEpt;
3407 pVM->hm.s.ForR3.vmx.enmTlbFlushVpid = pVM->hmr0.s.vmx.enmTlbFlushVpid;
3408 return VINF_SUCCESS;
3409}
3410
3411
3412/**
3413 * Sets up the LBR MSR ranges based on the host CPU.
3414 *
3415 * @returns VBox status code.
3416 * @param pVM The cross context VM structure.
3417 */
3418static int hmR0VmxSetupLbrMsrRange(PVMCC pVM)
3419{
3420 Assert(pVM->hmr0.s.vmx.fLbr);
3421 uint32_t idLbrFromIpMsrFirst;
3422 uint32_t idLbrFromIpMsrLast;
3423 uint32_t idLbrToIpMsrFirst;
3424 uint32_t idLbrToIpMsrLast;
3425 uint32_t idLbrTosMsr;
3426
3427 /*
3428 * Determine the LBR MSRs supported for this host CPU family and model.
3429 *
3430 * See Intel spec. 17.4.8 "LBR Stack".
3431 * See Intel "Model-Specific Registers" spec.
3432 */
3433 uint32_t const uFamilyModel = (pVM->cpum.ro.HostFeatures.uFamily << 8)
3434 | pVM->cpum.ro.HostFeatures.uModel;
3435 switch (uFamilyModel)
3436 {
3437 case 0x0f01: case 0x0f02:
3438 idLbrFromIpMsrFirst = MSR_P4_LASTBRANCH_0;
3439 idLbrFromIpMsrLast = MSR_P4_LASTBRANCH_3;
3440 idLbrToIpMsrFirst = 0x0;
3441 idLbrToIpMsrLast = 0x0;
3442 idLbrTosMsr = MSR_P4_LASTBRANCH_TOS;
3443 break;
3444
3445 case 0x065c: case 0x065f: case 0x064e: case 0x065e: case 0x068e:
3446 case 0x069e: case 0x0655: case 0x0666: case 0x067a: case 0x0667:
3447 case 0x066a: case 0x066c: case 0x067d: case 0x067e:
3448 idLbrFromIpMsrFirst = MSR_LASTBRANCH_0_FROM_IP;
3449 idLbrFromIpMsrLast = MSR_LASTBRANCH_31_FROM_IP;
3450 idLbrToIpMsrFirst = MSR_LASTBRANCH_0_TO_IP;
3451 idLbrToIpMsrLast = MSR_LASTBRANCH_31_TO_IP;
3452 idLbrTosMsr = MSR_LASTBRANCH_TOS;
3453 break;
3454
3455 case 0x063d: case 0x0647: case 0x064f: case 0x0656: case 0x063c:
3456 case 0x0645: case 0x0646: case 0x063f: case 0x062a: case 0x062d:
3457 case 0x063a: case 0x063e: case 0x061a: case 0x061e: case 0x061f:
3458 case 0x062e: case 0x0625: case 0x062c: case 0x062f:
3459 idLbrFromIpMsrFirst = MSR_LASTBRANCH_0_FROM_IP;
3460 idLbrFromIpMsrLast = MSR_LASTBRANCH_15_FROM_IP;
3461 idLbrToIpMsrFirst = MSR_LASTBRANCH_0_TO_IP;
3462 idLbrToIpMsrLast = MSR_LASTBRANCH_15_TO_IP;
3463 idLbrTosMsr = MSR_LASTBRANCH_TOS;
3464 break;
3465
3466 case 0x0617: case 0x061d: case 0x060f:
3467 idLbrFromIpMsrFirst = MSR_CORE2_LASTBRANCH_0_FROM_IP;
3468 idLbrFromIpMsrLast = MSR_CORE2_LASTBRANCH_3_FROM_IP;
3469 idLbrToIpMsrFirst = MSR_CORE2_LASTBRANCH_0_TO_IP;
3470 idLbrToIpMsrLast = MSR_CORE2_LASTBRANCH_3_TO_IP;
3471 idLbrTosMsr = MSR_CORE2_LASTBRANCH_TOS;
3472 break;
3473
3474 /* Atom and related microarchitectures we don't care about:
3475 case 0x0637: case 0x064a: case 0x064c: case 0x064d: case 0x065a:
3476 case 0x065d: case 0x061c: case 0x0626: case 0x0627: case 0x0635:
3477 case 0x0636: */
3478 /* All other CPUs: */
3479 default:
3480 {
3481 LogRelFunc(("Could not determine LBR stack size for the CPU model %#x\n", uFamilyModel));
3482 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_LBR_STACK_SIZE_UNKNOWN;
3483 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3484 }
3485 }
3486
3487 /*
3488 * Validate.
3489 */
3490 uint32_t const cLbrStack = idLbrFromIpMsrLast - idLbrFromIpMsrFirst + 1;
3491 PCVMCPU pVCpu0 = VMCC_GET_CPU_0(pVM);
3492 AssertCompile( RT_ELEMENTS(pVCpu0->hm.s.vmx.VmcsInfo.au64LbrFromIpMsr)
3493 == RT_ELEMENTS(pVCpu0->hm.s.vmx.VmcsInfo.au64LbrToIpMsr));
3494 if (cLbrStack > RT_ELEMENTS(pVCpu0->hm.s.vmx.VmcsInfo.au64LbrFromIpMsr))
3495 {
3496 LogRelFunc(("LBR stack size of the CPU (%u) exceeds our buffer size\n", cLbrStack));
3497 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_LBR_STACK_SIZE_OVERFLOW;
3498 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3499 }
3500 NOREF(pVCpu0);
3501
3502 /*
3503 * Update the LBR info. to the VM struct. for use later.
3504 */
3505 pVM->hmr0.s.vmx.idLbrTosMsr = idLbrTosMsr;
3506
3507 pVM->hm.s.ForR3.vmx.idLbrFromIpMsrFirst = pVM->hmr0.s.vmx.idLbrFromIpMsrFirst = idLbrFromIpMsrFirst;
3508 pVM->hm.s.ForR3.vmx.idLbrFromIpMsrLast = pVM->hmr0.s.vmx.idLbrFromIpMsrLast = idLbrFromIpMsrLast;
3509
3510 pVM->hm.s.ForR3.vmx.idLbrToIpMsrFirst = pVM->hmr0.s.vmx.idLbrToIpMsrFirst = idLbrToIpMsrFirst;
3511 pVM->hm.s.ForR3.vmx.idLbrToIpMsrLast = pVM->hmr0.s.vmx.idLbrToIpMsrLast = idLbrToIpMsrLast;
3512 return VINF_SUCCESS;
3513}
3514
3515
3516#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3517/**
3518 * Sets up the shadow VMCS fields arrays.
3519 *
3520 * This function builds arrays of VMCS fields to sync the shadow VMCS later while
3521 * executing the guest.
3522 *
3523 * @returns VBox status code.
3524 * @param pVM The cross context VM structure.
3525 */
3526static int hmR0VmxSetupShadowVmcsFieldsArrays(PVMCC pVM)
3527{
3528 /*
3529 * Paranoia. Ensure we haven't exposed the VMWRITE-All VMX feature to the guest
3530 * when the host does not support it.
3531 */
3532 bool const fGstVmwriteAll = pVM->cpum.ro.GuestFeatures.fVmxVmwriteAll;
3533 if ( !fGstVmwriteAll
3534 || (g_HmMsrs.u.vmx.u64Misc & VMX_MISC_VMWRITE_ALL))
3535 { /* likely. */ }
3536 else
3537 {
3538 LogRelFunc(("VMX VMWRITE-All feature exposed to the guest but host CPU does not support it!\n"));
3539 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_GST_HOST_VMWRITE_ALL;
3540 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3541 }
3542
3543 uint32_t const cVmcsFields = RT_ELEMENTS(g_aVmcsFields);
3544 uint32_t cRwFields = 0;
3545 uint32_t cRoFields = 0;
3546 for (uint32_t i = 0; i < cVmcsFields; i++)
3547 {
3548 VMXVMCSFIELD VmcsField;
3549 VmcsField.u = g_aVmcsFields[i];
3550
3551 /*
3552 * We will be writing "FULL" (64-bit) fields while syncing the shadow VMCS.
3553 * Therefore, "HIGH" (32-bit portion of 64-bit) fields must not be included
3554 * in the shadow VMCS fields array as they would be redundant.
3555 *
3556 * If the VMCS field depends on a CPU feature that is not exposed to the guest,
3557 * we must not include it in the shadow VMCS fields array. Guests attempting to
3558 * VMREAD/VMWRITE such VMCS fields would cause a VM-exit and we shall emulate
3559 * the required behavior.
3560 */
3561 if ( VmcsField.n.fAccessType == VMX_VMCSFIELD_ACCESS_FULL
3562 && CPUMIsGuestVmxVmcsFieldValid(pVM, VmcsField.u))
3563 {
3564 /*
3565 * Read-only fields are placed in a separate array so that while syncing shadow
3566 * VMCS fields later (which is more performance critical) we can avoid branches.
3567 *
3568 * However, if the guest can write to all fields (including read-only fields),
3569 * we treat it a as read/write field. Otherwise, writing to these fields would
3570 * cause a VMWRITE instruction error while syncing the shadow VMCS.
3571 */
3572 if ( fGstVmwriteAll
3573 || !VMXIsVmcsFieldReadOnly(VmcsField.u))
3574 pVM->hmr0.s.vmx.paShadowVmcsFields[cRwFields++] = VmcsField.u;
3575 else
3576 pVM->hmr0.s.vmx.paShadowVmcsRoFields[cRoFields++] = VmcsField.u;
3577 }
3578 }
3579
3580 /* Update the counts. */
3581 pVM->hmr0.s.vmx.cShadowVmcsFields = cRwFields;
3582 pVM->hmr0.s.vmx.cShadowVmcsRoFields = cRoFields;
3583 return VINF_SUCCESS;
3584}
3585
3586
3587/**
3588 * Sets up the VMREAD and VMWRITE bitmaps.
3589 *
3590 * @param pVM The cross context VM structure.
3591 */
3592static void hmR0VmxSetupVmreadVmwriteBitmaps(PVMCC pVM)
3593{
3594 /*
3595 * By default, ensure guest attempts to access any VMCS fields cause VM-exits.
3596 */
3597 uint32_t const cbBitmap = X86_PAGE_4K_SIZE;
3598 uint8_t *pbVmreadBitmap = (uint8_t *)pVM->hmr0.s.vmx.pvVmreadBitmap;
3599 uint8_t *pbVmwriteBitmap = (uint8_t *)pVM->hmr0.s.vmx.pvVmwriteBitmap;
3600 ASMMemFill32(pbVmreadBitmap, cbBitmap, UINT32_C(0xffffffff));
3601 ASMMemFill32(pbVmwriteBitmap, cbBitmap, UINT32_C(0xffffffff));
3602
3603 /*
3604 * Skip intercepting VMREAD/VMWRITE to guest read/write fields in the
3605 * VMREAD and VMWRITE bitmaps.
3606 */
3607 {
3608 uint32_t const *paShadowVmcsFields = pVM->hmr0.s.vmx.paShadowVmcsFields;
3609 uint32_t const cShadowVmcsFields = pVM->hmr0.s.vmx.cShadowVmcsFields;
3610 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
3611 {
3612 uint32_t const uVmcsField = paShadowVmcsFields[i];
3613 Assert(!(uVmcsField & VMX_VMCSFIELD_RSVD_MASK));
3614 Assert(uVmcsField >> 3 < cbBitmap);
3615 ASMBitClear(pbVmreadBitmap + (uVmcsField >> 3), uVmcsField & 7);
3616 ASMBitClear(pbVmwriteBitmap + (uVmcsField >> 3), uVmcsField & 7);
3617 }
3618 }
3619
3620 /*
3621 * Skip intercepting VMREAD for guest read-only fields in the VMREAD bitmap
3622 * if the host supports VMWRITE to all supported VMCS fields.
3623 */
3624 if (g_HmMsrs.u.vmx.u64Misc & VMX_MISC_VMWRITE_ALL)
3625 {
3626 uint32_t const *paShadowVmcsRoFields = pVM->hmr0.s.vmx.paShadowVmcsRoFields;
3627 uint32_t const cShadowVmcsRoFields = pVM->hmr0.s.vmx.cShadowVmcsRoFields;
3628 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
3629 {
3630 uint32_t const uVmcsField = paShadowVmcsRoFields[i];
3631 Assert(!(uVmcsField & VMX_VMCSFIELD_RSVD_MASK));
3632 Assert(uVmcsField >> 3 < cbBitmap);
3633 ASMBitClear(pbVmreadBitmap + (uVmcsField >> 3), uVmcsField & 7);
3634 }
3635 }
3636}
3637#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
3638
3639
3640/**
3641 * Sets up the virtual-APIC page address for the VMCS.
3642 *
3643 * @param pVmcsInfo The VMCS info. object.
3644 */
3645DECLINLINE(void) hmR0VmxSetupVmcsVirtApicAddr(PCVMXVMCSINFO pVmcsInfo)
3646{
3647 RTHCPHYS const HCPhysVirtApic = pVmcsInfo->HCPhysVirtApic;
3648 Assert(HCPhysVirtApic != NIL_RTHCPHYS);
3649 Assert(!(HCPhysVirtApic & 0xfff)); /* Bits 11:0 MBZ. */
3650 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
3651 AssertRC(rc);
3652}
3653
3654
3655/**
3656 * Sets up the MSR-bitmap address for the VMCS.
3657 *
3658 * @param pVmcsInfo The VMCS info. object.
3659 */
3660DECLINLINE(void) hmR0VmxSetupVmcsMsrBitmapAddr(PCVMXVMCSINFO pVmcsInfo)
3661{
3662 RTHCPHYS const HCPhysMsrBitmap = pVmcsInfo->HCPhysMsrBitmap;
3663 Assert(HCPhysMsrBitmap != NIL_RTHCPHYS);
3664 Assert(!(HCPhysMsrBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3665 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_MSR_BITMAP_FULL, HCPhysMsrBitmap);
3666 AssertRC(rc);
3667}
3668
3669
3670/**
3671 * Sets up the APIC-access page address for the VMCS.
3672 *
3673 * @param pVCpu The cross context virtual CPU structure.
3674 */
3675DECLINLINE(void) hmR0VmxSetupVmcsApicAccessAddr(PVMCPUCC pVCpu)
3676{
3677 RTHCPHYS const HCPhysApicAccess = pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.HCPhysApicAccess;
3678 Assert(HCPhysApicAccess != NIL_RTHCPHYS);
3679 Assert(!(HCPhysApicAccess & 0xfff)); /* Bits 11:0 MBZ. */
3680 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
3681 AssertRC(rc);
3682}
3683
3684#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3685
3686/**
3687 * Sets up the VMREAD bitmap address for the VMCS.
3688 *
3689 * @param pVCpu The cross context virtual CPU structure.
3690 */
3691DECLINLINE(void) hmR0VmxSetupVmcsVmreadBitmapAddr(PVMCPUCC pVCpu)
3692{
3693 RTHCPHYS const HCPhysVmreadBitmap = pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.HCPhysVmreadBitmap;
3694 Assert(HCPhysVmreadBitmap != NIL_RTHCPHYS);
3695 Assert(!(HCPhysVmreadBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3696 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VMREAD_BITMAP_FULL, HCPhysVmreadBitmap);
3697 AssertRC(rc);
3698}
3699
3700
3701/**
3702 * Sets up the VMWRITE bitmap address for the VMCS.
3703 *
3704 * @param pVCpu The cross context virtual CPU structure.
3705 */
3706DECLINLINE(void) hmR0VmxSetupVmcsVmwriteBitmapAddr(PVMCPUCC pVCpu)
3707{
3708 RTHCPHYS const HCPhysVmwriteBitmap = pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.HCPhysVmwriteBitmap;
3709 Assert(HCPhysVmwriteBitmap != NIL_RTHCPHYS);
3710 Assert(!(HCPhysVmwriteBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3711 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VMWRITE_BITMAP_FULL, HCPhysVmwriteBitmap);
3712 AssertRC(rc);
3713}
3714
3715#endif
3716
3717/**
3718 * Sets up the VM-entry MSR load, VM-exit MSR-store and VM-exit MSR-load addresses
3719 * in the VMCS.
3720 *
3721 * @returns VBox status code.
3722 * @param pVmcsInfo The VMCS info. object.
3723 */
3724DECLINLINE(int) hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(PVMXVMCSINFO pVmcsInfo)
3725{
3726 RTHCPHYS const HCPhysGuestMsrLoad = pVmcsInfo->HCPhysGuestMsrLoad;
3727 Assert(HCPhysGuestMsrLoad != NIL_RTHCPHYS);
3728 Assert(!(HCPhysGuestMsrLoad & 0xf)); /* Bits 3:0 MBZ. */
3729
3730 RTHCPHYS const HCPhysGuestMsrStore = pVmcsInfo->HCPhysGuestMsrStore;
3731 Assert(HCPhysGuestMsrStore != NIL_RTHCPHYS);
3732 Assert(!(HCPhysGuestMsrStore & 0xf)); /* Bits 3:0 MBZ. */
3733
3734 RTHCPHYS const HCPhysHostMsrLoad = pVmcsInfo->HCPhysHostMsrLoad;
3735 Assert(HCPhysHostMsrLoad != NIL_RTHCPHYS);
3736 Assert(!(HCPhysHostMsrLoad & 0xf)); /* Bits 3:0 MBZ. */
3737
3738 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL, HCPhysGuestMsrLoad); AssertRC(rc);
3739 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL, HCPhysGuestMsrStore); AssertRC(rc);
3740 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL, HCPhysHostMsrLoad); AssertRC(rc);
3741 return VINF_SUCCESS;
3742}
3743
3744
3745/**
3746 * Sets up MSR permissions in the MSR bitmap of a VMCS info. object.
3747 *
3748 * @param pVCpu The cross context virtual CPU structure.
3749 * @param pVmcsInfo The VMCS info. object.
3750 */
3751static void hmR0VmxSetupVmcsMsrPermissions(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3752{
3753 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS);
3754
3755 /*
3756 * By default, ensure guest attempts to access any MSR cause VM-exits.
3757 * This shall later be relaxed for specific MSRs as necessary.
3758 *
3759 * Note: For nested-guests, the entire bitmap will be merged prior to
3760 * executing the nested-guest using hardware-assisted VMX and hence there
3761 * is no need to perform this operation. See hmR0VmxMergeMsrBitmapNested.
3762 */
3763 Assert(pVmcsInfo->pvMsrBitmap);
3764 ASMMemFill32(pVmcsInfo->pvMsrBitmap, X86_PAGE_4K_SIZE, UINT32_C(0xffffffff));
3765
3766 /*
3767 * The guest can access the following MSRs (read, write) without causing
3768 * VM-exits; they are loaded/stored automatically using fields in the VMCS.
3769 */
3770 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3771 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_CS, VMXMSRPM_ALLOW_RD_WR);
3772 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_ESP, VMXMSRPM_ALLOW_RD_WR);
3773 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_EIP, VMXMSRPM_ALLOW_RD_WR);
3774 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_GS_BASE, VMXMSRPM_ALLOW_RD_WR);
3775 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_FS_BASE, VMXMSRPM_ALLOW_RD_WR);
3776
3777 /*
3778 * The IA32_PRED_CMD and IA32_FLUSH_CMD MSRs are write-only and has no state
3779 * associated with then. We never need to intercept access (writes need to be
3780 * executed without causing a VM-exit, reads will #GP fault anyway).
3781 *
3782 * The IA32_SPEC_CTRL MSR is read/write and has state. We allow the guest to
3783 * read/write them. We swap the guest/host MSR value using the
3784 * auto-load/store MSR area.
3785 */
3786 if (pVM->cpum.ro.GuestFeatures.fIbpb)
3787 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_PRED_CMD, VMXMSRPM_ALLOW_RD_WR);
3788 if (pVM->cpum.ro.GuestFeatures.fFlushCmd)
3789 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_FLUSH_CMD, VMXMSRPM_ALLOW_RD_WR);
3790 if (pVM->cpum.ro.GuestFeatures.fIbrs)
3791 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SPEC_CTRL, VMXMSRPM_ALLOW_RD_WR);
3792
3793 /*
3794 * Allow full read/write access for the following MSRs (mandatory for VT-x)
3795 * required for 64-bit guests.
3796 */
3797 if (pVM->hmr0.s.fAllow64BitGuests)
3798 {
3799 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_LSTAR, VMXMSRPM_ALLOW_RD_WR);
3800 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K6_STAR, VMXMSRPM_ALLOW_RD_WR);
3801 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_SF_MASK, VMXMSRPM_ALLOW_RD_WR);
3802 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_KERNEL_GS_BASE, VMXMSRPM_ALLOW_RD_WR);
3803 }
3804
3805 /*
3806 * IA32_EFER MSR is always intercepted, see @bugref{9180#c37}.
3807 */
3808#ifdef VBOX_STRICT
3809 Assert(pVmcsInfo->pvMsrBitmap);
3810 uint32_t const fMsrpmEfer = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, MSR_K6_EFER);
3811 Assert(fMsrpmEfer == VMXMSRPM_EXIT_RD_WR);
3812#endif
3813}
3814
3815
3816/**
3817 * Sets up pin-based VM-execution controls in the VMCS.
3818 *
3819 * @returns VBox status code.
3820 * @param pVCpu The cross context virtual CPU structure.
3821 * @param pVmcsInfo The VMCS info. object.
3822 */
3823static int hmR0VmxSetupVmcsPinCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3824{
3825 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3826 uint32_t fVal = g_HmMsrs.u.vmx.PinCtls.n.allowed0; /* Bits set here must always be set. */
3827 uint32_t const fZap = g_HmMsrs.u.vmx.PinCtls.n.allowed1; /* Bits cleared here must always be cleared. */
3828
3829 fVal |= VMX_PIN_CTLS_EXT_INT_EXIT /* External interrupts cause a VM-exit. */
3830 | VMX_PIN_CTLS_NMI_EXIT; /* Non-maskable interrupts (NMIs) cause a VM-exit. */
3831
3832 if (g_HmMsrs.u.vmx.PinCtls.n.allowed1 & VMX_PIN_CTLS_VIRT_NMI)
3833 fVal |= VMX_PIN_CTLS_VIRT_NMI; /* Use virtual NMIs and virtual-NMI blocking features. */
3834
3835 /* Enable the VMX-preemption timer. */
3836 if (pVM->hmr0.s.vmx.fUsePreemptTimer)
3837 {
3838 Assert(g_HmMsrs.u.vmx.PinCtls.n.allowed1 & VMX_PIN_CTLS_PREEMPT_TIMER);
3839 fVal |= VMX_PIN_CTLS_PREEMPT_TIMER;
3840 }
3841
3842#if 0
3843 /* Enable posted-interrupt processing. */
3844 if (pVM->hm.s.fPostedIntrs)
3845 {
3846 Assert(g_HmMsrs.u.vmx.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT);
3847 Assert(g_HmMsrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT);
3848 fVal |= VMX_PIN_CTLS_POSTED_INT;
3849 }
3850#endif
3851
3852 if ((fVal & fZap) != fVal)
3853 {
3854 LogRelFunc(("Invalid pin-based VM-execution controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3855 g_HmMsrs.u.vmx.PinCtls.n.allowed0, fVal, fZap));
3856 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PIN_EXEC;
3857 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3858 }
3859
3860 /* Commit it to the VMCS and update our cache. */
3861 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, fVal);
3862 AssertRC(rc);
3863 pVmcsInfo->u32PinCtls = fVal;
3864
3865 return VINF_SUCCESS;
3866}
3867
3868
3869/**
3870 * Sets up secondary processor-based VM-execution controls in the VMCS.
3871 *
3872 * @returns VBox status code.
3873 * @param pVCpu The cross context virtual CPU structure.
3874 * @param pVmcsInfo The VMCS info. object.
3875 */
3876static int hmR0VmxSetupVmcsProcCtls2(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3877{
3878 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3879 uint32_t fVal = g_HmMsrs.u.vmx.ProcCtls2.n.allowed0; /* Bits set here must be set in the VMCS. */
3880 uint32_t const fZap = g_HmMsrs.u.vmx.ProcCtls2.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3881
3882 /* WBINVD causes a VM-exit. */
3883 if (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_WBINVD_EXIT)
3884 fVal |= VMX_PROC_CTLS2_WBINVD_EXIT;
3885
3886 /* Enable EPT (aka nested-paging). */
3887 if (pVM->hmr0.s.fNestedPaging)
3888 fVal |= VMX_PROC_CTLS2_EPT;
3889
3890 /* Enable the INVPCID instruction if we expose it to the guest and is supported
3891 by the hardware. Without this, guest executing INVPCID would cause a #UD. */
3892 if ( pVM->cpum.ro.GuestFeatures.fInvpcid
3893 && (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_INVPCID))
3894 fVal |= VMX_PROC_CTLS2_INVPCID;
3895
3896 /* Enable VPID. */
3897 if (pVM->hmr0.s.vmx.fVpid)
3898 fVal |= VMX_PROC_CTLS2_VPID;
3899
3900 /* Enable unrestricted guest execution. */
3901 if (pVM->hmr0.s.vmx.fUnrestrictedGuest)
3902 fVal |= VMX_PROC_CTLS2_UNRESTRICTED_GUEST;
3903
3904#if 0
3905 if (pVM->hm.s.fVirtApicRegs)
3906 {
3907 /* Enable APIC-register virtualization. */
3908 Assert(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT);
3909 fVal |= VMX_PROC_CTLS2_APIC_REG_VIRT;
3910
3911 /* Enable virtual-interrupt delivery. */
3912 Assert(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY);
3913 fVal |= VMX_PROC_CTLS2_VIRT_INTR_DELIVERY;
3914 }
3915#endif
3916
3917 /* Virtualize-APIC accesses if supported by the CPU. The virtual-APIC page is
3918 where the TPR shadow resides. */
3919 /** @todo VIRT_X2APIC support, it's mutually exclusive with this. So must be
3920 * done dynamically. */
3921 if (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
3922 {
3923 fVal |= VMX_PROC_CTLS2_VIRT_APIC_ACCESS;
3924 hmR0VmxSetupVmcsApicAccessAddr(pVCpu);
3925 }
3926
3927 /* Enable the RDTSCP instruction if we expose it to the guest and is supported
3928 by the hardware. Without this, guest executing RDTSCP would cause a #UD. */
3929 if ( pVM->cpum.ro.GuestFeatures.fRdTscP
3930 && (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_RDTSCP))
3931 fVal |= VMX_PROC_CTLS2_RDTSCP;
3932
3933 /* Enable Pause-Loop exiting. */
3934 if ( (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT)
3935 && pVM->hm.s.vmx.cPleGapTicks
3936 && pVM->hm.s.vmx.cPleWindowTicks)
3937 {
3938 fVal |= VMX_PROC_CTLS2_PAUSE_LOOP_EXIT;
3939
3940 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, pVM->hm.s.vmx.cPleGapTicks); AssertRC(rc);
3941 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, pVM->hm.s.vmx.cPleWindowTicks); AssertRC(rc);
3942 }
3943
3944 if ((fVal & fZap) != fVal)
3945 {
3946 LogRelFunc(("Invalid secondary processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3947 g_HmMsrs.u.vmx.ProcCtls2.n.allowed0, fVal, fZap));
3948 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC2;
3949 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3950 }
3951
3952 /* Commit it to the VMCS and update our cache. */
3953 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, fVal);
3954 AssertRC(rc);
3955 pVmcsInfo->u32ProcCtls2 = fVal;
3956
3957 return VINF_SUCCESS;
3958}
3959
3960
3961/**
3962 * Sets up processor-based VM-execution controls in the VMCS.
3963 *
3964 * @returns VBox status code.
3965 * @param pVCpu The cross context virtual CPU structure.
3966 * @param pVmcsInfo The VMCS info. object.
3967 */
3968static int hmR0VmxSetupVmcsProcCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3969{
3970 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3971 uint32_t fVal = g_HmMsrs.u.vmx.ProcCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
3972 uint32_t const fZap = g_HmMsrs.u.vmx.ProcCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3973
3974 fVal |= VMX_PROC_CTLS_HLT_EXIT /* HLT causes a VM-exit. */
3975 | VMX_PROC_CTLS_USE_TSC_OFFSETTING /* Use TSC-offsetting. */
3976 | VMX_PROC_CTLS_MOV_DR_EXIT /* MOV DRx causes a VM-exit. */
3977 | VMX_PROC_CTLS_UNCOND_IO_EXIT /* All IO instructions cause a VM-exit. */
3978 | VMX_PROC_CTLS_RDPMC_EXIT /* RDPMC causes a VM-exit. */
3979 | VMX_PROC_CTLS_MONITOR_EXIT /* MONITOR causes a VM-exit. */
3980 | VMX_PROC_CTLS_MWAIT_EXIT; /* MWAIT causes a VM-exit. */
3981
3982 /* We toggle VMX_PROC_CTLS_MOV_DR_EXIT later, check if it's not -always- needed to be set or clear. */
3983 if ( !(g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MOV_DR_EXIT)
3984 || (g_HmMsrs.u.vmx.ProcCtls.n.allowed0 & VMX_PROC_CTLS_MOV_DR_EXIT))
3985 {
3986 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_MOV_DRX_EXIT;
3987 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3988 }
3989
3990 /* Without nested paging, INVLPG (also affects INVPCID) and MOV CR3 instructions should cause VM-exits. */
3991 if (!pVM->hmr0.s.fNestedPaging)
3992 {
3993 Assert(!pVM->hmr0.s.vmx.fUnrestrictedGuest);
3994 fVal |= VMX_PROC_CTLS_INVLPG_EXIT
3995 | VMX_PROC_CTLS_CR3_LOAD_EXIT
3996 | VMX_PROC_CTLS_CR3_STORE_EXIT;
3997 }
3998
3999 /* Use TPR shadowing if supported by the CPU. */
4000 if ( PDMHasApic(pVM)
4001 && (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW))
4002 {
4003 fVal |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* CR8 reads from the Virtual-APIC page. */
4004 /* CR8 writes cause a VM-exit based on TPR threshold. */
4005 Assert(!(fVal & VMX_PROC_CTLS_CR8_STORE_EXIT));
4006 Assert(!(fVal & VMX_PROC_CTLS_CR8_LOAD_EXIT));
4007 hmR0VmxSetupVmcsVirtApicAddr(pVmcsInfo);
4008 }
4009 else
4010 {
4011 /* Some 32-bit CPUs do not support CR8 load/store exiting as MOV CR8 is
4012 invalid on 32-bit Intel CPUs. Set this control only for 64-bit guests. */
4013 if (pVM->hmr0.s.fAllow64BitGuests)
4014 fVal |= VMX_PROC_CTLS_CR8_STORE_EXIT /* CR8 reads cause a VM-exit. */
4015 | VMX_PROC_CTLS_CR8_LOAD_EXIT; /* CR8 writes cause a VM-exit. */
4016 }
4017
4018 /* Use MSR-bitmaps if supported by the CPU. */
4019 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
4020 {
4021 fVal |= VMX_PROC_CTLS_USE_MSR_BITMAPS;
4022 hmR0VmxSetupVmcsMsrBitmapAddr(pVmcsInfo);
4023 }
4024
4025 /* Use the secondary processor-based VM-execution controls if supported by the CPU. */
4026 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4027 fVal |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
4028
4029 if ((fVal & fZap) != fVal)
4030 {
4031 LogRelFunc(("Invalid processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
4032 g_HmMsrs.u.vmx.ProcCtls.n.allowed0, fVal, fZap));
4033 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC;
4034 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4035 }
4036
4037 /* Commit it to the VMCS and update our cache. */
4038 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, fVal);
4039 AssertRC(rc);
4040 pVmcsInfo->u32ProcCtls = fVal;
4041
4042 /* Set up MSR permissions that don't change through the lifetime of the VM. */
4043 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
4044 hmR0VmxSetupVmcsMsrPermissions(pVCpu, pVmcsInfo);
4045
4046 /* Set up secondary processor-based VM-execution controls if the CPU supports it. */
4047 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4048 return hmR0VmxSetupVmcsProcCtls2(pVCpu, pVmcsInfo);
4049
4050 /* Sanity check, should not really happen. */
4051 if (RT_LIKELY(!pVM->hmr0.s.vmx.fUnrestrictedGuest))
4052 { /* likely */ }
4053 else
4054 {
4055 pVCpu->hm.s.u32HMError = VMX_UFC_INVALID_UX_COMBO;
4056 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4057 }
4058
4059 /* Old CPUs without secondary processor-based VM-execution controls would end up here. */
4060 return VINF_SUCCESS;
4061}
4062
4063
4064/**
4065 * Sets up miscellaneous (everything other than Pin, Processor and secondary
4066 * Processor-based VM-execution) control fields in the VMCS.
4067 *
4068 * @returns VBox status code.
4069 * @param pVCpu The cross context virtual CPU structure.
4070 * @param pVmcsInfo The VMCS info. object.
4071 */
4072static int hmR0VmxSetupVmcsMiscCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
4073{
4074#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4075 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fUseVmcsShadowing)
4076 {
4077 hmR0VmxSetupVmcsVmreadBitmapAddr(pVCpu);
4078 hmR0VmxSetupVmcsVmwriteBitmapAddr(pVCpu);
4079 }
4080#endif
4081
4082 Assert(pVmcsInfo->u64VmcsLinkPtr == NIL_RTHCPHYS);
4083 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS);
4084 AssertRC(rc);
4085
4086 rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo);
4087 if (RT_SUCCESS(rc))
4088 {
4089 uint64_t const u64Cr0Mask = hmR0VmxGetFixedCr0Mask(pVCpu);
4090 uint64_t const u64Cr4Mask = hmR0VmxGetFixedCr4Mask(pVCpu);
4091
4092 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask); AssertRC(rc);
4093 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask); AssertRC(rc);
4094
4095 pVmcsInfo->u64Cr0Mask = u64Cr0Mask;
4096 pVmcsInfo->u64Cr4Mask = u64Cr4Mask;
4097
4098 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fLbr)
4099 {
4100 rc = VMXWriteVmcsNw(VMX_VMCS64_GUEST_DEBUGCTL_FULL, MSR_IA32_DEBUGCTL_LBR);
4101 AssertRC(rc);
4102 }
4103 return VINF_SUCCESS;
4104 }
4105 else
4106 LogRelFunc(("Failed to initialize VMCS auto-load/store MSR addresses. rc=%Rrc\n", rc));
4107 return rc;
4108}
4109
4110
4111/**
4112 * Sets up the initial exception bitmap in the VMCS based on static conditions.
4113 *
4114 * We shall setup those exception intercepts that don't change during the
4115 * lifetime of the VM here. The rest are done dynamically while loading the
4116 * guest state.
4117 *
4118 * @param pVCpu The cross context virtual CPU structure.
4119 * @param pVmcsInfo The VMCS info. object.
4120 */
4121static void hmR0VmxSetupVmcsXcptBitmap(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
4122{
4123 /*
4124 * The following exceptions are always intercepted:
4125 *
4126 * #AC - To prevent the guest from hanging the CPU and for dealing with
4127 * split-lock detecting host configs.
4128 * #DB - To maintain the DR6 state even when intercepting DRx reads/writes and
4129 * recursive #DBs can cause a CPU hang.
4130 * #PF - To sync our shadow page tables when nested-paging is not used.
4131 */
4132 bool const fNestedPaging = pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging;
4133 uint32_t const uXcptBitmap = RT_BIT(X86_XCPT_AC)
4134 | RT_BIT(X86_XCPT_DB)
4135 | (fNestedPaging ? 0 : RT_BIT(X86_XCPT_PF));
4136
4137 /* Commit it to the VMCS. */
4138 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
4139 AssertRC(rc);
4140
4141 /* Update our cache of the exception bitmap. */
4142 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
4143}
4144
4145
4146#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4147/**
4148 * Sets up the VMCS for executing a nested-guest using hardware-assisted VMX.
4149 *
4150 * @returns VBox status code.
4151 * @param pVmcsInfo The VMCS info. object.
4152 */
4153static int hmR0VmxSetupVmcsCtlsNested(PVMXVMCSINFO pVmcsInfo)
4154{
4155 Assert(pVmcsInfo->u64VmcsLinkPtr == NIL_RTHCPHYS);
4156 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS);
4157 AssertRC(rc);
4158
4159 rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo);
4160 if (RT_SUCCESS(rc))
4161 {
4162 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
4163 hmR0VmxSetupVmcsMsrBitmapAddr(pVmcsInfo);
4164
4165 /* Paranoia - We've not yet initialized these, they shall be done while merging the VMCS. */
4166 Assert(!pVmcsInfo->u64Cr0Mask);
4167 Assert(!pVmcsInfo->u64Cr4Mask);
4168 return VINF_SUCCESS;
4169 }
4170 LogRelFunc(("Failed to set up the VMCS link pointer in the nested-guest VMCS. rc=%Rrc\n", rc));
4171 return rc;
4172}
4173#endif
4174
4175
4176/**
4177 * Sets pfnStartVm to the best suited variant.
4178 *
4179 * This must be called whenever anything changes relative to the hmR0VmXStartVm
4180 * variant selection:
4181 * - pVCpu->hm.s.fLoadSaveGuestXcr0
4182 * - HM_WSF_IBPB_ENTRY in pVCpu->hmr0.s.fWorldSwitcher
4183 * - HM_WSF_IBPB_EXIT in pVCpu->hmr0.s.fWorldSwitcher
4184 * - Perhaps: CPUMIsGuestFPUStateActive() (windows only)
4185 * - Perhaps: CPUMCTX.fXStateMask (windows only)
4186 *
4187 * We currently ASSUME that neither HM_WSF_IBPB_ENTRY nor HM_WSF_IBPB_EXIT
4188 * cannot be changed at runtime.
4189 */
4190static void hmR0VmxUpdateStartVmFunction(PVMCPUCC pVCpu)
4191{
4192 static const struct CLANGWORKAROUND { PFNHMVMXSTARTVM pfn; } s_aHmR0VmxStartVmFunctions[] =
4193 {
4194 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_SansL1dEntry_SansMdsEntry_SansIbpbExit },
4195 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_SansL1dEntry_SansMdsEntry_SansIbpbExit },
4196 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_SansL1dEntry_SansMdsEntry_SansIbpbExit },
4197 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_SansL1dEntry_SansMdsEntry_SansIbpbExit },
4198 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_WithL1dEntry_SansMdsEntry_SansIbpbExit },
4199 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_WithL1dEntry_SansMdsEntry_SansIbpbExit },
4200 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_WithL1dEntry_SansMdsEntry_SansIbpbExit },
4201 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_WithL1dEntry_SansMdsEntry_SansIbpbExit },
4202 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_SansL1dEntry_WithMdsEntry_SansIbpbExit },
4203 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_SansL1dEntry_WithMdsEntry_SansIbpbExit },
4204 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_SansL1dEntry_WithMdsEntry_SansIbpbExit },
4205 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_SansL1dEntry_WithMdsEntry_SansIbpbExit },
4206 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_WithL1dEntry_WithMdsEntry_SansIbpbExit },
4207 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_WithL1dEntry_WithMdsEntry_SansIbpbExit },
4208 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_WithL1dEntry_WithMdsEntry_SansIbpbExit },
4209 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_WithL1dEntry_WithMdsEntry_SansIbpbExit },
4210 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_SansL1dEntry_SansMdsEntry_WithIbpbExit },
4211 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_SansL1dEntry_SansMdsEntry_WithIbpbExit },
4212 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_SansL1dEntry_SansMdsEntry_WithIbpbExit },
4213 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_SansL1dEntry_SansMdsEntry_WithIbpbExit },
4214 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_WithL1dEntry_SansMdsEntry_WithIbpbExit },
4215 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_WithL1dEntry_SansMdsEntry_WithIbpbExit },
4216 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_WithL1dEntry_SansMdsEntry_WithIbpbExit },
4217 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_WithL1dEntry_SansMdsEntry_WithIbpbExit },
4218 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_SansL1dEntry_WithMdsEntry_WithIbpbExit },
4219 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_SansL1dEntry_WithMdsEntry_WithIbpbExit },
4220 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_SansL1dEntry_WithMdsEntry_WithIbpbExit },
4221 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_SansL1dEntry_WithMdsEntry_WithIbpbExit },
4222 { hmR0VmxStartVm_SansXcr0_SansIbpbEntry_WithL1dEntry_WithMdsEntry_WithIbpbExit },
4223 { hmR0VmxStartVm_WithXcr0_SansIbpbEntry_WithL1dEntry_WithMdsEntry_WithIbpbExit },
4224 { hmR0VmxStartVm_SansXcr0_WithIbpbEntry_WithL1dEntry_WithMdsEntry_WithIbpbExit },
4225 { hmR0VmxStartVm_WithXcr0_WithIbpbEntry_WithL1dEntry_WithMdsEntry_WithIbpbExit },
4226 };
4227 uintptr_t const idx = (pVCpu->hmr0.s.fLoadSaveGuestXcr0 ? 1 : 0)
4228 | (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_IBPB_ENTRY ? 2 : 0)
4229 | (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_L1D_ENTRY ? 4 : 0)
4230 | (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_MDS_ENTRY ? 8 : 0)
4231 | (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_IBPB_EXIT ? 16 : 0);
4232 PFNHMVMXSTARTVM const pfnStartVm = s_aHmR0VmxStartVmFunctions[idx].pfn;
4233 if (pVCpu->hmr0.s.vmx.pfnStartVm != pfnStartVm)
4234 pVCpu->hmr0.s.vmx.pfnStartVm = pfnStartVm;
4235}
4236
4237
4238/**
4239 * Selector FNHMSVMVMRUN implementation.
4240 */
4241static DECLCALLBACK(int) hmR0VmxStartVmSelector(PVMXVMCSINFO pVmcsInfo, PVMCPUCC pVCpu, bool fResume)
4242{
4243 hmR0VmxUpdateStartVmFunction(pVCpu);
4244 return pVCpu->hmr0.s.vmx.pfnStartVm(pVmcsInfo, pVCpu, fResume);
4245}
4246
4247
4248/**
4249 * Sets up the VMCS for executing a guest (or nested-guest) using hardware-assisted
4250 * VMX.
4251 *
4252 * @returns VBox status code.
4253 * @param pVCpu The cross context virtual CPU structure.
4254 * @param pVmcsInfo The VMCS info. object.
4255 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
4256 */
4257static int hmR0VmxSetupVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
4258{
4259 Assert(pVmcsInfo->pvVmcs);
4260 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4261
4262 /* Set the CPU specified revision identifier at the beginning of the VMCS structure. */
4263 *(uint32_t *)pVmcsInfo->pvVmcs = RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_ID);
4264 const char * const pszVmcs = fIsNstGstVmcs ? "nested-guest VMCS" : "guest VMCS";
4265
4266 LogFlowFunc(("\n"));
4267
4268 /*
4269 * Initialize the VMCS using VMCLEAR before loading the VMCS.
4270 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
4271 */
4272 int rc = hmR0VmxClearVmcs(pVmcsInfo);
4273 if (RT_SUCCESS(rc))
4274 {
4275 rc = hmR0VmxLoadVmcs(pVmcsInfo);
4276 if (RT_SUCCESS(rc))
4277 {
4278 /*
4279 * Initialize the hardware-assisted VMX execution handler for guest and nested-guest VMCS.
4280 * The host is always 64-bit since we no longer support 32-bit hosts.
4281 * Currently we have just a single handler for all guest modes as well, see @bugref{6208#c73}.
4282 */
4283 if (!fIsNstGstVmcs)
4284 {
4285 rc = hmR0VmxSetupVmcsPinCtls(pVCpu, pVmcsInfo);
4286 if (RT_SUCCESS(rc))
4287 {
4288 rc = hmR0VmxSetupVmcsProcCtls(pVCpu, pVmcsInfo);
4289 if (RT_SUCCESS(rc))
4290 {
4291 rc = hmR0VmxSetupVmcsMiscCtls(pVCpu, pVmcsInfo);
4292 if (RT_SUCCESS(rc))
4293 {
4294 hmR0VmxSetupVmcsXcptBitmap(pVCpu, pVmcsInfo);
4295#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4296 /*
4297 * If a shadow VMCS is allocated for the VMCS info. object, initialize the
4298 * VMCS revision ID and shadow VMCS indicator bit. Also, clear the VMCS
4299 * making it fit for use when VMCS shadowing is later enabled.
4300 */
4301 if (pVmcsInfo->pvShadowVmcs)
4302 {
4303 VMXVMCSREVID VmcsRevId;
4304 VmcsRevId.u = RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_ID);
4305 VmcsRevId.n.fIsShadowVmcs = 1;
4306 *(uint32_t *)pVmcsInfo->pvShadowVmcs = VmcsRevId.u;
4307 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
4308 if (RT_SUCCESS(rc))
4309 { /* likely */ }
4310 else
4311 LogRelFunc(("Failed to initialize shadow VMCS. rc=%Rrc\n", rc));
4312 }
4313#endif
4314 }
4315 else
4316 LogRelFunc(("Failed to setup miscellaneous controls. rc=%Rrc\n", rc));
4317 }
4318 else
4319 LogRelFunc(("Failed to setup processor-based VM-execution controls. rc=%Rrc\n", rc));
4320 }
4321 else
4322 LogRelFunc(("Failed to setup pin-based controls. rc=%Rrc\n", rc));
4323 }
4324 else
4325 {
4326#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4327 rc = hmR0VmxSetupVmcsCtlsNested(pVmcsInfo);
4328 if (RT_SUCCESS(rc))
4329 { /* likely */ }
4330 else
4331 LogRelFunc(("Failed to initialize nested-guest VMCS. rc=%Rrc\n", rc));
4332#else
4333 AssertFailed();
4334#endif
4335 }
4336 }
4337 else
4338 LogRelFunc(("Failed to load the %s. rc=%Rrc\n", rc, pszVmcs));
4339 }
4340 else
4341 LogRelFunc(("Failed to clear the %s. rc=%Rrc\n", rc, pszVmcs));
4342
4343 /* Sync any CPU internal VMCS data back into our VMCS in memory. */
4344 if (RT_SUCCESS(rc))
4345 {
4346 rc = hmR0VmxClearVmcs(pVmcsInfo);
4347 if (RT_SUCCESS(rc))
4348 { /* likely */ }
4349 else
4350 LogRelFunc(("Failed to clear the %s post setup. rc=%Rrc\n", rc, pszVmcs));
4351 }
4352
4353 /*
4354 * Update the last-error record both for failures and success, so we
4355 * can propagate the status code back to ring-3 for diagnostics.
4356 */
4357 hmR0VmxUpdateErrorRecord(pVCpu, rc);
4358 NOREF(pszVmcs);
4359 return rc;
4360}
4361
4362
4363/**
4364 * Does global VT-x initialization (called during module initialization).
4365 *
4366 * @returns VBox status code.
4367 */
4368VMMR0DECL(int) VMXR0GlobalInit(void)
4369{
4370#ifdef HMVMX_USE_FUNCTION_TABLE
4371 AssertCompile(VMX_EXIT_MAX + 1 == RT_ELEMENTS(g_aVMExitHandlers));
4372# ifdef VBOX_STRICT
4373 for (unsigned i = 0; i < RT_ELEMENTS(g_aVMExitHandlers); i++)
4374 Assert(g_aVMExitHandlers[i].pfn);
4375# endif
4376#endif
4377 return VINF_SUCCESS;
4378}
4379
4380
4381/**
4382 * Does global VT-x termination (called during module termination).
4383 */
4384VMMR0DECL(void) VMXR0GlobalTerm()
4385{
4386 /* Nothing to do currently. */
4387}
4388
4389
4390/**
4391 * Sets up and activates VT-x on the current CPU.
4392 *
4393 * @returns VBox status code.
4394 * @param pHostCpu The HM physical-CPU structure.
4395 * @param pVM The cross context VM structure. Can be
4396 * NULL after a host resume operation.
4397 * @param pvCpuPage Pointer to the VMXON region (can be NULL if @a
4398 * fEnabledByHost is @c true).
4399 * @param HCPhysCpuPage Physical address of the VMXON region (can be 0 if
4400 * @a fEnabledByHost is @c true).
4401 * @param fEnabledByHost Set if SUPR0EnableVTx() or similar was used to
4402 * enable VT-x on the host.
4403 * @param pHwvirtMsrs Pointer to the hardware-virtualization MSRs.
4404 */
4405VMMR0DECL(int) VMXR0EnableCpu(PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
4406 PCSUPHWVIRTMSRS pHwvirtMsrs)
4407{
4408 AssertPtr(pHostCpu);
4409 AssertPtr(pHwvirtMsrs);
4410 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4411
4412 /* Enable VT-x if it's not already enabled by the host. */
4413 if (!fEnabledByHost)
4414 {
4415 int rc = hmR0VmxEnterRootMode(pHostCpu, pVM, HCPhysCpuPage, pvCpuPage);
4416 if (RT_FAILURE(rc))
4417 return rc;
4418 }
4419
4420 /*
4421 * Flush all EPT tagged-TLB entries (in case VirtualBox or any other hypervisor have been
4422 * using EPTPs) so we don't retain any stale guest-physical mappings which won't get
4423 * invalidated when flushing by VPID.
4424 */
4425 if (pHwvirtMsrs->u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
4426 {
4427 hmR0VmxFlushEpt(NULL /* pVCpu */, NULL /* pVmcsInfo */, VMXTLBFLUSHEPT_ALL_CONTEXTS);
4428 pHostCpu->fFlushAsidBeforeUse = false;
4429 }
4430 else
4431 pHostCpu->fFlushAsidBeforeUse = true;
4432
4433 /* Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}. */
4434 ++pHostCpu->cTlbFlushes;
4435
4436 return VINF_SUCCESS;
4437}
4438
4439
4440/**
4441 * Deactivates VT-x on the current CPU.
4442 *
4443 * @returns VBox status code.
4444 * @param pHostCpu The HM physical-CPU structure.
4445 * @param pvCpuPage Pointer to the VMXON region.
4446 * @param HCPhysCpuPage Physical address of the VMXON region.
4447 *
4448 * @remarks This function should never be called when SUPR0EnableVTx() or
4449 * similar was used to enable VT-x on the host.
4450 */
4451VMMR0DECL(int) VMXR0DisableCpu(PHMPHYSCPU pHostCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
4452{
4453 RT_NOREF2(pvCpuPage, HCPhysCpuPage);
4454
4455 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4456 return hmR0VmxLeaveRootMode(pHostCpu);
4457}
4458
4459
4460/**
4461 * Does per-VM VT-x initialization.
4462 *
4463 * @returns VBox status code.
4464 * @param pVM The cross context VM structure.
4465 */
4466VMMR0DECL(int) VMXR0InitVM(PVMCC pVM)
4467{
4468 AssertPtr(pVM);
4469 LogFlowFunc(("pVM=%p\n", pVM));
4470
4471 hmR0VmxStructsInit(pVM);
4472 int rc = hmR0VmxStructsAlloc(pVM);
4473 if (RT_FAILURE(rc))
4474 {
4475 LogRelFunc(("Failed to allocated VMX structures. rc=%Rrc\n", rc));
4476 return rc;
4477 }
4478
4479 /* Setup the crash dump page. */
4480#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4481 strcpy((char *)pVM->hmr0.s.vmx.pbScratch, "SCRATCH Magic");
4482 *(uint64_t *)(pVM->hmr0.s.vmx.pbScratch + 16) = UINT64_C(0xdeadbeefdeadbeef);
4483#endif
4484 return VINF_SUCCESS;
4485}
4486
4487
4488/**
4489 * Does per-VM VT-x termination.
4490 *
4491 * @returns VBox status code.
4492 * @param pVM The cross context VM structure.
4493 */
4494VMMR0DECL(int) VMXR0TermVM(PVMCC pVM)
4495{
4496 AssertPtr(pVM);
4497 LogFlowFunc(("pVM=%p\n", pVM));
4498
4499#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4500 if (pVM->hmr0.s.vmx.pbScratch)
4501 RT_BZERO(pVM->hmr0.s.vmx.pbScratch, X86_PAGE_4K_SIZE);
4502#endif
4503 hmR0VmxStructsFree(pVM);
4504 return VINF_SUCCESS;
4505}
4506
4507
4508/**
4509 * Sets up the VM for execution using hardware-assisted VMX.
4510 * This function is only called once per-VM during initialization.
4511 *
4512 * @returns VBox status code.
4513 * @param pVM The cross context VM structure.
4514 */
4515VMMR0DECL(int) VMXR0SetupVM(PVMCC pVM)
4516{
4517 AssertPtr(pVM);
4518 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4519
4520 LogFlowFunc(("pVM=%p\n", pVM));
4521
4522 /*
4523 * At least verify if VMX is enabled, since we can't check if we're in VMX root mode or not
4524 * without causing a #GP.
4525 */
4526 RTCCUINTREG const uHostCr4 = ASMGetCR4();
4527 if (RT_LIKELY(uHostCr4 & X86_CR4_VMXE))
4528 { /* likely */ }
4529 else
4530 return VERR_VMX_NOT_IN_VMX_ROOT_MODE;
4531
4532 /*
4533 * Check that nested paging is supported if enabled and copy over the flag to the
4534 * ring-0 only structure.
4535 */
4536 bool const fNestedPaging = pVM->hm.s.fNestedPagingCfg;
4537 AssertReturn( !fNestedPaging
4538 || (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_EPT), /** @todo use a ring-0 copy of ProcCtls2.n.allowed1 */
4539 VERR_INCOMPATIBLE_CONFIG);
4540 pVM->hmr0.s.fNestedPaging = fNestedPaging;
4541 pVM->hmr0.s.fAllow64BitGuests = pVM->hm.s.fAllow64BitGuestsCfg;
4542
4543 /*
4544 * Without unrestricted guest execution, pRealModeTSS and pNonPagingModeEPTPageTable *must*
4545 * always be allocated. We no longer support the highly unlikely case of unrestricted guest
4546 * without pRealModeTSS, see hmR3InitFinalizeR0Intel().
4547 */
4548 bool const fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuestCfg;
4549 AssertReturn( !fUnrestrictedGuest
4550 || ( (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_UNRESTRICTED_GUEST)
4551 && fNestedPaging),
4552 VERR_INCOMPATIBLE_CONFIG);
4553 if ( !fUnrestrictedGuest
4554 && ( !pVM->hm.s.vmx.pNonPagingModeEPTPageTable
4555 || !pVM->hm.s.vmx.pRealModeTSS))
4556 {
4557 LogRelFunc(("Invalid real-on-v86 state.\n"));
4558 return VERR_INTERNAL_ERROR;
4559 }
4560 pVM->hmr0.s.vmx.fUnrestrictedGuest = fUnrestrictedGuest;
4561
4562 /* Initialize these always, see hmR3InitFinalizeR0().*/
4563 pVM->hm.s.ForR3.vmx.enmTlbFlushEpt = pVM->hmr0.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NONE;
4564 pVM->hm.s.ForR3.vmx.enmTlbFlushVpid = pVM->hmr0.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NONE;
4565
4566 /* Setup the tagged-TLB flush handlers. */
4567 int rc = hmR0VmxSetupTaggedTlb(pVM);
4568 if (RT_FAILURE(rc))
4569 {
4570 LogRelFunc(("Failed to setup tagged TLB. rc=%Rrc\n", rc));
4571 return rc;
4572 }
4573
4574 /* Determine LBR capabilities. */
4575 pVM->hmr0.s.vmx.fLbr = pVM->hm.s.vmx.fLbrCfg;
4576 if (pVM->hmr0.s.vmx.fLbr)
4577 {
4578 rc = hmR0VmxSetupLbrMsrRange(pVM);
4579 if (RT_FAILURE(rc))
4580 {
4581 LogRelFunc(("Failed to setup LBR MSR range. rc=%Rrc\n", rc));
4582 return rc;
4583 }
4584 }
4585
4586#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4587 /* Setup the shadow VMCS fields array and VMREAD/VMWRITE bitmaps. */
4588 if (pVM->hmr0.s.vmx.fUseVmcsShadowing)
4589 {
4590 rc = hmR0VmxSetupShadowVmcsFieldsArrays(pVM);
4591 if (RT_SUCCESS(rc))
4592 hmR0VmxSetupVmreadVmwriteBitmaps(pVM);
4593 else
4594 {
4595 LogRelFunc(("Failed to setup shadow VMCS fields arrays. rc=%Rrc\n", rc));
4596 return rc;
4597 }
4598 }
4599#endif
4600
4601 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
4602 {
4603 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
4604 Log4Func(("pVCpu=%p idCpu=%RU32\n", pVCpu, pVCpu->idCpu));
4605
4606 pVCpu->hmr0.s.vmx.pfnStartVm = hmR0VmxStartVmSelector;
4607
4608 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hmr0.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
4609 if (RT_SUCCESS(rc))
4610 {
4611#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4612 if (pVM->cpum.ro.GuestFeatures.fVmx)
4613 {
4614 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hmr0.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
4615 if (RT_SUCCESS(rc))
4616 { /* likely */ }
4617 else
4618 {
4619 LogRelFunc(("Nested-guest VMCS setup failed. rc=%Rrc\n", rc));
4620 return rc;
4621 }
4622 }
4623#endif
4624 }
4625 else
4626 {
4627 LogRelFunc(("VMCS setup failed. rc=%Rrc\n", rc));
4628 return rc;
4629 }
4630 }
4631
4632 return VINF_SUCCESS;
4633}
4634
4635
4636/**
4637 * Saves the host control registers (CR0, CR3, CR4) into the host-state area in
4638 * the VMCS.
4639 * @returns CR4 for passing along to hmR0VmxExportHostSegmentRegs.
4640 */
4641static uint64_t hmR0VmxExportHostControlRegs(void)
4642{
4643 int rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR0, ASMGetCR0()); AssertRC(rc);
4644 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR3, ASMGetCR3()); AssertRC(rc);
4645 uint64_t uHostCr4 = ASMGetCR4();
4646 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR4, uHostCr4); AssertRC(rc);
4647 return uHostCr4;
4648}
4649
4650
4651/**
4652 * Saves the host segment registers and GDTR, IDTR, (TR, GS and FS bases) into
4653 * the host-state area in the VMCS.
4654 *
4655 * @returns VBox status code.
4656 * @param pVCpu The cross context virtual CPU structure.
4657 * @param uHostCr4 The host CR4 value.
4658 */
4659static int hmR0VmxExportHostSegmentRegs(PVMCPUCC pVCpu, uint64_t uHostCr4)
4660{
4661 /*
4662 * If we've executed guest code using hardware-assisted VMX, the host-state bits
4663 * will be messed up. We should -not- save the messed up state without restoring
4664 * the original host-state, see @bugref{7240}.
4665 *
4666 * This apparently can happen (most likely the FPU changes), deal with it rather than
4667 * asserting. Was observed booting Solaris 10u10 32-bit guest.
4668 */
4669 if (pVCpu->hmr0.s.vmx.fRestoreHostFlags > VMX_RESTORE_HOST_REQUIRED)
4670 {
4671 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hmr0.s.vmx.fRestoreHostFlags,
4672 pVCpu->idCpu));
4673 VMXRestoreHostState(pVCpu->hmr0.s.vmx.fRestoreHostFlags, &pVCpu->hmr0.s.vmx.RestoreHost);
4674 pVCpu->hmr0.s.vmx.fRestoreHostFlags = 0;
4675 }
4676
4677 /*
4678 * Get all the host info.
4679 * ASSUME it is safe to use rdfsbase and friends if the CR4.FSGSBASE bit is set
4680 * without also checking the cpuid bit.
4681 */
4682 uint32_t fRestoreHostFlags;
4683#if RT_INLINE_ASM_EXTERNAL
4684 if (uHostCr4 & X86_CR4_FSGSBASE)
4685 {
4686 hmR0VmxExportHostSegmentRegsAsmHlp(&pVCpu->hmr0.s.vmx.RestoreHost, true /*fHaveFsGsBase*/);
4687 fRestoreHostFlags = VMX_RESTORE_HOST_CAN_USE_WRFSBASE_AND_WRGSBASE;
4688 }
4689 else
4690 {
4691 hmR0VmxExportHostSegmentRegsAsmHlp(&pVCpu->hmr0.s.vmx.RestoreHost, false /*fHaveFsGsBase*/);
4692 fRestoreHostFlags = 0;
4693 }
4694 RTSEL uSelES = pVCpu->hmr0.s.vmx.RestoreHost.uHostSelES;
4695 RTSEL uSelDS = pVCpu->hmr0.s.vmx.RestoreHost.uHostSelDS;
4696 RTSEL uSelFS = pVCpu->hmr0.s.vmx.RestoreHost.uHostSelFS;
4697 RTSEL uSelGS = pVCpu->hmr0.s.vmx.RestoreHost.uHostSelGS;
4698#else
4699 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelTR = ASMGetTR();
4700 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelSS = ASMGetSS();
4701 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelCS = ASMGetCS();
4702 ASMGetGDTR((PRTGDTR)&pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr);
4703 ASMGetIDTR((PRTIDTR)&pVCpu->hmr0.s.vmx.RestoreHost.HostIdtr);
4704 if (uHostCr4 & X86_CR4_FSGSBASE)
4705 {
4706 pVCpu->hmr0.s.vmx.RestoreHost.uHostFSBase = ASMGetFSBase();
4707 pVCpu->hmr0.s.vmx.RestoreHost.uHostGSBase = ASMGetGSBase();
4708 fRestoreHostFlags = VMX_RESTORE_HOST_CAN_USE_WRFSBASE_AND_WRGSBASE;
4709 }
4710 else
4711 {
4712 pVCpu->hmr0.s.vmx.RestoreHost.uHostFSBase = ASMRdMsr(MSR_K8_FS_BASE);
4713 pVCpu->hmr0.s.vmx.RestoreHost.uHostGSBase = ASMRdMsr(MSR_K8_GS_BASE);
4714 fRestoreHostFlags = 0;
4715 }
4716 RTSEL uSelES, uSelDS, uSelFS, uSelGS;
4717 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelDS = uSelDS = ASMGetDS();
4718 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelES = uSelES = ASMGetES();
4719 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelFS = uSelFS = ASMGetFS();
4720 pVCpu->hmr0.s.vmx.RestoreHost.uHostSelGS = uSelGS = ASMGetGS();
4721#endif
4722
4723 /*
4724 * Determine if the host segment registers are suitable for VT-x. Otherwise use zero to
4725 * gain VM-entry and restore them before we get preempted.
4726 *
4727 * See Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers".
4728 */
4729 RTSEL const uSelAll = uSelFS | uSelGS | uSelES | uSelDS;
4730 if (uSelAll & (X86_SEL_RPL | X86_SEL_LDT))
4731 {
4732 if (!(uSelAll & X86_SEL_LDT))
4733 {
4734#define VMXLOCAL_ADJUST_HOST_SEG(a_Seg, a_uVmcsVar) \
4735 do { \
4736 (a_uVmcsVar) = pVCpu->hmr0.s.vmx.RestoreHost.uHostSel##a_Seg; \
4737 if ((a_uVmcsVar) & X86_SEL_RPL) \
4738 { \
4739 fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##a_Seg; \
4740 (a_uVmcsVar) = 0; \
4741 } \
4742 } while (0)
4743 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
4744 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
4745 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
4746 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
4747#undef VMXLOCAL_ADJUST_HOST_SEG
4748 }
4749 else
4750 {
4751#define VMXLOCAL_ADJUST_HOST_SEG(a_Seg, a_uVmcsVar) \
4752 do { \
4753 (a_uVmcsVar) = pVCpu->hmr0.s.vmx.RestoreHost.uHostSel##a_Seg; \
4754 if ((a_uVmcsVar) & (X86_SEL_RPL | X86_SEL_LDT)) \
4755 { \
4756 if (!((a_uVmcsVar) & X86_SEL_LDT)) \
4757 fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##a_Seg; \
4758 else \
4759 { \
4760 uint32_t const fAttr = ASMGetSegAttr(a_uVmcsVar); \
4761 if ((fAttr & X86_DESC_P) && fAttr != UINT32_MAX) \
4762 fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##a_Seg; \
4763 } \
4764 (a_uVmcsVar) = 0; \
4765 } \
4766 } while (0)
4767 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
4768 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
4769 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
4770 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
4771#undef VMXLOCAL_ADJUST_HOST_SEG
4772 }
4773 }
4774
4775 /* Verification based on Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers" */
4776 Assert(!(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelTR & X86_SEL_RPL)); Assert(!(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelTR & X86_SEL_LDT)); Assert(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelTR);
4777 Assert(!(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelCS & X86_SEL_RPL)); Assert(!(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelCS & X86_SEL_LDT)); Assert(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelCS);
4778 Assert(!(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelSS & X86_SEL_RPL)); Assert(!(pVCpu->hmr0.s.vmx.RestoreHost.uHostSelSS & X86_SEL_LDT));
4779 Assert(!(uSelDS & X86_SEL_RPL)); Assert(!(uSelDS & X86_SEL_LDT));
4780 Assert(!(uSelES & X86_SEL_RPL)); Assert(!(uSelES & X86_SEL_LDT));
4781 Assert(!(uSelFS & X86_SEL_RPL)); Assert(!(uSelFS & X86_SEL_LDT));
4782 Assert(!(uSelGS & X86_SEL_RPL)); Assert(!(uSelGS & X86_SEL_LDT));
4783
4784 /*
4785 * Determine if we need to manually need to restore the GDTR and IDTR limits as VT-x zaps
4786 * them to the maximum limit (0xffff) on every VM-exit.
4787 */
4788 if (pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr.cb != 0xffff)
4789 fRestoreHostFlags |= VMX_RESTORE_HOST_GDTR;
4790
4791 /*
4792 * IDT limit is effectively capped at 0xfff. (See Intel spec. 6.14.1 "64-Bit Mode IDT" and
4793 * Intel spec. 6.2 "Exception and Interrupt Vectors".) Therefore if the host has the limit
4794 * as 0xfff, VT-x bloating the limit to 0xffff shouldn't cause any different CPU behavior.
4795 * However, several hosts either insists on 0xfff being the limit (Windows Patch Guard) or
4796 * uses the limit for other purposes (darwin puts the CPU ID in there but botches sidt
4797 * alignment in at least one consumer). So, we're only allowing the IDTR.LIMIT to be left
4798 * at 0xffff on hosts where we are sure it won't cause trouble.
4799 */
4800#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
4801 if (pVCpu->hmr0.s.vmx.RestoreHost.HostIdtr.cb < 0x0fff)
4802#else
4803 if (pVCpu->hmr0.s.vmx.RestoreHost.HostIdtr.cb != 0xffff)
4804#endif
4805 fRestoreHostFlags |= VMX_RESTORE_HOST_IDTR;
4806
4807 /*
4808 * Host TR base. Verify that TR selector doesn't point past the GDT. Masking off the TI
4809 * and RPL bits is effectively what the CPU does for "scaling by 8". TI is always 0 and
4810 * RPL should be too in most cases.
4811 */
4812 RTSEL const uSelTR = pVCpu->hmr0.s.vmx.RestoreHost.uHostSelTR;
4813 AssertMsgReturn((uSelTR | X86_SEL_RPL_LDT) <= pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr.cb,
4814 ("TR selector exceeds limit. TR=%RTsel cbGdt=%#x\n", uSelTR, pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr.cb),
4815 VERR_VMX_INVALID_HOST_STATE);
4816
4817 PCX86DESCHC pDesc = (PCX86DESCHC)(pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr.uAddr + (uSelTR & X86_SEL_MASK));
4818 uintptr_t const uTRBase = X86DESC64_BASE(pDesc);
4819
4820 /*
4821 * VT-x unconditionally restores the TR limit to 0x67 and type to 11 (32-bit busy TSS) on
4822 * all VM-exits. The type is the same for 64-bit busy TSS[1]. The limit needs manual
4823 * restoration if the host has something else. Task switching is not supported in 64-bit
4824 * mode[2], but the limit still matters as IOPM is supported in 64-bit mode. Restoring the
4825 * limit lazily while returning to ring-3 is safe because IOPM is not applicable in ring-0.
4826 *
4827 * [1] See Intel spec. 3.5 "System Descriptor Types".
4828 * [2] See Intel spec. 7.2.3 "TSS Descriptor in 64-bit mode".
4829 */
4830 Assert(pDesc->System.u4Type == 11);
4831 if ( pDesc->System.u16LimitLow != 0x67
4832 || pDesc->System.u4LimitHigh)
4833 {
4834 fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_TR;
4835
4836 /* If the host has made GDT read-only, we would need to temporarily toggle CR0.WP before writing the GDT. */
4837 if (g_fHmHostKernelFeatures & SUPKERNELFEATURES_GDT_READ_ONLY)
4838 fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_READ_ONLY;
4839 if (g_fHmHostKernelFeatures & SUPKERNELFEATURES_GDT_NEED_WRITABLE)
4840 {
4841 /* The GDT is read-only but the writable GDT is available. */
4842 fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_NEED_WRITABLE;
4843 pVCpu->hmr0.s.vmx.RestoreHost.HostGdtrRw.cb = pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr.cb;
4844 int rc = SUPR0GetCurrentGdtRw(&pVCpu->hmr0.s.vmx.RestoreHost.HostGdtrRw.uAddr);
4845 AssertRCReturn(rc, rc);
4846 }
4847 }
4848
4849 pVCpu->hmr0.s.vmx.fRestoreHostFlags = fRestoreHostFlags;
4850
4851 /*
4852 * Do all the VMCS updates in one block to assist nested virtualization.
4853 */
4854 int rc;
4855 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_CS_SEL, pVCpu->hmr0.s.vmx.RestoreHost.uHostSelCS); AssertRC(rc);
4856 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_SS_SEL, pVCpu->hmr0.s.vmx.RestoreHost.uHostSelSS); AssertRC(rc);
4857 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_DS_SEL, uSelDS); AssertRC(rc);
4858 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_ES_SEL, uSelES); AssertRC(rc);
4859 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_FS_SEL, uSelFS); AssertRC(rc);
4860 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_GS_SEL, uSelGS); AssertRC(rc);
4861 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_TR_SEL, pVCpu->hmr0.s.vmx.RestoreHost.uHostSelTR); AssertRC(rc);
4862 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GDTR_BASE, pVCpu->hmr0.s.vmx.RestoreHost.HostGdtr.uAddr); AssertRC(rc);
4863 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_IDTR_BASE, pVCpu->hmr0.s.vmx.RestoreHost.HostIdtr.uAddr); AssertRC(rc);
4864 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_TR_BASE, uTRBase); AssertRC(rc);
4865 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_FS_BASE, pVCpu->hmr0.s.vmx.RestoreHost.uHostFSBase); AssertRC(rc);
4866 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GS_BASE, pVCpu->hmr0.s.vmx.RestoreHost.uHostGSBase); AssertRC(rc);
4867
4868 return VINF_SUCCESS;
4869}
4870
4871
4872/**
4873 * Exports certain host MSRs in the VM-exit MSR-load area and some in the
4874 * host-state area of the VMCS.
4875 *
4876 * These MSRs will be automatically restored on the host after every successful
4877 * VM-exit.
4878 *
4879 * @param pVCpu The cross context virtual CPU structure.
4880 *
4881 * @remarks No-long-jump zone!!!
4882 */
4883static void hmR0VmxExportHostMsrs(PVMCPUCC pVCpu)
4884{
4885 AssertPtr(pVCpu);
4886
4887 /*
4888 * Save MSRs that we restore lazily (due to preemption or transition to ring-3)
4889 * rather than swapping them on every VM-entry.
4890 */
4891 hmR0VmxLazySaveHostMsrs(pVCpu);
4892
4893 /*
4894 * Host Sysenter MSRs.
4895 */
4896 int rc = VMXWriteVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS)); AssertRC(rc);
4897 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP)); AssertRC(rc);
4898 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP)); AssertRC(rc);
4899
4900 /*
4901 * Host EFER MSR.
4902 *
4903 * If the CPU supports the newer VMCS controls for managing EFER, use it. Otherwise it's
4904 * done as part of auto-load/store MSR area in the VMCS, see hmR0VmxExportGuestMsrs().
4905 */
4906 if (g_fHmVmxSupportsVmcsEfer)
4907 {
4908 rc = VMXWriteVmcs64(VMX_VMCS64_HOST_EFER_FULL, g_uHmVmxHostMsrEfer);
4909 AssertRC(rc);
4910 }
4911
4912 /** @todo IA32_PERF_GLOBALCTRL, IA32_PAT also see
4913 * hmR0VmxExportGuestEntryExitCtls(). */
4914}
4915
4916
4917/**
4918 * Figures out if we need to swap the EFER MSR which is particularly expensive.
4919 *
4920 * We check all relevant bits. For now, that's everything besides LMA/LME, as
4921 * these two bits are handled by VM-entry, see hmR0VMxExportGuestEntryExitCtls().
4922 *
4923 * @returns true if we need to load guest EFER, false otherwise.
4924 * @param pVCpu The cross context virtual CPU structure.
4925 * @param pVmxTransient The VMX-transient structure.
4926 *
4927 * @remarks Requires EFER, CR4.
4928 * @remarks No-long-jump zone!!!
4929 */
4930static bool hmR0VmxShouldSwapEferMsr(PCVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
4931{
4932#ifdef HMVMX_ALWAYS_SWAP_EFER
4933 RT_NOREF2(pVCpu, pVmxTransient);
4934 return true;
4935#else
4936 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4937 uint64_t const u64HostEfer = g_uHmVmxHostMsrEfer;
4938 uint64_t const u64GuestEfer = pCtx->msrEFER;
4939
4940# ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4941 /*
4942 * For nested-guests, we shall honor swapping the EFER MSR when requested by
4943 * the nested-guest.
4944 */
4945 if ( pVmxTransient->fIsNestedGuest
4946 && ( CPUMIsGuestVmxEntryCtlsSet(pCtx, VMX_ENTRY_CTLS_LOAD_EFER_MSR)
4947 || CPUMIsGuestVmxExitCtlsSet(pCtx, VMX_EXIT_CTLS_SAVE_EFER_MSR)
4948 || CPUMIsGuestVmxExitCtlsSet(pCtx, VMX_EXIT_CTLS_LOAD_EFER_MSR)))
4949 return true;
4950# else
4951 RT_NOREF(pVmxTransient);
4952#endif
4953
4954 /*
4955 * For 64-bit guests, if EFER.SCE bit differs, we need to swap the EFER MSR
4956 * to ensure that the guest's SYSCALL behaviour isn't broken, see @bugref{7386}.
4957 */
4958 if ( CPUMIsGuestInLongModeEx(pCtx)
4959 && (u64GuestEfer & MSR_K6_EFER_SCE) != (u64HostEfer & MSR_K6_EFER_SCE))
4960 return true;
4961
4962 /*
4963 * If the guest uses PAE and EFER.NXE bit differs, we need to swap the EFER MSR
4964 * as it affects guest paging. 64-bit paging implies CR4.PAE as well.
4965 *
4966 * See Intel spec. 4.5 "IA-32e Paging".
4967 * See Intel spec. 4.1.1 "Three Paging Modes".
4968 *
4969 * Verify that we always intercept CR4.PAE and CR0.PG bits, so we don't need to
4970 * import CR4 and CR0 from the VMCS here as those bits are always up to date.
4971 */
4972 Assert(hmR0VmxGetFixedCr4Mask(pVCpu) & X86_CR4_PAE);
4973 Assert(hmR0VmxGetFixedCr0Mask(pVCpu) & X86_CR0_PG);
4974 if ( (pCtx->cr4 & X86_CR4_PAE)
4975 && (pCtx->cr0 & X86_CR0_PG))
4976 {
4977 /*
4978 * If nested paging is not used, verify that the guest paging mode matches the
4979 * shadow paging mode which is/will be placed in the VMCS (which is what will
4980 * actually be used while executing the guest and not the CR4 shadow value).
4981 */
4982 AssertMsg( pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging
4983 || pVCpu->hm.s.enmShadowMode == PGMMODE_PAE
4984 || pVCpu->hm.s.enmShadowMode == PGMMODE_PAE_NX
4985 || pVCpu->hm.s.enmShadowMode == PGMMODE_AMD64
4986 || pVCpu->hm.s.enmShadowMode == PGMMODE_AMD64_NX,
4987 ("enmShadowMode=%u\n", pVCpu->hm.s.enmShadowMode));
4988 if ((u64GuestEfer & MSR_K6_EFER_NXE) != (u64HostEfer & MSR_K6_EFER_NXE))
4989 {
4990 /* Verify that the host is NX capable. */
4991 Assert(pVCpu->CTX_SUFF(pVM)->cpum.ro.HostFeatures.fNoExecute);
4992 return true;
4993 }
4994 }
4995
4996 return false;
4997#endif
4998}
4999
5000
5001/**
5002 * Exports the guest state with appropriate VM-entry and VM-exit controls in the
5003 * VMCS.
5004 *
5005 * This is typically required when the guest changes paging mode.
5006 *
5007 * @returns VBox status code.
5008 * @param pVCpu The cross context virtual CPU structure.
5009 * @param pVmxTransient The VMX-transient structure.
5010 *
5011 * @remarks Requires EFER.
5012 * @remarks No-long-jump zone!!!
5013 */
5014static int hmR0VmxExportGuestEntryExitCtls(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5015{
5016 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS)
5017 {
5018 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5019 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5020
5021 /*
5022 * VM-entry controls.
5023 */
5024 {
5025 uint32_t fVal = g_HmMsrs.u.vmx.EntryCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
5026 uint32_t const fZap = g_HmMsrs.u.vmx.EntryCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
5027
5028 /*
5029 * Load the guest debug controls (DR7 and IA32_DEBUGCTL MSR) on VM-entry.
5030 * The first VT-x capable CPUs only supported the 1-setting of this bit.
5031 *
5032 * For nested-guests, this is a mandatory VM-entry control. It's also
5033 * required because we do not want to leak host bits to the nested-guest.
5034 */
5035 fVal |= VMX_ENTRY_CTLS_LOAD_DEBUG;
5036
5037 /*
5038 * Set if the guest is in long mode. This will set/clear the EFER.LMA bit on VM-entry.
5039 *
5040 * For nested-guests, the "IA-32e mode guest" control we initialize with what is
5041 * required to get the nested-guest working with hardware-assisted VMX execution.
5042 * It depends on the nested-guest's IA32_EFER.LMA bit. Remember, a nested hypervisor
5043 * can skip intercepting changes to the EFER MSR. This is why it needs to be done
5044 * here rather than while merging the guest VMCS controls.
5045 */
5046 if (CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
5047 {
5048 Assert(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_LME);
5049 fVal |= VMX_ENTRY_CTLS_IA32E_MODE_GUEST;
5050 }
5051 else
5052 Assert(!(fVal & VMX_ENTRY_CTLS_IA32E_MODE_GUEST));
5053
5054 /*
5055 * If the CPU supports the newer VMCS controls for managing guest/host EFER, use it.
5056 *
5057 * For nested-guests, we use the "load IA32_EFER" if the hardware supports it,
5058 * regardless of whether the nested-guest VMCS specifies it because we are free to
5059 * load whatever MSRs we require and we do not need to modify the guest visible copy
5060 * of the VM-entry MSR load area.
5061 */
5062 if ( g_fHmVmxSupportsVmcsEfer
5063 && hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
5064 fVal |= VMX_ENTRY_CTLS_LOAD_EFER_MSR;
5065 else
5066 Assert(!(fVal & VMX_ENTRY_CTLS_LOAD_EFER_MSR));
5067
5068 /*
5069 * The following should -not- be set (since we're not in SMM mode):
5070 * - VMX_ENTRY_CTLS_ENTRY_TO_SMM
5071 * - VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON
5072 */
5073
5074 /** @todo VMX_ENTRY_CTLS_LOAD_PERF_MSR,
5075 * VMX_ENTRY_CTLS_LOAD_PAT_MSR. */
5076
5077 if ((fVal & fZap) == fVal)
5078 { /* likely */ }
5079 else
5080 {
5081 Log4Func(("Invalid VM-entry controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
5082 g_HmMsrs.u.vmx.EntryCtls.n.allowed0, fVal, fZap));
5083 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_ENTRY;
5084 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
5085 }
5086
5087 /* Commit it to the VMCS. */
5088 if (pVmcsInfo->u32EntryCtls != fVal)
5089 {
5090 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY, fVal);
5091 AssertRC(rc);
5092 pVmcsInfo->u32EntryCtls = fVal;
5093 }
5094 }
5095
5096 /*
5097 * VM-exit controls.
5098 */
5099 {
5100 uint32_t fVal = g_HmMsrs.u.vmx.ExitCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
5101 uint32_t const fZap = g_HmMsrs.u.vmx.ExitCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
5102
5103 /*
5104 * Save debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x CPUs only
5105 * supported the 1-setting of this bit.
5106 *
5107 * For nested-guests, we set the "save debug controls" as the converse
5108 * "load debug controls" is mandatory for nested-guests anyway.
5109 */
5110 fVal |= VMX_EXIT_CTLS_SAVE_DEBUG;
5111
5112 /*
5113 * Set the host long mode active (EFER.LMA) bit (which Intel calls
5114 * "Host address-space size") if necessary. On VM-exit, VT-x sets both the
5115 * host EFER.LMA and EFER.LME bit to this value. See assertion in
5116 * hmR0VmxExportHostMsrs().
5117 *
5118 * For nested-guests, we always set this bit as we do not support 32-bit
5119 * hosts.
5120 */
5121 fVal |= VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE;
5122
5123 /*
5124 * If the VMCS EFER MSR fields are supported by the hardware, we use it.
5125 *
5126 * For nested-guests, we should use the "save IA32_EFER" control if we also
5127 * used the "load IA32_EFER" control while exporting VM-entry controls.
5128 */
5129 if ( g_fHmVmxSupportsVmcsEfer
5130 && hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
5131 {
5132 fVal |= VMX_EXIT_CTLS_SAVE_EFER_MSR
5133 | VMX_EXIT_CTLS_LOAD_EFER_MSR;
5134 }
5135
5136 /*
5137 * Enable saving of the VMX-preemption timer value on VM-exit.
5138 * For nested-guests, currently not exposed/used.
5139 */
5140 /** @todo r=bird: Measure performance hit because of this vs. always rewriting
5141 * the timer value. */
5142 if (pVM->hmr0.s.vmx.fUsePreemptTimer)
5143 {
5144 Assert(g_HmMsrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER);
5145 fVal |= VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER;
5146 }
5147
5148 /* Don't acknowledge external interrupts on VM-exit. We want to let the host do that. */
5149 Assert(!(fVal & VMX_EXIT_CTLS_ACK_EXT_INT));
5150
5151 /** @todo VMX_EXIT_CTLS_LOAD_PERF_MSR,
5152 * VMX_EXIT_CTLS_SAVE_PAT_MSR,
5153 * VMX_EXIT_CTLS_LOAD_PAT_MSR. */
5154
5155 if ((fVal & fZap) == fVal)
5156 { /* likely */ }
5157 else
5158 {
5159 Log4Func(("Invalid VM-exit controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%R#X32\n",
5160 g_HmMsrs.u.vmx.ExitCtls.n.allowed0, fVal, fZap));
5161 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_EXIT;
5162 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
5163 }
5164
5165 /* Commit it to the VMCS. */
5166 if (pVmcsInfo->u32ExitCtls != fVal)
5167 {
5168 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT, fVal);
5169 AssertRC(rc);
5170 pVmcsInfo->u32ExitCtls = fVal;
5171 }
5172 }
5173
5174 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
5175 }
5176 return VINF_SUCCESS;
5177}
5178
5179
5180/**
5181 * Sets the TPR threshold in the VMCS.
5182 *
5183 * @param pVmcsInfo The VMCS info. object.
5184 * @param u32TprThreshold The TPR threshold (task-priority class only).
5185 */
5186DECLINLINE(void) hmR0VmxApicSetTprThreshold(PVMXVMCSINFO pVmcsInfo, uint32_t u32TprThreshold)
5187{
5188 Assert(!(u32TprThreshold & ~VMX_TPR_THRESHOLD_MASK)); /* Bits 31:4 MBZ. */
5189 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
5190 RT_NOREF(pVmcsInfo);
5191 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
5192 AssertRC(rc);
5193}
5194
5195
5196/**
5197 * Exports the guest APIC TPR state into the VMCS.
5198 *
5199 * @param pVCpu The cross context virtual CPU structure.
5200 * @param pVmxTransient The VMX-transient structure.
5201 *
5202 * @remarks No-long-jump zone!!!
5203 */
5204static void hmR0VmxExportGuestApicTpr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5205{
5206 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_APIC_TPR)
5207 {
5208 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_APIC_TPR);
5209
5210 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5211 if (!pVmxTransient->fIsNestedGuest)
5212 {
5213 if ( PDMHasApic(pVCpu->CTX_SUFF(pVM))
5214 && APICIsEnabled(pVCpu))
5215 {
5216 /*
5217 * Setup TPR shadowing.
5218 */
5219 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
5220 {
5221 bool fPendingIntr = false;
5222 uint8_t u8Tpr = 0;
5223 uint8_t u8PendingIntr = 0;
5224 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
5225 AssertRC(rc);
5226
5227 /*
5228 * If there are interrupts pending but masked by the TPR, instruct VT-x to
5229 * cause a TPR-below-threshold VM-exit when the guest lowers its TPR below the
5230 * priority of the pending interrupt so we can deliver the interrupt. If there
5231 * are no interrupts pending, set threshold to 0 to not cause any
5232 * TPR-below-threshold VM-exits.
5233 */
5234 uint32_t u32TprThreshold = 0;
5235 if (fPendingIntr)
5236 {
5237 /* Bits 3:0 of the TPR threshold field correspond to bits 7:4 of the TPR
5238 (which is the Task-Priority Class). */
5239 const uint8_t u8PendingPriority = u8PendingIntr >> 4;
5240 const uint8_t u8TprPriority = u8Tpr >> 4;
5241 if (u8PendingPriority <= u8TprPriority)
5242 u32TprThreshold = u8PendingPriority;
5243 }
5244
5245 hmR0VmxApicSetTprThreshold(pVmcsInfo, u32TprThreshold);
5246 }
5247 }
5248 }
5249 /* else: the TPR threshold has already been updated while merging the nested-guest VMCS. */
5250 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_APIC_TPR);
5251 }
5252}
5253
5254
5255/**
5256 * Gets the guest interruptibility-state and updates related force-flags.
5257 *
5258 * @returns Guest's interruptibility-state.
5259 * @param pVCpu The cross context virtual CPU structure.
5260 *
5261 * @remarks No-long-jump zone!!!
5262 */
5263static uint32_t hmR0VmxGetGuestIntrStateAndUpdateFFs(PVMCPUCC pVCpu)
5264{
5265 /*
5266 * Check if we should inhibit interrupt delivery due to instructions like STI and MOV SS.
5267 */
5268 uint32_t fIntrState = 0;
5269 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
5270 {
5271 /* If inhibition is active, RIP and RFLAGS should've been imported from the VMCS already. */
5272 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
5273
5274 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5275 if (pCtx->rip == EMGetInhibitInterruptsPC(pVCpu))
5276 {
5277 if (pCtx->eflags.Bits.u1IF)
5278 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
5279 else
5280 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS;
5281 }
5282 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
5283 {
5284 /*
5285 * We can clear the inhibit force flag as even if we go back to the recompiler
5286 * without executing guest code in VT-x, the flag's condition to be cleared is
5287 * met and thus the cleared state is correct.
5288 */
5289 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
5290 }
5291 }
5292
5293 /*
5294 * Check if we should inhibit NMI delivery.
5295 */
5296 if (CPUMIsGuestNmiBlocking(pVCpu))
5297 fIntrState |= VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI;
5298
5299 /*
5300 * Validate.
5301 */
5302#ifdef VBOX_STRICT
5303 /* We don't support block-by-SMI yet.*/
5304 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI));
5305
5306 /* Block-by-STI must not be set when interrupts are disabled. */
5307 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
5308 {
5309 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
5310 Assert(pVCpu->cpum.GstCtx.eflags.u & X86_EFL_IF);
5311 }
5312#endif
5313
5314 return fIntrState;
5315}
5316
5317
5318/**
5319 * Exports the exception intercepts required for guest execution in the VMCS.
5320 *
5321 * @param pVCpu The cross context virtual CPU structure.
5322 * @param pVmxTransient The VMX-transient structure.
5323 *
5324 * @remarks No-long-jump zone!!!
5325 */
5326static void hmR0VmxExportGuestXcptIntercepts(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5327{
5328 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_XCPT_INTERCEPTS)
5329 {
5330 /* When executing a nested-guest, we do not need to trap GIM hypercalls by intercepting #UD. */
5331 if ( !pVmxTransient->fIsNestedGuest
5332 && pVCpu->hm.s.fGIMTrapXcptUD)
5333 hmR0VmxAddXcptIntercept(pVmxTransient, X86_XCPT_UD);
5334 else
5335 hmR0VmxRemoveXcptIntercept(pVCpu, pVmxTransient, X86_XCPT_UD);
5336
5337 /* Other exception intercepts are handled elsewhere, e.g. while exporting guest CR0. */
5338 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_XCPT_INTERCEPTS);
5339 }
5340}
5341
5342
5343/**
5344 * Exports the guest's RIP into the guest-state area in the VMCS.
5345 *
5346 * @param pVCpu The cross context virtual CPU structure.
5347 *
5348 * @remarks No-long-jump zone!!!
5349 */
5350static void hmR0VmxExportGuestRip(PVMCPUCC pVCpu)
5351{
5352 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RIP)
5353 {
5354 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP);
5355
5356 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RIP, pVCpu->cpum.GstCtx.rip);
5357 AssertRC(rc);
5358
5359 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RIP);
5360 Log4Func(("rip=%#RX64\n", pVCpu->cpum.GstCtx.rip));
5361 }
5362}
5363
5364
5365/**
5366 * Exports the guest's RSP into the guest-state area in the VMCS.
5367 *
5368 * @param pVCpu The cross context virtual CPU structure.
5369 *
5370 * @remarks No-long-jump zone!!!
5371 */
5372static void hmR0VmxExportGuestRsp(PVMCPUCC pVCpu)
5373{
5374 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RSP)
5375 {
5376 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RSP);
5377
5378 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RSP, pVCpu->cpum.GstCtx.rsp);
5379 AssertRC(rc);
5380
5381 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RSP);
5382 Log4Func(("rsp=%#RX64\n", pVCpu->cpum.GstCtx.rsp));
5383 }
5384}
5385
5386
5387/**
5388 * Exports the guest's RFLAGS into the guest-state area in the VMCS.
5389 *
5390 * @param pVCpu The cross context virtual CPU structure.
5391 * @param pVmxTransient The VMX-transient structure.
5392 *
5393 * @remarks No-long-jump zone!!!
5394 */
5395static void hmR0VmxExportGuestRflags(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5396{
5397 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RFLAGS)
5398 {
5399 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
5400
5401 /* Intel spec. 2.3.1 "System Flags and Fields in IA-32e Mode" claims the upper 32-bits of RFLAGS are reserved (MBZ).
5402 Let us assert it as such and use 32-bit VMWRITE. */
5403 Assert(!RT_HI_U32(pVCpu->cpum.GstCtx.rflags.u64));
5404 X86EFLAGS fEFlags = pVCpu->cpum.GstCtx.eflags;
5405 Assert(fEFlags.u32 & X86_EFL_RA1_MASK);
5406 Assert(!(fEFlags.u32 & ~(X86_EFL_1 | X86_EFL_LIVE_MASK)));
5407
5408 /*
5409 * If we're emulating real-mode using Virtual 8086 mode, save the real-mode eflags so
5410 * we can restore them on VM-exit. Modify the real-mode guest's eflags so that VT-x
5411 * can run the real-mode guest code under Virtual 8086 mode.
5412 */
5413 PVMXVMCSINFOSHARED pVmcsInfo = pVmxTransient->pVmcsInfo->pShared;
5414 if (pVmcsInfo->RealMode.fRealOnV86Active)
5415 {
5416 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
5417 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
5418 Assert(!pVmxTransient->fIsNestedGuest);
5419 pVmcsInfo->RealMode.Eflags.u32 = fEFlags.u32; /* Save the original eflags of the real-mode guest. */
5420 fEFlags.Bits.u1VM = 1; /* Set the Virtual 8086 mode bit. */
5421 fEFlags.Bits.u2IOPL = 0; /* Change IOPL to 0, otherwise certain instructions won't fault. */
5422 }
5423
5424 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RFLAGS, fEFlags.u32);
5425 AssertRC(rc);
5426
5427 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RFLAGS);
5428 Log4Func(("eflags=%#RX32\n", fEFlags.u32));
5429 }
5430}
5431
5432
5433#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5434/**
5435 * Copies the nested-guest VMCS to the shadow VMCS.
5436 *
5437 * @returns VBox status code.
5438 * @param pVCpu The cross context virtual CPU structure.
5439 * @param pVmcsInfo The VMCS info. object.
5440 *
5441 * @remarks No-long-jump zone!!!
5442 */
5443static int hmR0VmxCopyNstGstToShadowVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5444{
5445 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5446 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5447
5448 /*
5449 * Disable interrupts so we don't get preempted while the shadow VMCS is the
5450 * current VMCS, as we may try saving guest lazy MSRs.
5451 *
5452 * Strictly speaking the lazy MSRs are not in the VMCS, but I'd rather not risk
5453 * calling the import VMCS code which is currently performing the guest MSR reads
5454 * (on 64-bit hosts) and accessing the auto-load/store MSR area on 32-bit hosts
5455 * and the rest of the VMX leave session machinery.
5456 */
5457 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
5458
5459 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5460 if (RT_SUCCESS(rc))
5461 {
5462 /*
5463 * Copy all guest read/write VMCS fields.
5464 *
5465 * We don't check for VMWRITE failures here for performance reasons and
5466 * because they are not expected to fail, barring irrecoverable conditions
5467 * like hardware errors.
5468 */
5469 uint32_t const cShadowVmcsFields = pVM->hmr0.s.vmx.cShadowVmcsFields;
5470 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5471 {
5472 uint64_t u64Val;
5473 uint32_t const uVmcsField = pVM->hmr0.s.vmx.paShadowVmcsFields[i];
5474 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5475 VMXWriteVmcs64(uVmcsField, u64Val);
5476 }
5477
5478 /*
5479 * If the host CPU supports writing all VMCS fields, copy the guest read-only
5480 * VMCS fields, so the guest can VMREAD them without causing a VM-exit.
5481 */
5482 if (g_HmMsrs.u.vmx.u64Misc & VMX_MISC_VMWRITE_ALL)
5483 {
5484 uint32_t const cShadowVmcsRoFields = pVM->hmr0.s.vmx.cShadowVmcsRoFields;
5485 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
5486 {
5487 uint64_t u64Val;
5488 uint32_t const uVmcsField = pVM->hmr0.s.vmx.paShadowVmcsRoFields[i];
5489 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5490 VMXWriteVmcs64(uVmcsField, u64Val);
5491 }
5492 }
5493
5494 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5495 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5496 }
5497
5498 ASMSetFlags(fEFlags);
5499 return rc;
5500}
5501
5502
5503/**
5504 * Copies the shadow VMCS to the nested-guest VMCS.
5505 *
5506 * @returns VBox status code.
5507 * @param pVCpu The cross context virtual CPU structure.
5508 * @param pVmcsInfo The VMCS info. object.
5509 *
5510 * @remarks Called with interrupts disabled.
5511 */
5512static int hmR0VmxCopyShadowToNstGstVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5513{
5514 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5515 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5516 PVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5517
5518 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5519 if (RT_SUCCESS(rc))
5520 {
5521 /*
5522 * Copy guest read/write fields from the shadow VMCS.
5523 * Guest read-only fields cannot be modified, so no need to copy them.
5524 *
5525 * We don't check for VMREAD failures here for performance reasons and
5526 * because they are not expected to fail, barring irrecoverable conditions
5527 * like hardware errors.
5528 */
5529 uint32_t const cShadowVmcsFields = pVM->hmr0.s.vmx.cShadowVmcsFields;
5530 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5531 {
5532 uint64_t u64Val;
5533 uint32_t const uVmcsField = pVM->hmr0.s.vmx.paShadowVmcsFields[i];
5534 VMXReadVmcs64(uVmcsField, &u64Val);
5535 IEMWriteVmxVmcsField(pVmcsNstGst, uVmcsField, u64Val);
5536 }
5537
5538 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5539 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5540 }
5541 return rc;
5542}
5543
5544
5545/**
5546 * Enables VMCS shadowing for the given VMCS info. object.
5547 *
5548 * @param pVmcsInfo The VMCS info. object.
5549 *
5550 * @remarks No-long-jump zone!!!
5551 */
5552static void hmR0VmxEnableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5553{
5554 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5555 if (!(uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING))
5556 {
5557 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
5558 uProcCtls2 |= VMX_PROC_CTLS2_VMCS_SHADOWING;
5559 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5560 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, pVmcsInfo->HCPhysShadowVmcs); AssertRC(rc);
5561 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5562 pVmcsInfo->u64VmcsLinkPtr = pVmcsInfo->HCPhysShadowVmcs;
5563 Log4Func(("Enabled\n"));
5564 }
5565}
5566
5567
5568/**
5569 * Disables VMCS shadowing for the given VMCS info. object.
5570 *
5571 * @param pVmcsInfo The VMCS info. object.
5572 *
5573 * @remarks No-long-jump zone!!!
5574 */
5575static void hmR0VmxDisableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5576{
5577 /*
5578 * We want all VMREAD and VMWRITE instructions to cause VM-exits, so we clear the
5579 * VMCS shadowing control. However, VM-entry requires the shadow VMCS indicator bit
5580 * to match the VMCS shadowing control if the VMCS link pointer is not NIL_RTHCPHYS.
5581 * Hence, we must also reset the VMCS link pointer to ensure VM-entry does not fail.
5582 *
5583 * See Intel spec. 26.2.1.1 "VM-Execution Control Fields".
5584 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5585 */
5586 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5587 if (uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
5588 {
5589 uProcCtls2 &= ~VMX_PROC_CTLS2_VMCS_SHADOWING;
5590 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5591 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS); AssertRC(rc);
5592 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5593 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
5594 Log4Func(("Disabled\n"));
5595 }
5596}
5597#endif
5598
5599
5600/**
5601 * Exports the guest hardware-virtualization state.
5602 *
5603 * @returns VBox status code.
5604 * @param pVCpu The cross context virtual CPU structure.
5605 * @param pVmxTransient The VMX-transient structure.
5606 *
5607 * @remarks No-long-jump zone!!!
5608 */
5609static int hmR0VmxExportGuestHwvirtState(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5610{
5611 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_HWVIRT)
5612 {
5613#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5614 /*
5615 * Check if the VMX feature is exposed to the guest and if the host CPU supports
5616 * VMCS shadowing.
5617 */
5618 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fUseVmcsShadowing)
5619 {
5620 /*
5621 * If the nested hypervisor has loaded a current VMCS and is in VMX root mode,
5622 * copy the nested hypervisor's current VMCS into the shadow VMCS and enable
5623 * VMCS shadowing to skip intercepting some or all VMREAD/VMWRITE VM-exits.
5624 *
5625 * We check for VMX root mode here in case the guest executes VMXOFF without
5626 * clearing the current VMCS pointer and our VMXOFF instruction emulation does
5627 * not clear the current VMCS pointer.
5628 */
5629 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5630 if ( CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx)
5631 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx)
5632 && CPUMIsGuestVmxCurrentVmcsValid(&pVCpu->cpum.GstCtx))
5633 {
5634 /* Paranoia. */
5635 Assert(!pVmxTransient->fIsNestedGuest);
5636
5637 /*
5638 * For performance reasons, also check if the nested hypervisor's current VMCS
5639 * was newly loaded or modified before copying it to the shadow VMCS.
5640 */
5641 if (!pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs)
5642 {
5643 int rc = hmR0VmxCopyNstGstToShadowVmcs(pVCpu, pVmcsInfo);
5644 AssertRCReturn(rc, rc);
5645 pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs = true;
5646 }
5647 hmR0VmxEnableVmcsShadowing(pVmcsInfo);
5648 }
5649 else
5650 hmR0VmxDisableVmcsShadowing(pVmcsInfo);
5651 }
5652#else
5653 NOREF(pVmxTransient);
5654#endif
5655 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_HWVIRT);
5656 }
5657 return VINF_SUCCESS;
5658}
5659
5660
5661/**
5662 * Exports the guest CR0 control register into the guest-state area in the VMCS.
5663 *
5664 * The guest FPU state is always pre-loaded hence we don't need to bother about
5665 * sharing FPU related CR0 bits between the guest and host.
5666 *
5667 * @returns VBox status code.
5668 * @param pVCpu The cross context virtual CPU structure.
5669 * @param pVmxTransient The VMX-transient structure.
5670 *
5671 * @remarks No-long-jump zone!!!
5672 */
5673static int hmR0VmxExportGuestCR0(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5674{
5675 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR0)
5676 {
5677 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5678 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5679
5680 uint64_t fSetCr0 = g_HmMsrs.u.vmx.u64Cr0Fixed0;
5681 uint64_t const fZapCr0 = g_HmMsrs.u.vmx.u64Cr0Fixed1;
5682 if (pVM->hmr0.s.vmx.fUnrestrictedGuest)
5683 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
5684 else
5685 Assert((fSetCr0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG));
5686
5687 if (!pVmxTransient->fIsNestedGuest)
5688 {
5689 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5690 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5691 uint64_t const u64ShadowCr0 = u64GuestCr0;
5692 Assert(!RT_HI_U32(u64GuestCr0));
5693
5694 /*
5695 * Setup VT-x's view of the guest CR0.
5696 */
5697 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5698 if (pVM->hmr0.s.fNestedPaging)
5699 {
5700 if (CPUMIsGuestPagingEnabled(pVCpu))
5701 {
5702 /* The guest has paging enabled, let it access CR3 without causing a VM-exit if supported. */
5703 uProcCtls &= ~( VMX_PROC_CTLS_CR3_LOAD_EXIT
5704 | VMX_PROC_CTLS_CR3_STORE_EXIT);
5705 }
5706 else
5707 {
5708 /* The guest doesn't have paging enabled, make CR3 access cause a VM-exit to update our shadow. */
5709 uProcCtls |= VMX_PROC_CTLS_CR3_LOAD_EXIT
5710 | VMX_PROC_CTLS_CR3_STORE_EXIT;
5711 }
5712
5713 /* If we have unrestricted guest execution, we never have to intercept CR3 reads. */
5714 if (pVM->hmr0.s.vmx.fUnrestrictedGuest)
5715 uProcCtls &= ~VMX_PROC_CTLS_CR3_STORE_EXIT;
5716 }
5717 else
5718 {
5719 /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
5720 u64GuestCr0 |= X86_CR0_WP;
5721 }
5722
5723 /*
5724 * Guest FPU bits.
5725 *
5726 * Since we pre-load the guest FPU always before VM-entry there is no need to track lazy state
5727 * using CR0.TS.
5728 *
5729 * Intel spec. 23.8 "Restrictions on VMX operation" mentions that CR0.NE bit must always be
5730 * set on the first CPUs to support VT-x and no mention of with regards to UX in VM-entry checks.
5731 */
5732 u64GuestCr0 |= X86_CR0_NE;
5733
5734 /* If CR0.NE isn't set, we need to intercept #MF exceptions and report them to the guest differently. */
5735 bool const fInterceptMF = !(u64ShadowCr0 & X86_CR0_NE);
5736
5737 /*
5738 * Update exception intercepts.
5739 */
5740 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
5741 if (pVmcsInfo->pShared->RealMode.fRealOnV86Active)
5742 {
5743 Assert(PDMVmmDevHeapIsEnabled(pVM));
5744 Assert(pVM->hm.s.vmx.pRealModeTSS);
5745 uXcptBitmap |= HMVMX_REAL_MODE_XCPT_MASK;
5746 }
5747 else
5748 {
5749 /* For now, cleared here as mode-switches can happen outside HM/VT-x. See @bugref{7626#c11}. */
5750 uXcptBitmap &= ~HMVMX_REAL_MODE_XCPT_MASK;
5751 if (fInterceptMF)
5752 uXcptBitmap |= RT_BIT(X86_XCPT_MF);
5753 }
5754
5755 /* Additional intercepts for debugging, define these yourself explicitly. */
5756#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
5757 uXcptBitmap |= 0
5758 | RT_BIT(X86_XCPT_BP)
5759 | RT_BIT(X86_XCPT_DE)
5760 | RT_BIT(X86_XCPT_NM)
5761 | RT_BIT(X86_XCPT_TS)
5762 | RT_BIT(X86_XCPT_UD)
5763 | RT_BIT(X86_XCPT_NP)
5764 | RT_BIT(X86_XCPT_SS)
5765 | RT_BIT(X86_XCPT_GP)
5766 | RT_BIT(X86_XCPT_PF)
5767 | RT_BIT(X86_XCPT_MF)
5768 ;
5769#elif defined(HMVMX_ALWAYS_TRAP_PF)
5770 uXcptBitmap |= RT_BIT(X86_XCPT_PF);
5771#endif
5772 if (pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv)
5773 uXcptBitmap |= RT_BIT(X86_XCPT_GP);
5774 Assert(pVM->hmr0.s.fNestedPaging || (uXcptBitmap & RT_BIT(X86_XCPT_PF)));
5775
5776 /* Apply the hardware specified CR0 fixed bits and enable caching. */
5777 u64GuestCr0 |= fSetCr0;
5778 u64GuestCr0 &= fZapCr0;
5779 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5780
5781 /* Commit the CR0 and related fields to the guest VMCS. */
5782 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5783 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5784 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5785 {
5786 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5787 AssertRC(rc);
5788 }
5789 if (uXcptBitmap != pVmcsInfo->u32XcptBitmap)
5790 {
5791 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
5792 AssertRC(rc);
5793 }
5794
5795 /* Update our caches. */
5796 pVmcsInfo->u32ProcCtls = uProcCtls;
5797 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
5798
5799 Log4Func(("cr0=%#RX64 shadow=%#RX64 set=%#RX64 zap=%#RX64\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5800 }
5801 else
5802 {
5803 /*
5804 * With nested-guests, we may have extended the guest/host mask here since we
5805 * merged in the outer guest's mask. Thus, the merged mask can include more bits
5806 * (to read from the nested-guest CR0 read-shadow) than the nested hypervisor
5807 * originally supplied. We must copy those bits from the nested-guest CR0 into
5808 * the nested-guest CR0 read-shadow.
5809 */
5810 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5811 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5812 uint64_t const u64ShadowCr0 = CPUMGetGuestVmxMaskedCr0(&pVCpu->cpum.GstCtx, pVmcsInfo->u64Cr0Mask);
5813 Assert(!RT_HI_U32(u64GuestCr0));
5814 Assert(u64GuestCr0 & X86_CR0_NE);
5815
5816 /* Apply the hardware specified CR0 fixed bits and enable caching. */
5817 u64GuestCr0 |= fSetCr0;
5818 u64GuestCr0 &= fZapCr0;
5819 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5820
5821 /* Commit the CR0 and CR0 read-shadow to the nested-guest VMCS. */
5822 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5823 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5824
5825 Log4Func(("cr0=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5826 }
5827
5828 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR0);
5829 }
5830
5831 return VINF_SUCCESS;
5832}
5833
5834
5835/**
5836 * Exports the guest control registers (CR3, CR4) into the guest-state area
5837 * in the VMCS.
5838 *
5839 * @returns VBox strict status code.
5840 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
5841 * without unrestricted guest access and the VMMDev is not presently
5842 * mapped (e.g. EFI32).
5843 *
5844 * @param pVCpu The cross context virtual CPU structure.
5845 * @param pVmxTransient The VMX-transient structure.
5846 *
5847 * @remarks No-long-jump zone!!!
5848 */
5849static VBOXSTRICTRC hmR0VmxExportGuestCR3AndCR4(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5850{
5851 int rc = VINF_SUCCESS;
5852 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5853
5854 /*
5855 * Guest CR2.
5856 * It's always loaded in the assembler code. Nothing to do here.
5857 */
5858
5859 /*
5860 * Guest CR3.
5861 */
5862 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR3)
5863 {
5864 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR3);
5865
5866 if (pVM->hmr0.s.fNestedPaging)
5867 {
5868 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5869 pVmcsInfo->HCPhysEPTP = PGMGetHyperCR3(pVCpu);
5870
5871 /* Validate. See Intel spec. 28.2.2 "EPT Translation Mechanism" and 24.6.11 "Extended-Page-Table Pointer (EPTP)" */
5872 Assert(pVmcsInfo->HCPhysEPTP != NIL_RTHCPHYS);
5873 Assert(!(pVmcsInfo->HCPhysEPTP & UINT64_C(0xfff0000000000000)));
5874 Assert(!(pVmcsInfo->HCPhysEPTP & 0xfff));
5875
5876 /* VMX_EPT_MEMTYPE_WB support is already checked in hmR0VmxSetupTaggedTlb(). */
5877 pVmcsInfo->HCPhysEPTP |= VMX_EPT_MEMTYPE_WB
5878 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
5879
5880 /* Validate. See Intel spec. 26.2.1 "Checks on VMX Controls" */
5881 AssertMsg( ((pVmcsInfo->HCPhysEPTP >> 3) & 0x07) == 3 /* Bits 3:5 (EPT page walk length - 1) must be 3. */
5882 && ((pVmcsInfo->HCPhysEPTP >> 7) & 0x1f) == 0, /* Bits 7:11 MBZ. */
5883 ("EPTP %#RX64\n", pVmcsInfo->HCPhysEPTP));
5884 AssertMsg( !((pVmcsInfo->HCPhysEPTP >> 6) & 0x01) /* Bit 6 (EPT accessed & dirty bit). */
5885 || (g_HmMsrs.u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY),
5886 ("EPTP accessed/dirty bit not supported by CPU but set %#RX64\n", pVmcsInfo->HCPhysEPTP));
5887
5888 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, pVmcsInfo->HCPhysEPTP);
5889 AssertRC(rc);
5890
5891 uint64_t u64GuestCr3;
5892 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5893 if ( pVM->hmr0.s.vmx.fUnrestrictedGuest
5894 || CPUMIsGuestPagingEnabledEx(pCtx))
5895 {
5896 /* If the guest is in PAE mode, pass the PDPEs to VT-x using the VMCS fields. */
5897 if (CPUMIsGuestInPAEModeEx(pCtx))
5898 {
5899 rc = PGMGstGetPaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
5900 AssertRC(rc);
5901 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
5902 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
5903 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
5904 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
5905 }
5906
5907 /*
5908 * The guest's view of its CR3 is unblemished with nested paging when the
5909 * guest is using paging or we have unrestricted guest execution to handle
5910 * the guest when it's not using paging.
5911 */
5912 u64GuestCr3 = pCtx->cr3;
5913 }
5914 else
5915 {
5916 /*
5917 * The guest is not using paging, but the CPU (VT-x) has to. While the guest
5918 * thinks it accesses physical memory directly, we use our identity-mapped
5919 * page table to map guest-linear to guest-physical addresses. EPT takes care
5920 * of translating it to host-physical addresses.
5921 */
5922 RTGCPHYS GCPhys;
5923 Assert(pVM->hm.s.vmx.pNonPagingModeEPTPageTable);
5924
5925 /* We obtain it here every time as the guest could have relocated this PCI region. */
5926 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
5927 if (RT_SUCCESS(rc))
5928 { /* likely */ }
5929 else if (rc == VERR_PDM_DEV_HEAP_R3_TO_GCPHYS)
5930 {
5931 Log4Func(("VERR_PDM_DEV_HEAP_R3_TO_GCPHYS -> VINF_EM_RESCHEDULE_REM\n"));
5932 return VINF_EM_RESCHEDULE_REM; /* We cannot execute now, switch to REM/IEM till the guest maps in VMMDev. */
5933 }
5934 else
5935 AssertMsgFailedReturn(("%Rrc\n", rc), rc);
5936
5937 u64GuestCr3 = GCPhys;
5938 }
5939
5940 Log4Func(("guest_cr3=%#RX64 (GstN)\n", u64GuestCr3));
5941 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, u64GuestCr3);
5942 AssertRC(rc);
5943 }
5944 else
5945 {
5946 Assert(!pVmxTransient->fIsNestedGuest);
5947 /* Non-nested paging case, just use the hypervisor's CR3. */
5948 RTHCPHYS const HCPhysGuestCr3 = PGMGetHyperCR3(pVCpu);
5949
5950 Log4Func(("guest_cr3=%#RX64 (HstN)\n", HCPhysGuestCr3));
5951 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, HCPhysGuestCr3);
5952 AssertRC(rc);
5953 }
5954
5955 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR3);
5956 }
5957
5958 /*
5959 * Guest CR4.
5960 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
5961 */
5962 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR4)
5963 {
5964 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5965 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5966
5967 uint64_t const fSetCr4 = g_HmMsrs.u.vmx.u64Cr4Fixed0;
5968 uint64_t const fZapCr4 = g_HmMsrs.u.vmx.u64Cr4Fixed1;
5969
5970 /*
5971 * With nested-guests, we may have extended the guest/host mask here (since we
5972 * merged in the outer guest's mask, see hmR0VmxMergeVmcsNested). This means, the
5973 * mask can include more bits (to read from the nested-guest CR4 read-shadow) than
5974 * the nested hypervisor originally supplied. Thus, we should, in essence, copy
5975 * those bits from the nested-guest CR4 into the nested-guest CR4 read-shadow.
5976 */
5977 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
5978 uint64_t u64GuestCr4 = pCtx->cr4;
5979 uint64_t const u64ShadowCr4 = !pVmxTransient->fIsNestedGuest
5980 ? pCtx->cr4
5981 : CPUMGetGuestVmxMaskedCr4(pCtx, pVmcsInfo->u64Cr4Mask);
5982 Assert(!RT_HI_U32(u64GuestCr4));
5983
5984 /*
5985 * Setup VT-x's view of the guest CR4.
5986 *
5987 * If we're emulating real-mode using virtual-8086 mode, we want to redirect software
5988 * interrupts to the 8086 program interrupt handler. Clear the VME bit (the interrupt
5989 * redirection bitmap is already all 0, see hmR3InitFinalizeR0())
5990 *
5991 * See Intel spec. 20.2 "Software Interrupt Handling Methods While in Virtual-8086 Mode".
5992 */
5993 if (pVmcsInfo->pShared->RealMode.fRealOnV86Active)
5994 {
5995 Assert(pVM->hm.s.vmx.pRealModeTSS);
5996 Assert(PDMVmmDevHeapIsEnabled(pVM));
5997 u64GuestCr4 &= ~(uint64_t)X86_CR4_VME;
5998 }
5999
6000 if (pVM->hmr0.s.fNestedPaging)
6001 {
6002 if ( !CPUMIsGuestPagingEnabledEx(pCtx)
6003 && !pVM->hmr0.s.vmx.fUnrestrictedGuest)
6004 {
6005 /* We use 4 MB pages in our identity mapping page table when the guest doesn't have paging. */
6006 u64GuestCr4 |= X86_CR4_PSE;
6007 /* Our identity mapping is a 32-bit page directory. */
6008 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
6009 }
6010 /* else use guest CR4.*/
6011 }
6012 else
6013 {
6014 Assert(!pVmxTransient->fIsNestedGuest);
6015
6016 /*
6017 * The shadow paging modes and guest paging modes are different, the shadow is in accordance with the host
6018 * paging mode and thus we need to adjust VT-x's view of CR4 depending on our shadow page tables.
6019 */
6020 switch (pVCpu->hm.s.enmShadowMode)
6021 {
6022 case PGMMODE_REAL: /* Real-mode. */
6023 case PGMMODE_PROTECTED: /* Protected mode without paging. */
6024 case PGMMODE_32_BIT: /* 32-bit paging. */
6025 {
6026 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
6027 break;
6028 }
6029
6030 case PGMMODE_PAE: /* PAE paging. */
6031 case PGMMODE_PAE_NX: /* PAE paging with NX. */
6032 {
6033 u64GuestCr4 |= X86_CR4_PAE;
6034 break;
6035 }
6036
6037 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
6038 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
6039 {
6040#ifdef VBOX_WITH_64_BITS_GUESTS
6041 /* For our assumption in hmR0VmxShouldSwapEferMsr. */
6042 Assert(u64GuestCr4 & X86_CR4_PAE);
6043 break;
6044#endif
6045 }
6046 default:
6047 AssertFailed();
6048 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
6049 }
6050 }
6051
6052 /* Apply the hardware specified CR4 fixed bits (mainly CR4.VMXE). */
6053 u64GuestCr4 |= fSetCr4;
6054 u64GuestCr4 &= fZapCr4;
6055
6056 /* Commit the CR4 and CR4 read-shadow to the guest VMCS. */
6057 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR4, u64GuestCr4); AssertRC(rc);
6058 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, u64ShadowCr4); AssertRC(rc);
6059
6060 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
6061 bool const fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
6062 if (fLoadSaveGuestXcr0 != pVCpu->hmr0.s.fLoadSaveGuestXcr0)
6063 {
6064 pVCpu->hmr0.s.fLoadSaveGuestXcr0 = fLoadSaveGuestXcr0;
6065 hmR0VmxUpdateStartVmFunction(pVCpu);
6066 }
6067
6068 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR4);
6069
6070 Log4Func(("cr4=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr4, u64ShadowCr4, fSetCr4, fZapCr4));
6071 }
6072 return rc;
6073}
6074
6075
6076/**
6077 * Exports the guest debug registers into the guest-state area in the VMCS.
6078 * The guest debug bits are partially shared with the host (e.g. DR6, DR0-3).
6079 *
6080 * This also sets up whether \#DB and MOV DRx accesses cause VM-exits.
6081 *
6082 * @returns VBox status code.
6083 * @param pVCpu The cross context virtual CPU structure.
6084 * @param pVmxTransient The VMX-transient structure.
6085 *
6086 * @remarks No-long-jump zone!!!
6087 */
6088static int hmR0VmxExportSharedDebugState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6089{
6090 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
6091
6092 /** @todo NSTVMX: Figure out what we want to do with nested-guest instruction
6093 * stepping. */
6094 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6095 if (pVmxTransient->fIsNestedGuest)
6096 {
6097 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, CPUMGetGuestDR7(pVCpu));
6098 AssertRC(rc);
6099
6100 /*
6101 * We don't want to always intercept MOV DRx for nested-guests as it causes
6102 * problems when the nested hypervisor isn't intercepting them, see @bugref{10080}.
6103 * Instead, they are strictly only requested when the nested hypervisor intercepts
6104 * them -- handled while merging VMCS controls.
6105 *
6106 * If neither the outer nor the nested-hypervisor is intercepting MOV DRx,
6107 * then the nested-guest debug state should be actively loaded on the host so that
6108 * nested-guest reads its own debug registers without causing VM-exits.
6109 */
6110 if ( !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_MOV_DR_EXIT)
6111 && !CPUMIsGuestDebugStateActive(pVCpu))
6112 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
6113 return VINF_SUCCESS;
6114 }
6115
6116#ifdef VBOX_STRICT
6117 /* Validate. Intel spec. 26.3.1.1 "Checks on Guest Controls Registers, Debug Registers, MSRs" */
6118 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
6119 {
6120 /* Validate. Intel spec. 17.2 "Debug Registers", recompiler paranoia checks. */
6121 Assert((pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_MBZ_MASK | X86_DR7_RAZ_MASK)) == 0);
6122 Assert((pVCpu->cpum.GstCtx.dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK);
6123 }
6124#endif
6125
6126 bool fSteppingDB = false;
6127 bool fInterceptMovDRx = false;
6128 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
6129 if (pVCpu->hm.s.fSingleInstruction)
6130 {
6131 /* If the CPU supports the monitor trap flag, use it for single stepping in DBGF and avoid intercepting #DB. */
6132 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MONITOR_TRAP_FLAG)
6133 {
6134 uProcCtls |= VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
6135 Assert(fSteppingDB == false);
6136 }
6137 else
6138 {
6139 pVCpu->cpum.GstCtx.eflags.u32 |= X86_EFL_TF;
6140 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_RFLAGS;
6141 pVCpu->hmr0.s.fClearTrapFlag = true;
6142 fSteppingDB = true;
6143 }
6144 }
6145
6146 uint64_t u64GuestDr7;
6147 if ( fSteppingDB
6148 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
6149 {
6150 /*
6151 * Use the combined guest and host DRx values found in the hypervisor register set
6152 * because the hypervisor debugger has breakpoints active or someone is single stepping
6153 * on the host side without a monitor trap flag.
6154 *
6155 * Note! DBGF expects a clean DR6 state before executing guest code.
6156 */
6157 if (!CPUMIsHyperDebugStateActive(pVCpu))
6158 {
6159 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
6160 Assert(CPUMIsHyperDebugStateActive(pVCpu));
6161 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
6162 }
6163
6164 /* Update DR7 with the hypervisor value (other DRx registers are handled by CPUM one way or another). */
6165 u64GuestDr7 = CPUMGetHyperDR7(pVCpu);
6166 pVCpu->hmr0.s.fUsingHyperDR7 = true;
6167 fInterceptMovDRx = true;
6168 }
6169 else
6170 {
6171 /*
6172 * If the guest has enabled debug registers, we need to load them prior to
6173 * executing guest code so they'll trigger at the right time.
6174 */
6175 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DR7);
6176 if (pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
6177 {
6178 if (!CPUMIsGuestDebugStateActive(pVCpu))
6179 {
6180 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
6181 Assert(CPUMIsGuestDebugStateActive(pVCpu));
6182 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
6183 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
6184 }
6185 Assert(!fInterceptMovDRx);
6186 }
6187 else if (!CPUMIsGuestDebugStateActive(pVCpu))
6188 {
6189 /*
6190 * If no debugging enabled, we'll lazy load DR0-3. Unlike on AMD-V, we
6191 * must intercept #DB in order to maintain a correct DR6 guest value, and
6192 * because we need to intercept it to prevent nested #DBs from hanging the
6193 * CPU, we end up always having to intercept it. See hmR0VmxSetupVmcsXcptBitmap().
6194 */
6195 fInterceptMovDRx = true;
6196 }
6197
6198 /* Update DR7 with the actual guest value. */
6199 u64GuestDr7 = pVCpu->cpum.GstCtx.dr[7];
6200 pVCpu->hmr0.s.fUsingHyperDR7 = false;
6201 }
6202
6203 if (fInterceptMovDRx)
6204 uProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
6205 else
6206 uProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
6207
6208 /*
6209 * Update the processor-based VM-execution controls with the MOV-DRx intercepts and the
6210 * monitor-trap flag and update our cache.
6211 */
6212 if (uProcCtls != pVmcsInfo->u32ProcCtls)
6213 {
6214 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
6215 AssertRC(rc);
6216 pVmcsInfo->u32ProcCtls = uProcCtls;
6217 }
6218
6219 /*
6220 * Update guest DR7.
6221 */
6222 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, u64GuestDr7);
6223 AssertRC(rc);
6224
6225 /*
6226 * If we have forced EFLAGS.TF to be set because we're single-stepping in the hypervisor debugger,
6227 * we need to clear interrupt inhibition if any as otherwise it causes a VM-entry failure.
6228 *
6229 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
6230 */
6231 if (fSteppingDB)
6232 {
6233 Assert(pVCpu->hm.s.fSingleInstruction);
6234 Assert(pVCpu->cpum.GstCtx.eflags.Bits.u1TF);
6235
6236 uint32_t fIntrState = 0;
6237 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
6238 AssertRC(rc);
6239
6240 if (fIntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
6241 {
6242 fIntrState &= ~(VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
6243 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
6244 AssertRC(rc);
6245 }
6246 }
6247
6248 return VINF_SUCCESS;
6249}
6250
6251
6252#ifdef VBOX_STRICT
6253/**
6254 * Strict function to validate segment registers.
6255 *
6256 * @param pVCpu The cross context virtual CPU structure.
6257 * @param pVmcsInfo The VMCS info. object.
6258 *
6259 * @remarks Will import guest CR0 on strict builds during validation of
6260 * segments.
6261 */
6262static void hmR0VmxValidateSegmentRegs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
6263{
6264 /*
6265 * Validate segment registers. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
6266 *
6267 * The reason we check for attribute value 0 in this function and not just the unusable bit is
6268 * because hmR0VmxExportGuestSegReg() only updates the VMCS' copy of the value with the
6269 * unusable bit and doesn't change the guest-context value.
6270 */
6271 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6272 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6273 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR0);
6274 if ( !pVM->hmr0.s.vmx.fUnrestrictedGuest
6275 && ( !CPUMIsGuestInRealModeEx(pCtx)
6276 && !CPUMIsGuestInV86ModeEx(pCtx)))
6277 {
6278 /* Protected mode checks */
6279 /* CS */
6280 Assert(pCtx->cs.Attr.n.u1Present);
6281 Assert(!(pCtx->cs.Attr.u & 0xf00));
6282 Assert(!(pCtx->cs.Attr.u & 0xfffe0000));
6283 Assert( (pCtx->cs.u32Limit & 0xfff) == 0xfff
6284 || !(pCtx->cs.Attr.n.u1Granularity));
6285 Assert( !(pCtx->cs.u32Limit & 0xfff00000)
6286 || (pCtx->cs.Attr.n.u1Granularity));
6287 /* CS cannot be loaded with NULL in protected mode. */
6288 Assert(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE)); /** @todo is this really true even for 64-bit CS? */
6289 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
6290 Assert(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl);
6291 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
6292 Assert(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl);
6293 else
6294 AssertMsgFailed(("Invalid CS Type %#x\n", pCtx->cs.Attr.n.u2Dpl));
6295 /* SS */
6296 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
6297 Assert(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL));
6298 if ( !(pCtx->cr0 & X86_CR0_PE)
6299 || pCtx->cs.Attr.n.u4Type == 3)
6300 {
6301 Assert(!pCtx->ss.Attr.n.u2Dpl);
6302 }
6303 if (pCtx->ss.Attr.u && !(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
6304 {
6305 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
6306 Assert(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7);
6307 Assert(pCtx->ss.Attr.n.u1Present);
6308 Assert(!(pCtx->ss.Attr.u & 0xf00));
6309 Assert(!(pCtx->ss.Attr.u & 0xfffe0000));
6310 Assert( (pCtx->ss.u32Limit & 0xfff) == 0xfff
6311 || !(pCtx->ss.Attr.n.u1Granularity));
6312 Assert( !(pCtx->ss.u32Limit & 0xfff00000)
6313 || (pCtx->ss.Attr.n.u1Granularity));
6314 }
6315 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSegReg(). */
6316 if (pCtx->ds.Attr.u && !(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
6317 {
6318 Assert(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
6319 Assert(pCtx->ds.Attr.n.u1Present);
6320 Assert(pCtx->ds.Attr.n.u4Type > 11 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL));
6321 Assert(!(pCtx->ds.Attr.u & 0xf00));
6322 Assert(!(pCtx->ds.Attr.u & 0xfffe0000));
6323 Assert( (pCtx->ds.u32Limit & 0xfff) == 0xfff
6324 || !(pCtx->ds.Attr.n.u1Granularity));
6325 Assert( !(pCtx->ds.u32Limit & 0xfff00000)
6326 || (pCtx->ds.Attr.n.u1Granularity));
6327 Assert( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
6328 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ));
6329 }
6330 if (pCtx->es.Attr.u && !(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
6331 {
6332 Assert(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
6333 Assert(pCtx->es.Attr.n.u1Present);
6334 Assert(pCtx->es.Attr.n.u4Type > 11 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL));
6335 Assert(!(pCtx->es.Attr.u & 0xf00));
6336 Assert(!(pCtx->es.Attr.u & 0xfffe0000));
6337 Assert( (pCtx->es.u32Limit & 0xfff) == 0xfff
6338 || !(pCtx->es.Attr.n.u1Granularity));
6339 Assert( !(pCtx->es.u32Limit & 0xfff00000)
6340 || (pCtx->es.Attr.n.u1Granularity));
6341 Assert( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
6342 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ));
6343 }
6344 if (pCtx->fs.Attr.u && !(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
6345 {
6346 Assert(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
6347 Assert(pCtx->fs.Attr.n.u1Present);
6348 Assert(pCtx->fs.Attr.n.u4Type > 11 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL));
6349 Assert(!(pCtx->fs.Attr.u & 0xf00));
6350 Assert(!(pCtx->fs.Attr.u & 0xfffe0000));
6351 Assert( (pCtx->fs.u32Limit & 0xfff) == 0xfff
6352 || !(pCtx->fs.Attr.n.u1Granularity));
6353 Assert( !(pCtx->fs.u32Limit & 0xfff00000)
6354 || (pCtx->fs.Attr.n.u1Granularity));
6355 Assert( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
6356 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ));
6357 }
6358 if (pCtx->gs.Attr.u && !(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
6359 {
6360 Assert(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
6361 Assert(pCtx->gs.Attr.n.u1Present);
6362 Assert(pCtx->gs.Attr.n.u4Type > 11 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL));
6363 Assert(!(pCtx->gs.Attr.u & 0xf00));
6364 Assert(!(pCtx->gs.Attr.u & 0xfffe0000));
6365 Assert( (pCtx->gs.u32Limit & 0xfff) == 0xfff
6366 || !(pCtx->gs.Attr.n.u1Granularity));
6367 Assert( !(pCtx->gs.u32Limit & 0xfff00000)
6368 || (pCtx->gs.Attr.n.u1Granularity));
6369 Assert( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
6370 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ));
6371 }
6372 /* 64-bit capable CPUs. */
6373 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6374 Assert(!pCtx->ss.Attr.u || !RT_HI_U32(pCtx->ss.u64Base));
6375 Assert(!pCtx->ds.Attr.u || !RT_HI_U32(pCtx->ds.u64Base));
6376 Assert(!pCtx->es.Attr.u || !RT_HI_U32(pCtx->es.u64Base));
6377 }
6378 else if ( CPUMIsGuestInV86ModeEx(pCtx)
6379 || ( CPUMIsGuestInRealModeEx(pCtx)
6380 && !pVM->hmr0.s.vmx.fUnrestrictedGuest))
6381 {
6382 /* Real and v86 mode checks. */
6383 /* hmR0VmxExportGuestSegReg() writes the modified in VMCS. We want what we're feeding to VT-x. */
6384 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
6385 if (pVmcsInfo->pShared->RealMode.fRealOnV86Active)
6386 {
6387 u32CSAttr = 0xf3; u32SSAttr = 0xf3; u32DSAttr = 0xf3;
6388 u32ESAttr = 0xf3; u32FSAttr = 0xf3; u32GSAttr = 0xf3;
6389 }
6390 else
6391 {
6392 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u; u32DSAttr = pCtx->ds.Attr.u;
6393 u32ESAttr = pCtx->es.Attr.u; u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
6394 }
6395
6396 /* CS */
6397 AssertMsg((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), ("CS base %#x %#x\n", pCtx->cs.u64Base, pCtx->cs.Sel));
6398 Assert(pCtx->cs.u32Limit == 0xffff);
6399 Assert(u32CSAttr == 0xf3);
6400 /* SS */
6401 Assert(pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4);
6402 Assert(pCtx->ss.u32Limit == 0xffff);
6403 Assert(u32SSAttr == 0xf3);
6404 /* DS */
6405 Assert(pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4);
6406 Assert(pCtx->ds.u32Limit == 0xffff);
6407 Assert(u32DSAttr == 0xf3);
6408 /* ES */
6409 Assert(pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4);
6410 Assert(pCtx->es.u32Limit == 0xffff);
6411 Assert(u32ESAttr == 0xf3);
6412 /* FS */
6413 Assert(pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4);
6414 Assert(pCtx->fs.u32Limit == 0xffff);
6415 Assert(u32FSAttr == 0xf3);
6416 /* GS */
6417 Assert(pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4);
6418 Assert(pCtx->gs.u32Limit == 0xffff);
6419 Assert(u32GSAttr == 0xf3);
6420 /* 64-bit capable CPUs. */
6421 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6422 Assert(!u32SSAttr || !RT_HI_U32(pCtx->ss.u64Base));
6423 Assert(!u32DSAttr || !RT_HI_U32(pCtx->ds.u64Base));
6424 Assert(!u32ESAttr || !RT_HI_U32(pCtx->es.u64Base));
6425 }
6426}
6427#endif /* VBOX_STRICT */
6428
6429
6430/**
6431 * Exports a guest segment register into the guest-state area in the VMCS.
6432 *
6433 * @returns VBox status code.
6434 * @param pVCpu The cross context virtual CPU structure.
6435 * @param pVmcsInfo The VMCS info. object.
6436 * @param iSegReg The segment register number (X86_SREG_XXX).
6437 * @param pSelReg Pointer to the segment selector.
6438 *
6439 * @remarks No-long-jump zone!!!
6440 */
6441static int hmR0VmxExportGuestSegReg(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, uint32_t iSegReg, PCCPUMSELREG pSelReg)
6442{
6443 Assert(iSegReg < X86_SREG_COUNT);
6444
6445 uint32_t u32Access = pSelReg->Attr.u;
6446 if (!pVmcsInfo->pShared->RealMode.fRealOnV86Active)
6447 {
6448 /*
6449 * The way to differentiate between whether this is really a null selector or was just
6450 * a selector loaded with 0 in real-mode is using the segment attributes. A selector
6451 * loaded in real-mode with the value 0 is valid and usable in protected-mode and we
6452 * should -not- mark it as an unusable segment. Both the recompiler & VT-x ensures
6453 * NULL selectors loaded in protected-mode have their attribute as 0.
6454 */
6455 if (u32Access)
6456 { }
6457 else
6458 u32Access = X86DESCATTR_UNUSABLE;
6459 }
6460 else
6461 {
6462 /* VT-x requires our real-using-v86 mode hack to override the segment access-right bits. */
6463 u32Access = 0xf3;
6464 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
6465 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
6466 RT_NOREF_PV(pVCpu);
6467 }
6468
6469 /* Validate segment access rights. Refer to Intel spec. "26.3.1.2 Checks on Guest Segment Registers". */
6470 AssertMsg((u32Access & X86DESCATTR_UNUSABLE) || (u32Access & X86_SEL_TYPE_ACCESSED),
6471 ("Access bit not set for usable segment. %.2s sel=%#x attr %#x\n", "ESCSSSDSFSGS" + iSegReg * 2, pSelReg, pSelReg->Attr.u));
6472
6473 /*
6474 * Commit it to the VMCS.
6475 */
6476 Assert((uint32_t)VMX_VMCS16_GUEST_SEG_SEL(iSegReg) == g_aVmcsSegSel[iSegReg]);
6477 Assert((uint32_t)VMX_VMCS32_GUEST_SEG_LIMIT(iSegReg) == g_aVmcsSegLimit[iSegReg]);
6478 Assert((uint32_t)VMX_VMCS32_GUEST_SEG_ACCESS_RIGHTS(iSegReg) == g_aVmcsSegAttr[iSegReg]);
6479 Assert((uint32_t)VMX_VMCS_GUEST_SEG_BASE(iSegReg) == g_aVmcsSegBase[iSegReg]);
6480 int rc = VMXWriteVmcs32(VMX_VMCS16_GUEST_SEG_SEL(iSegReg), pSelReg->Sel); AssertRC(rc);
6481 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SEG_LIMIT(iSegReg), pSelReg->u32Limit); AssertRC(rc);
6482 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SEG_BASE(iSegReg), pSelReg->u64Base); AssertRC(rc);
6483 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SEG_ACCESS_RIGHTS(iSegReg), u32Access); AssertRC(rc);
6484 return VINF_SUCCESS;
6485}
6486
6487
6488/**
6489 * Exports the guest segment registers, GDTR, IDTR, LDTR, TR into the guest-state
6490 * area in the VMCS.
6491 *
6492 * @returns VBox status code.
6493 * @param pVCpu The cross context virtual CPU structure.
6494 * @param pVmxTransient The VMX-transient structure.
6495 *
6496 * @remarks Will import guest CR0 on strict builds during validation of
6497 * segments.
6498 * @remarks No-long-jump zone!!!
6499 */
6500static int hmR0VmxExportGuestSegRegsXdtr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6501{
6502 int rc = VERR_INTERNAL_ERROR_5;
6503 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6504 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6505 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6506 PVMXVMCSINFOSHARED pVmcsInfoShared = pVmcsInfo->pShared;
6507
6508 /*
6509 * Guest Segment registers: CS, SS, DS, ES, FS, GS.
6510 */
6511 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SREG_MASK)
6512 {
6513 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CS)
6514 {
6515 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS);
6516 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
6517 pVmcsInfoShared->RealMode.AttrCS.u = pCtx->cs.Attr.u;
6518 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_CS, &pCtx->cs);
6519 AssertRC(rc);
6520 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CS);
6521 }
6522
6523 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SS)
6524 {
6525 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SS);
6526 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
6527 pVmcsInfoShared->RealMode.AttrSS.u = pCtx->ss.Attr.u;
6528 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_SS, &pCtx->ss);
6529 AssertRC(rc);
6530 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SS);
6531 }
6532
6533 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_DS)
6534 {
6535 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DS);
6536 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
6537 pVmcsInfoShared->RealMode.AttrDS.u = pCtx->ds.Attr.u;
6538 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_DS, &pCtx->ds);
6539 AssertRC(rc);
6540 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_DS);
6541 }
6542
6543 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_ES)
6544 {
6545 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_ES);
6546 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
6547 pVmcsInfoShared->RealMode.AttrES.u = pCtx->es.Attr.u;
6548 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_ES, &pCtx->es);
6549 AssertRC(rc);
6550 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_ES);
6551 }
6552
6553 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_FS)
6554 {
6555 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_FS);
6556 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
6557 pVmcsInfoShared->RealMode.AttrFS.u = pCtx->fs.Attr.u;
6558 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_FS, &pCtx->fs);
6559 AssertRC(rc);
6560 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_FS);
6561 }
6562
6563 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GS)
6564 {
6565 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GS);
6566 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
6567 pVmcsInfoShared->RealMode.AttrGS.u = pCtx->gs.Attr.u;
6568 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_GS, &pCtx->gs);
6569 AssertRC(rc);
6570 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GS);
6571 }
6572
6573#ifdef VBOX_STRICT
6574 hmR0VmxValidateSegmentRegs(pVCpu, pVmcsInfo);
6575#endif
6576 Log4Func(("cs={%#04x base=%#RX64 limit=%#RX32 attr=%#RX32}\n", pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit,
6577 pCtx->cs.Attr.u));
6578 }
6579
6580 /*
6581 * Guest TR.
6582 */
6583 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_TR)
6584 {
6585 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_TR);
6586
6587 /*
6588 * Real-mode emulation using virtual-8086 mode with CR4.VME. Interrupt redirection is
6589 * achieved using the interrupt redirection bitmap (all bits cleared to let the guest
6590 * handle INT-n's) in the TSS. See hmR3InitFinalizeR0() to see how pRealModeTSS is setup.
6591 */
6592 uint16_t u16Sel;
6593 uint32_t u32Limit;
6594 uint64_t u64Base;
6595 uint32_t u32AccessRights;
6596 if (!pVmcsInfoShared->RealMode.fRealOnV86Active)
6597 {
6598 u16Sel = pCtx->tr.Sel;
6599 u32Limit = pCtx->tr.u32Limit;
6600 u64Base = pCtx->tr.u64Base;
6601 u32AccessRights = pCtx->tr.Attr.u;
6602 }
6603 else
6604 {
6605 Assert(!pVmxTransient->fIsNestedGuest);
6606 Assert(pVM->hm.s.vmx.pRealModeTSS);
6607 Assert(PDMVmmDevHeapIsEnabled(pVM)); /* Guaranteed by HMCanExecuteGuest() -XXX- what about inner loop changes? */
6608
6609 /* We obtain it here every time as PCI regions could be reconfigured in the guest, changing the VMMDev base. */
6610 RTGCPHYS GCPhys;
6611 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
6612 AssertRCReturn(rc, rc);
6613
6614 X86DESCATTR DescAttr;
6615 DescAttr.u = 0;
6616 DescAttr.n.u1Present = 1;
6617 DescAttr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
6618
6619 u16Sel = 0;
6620 u32Limit = HM_VTX_TSS_SIZE;
6621 u64Base = GCPhys;
6622 u32AccessRights = DescAttr.u;
6623 }
6624
6625 /* Validate. */
6626 Assert(!(u16Sel & RT_BIT(2)));
6627 AssertMsg( (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY
6628 || (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("TSS is not busy!? %#x\n", u32AccessRights));
6629 AssertMsg(!(u32AccessRights & X86DESCATTR_UNUSABLE), ("TR unusable bit is not clear!? %#x\n", u32AccessRights));
6630 Assert(!(u32AccessRights & RT_BIT(4))); /* System MBZ.*/
6631 Assert(u32AccessRights & RT_BIT(7)); /* Present MB1.*/
6632 Assert(!(u32AccessRights & 0xf00)); /* 11:8 MBZ. */
6633 Assert(!(u32AccessRights & 0xfffe0000)); /* 31:17 MBZ. */
6634 Assert( (u32Limit & 0xfff) == 0xfff
6635 || !(u32AccessRights & RT_BIT(15))); /* Granularity MBZ. */
6636 Assert( !(pCtx->tr.u32Limit & 0xfff00000)
6637 || (u32AccessRights & RT_BIT(15))); /* Granularity MB1. */
6638
6639 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_TR_SEL, u16Sel); AssertRC(rc);
6640 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, u32Limit); AssertRC(rc);
6641 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, u32AccessRights); AssertRC(rc);
6642 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_TR_BASE, u64Base); AssertRC(rc);
6643
6644 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_TR);
6645 Log4Func(("tr base=%#RX64 limit=%#RX32\n", pCtx->tr.u64Base, pCtx->tr.u32Limit));
6646 }
6647
6648 /*
6649 * Guest GDTR.
6650 */
6651 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GDTR)
6652 {
6653 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GDTR);
6654
6655 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, pCtx->gdtr.cbGdt); AssertRC(rc);
6656 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, pCtx->gdtr.pGdt); AssertRC(rc);
6657
6658 /* Validate. */
6659 Assert(!(pCtx->gdtr.cbGdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6660
6661 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GDTR);
6662 Log4Func(("gdtr base=%#RX64 limit=%#RX32\n", pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt));
6663 }
6664
6665 /*
6666 * Guest LDTR.
6667 */
6668 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_LDTR)
6669 {
6670 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_LDTR);
6671
6672 /* The unusable bit is specific to VT-x, if it's a null selector mark it as an unusable segment. */
6673 uint32_t u32Access;
6674 if ( !pVmxTransient->fIsNestedGuest
6675 && !pCtx->ldtr.Attr.u)
6676 u32Access = X86DESCATTR_UNUSABLE;
6677 else
6678 u32Access = pCtx->ldtr.Attr.u;
6679
6680 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, pCtx->ldtr.Sel); AssertRC(rc);
6681 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, pCtx->ldtr.u32Limit); AssertRC(rc);
6682 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, u32Access); AssertRC(rc);
6683 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, pCtx->ldtr.u64Base); AssertRC(rc);
6684
6685 /* Validate. */
6686 if (!(u32Access & X86DESCATTR_UNUSABLE))
6687 {
6688 Assert(!(pCtx->ldtr.Sel & RT_BIT(2))); /* TI MBZ. */
6689 Assert(pCtx->ldtr.Attr.n.u4Type == 2); /* Type MB2 (LDT). */
6690 Assert(!pCtx->ldtr.Attr.n.u1DescType); /* System MBZ. */
6691 Assert(pCtx->ldtr.Attr.n.u1Present == 1); /* Present MB1. */
6692 Assert(!pCtx->ldtr.Attr.n.u4LimitHigh); /* 11:8 MBZ. */
6693 Assert(!(pCtx->ldtr.Attr.u & 0xfffe0000)); /* 31:17 MBZ. */
6694 Assert( (pCtx->ldtr.u32Limit & 0xfff) == 0xfff
6695 || !pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MBZ. */
6696 Assert( !(pCtx->ldtr.u32Limit & 0xfff00000)
6697 || pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MB1. */
6698 }
6699
6700 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_LDTR);
6701 Log4Func(("ldtr base=%#RX64 limit=%#RX32\n", pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit));
6702 }
6703
6704 /*
6705 * Guest IDTR.
6706 */
6707 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_IDTR)
6708 {
6709 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_IDTR);
6710
6711 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, pCtx->idtr.cbIdt); AssertRC(rc);
6712 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, pCtx->idtr.pIdt); AssertRC(rc);
6713
6714 /* Validate. */
6715 Assert(!(pCtx->idtr.cbIdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6716
6717 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_IDTR);
6718 Log4Func(("idtr base=%#RX64 limit=%#RX32\n", pCtx->idtr.pIdt, pCtx->idtr.cbIdt));
6719 }
6720
6721 return VINF_SUCCESS;
6722}
6723
6724
6725/**
6726 * Exports certain guest MSRs into the VM-entry MSR-load and VM-exit MSR-store
6727 * areas.
6728 *
6729 * These MSRs will automatically be loaded to the host CPU on every successful
6730 * VM-entry and stored from the host CPU on every successful VM-exit.
6731 *
6732 * We creates/updates MSR slots for the host MSRs in the VM-exit MSR-load area. The
6733 * actual host MSR values are not- updated here for performance reasons. See
6734 * hmR0VmxExportHostMsrs().
6735 *
6736 * We also exports the guest sysenter MSRs into the guest-state area in the VMCS.
6737 *
6738 * @returns VBox status code.
6739 * @param pVCpu The cross context virtual CPU structure.
6740 * @param pVmxTransient The VMX-transient structure.
6741 *
6742 * @remarks No-long-jump zone!!!
6743 */
6744static int hmR0VmxExportGuestMsrs(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6745{
6746 AssertPtr(pVCpu);
6747 AssertPtr(pVmxTransient);
6748
6749 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6750 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6751
6752 /*
6753 * MSRs that we use the auto-load/store MSR area in the VMCS.
6754 * For 64-bit hosts, we load/restore them lazily, see hmR0VmxLazyLoadGuestMsrs(),
6755 * nothing to do here. The host MSR values are updated when it's safe in
6756 * hmR0VmxLazySaveHostMsrs().
6757 *
6758 * For nested-guests, the guests MSRs from the VM-entry MSR-load area are already
6759 * loaded (into the guest-CPU context) by the VMLAUNCH/VMRESUME instruction
6760 * emulation. The merged MSR permission bitmap will ensure that we get VM-exits
6761 * for any MSR that are not part of the lazy MSRs so we do not need to place
6762 * those MSRs into the auto-load/store MSR area. Nothing to do here.
6763 */
6764 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_GUEST_AUTO_MSRS)
6765 {
6766 /* No auto-load/store MSRs currently. */
6767 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_GUEST_AUTO_MSRS);
6768 }
6769
6770 /*
6771 * Guest Sysenter MSRs.
6772 */
6773 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_MSR_MASK)
6774 {
6775 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SYSENTER_MSRS);
6776
6777 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_CS_MSR)
6778 {
6779 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, pCtx->SysEnter.cs);
6780 AssertRC(rc);
6781 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_CS_MSR);
6782 }
6783
6784 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_EIP_MSR)
6785 {
6786 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, pCtx->SysEnter.eip);
6787 AssertRC(rc);
6788 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
6789 }
6790
6791 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_ESP_MSR)
6792 {
6793 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, pCtx->SysEnter.esp);
6794 AssertRC(rc);
6795 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
6796 }
6797 }
6798
6799 /*
6800 * Guest/host EFER MSR.
6801 */
6802 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_EFER_MSR)
6803 {
6804 /* Whether we are using the VMCS to swap the EFER MSR must have been
6805 determined earlier while exporting VM-entry/VM-exit controls. */
6806 Assert(!(ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS));
6807 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
6808
6809 if (hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
6810 {
6811 /*
6812 * EFER.LME is written by software, while EFER.LMA is set by the CPU to (CR0.PG & EFER.LME).
6813 * This means a guest can set EFER.LME=1 while CR0.PG=0 and EFER.LMA can remain 0.
6814 * VT-x requires that "IA-32e mode guest" VM-entry control must be identical to EFER.LMA
6815 * and to CR0.PG. Without unrestricted execution, CR0.PG (used for VT-x, not the shadow)
6816 * must always be 1. This forces us to effectively clear both EFER.LMA and EFER.LME until
6817 * the guest has also set CR0.PG=1. Otherwise, we would run into an invalid-guest state
6818 * during VM-entry.
6819 */
6820 uint64_t uGuestEferMsr = pCtx->msrEFER;
6821 if (!pVM->hmr0.s.vmx.fUnrestrictedGuest)
6822 {
6823 if (!(pCtx->msrEFER & MSR_K6_EFER_LMA))
6824 uGuestEferMsr &= ~MSR_K6_EFER_LME;
6825 else
6826 Assert((pCtx->msrEFER & (MSR_K6_EFER_LMA | MSR_K6_EFER_LME)) == (MSR_K6_EFER_LMA | MSR_K6_EFER_LME));
6827 }
6828
6829 /*
6830 * If the CPU supports VMCS controls for swapping EFER, use it. Otherwise, we have no option
6831 * but to use the auto-load store MSR area in the VMCS for swapping EFER. See @bugref{7368}.
6832 */
6833 if (g_fHmVmxSupportsVmcsEfer)
6834 {
6835 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_EFER_FULL, uGuestEferMsr);
6836 AssertRC(rc);
6837 }
6838 else
6839 {
6840 /*
6841 * We shall use the auto-load/store MSR area only for loading the EFER MSR but we must
6842 * continue to intercept guest read and write accesses to it, see @bugref{7386#c16}.
6843 */
6844 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER, uGuestEferMsr,
6845 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6846 AssertRCReturn(rc, rc);
6847 }
6848
6849 Log4Func(("efer=%#RX64 shadow=%#RX64\n", uGuestEferMsr, pCtx->msrEFER));
6850 }
6851 else if (!g_fHmVmxSupportsVmcsEfer)
6852 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER);
6853
6854 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_EFER_MSR);
6855 }
6856
6857 /*
6858 * Other MSRs.
6859 */
6860 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_OTHER_MSRS)
6861 {
6862 /* Speculation Control (R/W). */
6863 HMVMX_CPUMCTX_ASSERT(pVCpu, HM_CHANGED_GUEST_OTHER_MSRS);
6864 if (pVM->cpum.ro.GuestFeatures.fIbrs)
6865 {
6866 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_IA32_SPEC_CTRL, CPUMGetGuestSpecCtrl(pVCpu),
6867 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6868 AssertRCReturn(rc, rc);
6869 }
6870
6871 /* Last Branch Record. */
6872 if (pVM->hmr0.s.vmx.fLbr)
6873 {
6874 PVMXVMCSINFOSHARED const pVmcsInfoShared = pVmxTransient->pVmcsInfo->pShared;
6875 uint32_t const idFromIpMsrStart = pVM->hmr0.s.vmx.idLbrFromIpMsrFirst;
6876 uint32_t const idToIpMsrStart = pVM->hmr0.s.vmx.idLbrToIpMsrFirst;
6877 uint32_t const cLbrStack = pVM->hmr0.s.vmx.idLbrFromIpMsrLast - pVM->hmr0.s.vmx.idLbrFromIpMsrFirst + 1;
6878 Assert(cLbrStack <= 32);
6879 for (uint32_t i = 0; i < cLbrStack; i++)
6880 {
6881 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, idFromIpMsrStart + i,
6882 pVmcsInfoShared->au64LbrFromIpMsr[i],
6883 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6884 AssertRCReturn(rc, rc);
6885
6886 /* Some CPUs don't have a Branch-To-IP MSR (P4 and related Xeons). */
6887 if (idToIpMsrStart != 0)
6888 {
6889 rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, idToIpMsrStart + i,
6890 pVmcsInfoShared->au64LbrToIpMsr[i],
6891 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6892 AssertRCReturn(rc, rc);
6893 }
6894 }
6895
6896 /* Add LBR top-of-stack MSR (which contains the index to the most recent record). */
6897 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, pVM->hmr0.s.vmx.idLbrTosMsr,
6898 pVmcsInfoShared->u64LbrTosMsr, false /* fSetReadWrite */,
6899 false /* fUpdateHostMsr */);
6900 AssertRCReturn(rc, rc);
6901 }
6902
6903 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_OTHER_MSRS);
6904 }
6905
6906 return VINF_SUCCESS;
6907}
6908
6909
6910/**
6911 * Wrapper for running the guest code in VT-x.
6912 *
6913 * @returns VBox status code, no informational status codes.
6914 * @param pVCpu The cross context virtual CPU structure.
6915 * @param pVmxTransient The VMX-transient structure.
6916 *
6917 * @remarks No-long-jump zone!!!
6918 */
6919DECLINLINE(int) hmR0VmxRunGuest(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6920{
6921 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
6922 pVCpu->cpum.GstCtx.fExtrn |= HMVMX_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
6923
6924 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6925 bool const fResumeVM = RT_BOOL(pVmcsInfo->fVmcsState & VMX_V_VMCS_LAUNCH_STATE_LAUNCHED);
6926#ifdef VBOX_WITH_STATISTICS
6927 if (fResumeVM)
6928 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxVmResume);
6929 else
6930 STAM_COUNTER_INC(&pVCpu->hm.s.StatVmxVmLaunch);
6931#endif
6932 int rc = pVCpu->hmr0.s.vmx.pfnStartVm(pVmcsInfo, pVCpu, fResumeVM);
6933 AssertMsg(rc <= VINF_SUCCESS, ("%Rrc\n", rc));
6934 return rc;
6935}
6936
6937
6938/**
6939 * Reports world-switch error and dumps some useful debug info.
6940 *
6941 * @param pVCpu The cross context virtual CPU structure.
6942 * @param rcVMRun The return code from VMLAUNCH/VMRESUME.
6943 * @param pVmxTransient The VMX-transient structure (only
6944 * exitReason updated).
6945 */
6946static void hmR0VmxReportWorldSwitchError(PVMCPUCC pVCpu, int rcVMRun, PVMXTRANSIENT pVmxTransient)
6947{
6948 Assert(pVCpu);
6949 Assert(pVmxTransient);
6950 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
6951
6952 Log4Func(("VM-entry failure: %Rrc\n", rcVMRun));
6953 switch (rcVMRun)
6954 {
6955 case VERR_VMX_INVALID_VMXON_PTR:
6956 AssertFailed();
6957 break;
6958 case VINF_SUCCESS: /* VMLAUNCH/VMRESUME succeeded but VM-entry failed... yeah, true story. */
6959 case VERR_VMX_UNABLE_TO_START_VM: /* VMLAUNCH/VMRESUME itself failed. */
6960 {
6961 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &pVCpu->hm.s.vmx.LastError.u32ExitReason);
6962 rc |= VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
6963 AssertRC(rc);
6964 hmR0VmxReadExitQualVmcs(pVmxTransient);
6965
6966 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hmr0.s.idEnteredCpu;
6967 /* LastError.idCurrentCpu was already updated in hmR0VmxPreRunGuestCommitted().
6968 Cannot do it here as we may have been long preempted. */
6969
6970#ifdef VBOX_STRICT
6971 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6972 Log4(("uExitReason %#RX32 (VmxTransient %#RX16)\n", pVCpu->hm.s.vmx.LastError.u32ExitReason,
6973 pVmxTransient->uExitReason));
6974 Log4(("Exit Qualification %#RX64\n", pVmxTransient->uExitQual));
6975 Log4(("InstrError %#RX32\n", pVCpu->hm.s.vmx.LastError.u32InstrError));
6976 if (pVCpu->hm.s.vmx.LastError.u32InstrError <= HMVMX_INSTR_ERROR_MAX)
6977 Log4(("InstrError Desc. \"%s\"\n", g_apszVmxInstrErrors[pVCpu->hm.s.vmx.LastError.u32InstrError]));
6978 else
6979 Log4(("InstrError Desc. Range exceeded %u\n", HMVMX_INSTR_ERROR_MAX));
6980 Log4(("Entered host CPU %u\n", pVCpu->hm.s.vmx.LastError.idEnteredCpu));
6981 Log4(("Current host CPU %u\n", pVCpu->hm.s.vmx.LastError.idCurrentCpu));
6982
6983 static struct
6984 {
6985 /** Name of the field to log. */
6986 const char *pszName;
6987 /** The VMCS field. */
6988 uint32_t uVmcsField;
6989 /** Whether host support of this field needs to be checked. */
6990 bool fCheckSupport;
6991 } const s_aVmcsFields[] =
6992 {
6993 { "VMX_VMCS32_CTRL_PIN_EXEC", VMX_VMCS32_CTRL_PIN_EXEC, false },
6994 { "VMX_VMCS32_CTRL_PROC_EXEC", VMX_VMCS32_CTRL_PROC_EXEC, false },
6995 { "VMX_VMCS32_CTRL_PROC_EXEC2", VMX_VMCS32_CTRL_PROC_EXEC2, true },
6996 { "VMX_VMCS32_CTRL_ENTRY", VMX_VMCS32_CTRL_ENTRY, false },
6997 { "VMX_VMCS32_CTRL_EXIT", VMX_VMCS32_CTRL_EXIT, false },
6998 { "VMX_VMCS32_CTRL_CR3_TARGET_COUNT", VMX_VMCS32_CTRL_CR3_TARGET_COUNT, false },
6999 { "VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO", VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, false },
7000 { "VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE", VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, false },
7001 { "VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH", VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, false },
7002 { "VMX_VMCS32_CTRL_TPR_THRESHOLD", VMX_VMCS32_CTRL_TPR_THRESHOLD, false },
7003 { "VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, false },
7004 { "VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, false },
7005 { "VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, false },
7006 { "VMX_VMCS32_CTRL_EXCEPTION_BITMAP", VMX_VMCS32_CTRL_EXCEPTION_BITMAP, false },
7007 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, false },
7008 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, false },
7009 { "VMX_VMCS_CTRL_CR0_MASK", VMX_VMCS_CTRL_CR0_MASK, false },
7010 { "VMX_VMCS_CTRL_CR0_READ_SHADOW", VMX_VMCS_CTRL_CR0_READ_SHADOW, false },
7011 { "VMX_VMCS_CTRL_CR4_MASK", VMX_VMCS_CTRL_CR4_MASK, false },
7012 { "VMX_VMCS_CTRL_CR4_READ_SHADOW", VMX_VMCS_CTRL_CR4_READ_SHADOW, false },
7013 { "VMX_VMCS64_CTRL_EPTP_FULL", VMX_VMCS64_CTRL_EPTP_FULL, true },
7014 { "VMX_VMCS_GUEST_RIP", VMX_VMCS_GUEST_RIP, false },
7015 { "VMX_VMCS_GUEST_RSP", VMX_VMCS_GUEST_RSP, false },
7016 { "VMX_VMCS_GUEST_RFLAGS", VMX_VMCS_GUEST_RFLAGS, false },
7017 { "VMX_VMCS16_VPID", VMX_VMCS16_VPID, true, },
7018 { "VMX_VMCS_HOST_CR0", VMX_VMCS_HOST_CR0, false },
7019 { "VMX_VMCS_HOST_CR3", VMX_VMCS_HOST_CR3, false },
7020 { "VMX_VMCS_HOST_CR4", VMX_VMCS_HOST_CR4, false },
7021 /* The order of selector fields below are fixed! */
7022 { "VMX_VMCS16_HOST_ES_SEL", VMX_VMCS16_HOST_ES_SEL, false },
7023 { "VMX_VMCS16_HOST_CS_SEL", VMX_VMCS16_HOST_CS_SEL, false },
7024 { "VMX_VMCS16_HOST_SS_SEL", VMX_VMCS16_HOST_SS_SEL, false },
7025 { "VMX_VMCS16_HOST_DS_SEL", VMX_VMCS16_HOST_DS_SEL, false },
7026 { "VMX_VMCS16_HOST_FS_SEL", VMX_VMCS16_HOST_FS_SEL, false },
7027 { "VMX_VMCS16_HOST_GS_SEL", VMX_VMCS16_HOST_GS_SEL, false },
7028 { "VMX_VMCS16_HOST_TR_SEL", VMX_VMCS16_HOST_TR_SEL, false },
7029 /* End of ordered selector fields. */
7030 { "VMX_VMCS_HOST_TR_BASE", VMX_VMCS_HOST_TR_BASE, false },
7031 { "VMX_VMCS_HOST_GDTR_BASE", VMX_VMCS_HOST_GDTR_BASE, false },
7032 { "VMX_VMCS_HOST_IDTR_BASE", VMX_VMCS_HOST_IDTR_BASE, false },
7033 { "VMX_VMCS32_HOST_SYSENTER_CS", VMX_VMCS32_HOST_SYSENTER_CS, false },
7034 { "VMX_VMCS_HOST_SYSENTER_EIP", VMX_VMCS_HOST_SYSENTER_EIP, false },
7035 { "VMX_VMCS_HOST_SYSENTER_ESP", VMX_VMCS_HOST_SYSENTER_ESP, false },
7036 { "VMX_VMCS_HOST_RSP", VMX_VMCS_HOST_RSP, false },
7037 { "VMX_VMCS_HOST_RIP", VMX_VMCS_HOST_RIP, false }
7038 };
7039
7040 RTGDTR HostGdtr;
7041 ASMGetGDTR(&HostGdtr);
7042
7043 uint32_t const cVmcsFields = RT_ELEMENTS(s_aVmcsFields);
7044 for (uint32_t i = 0; i < cVmcsFields; i++)
7045 {
7046 uint32_t const uVmcsField = s_aVmcsFields[i].uVmcsField;
7047
7048 bool fSupported;
7049 if (!s_aVmcsFields[i].fCheckSupport)
7050 fSupported = true;
7051 else
7052 {
7053 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7054 switch (uVmcsField)
7055 {
7056 case VMX_VMCS64_CTRL_EPTP_FULL: fSupported = pVM->hmr0.s.fNestedPaging; break;
7057 case VMX_VMCS16_VPID: fSupported = pVM->hmr0.s.vmx.fVpid; break;
7058 case VMX_VMCS32_CTRL_PROC_EXEC2:
7059 fSupported = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
7060 break;
7061 default:
7062 AssertMsgFailedReturnVoid(("Failed to provide VMCS field support for %#RX32\n", uVmcsField));
7063 }
7064 }
7065
7066 if (fSupported)
7067 {
7068 uint8_t const uWidth = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_WIDTH);
7069 switch (uWidth)
7070 {
7071 case VMX_VMCSFIELD_WIDTH_16BIT:
7072 {
7073 uint16_t u16Val;
7074 rc = VMXReadVmcs16(uVmcsField, &u16Val);
7075 AssertRC(rc);
7076 Log4(("%-40s = %#RX16\n", s_aVmcsFields[i].pszName, u16Val));
7077
7078 if ( uVmcsField >= VMX_VMCS16_HOST_ES_SEL
7079 && uVmcsField <= VMX_VMCS16_HOST_TR_SEL)
7080 {
7081 if (u16Val < HostGdtr.cbGdt)
7082 {
7083 /* Order of selectors in s_apszSel is fixed and matches the order in s_aVmcsFields. */
7084 static const char * const s_apszSel[] = { "Host ES", "Host CS", "Host SS", "Host DS",
7085 "Host FS", "Host GS", "Host TR" };
7086 uint8_t const idxSel = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_INDEX);
7087 Assert(idxSel < RT_ELEMENTS(s_apszSel));
7088 PCX86DESCHC pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u16Val & X86_SEL_MASK));
7089 hmR0DumpDescriptor(pDesc, u16Val, s_apszSel[idxSel]);
7090 }
7091 else
7092 Log4((" Selector value exceeds GDT limit!\n"));
7093 }
7094 break;
7095 }
7096
7097 case VMX_VMCSFIELD_WIDTH_32BIT:
7098 {
7099 uint32_t u32Val;
7100 rc = VMXReadVmcs32(uVmcsField, &u32Val);
7101 AssertRC(rc);
7102 Log4(("%-40s = %#RX32\n", s_aVmcsFields[i].pszName, u32Val));
7103 break;
7104 }
7105
7106 case VMX_VMCSFIELD_WIDTH_64BIT:
7107 case VMX_VMCSFIELD_WIDTH_NATURAL:
7108 {
7109 uint64_t u64Val;
7110 rc = VMXReadVmcs64(uVmcsField, &u64Val);
7111 AssertRC(rc);
7112 Log4(("%-40s = %#RX64\n", s_aVmcsFields[i].pszName, u64Val));
7113 break;
7114 }
7115 }
7116 }
7117 }
7118
7119 Log4(("MSR_K6_EFER = %#RX64\n", ASMRdMsr(MSR_K6_EFER)));
7120 Log4(("MSR_K8_CSTAR = %#RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
7121 Log4(("MSR_K8_LSTAR = %#RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
7122 Log4(("MSR_K6_STAR = %#RX64\n", ASMRdMsr(MSR_K6_STAR)));
7123 Log4(("MSR_K8_SF_MASK = %#RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
7124 Log4(("MSR_K8_KERNEL_GS_BASE = %#RX64\n", ASMRdMsr(MSR_K8_KERNEL_GS_BASE)));
7125#endif /* VBOX_STRICT */
7126 break;
7127 }
7128
7129 default:
7130 /* Impossible */
7131 AssertMsgFailed(("hmR0VmxReportWorldSwitchError %Rrc (%#x)\n", rcVMRun, rcVMRun));
7132 break;
7133 }
7134}
7135
7136
7137/**
7138 * Sets up the usage of TSC-offsetting and updates the VMCS.
7139 *
7140 * If offsetting is not possible, cause VM-exits on RDTSC(P)s. Also sets up the
7141 * VMX-preemption timer.
7142 *
7143 * @returns VBox status code.
7144 * @param pVCpu The cross context virtual CPU structure.
7145 * @param pVmxTransient The VMX-transient structure.
7146 * @param idCurrentCpu The current CPU number.
7147 *
7148 * @remarks No-long-jump zone!!!
7149 */
7150static void hmR0VmxUpdateTscOffsettingAndPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, RTCPUID idCurrentCpu)
7151{
7152 bool fOffsettedTsc;
7153 bool fParavirtTsc;
7154 uint64_t uTscOffset;
7155 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7156 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7157
7158 if (pVM->hmr0.s.vmx.fUsePreemptTimer)
7159 {
7160 /* The TMCpuTickGetDeadlineAndTscOffset function is expensive (calling it on
7161 every entry slowed down the bs2-test1 CPUID testcase by ~33% (on an 10980xe). */
7162 uint64_t cTicksToDeadline;
7163 if ( idCurrentCpu == pVCpu->hmr0.s.idLastCpu
7164 && TMVirtualSyncIsCurrentDeadlineVersion(pVM, pVCpu->hmr0.s.vmx.uTscDeadlineVersion))
7165 {
7166 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatVmxPreemptionReusingDeadline);
7167 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
7168 cTicksToDeadline = pVCpu->hmr0.s.vmx.uTscDeadline - SUPReadTsc();
7169 if ((int64_t)cTicksToDeadline > 0)
7170 { /* hopefully */ }
7171 else
7172 {
7173 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatVmxPreemptionReusingDeadlineExpired);
7174 cTicksToDeadline = 0;
7175 }
7176 }
7177 else
7178 {
7179 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatVmxPreemptionRecalcingDeadline);
7180 cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVM, pVCpu, &uTscOffset, &fOffsettedTsc, &fParavirtTsc,
7181 &pVCpu->hmr0.s.vmx.uTscDeadline,
7182 &pVCpu->hmr0.s.vmx.uTscDeadlineVersion);
7183 pVCpu->hmr0.s.vmx.uTscDeadline += cTicksToDeadline;
7184 if (cTicksToDeadline >= 128)
7185 { /* hopefully */ }
7186 else
7187 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatVmxPreemptionRecalcingDeadlineExpired);
7188 }
7189
7190 /* Make sure the returned values have sane upper and lower boundaries. */
7191 uint64_t const u64CpuHz = SUPGetCpuHzFromGipBySetIndex(g_pSUPGlobalInfoPage, pVCpu->iHostCpuSet);
7192 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64th of a second, 15.625ms. */ /** @todo r=bird: Once real+virtual timers move to separate thread, we can raise the upper limit (16ms isn't much). ASSUMES working poke cpu function. */
7193 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 32678); /* 1/32768th of a second, ~30us. */
7194 cTicksToDeadline >>= pVM->hm.s.vmx.cPreemptTimerShift;
7195
7196 /** @todo r=ramshankar: We need to find a way to integrate nested-guest
7197 * preemption timers here. We probably need to clamp the preemption timer,
7198 * after converting the timer value to the host. */
7199 uint32_t const cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
7200 int rc = VMXWriteVmcs32(VMX_VMCS32_PREEMPT_TIMER_VALUE, cPreemptionTickCount);
7201 AssertRC(rc);
7202 }
7203 else
7204 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
7205
7206 if (fParavirtTsc)
7207 {
7208 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
7209 information before every VM-entry, hence disable it for performance sake. */
7210#if 0
7211 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
7212 AssertRC(rc);
7213#endif
7214 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
7215 }
7216
7217 if ( fOffsettedTsc
7218 && RT_LIKELY(!pVCpu->hmr0.s.fDebugWantRdTscExit))
7219 {
7220 if (pVmxTransient->fIsNestedGuest)
7221 uTscOffset = CPUMApplyNestedGuestTscOffset(pVCpu, uTscOffset);
7222 hmR0VmxSetTscOffsetVmcs(pVmcsInfo, uTscOffset);
7223 hmR0VmxRemoveProcCtlsVmcs(pVCpu, pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
7224 }
7225 else
7226 {
7227 /* We can't use TSC-offsetting (non-fixed TSC, warp drive active etc.), VM-exit on RDTSC(P). */
7228 hmR0VmxSetProcCtlsVmcs(pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
7229 }
7230}
7231
7232
7233/**
7234 * Gets the IEM exception flags for the specified vector and IDT vectoring /
7235 * VM-exit interruption info type.
7236 *
7237 * @returns The IEM exception flags.
7238 * @param uVector The event vector.
7239 * @param uVmxEventType The VMX event type.
7240 *
7241 * @remarks This function currently only constructs flags required for
7242 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g, error-code
7243 * and CR2 aspects of an exception are not included).
7244 */
7245static uint32_t hmR0VmxGetIemXcptFlags(uint8_t uVector, uint32_t uVmxEventType)
7246{
7247 uint32_t fIemXcptFlags;
7248 switch (uVmxEventType)
7249 {
7250 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
7251 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
7252 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
7253 break;
7254
7255 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
7256 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
7257 break;
7258
7259 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
7260 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_ICEBP_INSTR;
7261 break;
7262
7263 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT:
7264 {
7265 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
7266 if (uVector == X86_XCPT_BP)
7267 fIemXcptFlags |= IEM_XCPT_FLAGS_BP_INSTR;
7268 else if (uVector == X86_XCPT_OF)
7269 fIemXcptFlags |= IEM_XCPT_FLAGS_OF_INSTR;
7270 else
7271 {
7272 fIemXcptFlags = 0;
7273 AssertMsgFailed(("Unexpected vector for software exception. uVector=%#x", uVector));
7274 }
7275 break;
7276 }
7277
7278 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
7279 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
7280 break;
7281
7282 default:
7283 fIemXcptFlags = 0;
7284 AssertMsgFailed(("Unexpected vector type! uVmxEventType=%#x uVector=%#x", uVmxEventType, uVector));
7285 break;
7286 }
7287 return fIemXcptFlags;
7288}
7289
7290
7291/**
7292 * Sets an event as a pending event to be injected into the guest.
7293 *
7294 * @param pVCpu The cross context virtual CPU structure.
7295 * @param u32IntInfo The VM-entry interruption-information field.
7296 * @param cbInstr The VM-entry instruction length in bytes (for
7297 * software interrupts, exceptions and privileged
7298 * software exceptions).
7299 * @param u32ErrCode The VM-entry exception error code.
7300 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
7301 * page-fault.
7302 */
7303DECLINLINE(void) hmR0VmxSetPendingEvent(PVMCPUCC pVCpu, uint32_t u32IntInfo, uint32_t cbInstr, uint32_t u32ErrCode,
7304 RTGCUINTPTR GCPtrFaultAddress)
7305{
7306 Assert(!pVCpu->hm.s.Event.fPending);
7307 pVCpu->hm.s.Event.fPending = true;
7308 pVCpu->hm.s.Event.u64IntInfo = u32IntInfo;
7309 pVCpu->hm.s.Event.u32ErrCode = u32ErrCode;
7310 pVCpu->hm.s.Event.cbInstr = cbInstr;
7311 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
7312}
7313
7314
7315/**
7316 * Sets an external interrupt as pending-for-injection into the VM.
7317 *
7318 * @param pVCpu The cross context virtual CPU structure.
7319 * @param u8Interrupt The external interrupt vector.
7320 */
7321DECLINLINE(void) hmR0VmxSetPendingExtInt(PVMCPUCC pVCpu, uint8_t u8Interrupt)
7322{
7323 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_EXIT_INT_INFO_VECTOR, u8Interrupt)
7324 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
7325 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
7326 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7327 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7328}
7329
7330
7331/**
7332 * Sets an NMI (\#NMI) exception as pending-for-injection into the VM.
7333 *
7334 * @param pVCpu The cross context virtual CPU structure.
7335 */
7336DECLINLINE(void) hmR0VmxSetPendingXcptNmi(PVMCPUCC pVCpu)
7337{
7338 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_NMI)
7339 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_NMI)
7340 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
7341 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7342 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7343}
7344
7345
7346/**
7347 * Sets a double-fault (\#DF) exception as pending-for-injection into the VM.
7348 *
7349 * @param pVCpu The cross context virtual CPU structure.
7350 */
7351DECLINLINE(void) hmR0VmxSetPendingXcptDF(PVMCPUCC pVCpu)
7352{
7353 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
7354 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7355 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
7356 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7357 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7358}
7359
7360
7361/**
7362 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
7363 *
7364 * @param pVCpu The cross context virtual CPU structure.
7365 */
7366DECLINLINE(void) hmR0VmxSetPendingXcptUD(PVMCPUCC pVCpu)
7367{
7368 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_UD)
7369 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7370 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
7371 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7372 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7373}
7374
7375
7376/**
7377 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
7378 *
7379 * @param pVCpu The cross context virtual CPU structure.
7380 */
7381DECLINLINE(void) hmR0VmxSetPendingXcptDB(PVMCPUCC pVCpu)
7382{
7383 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DB)
7384 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7385 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
7386 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7387 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7388}
7389
7390
7391#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7392/**
7393 * Sets a general-protection (\#GP) exception as pending-for-injection into the VM.
7394 *
7395 * @param pVCpu The cross context virtual CPU structure.
7396 * @param u32ErrCode The error code for the general-protection exception.
7397 */
7398DECLINLINE(void) hmR0VmxSetPendingXcptGP(PVMCPUCC pVCpu, uint32_t u32ErrCode)
7399{
7400 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
7401 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7402 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
7403 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7404 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
7405}
7406
7407
7408/**
7409 * Sets a stack (\#SS) exception as pending-for-injection into the VM.
7410 *
7411 * @param pVCpu The cross context virtual CPU structure.
7412 * @param u32ErrCode The error code for the stack exception.
7413 */
7414DECLINLINE(void) hmR0VmxSetPendingXcptSS(PVMCPUCC pVCpu, uint32_t u32ErrCode)
7415{
7416 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_SS)
7417 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7418 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
7419 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7420 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
7421}
7422#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
7423
7424
7425/**
7426 * Fixes up attributes for the specified segment register.
7427 *
7428 * @param pVCpu The cross context virtual CPU structure.
7429 * @param pSelReg The segment register that needs fixing.
7430 * @param pszRegName The register name (for logging and assertions).
7431 */
7432static void hmR0VmxFixUnusableSegRegAttr(PVMCPUCC pVCpu, PCPUMSELREG pSelReg, const char *pszRegName)
7433{
7434 Assert(pSelReg->Attr.u & X86DESCATTR_UNUSABLE);
7435
7436 /*
7437 * If VT-x marks the segment as unusable, most other bits remain undefined:
7438 * - For CS the L, D and G bits have meaning.
7439 * - For SS the DPL has meaning (it -is- the CPL for Intel and VBox).
7440 * - For the remaining data segments no bits are defined.
7441 *
7442 * The present bit and the unusable bit has been observed to be set at the
7443 * same time (the selector was supposed to be invalid as we started executing
7444 * a V8086 interrupt in ring-0).
7445 *
7446 * What should be important for the rest of the VBox code, is that the P bit is
7447 * cleared. Some of the other VBox code recognizes the unusable bit, but
7448 * AMD-V certainly don't, and REM doesn't really either. So, to be on the
7449 * safe side here, we'll strip off P and other bits we don't care about. If
7450 * any code breaks because Attr.u != 0 when Sel < 4, it should be fixed.
7451 *
7452 * See Intel spec. 27.3.2 "Saving Segment Registers and Descriptor-Table Registers".
7453 */
7454#ifdef VBOX_STRICT
7455 uint32_t const uAttr = pSelReg->Attr.u;
7456#endif
7457
7458 /* Masking off: X86DESCATTR_P, X86DESCATTR_LIMIT_HIGH, and X86DESCATTR_AVL. The latter two are really irrelevant. */
7459 pSelReg->Attr.u &= X86DESCATTR_UNUSABLE | X86DESCATTR_L | X86DESCATTR_D | X86DESCATTR_G
7460 | X86DESCATTR_DPL | X86DESCATTR_TYPE | X86DESCATTR_DT;
7461
7462#ifdef VBOX_STRICT
7463 VMMRZCallRing3Disable(pVCpu);
7464 Log4Func(("Unusable %s: sel=%#x attr=%#x -> %#x\n", pszRegName, pSelReg->Sel, uAttr, pSelReg->Attr.u));
7465# ifdef DEBUG_bird
7466 AssertMsg((uAttr & ~X86DESCATTR_P) == pSelReg->Attr.u,
7467 ("%s: %#x != %#x (sel=%#x base=%#llx limit=%#x)\n",
7468 pszRegName, uAttr, pSelReg->Attr.u, pSelReg->Sel, pSelReg->u64Base, pSelReg->u32Limit));
7469# endif
7470 VMMRZCallRing3Enable(pVCpu);
7471 NOREF(uAttr);
7472#endif
7473 RT_NOREF2(pVCpu, pszRegName);
7474}
7475
7476
7477/**
7478 * Imports a guest segment register from the current VMCS into the guest-CPU
7479 * context.
7480 *
7481 * @param pVCpu The cross context virtual CPU structure.
7482 * @param iSegReg The segment register number (X86_SREG_XXX).
7483 *
7484 * @remarks Called with interrupts and/or preemption disabled.
7485 */
7486static void hmR0VmxImportGuestSegReg(PVMCPUCC pVCpu, uint32_t iSegReg)
7487{
7488 Assert(iSegReg < X86_SREG_COUNT);
7489 Assert((uint32_t)VMX_VMCS16_GUEST_SEG_SEL(iSegReg) == g_aVmcsSegSel[iSegReg]);
7490 Assert((uint32_t)VMX_VMCS32_GUEST_SEG_LIMIT(iSegReg) == g_aVmcsSegLimit[iSegReg]);
7491 Assert((uint32_t)VMX_VMCS32_GUEST_SEG_ACCESS_RIGHTS(iSegReg) == g_aVmcsSegAttr[iSegReg]);
7492 Assert((uint32_t)VMX_VMCS_GUEST_SEG_BASE(iSegReg) == g_aVmcsSegBase[iSegReg]);
7493
7494 PCPUMSELREG pSelReg = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
7495
7496 uint16_t u16Sel;
7497 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_SEG_SEL(iSegReg), &u16Sel); AssertRC(rc);
7498 pSelReg->Sel = u16Sel;
7499 pSelReg->ValidSel = u16Sel;
7500
7501 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SEG_LIMIT(iSegReg), &pSelReg->u32Limit); AssertRC(rc);
7502 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SEG_BASE(iSegReg), &pSelReg->u64Base); AssertRC(rc);
7503
7504 uint32_t u32Attr;
7505 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SEG_ACCESS_RIGHTS(iSegReg), &u32Attr); AssertRC(rc);
7506 pSelReg->Attr.u = u32Attr;
7507 if (u32Attr & X86DESCATTR_UNUSABLE)
7508 hmR0VmxFixUnusableSegRegAttr(pVCpu, pSelReg, "ES\0CS\0SS\0DS\0FS\0GS" + iSegReg * 3);
7509
7510 pSelReg->fFlags = CPUMSELREG_FLAGS_VALID;
7511}
7512
7513
7514/**
7515 * Imports the guest LDTR from the current VMCS into the guest-CPU context.
7516 *
7517 * @param pVCpu The cross context virtual CPU structure.
7518 *
7519 * @remarks Called with interrupts and/or preemption disabled.
7520 */
7521static void hmR0VmxImportGuestLdtr(PVMCPUCC pVCpu)
7522{
7523 uint16_t u16Sel;
7524 uint64_t u64Base;
7525 uint32_t u32Limit, u32Attr;
7526 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, &u16Sel); AssertRC(rc);
7527 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, &u32Limit); AssertRC(rc);
7528 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7529 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, &u64Base); AssertRC(rc);
7530
7531 pVCpu->cpum.GstCtx.ldtr.Sel = u16Sel;
7532 pVCpu->cpum.GstCtx.ldtr.ValidSel = u16Sel;
7533 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
7534 pVCpu->cpum.GstCtx.ldtr.u32Limit = u32Limit;
7535 pVCpu->cpum.GstCtx.ldtr.u64Base = u64Base;
7536 pVCpu->cpum.GstCtx.ldtr.Attr.u = u32Attr;
7537 if (u32Attr & X86DESCATTR_UNUSABLE)
7538 hmR0VmxFixUnusableSegRegAttr(pVCpu, &pVCpu->cpum.GstCtx.ldtr, "LDTR");
7539}
7540
7541
7542/**
7543 * Imports the guest TR from the current VMCS into the guest-CPU context.
7544 *
7545 * @param pVCpu The cross context virtual CPU structure.
7546 *
7547 * @remarks Called with interrupts and/or preemption disabled.
7548 */
7549static void hmR0VmxImportGuestTr(PVMCPUCC pVCpu)
7550{
7551 uint16_t u16Sel;
7552 uint64_t u64Base;
7553 uint32_t u32Limit, u32Attr;
7554 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_TR_SEL, &u16Sel); AssertRC(rc);
7555 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, &u32Limit); AssertRC(rc);
7556 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7557 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_TR_BASE, &u64Base); AssertRC(rc);
7558
7559 pVCpu->cpum.GstCtx.tr.Sel = u16Sel;
7560 pVCpu->cpum.GstCtx.tr.ValidSel = u16Sel;
7561 pVCpu->cpum.GstCtx.tr.fFlags = CPUMSELREG_FLAGS_VALID;
7562 pVCpu->cpum.GstCtx.tr.u32Limit = u32Limit;
7563 pVCpu->cpum.GstCtx.tr.u64Base = u64Base;
7564 pVCpu->cpum.GstCtx.tr.Attr.u = u32Attr;
7565 /* TR is the only selector that can never be unusable. */
7566 Assert(!(u32Attr & X86DESCATTR_UNUSABLE));
7567}
7568
7569
7570/**
7571 * Imports the guest RIP from the VMCS back into the guest-CPU context.
7572 *
7573 * @param pVCpu The cross context virtual CPU structure.
7574 *
7575 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7576 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7577 * instead!!!
7578 */
7579static void hmR0VmxImportGuestRip(PVMCPUCC pVCpu)
7580{
7581 uint64_t u64Val;
7582 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7583 if (pCtx->fExtrn & CPUMCTX_EXTRN_RIP)
7584 {
7585 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
7586 AssertRC(rc);
7587
7588 pCtx->rip = u64Val;
7589 EMR0HistoryUpdatePC(pVCpu, pCtx->rip, false);
7590 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RIP;
7591 }
7592}
7593
7594
7595/**
7596 * Imports the guest RFLAGS from the VMCS back into the guest-CPU context.
7597 *
7598 * @param pVCpu The cross context virtual CPU structure.
7599 * @param pVmcsInfo The VMCS info. object.
7600 *
7601 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7602 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7603 * instead!!!
7604 */
7605static void hmR0VmxImportGuestRFlags(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7606{
7607 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7608 if (pCtx->fExtrn & CPUMCTX_EXTRN_RFLAGS)
7609 {
7610 uint64_t u64Val;
7611 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
7612 AssertRC(rc);
7613
7614 pCtx->rflags.u64 = u64Val;
7615 PCVMXVMCSINFOSHARED pVmcsInfoShared = pVmcsInfo->pShared;
7616 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
7617 {
7618 pCtx->eflags.Bits.u1VM = 0;
7619 pCtx->eflags.Bits.u2IOPL = pVmcsInfoShared->RealMode.Eflags.Bits.u2IOPL;
7620 }
7621 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RFLAGS;
7622 }
7623}
7624
7625
7626/**
7627 * Imports the guest interruptibility-state from the VMCS back into the guest-CPU
7628 * context.
7629 *
7630 * @param pVCpu The cross context virtual CPU structure.
7631 * @param pVmcsInfo The VMCS info. object.
7632 *
7633 * @remarks Called with interrupts and/or preemption disabled, try not to assert and
7634 * do not log!
7635 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7636 * instead!!!
7637 */
7638static void hmR0VmxImportGuestIntrState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7639{
7640 uint32_t u32Val;
7641 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32Val); AssertRC(rc);
7642 if (!u32Val)
7643 {
7644 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7645 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7646 CPUMSetGuestNmiBlocking(pVCpu, false);
7647 }
7648 else
7649 {
7650 /*
7651 * We must import RIP here to set our EM interrupt-inhibited state.
7652 * We also import RFLAGS as our code that evaluates pending interrupts
7653 * before VM-entry requires it.
7654 */
7655 hmR0VmxImportGuestRip(pVCpu);
7656 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7657
7658 if (u32Val & (VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS | VMX_VMCS_GUEST_INT_STATE_BLOCK_STI))
7659 EMSetInhibitInterruptsPC(pVCpu, pVCpu->cpum.GstCtx.rip);
7660 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7661 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7662
7663 bool const fNmiBlocking = RT_BOOL(u32Val & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
7664 CPUMSetGuestNmiBlocking(pVCpu, fNmiBlocking);
7665 }
7666}
7667
7668
7669/**
7670 * Worker for VMXR0ImportStateOnDemand.
7671 *
7672 * @returns VBox status code.
7673 * @param pVCpu The cross context virtual CPU structure.
7674 * @param pVmcsInfo The VMCS info. object.
7675 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7676 */
7677static int hmR0VmxImportGuestState(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint64_t fWhat)
7678{
7679 int rc = VINF_SUCCESS;
7680 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7681 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7682 uint32_t u32Val;
7683
7684 /*
7685 * Note! This is hack to workaround a mysterious BSOD observed with release builds
7686 * on Windows 10 64-bit hosts. Profile and debug builds are not affected and
7687 * neither are other host platforms.
7688 *
7689 * Committing this temporarily as it prevents BSOD.
7690 *
7691 * Update: This is very likely a compiler optimization bug, see @bugref{9180}.
7692 */
7693#ifdef RT_OS_WINDOWS
7694 if (pVM == 0 || pVM == (void *)(uintptr_t)-1)
7695 return VERR_HM_IPE_1;
7696#endif
7697
7698 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatImportGuestState, x);
7699
7700 /*
7701 * We disable interrupts to make the updating of the state and in particular
7702 * the fExtrn modification atomic wrt to preemption hooks.
7703 */
7704 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
7705
7706 fWhat &= pCtx->fExtrn;
7707 if (fWhat)
7708 {
7709 do
7710 {
7711 if (fWhat & CPUMCTX_EXTRN_RIP)
7712 hmR0VmxImportGuestRip(pVCpu);
7713
7714 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
7715 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7716
7717 if (fWhat & CPUMCTX_EXTRN_HM_VMX_INT_STATE)
7718 hmR0VmxImportGuestIntrState(pVCpu, pVmcsInfo);
7719
7720 if (fWhat & CPUMCTX_EXTRN_RSP)
7721 {
7722 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RSP, &pCtx->rsp);
7723 AssertRC(rc);
7724 }
7725
7726 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
7727 {
7728 PVMXVMCSINFOSHARED pVmcsInfoShared = pVmcsInfo->pShared;
7729 bool const fRealOnV86Active = pVmcsInfoShared->RealMode.fRealOnV86Active;
7730 if (fWhat & CPUMCTX_EXTRN_CS)
7731 {
7732 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_CS);
7733 hmR0VmxImportGuestRip(pVCpu);
7734 if (fRealOnV86Active)
7735 pCtx->cs.Attr.u = pVmcsInfoShared->RealMode.AttrCS.u;
7736 EMR0HistoryUpdatePC(pVCpu, pCtx->cs.u64Base + pCtx->rip, true /* fFlattened */);
7737 }
7738 if (fWhat & CPUMCTX_EXTRN_SS)
7739 {
7740 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_SS);
7741 if (fRealOnV86Active)
7742 pCtx->ss.Attr.u = pVmcsInfoShared->RealMode.AttrSS.u;
7743 }
7744 if (fWhat & CPUMCTX_EXTRN_DS)
7745 {
7746 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_DS);
7747 if (fRealOnV86Active)
7748 pCtx->ds.Attr.u = pVmcsInfoShared->RealMode.AttrDS.u;
7749 }
7750 if (fWhat & CPUMCTX_EXTRN_ES)
7751 {
7752 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_ES);
7753 if (fRealOnV86Active)
7754 pCtx->es.Attr.u = pVmcsInfoShared->RealMode.AttrES.u;
7755 }
7756 if (fWhat & CPUMCTX_EXTRN_FS)
7757 {
7758 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_FS);
7759 if (fRealOnV86Active)
7760 pCtx->fs.Attr.u = pVmcsInfoShared->RealMode.AttrFS.u;
7761 }
7762 if (fWhat & CPUMCTX_EXTRN_GS)
7763 {
7764 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_GS);
7765 if (fRealOnV86Active)
7766 pCtx->gs.Attr.u = pVmcsInfoShared->RealMode.AttrGS.u;
7767 }
7768 }
7769
7770 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
7771 {
7772 if (fWhat & CPUMCTX_EXTRN_LDTR)
7773 hmR0VmxImportGuestLdtr(pVCpu);
7774
7775 if (fWhat & CPUMCTX_EXTRN_GDTR)
7776 {
7777 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &pCtx->gdtr.pGdt); AssertRC(rc);
7778 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val); AssertRC(rc);
7779 pCtx->gdtr.cbGdt = u32Val;
7780 }
7781
7782 /* Guest IDTR. */
7783 if (fWhat & CPUMCTX_EXTRN_IDTR)
7784 {
7785 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &pCtx->idtr.pIdt); AssertRC(rc);
7786 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val); AssertRC(rc);
7787 pCtx->idtr.cbIdt = u32Val;
7788 }
7789
7790 /* Guest TR. */
7791 if (fWhat & CPUMCTX_EXTRN_TR)
7792 {
7793 /* Real-mode emulation using virtual-8086 mode has the fake TSS (pRealModeTSS) in TR,
7794 don't need to import that one. */
7795 if (!pVmcsInfo->pShared->RealMode.fRealOnV86Active)
7796 hmR0VmxImportGuestTr(pVCpu);
7797 }
7798 }
7799
7800 if (fWhat & CPUMCTX_EXTRN_DR7)
7801 {
7802 if (!pVCpu->hmr0.s.fUsingHyperDR7)
7803 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_DR7, &pCtx->dr[7]); AssertRC(rc);
7804 }
7805
7806 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
7807 {
7808 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, &pCtx->SysEnter.eip); AssertRC(rc);
7809 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, &pCtx->SysEnter.esp); AssertRC(rc);
7810 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, &u32Val); AssertRC(rc);
7811 pCtx->SysEnter.cs = u32Val;
7812 }
7813
7814 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
7815 {
7816 if ( pVM->hmr0.s.fAllow64BitGuests
7817 && (pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7818 pCtx->msrKERNELGSBASE = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
7819 }
7820
7821 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
7822 {
7823 if ( pVM->hmr0.s.fAllow64BitGuests
7824 && (pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7825 {
7826 pCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
7827 pCtx->msrSTAR = ASMRdMsr(MSR_K6_STAR);
7828 pCtx->msrSFMASK = ASMRdMsr(MSR_K8_SF_MASK);
7829 }
7830 }
7831
7832 if (fWhat & (CPUMCTX_EXTRN_TSC_AUX | CPUMCTX_EXTRN_OTHER_MSRS))
7833 {
7834 PVMXVMCSINFOSHARED pVmcsInfoShared = pVmcsInfo->pShared;
7835 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
7836 uint32_t const cMsrs = pVmcsInfo->cExitMsrStore;
7837 Assert(pMsrs);
7838 Assert(cMsrs <= VMX_MISC_MAX_MSRS(g_HmMsrs.u.vmx.u64Misc));
7839 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
7840 for (uint32_t i = 0; i < cMsrs; i++)
7841 {
7842 uint32_t const idMsr = pMsrs[i].u32Msr;
7843 switch (idMsr)
7844 {
7845 case MSR_K8_TSC_AUX: CPUMSetGuestTscAux(pVCpu, pMsrs[i].u64Value); break;
7846 case MSR_IA32_SPEC_CTRL: CPUMSetGuestSpecCtrl(pVCpu, pMsrs[i].u64Value); break;
7847 case MSR_K6_EFER: /* Can't be changed without causing a VM-exit */ break;
7848 default:
7849 {
7850 uint32_t idxLbrMsr;
7851 if (pVM->hmr0.s.vmx.fLbr)
7852 {
7853 if (hmR0VmxIsLbrBranchFromMsr(pVM, idMsr, &idxLbrMsr))
7854 {
7855 Assert(idxLbrMsr < RT_ELEMENTS(pVmcsInfoShared->au64LbrFromIpMsr));
7856 pVmcsInfoShared->au64LbrFromIpMsr[idxLbrMsr] = pMsrs[i].u64Value;
7857 break;
7858 }
7859 if (hmR0VmxIsLbrBranchToMsr(pVM, idMsr, &idxLbrMsr))
7860 {
7861 Assert(idxLbrMsr < RT_ELEMENTS(pVmcsInfoShared->au64LbrFromIpMsr));
7862 pVmcsInfoShared->au64LbrToIpMsr[idxLbrMsr] = pMsrs[i].u64Value;
7863 break;
7864 }
7865 if (idMsr == pVM->hmr0.s.vmx.idLbrTosMsr)
7866 {
7867 pVmcsInfoShared->u64LbrTosMsr = pMsrs[i].u64Value;
7868 break;
7869 }
7870 /* Fallthru (no break) */
7871 }
7872 pCtx->fExtrn = 0;
7873 pVCpu->hm.s.u32HMError = pMsrs->u32Msr;
7874 ASMSetFlags(fEFlags);
7875 AssertMsgFailed(("Unexpected MSR in auto-load/store area. idMsr=%#RX32 cMsrs=%u\n", idMsr, cMsrs));
7876 return VERR_HM_UNEXPECTED_LD_ST_MSR;
7877 }
7878 }
7879 }
7880 }
7881
7882 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
7883 {
7884 if (fWhat & CPUMCTX_EXTRN_CR0)
7885 {
7886 uint64_t u64Cr0;
7887 uint64_t u64Shadow;
7888 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Cr0); AssertRC(rc);
7889 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Shadow); AssertRC(rc);
7890#ifndef VBOX_WITH_NESTED_HWVIRT_VMX
7891 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7892 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7893#else
7894 if (!CPUMIsGuestInVmxNonRootMode(pCtx))
7895 {
7896 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7897 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7898 }
7899 else
7900 {
7901 /*
7902 * We've merged the guest and nested-guest's CR0 guest/host mask while executing
7903 * the nested-guest using hardware-assisted VMX. Accordingly we need to
7904 * re-construct CR0. See @bugref{9180#c95} for details.
7905 */
7906 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hmr0.s.vmx.VmcsInfo;
7907 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
7908 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7909 | (pVmcsNstGst->u64GuestCr0.u & pVmcsNstGst->u64Cr0Mask.u)
7910 | (u64Shadow & (pVmcsInfoGst->u64Cr0Mask & ~pVmcsNstGst->u64Cr0Mask.u));
7911 }
7912#endif
7913 VMMRZCallRing3Disable(pVCpu); /* May call into PGM which has Log statements. */
7914 CPUMSetGuestCR0(pVCpu, u64Cr0);
7915 VMMRZCallRing3Enable(pVCpu);
7916 }
7917
7918 if (fWhat & CPUMCTX_EXTRN_CR4)
7919 {
7920 uint64_t u64Cr4;
7921 uint64_t u64Shadow;
7922 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64Cr4); AssertRC(rc);
7923 rc |= VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Shadow); AssertRC(rc);
7924#ifndef VBOX_WITH_NESTED_HWVIRT_VMX
7925 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7926 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7927#else
7928 if (!CPUMIsGuestInVmxNonRootMode(pCtx))
7929 {
7930 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7931 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7932 }
7933 else
7934 {
7935 /*
7936 * We've merged the guest and nested-guest's CR4 guest/host mask while executing
7937 * the nested-guest using hardware-assisted VMX. Accordingly we need to
7938 * re-construct CR4. See @bugref{9180#c95} for details.
7939 */
7940 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hmr0.s.vmx.VmcsInfo;
7941 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
7942 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7943 | (pVmcsNstGst->u64GuestCr4.u & pVmcsNstGst->u64Cr4Mask.u)
7944 | (u64Shadow & (pVmcsInfoGst->u64Cr4Mask & ~pVmcsNstGst->u64Cr4Mask.u));
7945 }
7946#endif
7947 pCtx->cr4 = u64Cr4;
7948 }
7949
7950 if (fWhat & CPUMCTX_EXTRN_CR3)
7951 {
7952 /* CR0.PG bit changes are always intercepted, so it's up to date. */
7953 if ( pVM->hmr0.s.vmx.fUnrestrictedGuest
7954 || ( pVM->hmr0.s.fNestedPaging
7955 && CPUMIsGuestPagingEnabledEx(pCtx)))
7956 {
7957 uint64_t u64Cr3;
7958 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR3, &u64Cr3); AssertRC(rc);
7959 if (pCtx->cr3 != u64Cr3)
7960 {
7961 pCtx->cr3 = u64Cr3;
7962 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
7963 }
7964
7965 /* If the guest is in PAE mode, sync back the PDPE's into the guest state.
7966 Note: CR4.PAE, CR0.PG, EFER MSR changes are always intercepted, so they're up to date. */
7967 if (CPUMIsGuestInPAEModeEx(pCtx))
7968 {
7969 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
7970 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
7971 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
7972 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
7973 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES);
7974 }
7975 }
7976 }
7977 }
7978
7979#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7980 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
7981 {
7982 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
7983 && !CPUMIsGuestInVmxNonRootMode(pCtx))
7984 {
7985 Assert(CPUMIsGuestInVmxRootMode(pCtx));
7986 rc = hmR0VmxCopyShadowToNstGstVmcs(pVCpu, pVmcsInfo);
7987 if (RT_SUCCESS(rc))
7988 { /* likely */ }
7989 else
7990 break;
7991 }
7992 }
7993#endif
7994 } while (0);
7995
7996 if (RT_SUCCESS(rc))
7997 {
7998 /* Update fExtrn. */
7999 pCtx->fExtrn &= ~fWhat;
8000
8001 /* If everything has been imported, clear the HM keeper bit. */
8002 if (!(pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL))
8003 {
8004 pCtx->fExtrn &= ~CPUMCTX_EXTRN_KEEPER_HM;
8005 Assert(!pCtx->fExtrn);
8006 }
8007 }
8008 }
8009 else
8010 AssertMsg(!pCtx->fExtrn || (pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL), ("%#RX64\n", pCtx->fExtrn));
8011
8012 /*
8013 * Restore interrupts.
8014 */
8015 ASMSetFlags(fEFlags);
8016
8017 STAM_PROFILE_ADV_STOP(& pVCpu->hm.s.StatImportGuestState, x);
8018
8019 if (RT_SUCCESS(rc))
8020 { /* likely */ }
8021 else
8022 return rc;
8023
8024 /*
8025 * Honor any pending CR3 updates.
8026 *
8027 * Consider this scenario: VM-exit -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp -> VMXR0CallRing3Callback()
8028 * -> VMMRZCallRing3Disable() -> hmR0VmxImportGuestState() -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp
8029 * -> continue with VM-exit handling -> hmR0VmxImportGuestState() and here we are.
8030 *
8031 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be up-to-date and thus
8032 * if any CR3-saves -before- the VM-exit (longjmp) postponed the CR3 update via the force-flag, any VM-exit handler that
8033 * calls into PGM when it re-saves CR3 will end up here and we call PGMUpdateCR3(). This is why the code below should
8034 * -NOT- check if CPUMCTX_EXTRN_CR3 is set!
8035 *
8036 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again. We cover for it here.
8037 */
8038 if (VMMRZCallRing3IsEnabled(pVCpu))
8039 {
8040 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
8041 {
8042 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & CPUMCTX_EXTRN_CR3));
8043 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
8044 }
8045
8046 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
8047 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
8048
8049 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
8050 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
8051 }
8052
8053 return VINF_SUCCESS;
8054}
8055
8056
8057/**
8058 * Saves the guest state from the VMCS into the guest-CPU context.
8059 *
8060 * @returns VBox status code.
8061 * @param pVCpu The cross context virtual CPU structure.
8062 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
8063 */
8064VMMR0DECL(int) VMXR0ImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
8065{
8066 AssertPtr(pVCpu);
8067 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8068 return hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fWhat);
8069}
8070
8071
8072/**
8073 * Check per-VM and per-VCPU force flag actions that require us to go back to
8074 * ring-3 for one reason or another.
8075 *
8076 * @returns Strict VBox status code (i.e. informational status codes too)
8077 * @retval VINF_SUCCESS if we don't have any actions that require going back to
8078 * ring-3.
8079 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
8080 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
8081 * interrupts)
8082 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
8083 * all EMTs to be in ring-3.
8084 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
8085 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
8086 * to the EM loop.
8087 *
8088 * @param pVCpu The cross context virtual CPU structure.
8089 * @param pVmxTransient The VMX-transient structure.
8090 * @param fStepping Whether we are single-stepping the guest using the
8091 * hypervisor debugger.
8092 *
8093 * @remarks This might cause nested-guest VM-exits, caller must check if the guest
8094 * is no longer in VMX non-root mode.
8095 */
8096static VBOXSTRICTRC hmR0VmxCheckForceFlags(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, bool fStepping)
8097{
8098 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8099
8100 /*
8101 * Update pending interrupts into the APIC's IRR.
8102 */
8103 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
8104 APICUpdatePendingInterrupts(pVCpu);
8105
8106 /*
8107 * Anything pending? Should be more likely than not if we're doing a good job.
8108 */
8109 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
8110 if ( !fStepping
8111 ? !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_MASK)
8112 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_MASK)
8113 : !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_STEP_MASK)
8114 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
8115 return VINF_SUCCESS;
8116
8117 /* Pending PGM C3 sync. */
8118 if (VMCPU_FF_IS_ANY_SET(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
8119 {
8120 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8121 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & (CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4)));
8122 VBOXSTRICTRC rcStrict = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4,
8123 VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
8124 if (rcStrict != VINF_SUCCESS)
8125 {
8126 AssertRC(VBOXSTRICTRC_VAL(rcStrict));
8127 Log4Func(("PGMSyncCR3 forcing us back to ring-3. rc2=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
8128 return rcStrict;
8129 }
8130 }
8131
8132 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
8133 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_HM_TO_R3_MASK)
8134 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
8135 {
8136 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
8137 int rc = RT_LIKELY(!VM_FF_IS_SET(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_RAW_TO_R3 : VINF_EM_NO_MEMORY;
8138 Log4Func(("HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
8139 return rc;
8140 }
8141
8142 /* Pending VM request packets, such as hardware interrupts. */
8143 if ( VM_FF_IS_SET(pVM, VM_FF_REQUEST)
8144 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_REQUEST))
8145 {
8146 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchVmReq);
8147 Log4Func(("Pending VM request forcing us back to ring-3\n"));
8148 return VINF_EM_PENDING_REQUEST;
8149 }
8150
8151 /* Pending PGM pool flushes. */
8152 if (VM_FF_IS_SET(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
8153 {
8154 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPgmPoolFlush);
8155 Log4Func(("PGM pool flush pending forcing us back to ring-3\n"));
8156 return VINF_PGM_POOL_FLUSH_PENDING;
8157 }
8158
8159 /* Pending DMA requests. */
8160 if (VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))
8161 {
8162 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchDma);
8163 Log4Func(("Pending DMA request forcing us back to ring-3\n"));
8164 return VINF_EM_RAW_TO_R3;
8165 }
8166
8167#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8168 /*
8169 * Pending nested-guest events.
8170 *
8171 * Please note the priority of these events are specified and important.
8172 * See Intel spec. 29.4.3.2 "APIC-Write Emulation".
8173 * See Intel spec. 6.9 "Priority Among Simultaneous Exceptions And Interrupts".
8174 */
8175 if (pVmxTransient->fIsNestedGuest)
8176 {
8177 /* Pending nested-guest APIC-write. */
8178 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_APIC_WRITE))
8179 {
8180 Log4Func(("Pending nested-guest APIC-write\n"));
8181 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitApicWrite(pVCpu);
8182 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8183 return rcStrict;
8184 }
8185
8186 /* Pending nested-guest monitor-trap flag (MTF). */
8187 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_MTF))
8188 {
8189 Log4Func(("Pending nested-guest MTF\n"));
8190 VBOXSTRICTRC rcStrict = IEMExecVmxVmexit(pVCpu, VMX_EXIT_MTF, 0 /* uExitQual */);
8191 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8192 return rcStrict;
8193 }
8194
8195 /* Pending nested-guest VMX-preemption timer expired. */
8196 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_PREEMPT_TIMER))
8197 {
8198 Log4Func(("Pending nested-guest preempt timer\n"));
8199 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitPreemptTimer(pVCpu);
8200 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8201 return rcStrict;
8202 }
8203 }
8204#else
8205 NOREF(pVmxTransient);
8206#endif
8207
8208 return VINF_SUCCESS;
8209}
8210
8211
8212/**
8213 * Converts any TRPM trap into a pending HM event. This is typically used when
8214 * entering from ring-3 (not longjmp returns).
8215 *
8216 * @param pVCpu The cross context virtual CPU structure.
8217 */
8218static void hmR0VmxTrpmTrapToPendingEvent(PVMCPUCC pVCpu)
8219{
8220 Assert(TRPMHasTrap(pVCpu));
8221 Assert(!pVCpu->hm.s.Event.fPending);
8222
8223 uint8_t uVector;
8224 TRPMEVENT enmTrpmEvent;
8225 uint32_t uErrCode;
8226 RTGCUINTPTR GCPtrFaultAddress;
8227 uint8_t cbInstr;
8228 bool fIcebp;
8229
8230 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr, &fIcebp);
8231 AssertRC(rc);
8232
8233 uint32_t u32IntInfo;
8234 u32IntInfo = uVector | VMX_IDT_VECTORING_INFO_VALID;
8235 u32IntInfo |= HMTrpmEventTypeToVmxEventType(uVector, enmTrpmEvent, fIcebp);
8236
8237 rc = TRPMResetTrap(pVCpu);
8238 AssertRC(rc);
8239 Log4(("TRPM->HM event: u32IntInfo=%#RX32 enmTrpmEvent=%d cbInstr=%u uErrCode=%#RX32 GCPtrFaultAddress=%#RGv\n",
8240 u32IntInfo, enmTrpmEvent, cbInstr, uErrCode, GCPtrFaultAddress));
8241
8242 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, uErrCode, GCPtrFaultAddress);
8243}
8244
8245
8246/**
8247 * Converts the pending HM event into a TRPM trap.
8248 *
8249 * @param pVCpu The cross context virtual CPU structure.
8250 */
8251static void hmR0VmxPendingEventToTrpmTrap(PVMCPUCC pVCpu)
8252{
8253 Assert(pVCpu->hm.s.Event.fPending);
8254
8255 /* If a trap was already pending, we did something wrong! */
8256 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
8257
8258 uint32_t const u32IntInfo = pVCpu->hm.s.Event.u64IntInfo;
8259 uint32_t const uVector = VMX_IDT_VECTORING_INFO_VECTOR(u32IntInfo);
8260 TRPMEVENT const enmTrapType = HMVmxEventTypeToTrpmEventType(u32IntInfo);
8261
8262 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, enmTrapType));
8263
8264 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
8265 AssertRC(rc);
8266
8267 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
8268 TRPMSetErrorCode(pVCpu, pVCpu->hm.s.Event.u32ErrCode);
8269
8270 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(u32IntInfo))
8271 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
8272 else
8273 {
8274 uint8_t const uVectorType = VMX_IDT_VECTORING_INFO_TYPE(u32IntInfo);
8275 switch (uVectorType)
8276 {
8277 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
8278 TRPMSetTrapDueToIcebp(pVCpu);
8279 RT_FALL_THRU();
8280 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
8281 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT:
8282 {
8283 AssertMsg( uVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
8284 || ( uVector == X86_XCPT_BP /* INT3 */
8285 || uVector == X86_XCPT_OF /* INTO */
8286 || uVector == X86_XCPT_DB /* INT1 (ICEBP) */),
8287 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
8288 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
8289 break;
8290 }
8291 }
8292 }
8293
8294 /* We're now done converting the pending event. */
8295 pVCpu->hm.s.Event.fPending = false;
8296}
8297
8298
8299/**
8300 * Sets the interrupt-window exiting control in the VMCS which instructs VT-x to
8301 * cause a VM-exit as soon as the guest is in a state to receive interrupts.
8302 *
8303 * @param pVmcsInfo The VMCS info. object.
8304 */
8305static void hmR0VmxSetIntWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
8306{
8307 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_INT_WINDOW_EXIT)
8308 {
8309 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT))
8310 {
8311 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_INT_WINDOW_EXIT;
8312 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
8313 AssertRC(rc);
8314 }
8315 } /* else we will deliver interrupts whenever the guest Vm-exits next and is in a state to receive the interrupt. */
8316}
8317
8318
8319/**
8320 * Clears the interrupt-window exiting control in the VMCS.
8321 *
8322 * @param pVmcsInfo The VMCS info. object.
8323 */
8324DECLINLINE(void) hmR0VmxClearIntWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
8325{
8326 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT)
8327 {
8328 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_INT_WINDOW_EXIT;
8329 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
8330 AssertRC(rc);
8331 }
8332}
8333
8334
8335/**
8336 * Sets the NMI-window exiting control in the VMCS which instructs VT-x to
8337 * cause a VM-exit as soon as the guest is in a state to receive NMIs.
8338 *
8339 * @param pVmcsInfo The VMCS info. object.
8340 */
8341static void hmR0VmxSetNmiWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
8342{
8343 if (g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
8344 {
8345 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))
8346 {
8347 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_NMI_WINDOW_EXIT;
8348 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
8349 AssertRC(rc);
8350 Log4Func(("Setup NMI-window exiting\n"));
8351 }
8352 } /* else we will deliver NMIs whenever we VM-exit next, even possibly nesting NMIs. Can't be helped on ancient CPUs. */
8353}
8354
8355
8356/**
8357 * Clears the NMI-window exiting control in the VMCS.
8358 *
8359 * @param pVmcsInfo The VMCS info. object.
8360 */
8361DECLINLINE(void) hmR0VmxClearNmiWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
8362{
8363 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
8364 {
8365 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_NMI_WINDOW_EXIT;
8366 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
8367 AssertRC(rc);
8368 }
8369}
8370
8371
8372/**
8373 * Does the necessary state syncing before returning to ring-3 for any reason
8374 * (longjmp, preemption, voluntary exits to ring-3) from VT-x.
8375 *
8376 * @returns VBox status code.
8377 * @param pVCpu The cross context virtual CPU structure.
8378 * @param fImportState Whether to import the guest state from the VMCS back
8379 * to the guest-CPU context.
8380 *
8381 * @remarks No-long-jmp zone!!!
8382 */
8383static int hmR0VmxLeave(PVMCPUCC pVCpu, bool fImportState)
8384{
8385 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8386 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8387
8388 RTCPUID const idCpu = RTMpCpuId();
8389 Log4Func(("HostCpuId=%u\n", idCpu));
8390
8391 /*
8392 * !!! IMPORTANT !!!
8393 * If you modify code here, check whether VMXR0CallRing3Callback() needs to be updated too.
8394 */
8395
8396 /* Save the guest state if necessary. */
8397 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8398 if (fImportState)
8399 {
8400 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
8401 AssertRCReturn(rc, rc);
8402 }
8403
8404 /* Restore host FPU state if necessary. We will resync on next R0 reentry. */
8405 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
8406 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
8407
8408 /* Restore host debug registers if necessary. We will resync on next R0 reentry. */
8409#ifdef VBOX_STRICT
8410 if (CPUMIsHyperDebugStateActive(pVCpu))
8411 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_MOV_DR_EXIT);
8412#endif
8413 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
8414 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
8415 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
8416
8417 /* Restore host-state bits that VT-x only restores partially. */
8418 if (pVCpu->hmr0.s.vmx.fRestoreHostFlags > VMX_RESTORE_HOST_REQUIRED)
8419 {
8420 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hmr0.s.vmx.fRestoreHostFlags, idCpu));
8421 VMXRestoreHostState(pVCpu->hmr0.s.vmx.fRestoreHostFlags, &pVCpu->hmr0.s.vmx.RestoreHost);
8422 }
8423 pVCpu->hmr0.s.vmx.fRestoreHostFlags = 0;
8424
8425 /* Restore the lazy host MSRs as we're leaving VT-x context. */
8426 if (pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
8427 {
8428 /* We shouldn't restore the host MSRs without saving the guest MSRs first. */
8429 if (!fImportState)
8430 {
8431 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_KERNEL_GS_BASE | CPUMCTX_EXTRN_SYSCALL_MSRS);
8432 AssertRCReturn(rc, rc);
8433 }
8434 hmR0VmxLazyRestoreHostMsrs(pVCpu);
8435 Assert(!pVCpu->hmr0.s.vmx.fLazyMsrs);
8436 }
8437 else
8438 pVCpu->hmr0.s.vmx.fLazyMsrs = 0;
8439
8440 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
8441 pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs = false;
8442
8443 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
8444 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatImportGuestState);
8445 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExportGuestState);
8446 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatPreExit);
8447 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitHandling);
8448 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitIO);
8449 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitMovCRx);
8450 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitXcptNmi);
8451 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitVmentry);
8452 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8453
8454 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8455
8456 /** @todo This partially defeats the purpose of having preemption hooks.
8457 * The problem is, deregistering the hooks should be moved to a place that
8458 * lasts until the EMT is about to be destroyed not everytime while leaving HM
8459 * context.
8460 */
8461 int rc = hmR0VmxClearVmcs(pVmcsInfo);
8462 AssertRCReturn(rc, rc);
8463
8464#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8465 /*
8466 * A valid shadow VMCS is made active as part of VM-entry. It is necessary to
8467 * clear a shadow VMCS before allowing that VMCS to become active on another
8468 * logical processor. We may or may not be importing guest state which clears
8469 * it, so cover for it here.
8470 *
8471 * See Intel spec. 24.11.1 "Software Use of Virtual-Machine Control Structures".
8472 */
8473 if ( pVmcsInfo->pvShadowVmcs
8474 && pVmcsInfo->fShadowVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
8475 {
8476 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
8477 AssertRCReturn(rc, rc);
8478 }
8479
8480 /*
8481 * Flag that we need to re-export the host state if we switch to this VMCS before
8482 * executing guest or nested-guest code.
8483 */
8484 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
8485#endif
8486
8487 Log4Func(("Cleared Vmcs. HostCpuId=%u\n", idCpu));
8488 NOREF(idCpu);
8489 return VINF_SUCCESS;
8490}
8491
8492
8493/**
8494 * Leaves the VT-x session.
8495 *
8496 * @returns VBox status code.
8497 * @param pVCpu The cross context virtual CPU structure.
8498 *
8499 * @remarks No-long-jmp zone!!!
8500 */
8501static int hmR0VmxLeaveSession(PVMCPUCC pVCpu)
8502{
8503 HM_DISABLE_PREEMPT(pVCpu);
8504 HMVMX_ASSERT_CPU_SAFE(pVCpu);
8505 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8506 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8507
8508 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
8509 and done this from the VMXR0ThreadCtxCallback(). */
8510 if (!pVCpu->hmr0.s.fLeaveDone)
8511 {
8512 int rc2 = hmR0VmxLeave(pVCpu, true /* fImportState */);
8513 AssertRCReturnStmt(rc2, HM_RESTORE_PREEMPT(), rc2);
8514 pVCpu->hmr0.s.fLeaveDone = true;
8515 }
8516 Assert(!pVCpu->cpum.GstCtx.fExtrn);
8517
8518 /*
8519 * !!! IMPORTANT !!!
8520 * If you modify code here, make sure to check whether VMXR0CallRing3Callback() needs to be updated too.
8521 */
8522
8523 /* Deregister hook now that we've left HM context before re-enabling preemption. */
8524 /** @todo Deregistering here means we need to VMCLEAR always
8525 * (longjmp/exit-to-r3) in VT-x which is not efficient, eliminate need
8526 * for calling VMMR0ThreadCtxHookDisable here! */
8527 VMMR0ThreadCtxHookDisable(pVCpu);
8528
8529 /* Leave HM context. This takes care of local init (term) and deregistering the longjmp-to-ring-3 callback. */
8530 int rc = HMR0LeaveCpu(pVCpu);
8531 HM_RESTORE_PREEMPT();
8532 return rc;
8533}
8534
8535
8536/**
8537 * Does the necessary state syncing before doing a longjmp to ring-3.
8538 *
8539 * @returns VBox status code.
8540 * @param pVCpu The cross context virtual CPU structure.
8541 *
8542 * @remarks No-long-jmp zone!!!
8543 */
8544DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPUCC pVCpu)
8545{
8546 return hmR0VmxLeaveSession(pVCpu);
8547}
8548
8549
8550/**
8551 * Take necessary actions before going back to ring-3.
8552 *
8553 * An action requires us to go back to ring-3. This function does the necessary
8554 * steps before we can safely return to ring-3. This is not the same as longjmps
8555 * to ring-3, this is voluntary and prepares the guest so it may continue
8556 * executing outside HM (recompiler/IEM).
8557 *
8558 * @returns VBox status code.
8559 * @param pVCpu The cross context virtual CPU structure.
8560 * @param rcExit The reason for exiting to ring-3. Can be
8561 * VINF_VMM_UNKNOWN_RING3_CALL.
8562 */
8563static int hmR0VmxExitToRing3(PVMCPUCC pVCpu, VBOXSTRICTRC rcExit)
8564{
8565 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8566
8567 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8568 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
8569 {
8570 VMXGetCurrentVmcs(&pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs);
8571 pVCpu->hm.s.vmx.LastError.u32VmcsRev = *(uint32_t *)pVmcsInfo->pvVmcs;
8572 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hmr0.s.idEnteredCpu;
8573 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
8574 }
8575
8576 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
8577 VMMRZCallRing3Disable(pVCpu);
8578 Log4Func(("rcExit=%d\n", VBOXSTRICTRC_VAL(rcExit)));
8579
8580 /*
8581 * Convert any pending HM events back to TRPM due to premature exits to ring-3.
8582 * We need to do this only on returns to ring-3 and not for longjmps to ring3.
8583 *
8584 * This is because execution may continue from ring-3 and we would need to inject
8585 * the event from there (hence place it back in TRPM).
8586 */
8587 if (pVCpu->hm.s.Event.fPending)
8588 {
8589 hmR0VmxPendingEventToTrpmTrap(pVCpu);
8590 Assert(!pVCpu->hm.s.Event.fPending);
8591
8592 /* Clear the events from the VMCS. */
8593 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0); AssertRC(rc);
8594 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, 0); AssertRC(rc);
8595 }
8596#ifdef VBOX_STRICT
8597 /*
8598 * We check for rcExit here since for errors like VERR_VMX_UNABLE_TO_START_VM (which are
8599 * fatal), we don't care about verifying duplicate injection of events. Errors like
8600 * VERR_EM_INTERPRET are converted to their VINF_* counterparts -prior- to calling this
8601 * function so those should and will be checked below.
8602 */
8603 else if (RT_SUCCESS(rcExit))
8604 {
8605 /*
8606 * Ensure we don't accidentally clear a pending HM event without clearing the VMCS.
8607 * This can be pretty hard to debug otherwise, interrupts might get injected twice
8608 * occasionally, see @bugref{9180#c42}.
8609 *
8610 * However, if the VM-entry failed, any VM entry-interruption info. field would
8611 * be left unmodified as the event would not have been injected to the guest. In
8612 * such cases, don't assert, we're not going to continue guest execution anyway.
8613 */
8614 uint32_t uExitReason;
8615 uint32_t uEntryIntInfo;
8616 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
8617 rc |= VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &uEntryIntInfo);
8618 AssertRC(rc);
8619 AssertMsg(VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason) || !VMX_ENTRY_INT_INFO_IS_VALID(uEntryIntInfo),
8620 ("uExitReason=%#RX32 uEntryIntInfo=%#RX32 rcExit=%d\n", uExitReason, uEntryIntInfo, VBOXSTRICTRC_VAL(rcExit)));
8621 }
8622#endif
8623
8624 /*
8625 * Clear the interrupt-window and NMI-window VMCS controls as we could have got
8626 * a VM-exit with higher priority than interrupt-window or NMI-window VM-exits
8627 * (e.g. TPR below threshold).
8628 */
8629 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8630 {
8631 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
8632 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
8633 }
8634
8635 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
8636 and if we're injecting an event we should have a TRPM trap pending. */
8637 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8638#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a triple fault in progress. */
8639 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8640#endif
8641
8642 /* Save guest state and restore host state bits. */
8643 int rc = hmR0VmxLeaveSession(pVCpu);
8644 AssertRCReturn(rc, rc);
8645 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8646
8647 /* Thread-context hooks are unregistered at this point!!! */
8648 /* Ring-3 callback notifications are unregistered at this point!!! */
8649
8650 /* Sync recompiler state. */
8651 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
8652 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
8653 | CPUM_CHANGED_LDTR
8654 | CPUM_CHANGED_GDTR
8655 | CPUM_CHANGED_IDTR
8656 | CPUM_CHANGED_TR
8657 | CPUM_CHANGED_HIDDEN_SEL_REGS);
8658 if ( pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging
8659 && CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx))
8660 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
8661
8662 Assert(!pVCpu->hmr0.s.fClearTrapFlag);
8663
8664 /* Update the exit-to-ring 3 reason. */
8665 pVCpu->hm.s.rcLastExitToR3 = VBOXSTRICTRC_VAL(rcExit);
8666
8667 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
8668 if ( rcExit != VINF_EM_RAW_INTERRUPT
8669 || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8670 {
8671 Assert(!(pVCpu->cpum.GstCtx.fExtrn & HMVMX_CPUMCTX_EXTRN_ALL));
8672 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
8673 }
8674
8675 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
8676 VMMRZCallRing3Enable(pVCpu);
8677 return rc;
8678}
8679
8680
8681/**
8682 * VMMRZCallRing3() callback wrapper which saves the guest state before we
8683 * longjump to ring-3 and possibly get preempted.
8684 *
8685 * @returns VBox status code.
8686 * @param pVCpu The cross context virtual CPU structure.
8687 * @param enmOperation The operation causing the ring-3 longjump.
8688 */
8689VMMR0DECL(int) VMXR0CallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation)
8690{
8691 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
8692 {
8693 /*
8694 * !!! IMPORTANT !!!
8695 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
8696 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
8697 */
8698 VMMRZCallRing3RemoveNotification(pVCpu);
8699 VMMRZCallRing3Disable(pVCpu);
8700 HM_DISABLE_PREEMPT(pVCpu);
8701
8702 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8703 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
8704 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
8705 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
8706
8707 /* Restore host-state bits that VT-x only restores partially. */
8708 if (pVCpu->hmr0.s.vmx.fRestoreHostFlags > VMX_RESTORE_HOST_REQUIRED)
8709 VMXRestoreHostState(pVCpu->hmr0.s.vmx.fRestoreHostFlags, &pVCpu->hmr0.s.vmx.RestoreHost);
8710 pVCpu->hmr0.s.vmx.fRestoreHostFlags = 0;
8711
8712 /* Restore the lazy host MSRs as we're leaving VT-x context. */
8713 if (pVCpu->hmr0.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
8714 hmR0VmxLazyRestoreHostMsrs(pVCpu);
8715
8716 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
8717 pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs = false;
8718 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8719
8720 /* Clear the current VMCS data back to memory (shadow VMCS if any would have been
8721 cleared as part of importing the guest state above. */
8722 hmR0VmxClearVmcs(pVmcsInfo);
8723
8724 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
8725 VMMR0ThreadCtxHookDisable(pVCpu);
8726
8727 /* Leave HM context. This takes care of local init (term). */
8728 HMR0LeaveCpu(pVCpu);
8729 HM_RESTORE_PREEMPT();
8730 return VINF_SUCCESS;
8731 }
8732
8733 Assert(pVCpu);
8734 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8735 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8736
8737 VMMRZCallRing3Disable(pVCpu);
8738
8739 Log4Func(("-> hmR0VmxLongJmpToRing3 enmOperation=%d\n", enmOperation));
8740
8741 int rc = hmR0VmxLongJmpToRing3(pVCpu);
8742 AssertRCReturn(rc, rc);
8743
8744 VMMRZCallRing3Enable(pVCpu);
8745 return VINF_SUCCESS;
8746}
8747
8748
8749/**
8750 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
8751 * stack.
8752 *
8753 * @returns Strict VBox status code (i.e. informational status codes too).
8754 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
8755 * @param pVCpu The cross context virtual CPU structure.
8756 * @param uValue The value to push to the guest stack.
8757 */
8758static VBOXSTRICTRC hmR0VmxRealModeGuestStackPush(PVMCPUCC pVCpu, uint16_t uValue)
8759{
8760 /*
8761 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
8762 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
8763 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
8764 */
8765 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8766 if (pCtx->sp == 1)
8767 return VINF_EM_RESET;
8768 pCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
8769 int rc = PGMPhysSimpleWriteGCPhys(pVCpu->CTX_SUFF(pVM), pCtx->ss.u64Base + pCtx->sp, &uValue, sizeof(uint16_t));
8770 AssertRC(rc);
8771 return rc;
8772}
8773
8774
8775/**
8776 * Injects an event into the guest upon VM-entry by updating the relevant fields
8777 * in the VM-entry area in the VMCS.
8778 *
8779 * @returns Strict VBox status code (i.e. informational status codes too).
8780 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
8781 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
8782 *
8783 * @param pVCpu The cross context virtual CPU structure.
8784 * @param pVmxTransient The VMX-transient structure.
8785 * @param pEvent The event being injected.
8786 * @param pfIntrState Pointer to the VT-x guest-interruptibility-state. This
8787 * will be updated if necessary. This cannot not be NULL.
8788 * @param fStepping Whether we're single-stepping guest execution and should
8789 * return VINF_EM_DBG_STEPPED if the event is injected
8790 * directly (registers modified by us, not by hardware on
8791 * VM-entry).
8792 */
8793static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PCHMEVENT pEvent, bool fStepping,
8794 uint32_t *pfIntrState)
8795{
8796 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
8797 AssertMsg(!RT_HI_U32(pEvent->u64IntInfo), ("%#RX64\n", pEvent->u64IntInfo));
8798 Assert(pfIntrState);
8799
8800 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8801 uint32_t u32IntInfo = pEvent->u64IntInfo;
8802 uint32_t const u32ErrCode = pEvent->u32ErrCode;
8803 uint32_t const cbInstr = pEvent->cbInstr;
8804 RTGCUINTPTR const GCPtrFault = pEvent->GCPtrFaultAddress;
8805 uint8_t const uVector = VMX_ENTRY_INT_INFO_VECTOR(u32IntInfo);
8806 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(u32IntInfo);
8807
8808#ifdef VBOX_STRICT
8809 /*
8810 * Validate the error-code-valid bit for hardware exceptions.
8811 * No error codes for exceptions in real-mode.
8812 *
8813 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8814 */
8815 if ( uIntType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT
8816 && !CPUMIsGuestInRealModeEx(pCtx))
8817 {
8818 switch (uVector)
8819 {
8820 case X86_XCPT_PF:
8821 case X86_XCPT_DF:
8822 case X86_XCPT_TS:
8823 case X86_XCPT_NP:
8824 case X86_XCPT_SS:
8825 case X86_XCPT_GP:
8826 case X86_XCPT_AC:
8827 AssertMsg(VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo),
8828 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
8829 RT_FALL_THRU();
8830 default:
8831 break;
8832 }
8833 }
8834
8835 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
8836 Assert( uIntType != VMX_EXIT_INT_INFO_TYPE_NMI
8837 || !(*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8838#endif
8839
8840 if ( uIntType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT
8841 || uIntType == VMX_EXIT_INT_INFO_TYPE_NMI
8842 || uIntType == VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT
8843 || uIntType == VMX_EXIT_INT_INFO_TYPE_SW_XCPT)
8844 {
8845 Assert(uVector <= X86_XCPT_LAST);
8846 Assert(uIntType != VMX_EXIT_INT_INFO_TYPE_NMI || uVector == X86_XCPT_NMI);
8847 Assert(uIntType != VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT || uVector == X86_XCPT_DB);
8848 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedXcptsR0[uVector]);
8849 }
8850 else
8851 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
8852
8853 /*
8854 * Hardware interrupts & exceptions cannot be delivered through the software interrupt
8855 * redirection bitmap to the real mode task in virtual-8086 mode. We must jump to the
8856 * interrupt handler in the (real-mode) guest.
8857 *
8858 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode".
8859 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8860 */
8861 if (CPUMIsGuestInRealModeEx(pCtx)) /* CR0.PE bit changes are always intercepted, so it's up to date. */
8862 {
8863 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fUnrestrictedGuest)
8864 {
8865 /*
8866 * For CPUs with unrestricted guest execution enabled and with the guest
8867 * in real-mode, we must not set the deliver-error-code bit.
8868 *
8869 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8870 */
8871 u32IntInfo &= ~VMX_ENTRY_INT_INFO_ERROR_CODE_VALID;
8872 }
8873 else
8874 {
8875 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
8876 Assert(PDMVmmDevHeapIsEnabled(pVM));
8877 Assert(pVM->hm.s.vmx.pRealModeTSS);
8878 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
8879
8880 /* We require RIP, RSP, RFLAGS, CS, IDTR, import them. */
8881 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8882 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_TABLE_MASK
8883 | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RFLAGS);
8884 AssertRCReturn(rc2, rc2);
8885
8886 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8887 size_t const cbIdtEntry = sizeof(X86IDTR16);
8888 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pCtx->idtr.cbIdt)
8889 {
8890 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8891 if (uVector == X86_XCPT_DF)
8892 return VINF_EM_RESET;
8893
8894 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault.
8895 No error codes for exceptions in real-mode. */
8896 if (uVector == X86_XCPT_GP)
8897 {
8898 uint32_t const uXcptDfInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
8899 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8900 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8901 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8902 HMEVENT EventXcptDf;
8903 RT_ZERO(EventXcptDf);
8904 EventXcptDf.u64IntInfo = uXcptDfInfo;
8905 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptDf, fStepping, pfIntrState);
8906 }
8907
8908 /*
8909 * If we're injecting an event with no valid IDT entry, inject a #GP.
8910 * No error codes for exceptions in real-mode.
8911 *
8912 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8913 */
8914 uint32_t const uXcptGpInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
8915 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8916 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8917 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8918 HMEVENT EventXcptGp;
8919 RT_ZERO(EventXcptGp);
8920 EventXcptGp.u64IntInfo = uXcptGpInfo;
8921 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptGp, fStepping, pfIntrState);
8922 }
8923
8924 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8925 uint16_t uGuestIp = pCtx->ip;
8926 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_XCPT)
8927 {
8928 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8929 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8930 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8931 }
8932 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_INT)
8933 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8934
8935 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8936 X86IDTR16 IdtEntry;
8937 RTGCPHYS const GCPhysIdtEntry = (RTGCPHYS)pCtx->idtr.pIdt + uVector * cbIdtEntry;
8938 rc2 = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8939 AssertRCReturn(rc2, rc2);
8940
8941 /* Construct the stack frame for the interrupt/exception handler. */
8942 VBOXSTRICTRC rcStrict;
8943 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->eflags.u32);
8944 if (rcStrict == VINF_SUCCESS)
8945 {
8946 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->cs.Sel);
8947 if (rcStrict == VINF_SUCCESS)
8948 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, uGuestIp);
8949 }
8950
8951 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8952 if (rcStrict == VINF_SUCCESS)
8953 {
8954 pCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8955 pCtx->rip = IdtEntry.offSel;
8956 pCtx->cs.Sel = IdtEntry.uSel;
8957 pCtx->cs.ValidSel = IdtEntry.uSel;
8958 pCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8959 if ( uIntType == VMX_ENTRY_INT_INFO_TYPE_HW_XCPT
8960 && uVector == X86_XCPT_PF)
8961 pCtx->cr2 = GCPtrFault;
8962
8963 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CS | HM_CHANGED_GUEST_CR2
8964 | HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
8965 | HM_CHANGED_GUEST_RSP);
8966
8967 /*
8968 * If we delivered a hardware exception (other than an NMI) and if there was
8969 * block-by-STI in effect, we should clear it.
8970 */
8971 if (*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
8972 {
8973 Assert( uIntType != VMX_ENTRY_INT_INFO_TYPE_NMI
8974 && uIntType != VMX_ENTRY_INT_INFO_TYPE_EXT_INT);
8975 Log4Func(("Clearing inhibition due to STI\n"));
8976 *pfIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
8977 }
8978
8979 Log4(("Injected real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8980 u32IntInfo, u32ErrCode, cbInstr, pCtx->eflags.u, pCtx->cs.Sel, pCtx->eip));
8981
8982 /*
8983 * The event has been truly dispatched to the guest. Mark it as no longer pending so
8984 * we don't attempt to undo it if we are returning to ring-3 before executing guest code.
8985 */
8986 pVCpu->hm.s.Event.fPending = false;
8987
8988 /*
8989 * If we eventually support nested-guest execution without unrestricted guest execution,
8990 * we should set fInterceptEvents here.
8991 */
8992 Assert(!pVmxTransient->fIsNestedGuest);
8993
8994 /* If we're stepping and we've changed cs:rip above, bail out of the VMX R0 execution loop. */
8995 if (fStepping)
8996 rcStrict = VINF_EM_DBG_STEPPED;
8997 }
8998 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8999 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
9000 return rcStrict;
9001 }
9002 }
9003
9004 /*
9005 * Validate.
9006 */
9007 Assert(VMX_ENTRY_INT_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
9008 Assert(!(u32IntInfo & VMX_BF_ENTRY_INT_INFO_RSVD_12_30_MASK)); /* Bits 30:12 MBZ. */
9009
9010 /*
9011 * Inject the event into the VMCS.
9012 */
9013 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
9014 if (VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
9015 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
9016 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
9017 AssertRC(rc);
9018
9019 /*
9020 * Update guest CR2 if this is a page-fault.
9021 */
9022 if (VMX_ENTRY_INT_INFO_IS_XCPT_PF(u32IntInfo))
9023 pCtx->cr2 = GCPtrFault;
9024
9025 Log4(("Injecting u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x CR2=%#RX64\n", u32IntInfo, u32ErrCode, cbInstr, pCtx->cr2));
9026 return VINF_SUCCESS;
9027}
9028
9029
9030/**
9031 * Evaluates the event to be delivered to the guest and sets it as the pending
9032 * event.
9033 *
9034 * Toggling of interrupt force-flags here is safe since we update TRPM on premature
9035 * exits to ring-3 before executing guest code, see hmR0VmxExitToRing3(). We must
9036 * NOT restore these force-flags.
9037 *
9038 * @returns Strict VBox status code (i.e. informational status codes too).
9039 * @param pVCpu The cross context virtual CPU structure.
9040 * @param pVmxTransient The VMX-transient structure.
9041 * @param pfIntrState Where to store the VT-x guest-interruptibility state.
9042 */
9043static VBOXSTRICTRC hmR0VmxEvaluatePendingEvent(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t *pfIntrState)
9044{
9045 Assert(pfIntrState);
9046 Assert(!TRPMHasTrap(pVCpu));
9047
9048 /*
9049 * Compute/update guest-interruptibility state related FFs.
9050 * The FFs will be used below while evaluating events to be injected.
9051 */
9052 *pfIntrState = hmR0VmxGetGuestIntrStateAndUpdateFFs(pVCpu);
9053
9054 /*
9055 * Evaluate if a new event needs to be injected.
9056 * An event that's already pending has already performed all necessary checks.
9057 */
9058 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
9059 bool const fIsNestedGuest = pVmxTransient->fIsNestedGuest;
9060 if ( !pVCpu->hm.s.Event.fPending
9061 && !VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
9062 {
9063 /** @todo SMI. SMIs take priority over NMIs. */
9064
9065 /*
9066 * NMIs.
9067 * NMIs take priority over external interrupts.
9068 */
9069 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
9070 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
9071 {
9072 /*
9073 * For a guest, the FF always indicates the guest's ability to receive an NMI.
9074 *
9075 * For a nested-guest, the FF always indicates the outer guest's ability to
9076 * receive an NMI while the guest-interruptibility state bit depends on whether
9077 * the nested-hypervisor is using virtual-NMIs.
9078 */
9079 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
9080 {
9081#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9082 if ( fIsNestedGuest
9083 && CPUMIsGuestVmxPinCtlsSet(pCtx, VMX_PIN_CTLS_NMI_EXIT))
9084 return IEMExecVmxVmexitXcptNmi(pVCpu);
9085#endif
9086 hmR0VmxSetPendingXcptNmi(pVCpu);
9087 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
9088 Log4Func(("NMI pending injection\n"));
9089
9090 /* We've injected the NMI, bail. */
9091 return VINF_SUCCESS;
9092 }
9093 else if (!fIsNestedGuest)
9094 hmR0VmxSetNmiWindowExitVmcs(pVmcsInfo);
9095 }
9096
9097 /*
9098 * External interrupts (PIC/APIC).
9099 * Once PDMGetInterrupt() returns a valid interrupt we -must- deliver it.
9100 * We cannot re-request the interrupt from the controller again.
9101 */
9102 if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
9103 && !pVCpu->hm.s.fSingleInstruction)
9104 {
9105 Assert(!DBGFIsStepping(pVCpu));
9106 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
9107 AssertRC(rc);
9108
9109 /*
9110 * We must not check EFLAGS directly when executing a nested-guest, use
9111 * CPUMIsGuestPhysIntrEnabled() instead as EFLAGS.IF does not control the blocking of
9112 * external interrupts when "External interrupt exiting" is set. This fixes a nasty
9113 * SMP hang while executing nested-guest VCPUs on spinlocks which aren't rescued by
9114 * other VM-exits (like a preemption timer), see @bugref{9562#c18}.
9115 *
9116 * See Intel spec. 25.4.1 "Event Blocking".
9117 */
9118 if (CPUMIsGuestPhysIntrEnabled(pVCpu))
9119 {
9120#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9121 if ( fIsNestedGuest
9122 && CPUMIsGuestVmxPinCtlsSet(pCtx, VMX_PIN_CTLS_EXT_INT_EXIT))
9123 {
9124 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, 0 /* uVector */, true /* fIntPending */);
9125 if (rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE)
9126 return rcStrict;
9127 }
9128#endif
9129 uint8_t u8Interrupt;
9130 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
9131 if (RT_SUCCESS(rc))
9132 {
9133#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9134 if ( fIsNestedGuest
9135 && CPUMIsGuestVmxPinCtlsSet(pCtx, VMX_PIN_CTLS_EXT_INT_EXIT))
9136 {
9137 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, u8Interrupt, false /* fIntPending */);
9138 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
9139 return rcStrict;
9140 }
9141#endif
9142 hmR0VmxSetPendingExtInt(pVCpu, u8Interrupt);
9143 Log4Func(("External interrupt (%#x) pending injection\n", u8Interrupt));
9144 }
9145 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
9146 {
9147 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
9148
9149 if ( !fIsNestedGuest
9150 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
9151 hmR0VmxApicSetTprThreshold(pVmcsInfo, u8Interrupt >> 4);
9152 /* else: for nested-guests, TPR threshold is picked up while merging VMCS controls. */
9153
9154 /*
9155 * If the CPU doesn't have TPR shadowing, we will always get a VM-exit on TPR changes and
9156 * APICSetTpr() will end up setting the VMCPU_FF_INTERRUPT_APIC if required, so there is no
9157 * need to re-set this force-flag here.
9158 */
9159 }
9160 else
9161 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
9162
9163 /* We've injected the interrupt or taken necessary action, bail. */
9164 return VINF_SUCCESS;
9165 }
9166 if (!fIsNestedGuest)
9167 hmR0VmxSetIntWindowExitVmcs(pVmcsInfo);
9168 }
9169 }
9170 else if (!fIsNestedGuest)
9171 {
9172 /*
9173 * An event is being injected or we are in an interrupt shadow. Check if another event is
9174 * pending. If so, instruct VT-x to cause a VM-exit as soon as the guest is ready to accept
9175 * the pending event.
9176 */
9177 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
9178 hmR0VmxSetNmiWindowExitVmcs(pVmcsInfo);
9179 else if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
9180 && !pVCpu->hm.s.fSingleInstruction)
9181 hmR0VmxSetIntWindowExitVmcs(pVmcsInfo);
9182 }
9183 /* else: for nested-guests, NMI/interrupt-window exiting will be picked up when merging VMCS controls. */
9184
9185 return VINF_SUCCESS;
9186}
9187
9188
9189/**
9190 * Injects any pending events into the guest if the guest is in a state to
9191 * receive them.
9192 *
9193 * @returns Strict VBox status code (i.e. informational status codes too).
9194 * @param pVCpu The cross context virtual CPU structure.
9195 * @param pVmxTransient The VMX-transient structure.
9196 * @param fIntrState The VT-x guest-interruptibility state.
9197 * @param fStepping Whether we are single-stepping the guest using the
9198 * hypervisor debugger and should return
9199 * VINF_EM_DBG_STEPPED if the event was dispatched
9200 * directly.
9201 */
9202static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t fIntrState, bool fStepping)
9203{
9204 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9205 Assert(VMMRZCallRing3IsEnabled(pVCpu));
9206
9207#ifdef VBOX_STRICT
9208 /*
9209 * Verify guest-interruptibility state.
9210 *
9211 * We put this in a scoped block so we do not accidentally use fBlockSti or fBlockMovSS,
9212 * since injecting an event may modify the interruptibility state and we must thus always
9213 * use fIntrState.
9214 */
9215 {
9216 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
9217 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
9218 Assert(!fBlockSti || !(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_RFLAGS));
9219 Assert(!fBlockSti || pVCpu->cpum.GstCtx.eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
9220 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
9221 Assert(!TRPMHasTrap(pVCpu));
9222 NOREF(fBlockMovSS); NOREF(fBlockSti);
9223 }
9224#endif
9225
9226 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
9227 if (pVCpu->hm.s.Event.fPending)
9228 {
9229 /*
9230 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
9231 * pending even while injecting an event and in this case, we want a VM-exit as soon as
9232 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
9233 *
9234 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
9235 */
9236 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
9237#ifdef VBOX_STRICT
9238 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
9239 {
9240 Assert(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_IF);
9241 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI));
9242 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
9243 }
9244 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_NMI)
9245 {
9246 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI));
9247 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI));
9248 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
9249 }
9250#endif
9251 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#RX32\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
9252 uIntType));
9253
9254 /*
9255 * Inject the event and get any changes to the guest-interruptibility state.
9256 *
9257 * The guest-interruptibility state may need to be updated if we inject the event
9258 * into the guest IDT ourselves (for real-on-v86 guest injecting software interrupts).
9259 */
9260 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &pVCpu->hm.s.Event, fStepping, &fIntrState);
9261 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
9262
9263 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
9264 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
9265 else
9266 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
9267 }
9268
9269 /*
9270 * Deliver any pending debug exceptions if the guest is single-stepping using EFLAGS.TF and
9271 * is an interrupt shadow (block-by-STI or block-by-MOV SS).
9272 */
9273 if ( (fIntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
9274 && !pVmxTransient->fIsNestedGuest)
9275 {
9276 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
9277
9278 if (!pVCpu->hm.s.fSingleInstruction)
9279 {
9280 /*
9281 * Set or clear the BS bit depending on whether the trap flag is active or not. We need
9282 * to do both since we clear the BS bit from the VMCS while exiting to ring-3.
9283 */
9284 Assert(!DBGFIsStepping(pVCpu));
9285 uint8_t const fTrapFlag = !!(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_TF);
9286 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, fTrapFlag << VMX_BF_VMCS_PENDING_DBG_XCPT_BS_SHIFT);
9287 AssertRC(rc);
9288 }
9289 else
9290 {
9291 /*
9292 * We must not deliver a debug exception when single-stepping over STI/Mov-SS in the
9293 * hypervisor debugger using EFLAGS.TF but rather clear interrupt inhibition. However,
9294 * we take care of this case in hmR0VmxExportSharedDebugState and also the case if
9295 * we use MTF, so just make sure it's called before executing guest-code.
9296 */
9297 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR_MASK);
9298 }
9299 }
9300 /* else: for nested-guest currently handling while merging controls. */
9301
9302 /*
9303 * Finally, update the guest-interruptibility state.
9304 *
9305 * This is required for the real-on-v86 software interrupt injection, for
9306 * pending debug exceptions as well as updates to the guest state from ring-3 (IEM).
9307 */
9308 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
9309 AssertRC(rc);
9310
9311 /*
9312 * There's no need to clear the VM-entry interruption-information field here if we're not
9313 * injecting anything. VT-x clears the valid bit on every VM-exit.
9314 *
9315 * See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
9316 */
9317
9318 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
9319 return rcStrict;
9320}
9321
9322
9323/**
9324 * Enters the VT-x session.
9325 *
9326 * @returns VBox status code.
9327 * @param pVCpu The cross context virtual CPU structure.
9328 */
9329VMMR0DECL(int) VMXR0Enter(PVMCPUCC pVCpu)
9330{
9331 AssertPtr(pVCpu);
9332 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported);
9333 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9334
9335 LogFlowFunc(("pVCpu=%p\n", pVCpu));
9336 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
9337 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
9338
9339#ifdef VBOX_STRICT
9340 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
9341 RTCCUINTREG uHostCr4 = ASMGetCR4();
9342 if (!(uHostCr4 & X86_CR4_VMXE))
9343 {
9344 LogRelFunc(("X86_CR4_VMXE bit in CR4 is not set!\n"));
9345 return VERR_VMX_X86_CR4_VMXE_CLEARED;
9346 }
9347#endif
9348
9349 /*
9350 * Do the EMT scheduled L1D and MDS flush here if needed.
9351 */
9352 if (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_L1D_SCHED)
9353 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
9354 else if (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_MDS_SCHED)
9355 hmR0MdsClear();
9356
9357 /*
9358 * Load the appropriate VMCS as the current and active one.
9359 */
9360 PVMXVMCSINFO pVmcsInfo;
9361 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx);
9362 if (!fInNestedGuestMode)
9363 pVmcsInfo = &pVCpu->hmr0.s.vmx.VmcsInfo;
9364 else
9365 pVmcsInfo = &pVCpu->hmr0.s.vmx.VmcsInfoNstGst;
9366 int rc = hmR0VmxLoadVmcs(pVmcsInfo);
9367 if (RT_SUCCESS(rc))
9368 {
9369 pVCpu->hmr0.s.vmx.fSwitchedToNstGstVmcs = fInNestedGuestMode;
9370 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcsCopyForRing3 = fInNestedGuestMode;
9371 pVCpu->hmr0.s.fLeaveDone = false;
9372 Log4Func(("Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
9373 }
9374 return rc;
9375}
9376
9377
9378/**
9379 * The thread-context callback.
9380 *
9381 * This is used together with RTThreadCtxHookCreate() on platforms which
9382 * supports it, and directly from VMMR0EmtPrepareForBlocking() and
9383 * VMMR0EmtResumeAfterBlocking() on platforms which don't.
9384 *
9385 * @param enmEvent The thread-context event.
9386 * @param pVCpu The cross context virtual CPU structure.
9387 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
9388 * @thread EMT(pVCpu)
9389 */
9390VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
9391{
9392 AssertPtr(pVCpu);
9393 RT_NOREF1(fGlobalInit);
9394
9395 switch (enmEvent)
9396 {
9397 case RTTHREADCTXEVENT_OUT:
9398 {
9399 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9400 VMCPU_ASSERT_EMT(pVCpu);
9401
9402 /* No longjmps (logger flushes, locks) in this fragile context. */
9403 VMMRZCallRing3Disable(pVCpu);
9404 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
9405
9406 /* Restore host-state (FPU, debug etc.) */
9407 if (!pVCpu->hmr0.s.fLeaveDone)
9408 {
9409 /*
9410 * Do -not- import the guest-state here as we might already be in the middle of importing
9411 * it, esp. bad if we're holding the PGM lock, see comment in hmR0VmxImportGuestState().
9412 */
9413 hmR0VmxLeave(pVCpu, false /* fImportState */);
9414 pVCpu->hmr0.s.fLeaveDone = true;
9415 }
9416
9417 /* Leave HM context, takes care of local init (term). */
9418 int rc = HMR0LeaveCpu(pVCpu);
9419 AssertRC(rc);
9420
9421 /* Restore longjmp state. */
9422 VMMRZCallRing3Enable(pVCpu);
9423 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
9424 break;
9425 }
9426
9427 case RTTHREADCTXEVENT_IN:
9428 {
9429 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9430 VMCPU_ASSERT_EMT(pVCpu);
9431
9432 /* Do the EMT scheduled L1D and MDS flush here if needed. */
9433 if (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_L1D_SCHED)
9434 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
9435 else if (pVCpu->hmr0.s.fWorldSwitcher & HM_WSF_MDS_SCHED)
9436 hmR0MdsClear();
9437
9438 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
9439 VMMRZCallRing3Disable(pVCpu);
9440 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
9441
9442 /* Initialize the bare minimum state required for HM. This takes care of
9443 initializing VT-x if necessary (onlined CPUs, local init etc.) */
9444 int rc = hmR0EnterCpu(pVCpu);
9445 AssertRC(rc);
9446 Assert( (pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
9447 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
9448
9449 /* Load the active VMCS as the current one. */
9450 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
9451 rc = hmR0VmxLoadVmcs(pVmcsInfo);
9452 AssertRC(rc);
9453 Log4Func(("Resumed: Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
9454 pVCpu->hmr0.s.fLeaveDone = false;
9455
9456 /* Restore longjmp state. */
9457 VMMRZCallRing3Enable(pVCpu);
9458 break;
9459 }
9460
9461 default:
9462 break;
9463 }
9464}
9465
9466
9467/**
9468 * Exports the host state into the VMCS host-state area.
9469 * Sets up the VM-exit MSR-load area.
9470 *
9471 * The CPU state will be loaded from these fields on every successful VM-exit.
9472 *
9473 * @returns VBox status code.
9474 * @param pVCpu The cross context virtual CPU structure.
9475 *
9476 * @remarks No-long-jump zone!!!
9477 */
9478static int hmR0VmxExportHostState(PVMCPUCC pVCpu)
9479{
9480 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9481
9482 int rc = VINF_SUCCESS;
9483 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
9484 {
9485 uint64_t uHostCr4 = hmR0VmxExportHostControlRegs();
9486
9487 rc = hmR0VmxExportHostSegmentRegs(pVCpu, uHostCr4);
9488 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9489
9490 hmR0VmxExportHostMsrs(pVCpu);
9491
9492 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_HOST_CONTEXT;
9493 }
9494 return rc;
9495}
9496
9497
9498/**
9499 * Saves the host state in the VMCS host-state.
9500 *
9501 * @returns VBox status code.
9502 * @param pVCpu The cross context virtual CPU structure.
9503 *
9504 * @remarks No-long-jump zone!!!
9505 */
9506VMMR0DECL(int) VMXR0ExportHostState(PVMCPUCC pVCpu)
9507{
9508 AssertPtr(pVCpu);
9509 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9510
9511 /*
9512 * Export the host state here while entering HM context.
9513 * When thread-context hooks are used, we might get preempted and have to re-save the host
9514 * state but most of the time we won't be, so do it here before we disable interrupts.
9515 */
9516 return hmR0VmxExportHostState(pVCpu);
9517}
9518
9519
9520/**
9521 * Exports the guest state into the VMCS guest-state area.
9522 *
9523 * The will typically be done before VM-entry when the guest-CPU state and the
9524 * VMCS state may potentially be out of sync.
9525 *
9526 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
9527 * VM-entry controls.
9528 * Sets up the appropriate VMX non-root function to execute guest code based on
9529 * the guest CPU mode.
9530 *
9531 * @returns VBox strict status code.
9532 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9533 * without unrestricted guest execution and the VMMDev is not presently
9534 * mapped (e.g. EFI32).
9535 *
9536 * @param pVCpu The cross context virtual CPU structure.
9537 * @param pVmxTransient The VMX-transient structure.
9538 *
9539 * @remarks No-long-jump zone!!!
9540 */
9541static VBOXSTRICTRC hmR0VmxExportGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9542{
9543 AssertPtr(pVCpu);
9544 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9545 LogFlowFunc(("pVCpu=%p\n", pVCpu));
9546
9547 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
9548
9549 /*
9550 * Determine real-on-v86 mode.
9551 * Used when the guest is in real-mode and unrestricted guest execution is not used.
9552 */
9553 PVMXVMCSINFOSHARED pVmcsInfoShared = pVmxTransient->pVmcsInfo->pShared;
9554 if ( pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fUnrestrictedGuest
9555 || !CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx))
9556 pVmcsInfoShared->RealMode.fRealOnV86Active = false;
9557 else
9558 {
9559 Assert(!pVmxTransient->fIsNestedGuest);
9560 pVmcsInfoShared->RealMode.fRealOnV86Active = true;
9561 }
9562
9563 /*
9564 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
9565 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
9566 */
9567 int rc = hmR0VmxExportGuestEntryExitCtls(pVCpu, pVmxTransient);
9568 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9569
9570 rc = hmR0VmxExportGuestCR0(pVCpu, pVmxTransient);
9571 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9572
9573 VBOXSTRICTRC rcStrict = hmR0VmxExportGuestCR3AndCR4(pVCpu, pVmxTransient);
9574 if (rcStrict == VINF_SUCCESS)
9575 { /* likely */ }
9576 else
9577 {
9578 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
9579 return rcStrict;
9580 }
9581
9582 rc = hmR0VmxExportGuestSegRegsXdtr(pVCpu, pVmxTransient);
9583 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9584
9585 rc = hmR0VmxExportGuestMsrs(pVCpu, pVmxTransient);
9586 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9587
9588 hmR0VmxExportGuestApicTpr(pVCpu, pVmxTransient);
9589 hmR0VmxExportGuestXcptIntercepts(pVCpu, pVmxTransient);
9590 hmR0VmxExportGuestRip(pVCpu);
9591 hmR0VmxExportGuestRsp(pVCpu);
9592 hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9593
9594 rc = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9595 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9596
9597 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
9598 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( (HM_CHANGED_GUEST_GPRS_MASK & ~HM_CHANGED_GUEST_RSP)
9599 | HM_CHANGED_GUEST_CR2
9600 | (HM_CHANGED_GUEST_DR_MASK & ~HM_CHANGED_GUEST_DR7)
9601 | HM_CHANGED_GUEST_X87
9602 | HM_CHANGED_GUEST_SSE_AVX
9603 | HM_CHANGED_GUEST_OTHER_XSAVE
9604 | HM_CHANGED_GUEST_XCRx
9605 | HM_CHANGED_GUEST_KERNEL_GS_BASE /* Part of lazy or auto load-store MSRs. */
9606 | HM_CHANGED_GUEST_SYSCALL_MSRS /* Part of lazy or auto load-store MSRs. */
9607 | HM_CHANGED_GUEST_TSC_AUX
9608 | HM_CHANGED_GUEST_OTHER_MSRS
9609 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_VMX_MASK)));
9610
9611 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
9612 return rc;
9613}
9614
9615
9616/**
9617 * Exports the state shared between the host and guest into the VMCS.
9618 *
9619 * @param pVCpu The cross context virtual CPU structure.
9620 * @param pVmxTransient The VMX-transient structure.
9621 *
9622 * @remarks No-long-jump zone!!!
9623 */
9624static void hmR0VmxExportSharedState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9625{
9626 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9627 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9628
9629 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DR_MASK)
9630 {
9631 int rc = hmR0VmxExportSharedDebugState(pVCpu, pVmxTransient);
9632 AssertRC(rc);
9633 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_DR_MASK;
9634
9635 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
9636 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_RFLAGS)
9637 hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9638 }
9639
9640 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_GUEST_LAZY_MSRS)
9641 {
9642 hmR0VmxLazyLoadGuestMsrs(pVCpu);
9643 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_VMX_GUEST_LAZY_MSRS;
9644 }
9645
9646 AssertMsg(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE),
9647 ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
9648}
9649
9650
9651/**
9652 * Worker for loading the guest-state bits in the inner VT-x execution loop.
9653 *
9654 * @returns Strict VBox status code (i.e. informational status codes too).
9655 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9656 * without unrestricted guest execution and the VMMDev is not presently
9657 * mapped (e.g. EFI32).
9658 *
9659 * @param pVCpu The cross context virtual CPU structure.
9660 * @param pVmxTransient The VMX-transient structure.
9661 *
9662 * @remarks No-long-jump zone!!!
9663 */
9664static VBOXSTRICTRC hmR0VmxExportGuestStateOptimal(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9665{
9666 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9667 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9668
9669#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
9670 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
9671#endif
9672
9673 /*
9674 * For many VM-exits only RIP/RSP/RFLAGS (and HWVIRT state when executing a nested-guest)
9675 * changes. First try to export only these without going through all other changed-flag checks.
9676 */
9677 VBOXSTRICTRC rcStrict;
9678 uint64_t const fCtxMask = HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE;
9679 uint64_t const fMinimalMask = HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT;
9680 uint64_t const fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9681
9682 /* If only RIP/RSP/RFLAGS/HWVIRT changed, export only those (quicker, happens more often).*/
9683 if ( (fCtxChanged & fMinimalMask)
9684 && !(fCtxChanged & (fCtxMask & ~fMinimalMask)))
9685 {
9686 hmR0VmxExportGuestRip(pVCpu);
9687 hmR0VmxExportGuestRsp(pVCpu);
9688 hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9689 rcStrict = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9690 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportMinimal);
9691 }
9692 /* If anything else also changed, go through the full export routine and export as required. */
9693 else if (fCtxChanged & fCtxMask)
9694 {
9695 rcStrict = hmR0VmxExportGuestState(pVCpu, pVmxTransient);
9696 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9697 { /* likely */}
9698 else
9699 {
9700 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM, ("Failed to export guest state! rc=%Rrc\n",
9701 VBOXSTRICTRC_VAL(rcStrict)));
9702 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9703 return rcStrict;
9704 }
9705 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
9706 }
9707 /* Nothing changed, nothing to load here. */
9708 else
9709 rcStrict = VINF_SUCCESS;
9710
9711#ifdef VBOX_STRICT
9712 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
9713 uint64_t const fCtxChangedCur = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9714 AssertMsg(!(fCtxChangedCur & fCtxMask), ("fCtxChangedCur=%#RX64\n", fCtxChangedCur));
9715#endif
9716 return rcStrict;
9717}
9718
9719
9720/**
9721 * Tries to determine what part of the guest-state VT-x has deemed as invalid
9722 * and update error record fields accordingly.
9723 *
9724 * @returns VMX_IGS_* error codes.
9725 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
9726 * wrong with the guest state.
9727 *
9728 * @param pVCpu The cross context virtual CPU structure.
9729 * @param pVmcsInfo The VMCS info. object.
9730 *
9731 * @remarks This function assumes our cache of the VMCS controls
9732 * are valid, i.e. hmR0VmxCheckCachedVmcsCtls() succeeded.
9733 */
9734static uint32_t hmR0VmxCheckGuestState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9735{
9736#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
9737#define HMVMX_CHECK_BREAK(expr, err) do { \
9738 if (!(expr)) { uError = (err); break; } \
9739 } while (0)
9740
9741 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9742 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
9743 uint32_t uError = VMX_IGS_ERROR;
9744 uint32_t u32IntrState = 0;
9745 bool const fUnrestrictedGuest = pVM->hmr0.s.vmx.fUnrestrictedGuest;
9746 do
9747 {
9748 int rc;
9749
9750 /*
9751 * Guest-interruptibility state.
9752 *
9753 * Read this first so that any check that fails prior to those that actually
9754 * require the guest-interruptibility state would still reflect the correct
9755 * VMCS value and avoids causing further confusion.
9756 */
9757 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32IntrState);
9758 AssertRC(rc);
9759
9760 uint32_t u32Val;
9761 uint64_t u64Val;
9762
9763 /*
9764 * CR0.
9765 */
9766 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9767 uint64_t fSetCr0 = (g_HmMsrs.u.vmx.u64Cr0Fixed0 & g_HmMsrs.u.vmx.u64Cr0Fixed1);
9768 uint64_t const fZapCr0 = (g_HmMsrs.u.vmx.u64Cr0Fixed0 | g_HmMsrs.u.vmx.u64Cr0Fixed1);
9769 /* Exceptions for unrestricted guest execution for CR0 fixed bits (PE, PG).
9770 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
9771 if (fUnrestrictedGuest)
9772 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
9773
9774 uint64_t u64GuestCr0;
9775 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64GuestCr0);
9776 AssertRC(rc);
9777 HMVMX_CHECK_BREAK((u64GuestCr0 & fSetCr0) == fSetCr0, VMX_IGS_CR0_FIXED1);
9778 HMVMX_CHECK_BREAK(!(u64GuestCr0 & ~fZapCr0), VMX_IGS_CR0_FIXED0);
9779 if ( !fUnrestrictedGuest
9780 && (u64GuestCr0 & X86_CR0_PG)
9781 && !(u64GuestCr0 & X86_CR0_PE))
9782 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
9783
9784 /*
9785 * CR4.
9786 */
9787 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9788 uint64_t const fSetCr4 = (g_HmMsrs.u.vmx.u64Cr4Fixed0 & g_HmMsrs.u.vmx.u64Cr4Fixed1);
9789 uint64_t const fZapCr4 = (g_HmMsrs.u.vmx.u64Cr4Fixed0 | g_HmMsrs.u.vmx.u64Cr4Fixed1);
9790
9791 uint64_t u64GuestCr4;
9792 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64GuestCr4);
9793 AssertRC(rc);
9794 HMVMX_CHECK_BREAK((u64GuestCr4 & fSetCr4) == fSetCr4, VMX_IGS_CR4_FIXED1);
9795 HMVMX_CHECK_BREAK(!(u64GuestCr4 & ~fZapCr4), VMX_IGS_CR4_FIXED0);
9796
9797 /*
9798 * IA32_DEBUGCTL MSR.
9799 */
9800 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
9801 AssertRC(rc);
9802 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9803 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
9804 {
9805 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
9806 }
9807 uint64_t u64DebugCtlMsr = u64Val;
9808
9809#ifdef VBOX_STRICT
9810 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
9811 AssertRC(rc);
9812 Assert(u32Val == pVmcsInfo->u32EntryCtls);
9813#endif
9814 bool const fLongModeGuest = RT_BOOL(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_IA32E_MODE_GUEST);
9815
9816 /*
9817 * RIP and RFLAGS.
9818 */
9819 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
9820 AssertRC(rc);
9821 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
9822 if ( !fLongModeGuest
9823 || !pCtx->cs.Attr.n.u1Long)
9824 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
9825 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
9826 * must be identical if the "IA-32e mode guest" VM-entry
9827 * control is 1 and CS.L is 1. No check applies if the
9828 * CPU supports 64 linear-address bits. */
9829
9830 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
9831 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
9832 AssertRC(rc);
9833 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
9834 VMX_IGS_RFLAGS_RESERVED);
9835 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
9836 uint32_t const u32Eflags = u64Val;
9837
9838 if ( fLongModeGuest
9839 || ( fUnrestrictedGuest
9840 && !(u64GuestCr0 & X86_CR0_PE)))
9841 {
9842 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
9843 }
9844
9845 uint32_t u32EntryInfo;
9846 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
9847 AssertRC(rc);
9848 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9849 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
9850
9851 /*
9852 * 64-bit checks.
9853 */
9854 if (fLongModeGuest)
9855 {
9856 HMVMX_CHECK_BREAK(u64GuestCr0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
9857 HMVMX_CHECK_BREAK(u64GuestCr4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
9858 }
9859
9860 if ( !fLongModeGuest
9861 && (u64GuestCr4 & X86_CR4_PCIDE))
9862 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
9863
9864 /** @todo CR3 field must be such that bits 63:52 and bits in the range
9865 * 51:32 beyond the processor's physical-address width are 0. */
9866
9867 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9868 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
9869 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
9870
9871 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
9872 AssertRC(rc);
9873 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
9874
9875 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
9876 AssertRC(rc);
9877 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
9878
9879 /*
9880 * PERF_GLOBAL MSR.
9881 */
9882 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PERF_MSR)
9883 {
9884 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
9885 AssertRC(rc);
9886 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
9887 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
9888 }
9889
9890 /*
9891 * PAT MSR.
9892 */
9893 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PAT_MSR)
9894 {
9895 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
9896 AssertRC(rc);
9897 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
9898 for (unsigned i = 0; i < 8; i++)
9899 {
9900 uint8_t u8Val = (u64Val & 0xff);
9901 if ( u8Val != 0 /* UC */
9902 && u8Val != 1 /* WC */
9903 && u8Val != 4 /* WT */
9904 && u8Val != 5 /* WP */
9905 && u8Val != 6 /* WB */
9906 && u8Val != 7 /* UC- */)
9907 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
9908 u64Val >>= 8;
9909 }
9910 }
9911
9912 /*
9913 * EFER MSR.
9914 */
9915 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
9916 {
9917 Assert(g_fHmVmxSupportsVmcsEfer);
9918 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
9919 AssertRC(rc);
9920 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
9921 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
9922 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVmcsInfo->u32EntryCtls
9923 & VMX_ENTRY_CTLS_IA32E_MODE_GUEST),
9924 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
9925 /** @todo r=ramshankar: Unrestricted check here is probably wrong, see
9926 * iemVmxVmentryCheckGuestState(). */
9927 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9928 || !(u64GuestCr0 & X86_CR0_PG)
9929 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
9930 VMX_IGS_EFER_LMA_LME_MISMATCH);
9931 }
9932
9933 /*
9934 * Segment registers.
9935 */
9936 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9937 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
9938 if (!(u32Eflags & X86_EFL_VM))
9939 {
9940 /* CS */
9941 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
9942 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
9943 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
9944 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
9945 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9946 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
9947 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9948 /* CS cannot be loaded with NULL in protected mode. */
9949 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
9950 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
9951 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
9952 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
9953 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
9954 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
9955 else if (fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
9956 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
9957 else
9958 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
9959
9960 /* SS */
9961 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9962 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
9963 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
9964 if ( !(pCtx->cr0 & X86_CR0_PE)
9965 || pCtx->cs.Attr.n.u4Type == 3)
9966 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
9967
9968 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
9969 {
9970 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
9971 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
9972 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
9973 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
9974 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
9975 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9976 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
9977 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9978 }
9979
9980 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSReg(). */
9981 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
9982 {
9983 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
9984 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
9985 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9986 || pCtx->ds.Attr.n.u4Type > 11
9987 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9988 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
9989 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
9990 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
9991 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9992 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
9993 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9994 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9995 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
9996 }
9997 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
9998 {
9999 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
10000 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
10001 HMVMX_CHECK_BREAK( fUnrestrictedGuest
10002 || pCtx->es.Attr.n.u4Type > 11
10003 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
10004 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
10005 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
10006 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
10007 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
10008 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
10009 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
10010 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10011 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
10012 }
10013 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
10014 {
10015 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
10016 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
10017 HMVMX_CHECK_BREAK( fUnrestrictedGuest
10018 || pCtx->fs.Attr.n.u4Type > 11
10019 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
10020 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
10021 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
10022 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
10023 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
10024 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
10025 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
10026 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10027 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
10028 }
10029 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
10030 {
10031 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
10032 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
10033 HMVMX_CHECK_BREAK( fUnrestrictedGuest
10034 || pCtx->gs.Attr.n.u4Type > 11
10035 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
10036 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
10037 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
10038 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
10039 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
10040 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
10041 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
10042 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
10043 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
10044 }
10045 /* 64-bit capable CPUs. */
10046 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
10047 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
10048 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
10049 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
10050 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
10051 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
10052 VMX_IGS_LONGMODE_SS_BASE_INVALID);
10053 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
10054 VMX_IGS_LONGMODE_DS_BASE_INVALID);
10055 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
10056 VMX_IGS_LONGMODE_ES_BASE_INVALID);
10057 }
10058 else
10059 {
10060 /* V86 mode checks. */
10061 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
10062 if (pVmcsInfo->pShared->RealMode.fRealOnV86Active)
10063 {
10064 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
10065 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
10066 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
10067 }
10068 else
10069 {
10070 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
10071 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
10072 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
10073 }
10074
10075 /* CS */
10076 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
10077 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
10078 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
10079 /* SS */
10080 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
10081 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
10082 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
10083 /* DS */
10084 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
10085 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
10086 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
10087 /* ES */
10088 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
10089 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
10090 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
10091 /* FS */
10092 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
10093 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
10094 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
10095 /* GS */
10096 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
10097 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
10098 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
10099 /* 64-bit capable CPUs. */
10100 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
10101 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
10102 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
10103 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
10104 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
10105 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
10106 VMX_IGS_LONGMODE_SS_BASE_INVALID);
10107 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
10108 VMX_IGS_LONGMODE_DS_BASE_INVALID);
10109 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
10110 VMX_IGS_LONGMODE_ES_BASE_INVALID);
10111 }
10112
10113 /*
10114 * TR.
10115 */
10116 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
10117 /* 64-bit capable CPUs. */
10118 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
10119 if (fLongModeGuest)
10120 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
10121 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
10122 else
10123 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
10124 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
10125 VMX_IGS_TR_ATTR_TYPE_INVALID);
10126 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
10127 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
10128 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
10129 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
10130 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
10131 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
10132 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
10133 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
10134
10135 /*
10136 * GDTR and IDTR (64-bit capable checks).
10137 */
10138 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
10139 AssertRC(rc);
10140 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
10141
10142 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
10143 AssertRC(rc);
10144 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
10145
10146 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
10147 AssertRC(rc);
10148 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
10149
10150 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
10151 AssertRC(rc);
10152 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
10153
10154 /*
10155 * Guest Non-Register State.
10156 */
10157 /* Activity State. */
10158 uint32_t u32ActivityState;
10159 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
10160 AssertRC(rc);
10161 HMVMX_CHECK_BREAK( !u32ActivityState
10162 || (u32ActivityState & RT_BF_GET(g_HmMsrs.u.vmx.u64Misc, VMX_BF_MISC_ACTIVITY_STATES)),
10163 VMX_IGS_ACTIVITY_STATE_INVALID);
10164 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
10165 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
10166
10167 if ( u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS
10168 || u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
10169 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
10170
10171 /** @todo Activity state and injecting interrupts. Left as a todo since we
10172 * currently don't use activity states but ACTIVE. */
10173
10174 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
10175 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
10176
10177 /* Guest interruptibility-state. */
10178 HMVMX_CHECK_BREAK(!(u32IntrState & 0xffffffe0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
10179 HMVMX_CHECK_BREAK((u32IntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
10180 != (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
10181 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
10182 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
10183 || !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
10184 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
10185 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
10186 {
10187 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
10188 && !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
10189 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
10190 }
10191 else if (VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
10192 {
10193 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
10194 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
10195 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
10196 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
10197 }
10198 /** @todo Assumes the processor is not in SMM. */
10199 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
10200 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
10201 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
10202 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
10203 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
10204 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
10205 && VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
10206 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI), VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
10207
10208 /* Pending debug exceptions. */
10209 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &u64Val);
10210 AssertRC(rc);
10211 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
10212 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
10213 u32Val = u64Val; /* For pending debug exceptions checks below. */
10214
10215 if ( (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
10216 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS)
10217 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
10218 {
10219 if ( (u32Eflags & X86_EFL_TF)
10220 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
10221 {
10222 /* Bit 14 is PendingDebug.BS. */
10223 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
10224 }
10225 if ( !(u32Eflags & X86_EFL_TF)
10226 || (u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
10227 {
10228 /* Bit 14 is PendingDebug.BS. */
10229 HMVMX_CHECK_BREAK(!(u32Val & RT_BIT(14)), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_CLEAR);
10230 }
10231 }
10232
10233 /* VMCS link pointer. */
10234 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
10235 AssertRC(rc);
10236 if (u64Val != UINT64_C(0xffffffffffffffff))
10237 {
10238 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
10239 /** @todo Bits beyond the processor's physical-address width MBZ. */
10240 /** @todo SMM checks. */
10241 Assert(pVmcsInfo->HCPhysShadowVmcs == u64Val);
10242 Assert(pVmcsInfo->pvShadowVmcs);
10243 VMXVMCSREVID VmcsRevId;
10244 VmcsRevId.u = *(uint32_t *)pVmcsInfo->pvShadowVmcs;
10245 HMVMX_CHECK_BREAK(VmcsRevId.n.u31RevisionId == RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_ID),
10246 VMX_IGS_VMCS_LINK_PTR_SHADOW_VMCS_ID_INVALID);
10247 HMVMX_CHECK_BREAK(VmcsRevId.n.fIsShadowVmcs == (uint32_t)!!(pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING),
10248 VMX_IGS_VMCS_LINK_PTR_NOT_SHADOW);
10249 }
10250
10251 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
10252 * not using nested paging? */
10253 if ( pVM->hmr0.s.fNestedPaging
10254 && !fLongModeGuest
10255 && CPUMIsGuestInPAEModeEx(pCtx))
10256 {
10257 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
10258 AssertRC(rc);
10259 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
10260
10261 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
10262 AssertRC(rc);
10263 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
10264
10265 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
10266 AssertRC(rc);
10267 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
10268
10269 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
10270 AssertRC(rc);
10271 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
10272 }
10273
10274 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
10275 if (uError == VMX_IGS_ERROR)
10276 uError = VMX_IGS_REASON_NOT_FOUND;
10277 } while (0);
10278
10279 pVCpu->hm.s.u32HMError = uError;
10280 pVCpu->hm.s.vmx.LastError.u32GuestIntrState = u32IntrState;
10281 return uError;
10282
10283#undef HMVMX_ERROR_BREAK
10284#undef HMVMX_CHECK_BREAK
10285}
10286
10287
10288/**
10289 * Map the APIC-access page for virtualizing APIC accesses.
10290 *
10291 * This can cause a longjumps to R3 due to the acquisition of the PGM lock. Hence,
10292 * this not done as part of exporting guest state, see @bugref{8721}.
10293 *
10294 * @returns VBox status code.
10295 * @param pVCpu The cross context virtual CPU structure.
10296 */
10297static int hmR0VmxMapHCApicAccessPage(PVMCPUCC pVCpu)
10298{
10299 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10300 uint64_t const u64MsrApicBase = APICGetBaseMsrNoCheck(pVCpu);
10301
10302 Assert(PDMHasApic(pVM));
10303 Assert(u64MsrApicBase);
10304
10305 RTGCPHYS const GCPhysApicBase = u64MsrApicBase & PAGE_BASE_GC_MASK;
10306 Log4Func(("Mappping HC APIC-access page at %#RGp\n", GCPhysApicBase));
10307
10308 /* Unalias the existing mapping. */
10309 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
10310 AssertRCReturn(rc, rc);
10311
10312 /* Map the HC APIC-access page in place of the MMIO page, also updates the shadow page tables if necessary. */
10313 Assert(pVM->hmr0.s.vmx.HCPhysApicAccess != NIL_RTHCPHYS);
10314 rc = IOMR0MmioMapMmioHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hmr0.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
10315 AssertRCReturn(rc, rc);
10316
10317 /* Update the per-VCPU cache of the APIC base MSR. */
10318 pVCpu->hm.s.vmx.u64GstMsrApicBase = u64MsrApicBase;
10319 return VINF_SUCCESS;
10320}
10321
10322
10323/**
10324 * Worker function passed to RTMpOnSpecific() that is to be called on the target
10325 * CPU.
10326 *
10327 * @param idCpu The ID for the CPU the function is called on.
10328 * @param pvUser1 Null, not used.
10329 * @param pvUser2 Null, not used.
10330 */
10331static DECLCALLBACK(void) hmR0DispatchHostNmi(RTCPUID idCpu, void *pvUser1, void *pvUser2)
10332{
10333 RT_NOREF3(idCpu, pvUser1, pvUser2);
10334 VMXDispatchHostNmi();
10335}
10336
10337
10338/**
10339 * Dispatching an NMI on the host CPU that received it.
10340 *
10341 * @returns VBox status code.
10342 * @param pVCpu The cross context virtual CPU structure.
10343 * @param pVmcsInfo The VMCS info. object corresponding to the VMCS that was
10344 * executing when receiving the host NMI in VMX non-root
10345 * operation.
10346 */
10347static int hmR0VmxExitHostNmi(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
10348{
10349 RTCPUID const idCpu = pVmcsInfo->idHostCpuExec;
10350 Assert(idCpu != NIL_RTCPUID);
10351
10352 /*
10353 * We don't want to delay dispatching the NMI any more than we have to. However,
10354 * we have already chosen -not- to dispatch NMIs when interrupts were still disabled
10355 * after executing guest or nested-guest code for the following reasons:
10356 *
10357 * - We would need to perform VMREADs with interrupts disabled and is orders of
10358 * magnitude worse when we run as a nested hypervisor without VMCS shadowing
10359 * supported by the host hypervisor.
10360 *
10361 * - It affects the common VM-exit scenario and keeps interrupts disabled for a
10362 * longer period of time just for handling an edge case like host NMIs which do
10363 * not occur nearly as frequently as other VM-exits.
10364 *
10365 * Let's cover the most likely scenario first. Check if we are on the target CPU
10366 * and dispatch the NMI right away. This should be much faster than calling into
10367 * RTMpOnSpecific() machinery.
10368 */
10369 bool fDispatched = false;
10370 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
10371 if (idCpu == RTMpCpuId())
10372 {
10373 VMXDispatchHostNmi();
10374 fDispatched = true;
10375 }
10376 ASMSetFlags(fEFlags);
10377 if (fDispatched)
10378 {
10379 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
10380 return VINF_SUCCESS;
10381 }
10382
10383 /*
10384 * RTMpOnSpecific() waits until the worker function has run on the target CPU. So
10385 * there should be no race or recursion even if we are unlucky enough to be preempted
10386 * (to the target CPU) without dispatching the host NMI above.
10387 */
10388 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGCIpi);
10389 return RTMpOnSpecific(idCpu, &hmR0DispatchHostNmi, NULL /* pvUser1 */, NULL /* pvUser2 */);
10390}
10391
10392
10393#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10394/**
10395 * Merges the guest with the nested-guest MSR bitmap in preparation of executing the
10396 * nested-guest using hardware-assisted VMX.
10397 *
10398 * @param pVCpu The cross context virtual CPU structure.
10399 * @param pVmcsInfoNstGst The nested-guest VMCS info. object.
10400 * @param pVmcsInfoGst The guest VMCS info. object.
10401 */
10402static void hmR0VmxMergeMsrBitmapNested(PCVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfoNstGst, PCVMXVMCSINFO pVmcsInfoGst)
10403{
10404 uint32_t const cbMsrBitmap = X86_PAGE_4K_SIZE;
10405 uint64_t *pu64MsrBitmap = (uint64_t *)pVmcsInfoNstGst->pvMsrBitmap;
10406 Assert(pu64MsrBitmap);
10407
10408 /*
10409 * We merge the guest MSR bitmap with the nested-guest MSR bitmap such that any
10410 * MSR that is intercepted by the guest is also intercepted while executing the
10411 * nested-guest using hardware-assisted VMX.
10412 *
10413 * Note! If the nested-guest is not using an MSR bitmap, every MSR must cause a
10414 * nested-guest VM-exit even if the outer guest is not intercepting some
10415 * MSRs. We cannot assume the caller has initialized the nested-guest
10416 * MSR bitmap in this case.
10417 *
10418 * The nested hypervisor may also switch whether it uses MSR bitmaps for
10419 * each of its VM-entry, hence initializing it once per-VM while setting
10420 * up the nested-guest VMCS is not sufficient.
10421 */
10422 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
10423 if (pVmcsNstGst->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
10424 {
10425 uint64_t const *pu64MsrBitmapNstGst = (uint64_t const *)pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
10426 uint64_t const *pu64MsrBitmapGst = (uint64_t const *)pVmcsInfoGst->pvMsrBitmap;
10427 Assert(pu64MsrBitmapNstGst);
10428 Assert(pu64MsrBitmapGst);
10429
10430 /** @todo Detect and use EVEX.POR? */
10431 uint32_t const cFrags = cbMsrBitmap / sizeof(uint64_t);
10432 for (uint32_t i = 0; i < cFrags; i++)
10433 pu64MsrBitmap[i] = pu64MsrBitmapNstGst[i] | pu64MsrBitmapGst[i];
10434 }
10435 else
10436 ASMMemFill32(pu64MsrBitmap, cbMsrBitmap, UINT32_C(0xffffffff));
10437}
10438
10439
10440/**
10441 * Merges the guest VMCS in to the nested-guest VMCS controls in preparation of
10442 * hardware-assisted VMX execution of the nested-guest.
10443 *
10444 * For a guest, we don't modify these controls once we set up the VMCS and hence
10445 * this function is never called.
10446 *
10447 * For nested-guests since the nested hypervisor provides these controls on every
10448 * nested-guest VM-entry and could potentially change them everytime we need to
10449 * merge them before every nested-guest VM-entry.
10450 *
10451 * @returns VBox status code.
10452 * @param pVCpu The cross context virtual CPU structure.
10453 */
10454static int hmR0VmxMergeVmcsNested(PVMCPUCC pVCpu)
10455{
10456 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10457 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hmr0.s.vmx.VmcsInfo;
10458 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
10459 Assert(pVmcsNstGst);
10460
10461 /*
10462 * Merge the controls with the requirements of the guest VMCS.
10463 *
10464 * We do not need to validate the nested-guest VMX features specified in the nested-guest
10465 * VMCS with the features supported by the physical CPU as it's already done by the
10466 * VMLAUNCH/VMRESUME instruction emulation.
10467 *
10468 * This is because the VMX features exposed by CPUM (through CPUID/MSRs) to the guest are
10469 * derived from the VMX features supported by the physical CPU.
10470 */
10471
10472 /* Pin-based VM-execution controls. */
10473 uint32_t const u32PinCtls = pVmcsNstGst->u32PinCtls | pVmcsInfoGst->u32PinCtls;
10474
10475 /* Processor-based VM-execution controls. */
10476 uint32_t u32ProcCtls = (pVmcsNstGst->u32ProcCtls & ~VMX_PROC_CTLS_USE_IO_BITMAPS)
10477 | (pVmcsInfoGst->u32ProcCtls & ~( VMX_PROC_CTLS_INT_WINDOW_EXIT
10478 | VMX_PROC_CTLS_NMI_WINDOW_EXIT
10479 | VMX_PROC_CTLS_MOV_DR_EXIT
10480 | VMX_PROC_CTLS_USE_TPR_SHADOW
10481 | VMX_PROC_CTLS_MONITOR_TRAP_FLAG));
10482
10483 /* Secondary processor-based VM-execution controls. */
10484 uint32_t const u32ProcCtls2 = (pVmcsNstGst->u32ProcCtls2 & ~VMX_PROC_CTLS2_VPID)
10485 | (pVmcsInfoGst->u32ProcCtls2 & ~( VMX_PROC_CTLS2_VIRT_APIC_ACCESS
10486 | VMX_PROC_CTLS2_INVPCID
10487 | VMX_PROC_CTLS2_VMCS_SHADOWING
10488 | VMX_PROC_CTLS2_RDTSCP
10489 | VMX_PROC_CTLS2_XSAVES_XRSTORS
10490 | VMX_PROC_CTLS2_APIC_REG_VIRT
10491 | VMX_PROC_CTLS2_VIRT_INT_DELIVERY
10492 | VMX_PROC_CTLS2_VMFUNC));
10493
10494 /*
10495 * VM-entry controls:
10496 * These controls contains state that depends on the nested-guest state (primarily
10497 * EFER MSR) and is thus not constant between VMLAUNCH/VMRESUME and the nested-guest
10498 * VM-exit. Although the nested hypervisor cannot change it, we need to in order to
10499 * properly continue executing the nested-guest if the EFER MSR changes but does not
10500 * cause a nested-guest VM-exits.
10501 *
10502 * VM-exit controls:
10503 * These controls specify the host state on return. We cannot use the controls from
10504 * the nested hypervisor state as is as it would contain the guest state rather than
10505 * the host state. Since the host state is subject to change (e.g. preemption, trips
10506 * to ring-3, longjmp and rescheduling to a different host CPU) they are not constant
10507 * through VMLAUNCH/VMRESUME and the nested-guest VM-exit.
10508 *
10509 * VM-entry MSR-load:
10510 * The guest MSRs from the VM-entry MSR-load area are already loaded into the guest-CPU
10511 * context by the VMLAUNCH/VMRESUME instruction emulation.
10512 *
10513 * VM-exit MSR-store:
10514 * The VM-exit emulation will take care of populating the MSRs from the guest-CPU context
10515 * back into the VM-exit MSR-store area.
10516 *
10517 * VM-exit MSR-load areas:
10518 * This must contain the real host MSRs with hardware-assisted VMX execution. Hence, we
10519 * can entirely ignore what the nested hypervisor wants to load here.
10520 */
10521
10522 /*
10523 * Exception bitmap.
10524 *
10525 * We could remove #UD from the guest bitmap and merge it with the nested-guest bitmap
10526 * here (and avoid doing anything while exporting nested-guest state), but to keep the
10527 * code more flexible if intercepting exceptions become more dynamic in the future we do
10528 * it as part of exporting the nested-guest state.
10529 */
10530 uint32_t const u32XcptBitmap = pVmcsNstGst->u32XcptBitmap | pVmcsInfoGst->u32XcptBitmap;
10531
10532 /*
10533 * CR0/CR4 guest/host mask.
10534 *
10535 * Modifications by the nested-guest to CR0/CR4 bits owned by the host and the guest must
10536 * cause VM-exits, so we need to merge them here.
10537 */
10538 uint64_t const u64Cr0Mask = pVmcsNstGst->u64Cr0Mask.u | pVmcsInfoGst->u64Cr0Mask;
10539 uint64_t const u64Cr4Mask = pVmcsNstGst->u64Cr4Mask.u | pVmcsInfoGst->u64Cr4Mask;
10540
10541 /*
10542 * Page-fault error-code mask and match.
10543 *
10544 * Although we require unrestricted guest execution (and thereby nested-paging) for
10545 * hardware-assisted VMX execution of nested-guests and thus the outer guest doesn't
10546 * normally intercept #PFs, it might intercept them for debugging purposes.
10547 *
10548 * If the outer guest is not intercepting #PFs, we can use the nested-guest #PF filters.
10549 * If the outer guest is intercepting #PFs, we must intercept all #PFs.
10550 */
10551 uint32_t u32XcptPFMask;
10552 uint32_t u32XcptPFMatch;
10553 if (!(pVmcsInfoGst->u32XcptBitmap & RT_BIT(X86_XCPT_PF)))
10554 {
10555 u32XcptPFMask = pVmcsNstGst->u32XcptPFMask;
10556 u32XcptPFMatch = pVmcsNstGst->u32XcptPFMatch;
10557 }
10558 else
10559 {
10560 u32XcptPFMask = 0;
10561 u32XcptPFMatch = 0;
10562 }
10563
10564 /*
10565 * Pause-Loop exiting.
10566 */
10567 /** @todo r=bird: given that both pVM->hm.s.vmx.cPleGapTicks and
10568 * pVM->hm.s.vmx.cPleWindowTicks defaults to zero, I cannot see how
10569 * this will work... */
10570 uint32_t const cPleGapTicks = RT_MIN(pVM->hm.s.vmx.cPleGapTicks, pVmcsNstGst->u32PleGap);
10571 uint32_t const cPleWindowTicks = RT_MIN(pVM->hm.s.vmx.cPleWindowTicks, pVmcsNstGst->u32PleWindow);
10572
10573 /*
10574 * Pending debug exceptions.
10575 * Currently just copy whatever the nested-guest provides us.
10576 */
10577 uint64_t const uPendingDbgXcpts = pVmcsNstGst->u64GuestPendingDbgXcpts.u;
10578
10579 /*
10580 * I/O Bitmap.
10581 *
10582 * We do not use the I/O bitmap that may be provided by the nested hypervisor as we always
10583 * intercept all I/O port accesses.
10584 */
10585 Assert(u32ProcCtls & VMX_PROC_CTLS_UNCOND_IO_EXIT);
10586 Assert(!(u32ProcCtls & VMX_PROC_CTLS_USE_IO_BITMAPS));
10587
10588 /*
10589 * VMCS shadowing.
10590 *
10591 * We do not yet expose VMCS shadowing to the guest and thus VMCS shadowing should not be
10592 * enabled while executing the nested-guest.
10593 */
10594 Assert(!(u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING));
10595
10596 /*
10597 * APIC-access page.
10598 */
10599 RTHCPHYS HCPhysApicAccess;
10600 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10601 {
10602 Assert(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
10603 RTGCPHYS const GCPhysApicAccess = pVmcsNstGst->u64AddrApicAccess.u;
10604
10605 /** @todo NSTVMX: This is not really correct but currently is required to make
10606 * things work. We need to re-enable the page handler when we fallback to
10607 * IEM execution of the nested-guest! */
10608 PGMHandlerPhysicalPageTempOff(pVM, GCPhysApicAccess, GCPhysApicAccess);
10609
10610 void *pvPage;
10611 PGMPAGEMAPLOCK PgLockApicAccess;
10612 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysApicAccess, &pvPage, &PgLockApicAccess);
10613 if (RT_SUCCESS(rc))
10614 {
10615 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysApicAccess, &HCPhysApicAccess);
10616 AssertMsgRCReturn(rc, ("Failed to get host-physical address for APIC-access page at %#RGp\n", GCPhysApicAccess), rc);
10617
10618 /** @todo Handle proper releasing of page-mapping lock later. */
10619 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockApicAccess);
10620 }
10621 else
10622 return rc;
10623 }
10624 else
10625 HCPhysApicAccess = 0;
10626
10627 /*
10628 * Virtual-APIC page and TPR threshold.
10629 */
10630 RTHCPHYS HCPhysVirtApic;
10631 uint32_t u32TprThreshold;
10632 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10633 {
10634 Assert(g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW);
10635 RTGCPHYS const GCPhysVirtApic = pVmcsNstGst->u64AddrVirtApic.u;
10636
10637 void *pvPage;
10638 PGMPAGEMAPLOCK PgLockVirtApic;
10639 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysVirtApic, &pvPage, &PgLockVirtApic);
10640 if (RT_SUCCESS(rc))
10641 {
10642 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysVirtApic, &HCPhysVirtApic);
10643 AssertMsgRCReturn(rc, ("Failed to get host-physical address for virtual-APIC page at %#RGp\n", GCPhysVirtApic), rc);
10644
10645 /** @todo Handle proper releasing of page-mapping lock later. */
10646 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockVirtApic);
10647 }
10648 else
10649 return rc;
10650
10651 u32TprThreshold = pVmcsNstGst->u32TprThreshold;
10652 }
10653 else
10654 {
10655 HCPhysVirtApic = 0;
10656 u32TprThreshold = 0;
10657
10658 /*
10659 * We must make sure CR8 reads/write must cause VM-exits when TPR shadowing is not
10660 * used by the nested hypervisor. Preventing MMIO accesses to the physical APIC will
10661 * be taken care of by EPT/shadow paging.
10662 */
10663 if (pVM->hmr0.s.fAllow64BitGuests)
10664 u32ProcCtls |= VMX_PROC_CTLS_CR8_STORE_EXIT
10665 | VMX_PROC_CTLS_CR8_LOAD_EXIT;
10666 }
10667
10668 /*
10669 * Validate basic assumptions.
10670 */
10671 PVMXVMCSINFO pVmcsInfoNstGst = &pVCpu->hmr0.s.vmx.VmcsInfoNstGst;
10672 Assert(pVM->hmr0.s.vmx.fUnrestrictedGuest);
10673 Assert(g_HmMsrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
10674 Assert(hmGetVmxActiveVmcsInfo(pVCpu) == pVmcsInfoNstGst);
10675
10676 /*
10677 * Commit it to the nested-guest VMCS.
10678 */
10679 int rc = VINF_SUCCESS;
10680 if (pVmcsInfoNstGst->u32PinCtls != u32PinCtls)
10681 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, u32PinCtls);
10682 if (pVmcsInfoNstGst->u32ProcCtls != u32ProcCtls)
10683 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, u32ProcCtls);
10684 if (pVmcsInfoNstGst->u32ProcCtls2 != u32ProcCtls2)
10685 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, u32ProcCtls2);
10686 if (pVmcsInfoNstGst->u32XcptBitmap != u32XcptBitmap)
10687 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
10688 if (pVmcsInfoNstGst->u64Cr0Mask != u64Cr0Mask)
10689 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask);
10690 if (pVmcsInfoNstGst->u64Cr4Mask != u64Cr4Mask)
10691 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask);
10692 if (pVmcsInfoNstGst->u32XcptPFMask != u32XcptPFMask)
10693 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, u32XcptPFMask);
10694 if (pVmcsInfoNstGst->u32XcptPFMatch != u32XcptPFMatch)
10695 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, u32XcptPFMatch);
10696 if ( !(u32ProcCtls & VMX_PROC_CTLS_PAUSE_EXIT)
10697 && (u32ProcCtls2 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
10698 {
10699 Assert(g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT);
10700 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, cPleGapTicks);
10701 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, cPleWindowTicks);
10702 }
10703 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10704 {
10705 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
10706 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
10707 }
10708 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10709 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
10710 rc |= VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, uPendingDbgXcpts);
10711 AssertRC(rc);
10712
10713 /*
10714 * Update the nested-guest VMCS cache.
10715 */
10716 pVmcsInfoNstGst->u32PinCtls = u32PinCtls;
10717 pVmcsInfoNstGst->u32ProcCtls = u32ProcCtls;
10718 pVmcsInfoNstGst->u32ProcCtls2 = u32ProcCtls2;
10719 pVmcsInfoNstGst->u32XcptBitmap = u32XcptBitmap;
10720 pVmcsInfoNstGst->u64Cr0Mask = u64Cr0Mask;
10721 pVmcsInfoNstGst->u64Cr4Mask = u64Cr4Mask;
10722 pVmcsInfoNstGst->u32XcptPFMask = u32XcptPFMask;
10723 pVmcsInfoNstGst->u32XcptPFMatch = u32XcptPFMatch;
10724 pVmcsInfoNstGst->HCPhysVirtApic = HCPhysVirtApic;
10725
10726 /*
10727 * We need to flush the TLB if we are switching the APIC-access page address.
10728 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
10729 */
10730 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10731 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = true;
10732
10733 /*
10734 * MSR bitmap.
10735 *
10736 * The MSR bitmap address has already been initialized while setting up the nested-guest
10737 * VMCS, here we need to merge the MSR bitmaps.
10738 */
10739 if (u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
10740 hmR0VmxMergeMsrBitmapNested(pVCpu, pVmcsInfoNstGst, pVmcsInfoGst);
10741
10742 return VINF_SUCCESS;
10743}
10744#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
10745
10746
10747/**
10748 * Does the preparations before executing guest code in VT-x.
10749 *
10750 * This may cause longjmps to ring-3 and may even result in rescheduling to the
10751 * recompiler/IEM. We must be cautious what we do here regarding committing
10752 * guest-state information into the VMCS assuming we assuredly execute the
10753 * guest in VT-x mode.
10754 *
10755 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
10756 * the common-state (TRPM/forceflags), we must undo those changes so that the
10757 * recompiler/IEM can (and should) use them when it resumes guest execution.
10758 * Otherwise such operations must be done when we can no longer exit to ring-3.
10759 *
10760 * @returns Strict VBox status code (i.e. informational status codes too).
10761 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
10762 * have been disabled.
10763 * @retval VINF_VMX_VMEXIT if a nested-guest VM-exit occurs (e.g., while evaluating
10764 * pending events).
10765 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
10766 * double-fault into the guest.
10767 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
10768 * dispatched directly.
10769 * @retval VINF_* scheduling changes, we have to go back to ring-3.
10770 *
10771 * @param pVCpu The cross context virtual CPU structure.
10772 * @param pVmxTransient The VMX-transient structure.
10773 * @param fStepping Whether we are single-stepping the guest in the
10774 * hypervisor debugger. Makes us ignore some of the reasons
10775 * for returning to ring-3, and return VINF_EM_DBG_STEPPED
10776 * if event dispatching took place.
10777 */
10778static VBOXSTRICTRC hmR0VmxPreRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, bool fStepping)
10779{
10780 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10781
10782 Log4Func(("fIsNested=%RTbool fStepping=%RTbool\n", pVmxTransient->fIsNestedGuest, fStepping));
10783
10784#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
10785 if (pVmxTransient->fIsNestedGuest)
10786 {
10787 RT_NOREF2(pVCpu, fStepping);
10788 Log2Func(("Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
10789 return VINF_EM_RESCHEDULE_REM;
10790 }
10791#endif
10792
10793 /*
10794 * Check and process force flag actions, some of which might require us to go back to ring-3.
10795 */
10796 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVCpu, pVmxTransient, fStepping);
10797 if (rcStrict == VINF_SUCCESS)
10798 {
10799 /* FFs don't get set all the time. */
10800#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10801 if ( pVmxTransient->fIsNestedGuest
10802 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10803 {
10804 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10805 return VINF_VMX_VMEXIT;
10806 }
10807#endif
10808 }
10809 else
10810 return rcStrict;
10811
10812 /*
10813 * Virtualize memory-mapped accesses to the physical APIC (may take locks).
10814 */
10815 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10816 if ( !pVCpu->hm.s.vmx.u64GstMsrApicBase
10817 && (g_HmMsrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10818 && PDMHasApic(pVM))
10819 {
10820 int rc = hmR0VmxMapHCApicAccessPage(pVCpu);
10821 AssertRCReturn(rc, rc);
10822 }
10823
10824#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10825 /*
10826 * Merge guest VMCS controls with the nested-guest VMCS controls.
10827 *
10828 * Even if we have not executed the guest prior to this (e.g. when resuming from a
10829 * saved state), we should be okay with merging controls as we initialize the
10830 * guest VMCS controls as part of VM setup phase.
10831 */
10832 if ( pVmxTransient->fIsNestedGuest
10833 && !pVCpu->hm.s.vmx.fMergedNstGstCtls)
10834 {
10835 int rc = hmR0VmxMergeVmcsNested(pVCpu);
10836 AssertRCReturn(rc, rc);
10837 pVCpu->hm.s.vmx.fMergedNstGstCtls = true;
10838 }
10839#endif
10840
10841 /*
10842 * Evaluate events to be injected into the guest.
10843 *
10844 * Events in TRPM can be injected without inspecting the guest state.
10845 * If any new events (interrupts/NMI) are pending currently, we try to set up the
10846 * guest to cause a VM-exit the next time they are ready to receive the event.
10847 */
10848 if (TRPMHasTrap(pVCpu))
10849 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
10850
10851 uint32_t fIntrState;
10852 rcStrict = hmR0VmxEvaluatePendingEvent(pVCpu, pVmxTransient, &fIntrState);
10853
10854#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10855 /*
10856 * While evaluating pending events if something failed (unlikely) or if we were
10857 * preparing to run a nested-guest but performed a nested-guest VM-exit, we should bail.
10858 */
10859 if (rcStrict != VINF_SUCCESS)
10860 return rcStrict;
10861 if ( pVmxTransient->fIsNestedGuest
10862 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10863 {
10864 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10865 return VINF_VMX_VMEXIT;
10866 }
10867#else
10868 Assert(rcStrict == VINF_SUCCESS);
10869#endif
10870
10871 /*
10872 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus
10873 * needs to be done with longjmps or interrupts + preemption enabled. Event injection might
10874 * also result in triple-faulting the VM.
10875 *
10876 * With nested-guests, the above does not apply since unrestricted guest execution is a
10877 * requirement. Regardless, we do this here to avoid duplicating code elsewhere.
10878 */
10879 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pVmxTransient, fIntrState, fStepping);
10880 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10881 { /* likely */ }
10882 else
10883 {
10884 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
10885 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
10886 return rcStrict;
10887 }
10888
10889 /*
10890 * A longjump might result in importing CR3 even for VM-exits that don't necessarily
10891 * import CR3 themselves. We will need to update them here, as even as late as the above
10892 * hmR0VmxInjectPendingEvent() call may lazily import guest-CPU state on demand causing
10893 * the below force flags to be set.
10894 */
10895 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
10896 {
10897 Assert(!(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_CR3));
10898 int rc2 = PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
10899 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
10900 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
10901 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10902 }
10903 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
10904 {
10905 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
10906 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10907 }
10908
10909#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10910 /* Paranoia. */
10911 Assert(!pVmxTransient->fIsNestedGuest || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10912#endif
10913
10914 /*
10915 * No longjmps to ring-3 from this point on!!!
10916 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
10917 * This also disables flushing of the R0-logger instance (if any).
10918 */
10919 VMMRZCallRing3Disable(pVCpu);
10920
10921 /*
10922 * Export the guest state bits.
10923 *
10924 * We cannot perform longjmps while loading the guest state because we do not preserve the
10925 * host/guest state (although the VMCS will be preserved) across longjmps which can cause
10926 * CPU migration.
10927 *
10928 * If we are injecting events to a real-on-v86 mode guest, we would have updated RIP and some segment
10929 * registers. Hence, exporting of the guest state needs to be done -after- injection of events.
10930 */
10931 rcStrict = hmR0VmxExportGuestStateOptimal(pVCpu, pVmxTransient);
10932 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10933 { /* likely */ }
10934 else
10935 {
10936 VMMRZCallRing3Enable(pVCpu);
10937 return rcStrict;
10938 }
10939
10940 /*
10941 * We disable interrupts so that we don't miss any interrupts that would flag preemption
10942 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
10943 * preemption disabled for a while. Since this is purely to aid the
10944 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
10945 * disable interrupt on NT.
10946 *
10947 * We need to check for force-flags that could've possible been altered since we last
10948 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
10949 * see @bugref{6398}).
10950 *
10951 * We also check a couple of other force-flags as a last opportunity to get the EMT back
10952 * to ring-3 before executing guest code.
10953 */
10954 pVmxTransient->fEFlags = ASMIntDisableFlags();
10955
10956 if ( ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
10957 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
10958 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
10959 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
10960 {
10961 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
10962 {
10963#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10964 /*
10965 * If we are executing a nested-guest make sure that we should intercept subsequent
10966 * events. The one we are injecting might be part of VM-entry. This is mainly to keep
10967 * the VM-exit instruction emulation happy.
10968 */
10969 if (pVmxTransient->fIsNestedGuest)
10970 CPUMSetGuestVmxInterceptEvents(&pVCpu->cpum.GstCtx, true);
10971#endif
10972
10973 /*
10974 * We've injected any pending events. This is really the point of no return (to ring-3).
10975 *
10976 * Note! The caller expects to continue with interrupts & longjmps disabled on successful
10977 * returns from this function, so do -not- enable them here.
10978 */
10979 pVCpu->hm.s.Event.fPending = false;
10980 return VINF_SUCCESS;
10981 }
10982
10983 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPendingHostIrq);
10984 rcStrict = VINF_EM_RAW_INTERRUPT;
10985 }
10986 else
10987 {
10988 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
10989 rcStrict = VINF_EM_RAW_TO_R3;
10990 }
10991
10992 ASMSetFlags(pVmxTransient->fEFlags);
10993 VMMRZCallRing3Enable(pVCpu);
10994
10995 return rcStrict;
10996}
10997
10998
10999/**
11000 * Final preparations before executing guest code using hardware-assisted VMX.
11001 *
11002 * We can no longer get preempted to a different host CPU and there are no returns
11003 * to ring-3. We ignore any errors that may happen from this point (e.g. VMWRITE
11004 * failures), this function is not intended to fail sans unrecoverable hardware
11005 * errors.
11006 *
11007 * @param pVCpu The cross context virtual CPU structure.
11008 * @param pVmxTransient The VMX-transient structure.
11009 *
11010 * @remarks Called with preemption disabled.
11011 * @remarks No-long-jump zone!!!
11012 */
11013static void hmR0VmxPreRunGuestCommitted(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
11014{
11015 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
11016 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
11017 Assert(!pVCpu->hm.s.Event.fPending);
11018
11019 /*
11020 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
11021 */
11022 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
11023 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
11024
11025 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11026 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11027 PHMPHYSCPU pHostCpu = hmR0GetCurrentCpu();
11028 RTCPUID const idCurrentCpu = pHostCpu->idCpu;
11029
11030 if (!CPUMIsGuestFPUStateActive(pVCpu))
11031 {
11032 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
11033 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
11034 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT;
11035 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
11036 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
11037 }
11038
11039 /*
11040 * Re-export the host state bits as we may've been preempted (only happens when
11041 * thread-context hooks are used or when the VM start function changes) or if
11042 * the host CR0 is modified while loading the guest FPU state above.
11043 *
11044 * The 64-on-32 switcher saves the (64-bit) host state into the VMCS and if we
11045 * changed the switcher back to 32-bit, we *must* save the 32-bit host state here,
11046 * see @bugref{8432}.
11047 *
11048 * This may also happen when switching to/from a nested-guest VMCS without leaving
11049 * ring-0.
11050 */
11051 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
11052 {
11053 hmR0VmxExportHostState(pVCpu);
11054 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportHostState);
11055 }
11056 Assert(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT));
11057
11058 /*
11059 * Export the state shared between host and guest (FPU, debug, lazy MSRs).
11060 */
11061 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)
11062 hmR0VmxExportSharedState(pVCpu, pVmxTransient);
11063 AssertMsg(!pVCpu->hm.s.fCtxChanged, ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
11064
11065 /*
11066 * Store status of the shared guest/host debug state at the time of VM-entry.
11067 */
11068 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
11069 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
11070
11071 /*
11072 * Always cache the TPR-shadow if the virtual-APIC page exists, thereby skipping
11073 * more than one conditional check. The post-run side of our code shall determine
11074 * if it needs to sync. the virtual APIC TPR with the TPR-shadow.
11075 */
11076 if (pVmcsInfo->pbVirtApic)
11077 pVmxTransient->u8GuestTpr = pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR];
11078
11079 /*
11080 * Update the host MSRs values in the VM-exit MSR-load area.
11081 */
11082 if (!pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs)
11083 {
11084 if (pVmcsInfo->cExitMsrLoad > 0)
11085 hmR0VmxUpdateAutoLoadHostMsrs(pVCpu, pVmcsInfo);
11086 pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs = true;
11087 }
11088
11089 /*
11090 * Evaluate if we need to intercept guest RDTSC/P accesses. Set up the
11091 * VMX-preemption timer based on the next virtual sync clock deadline.
11092 */
11093 if ( !pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer
11094 || idCurrentCpu != pVCpu->hmr0.s.idLastCpu)
11095 {
11096 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVCpu, pVmxTransient, idCurrentCpu);
11097 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = true;
11098 }
11099
11100 /* Record statistics of how often we use TSC offsetting as opposed to intercepting RDTSC/P. */
11101 bool const fIsRdtscIntercepted = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT);
11102 if (!fIsRdtscIntercepted)
11103 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
11104 else
11105 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
11106
11107 ASMAtomicUoWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
11108 hmR0VmxFlushTaggedTlb(pHostCpu, pVCpu, pVmcsInfo); /* Invalidate the appropriate guest entries from the TLB. */
11109 Assert(idCurrentCpu == pVCpu->hmr0.s.idLastCpu);
11110 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Record the error reporting info. with the current host CPU. */
11111 pVmcsInfo->idHostCpuState = idCurrentCpu; /* Record the CPU for which the host-state has been exported. */
11112 pVmcsInfo->idHostCpuExec = idCurrentCpu; /* Record the CPU on which we shall execute. */
11113
11114 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
11115
11116 TMNotifyStartOfExecution(pVM, pVCpu); /* Notify TM to resume its clocks when TSC is tied to execution,
11117 as we're about to start executing the guest. */
11118
11119 /*
11120 * Load the guest TSC_AUX MSR when we are not intercepting RDTSCP.
11121 *
11122 * This is done this late as updating the TSC offsetting/preemption timer above
11123 * figures out if we can skip intercepting RDTSCP by calculating the number of
11124 * host CPU ticks till the next virtual sync deadline (for the dynamic case).
11125 */
11126 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_RDTSCP)
11127 && !fIsRdtscIntercepted)
11128 {
11129 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_TSC_AUX);
11130
11131 /* NB: Because we call hmR0VmxAddAutoLoadStoreMsr with fUpdateHostMsr=true,
11132 it's safe even after hmR0VmxUpdateAutoLoadHostMsrs has already been done. */
11133 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX, CPUMGetGuestTscAux(pVCpu),
11134 true /* fSetReadWrite */, true /* fUpdateHostMsr */);
11135 AssertRC(rc);
11136 Assert(!pVmxTransient->fRemoveTscAuxMsr);
11137 pVmxTransient->fRemoveTscAuxMsr = true;
11138 }
11139
11140#ifdef VBOX_STRICT
11141 Assert(pVCpu->hmr0.s.vmx.fUpdatedHostAutoMsrs);
11142 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
11143 hmR0VmxCheckHostEferMsr(pVmcsInfo);
11144 AssertRC(hmR0VmxCheckCachedVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest));
11145#endif
11146
11147#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
11148 /** @todo r=ramshankar: We can now probably use iemVmxVmentryCheckGuestState here.
11149 * Add a PVMXMSRS parameter to it, so that IEM can look at the host MSRs,
11150 * see @bugref{9180#c54}. */
11151 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
11152 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
11153 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
11154#endif
11155}
11156
11157
11158/**
11159 * First C routine invoked after running guest code using hardware-assisted VMX.
11160 *
11161 * @param pVCpu The cross context virtual CPU structure.
11162 * @param pVmxTransient The VMX-transient structure.
11163 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
11164 *
11165 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
11166 *
11167 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
11168 * unconditionally when it is safe to do so.
11169 */
11170static void hmR0VmxPostRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, int rcVMRun)
11171{
11172 ASMAtomicUoWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
11173 ASMAtomicIncU32(&pVCpu->hmr0.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
11174 pVCpu->hm.s.fCtxChanged = 0; /* Exits/longjmps to ring-3 requires saving the guest state. */
11175 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
11176 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
11177 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
11178
11179 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11180 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT))
11181 {
11182 uint64_t uGstTsc;
11183 if (!pVmxTransient->fIsNestedGuest)
11184 uGstTsc = pVCpu->hmr0.s.uTscExit + pVmcsInfo->u64TscOffset;
11185 else
11186 {
11187 uint64_t const uNstGstTsc = pVCpu->hmr0.s.uTscExit + pVmcsInfo->u64TscOffset;
11188 uGstTsc = CPUMRemoveNestedGuestTscOffset(pVCpu, uNstGstTsc);
11189 }
11190 TMCpuTickSetLastSeen(pVCpu, uGstTsc); /* Update TM with the guest TSC. */
11191 }
11192
11193 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatPreExit, x);
11194 TMNotifyEndOfExecution(pVCpu->CTX_SUFF(pVM), pVCpu, pVCpu->hmr0.s.uTscExit); /* Notify TM that the guest is no longer running. */
11195 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
11196
11197 pVCpu->hmr0.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Some host state messed up by VMX needs restoring. */
11198 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
11199#ifdef VBOX_STRICT
11200 hmR0VmxCheckHostEferMsr(pVmcsInfo); /* Verify that the host EFER MSR wasn't modified. */
11201#endif
11202 Assert(!ASMIntAreEnabled());
11203 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
11204 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
11205
11206#ifdef HMVMX_ALWAYS_CLEAN_TRANSIENT
11207 /*
11208 * Clean all the VMCS fields in the transient structure before reading
11209 * anything from the VMCS.
11210 */
11211 pVmxTransient->uExitReason = 0;
11212 pVmxTransient->uExitIntErrorCode = 0;
11213 pVmxTransient->uExitQual = 0;
11214 pVmxTransient->uGuestLinearAddr = 0;
11215 pVmxTransient->uExitIntInfo = 0;
11216 pVmxTransient->cbExitInstr = 0;
11217 pVmxTransient->ExitInstrInfo.u = 0;
11218 pVmxTransient->uEntryIntInfo = 0;
11219 pVmxTransient->uEntryXcptErrorCode = 0;
11220 pVmxTransient->cbEntryInstr = 0;
11221 pVmxTransient->uIdtVectoringInfo = 0;
11222 pVmxTransient->uIdtVectoringErrorCode = 0;
11223#endif
11224
11225 /*
11226 * Save the basic VM-exit reason and check if the VM-entry failed.
11227 * See Intel spec. 24.9.1 "Basic VM-exit Information".
11228 */
11229 uint32_t uExitReason;
11230 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
11231 AssertRC(rc);
11232 pVmxTransient->uExitReason = VMX_EXIT_REASON_BASIC(uExitReason);
11233 pVmxTransient->fVMEntryFailed = VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason);
11234
11235 /*
11236 * Log the VM-exit before logging anything else as otherwise it might be a
11237 * tad confusing what happens before and after the world-switch.
11238 */
11239 HMVMX_LOG_EXIT(pVCpu, uExitReason);
11240
11241 /*
11242 * Remove the TSC_AUX MSR from the auto-load/store MSR area and reset any MSR
11243 * bitmap permissions, if it was added before VM-entry.
11244 */
11245 if (pVmxTransient->fRemoveTscAuxMsr)
11246 {
11247 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX);
11248 pVmxTransient->fRemoveTscAuxMsr = false;
11249 }
11250
11251 /*
11252 * Check if VMLAUNCH/VMRESUME succeeded.
11253 * If this failed, we cause a guru meditation and cease further execution.
11254 *
11255 * However, if we are executing a nested-guest we might fail if we use the
11256 * fast path rather than fully emulating VMLAUNCH/VMRESUME instruction in IEM.
11257 */
11258 if (RT_LIKELY(rcVMRun == VINF_SUCCESS))
11259 {
11260 /*
11261 * Update the VM-exit history array here even if the VM-entry failed due to:
11262 * - Invalid guest state.
11263 * - MSR loading.
11264 * - Machine-check event.
11265 *
11266 * In any of the above cases we will still have a "valid" VM-exit reason
11267 * despite @a fVMEntryFailed being false.
11268 *
11269 * See Intel spec. 26.7 "VM-Entry failures during or after loading guest state".
11270 *
11271 * Note! We don't have CS or RIP at this point. Will probably address that later
11272 * by amending the history entry added here.
11273 */
11274 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_VMX, pVmxTransient->uExitReason & EMEXIT_F_TYPE_MASK),
11275 UINT64_MAX, pVCpu->hmr0.s.uTscExit);
11276
11277 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
11278 {
11279 VMMRZCallRing3Enable(pVCpu);
11280
11281 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
11282 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
11283
11284#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
11285 hmR0VmxReadAllRoFieldsVmcs(pVmxTransient);
11286#endif
11287
11288 /*
11289 * Import the guest-interruptibility state always as we need it while evaluating
11290 * injecting events on re-entry.
11291 *
11292 * We don't import CR0 (when unrestricted guest execution is unavailable) despite
11293 * checking for real-mode while exporting the state because all bits that cause
11294 * mode changes wrt CR0 are intercepted.
11295 */
11296 uint64_t const fImportMask = CPUMCTX_EXTRN_HM_VMX_INT_STATE
11297#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
11298 | HMVMX_CPUMCTX_EXTRN_ALL
11299#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
11300 | CPUMCTX_EXTRN_RFLAGS
11301#endif
11302 ;
11303 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImportMask);
11304 AssertRC(rc);
11305
11306 /*
11307 * Sync the TPR shadow with our APIC state.
11308 */
11309 if ( !pVmxTransient->fIsNestedGuest
11310 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
11311 {
11312 Assert(pVmcsInfo->pbVirtApic);
11313 if (pVmxTransient->u8GuestTpr != pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR])
11314 {
11315 rc = APICSetTpr(pVCpu, pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR]);
11316 AssertRC(rc);
11317 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
11318 }
11319 }
11320
11321 Assert(VMMRZCallRing3IsEnabled(pVCpu));
11322 Assert( pVmxTransient->fWasGuestDebugStateActive == false
11323 || pVmxTransient->fWasHyperDebugStateActive == false);
11324 return;
11325 }
11326 }
11327#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
11328 else if (pVmxTransient->fIsNestedGuest)
11329 AssertMsgFailed(("VMLAUNCH/VMRESUME failed but shouldn't happen when VMLAUNCH/VMRESUME was emulated in IEM!\n"));
11330#endif
11331 else
11332 Log4Func(("VM-entry failure: rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", rcVMRun, pVmxTransient->fVMEntryFailed));
11333
11334 VMMRZCallRing3Enable(pVCpu);
11335}
11336
11337
11338/**
11339 * Runs the guest code using hardware-assisted VMX the normal way.
11340 *
11341 * @returns VBox status code.
11342 * @param pVCpu The cross context virtual CPU structure.
11343 * @param pcLoops Pointer to the number of executed loops.
11344 */
11345static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVMCPUCC pVCpu, uint32_t *pcLoops)
11346{
11347 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hmr0.s.cMaxResumeLoops;
11348 Assert(pcLoops);
11349 Assert(*pcLoops <= cMaxResumeLoops);
11350 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
11351
11352#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
11353 /*
11354 * Switch to the guest VMCS as we may have transitioned from executing the nested-guest
11355 * without leaving ring-0. Otherwise, if we came from ring-3 we would have loaded the
11356 * guest VMCS while entering the VMX ring-0 session.
11357 */
11358 if (pVCpu->hmr0.s.vmx.fSwitchedToNstGstVmcs)
11359 {
11360 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, false /* fSwitchToNstGstVmcs */);
11361 if (RT_SUCCESS(rc))
11362 { /* likely */ }
11363 else
11364 {
11365 LogRelFunc(("Failed to switch to the guest VMCS. rc=%Rrc\n", rc));
11366 return rc;
11367 }
11368 }
11369#endif
11370
11371 VMXTRANSIENT VmxTransient;
11372 RT_ZERO(VmxTransient);
11373 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
11374
11375 /* Paranoia. */
11376 Assert(VmxTransient.pVmcsInfo == &pVCpu->hmr0.s.vmx.VmcsInfo);
11377
11378 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
11379 for (;;)
11380 {
11381 Assert(!HMR0SuspendPending());
11382 HMVMX_ASSERT_CPU_SAFE(pVCpu);
11383 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
11384
11385 /*
11386 * Preparatory work for running nested-guest code, this may force us to
11387 * return to ring-3.
11388 *
11389 * Warning! This bugger disables interrupts on VINF_SUCCESS!
11390 */
11391 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
11392 if (rcStrict != VINF_SUCCESS)
11393 break;
11394
11395 /* Interrupts are disabled at this point! */
11396 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
11397 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
11398 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
11399 /* Interrupts are re-enabled at this point! */
11400
11401 /*
11402 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
11403 */
11404 if (RT_SUCCESS(rcRun))
11405 { /* very likely */ }
11406 else
11407 {
11408 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
11409 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
11410 return rcRun;
11411 }
11412
11413 /*
11414 * Profile the VM-exit.
11415 */
11416 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
11417 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
11418 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
11419 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
11420 HMVMX_START_EXIT_DISPATCH_PROF();
11421
11422 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
11423
11424 /*
11425 * Handle the VM-exit.
11426 */
11427#ifdef HMVMX_USE_FUNCTION_TABLE
11428 rcStrict = g_aVMExitHandlers[VmxTransient.uExitReason].pfn(pVCpu, &VmxTransient);
11429#else
11430 rcStrict = hmR0VmxHandleExit(pVCpu, &VmxTransient);
11431#endif
11432 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
11433 if (rcStrict == VINF_SUCCESS)
11434 {
11435 if (++(*pcLoops) <= cMaxResumeLoops)
11436 continue;
11437 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
11438 rcStrict = VINF_EM_RAW_INTERRUPT;
11439 }
11440 break;
11441 }
11442
11443 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
11444 return rcStrict;
11445}
11446
11447
11448#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
11449/**
11450 * Runs the nested-guest code using hardware-assisted VMX.
11451 *
11452 * @returns VBox status code.
11453 * @param pVCpu The cross context virtual CPU structure.
11454 * @param pcLoops Pointer to the number of executed loops.
11455 *
11456 * @sa hmR0VmxRunGuestCodeNormal.
11457 */
11458static VBOXSTRICTRC hmR0VmxRunGuestCodeNested(PVMCPUCC pVCpu, uint32_t *pcLoops)
11459{
11460 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hmr0.s.cMaxResumeLoops;
11461 Assert(pcLoops);
11462 Assert(*pcLoops <= cMaxResumeLoops);
11463 Assert(CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
11464
11465 /*
11466 * Switch to the nested-guest VMCS as we may have transitioned from executing the
11467 * guest without leaving ring-0. Otherwise, if we came from ring-3 we would have
11468 * loaded the nested-guest VMCS while entering the VMX ring-0 session.
11469 */
11470 if (!pVCpu->hmr0.s.vmx.fSwitchedToNstGstVmcs)
11471 {
11472 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, true /* fSwitchToNstGstVmcs */);
11473 if (RT_SUCCESS(rc))
11474 { /* likely */ }
11475 else
11476 {
11477 LogRelFunc(("Failed to switch to the nested-guest VMCS. rc=%Rrc\n", rc));
11478 return rc;
11479 }
11480 }
11481
11482 VMXTRANSIENT VmxTransient;
11483 RT_ZERO(VmxTransient);
11484 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
11485 VmxTransient.fIsNestedGuest = true;
11486
11487 /* Paranoia. */
11488 Assert(VmxTransient.pVmcsInfo == &pVCpu->hmr0.s.vmx.VmcsInfoNstGst);
11489
11490 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
11491 for (;;)
11492 {
11493 Assert(!HMR0SuspendPending());
11494 HMVMX_ASSERT_CPU_SAFE(pVCpu);
11495 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
11496
11497 /*
11498 * Preparatory work for running guest code, this may force us to
11499 * return to ring-3.
11500 *
11501 * Warning! This bugger disables interrupts on VINF_SUCCESS!
11502 */
11503 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
11504 if (rcStrict != VINF_SUCCESS)
11505 break;
11506
11507 /* Interrupts are disabled at this point! */
11508 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
11509 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
11510 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
11511 /* Interrupts are re-enabled at this point! */
11512
11513 /*
11514 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
11515 */
11516 if (RT_SUCCESS(rcRun))
11517 { /* very likely */ }
11518 else
11519 {
11520 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
11521 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
11522 return rcRun;
11523 }
11524
11525 /*
11526 * Profile the VM-exit.
11527 */
11528 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
11529 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
11530 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitAll);
11531 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
11532 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
11533 HMVMX_START_EXIT_DISPATCH_PROF();
11534
11535 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
11536
11537 /*
11538 * Handle the VM-exit.
11539 */
11540 rcStrict = hmR0VmxHandleExitNested(pVCpu, &VmxTransient);
11541 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
11542 if (rcStrict == VINF_SUCCESS)
11543 {
11544 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
11545 {
11546 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
11547 rcStrict = VINF_VMX_VMEXIT;
11548 }
11549 else
11550 {
11551 if (++(*pcLoops) <= cMaxResumeLoops)
11552 continue;
11553 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
11554 rcStrict = VINF_EM_RAW_INTERRUPT;
11555 }
11556 }
11557 else
11558 Assert(rcStrict != VINF_VMX_VMEXIT);
11559 break;
11560 }
11561
11562 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
11563 return rcStrict;
11564}
11565#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
11566
11567
11568/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
11569 * probes.
11570 *
11571 * The following few functions and associated structure contains the bloat
11572 * necessary for providing detailed debug events and dtrace probes as well as
11573 * reliable host side single stepping. This works on the principle of
11574 * "subclassing" the normal execution loop and workers. We replace the loop
11575 * method completely and override selected helpers to add necessary adjustments
11576 * to their core operation.
11577 *
11578 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
11579 * any performance for debug and analysis features.
11580 *
11581 * @{
11582 */
11583
11584/**
11585 * Transient per-VCPU debug state of VMCS and related info. we save/restore in
11586 * the debug run loop.
11587 */
11588typedef struct VMXRUNDBGSTATE
11589{
11590 /** The RIP we started executing at. This is for detecting that we stepped. */
11591 uint64_t uRipStart;
11592 /** The CS we started executing with. */
11593 uint16_t uCsStart;
11594
11595 /** Whether we've actually modified the 1st execution control field. */
11596 bool fModifiedProcCtls : 1;
11597 /** Whether we've actually modified the 2nd execution control field. */
11598 bool fModifiedProcCtls2 : 1;
11599 /** Whether we've actually modified the exception bitmap. */
11600 bool fModifiedXcptBitmap : 1;
11601
11602 /** We desire the modified the CR0 mask to be cleared. */
11603 bool fClearCr0Mask : 1;
11604 /** We desire the modified the CR4 mask to be cleared. */
11605 bool fClearCr4Mask : 1;
11606 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
11607 uint32_t fCpe1Extra;
11608 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
11609 uint32_t fCpe1Unwanted;
11610 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
11611 uint32_t fCpe2Extra;
11612 /** Extra stuff we need in VMX_VMCS32_CTRL_EXCEPTION_BITMAP. */
11613 uint32_t bmXcptExtra;
11614 /** The sequence number of the Dtrace provider settings the state was
11615 * configured against. */
11616 uint32_t uDtraceSettingsSeqNo;
11617 /** VM-exits to check (one bit per VM-exit). */
11618 uint32_t bmExitsToCheck[3];
11619
11620 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
11621 uint32_t fProcCtlsInitial;
11622 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
11623 uint32_t fProcCtls2Initial;
11624 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
11625 uint32_t bmXcptInitial;
11626} VMXRUNDBGSTATE;
11627AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
11628typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
11629
11630
11631/**
11632 * Initializes the VMXRUNDBGSTATE structure.
11633 *
11634 * @param pVCpu The cross context virtual CPU structure of the
11635 * calling EMT.
11636 * @param pVmxTransient The VMX-transient structure.
11637 * @param pDbgState The debug state to initialize.
11638 */
11639static void hmR0VmxRunDebugStateInit(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11640{
11641 pDbgState->uRipStart = pVCpu->cpum.GstCtx.rip;
11642 pDbgState->uCsStart = pVCpu->cpum.GstCtx.cs.Sel;
11643
11644 pDbgState->fModifiedProcCtls = false;
11645 pDbgState->fModifiedProcCtls2 = false;
11646 pDbgState->fModifiedXcptBitmap = false;
11647 pDbgState->fClearCr0Mask = false;
11648 pDbgState->fClearCr4Mask = false;
11649 pDbgState->fCpe1Extra = 0;
11650 pDbgState->fCpe1Unwanted = 0;
11651 pDbgState->fCpe2Extra = 0;
11652 pDbgState->bmXcptExtra = 0;
11653 pDbgState->fProcCtlsInitial = pVmxTransient->pVmcsInfo->u32ProcCtls;
11654 pDbgState->fProcCtls2Initial = pVmxTransient->pVmcsInfo->u32ProcCtls2;
11655 pDbgState->bmXcptInitial = pVmxTransient->pVmcsInfo->u32XcptBitmap;
11656}
11657
11658
11659/**
11660 * Updates the VMSC fields with changes requested by @a pDbgState.
11661 *
11662 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
11663 * immediately before executing guest code, i.e. when interrupts are disabled.
11664 * We don't check status codes here as we cannot easily assert or return in the
11665 * latter case.
11666 *
11667 * @param pVCpu The cross context virtual CPU structure.
11668 * @param pVmxTransient The VMX-transient structure.
11669 * @param pDbgState The debug state.
11670 */
11671static void hmR0VmxPreRunGuestDebugStateApply(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11672{
11673 /*
11674 * Ensure desired flags in VMCS control fields are set.
11675 * (Ignoring write failure here, as we're committed and it's just debug extras.)
11676 *
11677 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
11678 * there should be no stale data in pCtx at this point.
11679 */
11680 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11681 if ( (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
11682 || (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Unwanted))
11683 {
11684 pVmcsInfo->u32ProcCtls |= pDbgState->fCpe1Extra;
11685 pVmcsInfo->u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
11686 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
11687 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVmcsInfo->u32ProcCtls));
11688 pDbgState->fModifiedProcCtls = true;
11689 }
11690
11691 if ((pVmcsInfo->u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
11692 {
11693 pVmcsInfo->u32ProcCtls2 |= pDbgState->fCpe2Extra;
11694 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVmcsInfo->u32ProcCtls2);
11695 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVmcsInfo->u32ProcCtls2));
11696 pDbgState->fModifiedProcCtls2 = true;
11697 }
11698
11699 if ((pVmcsInfo->u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
11700 {
11701 pVmcsInfo->u32XcptBitmap |= pDbgState->bmXcptExtra;
11702 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVmcsInfo->u32XcptBitmap);
11703 Log6Func(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVmcsInfo->u32XcptBitmap));
11704 pDbgState->fModifiedXcptBitmap = true;
11705 }
11706
11707 if (pDbgState->fClearCr0Mask && pVmcsInfo->u64Cr0Mask != 0)
11708 {
11709 pVmcsInfo->u64Cr0Mask = 0;
11710 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, 0);
11711 Log6Func(("VMX_VMCS_CTRL_CR0_MASK: 0\n"));
11712 }
11713
11714 if (pDbgState->fClearCr4Mask && pVmcsInfo->u64Cr4Mask != 0)
11715 {
11716 pVmcsInfo->u64Cr4Mask = 0;
11717 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, 0);
11718 Log6Func(("VMX_VMCS_CTRL_CR4_MASK: 0\n"));
11719 }
11720
11721 NOREF(pVCpu);
11722}
11723
11724
11725/**
11726 * Restores VMCS fields that were changed by hmR0VmxPreRunGuestDebugStateApply for
11727 * re-entry next time around.
11728 *
11729 * @returns Strict VBox status code (i.e. informational status codes too).
11730 * @param pVCpu The cross context virtual CPU structure.
11731 * @param pVmxTransient The VMX-transient structure.
11732 * @param pDbgState The debug state.
11733 * @param rcStrict The return code from executing the guest using single
11734 * stepping.
11735 */
11736static VBOXSTRICTRC hmR0VmxRunDebugStateRevert(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState,
11737 VBOXSTRICTRC rcStrict)
11738{
11739 /*
11740 * Restore VM-exit control settings as we may not reenter this function the
11741 * next time around.
11742 */
11743 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11744
11745 /* We reload the initial value, trigger what we can of recalculations the
11746 next time around. From the looks of things, that's all that's required atm. */
11747 if (pDbgState->fModifiedProcCtls)
11748 {
11749 if (!(pDbgState->fProcCtlsInitial & VMX_PROC_CTLS_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
11750 pDbgState->fProcCtlsInitial |= VMX_PROC_CTLS_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
11751 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
11752 AssertRC(rc2);
11753 pVmcsInfo->u32ProcCtls = pDbgState->fProcCtlsInitial;
11754 }
11755
11756 /* We're currently the only ones messing with this one, so just restore the
11757 cached value and reload the field. */
11758 if ( pDbgState->fModifiedProcCtls2
11759 && pVmcsInfo->u32ProcCtls2 != pDbgState->fProcCtls2Initial)
11760 {
11761 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
11762 AssertRC(rc2);
11763 pVmcsInfo->u32ProcCtls2 = pDbgState->fProcCtls2Initial;
11764 }
11765
11766 /* If we've modified the exception bitmap, we restore it and trigger
11767 reloading and partial recalculation the next time around. */
11768 if (pDbgState->fModifiedXcptBitmap)
11769 pVmcsInfo->u32XcptBitmap = pDbgState->bmXcptInitial;
11770
11771 return rcStrict;
11772}
11773
11774
11775/**
11776 * Configures VM-exit controls for current DBGF and DTrace settings.
11777 *
11778 * This updates @a pDbgState and the VMCS execution control fields to reflect
11779 * the necessary VM-exits demanded by DBGF and DTrace.
11780 *
11781 * @param pVCpu The cross context virtual CPU structure.
11782 * @param pVmxTransient The VMX-transient structure. May update
11783 * fUpdatedTscOffsettingAndPreemptTimer.
11784 * @param pDbgState The debug state.
11785 */
11786static void hmR0VmxPreRunGuestDebugStateUpdate(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11787{
11788 /*
11789 * Take down the dtrace serial number so we can spot changes.
11790 */
11791 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
11792 ASMCompilerBarrier();
11793
11794 /*
11795 * We'll rebuild most of the middle block of data members (holding the
11796 * current settings) as we go along here, so start by clearing it all.
11797 */
11798 pDbgState->bmXcptExtra = 0;
11799 pDbgState->fCpe1Extra = 0;
11800 pDbgState->fCpe1Unwanted = 0;
11801 pDbgState->fCpe2Extra = 0;
11802 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
11803 pDbgState->bmExitsToCheck[i] = 0;
11804
11805 /*
11806 * Software interrupts (INT XXh) - no idea how to trigger these...
11807 */
11808 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11809 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
11810 || VBOXVMM_INT_SOFTWARE_ENABLED())
11811 {
11812 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11813 }
11814
11815 /*
11816 * INT3 breakpoints - triggered by #BP exceptions.
11817 */
11818 if (pVM->dbgf.ro.cEnabledInt3Breakpoints > 0)
11819 pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11820
11821 /*
11822 * Exception bitmap and XCPT events+probes.
11823 */
11824 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
11825 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
11826 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
11827
11828 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
11829 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
11830 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11831 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
11832 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
11833 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
11834 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
11835 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
11836 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
11837 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
11838 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
11839 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
11840 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
11841 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
11842 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
11843 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
11844 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
11845 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
11846
11847 if (pDbgState->bmXcptExtra)
11848 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11849
11850 /*
11851 * Process events and probes for VM-exits, making sure we get the wanted VM-exits.
11852 *
11853 * Note! This is the reverse of what hmR0VmxHandleExitDtraceEvents does.
11854 * So, when adding/changing/removing please don't forget to update it.
11855 *
11856 * Some of the macros are picking up local variables to save horizontal space,
11857 * (being able to see it in a table is the lesser evil here).
11858 */
11859#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
11860 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
11861 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
11862#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
11863 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11864 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11865 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11866 } else do { } while (0)
11867#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
11868 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11869 { \
11870 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
11871 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11872 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11873 } else do { } while (0)
11874#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
11875 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11876 { \
11877 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
11878 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11879 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11880 } else do { } while (0)
11881#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
11882 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11883 { \
11884 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
11885 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11886 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11887 } else do { } while (0)
11888
11889 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
11890 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
11891 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
11892 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
11893 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
11894
11895 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
11896 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
11897 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
11898 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
11899 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_PROC_CTLS_HLT_EXIT); /* paranoia */
11900 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
11901 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
11902 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
11903 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_PROC_CTLS_INVLPG_EXIT);
11904 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
11905 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_PROC_CTLS_RDPMC_EXIT);
11906 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
11907 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_PROC_CTLS_RDTSC_EXIT);
11908 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
11909 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
11910 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
11911 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
11912 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
11913 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
11914 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
11915 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
11916 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
11917 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
11918 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
11919 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
11920 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
11921 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
11922 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
11923 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
11924 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
11925 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
11926 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
11927 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
11928 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
11929 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
11930 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
11931
11932 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
11933 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11934 {
11935 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4
11936 | CPUMCTX_EXTRN_APIC_TPR);
11937 AssertRC(rc);
11938
11939#if 0 /** @todo fix me */
11940 pDbgState->fClearCr0Mask = true;
11941 pDbgState->fClearCr4Mask = true;
11942#endif
11943 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
11944 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_STORE_EXIT | VMX_PROC_CTLS_CR8_STORE_EXIT;
11945 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11946 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_LOAD_EXIT | VMX_PROC_CTLS_CR8_LOAD_EXIT;
11947 pDbgState->fCpe1Unwanted |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* risky? */
11948 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
11949 require clearing here and in the loop if we start using it. */
11950 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
11951 }
11952 else
11953 {
11954 if (pDbgState->fClearCr0Mask)
11955 {
11956 pDbgState->fClearCr0Mask = false;
11957 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
11958 }
11959 if (pDbgState->fClearCr4Mask)
11960 {
11961 pDbgState->fClearCr4Mask = false;
11962 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR4);
11963 }
11964 }
11965 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
11966 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
11967
11968 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
11969 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
11970 {
11971 /** @todo later, need to fix handler as it assumes this won't usually happen. */
11972 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
11973 }
11974 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
11975 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
11976
11977 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS); /* risky clearing this? */
11978 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
11979 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS);
11980 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
11981 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_PROC_CTLS_MWAIT_EXIT); /* paranoia */
11982 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
11983 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_PROC_CTLS_MONITOR_EXIT); /* paranoia */
11984 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
11985#if 0 /** @todo too slow, fix handler. */
11986 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_PROC_CTLS_PAUSE_EXIT);
11987#endif
11988 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
11989
11990 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
11991 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
11992 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
11993 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
11994 {
11995 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11996 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_GDTR_IDTR_ACCESS);
11997 }
11998 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11999 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
12000 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
12001 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
12002
12003 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
12004 || IS_EITHER_ENABLED(pVM, INSTR_STR)
12005 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
12006 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
12007 {
12008 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
12009 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_LDTR_TR_ACCESS);
12010 }
12011 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_LDTR_TR_ACCESS);
12012 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_LDTR_TR_ACCESS);
12013 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_LDTR_TR_ACCESS);
12014 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_LDTR_TR_ACCESS);
12015
12016 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
12017 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
12018 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_PROC_CTLS_RDTSC_EXIT);
12019 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
12020 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
12021 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
12022 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_PROC_CTLS2_WBINVD_EXIT);
12023 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
12024 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
12025 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
12026 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_PROC_CTLS2_RDRAND_EXIT);
12027 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
12028 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_PROC_CTLS_INVLPG_EXIT);
12029 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
12030 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
12031 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
12032 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_PROC_CTLS2_RDSEED_EXIT);
12033 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
12034 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
12035 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
12036 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
12037 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
12038
12039#undef IS_EITHER_ENABLED
12040#undef SET_ONLY_XBM_IF_EITHER_EN
12041#undef SET_CPE1_XBM_IF_EITHER_EN
12042#undef SET_CPEU_XBM_IF_EITHER_EN
12043#undef SET_CPE2_XBM_IF_EITHER_EN
12044
12045 /*
12046 * Sanitize the control stuff.
12047 */
12048 pDbgState->fCpe2Extra &= g_HmMsrs.u.vmx.ProcCtls2.n.allowed1;
12049 if (pDbgState->fCpe2Extra)
12050 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
12051 pDbgState->fCpe1Extra &= g_HmMsrs.u.vmx.ProcCtls.n.allowed1;
12052 pDbgState->fCpe1Unwanted &= ~g_HmMsrs.u.vmx.ProcCtls.n.allowed0;
12053 if (pVCpu->hmr0.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_PROC_CTLS_RDTSC_EXIT))
12054 {
12055 pVCpu->hmr0.s.fDebugWantRdTscExit ^= true;
12056 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
12057 }
12058
12059 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
12060 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
12061 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
12062 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
12063}
12064
12065
12066/**
12067 * Fires off DBGF events and dtrace probes for a VM-exit, when it's
12068 * appropriate.
12069 *
12070 * The caller has checked the VM-exit against the
12071 * VMXRUNDBGSTATE::bmExitsToCheck bitmap. The caller has checked for NMIs
12072 * already, so we don't have to do that either.
12073 *
12074 * @returns Strict VBox status code (i.e. informational status codes too).
12075 * @param pVCpu The cross context virtual CPU structure.
12076 * @param pVmxTransient The VMX-transient structure.
12077 * @param uExitReason The VM-exit reason.
12078 *
12079 * @remarks The name of this function is displayed by dtrace, so keep it short
12080 * and to the point. No longer than 33 chars long, please.
12081 */
12082static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
12083{
12084 /*
12085 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
12086 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
12087 *
12088 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
12089 * does. Must add/change/remove both places. Same ordering, please.
12090 *
12091 * Added/removed events must also be reflected in the next section
12092 * where we dispatch dtrace events.
12093 */
12094 bool fDtrace1 = false;
12095 bool fDtrace2 = false;
12096 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
12097 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
12098 uint32_t uEventArg = 0;
12099#define SET_EXIT(a_EventSubName) \
12100 do { \
12101 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
12102 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
12103 } while (0)
12104#define SET_BOTH(a_EventSubName) \
12105 do { \
12106 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
12107 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
12108 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
12109 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
12110 } while (0)
12111 switch (uExitReason)
12112 {
12113 case VMX_EXIT_MTF:
12114 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
12115
12116 case VMX_EXIT_XCPT_OR_NMI:
12117 {
12118 uint8_t const idxVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
12119 switch (VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo))
12120 {
12121 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
12122 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
12123 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
12124 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
12125 {
12126 if (VMX_EXIT_INT_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uExitIntInfo))
12127 {
12128 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
12129 uEventArg = pVmxTransient->uExitIntErrorCode;
12130 }
12131 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
12132 switch (enmEvent1)
12133 {
12134 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
12135 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
12136 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
12137 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
12138 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
12139 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
12140 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
12141 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
12142 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
12143 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
12144 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
12145 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
12146 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
12147 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
12148 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
12149 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
12150 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
12151 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
12152 default: break;
12153 }
12154 }
12155 else
12156 AssertFailed();
12157 break;
12158
12159 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
12160 uEventArg = idxVector;
12161 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
12162 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
12163 break;
12164 }
12165 break;
12166 }
12167
12168 case VMX_EXIT_TRIPLE_FAULT:
12169 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
12170 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
12171 break;
12172 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
12173 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
12174 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
12175 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
12176 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
12177
12178 /* Instruction specific VM-exits: */
12179 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
12180 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
12181 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
12182 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
12183 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
12184 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
12185 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
12186 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
12187 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
12188 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
12189 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
12190 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
12191 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
12192 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
12193 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
12194 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
12195 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
12196 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
12197 case VMX_EXIT_MOV_CRX:
12198 hmR0VmxReadExitQualVmcs(pVmxTransient);
12199 if (VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_CRX_ACCESS_READ)
12200 SET_BOTH(CRX_READ);
12201 else
12202 SET_BOTH(CRX_WRITE);
12203 uEventArg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
12204 break;
12205 case VMX_EXIT_MOV_DRX:
12206 hmR0VmxReadExitQualVmcs(pVmxTransient);
12207 if ( VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual)
12208 == VMX_EXIT_QUAL_DRX_DIRECTION_READ)
12209 SET_BOTH(DRX_READ);
12210 else
12211 SET_BOTH(DRX_WRITE);
12212 uEventArg = VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual);
12213 break;
12214 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
12215 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
12216 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
12217 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
12218 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
12219 case VMX_EXIT_GDTR_IDTR_ACCESS:
12220 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
12221 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_XDTR_INSINFO_INSTR_ID))
12222 {
12223 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
12224 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
12225 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
12226 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
12227 }
12228 break;
12229
12230 case VMX_EXIT_LDTR_TR_ACCESS:
12231 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
12232 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_YYTR_INSINFO_INSTR_ID))
12233 {
12234 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
12235 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
12236 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
12237 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
12238 }
12239 break;
12240
12241 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
12242 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
12243 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
12244 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
12245 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
12246 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
12247 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
12248 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
12249 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
12250 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
12251 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
12252
12253 /* Events that aren't relevant at this point. */
12254 case VMX_EXIT_EXT_INT:
12255 case VMX_EXIT_INT_WINDOW:
12256 case VMX_EXIT_NMI_WINDOW:
12257 case VMX_EXIT_TPR_BELOW_THRESHOLD:
12258 case VMX_EXIT_PREEMPT_TIMER:
12259 case VMX_EXIT_IO_INSTR:
12260 break;
12261
12262 /* Errors and unexpected events. */
12263 case VMX_EXIT_INIT_SIGNAL:
12264 case VMX_EXIT_SIPI:
12265 case VMX_EXIT_IO_SMI:
12266 case VMX_EXIT_SMI:
12267 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
12268 case VMX_EXIT_ERR_MSR_LOAD:
12269 case VMX_EXIT_ERR_MACHINE_CHECK:
12270 case VMX_EXIT_PML_FULL:
12271 case VMX_EXIT_VIRTUALIZED_EOI:
12272 break;
12273
12274 default:
12275 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
12276 break;
12277 }
12278#undef SET_BOTH
12279#undef SET_EXIT
12280
12281 /*
12282 * Dtrace tracepoints go first. We do them here at once so we don't
12283 * have to copy the guest state saving and stuff a few dozen times.
12284 * Down side is that we've got to repeat the switch, though this time
12285 * we use enmEvent since the probes are a subset of what DBGF does.
12286 */
12287 if (fDtrace1 || fDtrace2)
12288 {
12289 hmR0VmxReadExitQualVmcs(pVmxTransient);
12290 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12291 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
12292 switch (enmEvent1)
12293 {
12294 /** @todo consider which extra parameters would be helpful for each probe. */
12295 case DBGFEVENT_END: break;
12296 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pCtx); break;
12297 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pCtx, pCtx->dr[6]); break;
12298 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pCtx); break;
12299 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pCtx); break;
12300 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pCtx); break;
12301 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pCtx); break;
12302 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pCtx); break;
12303 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pCtx); break;
12304 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pCtx, uEventArg); break;
12305 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pCtx, uEventArg); break;
12306 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pCtx, uEventArg); break;
12307 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pCtx, uEventArg); break;
12308 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pCtx, uEventArg, pCtx->cr2); break;
12309 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pCtx); break;
12310 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pCtx); break;
12311 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pCtx); break;
12312 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pCtx); break;
12313 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pCtx, uEventArg); break;
12314 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pCtx, (uint8_t)uEventArg); break;
12315 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
12316 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pCtx); break;
12317 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pCtx); break;
12318 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pCtx); break;
12319 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pCtx); break;
12320 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pCtx); break;
12321 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pCtx); break;
12322 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pCtx); break;
12323 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
12324 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
12325 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
12326 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
12327 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
12328 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pCtx, pCtx->ecx,
12329 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
12330 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pCtx); break;
12331 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pCtx); break;
12332 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pCtx); break;
12333 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pCtx); break;
12334 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pCtx); break;
12335 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pCtx); break;
12336 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pCtx); break;
12337 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pCtx); break;
12338 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pCtx); break;
12339 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pCtx); break;
12340 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pCtx); break;
12341 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pCtx); break;
12342 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pCtx); break;
12343 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pCtx); break;
12344 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pCtx); break;
12345 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pCtx); break;
12346 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pCtx); break;
12347 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pCtx); break;
12348 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pCtx); break;
12349 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pCtx); break;
12350 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pCtx); break;
12351 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pCtx); break;
12352 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pCtx); break;
12353 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pCtx); break;
12354 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pCtx); break;
12355 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pCtx); break;
12356 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pCtx); break;
12357 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pCtx); break;
12358 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pCtx); break;
12359 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pCtx); break;
12360 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pCtx); break;
12361 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pCtx); break;
12362 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
12363 }
12364 switch (enmEvent2)
12365 {
12366 /** @todo consider which extra parameters would be helpful for each probe. */
12367 case DBGFEVENT_END: break;
12368 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pCtx); break;
12369 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
12370 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pCtx); break;
12371 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pCtx); break;
12372 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pCtx); break;
12373 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pCtx); break;
12374 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pCtx); break;
12375 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pCtx); break;
12376 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pCtx); break;
12377 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
12378 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
12379 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
12380 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
12381 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
12382 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pCtx, pCtx->ecx,
12383 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
12384 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pCtx); break;
12385 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pCtx); break;
12386 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pCtx); break;
12387 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pCtx); break;
12388 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pCtx); break;
12389 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pCtx); break;
12390 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pCtx); break;
12391 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pCtx); break;
12392 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pCtx); break;
12393 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pCtx); break;
12394 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pCtx); break;
12395 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pCtx); break;
12396 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pCtx); break;
12397 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pCtx); break;
12398 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pCtx); break;
12399 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pCtx); break;
12400 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pCtx); break;
12401 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pCtx); break;
12402 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pCtx); break;
12403 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pCtx); break;
12404 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pCtx); break;
12405 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pCtx); break;
12406 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pCtx); break;
12407 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pCtx); break;
12408 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pCtx); break;
12409 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pCtx); break;
12410 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pCtx); break;
12411 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pCtx); break;
12412 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pCtx); break;
12413 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pCtx); break;
12414 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pCtx); break;
12415 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pCtx); break;
12416 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pCtx); break;
12417 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pCtx); break;
12418 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pCtx); break;
12419 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pCtx); break;
12420 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
12421 }
12422 }
12423
12424 /*
12425 * Fire of the DBGF event, if enabled (our check here is just a quick one,
12426 * the DBGF call will do a full check).
12427 *
12428 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
12429 * Note! If we have to events, we prioritize the first, i.e. the instruction
12430 * one, in order to avoid event nesting.
12431 */
12432 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
12433 if ( enmEvent1 != DBGFEVENT_END
12434 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
12435 {
12436 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12437 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent1, DBGFEVENTCTX_HM, 1, uEventArg);
12438 if (rcStrict != VINF_SUCCESS)
12439 return rcStrict;
12440 }
12441 else if ( enmEvent2 != DBGFEVENT_END
12442 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
12443 {
12444 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12445 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent2, DBGFEVENTCTX_HM, 1, uEventArg);
12446 if (rcStrict != VINF_SUCCESS)
12447 return rcStrict;
12448 }
12449
12450 return VINF_SUCCESS;
12451}
12452
12453
12454/**
12455 * Single-stepping VM-exit filtering.
12456 *
12457 * This is preprocessing the VM-exits and deciding whether we've gotten far
12458 * enough to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit
12459 * handling is performed.
12460 *
12461 * @returns Strict VBox status code (i.e. informational status codes too).
12462 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
12463 * @param pVmxTransient The VMX-transient structure.
12464 * @param pDbgState The debug state.
12465 */
12466DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
12467{
12468 /*
12469 * Expensive (saves context) generic dtrace VM-exit probe.
12470 */
12471 uint32_t const uExitReason = pVmxTransient->uExitReason;
12472 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
12473 { /* more likely */ }
12474 else
12475 {
12476 hmR0VmxReadExitQualVmcs(pVmxTransient);
12477 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12478 AssertRC(rc);
12479 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, &pVCpu->cpum.GstCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
12480 }
12481
12482 /*
12483 * Check for host NMI, just to get that out of the way.
12484 */
12485 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
12486 { /* normally likely */ }
12487 else
12488 {
12489 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
12490 uint32_t const uIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
12491 if (uIntType == VMX_EXIT_INT_INFO_TYPE_NMI)
12492 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
12493 }
12494
12495 /*
12496 * Check for single stepping event if we're stepping.
12497 */
12498 if (pVCpu->hm.s.fSingleInstruction)
12499 {
12500 switch (uExitReason)
12501 {
12502 case VMX_EXIT_MTF:
12503 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
12504
12505 /* Various events: */
12506 case VMX_EXIT_XCPT_OR_NMI:
12507 case VMX_EXIT_EXT_INT:
12508 case VMX_EXIT_TRIPLE_FAULT:
12509 case VMX_EXIT_INT_WINDOW:
12510 case VMX_EXIT_NMI_WINDOW:
12511 case VMX_EXIT_TASK_SWITCH:
12512 case VMX_EXIT_TPR_BELOW_THRESHOLD:
12513 case VMX_EXIT_APIC_ACCESS:
12514 case VMX_EXIT_EPT_VIOLATION:
12515 case VMX_EXIT_EPT_MISCONFIG:
12516 case VMX_EXIT_PREEMPT_TIMER:
12517
12518 /* Instruction specific VM-exits: */
12519 case VMX_EXIT_CPUID:
12520 case VMX_EXIT_GETSEC:
12521 case VMX_EXIT_HLT:
12522 case VMX_EXIT_INVD:
12523 case VMX_EXIT_INVLPG:
12524 case VMX_EXIT_RDPMC:
12525 case VMX_EXIT_RDTSC:
12526 case VMX_EXIT_RSM:
12527 case VMX_EXIT_VMCALL:
12528 case VMX_EXIT_VMCLEAR:
12529 case VMX_EXIT_VMLAUNCH:
12530 case VMX_EXIT_VMPTRLD:
12531 case VMX_EXIT_VMPTRST:
12532 case VMX_EXIT_VMREAD:
12533 case VMX_EXIT_VMRESUME:
12534 case VMX_EXIT_VMWRITE:
12535 case VMX_EXIT_VMXOFF:
12536 case VMX_EXIT_VMXON:
12537 case VMX_EXIT_MOV_CRX:
12538 case VMX_EXIT_MOV_DRX:
12539 case VMX_EXIT_IO_INSTR:
12540 case VMX_EXIT_RDMSR:
12541 case VMX_EXIT_WRMSR:
12542 case VMX_EXIT_MWAIT:
12543 case VMX_EXIT_MONITOR:
12544 case VMX_EXIT_PAUSE:
12545 case VMX_EXIT_GDTR_IDTR_ACCESS:
12546 case VMX_EXIT_LDTR_TR_ACCESS:
12547 case VMX_EXIT_INVEPT:
12548 case VMX_EXIT_RDTSCP:
12549 case VMX_EXIT_INVVPID:
12550 case VMX_EXIT_WBINVD:
12551 case VMX_EXIT_XSETBV:
12552 case VMX_EXIT_RDRAND:
12553 case VMX_EXIT_INVPCID:
12554 case VMX_EXIT_VMFUNC:
12555 case VMX_EXIT_RDSEED:
12556 case VMX_EXIT_XSAVES:
12557 case VMX_EXIT_XRSTORS:
12558 {
12559 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12560 AssertRCReturn(rc, rc);
12561 if ( pVCpu->cpum.GstCtx.rip != pDbgState->uRipStart
12562 || pVCpu->cpum.GstCtx.cs.Sel != pDbgState->uCsStart)
12563 return VINF_EM_DBG_STEPPED;
12564 break;
12565 }
12566
12567 /* Errors and unexpected events: */
12568 case VMX_EXIT_INIT_SIGNAL:
12569 case VMX_EXIT_SIPI:
12570 case VMX_EXIT_IO_SMI:
12571 case VMX_EXIT_SMI:
12572 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
12573 case VMX_EXIT_ERR_MSR_LOAD:
12574 case VMX_EXIT_ERR_MACHINE_CHECK:
12575 case VMX_EXIT_PML_FULL:
12576 case VMX_EXIT_VIRTUALIZED_EOI:
12577 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
12578 break;
12579
12580 default:
12581 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
12582 break;
12583 }
12584 }
12585
12586 /*
12587 * Check for debugger event breakpoints and dtrace probes.
12588 */
12589 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
12590 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
12591 {
12592 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVCpu, pVmxTransient, uExitReason);
12593 if (rcStrict != VINF_SUCCESS)
12594 return rcStrict;
12595 }
12596
12597 /*
12598 * Normal processing.
12599 */
12600#ifdef HMVMX_USE_FUNCTION_TABLE
12601 return g_aVMExitHandlers[uExitReason].pfn(pVCpu, pVmxTransient);
12602#else
12603 return hmR0VmxHandleExit(pVCpu, pVmxTransient, uExitReason);
12604#endif
12605}
12606
12607
12608/**
12609 * Single steps guest code using hardware-assisted VMX.
12610 *
12611 * This is -not- the same as the guest single-stepping itself (say using EFLAGS.TF)
12612 * but single-stepping through the hypervisor debugger.
12613 *
12614 * @returns Strict VBox status code (i.e. informational status codes too).
12615 * @param pVCpu The cross context virtual CPU structure.
12616 * @param pcLoops Pointer to the number of executed loops.
12617 *
12618 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
12619 */
12620static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVMCPUCC pVCpu, uint32_t *pcLoops)
12621{
12622 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hmr0.s.cMaxResumeLoops;
12623 Assert(pcLoops);
12624 Assert(*pcLoops <= cMaxResumeLoops);
12625
12626 VMXTRANSIENT VmxTransient;
12627 RT_ZERO(VmxTransient);
12628 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
12629
12630 /* Set HMCPU indicators. */
12631 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
12632 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
12633 pVCpu->hmr0.s.fDebugWantRdTscExit = false;
12634 pVCpu->hmr0.s.fUsingDebugLoop = true;
12635
12636 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
12637 VMXRUNDBGSTATE DbgState;
12638 hmR0VmxRunDebugStateInit(pVCpu, &VmxTransient, &DbgState);
12639 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12640
12641 /*
12642 * The loop.
12643 */
12644 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
12645 for (;;)
12646 {
12647 Assert(!HMR0SuspendPending());
12648 HMVMX_ASSERT_CPU_SAFE(pVCpu);
12649 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
12650 bool fStepping = pVCpu->hm.s.fSingleInstruction;
12651
12652 /* Set up VM-execution controls the next two can respond to. */
12653 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12654
12655 /*
12656 * Preparatory work for running guest code, this may force us to
12657 * return to ring-3.
12658 *
12659 * Warning! This bugger disables interrupts on VINF_SUCCESS!
12660 */
12661 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, fStepping);
12662 if (rcStrict != VINF_SUCCESS)
12663 break;
12664
12665 /* Interrupts are disabled at this point! */
12666 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
12667
12668 /* Override any obnoxious code in the above two calls. */
12669 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12670
12671 /*
12672 * Finally execute the guest.
12673 */
12674 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
12675
12676 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
12677 /* Interrupts are re-enabled at this point! */
12678
12679 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
12680 if (RT_SUCCESS(rcRun))
12681 { /* very likely */ }
12682 else
12683 {
12684 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
12685 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
12686 return rcRun;
12687 }
12688
12689 /* Profile the VM-exit. */
12690 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
12691 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
12692 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
12693 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
12694 HMVMX_START_EXIT_DISPATCH_PROF();
12695
12696 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
12697
12698 /*
12699 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
12700 */
12701 rcStrict = hmR0VmxRunDebugHandleExit(pVCpu, &VmxTransient, &DbgState);
12702 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
12703 if (rcStrict != VINF_SUCCESS)
12704 break;
12705 if (++(*pcLoops) > cMaxResumeLoops)
12706 {
12707 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
12708 rcStrict = VINF_EM_RAW_INTERRUPT;
12709 break;
12710 }
12711
12712 /*
12713 * Stepping: Did the RIP change, if so, consider it a single step.
12714 * Otherwise, make sure one of the TFs gets set.
12715 */
12716 if (fStepping)
12717 {
12718 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12719 AssertRC(rc);
12720 if ( pVCpu->cpum.GstCtx.rip != DbgState.uRipStart
12721 || pVCpu->cpum.GstCtx.cs.Sel != DbgState.uCsStart)
12722 {
12723 rcStrict = VINF_EM_DBG_STEPPED;
12724 break;
12725 }
12726 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
12727 }
12728
12729 /*
12730 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
12731 */
12732 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
12733 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12734
12735 /* Restore all controls applied by hmR0VmxPreRunGuestDebugStateApply above. */
12736 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &VmxTransient, &DbgState, rcStrict);
12737 Assert(rcStrict == VINF_SUCCESS);
12738 }
12739
12740 /*
12741 * Clear the X86_EFL_TF if necessary.
12742 */
12743 if (pVCpu->hmr0.s.fClearTrapFlag)
12744 {
12745 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
12746 AssertRC(rc);
12747 pVCpu->hmr0.s.fClearTrapFlag = false;
12748 pVCpu->cpum.GstCtx.eflags.Bits.u1TF = 0;
12749 }
12750 /** @todo there seems to be issues with the resume flag when the monitor trap
12751 * flag is pending without being used. Seen early in bios init when
12752 * accessing APIC page in protected mode. */
12753
12754 /* Restore HMCPU indicators. */
12755 pVCpu->hmr0.s.fUsingDebugLoop = false;
12756 pVCpu->hmr0.s.fDebugWantRdTscExit = false;
12757 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
12758
12759 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
12760 return rcStrict;
12761}
12762
12763
12764/** @} */
12765
12766
12767/**
12768 * Checks if any expensive dtrace probes are enabled and we should go to the
12769 * debug loop.
12770 *
12771 * @returns true if we should use debug loop, false if not.
12772 */
12773static bool hmR0VmxAnyExpensiveProbesEnabled(void)
12774{
12775 /* It's probably faster to OR the raw 32-bit counter variables together.
12776 Since the variables are in an array and the probes are next to one
12777 another (more or less), we have good locality. So, better read
12778 eight-nine cache lines ever time and only have one conditional, than
12779 128+ conditionals, right? */
12780 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
12781 | VBOXVMM_XCPT_DE_ENABLED_RAW()
12782 | VBOXVMM_XCPT_DB_ENABLED_RAW()
12783 | VBOXVMM_XCPT_BP_ENABLED_RAW()
12784 | VBOXVMM_XCPT_OF_ENABLED_RAW()
12785 | VBOXVMM_XCPT_BR_ENABLED_RAW()
12786 | VBOXVMM_XCPT_UD_ENABLED_RAW()
12787 | VBOXVMM_XCPT_NM_ENABLED_RAW()
12788 | VBOXVMM_XCPT_DF_ENABLED_RAW()
12789 | VBOXVMM_XCPT_TS_ENABLED_RAW()
12790 | VBOXVMM_XCPT_NP_ENABLED_RAW()
12791 | VBOXVMM_XCPT_SS_ENABLED_RAW()
12792 | VBOXVMM_XCPT_GP_ENABLED_RAW()
12793 | VBOXVMM_XCPT_PF_ENABLED_RAW()
12794 | VBOXVMM_XCPT_MF_ENABLED_RAW()
12795 | VBOXVMM_XCPT_AC_ENABLED_RAW()
12796 | VBOXVMM_XCPT_XF_ENABLED_RAW()
12797 | VBOXVMM_XCPT_VE_ENABLED_RAW()
12798 | VBOXVMM_XCPT_SX_ENABLED_RAW()
12799 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
12800 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
12801 ) != 0
12802 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
12803 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
12804 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
12805 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
12806 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
12807 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
12808 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
12809 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
12810 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
12811 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
12812 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
12813 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
12814 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
12815 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
12816 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
12817 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
12818 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
12819 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
12820 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
12821 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
12822 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
12823 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
12824 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
12825 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
12826 | VBOXVMM_INSTR_STR_ENABLED_RAW()
12827 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
12828 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
12829 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
12830 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
12831 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
12832 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
12833 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
12834 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
12835 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
12836 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
12837 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
12838 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
12839 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
12840 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
12841 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
12842 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
12843 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
12844 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
12845 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
12846 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
12847 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
12848 ) != 0
12849 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
12850 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
12851 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
12852 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
12853 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
12854 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
12855 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
12856 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
12857 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
12858 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
12859 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
12860 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
12861 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
12862 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
12863 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
12864 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
12865 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
12866 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
12867 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
12868 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
12869 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
12870 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
12871 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
12872 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
12873 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
12874 | VBOXVMM_EXIT_STR_ENABLED_RAW()
12875 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
12876 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
12877 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
12878 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
12879 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
12880 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
12881 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
12882 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
12883 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
12884 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
12885 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
12886 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
12887 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
12888 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
12889 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
12890 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
12891 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
12892 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
12893 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
12894 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
12895 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
12896 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
12897 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
12898 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
12899 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
12900 ) != 0;
12901}
12902
12903
12904/**
12905 * Runs the guest using hardware-assisted VMX.
12906 *
12907 * @returns Strict VBox status code (i.e. informational status codes too).
12908 * @param pVCpu The cross context virtual CPU structure.
12909 */
12910VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVMCPUCC pVCpu)
12911{
12912 AssertPtr(pVCpu);
12913 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
12914 Assert(VMMRZCallRing3IsEnabled(pVCpu));
12915 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12916 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
12917
12918 VBOXSTRICTRC rcStrict;
12919 uint32_t cLoops = 0;
12920 for (;;)
12921 {
12922#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12923 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(pCtx);
12924#else
12925 NOREF(pCtx);
12926 bool const fInNestedGuestMode = false;
12927#endif
12928 if (!fInNestedGuestMode)
12929 {
12930 if ( !pVCpu->hm.s.fUseDebugLoop
12931 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
12932 && !DBGFIsStepping(pVCpu)
12933 && !pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
12934 rcStrict = hmR0VmxRunGuestCodeNormal(pVCpu, &cLoops);
12935 else
12936 rcStrict = hmR0VmxRunGuestCodeDebug(pVCpu, &cLoops);
12937 }
12938#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12939 else
12940 rcStrict = hmR0VmxRunGuestCodeNested(pVCpu, &cLoops);
12941
12942 if (rcStrict == VINF_VMX_VMLAUNCH_VMRESUME)
12943 {
12944 Assert(CPUMIsGuestInVmxNonRootMode(pCtx));
12945 continue;
12946 }
12947 if (rcStrict == VINF_VMX_VMEXIT)
12948 {
12949 Assert(!CPUMIsGuestInVmxNonRootMode(pCtx));
12950 continue;
12951 }
12952#endif
12953 break;
12954 }
12955
12956 int const rcLoop = VBOXSTRICTRC_VAL(rcStrict);
12957 switch (rcLoop)
12958 {
12959 case VERR_EM_INTERPRETER: rcStrict = VINF_EM_RAW_EMULATE_INSTR; break;
12960 case VINF_EM_RESET: rcStrict = VINF_EM_TRIPLE_FAULT; break;
12961 }
12962
12963 int rc2 = hmR0VmxExitToRing3(pVCpu, rcStrict);
12964 if (RT_FAILURE(rc2))
12965 {
12966 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
12967 rcStrict = rc2;
12968 }
12969 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12970 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
12971 return rcStrict;
12972}
12973
12974
12975#ifndef HMVMX_USE_FUNCTION_TABLE
12976/**
12977 * Handles a guest VM-exit from hardware-assisted VMX execution.
12978 *
12979 * @returns Strict VBox status code (i.e. informational status codes too).
12980 * @param pVCpu The cross context virtual CPU structure.
12981 * @param pVmxTransient The VMX-transient structure.
12982 */
12983DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12984{
12985#ifdef DEBUG_ramshankar
12986# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) \
12987 do { \
12988 if (a_fSave != 0) \
12989 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL); \
12990 VBOXSTRICTRC rcStrict = a_CallExpr; \
12991 if (a_fSave != 0) \
12992 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST); \
12993 return rcStrict; \
12994 } while (0)
12995#else
12996# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) return a_CallExpr
12997#endif
12998 uint32_t const uExitReason = pVmxTransient->uExitReason;
12999 switch (uExitReason)
13000 {
13001 case VMX_EXIT_EPT_MISCONFIG: VMEXIT_CALL_RET(0, hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient));
13002 case VMX_EXIT_EPT_VIOLATION: VMEXIT_CALL_RET(0, hmR0VmxExitEptViolation(pVCpu, pVmxTransient));
13003 case VMX_EXIT_IO_INSTR: VMEXIT_CALL_RET(0, hmR0VmxExitIoInstr(pVCpu, pVmxTransient));
13004 case VMX_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0VmxExitCpuid(pVCpu, pVmxTransient));
13005 case VMX_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0VmxExitRdtsc(pVCpu, pVmxTransient));
13006 case VMX_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0VmxExitRdtscp(pVCpu, pVmxTransient));
13007 case VMX_EXIT_APIC_ACCESS: VMEXIT_CALL_RET(0, hmR0VmxExitApicAccess(pVCpu, pVmxTransient));
13008 case VMX_EXIT_XCPT_OR_NMI: VMEXIT_CALL_RET(0, hmR0VmxExitXcptOrNmi(pVCpu, pVmxTransient));
13009 case VMX_EXIT_MOV_CRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovCRx(pVCpu, pVmxTransient));
13010 case VMX_EXIT_EXT_INT: VMEXIT_CALL_RET(0, hmR0VmxExitExtInt(pVCpu, pVmxTransient));
13011 case VMX_EXIT_INT_WINDOW: VMEXIT_CALL_RET(0, hmR0VmxExitIntWindow(pVCpu, pVmxTransient));
13012 case VMX_EXIT_TPR_BELOW_THRESHOLD: VMEXIT_CALL_RET(0, hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient));
13013 case VMX_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0VmxExitMwait(pVCpu, pVmxTransient));
13014 case VMX_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0VmxExitMonitor(pVCpu, pVmxTransient));
13015 case VMX_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0VmxExitTaskSwitch(pVCpu, pVmxTransient));
13016 case VMX_EXIT_PREEMPT_TIMER: VMEXIT_CALL_RET(0, hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient));
13017 case VMX_EXIT_RDMSR: VMEXIT_CALL_RET(0, hmR0VmxExitRdmsr(pVCpu, pVmxTransient));
13018 case VMX_EXIT_WRMSR: VMEXIT_CALL_RET(0, hmR0VmxExitWrmsr(pVCpu, pVmxTransient));
13019 case VMX_EXIT_VMCALL: VMEXIT_CALL_RET(0, hmR0VmxExitVmcall(pVCpu, pVmxTransient));
13020 case VMX_EXIT_MOV_DRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovDRx(pVCpu, pVmxTransient));
13021 case VMX_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0VmxExitHlt(pVCpu, pVmxTransient));
13022 case VMX_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0VmxExitInvd(pVCpu, pVmxTransient));
13023 case VMX_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0VmxExitInvlpg(pVCpu, pVmxTransient));
13024 case VMX_EXIT_MTF: VMEXIT_CALL_RET(0, hmR0VmxExitMtf(pVCpu, pVmxTransient));
13025 case VMX_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0VmxExitPause(pVCpu, pVmxTransient));
13026 case VMX_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0VmxExitWbinvd(pVCpu, pVmxTransient));
13027 case VMX_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0VmxExitXsetbv(pVCpu, pVmxTransient));
13028 case VMX_EXIT_INVPCID: VMEXIT_CALL_RET(0, hmR0VmxExitInvpcid(pVCpu, pVmxTransient));
13029 case VMX_EXIT_GETSEC: VMEXIT_CALL_RET(0, hmR0VmxExitGetsec(pVCpu, pVmxTransient));
13030 case VMX_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0VmxExitRdpmc(pVCpu, pVmxTransient));
13031#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13032 case VMX_EXIT_VMCLEAR: VMEXIT_CALL_RET(0, hmR0VmxExitVmclear(pVCpu, pVmxTransient));
13033 case VMX_EXIT_VMLAUNCH: VMEXIT_CALL_RET(0, hmR0VmxExitVmlaunch(pVCpu, pVmxTransient));
13034 case VMX_EXIT_VMPTRLD: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrld(pVCpu, pVmxTransient));
13035 case VMX_EXIT_VMPTRST: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrst(pVCpu, pVmxTransient));
13036 case VMX_EXIT_VMREAD: VMEXIT_CALL_RET(0, hmR0VmxExitVmread(pVCpu, pVmxTransient));
13037 case VMX_EXIT_VMRESUME: VMEXIT_CALL_RET(0, hmR0VmxExitVmwrite(pVCpu, pVmxTransient));
13038 case VMX_EXIT_VMWRITE: VMEXIT_CALL_RET(0, hmR0VmxExitVmresume(pVCpu, pVmxTransient));
13039 case VMX_EXIT_VMXOFF: VMEXIT_CALL_RET(0, hmR0VmxExitVmxoff(pVCpu, pVmxTransient));
13040 case VMX_EXIT_VMXON: VMEXIT_CALL_RET(0, hmR0VmxExitVmxon(pVCpu, pVmxTransient));
13041 case VMX_EXIT_INVVPID: VMEXIT_CALL_RET(0, hmR0VmxExitInvvpid(pVCpu, pVmxTransient));
13042 case VMX_EXIT_INVEPT: VMEXIT_CALL_RET(0, hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient));
13043#else
13044 case VMX_EXIT_VMCLEAR:
13045 case VMX_EXIT_VMLAUNCH:
13046 case VMX_EXIT_VMPTRLD:
13047 case VMX_EXIT_VMPTRST:
13048 case VMX_EXIT_VMREAD:
13049 case VMX_EXIT_VMRESUME:
13050 case VMX_EXIT_VMWRITE:
13051 case VMX_EXIT_VMXOFF:
13052 case VMX_EXIT_VMXON:
13053 case VMX_EXIT_INVVPID:
13054 case VMX_EXIT_INVEPT:
13055 return hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient);
13056#endif
13057
13058 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pVmxTransient);
13059 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pVmxTransient);
13060 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
13061
13062 case VMX_EXIT_INIT_SIGNAL:
13063 case VMX_EXIT_SIPI:
13064 case VMX_EXIT_IO_SMI:
13065 case VMX_EXIT_SMI:
13066 case VMX_EXIT_ERR_MSR_LOAD:
13067 case VMX_EXIT_ERR_MACHINE_CHECK:
13068 case VMX_EXIT_PML_FULL:
13069 case VMX_EXIT_VIRTUALIZED_EOI:
13070 case VMX_EXIT_GDTR_IDTR_ACCESS:
13071 case VMX_EXIT_LDTR_TR_ACCESS:
13072 case VMX_EXIT_APIC_WRITE:
13073 case VMX_EXIT_RDRAND:
13074 case VMX_EXIT_RSM:
13075 case VMX_EXIT_VMFUNC:
13076 case VMX_EXIT_ENCLS:
13077 case VMX_EXIT_RDSEED:
13078 case VMX_EXIT_XSAVES:
13079 case VMX_EXIT_XRSTORS:
13080 case VMX_EXIT_UMWAIT:
13081 case VMX_EXIT_TPAUSE:
13082 default:
13083 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
13084 }
13085#undef VMEXIT_CALL_RET
13086}
13087#endif /* !HMVMX_USE_FUNCTION_TABLE */
13088
13089
13090#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13091/**
13092 * Handles a nested-guest VM-exit from hardware-assisted VMX execution.
13093 *
13094 * @returns Strict VBox status code (i.e. informational status codes too).
13095 * @param pVCpu The cross context virtual CPU structure.
13096 * @param pVmxTransient The VMX-transient structure.
13097 */
13098DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13099{
13100 uint32_t const uExitReason = pVmxTransient->uExitReason;
13101 switch (uExitReason)
13102 {
13103 case VMX_EXIT_EPT_MISCONFIG: return hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient);
13104 case VMX_EXIT_EPT_VIOLATION: return hmR0VmxExitEptViolation(pVCpu, pVmxTransient);
13105 case VMX_EXIT_XCPT_OR_NMI: return hmR0VmxExitXcptOrNmiNested(pVCpu, pVmxTransient);
13106 case VMX_EXIT_IO_INSTR: return hmR0VmxExitIoInstrNested(pVCpu, pVmxTransient);
13107 case VMX_EXIT_HLT: return hmR0VmxExitHltNested(pVCpu, pVmxTransient);
13108
13109 /*
13110 * We shouldn't direct host physical interrupts to the nested-guest.
13111 */
13112 case VMX_EXIT_EXT_INT:
13113 return hmR0VmxExitExtInt(pVCpu, pVmxTransient);
13114
13115 /*
13116 * Instructions that cause VM-exits unconditionally or the condition is
13117 * always is taken solely from the nested hypervisor (meaning if the VM-exit
13118 * happens, it's guaranteed to be a nested-guest VM-exit).
13119 *
13120 * - Provides VM-exit instruction length ONLY.
13121 */
13122 case VMX_EXIT_CPUID: /* Unconditional. */
13123 case VMX_EXIT_VMCALL:
13124 case VMX_EXIT_GETSEC:
13125 case VMX_EXIT_INVD:
13126 case VMX_EXIT_XSETBV:
13127 case VMX_EXIT_VMLAUNCH:
13128 case VMX_EXIT_VMRESUME:
13129 case VMX_EXIT_VMXOFF:
13130 case VMX_EXIT_ENCLS: /* Condition specified solely by nested hypervisor. */
13131 case VMX_EXIT_VMFUNC:
13132 return hmR0VmxExitInstrNested(pVCpu, pVmxTransient);
13133
13134 /*
13135 * Instructions that cause VM-exits unconditionally or the condition is
13136 * always is taken solely from the nested hypervisor (meaning if the VM-exit
13137 * happens, it's guaranteed to be a nested-guest VM-exit).
13138 *
13139 * - Provides VM-exit instruction length.
13140 * - Provides VM-exit information.
13141 * - Optionally provides Exit qualification.
13142 *
13143 * Since Exit qualification is 0 for all VM-exits where it is not
13144 * applicable, reading and passing it to the guest should produce
13145 * defined behavior.
13146 *
13147 * See Intel spec. 27.2.1 "Basic VM-Exit Information".
13148 */
13149 case VMX_EXIT_INVEPT: /* Unconditional. */
13150 case VMX_EXIT_INVVPID:
13151 case VMX_EXIT_VMCLEAR:
13152 case VMX_EXIT_VMPTRLD:
13153 case VMX_EXIT_VMPTRST:
13154 case VMX_EXIT_VMXON:
13155 case VMX_EXIT_GDTR_IDTR_ACCESS: /* Condition specified solely by nested hypervisor. */
13156 case VMX_EXIT_LDTR_TR_ACCESS:
13157 case VMX_EXIT_RDRAND:
13158 case VMX_EXIT_RDSEED:
13159 case VMX_EXIT_XSAVES:
13160 case VMX_EXIT_XRSTORS:
13161 case VMX_EXIT_UMWAIT:
13162 case VMX_EXIT_TPAUSE:
13163 return hmR0VmxExitInstrWithInfoNested(pVCpu, pVmxTransient);
13164
13165 case VMX_EXIT_RDTSC: return hmR0VmxExitRdtscNested(pVCpu, pVmxTransient);
13166 case VMX_EXIT_RDTSCP: return hmR0VmxExitRdtscpNested(pVCpu, pVmxTransient);
13167 case VMX_EXIT_RDMSR: return hmR0VmxExitRdmsrNested(pVCpu, pVmxTransient);
13168 case VMX_EXIT_WRMSR: return hmR0VmxExitWrmsrNested(pVCpu, pVmxTransient);
13169 case VMX_EXIT_INVLPG: return hmR0VmxExitInvlpgNested(pVCpu, pVmxTransient);
13170 case VMX_EXIT_INVPCID: return hmR0VmxExitInvpcidNested(pVCpu, pVmxTransient);
13171 case VMX_EXIT_TASK_SWITCH: return hmR0VmxExitTaskSwitchNested(pVCpu, pVmxTransient);
13172 case VMX_EXIT_WBINVD: return hmR0VmxExitWbinvdNested(pVCpu, pVmxTransient);
13173 case VMX_EXIT_MTF: return hmR0VmxExitMtfNested(pVCpu, pVmxTransient);
13174 case VMX_EXIT_APIC_ACCESS: return hmR0VmxExitApicAccessNested(pVCpu, pVmxTransient);
13175 case VMX_EXIT_APIC_WRITE: return hmR0VmxExitApicWriteNested(pVCpu, pVmxTransient);
13176 case VMX_EXIT_VIRTUALIZED_EOI: return hmR0VmxExitVirtEoiNested(pVCpu, pVmxTransient);
13177 case VMX_EXIT_MOV_CRX: return hmR0VmxExitMovCRxNested(pVCpu, pVmxTransient);
13178 case VMX_EXIT_INT_WINDOW: return hmR0VmxExitIntWindowNested(pVCpu, pVmxTransient);
13179 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindowNested(pVCpu, pVmxTransient);
13180 case VMX_EXIT_TPR_BELOW_THRESHOLD: return hmR0VmxExitTprBelowThresholdNested(pVCpu, pVmxTransient);
13181 case VMX_EXIT_MWAIT: return hmR0VmxExitMwaitNested(pVCpu, pVmxTransient);
13182 case VMX_EXIT_MONITOR: return hmR0VmxExitMonitorNested(pVCpu, pVmxTransient);
13183 case VMX_EXIT_PAUSE: return hmR0VmxExitPauseNested(pVCpu, pVmxTransient);
13184
13185 case VMX_EXIT_PREEMPT_TIMER:
13186 {
13187 /** @todo NSTVMX: Preempt timer. */
13188 return hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient);
13189 }
13190
13191 case VMX_EXIT_MOV_DRX: return hmR0VmxExitMovDRxNested(pVCpu, pVmxTransient);
13192 case VMX_EXIT_RDPMC: return hmR0VmxExitRdpmcNested(pVCpu, pVmxTransient);
13193
13194 case VMX_EXIT_VMREAD:
13195 case VMX_EXIT_VMWRITE: return hmR0VmxExitVmreadVmwriteNested(pVCpu, pVmxTransient);
13196
13197 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFaultNested(pVCpu, pVmxTransient);
13198 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestStateNested(pVCpu, pVmxTransient);
13199
13200 case VMX_EXIT_INIT_SIGNAL:
13201 case VMX_EXIT_SIPI:
13202 case VMX_EXIT_IO_SMI:
13203 case VMX_EXIT_SMI:
13204 case VMX_EXIT_ERR_MSR_LOAD:
13205 case VMX_EXIT_ERR_MACHINE_CHECK:
13206 case VMX_EXIT_PML_FULL:
13207 case VMX_EXIT_RSM:
13208 default:
13209 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
13210 }
13211}
13212#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13213
13214
13215/** @name VM-exit helpers.
13216 * @{
13217 */
13218/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13219/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= VM-exit helpers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
13220/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13221
13222/** Macro for VM-exits called unexpectedly. */
13223#define HMVMX_UNEXPECTED_EXIT_RET(a_pVCpu, a_HmError) \
13224 do { \
13225 (a_pVCpu)->hm.s.u32HMError = (a_HmError); \
13226 return VERR_VMX_UNEXPECTED_EXIT; \
13227 } while (0)
13228
13229#ifdef VBOX_STRICT
13230/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
13231# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
13232 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
13233
13234# define HMVMX_ASSERT_PREEMPT_CPUID() \
13235 do { \
13236 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
13237 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
13238 } while (0)
13239
13240# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
13241 do { \
13242 AssertPtr((a_pVCpu)); \
13243 AssertPtr((a_pVmxTransient)); \
13244 Assert((a_pVmxTransient)->fVMEntryFailed == false); \
13245 Assert((a_pVmxTransient)->pVmcsInfo); \
13246 Assert(ASMIntAreEnabled()); \
13247 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
13248 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
13249 Log4Func(("vcpu[%RU32]\n", (a_pVCpu)->idCpu)); \
13250 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
13251 if (!VMMRZCallRing3IsEnabled((a_pVCpu))) \
13252 HMVMX_ASSERT_PREEMPT_CPUID(); \
13253 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
13254 } while (0)
13255
13256# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
13257 do { \
13258 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); \
13259 Assert((a_pVmxTransient)->fIsNestedGuest); \
13260 } while (0)
13261
13262# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
13263 do { \
13264 Log4Func(("\n")); \
13265 } while (0)
13266#else
13267# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
13268 do { \
13269 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
13270 NOREF((a_pVCpu)); NOREF((a_pVmxTransient)); \
13271 } while (0)
13272
13273# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
13274 do { HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); } while (0)
13275
13276# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) do { } while (0)
13277#endif
13278
13279#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13280/** Macro that does the necessary privilege checks and intercepted VM-exits for
13281 * guests that attempted to execute a VMX instruction. */
13282# define HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(a_pVCpu, a_uExitReason) \
13283 do \
13284 { \
13285 VBOXSTRICTRC rcStrictTmp = hmR0VmxCheckExitDueToVmxInstr((a_pVCpu), (a_uExitReason)); \
13286 if (rcStrictTmp == VINF_SUCCESS) \
13287 { /* likely */ } \
13288 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
13289 { \
13290 Assert((a_pVCpu)->hm.s.Event.fPending); \
13291 Log4Func(("Privilege checks failed -> %#x\n", VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo))); \
13292 return VINF_SUCCESS; \
13293 } \
13294 else \
13295 { \
13296 int rcTmp = VBOXSTRICTRC_VAL(rcStrictTmp); \
13297 AssertMsgFailedReturn(("Unexpected failure. rc=%Rrc", rcTmp), rcTmp); \
13298 } \
13299 } while (0)
13300
13301/** Macro that decodes a memory operand for an VM-exit caused by an instruction. */
13302# define HMVMX_DECODE_MEM_OPERAND(a_pVCpu, a_uExitInstrInfo, a_uExitQual, a_enmMemAccess, a_pGCPtrEffAddr) \
13303 do \
13304 { \
13305 VBOXSTRICTRC rcStrictTmp = hmR0VmxDecodeMemOperand((a_pVCpu), (a_uExitInstrInfo), (a_uExitQual), (a_enmMemAccess), \
13306 (a_pGCPtrEffAddr)); \
13307 if (rcStrictTmp == VINF_SUCCESS) \
13308 { /* likely */ } \
13309 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
13310 { \
13311 uint8_t const uXcptTmp = VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo); \
13312 Log4Func(("Memory operand decoding failed, raising xcpt %#x\n", uXcptTmp)); \
13313 NOREF(uXcptTmp); \
13314 return VINF_SUCCESS; \
13315 } \
13316 else \
13317 { \
13318 Log4Func(("hmR0VmxDecodeMemOperand failed. rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrictTmp))); \
13319 return rcStrictTmp; \
13320 } \
13321 } while (0)
13322#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13323
13324
13325/**
13326 * Advances the guest RIP by the specified number of bytes.
13327 *
13328 * @param pVCpu The cross context virtual CPU structure.
13329 * @param cbInstr Number of bytes to advance the RIP by.
13330 *
13331 * @remarks No-long-jump zone!!!
13332 */
13333DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPUCC pVCpu, uint32_t cbInstr)
13334{
13335 /* Advance the RIP. */
13336 pVCpu->cpum.GstCtx.rip += cbInstr;
13337 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
13338
13339 /* Update interrupt inhibition. */
13340 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
13341 && pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
13342 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
13343}
13344
13345
13346/**
13347 * Advances the guest RIP after reading it from the VMCS.
13348 *
13349 * @returns VBox status code, no informational status codes.
13350 * @param pVCpu The cross context virtual CPU structure.
13351 * @param pVmxTransient The VMX-transient structure.
13352 *
13353 * @remarks No-long-jump zone!!!
13354 */
13355static int hmR0VmxAdvanceGuestRip(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13356{
13357 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
13358 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
13359 AssertRCReturn(rc, rc);
13360
13361 hmR0VmxAdvanceGuestRipBy(pVCpu, pVmxTransient->cbExitInstr);
13362 return VINF_SUCCESS;
13363}
13364
13365
13366/**
13367 * Handle a condition that occurred while delivering an event through the guest or
13368 * nested-guest IDT.
13369 *
13370 * @returns Strict VBox status code (i.e. informational status codes too).
13371 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
13372 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
13373 * to continue execution of the guest which will delivery the \#DF.
13374 * @retval VINF_EM_RESET if we detected a triple-fault condition.
13375 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
13376 *
13377 * @param pVCpu The cross context virtual CPU structure.
13378 * @param pVmxTransient The VMX-transient structure.
13379 *
13380 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13381 * Additionally, HMVMX_READ_EXIT_QUALIFICATION is required if the VM-exit
13382 * is due to an EPT violation, PML full or SPP-related event.
13383 *
13384 * @remarks No-long-jump zone!!!
13385 */
13386static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13387{
13388 Assert(!pVCpu->hm.s.Event.fPending);
13389 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
13390 if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
13391 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
13392 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
13393 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_EXIT_QUALIFICATION);
13394
13395 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
13396 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13397 uint32_t const uIdtVectorInfo = pVmxTransient->uIdtVectoringInfo;
13398 uint32_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
13399 if (VMX_IDT_VECTORING_INFO_IS_VALID(uIdtVectorInfo))
13400 {
13401 uint32_t const uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(uIdtVectorInfo);
13402 uint32_t const uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(uIdtVectorInfo);
13403
13404 /*
13405 * If the event was a software interrupt (generated with INT n) or a software exception
13406 * (generated by INT3/INTO) or a privileged software exception (generated by INT1), we
13407 * can handle the VM-exit and continue guest execution which will re-execute the
13408 * instruction rather than re-injecting the exception, as that can cause premature
13409 * trips to ring-3 before injection and involve TRPM which currently has no way of
13410 * storing that these exceptions were caused by these instructions (ICEBP's #DB poses
13411 * the problem).
13412 */
13413 IEMXCPTRAISE enmRaise;
13414 IEMXCPTRAISEINFO fRaiseInfo;
13415 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
13416 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
13417 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
13418 {
13419 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
13420 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
13421 }
13422 else if (VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo))
13423 {
13424 uint32_t const uExitVectorType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
13425 uint8_t const uExitVector = VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo);
13426 Assert(uExitVectorType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT);
13427
13428 uint32_t const fIdtVectorFlags = hmR0VmxGetIemXcptFlags(uIdtVector, uIdtVectorType);
13429 uint32_t const fExitVectorFlags = hmR0VmxGetIemXcptFlags(uExitVector, uExitVectorType);
13430
13431 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
13432
13433 /* Determine a vectoring #PF condition, see comment in hmR0VmxExitXcptPF(). */
13434 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
13435 {
13436 pVmxTransient->fVectoringPF = true;
13437 enmRaise = IEMXCPTRAISE_PREV_EVENT;
13438 }
13439 }
13440 else
13441 {
13442 /*
13443 * If an exception or hardware interrupt delivery caused an EPT violation/misconfig or APIC access
13444 * VM-exit, then the VM-exit interruption-information will not be valid and we end up here.
13445 * It is sufficient to reflect the original event to the guest after handling the VM-exit.
13446 */
13447 Assert( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
13448 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
13449 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT);
13450 enmRaise = IEMXCPTRAISE_PREV_EVENT;
13451 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
13452 }
13453
13454 /*
13455 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig
13456 * etc.) occurred while delivering the NMI, we need to clear the block-by-NMI field in the guest
13457 * interruptibility-state before re-delivering the NMI after handling the VM-exit. Otherwise the
13458 * subsequent VM-entry would fail, see @bugref{7445}.
13459 *
13460 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception".
13461 */
13462 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
13463 && enmRaise == IEMXCPTRAISE_PREV_EVENT
13464 && (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
13465 && CPUMIsGuestNmiBlocking(pVCpu))
13466 {
13467 CPUMSetGuestNmiBlocking(pVCpu, false);
13468 }
13469
13470 switch (enmRaise)
13471 {
13472 case IEMXCPTRAISE_CURRENT_XCPT:
13473 {
13474 Log4Func(("IDT: Pending secondary Xcpt: idtinfo=%#RX64 exitinfo=%#RX64\n", uIdtVectorInfo, uExitIntInfo));
13475 Assert(rcStrict == VINF_SUCCESS);
13476 break;
13477 }
13478
13479 case IEMXCPTRAISE_PREV_EVENT:
13480 {
13481 uint32_t u32ErrCode;
13482 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(uIdtVectorInfo))
13483 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
13484 else
13485 u32ErrCode = 0;
13486
13487 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF, see hmR0VmxExitXcptPF(). */
13488 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflect);
13489 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(uIdtVectorInfo), 0 /* cbInstr */,
13490 u32ErrCode, pVCpu->cpum.GstCtx.cr2);
13491
13492 Log4Func(("IDT: Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->hm.s.Event.u64IntInfo,
13493 pVCpu->hm.s.Event.u32ErrCode));
13494 Assert(rcStrict == VINF_SUCCESS);
13495 break;
13496 }
13497
13498 case IEMXCPTRAISE_REEXEC_INSTR:
13499 Assert(rcStrict == VINF_SUCCESS);
13500 break;
13501
13502 case IEMXCPTRAISE_DOUBLE_FAULT:
13503 {
13504 /*
13505 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
13506 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
13507 */
13508 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
13509 {
13510 pVmxTransient->fVectoringDoublePF = true;
13511 Log4Func(("IDT: Vectoring double #PF %#RX64 cr2=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo,
13512 pVCpu->cpum.GstCtx.cr2));
13513 rcStrict = VINF_SUCCESS;
13514 }
13515 else
13516 {
13517 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectConvertDF);
13518 hmR0VmxSetPendingXcptDF(pVCpu);
13519 Log4Func(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
13520 uIdtVector, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
13521 rcStrict = VINF_HM_DOUBLE_FAULT;
13522 }
13523 break;
13524 }
13525
13526 case IEMXCPTRAISE_TRIPLE_FAULT:
13527 {
13528 Log4Func(("IDT: Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", uIdtVector,
13529 VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
13530 rcStrict = VINF_EM_RESET;
13531 break;
13532 }
13533
13534 case IEMXCPTRAISE_CPU_HANG:
13535 {
13536 Log4Func(("IDT: Bad guest! Entering CPU hang. fRaiseInfo=%#x\n", fRaiseInfo));
13537 rcStrict = VERR_EM_GUEST_CPU_HANG;
13538 break;
13539 }
13540
13541 default:
13542 {
13543 AssertMsgFailed(("IDT: vcpu[%RU32] Unexpected/invalid value! enmRaise=%#x\n", pVCpu->idCpu, enmRaise));
13544 rcStrict = VERR_VMX_IPE_2;
13545 break;
13546 }
13547 }
13548 }
13549 else if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
13550 && !CPUMIsGuestNmiBlocking(pVCpu))
13551 {
13552 if ( VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo)
13553 && VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo) != X86_XCPT_DF
13554 && VMX_EXIT_INT_INFO_IS_NMI_UNBLOCK_IRET(uExitIntInfo))
13555 {
13556 /*
13557 * Execution of IRET caused a fault when NMI blocking was in effect (i.e we're in
13558 * the guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13559 * that virtual NMIs remain blocked until the IRET execution is completed.
13560 *
13561 * See Intel spec. 31.7.1.2 "Resuming Guest Software After Handling An Exception".
13562 */
13563 CPUMSetGuestNmiBlocking(pVCpu, true);
13564 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13565 }
13566 else if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
13567 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
13568 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
13569 {
13570 /*
13571 * Execution of IRET caused an EPT violation, page-modification log-full event or
13572 * SPP-related event VM-exit when NMI blocking was in effect (i.e. we're in the
13573 * guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13574 * that virtual NMIs remain blocked until the IRET execution is completed.
13575 *
13576 * See Intel spec. 27.2.3 "Information about NMI unblocking due to IRET"
13577 */
13578 if (VMX_EXIT_QUAL_EPT_IS_NMI_UNBLOCK_IRET(pVmxTransient->uExitQual))
13579 {
13580 CPUMSetGuestNmiBlocking(pVCpu, true);
13581 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13582 }
13583 }
13584 }
13585
13586 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
13587 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
13588 return rcStrict;
13589}
13590
13591
13592#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13593/**
13594 * Perform the relevant VMX instruction checks for VM-exits that occurred due to the
13595 * guest attempting to execute a VMX instruction.
13596 *
13597 * @returns Strict VBox status code (i.e. informational status codes too).
13598 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
13599 * @retval VINF_HM_PENDING_XCPT if an exception was raised.
13600 *
13601 * @param pVCpu The cross context virtual CPU structure.
13602 * @param uExitReason The VM-exit reason.
13603 *
13604 * @todo NSTVMX: Document other error codes when VM-exit is implemented.
13605 * @remarks No-long-jump zone!!!
13606 */
13607static VBOXSTRICTRC hmR0VmxCheckExitDueToVmxInstr(PVMCPUCC pVCpu, uint32_t uExitReason)
13608{
13609 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS
13610 | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
13611
13612 /*
13613 * The physical CPU would have already checked the CPU mode/code segment.
13614 * We shall just assert here for paranoia.
13615 * See Intel spec. 25.1.1 "Relative Priority of Faults and VM Exits".
13616 */
13617 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13618 Assert( !CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx)
13619 || CPUMIsGuestIn64BitCodeEx(&pVCpu->cpum.GstCtx));
13620
13621 if (uExitReason == VMX_EXIT_VMXON)
13622 {
13623 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
13624
13625 /*
13626 * We check CR4.VMXE because it is required to be always set while in VMX operation
13627 * by physical CPUs and our CR4 read-shadow is only consulted when executing specific
13628 * instructions (CLTS, LMSW, MOV CR, and SMSW) and thus doesn't affect CPU operation
13629 * otherwise (i.e. physical CPU won't automatically #UD if Cr4Shadow.VMXE is 0).
13630 */
13631 if (!CPUMIsGuestVmxEnabled(&pVCpu->cpum.GstCtx))
13632 {
13633 Log4Func(("CR4.VMXE is not set -> #UD\n"));
13634 hmR0VmxSetPendingXcptUD(pVCpu);
13635 return VINF_HM_PENDING_XCPT;
13636 }
13637 }
13638 else if (!CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx))
13639 {
13640 /*
13641 * The guest has not entered VMX operation but attempted to execute a VMX instruction
13642 * (other than VMXON), we need to raise a #UD.
13643 */
13644 Log4Func(("Not in VMX root mode -> #UD\n"));
13645 hmR0VmxSetPendingXcptUD(pVCpu);
13646 return VINF_HM_PENDING_XCPT;
13647 }
13648
13649 /* All other checks (including VM-exit intercepts) are handled by IEM instruction emulation. */
13650 return VINF_SUCCESS;
13651}
13652
13653
13654/**
13655 * Decodes the memory operand of an instruction that caused a VM-exit.
13656 *
13657 * The Exit qualification field provides the displacement field for memory
13658 * operand instructions, if any.
13659 *
13660 * @returns Strict VBox status code (i.e. informational status codes too).
13661 * @retval VINF_SUCCESS if the operand was successfully decoded.
13662 * @retval VINF_HM_PENDING_XCPT if an exception was raised while decoding the
13663 * operand.
13664 * @param pVCpu The cross context virtual CPU structure.
13665 * @param uExitInstrInfo The VM-exit instruction information field.
13666 * @param enmMemAccess The memory operand's access type (read or write).
13667 * @param GCPtrDisp The instruction displacement field, if any. For
13668 * RIP-relative addressing pass RIP + displacement here.
13669 * @param pGCPtrMem Where to store the effective destination memory address.
13670 *
13671 * @remarks Warning! This function ASSUMES the instruction cannot be used in real or
13672 * virtual-8086 mode hence skips those checks while verifying if the
13673 * segment is valid.
13674 */
13675static VBOXSTRICTRC hmR0VmxDecodeMemOperand(PVMCPUCC pVCpu, uint32_t uExitInstrInfo, RTGCPTR GCPtrDisp, VMXMEMACCESS enmMemAccess,
13676 PRTGCPTR pGCPtrMem)
13677{
13678 Assert(pGCPtrMem);
13679 Assert(!CPUMIsGuestInRealOrV86Mode(pVCpu));
13680 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_EFER
13681 | CPUMCTX_EXTRN_CR0);
13682
13683 static uint64_t const s_auAddrSizeMasks[] = { UINT64_C(0xffff), UINT64_C(0xffffffff), UINT64_C(0xffffffffffffffff) };
13684 static uint64_t const s_auAccessSizeMasks[] = { sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t) };
13685 AssertCompile(RT_ELEMENTS(s_auAccessSizeMasks) == RT_ELEMENTS(s_auAddrSizeMasks));
13686
13687 VMXEXITINSTRINFO ExitInstrInfo;
13688 ExitInstrInfo.u = uExitInstrInfo;
13689 uint8_t const uAddrSize = ExitInstrInfo.All.u3AddrSize;
13690 uint8_t const iSegReg = ExitInstrInfo.All.iSegReg;
13691 bool const fIdxRegValid = !ExitInstrInfo.All.fIdxRegInvalid;
13692 uint8_t const iIdxReg = ExitInstrInfo.All.iIdxReg;
13693 uint8_t const uScale = ExitInstrInfo.All.u2Scaling;
13694 bool const fBaseRegValid = !ExitInstrInfo.All.fBaseRegInvalid;
13695 uint8_t const iBaseReg = ExitInstrInfo.All.iBaseReg;
13696 bool const fIsMemOperand = !ExitInstrInfo.All.fIsRegOperand;
13697 bool const fIsLongMode = CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx);
13698
13699 /*
13700 * Validate instruction information.
13701 * This shouldn't happen on real hardware but useful while testing our nested hardware-virtualization code.
13702 */
13703 AssertLogRelMsgReturn(uAddrSize < RT_ELEMENTS(s_auAddrSizeMasks),
13704 ("Invalid address size. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_1);
13705 AssertLogRelMsgReturn(iSegReg < X86_SREG_COUNT,
13706 ("Invalid segment register. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_2);
13707 AssertLogRelMsgReturn(fIsMemOperand,
13708 ("Expected memory operand. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_3);
13709
13710 /*
13711 * Compute the complete effective address.
13712 *
13713 * See AMD instruction spec. 1.4.2 "SIB Byte Format"
13714 * See AMD spec. 4.5.2 "Segment Registers".
13715 */
13716 RTGCPTR GCPtrMem = GCPtrDisp;
13717 if (fBaseRegValid)
13718 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iBaseReg].u64;
13719 if (fIdxRegValid)
13720 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iIdxReg].u64 << uScale;
13721
13722 RTGCPTR const GCPtrOff = GCPtrMem;
13723 if ( !fIsLongMode
13724 || iSegReg >= X86_SREG_FS)
13725 GCPtrMem += pVCpu->cpum.GstCtx.aSRegs[iSegReg].u64Base;
13726 GCPtrMem &= s_auAddrSizeMasks[uAddrSize];
13727
13728 /*
13729 * Validate effective address.
13730 * See AMD spec. 4.5.3 "Segment Registers in 64-Bit Mode".
13731 */
13732 uint8_t const cbAccess = s_auAccessSizeMasks[uAddrSize];
13733 Assert(cbAccess > 0);
13734 if (fIsLongMode)
13735 {
13736 if (X86_IS_CANONICAL(GCPtrMem))
13737 {
13738 *pGCPtrMem = GCPtrMem;
13739 return VINF_SUCCESS;
13740 }
13741
13742 /** @todo r=ramshankar: We should probably raise \#SS or \#GP. See AMD spec. 4.12.2
13743 * "Data Limit Checks in 64-bit Mode". */
13744 Log4Func(("Long mode effective address is not canonical GCPtrMem=%#RX64\n", GCPtrMem));
13745 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13746 return VINF_HM_PENDING_XCPT;
13747 }
13748
13749 /*
13750 * This is a watered down version of iemMemApplySegment().
13751 * Parts that are not applicable for VMX instructions like real-or-v8086 mode
13752 * and segment CPL/DPL checks are skipped.
13753 */
13754 RTGCPTR32 const GCPtrFirst32 = (RTGCPTR32)GCPtrOff;
13755 RTGCPTR32 const GCPtrLast32 = GCPtrFirst32 + cbAccess - 1;
13756 PCCPUMSELREG pSel = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
13757
13758 /* Check if the segment is present and usable. */
13759 if ( pSel->Attr.n.u1Present
13760 && !pSel->Attr.n.u1Unusable)
13761 {
13762 Assert(pSel->Attr.n.u1DescType);
13763 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_CODE))
13764 {
13765 /* Check permissions for the data segment. */
13766 if ( enmMemAccess == VMXMEMACCESS_WRITE
13767 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_WRITE))
13768 {
13769 Log4Func(("Data segment access invalid. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13770 hmR0VmxSetPendingXcptGP(pVCpu, iSegReg);
13771 return VINF_HM_PENDING_XCPT;
13772 }
13773
13774 /* Check limits if it's a normal data segment. */
13775 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_DOWN))
13776 {
13777 if ( GCPtrFirst32 > pSel->u32Limit
13778 || GCPtrLast32 > pSel->u32Limit)
13779 {
13780 Log4Func(("Data segment limit exceeded. "
13781 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13782 GCPtrLast32, pSel->u32Limit));
13783 if (iSegReg == X86_SREG_SS)
13784 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13785 else
13786 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13787 return VINF_HM_PENDING_XCPT;
13788 }
13789 }
13790 else
13791 {
13792 /* Check limits if it's an expand-down data segment.
13793 Note! The upper boundary is defined by the B bit, not the G bit! */
13794 if ( GCPtrFirst32 < pSel->u32Limit + UINT32_C(1)
13795 || GCPtrLast32 > (pSel->Attr.n.u1DefBig ? UINT32_MAX : UINT32_C(0xffff)))
13796 {
13797 Log4Func(("Expand-down data segment limit exceeded. "
13798 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13799 GCPtrLast32, pSel->u32Limit));
13800 if (iSegReg == X86_SREG_SS)
13801 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13802 else
13803 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13804 return VINF_HM_PENDING_XCPT;
13805 }
13806 }
13807 }
13808 else
13809 {
13810 /* Check permissions for the code segment. */
13811 if ( enmMemAccess == VMXMEMACCESS_WRITE
13812 || ( enmMemAccess == VMXMEMACCESS_READ
13813 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_READ)))
13814 {
13815 Log4Func(("Code segment access invalid. Attr=%#RX32\n", pSel->Attr.u));
13816 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13817 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13818 return VINF_HM_PENDING_XCPT;
13819 }
13820
13821 /* Check limits for the code segment (normal/expand-down not applicable for code segments). */
13822 if ( GCPtrFirst32 > pSel->u32Limit
13823 || GCPtrLast32 > pSel->u32Limit)
13824 {
13825 Log4Func(("Code segment limit exceeded. GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n",
13826 GCPtrFirst32, GCPtrLast32, pSel->u32Limit));
13827 if (iSegReg == X86_SREG_SS)
13828 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13829 else
13830 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13831 return VINF_HM_PENDING_XCPT;
13832 }
13833 }
13834 }
13835 else
13836 {
13837 Log4Func(("Not present or unusable segment. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13838 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13839 return VINF_HM_PENDING_XCPT;
13840 }
13841
13842 *pGCPtrMem = GCPtrMem;
13843 return VINF_SUCCESS;
13844}
13845#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13846
13847
13848/**
13849 * VM-exit helper for LMSW.
13850 */
13851static VBOXSTRICTRC hmR0VmxExitLmsw(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint16_t uMsw, RTGCPTR GCPtrEffDst)
13852{
13853 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13854 AssertRCReturn(rc, rc);
13855
13856 VBOXSTRICTRC rcStrict = IEMExecDecodedLmsw(pVCpu, cbInstr, uMsw, GCPtrEffDst);
13857 AssertMsg( rcStrict == VINF_SUCCESS
13858 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13859
13860 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13861 if (rcStrict == VINF_IEM_RAISED_XCPT)
13862 {
13863 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13864 rcStrict = VINF_SUCCESS;
13865 }
13866
13867 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
13868 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13869 return rcStrict;
13870}
13871
13872
13873/**
13874 * VM-exit helper for CLTS.
13875 */
13876static VBOXSTRICTRC hmR0VmxExitClts(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr)
13877{
13878 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13879 AssertRCReturn(rc, rc);
13880
13881 VBOXSTRICTRC rcStrict = IEMExecDecodedClts(pVCpu, cbInstr);
13882 AssertMsg( rcStrict == VINF_SUCCESS
13883 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13884
13885 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13886 if (rcStrict == VINF_IEM_RAISED_XCPT)
13887 {
13888 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13889 rcStrict = VINF_SUCCESS;
13890 }
13891
13892 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
13893 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13894 return rcStrict;
13895}
13896
13897
13898/**
13899 * VM-exit helper for MOV from CRx (CRx read).
13900 */
13901static VBOXSTRICTRC hmR0VmxExitMovFromCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13902{
13903 Assert(iCrReg < 16);
13904 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
13905
13906 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13907 AssertRCReturn(rc, rc);
13908
13909 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
13910 AssertMsg( rcStrict == VINF_SUCCESS
13911 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13912
13913 if (iGReg == X86_GREG_xSP)
13914 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_RSP);
13915 else
13916 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13917#ifdef VBOX_WITH_STATISTICS
13918 switch (iCrReg)
13919 {
13920 case 0: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Read); break;
13921 case 2: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Read); break;
13922 case 3: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Read); break;
13923 case 4: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Read); break;
13924 case 8: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Read); break;
13925 }
13926#endif
13927 Log4Func(("CR%d Read access rcStrict=%Rrc\n", iCrReg, VBOXSTRICTRC_VAL(rcStrict)));
13928 return rcStrict;
13929}
13930
13931
13932/**
13933 * VM-exit helper for MOV to CRx (CRx write).
13934 */
13935static VBOXSTRICTRC hmR0VmxExitMovToCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13936{
13937 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13938 AssertRCReturn(rc, rc);
13939
13940 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
13941 AssertMsg( rcStrict == VINF_SUCCESS
13942 || rcStrict == VINF_IEM_RAISED_XCPT
13943 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13944
13945 switch (iCrReg)
13946 {
13947 case 0:
13948 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0
13949 | HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
13950 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Write);
13951 Log4Func(("CR0 write. rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr0));
13952 break;
13953
13954 case 2:
13955 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Write);
13956 /* Nothing to do here, CR2 it's not part of the VMCS. */
13957 break;
13958
13959 case 3:
13960 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR3);
13961 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Write);
13962 Log4Func(("CR3 write. rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr3));
13963 break;
13964
13965 case 4:
13966 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR4);
13967 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Write);
13968 Log4Func(("CR4 write. rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n", VBOXSTRICTRC_VAL(rcStrict),
13969 pVCpu->cpum.GstCtx.cr4, pVCpu->hmr0.s.fLoadSaveGuestXcr0));
13970 break;
13971
13972 case 8:
13973 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged,
13974 HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_APIC_TPR);
13975 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Write);
13976 break;
13977
13978 default:
13979 AssertMsgFailed(("Invalid CRx register %#x\n", iCrReg));
13980 break;
13981 }
13982
13983 if (rcStrict == VINF_IEM_RAISED_XCPT)
13984 {
13985 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13986 rcStrict = VINF_SUCCESS;
13987 }
13988 return rcStrict;
13989}
13990
13991
13992/**
13993 * VM-exit exception handler for \#PF (Page-fault exception).
13994 *
13995 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13996 */
13997static VBOXSTRICTRC hmR0VmxExitXcptPF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13998{
13999 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14000 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14001 hmR0VmxReadExitQualVmcs(pVmxTransient);
14002
14003 if (!pVM->hmr0.s.fNestedPaging)
14004 { /* likely */ }
14005 else
14006 {
14007#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
14008 Assert(pVmxTransient->fIsNestedGuest || pVCpu->hmr0.s.fUsingDebugLoop);
14009#endif
14010 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
14011 if (!pVmxTransient->fVectoringDoublePF)
14012 {
14013 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
14014 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual);
14015 }
14016 else
14017 {
14018 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
14019 Assert(!pVmxTransient->fIsNestedGuest);
14020 hmR0VmxSetPendingXcptDF(pVCpu);
14021 Log4Func(("Pending #DF due to vectoring #PF w/ NestedPaging\n"));
14022 }
14023 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
14024 return VINF_SUCCESS;
14025 }
14026
14027 Assert(!pVmxTransient->fIsNestedGuest);
14028
14029 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
14030 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
14031 if (pVmxTransient->fVectoringPF)
14032 {
14033 Assert(pVCpu->hm.s.Event.fPending);
14034 return VINF_EM_RAW_INJECT_TRPM_EVENT;
14035 }
14036
14037 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14038 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14039 AssertRCReturn(rc, rc);
14040
14041 Log4Func(("#PF: cs:rip=%#04x:%#RX64 err_code=%#RX32 exit_qual=%#RX64 cr3=%#RX64\n", pCtx->cs.Sel, pCtx->rip,
14042 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual, pCtx->cr3));
14043
14044 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQual, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
14045 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pCtx), (RTGCPTR)pVmxTransient->uExitQual);
14046
14047 Log4Func(("#PF: rc=%Rrc\n", rc));
14048 if (rc == VINF_SUCCESS)
14049 {
14050 /*
14051 * This is typically a shadow page table sync or a MMIO instruction. But we may have
14052 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
14053 */
14054 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14055 TRPMResetTrap(pVCpu);
14056 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
14057 return rc;
14058 }
14059
14060 if (rc == VINF_EM_RAW_GUEST_TRAP)
14061 {
14062 if (!pVmxTransient->fVectoringDoublePF)
14063 {
14064 /* It's a guest page fault and needs to be reflected to the guest. */
14065 uint32_t const uGstErrorCode = TRPMGetErrorCode(pVCpu);
14066 TRPMResetTrap(pVCpu);
14067 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
14068 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
14069 uGstErrorCode, pVmxTransient->uExitQual);
14070 }
14071 else
14072 {
14073 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
14074 TRPMResetTrap(pVCpu);
14075 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
14076 hmR0VmxSetPendingXcptDF(pVCpu);
14077 Log4Func(("#PF: Pending #DF due to vectoring #PF\n"));
14078 }
14079
14080 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
14081 return VINF_SUCCESS;
14082 }
14083
14084 TRPMResetTrap(pVCpu);
14085 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
14086 return rc;
14087}
14088
14089
14090/**
14091 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
14092 *
14093 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
14094 */
14095static VBOXSTRICTRC hmR0VmxExitXcptMF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14096{
14097 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14098 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
14099
14100 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0);
14101 AssertRCReturn(rc, rc);
14102
14103 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_NE))
14104 {
14105 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
14106 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
14107
14108 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
14109 * provides VM-exit instruction length. If this causes problem later,
14110 * disassemble the instruction like it's done on AMD-V. */
14111 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14112 AssertRCReturn(rc2, rc2);
14113 return rc;
14114 }
14115
14116 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), pVmxTransient->cbExitInstr,
14117 pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14118 return VINF_SUCCESS;
14119}
14120
14121
14122/**
14123 * VM-exit exception handler for \#BP (Breakpoint exception).
14124 *
14125 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
14126 */
14127static VBOXSTRICTRC hmR0VmxExitXcptBP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14128{
14129 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14130 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
14131
14132 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14133 AssertRCReturn(rc, rc);
14134
14135 if (!pVmxTransient->fIsNestedGuest)
14136 rc = DBGFTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx));
14137 else
14138 rc = VINF_EM_RAW_GUEST_TRAP;
14139
14140 if (rc == VINF_EM_RAW_GUEST_TRAP)
14141 {
14142 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
14143 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14144 rc = VINF_SUCCESS;
14145 }
14146
14147 Assert(rc == VINF_SUCCESS || rc == VINF_EM_DBG_BREAKPOINT);
14148 return rc;
14149}
14150
14151
14152/**
14153 * VM-exit exception handler for \#AC (Alignment-check exception).
14154 *
14155 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
14156 */
14157static VBOXSTRICTRC hmR0VmxExitXcptAC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14158{
14159 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14160
14161 /*
14162 * Detect #ACs caused by host having enabled split-lock detection.
14163 * Emulate such instructions.
14164 */
14165 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo,
14166 CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_CS);
14167 AssertRCReturn(rc, rc);
14168 /** @todo detect split lock in cpu feature? */
14169 if ( /* 1. If 486-style alignment checks aren't enabled, then this must be a split-lock exception */
14170 !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_AM)
14171 /* 2. #AC cannot happen in rings 0-2 except for split-lock detection. */
14172 || CPUMGetGuestCPL(pVCpu) != 3
14173 /* 3. When the EFLAGS.AC != 0 this can only be a split-lock case. */
14174 || !(pVCpu->cpum.GstCtx.eflags.u & X86_EFL_AC) )
14175 {
14176 /*
14177 * Check for debug/trace events and import state accordingly.
14178 */
14179 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitGuestACSplitLock);
14180 PVMCC pVM = pVCpu->pVMR0;
14181 if ( !DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_VMX_SPLIT_LOCK)
14182 && !VBOXVMM_VMX_SPLIT_LOCK_ENABLED())
14183 {
14184 if (pVM->cCpus == 1)
14185 {
14186#if 0 /** @todo r=bird: This is potentially wrong. Might have to just do a whole state sync above and mark everything changed to be safe... */
14187 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14188#else
14189 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14190#endif
14191 AssertRCReturn(rc, rc);
14192 }
14193 }
14194 else
14195 {
14196 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14197 AssertRCReturn(rc, rc);
14198
14199 VBOXVMM_XCPT_DF(pVCpu, &pVCpu->cpum.GstCtx);
14200
14201 if (DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_VMX_SPLIT_LOCK))
14202 {
14203 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, DBGFEVENT_VMX_SPLIT_LOCK, DBGFEVENTCTX_HM, 0);
14204 if (rcStrict != VINF_SUCCESS)
14205 return rcStrict;
14206 }
14207 }
14208
14209 /*
14210 * Emulate the instruction.
14211 *
14212 * We have to ignore the LOCK prefix here as we must not retrigger the
14213 * detection on the host. This isn't all that satisfactory, though...
14214 */
14215 if (pVM->cCpus == 1)
14216 {
14217 Log8Func(("cs:rip=%#04x:%#RX64 rflags=%#RX64 cr0=%#RX64 split-lock #AC\n", pVCpu->cpum.GstCtx.cs.Sel,
14218 pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags, pVCpu->cpum.GstCtx.cr0));
14219
14220 /** @todo For SMP configs we should do a rendezvous here. */
14221 VBOXSTRICTRC rcStrict = IEMExecOneIgnoreLock(pVCpu);
14222 if (rcStrict == VINF_SUCCESS)
14223#if 0 /** @todo r=bird: This is potentially wrong. Might have to just do a whole state sync above and mark everything changed to be safe... */
14224 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged,
14225 HM_CHANGED_GUEST_RIP
14226 | HM_CHANGED_GUEST_RFLAGS
14227 | HM_CHANGED_GUEST_GPRS_MASK
14228 | HM_CHANGED_GUEST_CS
14229 | HM_CHANGED_GUEST_SS);
14230#else
14231 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14232#endif
14233 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14234 {
14235 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14236 rcStrict = VINF_SUCCESS;
14237 }
14238 return rcStrict;
14239 }
14240 Log8Func(("cs:rip=%#04x:%#RX64 rflags=%#RX64 cr0=%#RX64 split-lock #AC -> VINF_EM_EMULATE_SPLIT_LOCK\n",
14241 pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags, pVCpu->cpum.GstCtx.cr0));
14242 return VINF_EM_EMULATE_SPLIT_LOCK;
14243 }
14244
14245 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC);
14246 Log8Func(("cs:rip=%#04x:%#RX64 rflags=%#RX64 cr0=%#RX64 cpl=%d -> #AC\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
14247 pVCpu->cpum.GstCtx.rflags, pVCpu->cpum.GstCtx.cr0, CPUMGetGuestCPL(pVCpu) ));
14248
14249 /* Re-inject it. We'll detect any nesting before getting here. */
14250 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
14251 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14252 return VINF_SUCCESS;
14253}
14254
14255
14256/**
14257 * VM-exit exception handler for \#DB (Debug exception).
14258 *
14259 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
14260 */
14261static VBOXSTRICTRC hmR0VmxExitXcptDB(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14262{
14263 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14264 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
14265
14266 /*
14267 * Get the DR6-like values from the Exit qualification and pass it to DBGF for processing.
14268 */
14269 hmR0VmxReadExitQualVmcs(pVmxTransient);
14270
14271 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
14272 uint64_t const uDR6 = X86_DR6_INIT_VAL
14273 | (pVmxTransient->uExitQual & ( X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3
14274 | X86_DR6_BD | X86_DR6_BS));
14275
14276 int rc;
14277 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14278 if (!pVmxTransient->fIsNestedGuest)
14279 {
14280 rc = DBGFTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
14281
14282 /*
14283 * Prevents stepping twice over the same instruction when the guest is stepping using
14284 * EFLAGS.TF and the hypervisor debugger is stepping using MTF.
14285 * Testcase: DOSQEMM, break (using "ba x 1") at cs:rip 0x70:0x774 and step (using "t").
14286 */
14287 if ( rc == VINF_EM_DBG_STEPPED
14288 && (pVmxTransient->pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_MONITOR_TRAP_FLAG))
14289 {
14290 Assert(pVCpu->hm.s.fSingleInstruction);
14291 rc = VINF_EM_RAW_GUEST_TRAP;
14292 }
14293 }
14294 else
14295 rc = VINF_EM_RAW_GUEST_TRAP;
14296 Log6Func(("rc=%Rrc\n", rc));
14297 if (rc == VINF_EM_RAW_GUEST_TRAP)
14298 {
14299 /*
14300 * The exception was for the guest. Update DR6, DR7.GD and
14301 * IA32_DEBUGCTL.LBR before forwarding it.
14302 * See Intel spec. 27.1 "Architectural State before a VM-Exit".
14303 */
14304 VMMRZCallRing3Disable(pVCpu);
14305 HM_DISABLE_PREEMPT(pVCpu);
14306
14307 pCtx->dr[6] &= ~X86_DR6_B_MASK;
14308 pCtx->dr[6] |= uDR6;
14309 if (CPUMIsGuestDebugStateActive(pVCpu))
14310 ASMSetDR6(pCtx->dr[6]);
14311
14312 HM_RESTORE_PREEMPT();
14313 VMMRZCallRing3Enable(pVCpu);
14314
14315 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_DR7);
14316 AssertRCReturn(rc, rc);
14317
14318 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
14319 pCtx->dr[7] &= ~(uint64_t)X86_DR7_GD;
14320
14321 /* Paranoia. */
14322 pCtx->dr[7] &= ~(uint64_t)X86_DR7_RAZ_MASK;
14323 pCtx->dr[7] |= X86_DR7_RA1_MASK;
14324
14325 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, pCtx->dr[7]);
14326 AssertRC(rc);
14327
14328 /*
14329 * Raise #DB in the guest.
14330 *
14331 * It is important to reflect exactly what the VM-exit gave us (preserving the
14332 * interruption-type) rather than use hmR0VmxSetPendingXcptDB() as the #DB could've
14333 * been raised while executing ICEBP (INT1) and not the regular #DB. Thus it may
14334 * trigger different handling in the CPU (like skipping DPL checks), see @bugref{6398}.
14335 *
14336 * Intel re-documented ICEBP/INT1 on May 2018 previously documented as part of
14337 * Intel 386, see Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
14338 */
14339 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
14340 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14341 return VINF_SUCCESS;
14342 }
14343
14344 /*
14345 * Not a guest trap, must be a hypervisor related debug event then.
14346 * Update DR6 in case someone is interested in it.
14347 */
14348 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
14349 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
14350 CPUMSetHyperDR6(pVCpu, uDR6);
14351
14352 return rc;
14353}
14354
14355
14356/**
14357 * Hacks its way around the lovely mesa driver's backdoor accesses.
14358 *
14359 * @sa hmR0SvmHandleMesaDrvGp.
14360 */
14361static int hmR0VmxHandleMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
14362{
14363 LogFunc(("cs:rip=%#04x:%#RX64 rcx=%#RX64 rbx=%#RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->rcx, pCtx->rbx));
14364 RT_NOREF(pCtx);
14365
14366 /* For now we'll just skip the instruction. */
14367 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14368}
14369
14370
14371/**
14372 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
14373 * backdoor logging w/o checking what it is running inside.
14374 *
14375 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
14376 * backdoor port and magic numbers loaded in registers.
14377 *
14378 * @returns true if it is, false if it isn't.
14379 * @sa hmR0SvmIsMesaDrvGp.
14380 */
14381DECLINLINE(bool) hmR0VmxIsMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
14382{
14383 /* 0xed: IN eAX,dx */
14384 uint8_t abInstr[1];
14385 if (pVmxTransient->cbExitInstr != sizeof(abInstr))
14386 return false;
14387
14388 /* Check that it is #GP(0). */
14389 if (pVmxTransient->uExitIntErrorCode != 0)
14390 return false;
14391
14392 /* Check magic and port. */
14393 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RCX)));
14394 /*Log(("hmR0VmxIsMesaDrvGp: rax=%RX64 rdx=%RX64\n", pCtx->rax, pCtx->rdx));*/
14395 if (pCtx->rax != UINT32_C(0x564d5868))
14396 return false;
14397 if (pCtx->dx != UINT32_C(0x5658))
14398 return false;
14399
14400 /* Flat ring-3 CS. */
14401 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_CS);
14402 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CS));
14403 /*Log(("hmR0VmxIsMesaDrvGp: cs.Attr.n.u2Dpl=%d base=%Rx64\n", pCtx->cs.Attr.n.u2Dpl, pCtx->cs.u64Base));*/
14404 if (pCtx->cs.Attr.n.u2Dpl != 3)
14405 return false;
14406 if (pCtx->cs.u64Base != 0)
14407 return false;
14408
14409 /* Check opcode. */
14410 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_RIP);
14411 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
14412 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
14413 /*Log(("hmR0VmxIsMesaDrvGp: PGMPhysSimpleReadGCPtr -> %Rrc %#x\n", rc, abInstr[0]));*/
14414 if (RT_FAILURE(rc))
14415 return false;
14416 if (abInstr[0] != 0xed)
14417 return false;
14418
14419 return true;
14420}
14421
14422
14423/**
14424 * VM-exit exception handler for \#GP (General-protection exception).
14425 *
14426 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
14427 */
14428static VBOXSTRICTRC hmR0VmxExitXcptGP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14429{
14430 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14431 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
14432
14433 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14434 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14435 PVMXVMCSINFOSHARED pVmcsInfoShared = pVmcsInfo->pShared;
14436 if (pVmcsInfoShared->RealMode.fRealOnV86Active)
14437 { /* likely */ }
14438 else
14439 {
14440#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
14441 Assert(pVCpu->hmr0.s.fUsingDebugLoop || pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv || pVmxTransient->fIsNestedGuest);
14442#endif
14443 /*
14444 * If the guest is not in real-mode or we have unrestricted guest execution support, or if we are
14445 * executing a nested-guest, reflect #GP to the guest or nested-guest.
14446 */
14447 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14448 AssertRCReturn(rc, rc);
14449 Log4Func(("Gst: cs:rip=%#04x:%#RX64 ErrorCode=%#x cr0=%#RX64 cpl=%u tr=%#04x\n", pCtx->cs.Sel, pCtx->rip,
14450 pVmxTransient->uExitIntErrorCode, pCtx->cr0, CPUMGetGuestCPL(pVCpu), pCtx->tr.Sel));
14451
14452 if ( pVmxTransient->fIsNestedGuest
14453 || !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
14454 || !hmR0VmxIsMesaDrvGp(pVCpu, pVmxTransient, pCtx))
14455 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
14456 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14457 else
14458 rc = hmR0VmxHandleMesaDrvGp(pVCpu, pVmxTransient, pCtx);
14459 return rc;
14460 }
14461
14462 Assert(CPUMIsGuestInRealModeEx(pCtx));
14463 Assert(!pVCpu->CTX_SUFF(pVM)->hmr0.s.vmx.fUnrestrictedGuest);
14464 Assert(!pVmxTransient->fIsNestedGuest);
14465
14466 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14467 AssertRCReturn(rc, rc);
14468
14469 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
14470 if (rcStrict == VINF_SUCCESS)
14471 {
14472 if (!CPUMIsGuestInRealModeEx(pCtx))
14473 {
14474 /*
14475 * The guest is no longer in real-mode, check if we can continue executing the
14476 * guest using hardware-assisted VMX. Otherwise, fall back to emulation.
14477 */
14478 pVmcsInfoShared->RealMode.fRealOnV86Active = false;
14479 if (HMCanExecuteVmxGuest(pVCpu->pVMR0, pVCpu, pCtx))
14480 {
14481 Log4Func(("Mode changed but guest still suitable for executing using hardware-assisted VMX\n"));
14482 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14483 }
14484 else
14485 {
14486 Log4Func(("Mode changed -> VINF_EM_RESCHEDULE\n"));
14487 rcStrict = VINF_EM_RESCHEDULE;
14488 }
14489 }
14490 else
14491 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14492 }
14493 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14494 {
14495 rcStrict = VINF_SUCCESS;
14496 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14497 }
14498 return VBOXSTRICTRC_VAL(rcStrict);
14499}
14500
14501
14502/**
14503 * VM-exit exception handler wrapper for all other exceptions that are not handled
14504 * by a specific handler.
14505 *
14506 * This simply re-injects the exception back into the VM without any special
14507 * processing.
14508 *
14509 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
14510 */
14511static VBOXSTRICTRC hmR0VmxExitXcptOthers(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14512{
14513 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14514
14515#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
14516 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14517 AssertMsg(pVCpu->hmr0.s.fUsingDebugLoop || pVmcsInfo->pShared->RealMode.fRealOnV86Active || pVmxTransient->fIsNestedGuest,
14518 ("uVector=%#x u32XcptBitmap=%#X32\n",
14519 VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo), pVmcsInfo->u32XcptBitmap));
14520 NOREF(pVmcsInfo);
14521#endif
14522
14523 /*
14524 * Re-inject the exception into the guest. This cannot be a double-fault condition which
14525 * would have been handled while checking exits due to event delivery.
14526 */
14527 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14528
14529#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
14530 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
14531 AssertRCReturn(rc, rc);
14532 Log4Func(("Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
14533#endif
14534
14535#ifdef VBOX_WITH_STATISTICS
14536 switch (uVector)
14537 {
14538 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE); break;
14539 case X86_XCPT_DB: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB); break;
14540 case X86_XCPT_BP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP); break;
14541 case X86_XCPT_OF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
14542 case X86_XCPT_BR: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBR); break;
14543 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD); break;
14544 case X86_XCPT_NM: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
14545 case X86_XCPT_DF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDF); break;
14546 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS); break;
14547 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP); break;
14548 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS); break;
14549 case X86_XCPT_GP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP); break;
14550 case X86_XCPT_PF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF); break;
14551 case X86_XCPT_MF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF); break;
14552 case X86_XCPT_AC: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC); break;
14553 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF); break;
14554 default:
14555 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
14556 break;
14557 }
14558#endif
14559
14560 /* We should never call this function for a page-fault, we'd need to pass on the fault address below otherwise. */
14561 Assert(!VMX_EXIT_INT_INFO_IS_XCPT_PF(pVmxTransient->uExitIntInfo));
14562 NOREF(uVector);
14563
14564 /* Re-inject the original exception into the guest. */
14565 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
14566 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14567 return VINF_SUCCESS;
14568}
14569
14570
14571/**
14572 * VM-exit exception handler for all exceptions (except NMIs!).
14573 *
14574 * @remarks This may be called for both guests and nested-guests. Take care to not
14575 * make assumptions and avoid doing anything that is not relevant when
14576 * executing a nested-guest (e.g., Mesa driver hacks).
14577 */
14578static VBOXSTRICTRC hmR0VmxExitXcpt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14579{
14580 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
14581
14582 /*
14583 * If this VM-exit occurred while delivering an event through the guest IDT, take
14584 * action based on the return code and additional hints (e.g. for page-faults)
14585 * that will be updated in the VMX transient structure.
14586 */
14587 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
14588 if (rcStrict == VINF_SUCCESS)
14589 {
14590 /*
14591 * If an exception caused a VM-exit due to delivery of an event, the original
14592 * event may have to be re-injected into the guest. We shall reinject it and
14593 * continue guest execution. However, page-fault is a complicated case and
14594 * needs additional processing done in hmR0VmxExitXcptPF().
14595 */
14596 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14597 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14598 if ( !pVCpu->hm.s.Event.fPending
14599 || uVector == X86_XCPT_PF)
14600 {
14601 switch (uVector)
14602 {
14603 case X86_XCPT_PF: return hmR0VmxExitXcptPF(pVCpu, pVmxTransient);
14604 case X86_XCPT_GP: return hmR0VmxExitXcptGP(pVCpu, pVmxTransient);
14605 case X86_XCPT_MF: return hmR0VmxExitXcptMF(pVCpu, pVmxTransient);
14606 case X86_XCPT_DB: return hmR0VmxExitXcptDB(pVCpu, pVmxTransient);
14607 case X86_XCPT_BP: return hmR0VmxExitXcptBP(pVCpu, pVmxTransient);
14608 case X86_XCPT_AC: return hmR0VmxExitXcptAC(pVCpu, pVmxTransient);
14609 default:
14610 return hmR0VmxExitXcptOthers(pVCpu, pVmxTransient);
14611 }
14612 }
14613 /* else: inject pending event before resuming guest execution. */
14614 }
14615 else if (rcStrict == VINF_HM_DOUBLE_FAULT)
14616 {
14617 Assert(pVCpu->hm.s.Event.fPending);
14618 rcStrict = VINF_SUCCESS;
14619 }
14620
14621 return rcStrict;
14622}
14623/** @} */
14624
14625
14626/** @name VM-exit handlers.
14627 * @{
14628 */
14629/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
14630/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
14631/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
14632
14633/**
14634 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
14635 */
14636HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14637{
14638 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14639 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
14640 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
14641 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
14642 return VINF_SUCCESS;
14643 return VINF_EM_RAW_INTERRUPT;
14644}
14645
14646
14647/**
14648 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI). Conditional
14649 * VM-exit.
14650 */
14651HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14652{
14653 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14654 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
14655
14656 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
14657
14658 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
14659 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14660 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14661
14662 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14663 Assert( !(pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_ACK_EXT_INT)
14664 && uExitIntType != VMX_EXIT_INT_INFO_TYPE_EXT_INT);
14665 NOREF(pVmcsInfo);
14666
14667 VBOXSTRICTRC rcStrict;
14668 switch (uExitIntType)
14669 {
14670 /*
14671 * Host physical NMIs:
14672 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we
14673 * injected it ourselves and anything we inject is not going to cause a VM-exit directly
14674 * for the event being injected[1]. Go ahead and dispatch the NMI to the host[2].
14675 *
14676 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
14677 * See Intel spec. 27.5.5 "Updating Non-Register State".
14678 */
14679 case VMX_EXIT_INT_INFO_TYPE_NMI:
14680 {
14681 rcStrict = hmR0VmxExitHostNmi(pVCpu, pVmcsInfo);
14682 break;
14683 }
14684
14685 /*
14686 * Privileged software exceptions (#DB from ICEBP),
14687 * Software exceptions (#BP and #OF),
14688 * Hardware exceptions:
14689 * Process the required exceptions and resume guest execution if possible.
14690 */
14691 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
14692 Assert(uVector == X86_XCPT_DB);
14693 RT_FALL_THRU();
14694 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
14695 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uExitIntType == VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT);
14696 RT_FALL_THRU();
14697 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
14698 {
14699 NOREF(uVector);
14700 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
14701 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14702 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
14703 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
14704
14705 rcStrict = hmR0VmxExitXcpt(pVCpu, pVmxTransient);
14706 break;
14707 }
14708
14709 default:
14710 {
14711 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
14712 rcStrict = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
14713 AssertMsgFailed(("Invalid/unexpected VM-exit interruption info %#x\n", pVmxTransient->uExitIntInfo));
14714 break;
14715 }
14716 }
14717
14718 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
14719 return rcStrict;
14720}
14721
14722
14723/**
14724 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
14725 */
14726HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14727{
14728 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14729
14730 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
14731 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14732 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
14733
14734 /* Evaluate and deliver pending events and resume guest execution. */
14735 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
14736 return VINF_SUCCESS;
14737}
14738
14739
14740/**
14741 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
14742 */
14743HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14744{
14745 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14746
14747 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14748 if (RT_UNLIKELY(!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))) /** @todo NSTVMX: Turn this into an assertion. */
14749 {
14750 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
14751 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14752 }
14753
14754 Assert(!CPUMIsGuestNmiBlocking(pVCpu));
14755
14756 /*
14757 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
14758 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
14759 */
14760 uint32_t fIntrState;
14761 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
14762 AssertRC(rc);
14763 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
14764 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
14765 {
14766 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
14767 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
14768
14769 fIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
14770 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
14771 AssertRC(rc);
14772 }
14773
14774 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
14775 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
14776
14777 /* Evaluate and deliver pending events and resume guest execution. */
14778 return VINF_SUCCESS;
14779}
14780
14781
14782/**
14783 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
14784 */
14785HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14786{
14787 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14788 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14789}
14790
14791
14792/**
14793 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
14794 */
14795HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14796{
14797 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14798 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14799}
14800
14801
14802/**
14803 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
14804 */
14805HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14806{
14807 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14808
14809 /*
14810 * Get the state we need and update the exit history entry.
14811 */
14812 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14813 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14814
14815 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14816 AssertRCReturn(rc, rc);
14817
14818 VBOXSTRICTRC rcStrict;
14819 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
14820 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
14821 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
14822 if (!pExitRec)
14823 {
14824 /*
14825 * Regular CPUID instruction execution.
14826 */
14827 rcStrict = IEMExecDecodedCpuid(pVCpu, pVmxTransient->cbExitInstr);
14828 if (rcStrict == VINF_SUCCESS)
14829 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14830 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14831 {
14832 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14833 rcStrict = VINF_SUCCESS;
14834 }
14835 }
14836 else
14837 {
14838 /*
14839 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
14840 */
14841 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14842 AssertRCReturn(rc2, rc2);
14843
14844 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
14845 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
14846
14847 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
14848 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14849
14850 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
14851 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
14852 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
14853 }
14854 return rcStrict;
14855}
14856
14857
14858/**
14859 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
14860 */
14861HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14862{
14863 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14864
14865 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14866 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4);
14867 AssertRCReturn(rc, rc);
14868
14869 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_SMXE)
14870 return VINF_EM_RAW_EMULATE_INSTR;
14871
14872 AssertMsgFailed(("hmR0VmxExitGetsec: Unexpected VM-exit when CR4.SMXE is 0.\n"));
14873 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14874}
14875
14876
14877/**
14878 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
14879 */
14880HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14881{
14882 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14883
14884 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14885 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14886 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14887 AssertRCReturn(rc, rc);
14888
14889 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, pVmxTransient->cbExitInstr);
14890 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14891 {
14892 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14893 we must reset offsetting on VM-entry. See @bugref{6634}. */
14894 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14895 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14896 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14897 }
14898 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14899 {
14900 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14901 rcStrict = VINF_SUCCESS;
14902 }
14903 return rcStrict;
14904}
14905
14906
14907/**
14908 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
14909 */
14910HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14911{
14912 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14913
14914 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14915 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14916 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_TSC_AUX);
14917 AssertRCReturn(rc, rc);
14918
14919 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, pVmxTransient->cbExitInstr);
14920 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14921 {
14922 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14923 we must reset offsetting on VM-reentry. See @bugref{6634}. */
14924 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14925 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14926 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14927 }
14928 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14929 {
14930 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14931 rcStrict = VINF_SUCCESS;
14932 }
14933 return rcStrict;
14934}
14935
14936
14937/**
14938 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
14939 */
14940HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14941{
14942 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14943
14944 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14945 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_CR0
14946 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS);
14947 AssertRCReturn(rc, rc);
14948
14949 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14950 rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
14951 if (RT_LIKELY(rc == VINF_SUCCESS))
14952 {
14953 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14954 Assert(pVmxTransient->cbExitInstr == 2);
14955 }
14956 else
14957 {
14958 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
14959 rc = VERR_EM_INTERPRETER;
14960 }
14961 return rc;
14962}
14963
14964
14965/**
14966 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
14967 */
14968HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14969{
14970 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14971
14972 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
14973 if (EMAreHypercallInstructionsEnabled(pVCpu))
14974 {
14975 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14976 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CR0
14977 | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
14978 AssertRCReturn(rc, rc);
14979
14980 /* Perform the hypercall. */
14981 rcStrict = GIMHypercall(pVCpu, &pVCpu->cpum.GstCtx);
14982 if (rcStrict == VINF_SUCCESS)
14983 {
14984 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14985 AssertRCReturn(rc, rc);
14986 }
14987 else
14988 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
14989 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
14990 || RT_FAILURE(rcStrict));
14991
14992 /* If the hypercall changes anything other than guest's general-purpose registers,
14993 we would need to reload the guest changed bits here before VM-entry. */
14994 }
14995 else
14996 Log4Func(("Hypercalls not enabled\n"));
14997
14998 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
14999 if (RT_FAILURE(rcStrict))
15000 {
15001 hmR0VmxSetPendingXcptUD(pVCpu);
15002 rcStrict = VINF_SUCCESS;
15003 }
15004
15005 return rcStrict;
15006}
15007
15008
15009/**
15010 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
15011 */
15012HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15013{
15014 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15015 Assert(!pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging || pVCpu->hmr0.s.fUsingDebugLoop);
15016
15017 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15018 hmR0VmxReadExitQualVmcs(pVmxTransient);
15019 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15020 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15021 AssertRCReturn(rc, rc);
15022
15023 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->uExitQual);
15024
15025 if (rcStrict == VINF_SUCCESS || rcStrict == VINF_PGM_SYNC_CR3)
15026 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15027 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15028 {
15029 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15030 rcStrict = VINF_SUCCESS;
15031 }
15032 else
15033 AssertMsgFailed(("Unexpected IEMExecDecodedInvlpg(%#RX64) status: %Rrc\n", pVmxTransient->uExitQual,
15034 VBOXSTRICTRC_VAL(rcStrict)));
15035 return rcStrict;
15036}
15037
15038
15039/**
15040 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
15041 */
15042HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15043{
15044 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15045
15046 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15047 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15048 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK | CPUMCTX_EXTRN_DS);
15049 AssertRCReturn(rc, rc);
15050
15051 VBOXSTRICTRC rcStrict = IEMExecDecodedMonitor(pVCpu, pVmxTransient->cbExitInstr);
15052 if (rcStrict == VINF_SUCCESS)
15053 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15054 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15055 {
15056 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15057 rcStrict = VINF_SUCCESS;
15058 }
15059
15060 return rcStrict;
15061}
15062
15063
15064/**
15065 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
15066 */
15067HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15068{
15069 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15070
15071 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15072 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15073 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
15074 AssertRCReturn(rc, rc);
15075
15076 VBOXSTRICTRC rcStrict = IEMExecDecodedMwait(pVCpu, pVmxTransient->cbExitInstr);
15077 if (RT_SUCCESS(rcStrict))
15078 {
15079 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15080 if (EMMonitorWaitShouldContinue(pVCpu, &pVCpu->cpum.GstCtx))
15081 rcStrict = VINF_SUCCESS;
15082 }
15083
15084 return rcStrict;
15085}
15086
15087
15088/**
15089 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
15090 * VM-exit.
15091 */
15092HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15093{
15094 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15095 return VINF_EM_RESET;
15096}
15097
15098
15099/**
15100 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
15101 */
15102HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15103{
15104 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15105
15106 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15107 AssertRCReturn(rc, rc);
15108
15109 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS); /* Advancing the RIP above should've imported eflags. */
15110 if (EMShouldContinueAfterHalt(pVCpu, &pVCpu->cpum.GstCtx)) /* Requires eflags. */
15111 rc = VINF_SUCCESS;
15112 else
15113 rc = VINF_EM_HALT;
15114
15115 if (rc != VINF_SUCCESS)
15116 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
15117 return rc;
15118}
15119
15120
15121/**
15122 * VM-exit handler for instructions that result in a \#UD exception delivered to
15123 * the guest.
15124 */
15125HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15126{
15127 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15128 hmR0VmxSetPendingXcptUD(pVCpu);
15129 return VINF_SUCCESS;
15130}
15131
15132
15133/**
15134 * VM-exit handler for expiry of the VMX-preemption timer.
15135 */
15136HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15137{
15138 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15139
15140 /* If the VMX-preemption timer has expired, reinitialize the preemption timer on next VM-entry. */
15141 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
15142Log12(("hmR0VmxExitPreemptTimer:\n"));
15143
15144 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
15145 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15146 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
15147 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
15148 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
15149}
15150
15151
15152/**
15153 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
15154 */
15155HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15156{
15157 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15158
15159 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15160 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15161 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_CR4);
15162 AssertRCReturn(rc, rc);
15163
15164 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbExitInstr);
15165 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
15166 : HM_CHANGED_RAISED_XCPT_MASK);
15167
15168 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15169 bool const fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
15170 if (fLoadSaveGuestXcr0 != pVCpu->hmr0.s.fLoadSaveGuestXcr0)
15171 {
15172 pVCpu->hmr0.s.fLoadSaveGuestXcr0 = fLoadSaveGuestXcr0;
15173 hmR0VmxUpdateStartVmFunction(pVCpu);
15174 }
15175
15176 return rcStrict;
15177}
15178
15179
15180/**
15181 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
15182 */
15183HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15184{
15185 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15186
15187 /** @todo Enable the new code after finding a reliably guest test-case. */
15188#if 1
15189 return VERR_EM_INTERPRETER;
15190#else
15191 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15192 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15193 hmR0VmxReadExitQualVmcs(pVmxTransient);
15194 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15195 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15196 AssertRCReturn(rc, rc);
15197
15198 /* Paranoia. Ensure this has a memory operand. */
15199 Assert(!pVmxTransient->ExitInstrInfo.Inv.u1Cleared0);
15200
15201 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
15202 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
15203 uint64_t const uType = CPUMIsGuestIn64BitCode(pVCpu) ? pVCpu->cpum.GstCtx.aGRegs[iGReg].u64
15204 : pVCpu->cpum.GstCtx.aGRegs[iGReg].u32;
15205
15206 RTGCPTR GCPtrDesc;
15207 HMVMX_DECODE_MEM_OPERAND(pVCpu, pVmxTransient->ExitInstrInfo.u, pVmxTransient->uExitQual, VMXMEMACCESS_READ, &GCPtrDesc);
15208
15209 VBOXSTRICTRC rcStrict = IEMExecDecodedInvpcid(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->ExitInstrInfo.Inv.iSegReg,
15210 GCPtrDesc, uType);
15211 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15212 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15213 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15214 {
15215 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15216 rcStrict = VINF_SUCCESS;
15217 }
15218 return rcStrict;
15219#endif
15220}
15221
15222
15223/**
15224 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error
15225 * VM-exit.
15226 */
15227HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15228{
15229 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15230 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15231 AssertRCReturn(rc, rc);
15232
15233 rc = hmR0VmxCheckCachedVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
15234 if (RT_FAILURE(rc))
15235 return rc;
15236
15237 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
15238 NOREF(uInvalidReason);
15239
15240#ifdef VBOX_STRICT
15241 uint32_t fIntrState;
15242 uint64_t u64Val;
15243 hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
15244 hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
15245 hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
15246
15247 Log4(("uInvalidReason %u\n", uInvalidReason));
15248 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
15249 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
15250 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
15251
15252 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState); AssertRC(rc);
15253 Log4(("VMX_VMCS32_GUEST_INT_STATE %#RX32\n", fIntrState));
15254 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Val); AssertRC(rc);
15255 Log4(("VMX_VMCS_GUEST_CR0 %#RX64\n", u64Val));
15256 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_MASK, &u64Val); AssertRC(rc);
15257 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RX64\n", u64Val));
15258 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Val); AssertRC(rc);
15259 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
15260 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_MASK, &u64Val); AssertRC(rc);
15261 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RX64\n", u64Val));
15262 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Val); AssertRC(rc);
15263 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
15264 if (pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging)
15265 {
15266 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
15267 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
15268 }
15269 hmR0DumpRegs(pVCpu, HM_DUMP_REG_FLAGS_ALL);
15270#endif
15271
15272 return VERR_VMX_INVALID_GUEST_STATE;
15273}
15274
15275/**
15276 * VM-exit handler for all undefined/unexpected reasons. Should never happen.
15277 */
15278HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUnexpected(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15279{
15280 /*
15281 * Cumulative notes of all recognized but unexpected VM-exits.
15282 *
15283 * 1. This does -not- cover scenarios like a page-fault VM-exit occurring when
15284 * nested-paging is used.
15285 *
15286 * 2. Any instruction that causes a VM-exit unconditionally (for e.g. VMXON) must be
15287 * emulated or a #UD must be raised in the guest. Therefore, we should -not- be using
15288 * this function (and thereby stop VM execution) for handling such instructions.
15289 *
15290 *
15291 * VMX_EXIT_INIT_SIGNAL:
15292 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
15293 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these
15294 * VM-exits. However, we should not receive INIT signals VM-exit while executing a VM.
15295 *
15296 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery"
15297 * See Intel spec. 29.3 "VMX Instructions" for "VMXON".
15298 * See Intel spec. "23.8 Restrictions on VMX operation".
15299 *
15300 * VMX_EXIT_SIPI:
15301 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest
15302 * activity state is used. We don't make use of it as our guests don't have direct
15303 * access to the host local APIC.
15304 *
15305 * See Intel spec. 25.3 "Other Causes of VM-exits".
15306 *
15307 * VMX_EXIT_IO_SMI:
15308 * VMX_EXIT_SMI:
15309 * This can only happen if we support dual-monitor treatment of SMI, which can be
15310 * activated by executing VMCALL in VMX root operation. Only an STM (SMM transfer
15311 * monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL in
15312 * VMX root mode or receive an SMI. If we get here, something funny is going on.
15313 *
15314 * See Intel spec. 33.15.6 "Activating the Dual-Monitor Treatment"
15315 * See Intel spec. 25.3 "Other Causes of VM-Exits"
15316 *
15317 * VMX_EXIT_ERR_MSR_LOAD:
15318 * Failures while loading MSRs are part of the VM-entry MSR-load area are unexpected
15319 * and typically indicates a bug in the hypervisor code. We thus cannot not resume
15320 * execution.
15321 *
15322 * See Intel spec. 26.7 "VM-Entry Failures During Or After Loading Guest State".
15323 *
15324 * VMX_EXIT_ERR_MACHINE_CHECK:
15325 * Machine check exceptions indicates a fatal/unrecoverable hardware condition
15326 * including but not limited to system bus, ECC, parity, cache and TLB errors. A
15327 * #MC exception abort class exception is raised. We thus cannot assume a
15328 * reasonable chance of continuing any sort of execution and we bail.
15329 *
15330 * See Intel spec. 15.1 "Machine-check Architecture".
15331 * See Intel spec. 27.1 "Architectural State Before A VM Exit".
15332 *
15333 * VMX_EXIT_PML_FULL:
15334 * VMX_EXIT_VIRTUALIZED_EOI:
15335 * VMX_EXIT_APIC_WRITE:
15336 * We do not currently support any of these features and thus they are all unexpected
15337 * VM-exits.
15338 *
15339 * VMX_EXIT_GDTR_IDTR_ACCESS:
15340 * VMX_EXIT_LDTR_TR_ACCESS:
15341 * VMX_EXIT_RDRAND:
15342 * VMX_EXIT_RSM:
15343 * VMX_EXIT_VMFUNC:
15344 * VMX_EXIT_ENCLS:
15345 * VMX_EXIT_RDSEED:
15346 * VMX_EXIT_XSAVES:
15347 * VMX_EXIT_XRSTORS:
15348 * VMX_EXIT_UMWAIT:
15349 * VMX_EXIT_TPAUSE:
15350 * These VM-exits are -not- caused unconditionally by execution of the corresponding
15351 * instruction. Any VM-exit for these instructions indicate a hardware problem,
15352 * unsupported CPU modes (like SMM) or potentially corrupt VMCS controls.
15353 *
15354 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
15355 */
15356 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15357 AssertMsgFailed(("Unexpected VM-exit %u\n", pVmxTransient->uExitReason));
15358 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
15359}
15360
15361
15362/**
15363 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
15364 */
15365HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15366{
15367 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15368
15369 /** @todo Optimize this: We currently drag in the whole MSR state
15370 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
15371 * MSRs required. That would require changes to IEM and possibly CPUM too.
15372 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
15373 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15374 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
15375 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
15376 switch (idMsr)
15377 {
15378 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
15379 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
15380 }
15381
15382 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15383 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
15384 AssertRCReturn(rc, rc);
15385
15386 Log4Func(("ecx=%#RX32\n", idMsr));
15387
15388#ifdef VBOX_STRICT
15389 Assert(!pVmxTransient->fIsNestedGuest);
15390 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
15391 {
15392 if ( hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr)
15393 && idMsr != MSR_K6_EFER)
15394 {
15395 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n", idMsr));
15396 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
15397 }
15398 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
15399 {
15400 Assert(pVmcsInfo->pvMsrBitmap);
15401 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
15402 if (fMsrpm & VMXMSRPM_ALLOW_RD)
15403 {
15404 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", idMsr));
15405 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
15406 }
15407 }
15408 }
15409#endif
15410
15411 VBOXSTRICTRC rcStrict = IEMExecDecodedRdmsr(pVCpu, pVmxTransient->cbExitInstr);
15412 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
15413 if (rcStrict == VINF_SUCCESS)
15414 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15415 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15416 {
15417 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15418 rcStrict = VINF_SUCCESS;
15419 }
15420 else
15421 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_READ || rcStrict == VINF_EM_TRIPLE_FAULT,
15422 ("Unexpected IEMExecDecodedRdmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
15423
15424 return rcStrict;
15425}
15426
15427
15428/**
15429 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
15430 */
15431HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15432{
15433 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15434
15435 /** @todo Optimize this: We currently drag in the whole MSR state
15436 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
15437 * MSRs required. That would require changes to IEM and possibly CPUM too.
15438 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
15439 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
15440 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
15441
15442 /*
15443 * The FS and GS base MSRs are not part of the above all-MSRs mask.
15444 * Although we don't need to fetch the base as it will be overwritten shortly, while
15445 * loading guest-state we would also load the entire segment register including limit
15446 * and attributes and thus we need to load them here.
15447 */
15448 switch (idMsr)
15449 {
15450 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
15451 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
15452 }
15453
15454 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15455 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15456 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
15457 AssertRCReturn(rc, rc);
15458
15459 Log4Func(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", idMsr, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.eax));
15460
15461 VBOXSTRICTRC rcStrict = IEMExecDecodedWrmsr(pVCpu, pVmxTransient->cbExitInstr);
15462 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
15463
15464 if (rcStrict == VINF_SUCCESS)
15465 {
15466 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15467
15468 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
15469 if ( idMsr == MSR_IA32_APICBASE
15470 || ( idMsr >= MSR_IA32_X2APIC_START
15471 && idMsr <= MSR_IA32_X2APIC_END))
15472 {
15473 /*
15474 * We've already saved the APIC related guest-state (TPR) in post-run phase.
15475 * When full APIC register virtualization is implemented we'll have to make
15476 * sure APIC state is saved from the VMCS before IEM changes it.
15477 */
15478 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
15479 }
15480 else if (idMsr == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
15481 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
15482 else if (idMsr == MSR_K6_EFER)
15483 {
15484 /*
15485 * If the guest touches the EFER MSR we need to update the VM-Entry and VM-Exit controls
15486 * as well, even if it is -not- touching bits that cause paging mode changes (LMA/LME).
15487 * We care about the other bits as well, SCE and NXE. See @bugref{7368}.
15488 */
15489 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
15490 }
15491
15492 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not used. */
15493 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
15494 {
15495 switch (idMsr)
15496 {
15497 case MSR_IA32_SYSENTER_CS: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
15498 case MSR_IA32_SYSENTER_EIP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
15499 case MSR_IA32_SYSENTER_ESP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
15500 case MSR_K8_FS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS); break;
15501 case MSR_K8_GS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_GS); break;
15502 case MSR_K6_EFER: /* Nothing to do, already handled above. */ break;
15503 default:
15504 {
15505 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
15506 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_LAZY_MSRS);
15507 else if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
15508 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
15509 break;
15510 }
15511 }
15512 }
15513#ifdef VBOX_STRICT
15514 else
15515 {
15516 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
15517 switch (idMsr)
15518 {
15519 case MSR_IA32_SYSENTER_CS:
15520 case MSR_IA32_SYSENTER_EIP:
15521 case MSR_IA32_SYSENTER_ESP:
15522 case MSR_K8_FS_BASE:
15523 case MSR_K8_GS_BASE:
15524 {
15525 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", idMsr));
15526 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
15527 }
15528
15529 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
15530 default:
15531 {
15532 if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
15533 {
15534 /* EFER MSR writes are always intercepted. */
15535 if (idMsr != MSR_K6_EFER)
15536 {
15537 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
15538 idMsr));
15539 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
15540 }
15541 }
15542
15543 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
15544 {
15545 Assert(pVmcsInfo->pvMsrBitmap);
15546 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
15547 if (fMsrpm & VMXMSRPM_ALLOW_WR)
15548 {
15549 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", idMsr));
15550 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
15551 }
15552 }
15553 break;
15554 }
15555 }
15556 }
15557#endif /* VBOX_STRICT */
15558 }
15559 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15560 {
15561 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15562 rcStrict = VINF_SUCCESS;
15563 }
15564 else
15565 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_WRITE || rcStrict == VINF_EM_TRIPLE_FAULT,
15566 ("Unexpected IEMExecDecodedWrmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
15567
15568 return rcStrict;
15569}
15570
15571
15572/**
15573 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
15574 */
15575HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15576{
15577 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15578
15579 /** @todo The guest has likely hit a contended spinlock. We might want to
15580 * poke a schedule different guest VCPU. */
15581 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15582 if (RT_SUCCESS(rc))
15583 return VINF_EM_RAW_INTERRUPT;
15584
15585 AssertMsgFailed(("hmR0VmxExitPause: Failed to increment RIP. rc=%Rrc\n", rc));
15586 return rc;
15587}
15588
15589
15590/**
15591 * VM-exit handler for when the TPR value is lowered below the specified
15592 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
15593 */
15594HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15595{
15596 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15597 Assert(pVmxTransient->pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
15598
15599 /*
15600 * The TPR shadow would've been synced with the APIC TPR in the post-run phase.
15601 * We'll re-evaluate pending interrupts and inject them before the next VM
15602 * entry so we can just continue execution here.
15603 */
15604 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
15605 return VINF_SUCCESS;
15606}
15607
15608
15609/**
15610 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
15611 * VM-exit.
15612 *
15613 * @retval VINF_SUCCESS when guest execution can continue.
15614 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
15615 * @retval VERR_EM_RESCHEDULE_REM when we need to return to ring-3 due to
15616 * incompatible guest state for VMX execution (real-on-v86 case).
15617 */
15618HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15619{
15620 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15621 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
15622
15623 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15624 hmR0VmxReadExitQualVmcs(pVmxTransient);
15625 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15626
15627 VBOXSTRICTRC rcStrict;
15628 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15629 uint64_t const uExitQual = pVmxTransient->uExitQual;
15630 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(uExitQual);
15631 switch (uAccessType)
15632 {
15633 /*
15634 * MOV to CRx.
15635 */
15636 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
15637 {
15638 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15639 AssertRCReturn(rc, rc);
15640
15641 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
15642 uint32_t const uOldCr0 = pVCpu->cpum.GstCtx.cr0;
15643 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15644 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15645
15646 /*
15647 * MOV to CR3 only cause a VM-exit when one or more of the following are true:
15648 * - When nested paging isn't used.
15649 * - If the guest doesn't have paging enabled (intercept CR3 to update shadow page tables).
15650 * - We are executing in the VM debug loop.
15651 */
15652 Assert( iCrReg != 3
15653 || !pVM->hmr0.s.fNestedPaging
15654 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15655 || pVCpu->hmr0.s.fUsingDebugLoop);
15656
15657 /* MOV to CR8 writes only cause VM-exits when TPR shadow is not used. */
15658 Assert( iCrReg != 8
15659 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15660
15661 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15662 AssertMsg( rcStrict == VINF_SUCCESS
15663 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15664
15665 /*
15666 * This is a kludge for handling switches back to real mode when we try to use
15667 * V86 mode to run real mode code directly. Problem is that V86 mode cannot
15668 * deal with special selector values, so we have to return to ring-3 and run
15669 * there till the selector values are V86 mode compatible.
15670 *
15671 * Note! Using VINF_EM_RESCHEDULE_REM here rather than VINF_EM_RESCHEDULE since the
15672 * latter is an alias for VINF_IEM_RAISED_XCPT which is asserted at the end of
15673 * this function.
15674 */
15675 if ( iCrReg == 0
15676 && rcStrict == VINF_SUCCESS
15677 && !pVM->hmr0.s.vmx.fUnrestrictedGuest
15678 && CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx)
15679 && (uOldCr0 & X86_CR0_PE)
15680 && !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
15681 {
15682 /** @todo Check selectors rather than returning all the time. */
15683 Assert(!pVmxTransient->fIsNestedGuest);
15684 Log4Func(("CR0 write, back to real mode -> VINF_EM_RESCHEDULE_REM\n"));
15685 rcStrict = VINF_EM_RESCHEDULE_REM;
15686 }
15687 break;
15688 }
15689
15690 /*
15691 * MOV from CRx.
15692 */
15693 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
15694 {
15695 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15696 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15697
15698 /*
15699 * MOV from CR3 only cause a VM-exit when one or more of the following are true:
15700 * - When nested paging isn't used.
15701 * - If the guest doesn't have paging enabled (pass guest's CR3 rather than our identity mapped CR3).
15702 * - We are executing in the VM debug loop.
15703 */
15704 Assert( iCrReg != 3
15705 || !pVM->hmr0.s.fNestedPaging
15706 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15707 || pVCpu->hmr0.s.fLeaveDone);
15708
15709 /* MOV from CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
15710 Assert( iCrReg != 8
15711 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15712
15713 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15714 break;
15715 }
15716
15717 /*
15718 * CLTS (Clear Task-Switch Flag in CR0).
15719 */
15720 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
15721 {
15722 rcStrict = hmR0VmxExitClts(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr);
15723 break;
15724 }
15725
15726 /*
15727 * LMSW (Load Machine-Status Word into CR0).
15728 * LMSW cannot clear CR0.PE, so no fRealOnV86Active kludge needed here.
15729 */
15730 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW:
15731 {
15732 RTGCPTR GCPtrEffDst;
15733 uint8_t const cbInstr = pVmxTransient->cbExitInstr;
15734 uint16_t const uMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(uExitQual);
15735 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(uExitQual);
15736 if (fMemOperand)
15737 {
15738 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
15739 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
15740 }
15741 else
15742 GCPtrEffDst = NIL_RTGCPTR;
15743 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmcsInfo, cbInstr, uMsw, GCPtrEffDst);
15744 break;
15745 }
15746
15747 default:
15748 {
15749 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
15750 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
15751 }
15752 }
15753
15754 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS))
15755 == (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS));
15756 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15757
15758 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
15759 NOREF(pVM);
15760 return rcStrict;
15761}
15762
15763
15764/**
15765 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
15766 * VM-exit.
15767 */
15768HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15769{
15770 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15771 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
15772
15773 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15774 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15775 hmR0VmxReadExitQualVmcs(pVmxTransient);
15776 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15777 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK
15778 | CPUMCTX_EXTRN_EFER);
15779 /* EFER MSR also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
15780 AssertRCReturn(rc, rc);
15781
15782 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
15783 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
15784 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
15785 bool const fIOWrite = (VMX_EXIT_QUAL_IO_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_IO_DIRECTION_OUT);
15786 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
15787 bool const fGstStepping = RT_BOOL(pCtx->eflags.Bits.u1TF);
15788 bool const fDbgStepping = pVCpu->hm.s.fSingleInstruction;
15789 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
15790
15791 /*
15792 * Update exit history to see if this exit can be optimized.
15793 */
15794 VBOXSTRICTRC rcStrict;
15795 PCEMEXITREC pExitRec = NULL;
15796 if ( !fGstStepping
15797 && !fDbgStepping)
15798 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15799 !fIOString
15800 ? !fIOWrite
15801 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
15802 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
15803 : !fIOWrite
15804 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
15805 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
15806 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15807 if (!pExitRec)
15808 {
15809 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
15810 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving result in AL/AX/EAX. */
15811
15812 uint32_t const cbValue = s_aIOSizes[uIOSize];
15813 uint32_t const cbInstr = pVmxTransient->cbExitInstr;
15814 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
15815 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15816 if (fIOString)
15817 {
15818 /*
15819 * INS/OUTS - I/O String instruction.
15820 *
15821 * Use instruction-information if available, otherwise fall back on
15822 * interpreting the instruction.
15823 */
15824 Log4Func(("cs:rip=%#04x:%#RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15825 AssertReturn(pCtx->dx == uIOPort, VERR_VMX_IPE_2);
15826 bool const fInsOutsInfo = RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS);
15827 if (fInsOutsInfo)
15828 {
15829 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15830 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
15831 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
15832 IEMMODE const enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
15833 bool const fRep = VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual);
15834 if (fIOWrite)
15835 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
15836 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
15837 else
15838 {
15839 /*
15840 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
15841 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
15842 * See Intel Instruction spec. for "INS".
15843 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
15844 */
15845 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
15846 }
15847 }
15848 else
15849 rcStrict = IEMExecOne(pVCpu);
15850
15851 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15852 fUpdateRipAlready = true;
15853 }
15854 else
15855 {
15856 /*
15857 * IN/OUT - I/O instruction.
15858 */
15859 Log4Func(("cs:rip=%04x:%08RX64 %#06x/%u %c\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15860 uint32_t const uAndVal = s_aIOOpAnd[uIOSize];
15861 Assert(!VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual));
15862 if (fIOWrite)
15863 {
15864 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pCtx->eax & uAndVal, cbValue);
15865 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
15866 if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15867 && !pCtx->eflags.Bits.u1TF)
15868 rcStrict = EMRZSetPendingIoPortWrite(pVCpu, uIOPort, cbInstr, cbValue, pCtx->eax & uAndVal);
15869 }
15870 else
15871 {
15872 uint32_t u32Result = 0;
15873 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
15874 if (IOM_SUCCESS(rcStrict))
15875 {
15876 /* Save result of I/O IN instr. in AL/AX/EAX. */
15877 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Result & uAndVal);
15878 }
15879 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15880 && !pCtx->eflags.Bits.u1TF)
15881 rcStrict = EMRZSetPendingIoPortRead(pVCpu, uIOPort, cbInstr, cbValue);
15882 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
15883 }
15884 }
15885
15886 if (IOM_SUCCESS(rcStrict))
15887 {
15888 if (!fUpdateRipAlready)
15889 {
15890 hmR0VmxAdvanceGuestRipBy(pVCpu, cbInstr);
15891 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15892 }
15893
15894 /*
15895 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru
15896 * while booting Fedora 17 64-bit guest.
15897 *
15898 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
15899 */
15900 if (fIOString)
15901 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RFLAGS);
15902
15903 /*
15904 * If any I/O breakpoints are armed, we need to check if one triggered
15905 * and take appropriate action.
15906 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
15907 */
15908 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_DR7);
15909 AssertRCReturn(rc, rc);
15910
15911 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
15912 * execution engines about whether hyper BPs and such are pending. */
15913 uint32_t const uDr7 = pCtx->dr[7];
15914 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
15915 && X86_DR7_ANY_RW_IO(uDr7)
15916 && (pCtx->cr4 & X86_CR4_DE))
15917 || DBGFBpIsHwIoArmed(pVM)))
15918 {
15919 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
15920
15921 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
15922 VMMRZCallRing3Disable(pVCpu);
15923 HM_DISABLE_PREEMPT(pVCpu);
15924
15925 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
15926
15927 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, uIOPort, cbValue);
15928 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
15929 {
15930 /* Raise #DB. */
15931 if (fIsGuestDbgActive)
15932 ASMSetDR6(pCtx->dr[6]);
15933 if (pCtx->dr[7] != uDr7)
15934 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_DR7;
15935
15936 hmR0VmxSetPendingXcptDB(pVCpu);
15937 }
15938 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
15939 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
15940 else if ( rcStrict2 != VINF_SUCCESS
15941 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
15942 rcStrict = rcStrict2;
15943 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
15944
15945 HM_RESTORE_PREEMPT();
15946 VMMRZCallRing3Enable(pVCpu);
15947 }
15948 }
15949
15950#ifdef VBOX_STRICT
15951 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15952 || rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
15953 Assert(!fIOWrite);
15954 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15955 || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
15956 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
15957 Assert(fIOWrite);
15958 else
15959 {
15960# if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
15961 * statuses, that the VMM device and some others may return. See
15962 * IOM_SUCCESS() for guidance. */
15963 AssertMsg( RT_FAILURE(rcStrict)
15964 || rcStrict == VINF_SUCCESS
15965 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
15966 || rcStrict == VINF_EM_DBG_BREAKPOINT
15967 || rcStrict == VINF_EM_RAW_GUEST_TRAP
15968 || rcStrict == VINF_EM_RAW_TO_R3
15969 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15970# endif
15971 }
15972#endif
15973 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
15974 }
15975 else
15976 {
15977 /*
15978 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
15979 */
15980 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15981 AssertRCReturn(rc2, rc2);
15982 STAM_COUNTER_INC(!fIOString ? fIOWrite ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
15983 : fIOWrite ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
15984 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
15985 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15986 VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual) ? "REP " : "",
15987 fIOWrite ? "OUT" : "IN", fIOString ? "S" : "", uIOPort, uIOSize));
15988
15989 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15990 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15991
15992 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15993 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15994 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15995 }
15996 return rcStrict;
15997}
15998
15999
16000/**
16001 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
16002 * VM-exit.
16003 */
16004HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16005{
16006 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16007
16008 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
16009 hmR0VmxReadExitQualVmcs(pVmxTransient);
16010 if (VMX_EXIT_QUAL_TASK_SWITCH_TYPE(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_TASK_SWITCH_TYPE_IDT)
16011 {
16012 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16013 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
16014 {
16015 uint32_t uErrCode;
16016 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uIdtVectoringInfo))
16017 {
16018 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16019 uErrCode = pVmxTransient->uIdtVectoringErrorCode;
16020 }
16021 else
16022 uErrCode = 0;
16023
16024 RTGCUINTPTR GCPtrFaultAddress;
16025 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(pVmxTransient->uIdtVectoringInfo))
16026 GCPtrFaultAddress = pVCpu->cpum.GstCtx.cr2;
16027 else
16028 GCPtrFaultAddress = 0;
16029
16030 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16031
16032 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
16033 pVmxTransient->cbExitInstr, uErrCode, GCPtrFaultAddress);
16034
16035 Log4Func(("Pending event. uIntType=%#x uVector=%#x\n", VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo),
16036 VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo)));
16037 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
16038 return VINF_EM_RAW_INJECT_TRPM_EVENT;
16039 }
16040 }
16041
16042 /* Fall back to the interpreter to emulate the task-switch. */
16043 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
16044 return VERR_EM_INTERPRETER;
16045}
16046
16047
16048/**
16049 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
16050 */
16051HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16052{
16053 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16054
16055 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
16056 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
16057 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
16058 AssertRC(rc);
16059 return VINF_EM_DBG_STEPPED;
16060}
16061
16062
16063/**
16064 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
16065 */
16066HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16067{
16068 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16069 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
16070
16071 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16072 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16073 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16074 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16075 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16076
16077 /*
16078 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
16079 */
16080 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
16081 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16082 {
16083 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
16084 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
16085 {
16086 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
16087 return VINF_EM_RAW_INJECT_TRPM_EVENT;
16088 }
16089 }
16090 else
16091 {
16092 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
16093 return rcStrict;
16094 }
16095
16096 /* IOMMIOPhysHandler() below may call into IEM, save the necessary state. */
16097 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
16098 hmR0VmxReadExitQualVmcs(pVmxTransient);
16099 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
16100 AssertRCReturn(rc, rc);
16101
16102 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
16103 uint32_t const uAccessType = VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual);
16104 switch (uAccessType)
16105 {
16106 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
16107 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
16108 {
16109 AssertMsg( !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
16110 || VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual) != XAPIC_OFF_TPR,
16111 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
16112
16113 RTGCPHYS GCPhys = pVCpu->hm.s.vmx.u64GstMsrApicBase; /* Always up-to-date, as it is not part of the VMCS. */
16114 GCPhys &= PAGE_BASE_GC_MASK;
16115 GCPhys += VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual);
16116 Log4Func(("Linear access uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
16117 VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual)));
16118
16119 rcStrict = IOMR0MmioPhysHandler(pVCpu->CTX_SUFF(pVM), pVCpu,
16120 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW, GCPhys);
16121 Log4Func(("IOMMMIOPhysHandler returned %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
16122 if ( rcStrict == VINF_SUCCESS
16123 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
16124 || rcStrict == VERR_PAGE_NOT_PRESENT)
16125 {
16126 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
16127 | HM_CHANGED_GUEST_APIC_TPR);
16128 rcStrict = VINF_SUCCESS;
16129 }
16130 break;
16131 }
16132
16133 default:
16134 {
16135 Log4Func(("uAccessType=%#x\n", uAccessType));
16136 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
16137 break;
16138 }
16139 }
16140
16141 if (rcStrict != VINF_SUCCESS)
16142 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
16143 return rcStrict;
16144}
16145
16146
16147/**
16148 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
16149 * VM-exit.
16150 */
16151HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16152{
16153 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16154 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
16155
16156 /*
16157 * We might also get this VM-exit if the nested-guest isn't intercepting MOV DRx accesses.
16158 * In such a case, rather than disabling MOV DRx intercepts and resuming execution, we
16159 * must emulate the MOV DRx access.
16160 */
16161 if (!pVmxTransient->fIsNestedGuest)
16162 {
16163 /* We should -not- get this VM-exit if the guest's debug registers were active. */
16164 if (pVmxTransient->fWasGuestDebugStateActive)
16165 {
16166 AssertMsgFailed(("Unexpected MOV DRx exit\n"));
16167 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
16168 }
16169
16170 if ( !pVCpu->hm.s.fSingleInstruction
16171 && !pVmxTransient->fWasHyperDebugStateActive)
16172 {
16173 Assert(!DBGFIsStepping(pVCpu));
16174 Assert(pVmcsInfo->u32XcptBitmap & RT_BIT(X86_XCPT_DB));
16175
16176 /* Don't intercept MOV DRx any more. */
16177 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
16178 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
16179 AssertRC(rc);
16180
16181 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
16182 VMMRZCallRing3Disable(pVCpu);
16183 HM_DISABLE_PREEMPT(pVCpu);
16184
16185 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
16186 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
16187 Assert(CPUMIsGuestDebugStateActive(pVCpu));
16188
16189 HM_RESTORE_PREEMPT();
16190 VMMRZCallRing3Enable(pVCpu);
16191
16192#ifdef VBOX_WITH_STATISTICS
16193 hmR0VmxReadExitQualVmcs(pVmxTransient);
16194 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
16195 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
16196 else
16197 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
16198#endif
16199 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
16200 return VINF_SUCCESS;
16201 }
16202 }
16203
16204 /*
16205 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER MSR, CS.
16206 * The EFER MSR is always up-to-date.
16207 * Update the segment registers and DR7 from the CPU.
16208 */
16209 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16210 hmR0VmxReadExitQualVmcs(pVmxTransient);
16211 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_DR7);
16212 AssertRCReturn(rc, rc);
16213 Log4Func(("cs:rip=%#04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
16214
16215 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16216 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
16217 {
16218 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
16219 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual),
16220 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual));
16221 if (RT_SUCCESS(rc))
16222 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
16223 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
16224 }
16225 else
16226 {
16227 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
16228 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual),
16229 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual));
16230 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
16231 }
16232
16233 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
16234 if (RT_SUCCESS(rc))
16235 {
16236 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
16237 AssertRCReturn(rc2, rc2);
16238 return VINF_SUCCESS;
16239 }
16240 return rc;
16241}
16242
16243
16244/**
16245 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
16246 * Conditional VM-exit.
16247 */
16248HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16249{
16250 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16251 Assert(pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging);
16252
16253 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16254 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16255 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16256 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16257 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16258
16259 /*
16260 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
16261 */
16262 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
16263 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16264 {
16265 /*
16266 * In the unlikely case where delivering an event causes an EPT misconfig (MMIO), go back to
16267 * instruction emulation to inject the original event. Otherwise, injecting the original event
16268 * using hardware-assisted VMX would trigger the same EPT misconfig VM-exit again.
16269 */
16270 if (!pVCpu->hm.s.Event.fPending)
16271 { /* likely */ }
16272 else
16273 {
16274 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
16275#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16276 /** @todo NSTVMX: Think about how this should be handled. */
16277 if (pVmxTransient->fIsNestedGuest)
16278 return VERR_VMX_IPE_3;
16279#endif
16280 return VINF_EM_RAW_INJECT_TRPM_EVENT;
16281 }
16282 }
16283 else
16284 {
16285 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
16286 return rcStrict;
16287 }
16288
16289 /*
16290 * Get sufficient state and update the exit history entry.
16291 */
16292 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
16293 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
16294 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
16295 AssertRCReturn(rc, rc);
16296
16297 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
16298 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
16299 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
16300 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
16301 if (!pExitRec)
16302 {
16303 /*
16304 * If we succeed, resume guest execution.
16305 * If we fail in interpreting the instruction because we couldn't get the guest physical address
16306 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
16307 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
16308 * weird case. See @bugref{6043}.
16309 */
16310 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16311 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16312/** @todo bird: We can probably just go straight to IOM here and assume that
16313 * it's MMIO, then fall back on PGM if that hunch didn't work out so
16314 * well. However, we need to address that aliasing workarounds that
16315 * PGMR0Trap0eHandlerNPMisconfig implements. So, some care is needed.
16316 *
16317 * Might also be interesting to see if we can get this done more or
16318 * less locklessly inside IOM. Need to consider the lookup table
16319 * updating and use a bit more carefully first (or do all updates via
16320 * rendezvous) */
16321 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pCtx), GCPhys, UINT32_MAX);
16322 Log4Func(("At %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pCtx->rip, VBOXSTRICTRC_VAL(rcStrict)));
16323 if ( rcStrict == VINF_SUCCESS
16324 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
16325 || rcStrict == VERR_PAGE_NOT_PRESENT)
16326 {
16327 /* Successfully handled MMIO operation. */
16328 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
16329 | HM_CHANGED_GUEST_APIC_TPR);
16330 rcStrict = VINF_SUCCESS;
16331 }
16332 }
16333 else
16334 {
16335 /*
16336 * Frequent exit or something needing probing. Call EMHistoryExec.
16337 */
16338 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
16339 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhys));
16340
16341 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
16342 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
16343
16344 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
16345 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
16346 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
16347 }
16348 return rcStrict;
16349}
16350
16351
16352/**
16353 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
16354 * VM-exit.
16355 */
16356HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16357{
16358 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16359 Assert(pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging);
16360
16361 hmR0VmxReadExitQualVmcs(pVmxTransient);
16362 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16363 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16364 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16365 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16366 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16367
16368 /*
16369 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
16370 */
16371 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
16372 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16373 {
16374 /*
16375 * If delivery of an event causes an EPT violation (true nested #PF and not MMIO),
16376 * we shall resolve the nested #PF and re-inject the original event.
16377 */
16378 if (pVCpu->hm.s.Event.fPending)
16379 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflectNPF);
16380 }
16381 else
16382 {
16383 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
16384 return rcStrict;
16385 }
16386
16387 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
16388 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
16389 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
16390 AssertRCReturn(rc, rc);
16391
16392 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
16393 uint64_t const uExitQual = pVmxTransient->uExitQual;
16394 AssertMsg(((pVmxTransient->uExitQual >> 7) & 3) != 2, ("%#RX64", uExitQual));
16395
16396 RTGCUINT uErrorCode = 0;
16397 if (uExitQual & VMX_EXIT_QUAL_EPT_INSTR_FETCH)
16398 uErrorCode |= X86_TRAP_PF_ID;
16399 if (uExitQual & VMX_EXIT_QUAL_EPT_DATA_WRITE)
16400 uErrorCode |= X86_TRAP_PF_RW;
16401 if (uExitQual & VMX_EXIT_QUAL_EPT_ENTRY_PRESENT)
16402 uErrorCode |= X86_TRAP_PF_P;
16403
16404 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16405 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16406 Log4Func(("at %#RX64 (%#RX64 errcode=%#x) cs:rip=%#04x:%#RX64\n", GCPhys, uExitQual, uErrorCode, pCtx->cs.Sel, pCtx->rip));
16407
16408 /*
16409 * Handle the pagefault trap for the nested shadow table.
16410 */
16411 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
16412 rcStrict = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pCtx), GCPhys);
16413 TRPMResetTrap(pVCpu);
16414
16415 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
16416 if ( rcStrict == VINF_SUCCESS
16417 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
16418 || rcStrict == VERR_PAGE_NOT_PRESENT)
16419 {
16420 /* Successfully synced our nested page tables. */
16421 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
16422 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS);
16423 return VINF_SUCCESS;
16424 }
16425
16426 Log4Func(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
16427 return rcStrict;
16428}
16429
16430
16431#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16432/**
16433 * VM-exit handler for VMCLEAR (VMX_EXIT_VMCLEAR). Unconditional VM-exit.
16434 */
16435HMVMX_EXIT_DECL hmR0VmxExitVmclear(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16436{
16437 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16438
16439 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16440 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16441 hmR0VmxReadExitQualVmcs(pVmxTransient);
16442 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16443 | CPUMCTX_EXTRN_HWVIRT
16444 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16445 AssertRCReturn(rc, rc);
16446
16447 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16448
16449 VMXVEXITINFO ExitInfo;
16450 RT_ZERO(ExitInfo);
16451 ExitInfo.uReason = pVmxTransient->uExitReason;
16452 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16453 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16454 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16455 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16456
16457 VBOXSTRICTRC rcStrict = IEMExecDecodedVmclear(pVCpu, &ExitInfo);
16458 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16459 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16460 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16461 {
16462 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16463 rcStrict = VINF_SUCCESS;
16464 }
16465 return rcStrict;
16466}
16467
16468
16469/**
16470 * VM-exit handler for VMLAUNCH (VMX_EXIT_VMLAUNCH). Unconditional VM-exit.
16471 */
16472HMVMX_EXIT_DECL hmR0VmxExitVmlaunch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16473{
16474 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16475
16476 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMLAUNCH,
16477 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
16478 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16479 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16480 AssertRCReturn(rc, rc);
16481
16482 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16483
16484 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
16485 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMLAUNCH);
16486 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
16487 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16488 {
16489 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
16490 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
16491 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
16492 }
16493 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
16494 return rcStrict;
16495}
16496
16497
16498/**
16499 * VM-exit handler for VMPTRLD (VMX_EXIT_VMPTRLD). Unconditional VM-exit.
16500 */
16501HMVMX_EXIT_DECL hmR0VmxExitVmptrld(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16502{
16503 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16504
16505 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16506 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16507 hmR0VmxReadExitQualVmcs(pVmxTransient);
16508 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16509 | CPUMCTX_EXTRN_HWVIRT
16510 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16511 AssertRCReturn(rc, rc);
16512
16513 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16514
16515 VMXVEXITINFO ExitInfo;
16516 RT_ZERO(ExitInfo);
16517 ExitInfo.uReason = pVmxTransient->uExitReason;
16518 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16519 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16520 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16521 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16522
16523 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrld(pVCpu, &ExitInfo);
16524 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16525 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16526 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16527 {
16528 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16529 rcStrict = VINF_SUCCESS;
16530 }
16531 return rcStrict;
16532}
16533
16534
16535/**
16536 * VM-exit handler for VMPTRST (VMX_EXIT_VMPTRST). Unconditional VM-exit.
16537 */
16538HMVMX_EXIT_DECL hmR0VmxExitVmptrst(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16539{
16540 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16541
16542 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16543 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16544 hmR0VmxReadExitQualVmcs(pVmxTransient);
16545 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16546 | CPUMCTX_EXTRN_HWVIRT
16547 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16548 AssertRCReturn(rc, rc);
16549
16550 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16551
16552 VMXVEXITINFO ExitInfo;
16553 RT_ZERO(ExitInfo);
16554 ExitInfo.uReason = pVmxTransient->uExitReason;
16555 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16556 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16557 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16558 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
16559
16560 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrst(pVCpu, &ExitInfo);
16561 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16562 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16563 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16564 {
16565 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16566 rcStrict = VINF_SUCCESS;
16567 }
16568 return rcStrict;
16569}
16570
16571
16572/**
16573 * VM-exit handler for VMREAD (VMX_EXIT_VMREAD). Conditional VM-exit.
16574 */
16575HMVMX_EXIT_DECL hmR0VmxExitVmread(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16576{
16577 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16578
16579 /*
16580 * Strictly speaking we should not get VMREAD VM-exits for shadow VMCS fields and
16581 * thus might not need to import the shadow VMCS state, it's safer just in case
16582 * code elsewhere dares look at unsynced VMCS fields.
16583 */
16584 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16585 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16586 hmR0VmxReadExitQualVmcs(pVmxTransient);
16587 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16588 | CPUMCTX_EXTRN_HWVIRT
16589 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16590 AssertRCReturn(rc, rc);
16591
16592 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16593
16594 VMXVEXITINFO ExitInfo;
16595 RT_ZERO(ExitInfo);
16596 ExitInfo.uReason = pVmxTransient->uExitReason;
16597 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16598 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16599 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16600 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
16601 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
16602
16603 VBOXSTRICTRC rcStrict = IEMExecDecodedVmread(pVCpu, &ExitInfo);
16604 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16605 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16606 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16607 {
16608 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16609 rcStrict = VINF_SUCCESS;
16610 }
16611 return rcStrict;
16612}
16613
16614
16615/**
16616 * VM-exit handler for VMRESUME (VMX_EXIT_VMRESUME). Unconditional VM-exit.
16617 */
16618HMVMX_EXIT_DECL hmR0VmxExitVmresume(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16619{
16620 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16621
16622 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMRESUME,
16623 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
16624 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16625 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16626 AssertRCReturn(rc, rc);
16627
16628 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16629
16630 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
16631 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMRESUME);
16632 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
16633 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16634 {
16635 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
16636 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
16637 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
16638 }
16639 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
16640 return rcStrict;
16641}
16642
16643
16644/**
16645 * VM-exit handler for VMWRITE (VMX_EXIT_VMWRITE). Conditional VM-exit.
16646 */
16647HMVMX_EXIT_DECL hmR0VmxExitVmwrite(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16648{
16649 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16650
16651 /*
16652 * Although we should not get VMWRITE VM-exits for shadow VMCS fields, since our HM hook
16653 * gets invoked when IEM's VMWRITE instruction emulation modifies the current VMCS and it
16654 * flags re-loading the entire shadow VMCS, we should save the entire shadow VMCS here.
16655 */
16656 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16657 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16658 hmR0VmxReadExitQualVmcs(pVmxTransient);
16659 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16660 | CPUMCTX_EXTRN_HWVIRT
16661 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16662 AssertRCReturn(rc, rc);
16663
16664 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16665
16666 VMXVEXITINFO ExitInfo;
16667 RT_ZERO(ExitInfo);
16668 ExitInfo.uReason = pVmxTransient->uExitReason;
16669 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16670 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16671 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16672 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
16673 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16674
16675 VBOXSTRICTRC rcStrict = IEMExecDecodedVmwrite(pVCpu, &ExitInfo);
16676 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16677 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16678 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16679 {
16680 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16681 rcStrict = VINF_SUCCESS;
16682 }
16683 return rcStrict;
16684}
16685
16686
16687/**
16688 * VM-exit handler for VMXOFF (VMX_EXIT_VMXOFF). Unconditional VM-exit.
16689 */
16690HMVMX_EXIT_DECL hmR0VmxExitVmxoff(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16691{
16692 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16693
16694 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16695 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR4
16696 | CPUMCTX_EXTRN_HWVIRT
16697 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
16698 AssertRCReturn(rc, rc);
16699
16700 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16701
16702 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxoff(pVCpu, pVmxTransient->cbExitInstr);
16703 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16704 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_HWVIRT);
16705 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16706 {
16707 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16708 rcStrict = VINF_SUCCESS;
16709 }
16710 return rcStrict;
16711}
16712
16713
16714/**
16715 * VM-exit handler for VMXON (VMX_EXIT_VMXON). Unconditional VM-exit.
16716 */
16717HMVMX_EXIT_DECL hmR0VmxExitVmxon(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16718{
16719 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16720
16721 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16722 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16723 hmR0VmxReadExitQualVmcs(pVmxTransient);
16724 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16725 | CPUMCTX_EXTRN_HWVIRT
16726 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16727 AssertRCReturn(rc, rc);
16728
16729 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16730
16731 VMXVEXITINFO ExitInfo;
16732 RT_ZERO(ExitInfo);
16733 ExitInfo.uReason = pVmxTransient->uExitReason;
16734 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16735 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16736 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16737 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16738
16739 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxon(pVCpu, &ExitInfo);
16740 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16741 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16742 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16743 {
16744 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16745 rcStrict = VINF_SUCCESS;
16746 }
16747 return rcStrict;
16748}
16749
16750
16751/**
16752 * VM-exit handler for INVVPID (VMX_EXIT_INVVPID). Unconditional VM-exit.
16753 */
16754HMVMX_EXIT_DECL hmR0VmxExitInvvpid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16755{
16756 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16757
16758 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16759 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16760 hmR0VmxReadExitQualVmcs(pVmxTransient);
16761 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16762 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16763 AssertRCReturn(rc, rc);
16764
16765 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16766
16767 VMXVEXITINFO ExitInfo;
16768 RT_ZERO(ExitInfo);
16769 ExitInfo.uReason = pVmxTransient->uExitReason;
16770 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16771 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16772 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16773 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16774
16775 VBOXSTRICTRC rcStrict = IEMExecDecodedInvvpid(pVCpu, &ExitInfo);
16776 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16777 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16778 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16779 {
16780 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16781 rcStrict = VINF_SUCCESS;
16782 }
16783 return rcStrict;
16784}
16785#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16786/** @} */
16787
16788
16789#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16790/** @name Nested-guest VM-exit handlers.
16791 * @{
16792 */
16793/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16794/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Nested-guest VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16795/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16796
16797/**
16798 * Nested-guest VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
16799 * Conditional VM-exit.
16800 */
16801HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16802{
16803 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16804
16805 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16806
16807 uint64_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
16808 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
16809 Assert(VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo));
16810
16811 switch (uExitIntType)
16812 {
16813 /*
16814 * Physical NMIs:
16815 * We shouldn't direct host physical NMIs to the nested-guest. Dispatch it to the host.
16816 */
16817 case VMX_EXIT_INT_INFO_TYPE_NMI:
16818 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
16819
16820 /*
16821 * Hardware exceptions,
16822 * Software exceptions,
16823 * Privileged software exceptions:
16824 * Figure out if the exception must be delivered to the guest or the nested-guest.
16825 */
16826 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
16827 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
16828 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
16829 {
16830 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16831 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16832 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16833 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16834
16835 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16836 bool const fIntercept = CPUMIsGuestVmxXcptInterceptSet(pCtx, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo),
16837 pVmxTransient->uExitIntErrorCode);
16838 if (fIntercept)
16839 {
16840 /* Exit qualification is required for debug and page-fault exceptions. */
16841 hmR0VmxReadExitQualVmcs(pVmxTransient);
16842
16843 /*
16844 * For VM-exits due to software exceptions (those generated by INT3 or INTO) and privileged
16845 * software exceptions (those generated by INT1/ICEBP) we need to supply the VM-exit instruction
16846 * length. However, if delivery of a software interrupt, software exception or privileged
16847 * software exception causes a VM-exit, that too provides the VM-exit instruction length.
16848 */
16849 VMXVEXITINFO ExitInfo;
16850 RT_ZERO(ExitInfo);
16851 ExitInfo.uReason = pVmxTransient->uExitReason;
16852 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16853 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16854
16855 VMXVEXITEVENTINFO ExitEventInfo;
16856 RT_ZERO(ExitEventInfo);
16857 ExitEventInfo.uExitIntInfo = pVmxTransient->uExitIntInfo;
16858 ExitEventInfo.uExitIntErrCode = pVmxTransient->uExitIntErrorCode;
16859 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16860 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16861
16862#ifdef DEBUG_ramshankar
16863 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16864 Log4Func(("exit_int_info=%#RX32 err_code=%#RX32 exit_qual=%#RX64\n", pVmxTransient->uExitIntInfo,
16865 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual));
16866 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
16867 {
16868 Log4Func(("idt_info=%#RX32 idt_errcode=%#RX32 cr2=%#RX64\n", pVmxTransient->uIdtVectoringInfo,
16869 pVmxTransient->uIdtVectoringErrorCode, pCtx->cr2));
16870 }
16871#endif
16872 return IEMExecVmxVmexitXcpt(pVCpu, &ExitInfo, &ExitEventInfo);
16873 }
16874
16875 /* Nested paging is currently a requirement, otherwise we would need to handle shadow #PFs in hmR0VmxExitXcptPF. */
16876 Assert(pVCpu->CTX_SUFF(pVM)->hmr0.s.fNestedPaging);
16877 return hmR0VmxExitXcpt(pVCpu, pVmxTransient);
16878 }
16879
16880 /*
16881 * Software interrupts:
16882 * VM-exits cannot be caused by software interrupts.
16883 *
16884 * External interrupts:
16885 * This should only happen when "acknowledge external interrupts on VM-exit"
16886 * control is set. However, we never set this when executing a guest or
16887 * nested-guest. For nested-guests it is emulated while injecting interrupts into
16888 * the guest.
16889 */
16890 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
16891 case VMX_EXIT_INT_INFO_TYPE_EXT_INT:
16892 default:
16893 {
16894 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
16895 return VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
16896 }
16897 }
16898}
16899
16900
16901/**
16902 * Nested-guest VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT).
16903 * Unconditional VM-exit.
16904 */
16905HMVMX_EXIT_DECL hmR0VmxExitTripleFaultNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16906{
16907 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16908 return IEMExecVmxVmexitTripleFault(pVCpu);
16909}
16910
16911
16912/**
16913 * Nested-guest VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
16914 */
16915HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16916{
16917 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16918
16919 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INT_WINDOW_EXIT))
16920 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16921 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16922}
16923
16924
16925/**
16926 * Nested-guest VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
16927 */
16928HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16929{
16930 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16931
16932 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_NMI_WINDOW_EXIT))
16933 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16934 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16935}
16936
16937
16938/**
16939 * Nested-guest VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH).
16940 * Unconditional VM-exit.
16941 */
16942HMVMX_EXIT_DECL hmR0VmxExitTaskSwitchNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16943{
16944 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16945
16946 hmR0VmxReadExitQualVmcs(pVmxTransient);
16947 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16948 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16949 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16950
16951 VMXVEXITINFO ExitInfo;
16952 RT_ZERO(ExitInfo);
16953 ExitInfo.uReason = pVmxTransient->uExitReason;
16954 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16955 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16956
16957 VMXVEXITEVENTINFO ExitEventInfo;
16958 RT_ZERO(ExitEventInfo);
16959 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16960 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16961 return IEMExecVmxVmexitTaskSwitch(pVCpu, &ExitInfo, &ExitEventInfo);
16962}
16963
16964
16965/**
16966 * Nested-guest VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
16967 */
16968HMVMX_EXIT_DECL hmR0VmxExitHltNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16969{
16970 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16971
16972 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_HLT_EXIT))
16973 {
16974 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16975 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16976 }
16977 return hmR0VmxExitHlt(pVCpu, pVmxTransient);
16978}
16979
16980
16981/**
16982 * Nested-guest VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
16983 */
16984HMVMX_EXIT_DECL hmR0VmxExitInvlpgNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16985{
16986 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16987
16988 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16989 {
16990 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16991 hmR0VmxReadExitQualVmcs(pVmxTransient);
16992
16993 VMXVEXITINFO ExitInfo;
16994 RT_ZERO(ExitInfo);
16995 ExitInfo.uReason = pVmxTransient->uExitReason;
16996 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16997 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16998 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16999 }
17000 return hmR0VmxExitInvlpg(pVCpu, pVmxTransient);
17001}
17002
17003
17004/**
17005 * Nested-guest VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
17006 */
17007HMVMX_EXIT_DECL hmR0VmxExitRdpmcNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17008{
17009 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17010
17011 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDPMC_EXIT))
17012 {
17013 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17014 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17015 }
17016 return hmR0VmxExitRdpmc(pVCpu, pVmxTransient);
17017}
17018
17019
17020/**
17021 * Nested-guest VM-exit handler for VMREAD (VMX_EXIT_VMREAD) and VMWRITE
17022 * (VMX_EXIT_VMWRITE). Conditional VM-exit.
17023 */
17024HMVMX_EXIT_DECL hmR0VmxExitVmreadVmwriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17025{
17026 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17027
17028 Assert( pVmxTransient->uExitReason == VMX_EXIT_VMREAD
17029 || pVmxTransient->uExitReason == VMX_EXIT_VMWRITE);
17030
17031 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
17032
17033 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
17034 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
17035 uint64_t u64VmcsField = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
17036
17037 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
17038 if (!CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
17039 u64VmcsField &= UINT64_C(0xffffffff);
17040
17041 if (CPUMIsGuestVmxVmreadVmwriteInterceptSet(pVCpu, pVmxTransient->uExitReason, u64VmcsField))
17042 {
17043 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17044 hmR0VmxReadExitQualVmcs(pVmxTransient);
17045
17046 VMXVEXITINFO ExitInfo;
17047 RT_ZERO(ExitInfo);
17048 ExitInfo.uReason = pVmxTransient->uExitReason;
17049 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17050 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17051 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
17052 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17053 }
17054
17055 if (pVmxTransient->uExitReason == VMX_EXIT_VMREAD)
17056 return hmR0VmxExitVmread(pVCpu, pVmxTransient);
17057 return hmR0VmxExitVmwrite(pVCpu, pVmxTransient);
17058}
17059
17060
17061/**
17062 * Nested-guest VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
17063 */
17064HMVMX_EXIT_DECL hmR0VmxExitRdtscNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17065{
17066 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17067
17068 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
17069 {
17070 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17071 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17072 }
17073
17074 return hmR0VmxExitRdtsc(pVCpu, pVmxTransient);
17075}
17076
17077
17078/**
17079 * Nested-guest VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX).
17080 * Conditional VM-exit.
17081 */
17082HMVMX_EXIT_DECL hmR0VmxExitMovCRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17083{
17084 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17085
17086 hmR0VmxReadExitQualVmcs(pVmxTransient);
17087 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17088
17089 VBOXSTRICTRC rcStrict;
17090 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual);
17091 switch (uAccessType)
17092 {
17093 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
17094 {
17095 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
17096 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
17097 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
17098 uint64_t const uNewCrX = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
17099
17100 bool fIntercept;
17101 switch (iCrReg)
17102 {
17103 case 0:
17104 case 4:
17105 fIntercept = CPUMIsGuestVmxMovToCr0Cr4InterceptSet(&pVCpu->cpum.GstCtx, iCrReg, uNewCrX);
17106 break;
17107
17108 case 3:
17109 fIntercept = CPUMIsGuestVmxMovToCr3InterceptSet(pVCpu, uNewCrX);
17110 break;
17111
17112 case 8:
17113 fIntercept = CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_CR8_LOAD_EXIT);
17114 break;
17115
17116 default:
17117 fIntercept = false;
17118 break;
17119 }
17120 if (fIntercept)
17121 {
17122 VMXVEXITINFO ExitInfo;
17123 RT_ZERO(ExitInfo);
17124 ExitInfo.uReason = pVmxTransient->uExitReason;
17125 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17126 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17127 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17128 }
17129 else
17130 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
17131 break;
17132 }
17133
17134 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
17135 {
17136 /*
17137 * CR0/CR4 reads do not cause VM-exits, the read-shadow is used (subject to masking).
17138 * CR2 reads do not cause a VM-exit.
17139 * CR3 reads cause a VM-exit depending on the "CR3 store exiting" control.
17140 * CR8 reads cause a VM-exit depending on the "CR8 store exiting" control.
17141 */
17142 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
17143 if ( iCrReg == 3
17144 || iCrReg == 8)
17145 {
17146 static const uint32_t s_auCrXReadIntercepts[] = { 0, 0, 0, VMX_PROC_CTLS_CR3_STORE_EXIT, 0,
17147 0, 0, 0, VMX_PROC_CTLS_CR8_STORE_EXIT };
17148 uint32_t const uIntercept = s_auCrXReadIntercepts[iCrReg];
17149 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, uIntercept))
17150 {
17151 VMXVEXITINFO ExitInfo;
17152 RT_ZERO(ExitInfo);
17153 ExitInfo.uReason = pVmxTransient->uExitReason;
17154 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17155 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17156 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17157 }
17158 else
17159 {
17160 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
17161 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
17162 }
17163 }
17164 else
17165 {
17166 AssertMsgFailed(("MOV from CR%d VM-exit must not happen\n", iCrReg));
17167 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, iCrReg);
17168 }
17169 break;
17170 }
17171
17172 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
17173 {
17174 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
17175 Assert(pVmcsNstGst);
17176 uint64_t const uGstHostMask = pVmcsNstGst->u64Cr0Mask.u;
17177 uint64_t const uReadShadow = pVmcsNstGst->u64Cr0ReadShadow.u;
17178 if ( (uGstHostMask & X86_CR0_TS)
17179 && (uReadShadow & X86_CR0_TS))
17180 {
17181 VMXVEXITINFO ExitInfo;
17182 RT_ZERO(ExitInfo);
17183 ExitInfo.uReason = pVmxTransient->uExitReason;
17184 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17185 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17186 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17187 }
17188 else
17189 rcStrict = hmR0VmxExitClts(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr);
17190 break;
17191 }
17192
17193 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
17194 {
17195 RTGCPTR GCPtrEffDst;
17196 uint16_t const uNewMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(pVmxTransient->uExitQual);
17197 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(pVmxTransient->uExitQual);
17198 if (fMemOperand)
17199 {
17200 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
17201 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
17202 }
17203 else
17204 GCPtrEffDst = NIL_RTGCPTR;
17205
17206 if (CPUMIsGuestVmxLmswInterceptSet(&pVCpu->cpum.GstCtx, uNewMsw))
17207 {
17208 VMXVEXITINFO ExitInfo;
17209 RT_ZERO(ExitInfo);
17210 ExitInfo.uReason = pVmxTransient->uExitReason;
17211 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17212 ExitInfo.u64GuestLinearAddr = GCPtrEffDst;
17213 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17214 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17215 }
17216 else
17217 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, uNewMsw, GCPtrEffDst);
17218 break;
17219 }
17220
17221 default:
17222 {
17223 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
17224 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
17225 }
17226 }
17227
17228 if (rcStrict == VINF_IEM_RAISED_XCPT)
17229 {
17230 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
17231 rcStrict = VINF_SUCCESS;
17232 }
17233 return rcStrict;
17234}
17235
17236
17237/**
17238 * Nested-guest VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX).
17239 * Conditional VM-exit.
17240 */
17241HMVMX_EXIT_DECL hmR0VmxExitMovDRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17242{
17243 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17244
17245 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MOV_DR_EXIT))
17246 {
17247 hmR0VmxReadExitQualVmcs(pVmxTransient);
17248 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17249
17250 VMXVEXITINFO ExitInfo;
17251 RT_ZERO(ExitInfo);
17252 ExitInfo.uReason = pVmxTransient->uExitReason;
17253 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17254 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17255 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17256 }
17257 return hmR0VmxExitMovDRx(pVCpu, pVmxTransient);
17258}
17259
17260
17261/**
17262 * Nested-guest VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR).
17263 * Conditional VM-exit.
17264 */
17265HMVMX_EXIT_DECL hmR0VmxExitIoInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17266{
17267 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17268
17269 hmR0VmxReadExitQualVmcs(pVmxTransient);
17270
17271 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
17272 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
17273 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
17274
17275 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
17276 uint8_t const cbAccess = s_aIOSizes[uIOSize];
17277 if (CPUMIsGuestVmxIoInterceptSet(pVCpu, uIOPort, cbAccess))
17278 {
17279 /*
17280 * IN/OUT instruction:
17281 * - Provides VM-exit instruction length.
17282 *
17283 * INS/OUTS instruction:
17284 * - Provides VM-exit instruction length.
17285 * - Provides Guest-linear address.
17286 * - Optionally provides VM-exit instruction info (depends on CPU feature).
17287 */
17288 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
17289 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17290
17291 /* Make sure we don't use stale/uninitialized VMX-transient info. below. */
17292 pVmxTransient->ExitInstrInfo.u = 0;
17293 pVmxTransient->uGuestLinearAddr = 0;
17294
17295 bool const fVmxInsOutsInfo = pVM->cpum.ro.GuestFeatures.fVmxInsOutInfo;
17296 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
17297 if (fIOString)
17298 {
17299 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
17300 if (fVmxInsOutsInfo)
17301 {
17302 Assert(RT_BF_GET(g_HmMsrs.u.vmx.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS)); /* Paranoia. */
17303 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
17304 }
17305 }
17306
17307 VMXVEXITINFO ExitInfo;
17308 RT_ZERO(ExitInfo);
17309 ExitInfo.uReason = pVmxTransient->uExitReason;
17310 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17311 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17312 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
17313 ExitInfo.u64GuestLinearAddr = pVmxTransient->uGuestLinearAddr;
17314 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17315 }
17316 return hmR0VmxExitIoInstr(pVCpu, pVmxTransient);
17317}
17318
17319
17320/**
17321 * Nested-guest VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
17322 */
17323HMVMX_EXIT_DECL hmR0VmxExitRdmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17324{
17325 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17326
17327 uint32_t fMsrpm;
17328 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
17329 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
17330 else
17331 fMsrpm = VMXMSRPM_EXIT_RD;
17332
17333 if (fMsrpm & VMXMSRPM_EXIT_RD)
17334 {
17335 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17336 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17337 }
17338 return hmR0VmxExitRdmsr(pVCpu, pVmxTransient);
17339}
17340
17341
17342/**
17343 * Nested-guest VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
17344 */
17345HMVMX_EXIT_DECL hmR0VmxExitWrmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17346{
17347 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17348
17349 uint32_t fMsrpm;
17350 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
17351 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
17352 else
17353 fMsrpm = VMXMSRPM_EXIT_WR;
17354
17355 if (fMsrpm & VMXMSRPM_EXIT_WR)
17356 {
17357 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17358 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17359 }
17360 return hmR0VmxExitWrmsr(pVCpu, pVmxTransient);
17361}
17362
17363
17364/**
17365 * Nested-guest VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
17366 */
17367HMVMX_EXIT_DECL hmR0VmxExitMwaitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17368{
17369 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17370
17371 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MWAIT_EXIT))
17372 {
17373 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17374 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17375 }
17376 return hmR0VmxExitMwait(pVCpu, pVmxTransient);
17377}
17378
17379
17380/**
17381 * Nested-guest VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional
17382 * VM-exit.
17383 */
17384HMVMX_EXIT_DECL hmR0VmxExitMtfNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17385{
17386 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17387
17388 /** @todo NSTVMX: Should consider debugging nested-guests using VM debugger. */
17389 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
17390 VMXVEXITINFO ExitInfo;
17391 RT_ZERO(ExitInfo);
17392 ExitInfo.uReason = pVmxTransient->uExitReason;
17393 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
17394 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
17395}
17396
17397
17398/**
17399 * Nested-guest VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
17400 */
17401HMVMX_EXIT_DECL hmR0VmxExitMonitorNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17402{
17403 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17404
17405 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MONITOR_EXIT))
17406 {
17407 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17408 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17409 }
17410 return hmR0VmxExitMonitor(pVCpu, pVmxTransient);
17411}
17412
17413
17414/**
17415 * Nested-guest VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
17416 */
17417HMVMX_EXIT_DECL hmR0VmxExitPauseNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17418{
17419 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17420
17421 /** @todo NSTVMX: Think about this more. Does the outer guest need to intercept
17422 * PAUSE when executing a nested-guest? If it does not, we would not need
17423 * to check for the intercepts here. Just call VM-exit... */
17424
17425 /* The CPU would have already performed the necessary CPL checks for PAUSE-loop exiting. */
17426 if ( CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_PAUSE_EXIT)
17427 || CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
17428 {
17429 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17430 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17431 }
17432 return hmR0VmxExitPause(pVCpu, pVmxTransient);
17433}
17434
17435
17436/**
17437 * Nested-guest VM-exit handler for when the TPR value is lowered below the
17438 * specified threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
17439 */
17440HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThresholdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17441{
17442 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17443
17444 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_TPR_SHADOW))
17445 {
17446 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
17447 VMXVEXITINFO ExitInfo;
17448 RT_ZERO(ExitInfo);
17449 ExitInfo.uReason = pVmxTransient->uExitReason;
17450 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
17451 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
17452 }
17453 return hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient);
17454}
17455
17456
17457/**
17458 * Nested-guest VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional
17459 * VM-exit.
17460 */
17461HMVMX_EXIT_DECL hmR0VmxExitApicAccessNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17462{
17463 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17464
17465 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17466 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
17467 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
17468 hmR0VmxReadExitQualVmcs(pVmxTransient);
17469
17470 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_APIC_ACCESS));
17471
17472 Log4Func(("at offset %#x type=%u\n", VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual),
17473 VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual)));
17474
17475 VMXVEXITINFO ExitInfo;
17476 RT_ZERO(ExitInfo);
17477 ExitInfo.uReason = pVmxTransient->uExitReason;
17478 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17479 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17480
17481 VMXVEXITEVENTINFO ExitEventInfo;
17482 RT_ZERO(ExitEventInfo);
17483 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
17484 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
17485 return IEMExecVmxVmexitApicAccess(pVCpu, &ExitInfo, &ExitEventInfo);
17486}
17487
17488
17489/**
17490 * Nested-guest VM-exit handler for APIC write emulation (VMX_EXIT_APIC_WRITE).
17491 * Conditional VM-exit.
17492 */
17493HMVMX_EXIT_DECL hmR0VmxExitApicWriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17494{
17495 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17496
17497 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_APIC_REG_VIRT));
17498 hmR0VmxReadExitQualVmcs(pVmxTransient);
17499 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
17500}
17501
17502
17503/**
17504 * Nested-guest VM-exit handler for virtualized EOI (VMX_EXIT_VIRTUALIZED_EOI).
17505 * Conditional VM-exit.
17506 */
17507HMVMX_EXIT_DECL hmR0VmxExitVirtEoiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17508{
17509 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17510
17511 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_INT_DELIVERY));
17512 hmR0VmxReadExitQualVmcs(pVmxTransient);
17513 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
17514}
17515
17516
17517/**
17518 * Nested-guest VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
17519 */
17520HMVMX_EXIT_DECL hmR0VmxExitRdtscpNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17521{
17522 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17523
17524 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
17525 {
17526 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_RDTSCP));
17527 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17528 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17529 }
17530 return hmR0VmxExitRdtscp(pVCpu, pVmxTransient);
17531}
17532
17533
17534/**
17535 * Nested-guest VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
17536 */
17537HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17538{
17539 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17540
17541 if (CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_WBINVD_EXIT))
17542 {
17543 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17544 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17545 }
17546 return hmR0VmxExitWbinvd(pVCpu, pVmxTransient);
17547}
17548
17549
17550/**
17551 * Nested-guest VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
17552 */
17553HMVMX_EXIT_DECL hmR0VmxExitInvpcidNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17554{
17555 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17556
17557 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
17558 {
17559 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_INVPCID));
17560 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17561 hmR0VmxReadExitQualVmcs(pVmxTransient);
17562 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
17563
17564 VMXVEXITINFO ExitInfo;
17565 RT_ZERO(ExitInfo);
17566 ExitInfo.uReason = pVmxTransient->uExitReason;
17567 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17568 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17569 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
17570 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17571 }
17572 return hmR0VmxExitInvpcid(pVCpu, pVmxTransient);
17573}
17574
17575
17576/**
17577 * Nested-guest VM-exit handler for invalid-guest state
17578 * (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error VM-exit.
17579 */
17580HMVMX_EXIT_DECL hmR0VmxExitErrInvalidGuestStateNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17581{
17582 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17583
17584 /*
17585 * Currently this should never happen because we fully emulate VMLAUNCH/VMRESUME in IEM.
17586 * So if it does happen, it indicates a bug possibly in the hardware-assisted VMX code.
17587 * Handle it like it's in an invalid guest state of the outer guest.
17588 *
17589 * When the fast path is implemented, this should be changed to cause the corresponding
17590 * nested-guest VM-exit.
17591 */
17592 return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
17593}
17594
17595
17596/**
17597 * Nested-guest VM-exit handler for instructions that cause VM-exits uncondtionally
17598 * and only provide the instruction length.
17599 *
17600 * Unconditional VM-exit.
17601 */
17602HMVMX_EXIT_DECL hmR0VmxExitInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17603{
17604 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17605
17606#ifdef VBOX_STRICT
17607 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
17608 switch (pVmxTransient->uExitReason)
17609 {
17610 case VMX_EXIT_ENCLS:
17611 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_ENCLS_EXIT));
17612 break;
17613
17614 case VMX_EXIT_VMFUNC:
17615 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_VMFUNC));
17616 break;
17617 }
17618#endif
17619
17620 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17621 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17622}
17623
17624
17625/**
17626 * Nested-guest VM-exit handler for instructions that provide instruction length as
17627 * well as more information.
17628 *
17629 * Unconditional VM-exit.
17630 */
17631HMVMX_EXIT_DECL hmR0VmxExitInstrWithInfoNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17632{
17633 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17634
17635#ifdef VBOX_STRICT
17636 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
17637 switch (pVmxTransient->uExitReason)
17638 {
17639 case VMX_EXIT_GDTR_IDTR_ACCESS:
17640 case VMX_EXIT_LDTR_TR_ACCESS:
17641 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_DESC_TABLE_EXIT));
17642 break;
17643
17644 case VMX_EXIT_RDRAND:
17645 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_RDRAND_EXIT));
17646 break;
17647
17648 case VMX_EXIT_RDSEED:
17649 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_RDSEED_EXIT));
17650 break;
17651
17652 case VMX_EXIT_XSAVES:
17653 case VMX_EXIT_XRSTORS:
17654 /** @todo NSTVMX: Verify XSS-bitmap. */
17655 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_XSAVES_XRSTORS));
17656 break;
17657
17658 case VMX_EXIT_UMWAIT:
17659 case VMX_EXIT_TPAUSE:
17660 Assert(CPUMIsGuestVmxProcCtlsSet(pCtx, VMX_PROC_CTLS_RDTSC_EXIT));
17661 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_USER_WAIT_PAUSE));
17662 break;
17663 }
17664#endif
17665
17666 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17667 hmR0VmxReadExitQualVmcs(pVmxTransient);
17668 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
17669
17670 VMXVEXITINFO ExitInfo;
17671 RT_ZERO(ExitInfo);
17672 ExitInfo.uReason = pVmxTransient->uExitReason;
17673 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17674 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17675 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
17676 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17677}
17678
17679/** @} */
17680#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
17681
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